text
stringlengths
14
6.51M
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpBerSet; {$I ..\Include\CryptoLib.inc} interface uses Classes, SysUtils, ClpAsn1Tags, ClpDerSet, ClpIBerSet, ClpAsn1OutputStream, ClpBerOutputStream, ClpDerOutputStream, ClpIProxiedInterface, ClpIAsn1EncodableVector, ClpCryptoLibTypes; type /// <summary> /// A Ber encoded set object /// </summary> TBerSet = class sealed(TDerSet, IBerSet) strict private class var FEmpty: IBerSet; class constructor BerSet(); class function GetEmpty: IBerSet; static; inline; public class function FromVector(const v: IAsn1EncodableVector): IBerSet; overload; static; class function FromVector(const v: IAsn1EncodableVector; needsSorting: Boolean): IBerSet; overload; static; /// <summary> /// create an empty set /// </summary> constructor Create(); overload; /// <param name="obj"> /// a single object that makes up the set. /// </param> constructor Create(const obj: IAsn1Encodable); overload; /// <param name="v"> /// a vector of objects making up the set. /// </param> constructor Create(const v: IAsn1EncodableVector); overload; constructor Create(const v: IAsn1EncodableVector; needsSorting: Boolean); overload; destructor Destroy(); override; /// <summary> /// A note on the implementation: <br />As Ber requires the constructed, /// definite-length model to <br />be used for structured types, this /// varies slightly from the <br />ASN.1 descriptions given. Rather than /// just outputing Set, <br />we also have to specify Constructed, and /// the objects length. <br /> /// </summary> procedure Encode(const derOut: TStream); override; class property Empty: IBerSet read GetEmpty; end; implementation { TBerSet } class function TBerSet.GetEmpty: IBerSet; begin result := FEmpty; end; constructor TBerSet.Create; begin Inherited Create(); end; constructor TBerSet.Create(const v: IAsn1EncodableVector; needsSorting: Boolean); begin Inherited Create(v, needsSorting); end; destructor TBerSet.Destroy; begin inherited Destroy; end; constructor TBerSet.Create(const obj: IAsn1Encodable); begin Inherited Create(obj); end; constructor TBerSet.Create(const v: IAsn1EncodableVector); begin Inherited Create(v, false); end; class constructor TBerSet.BerSet; begin FEmpty := TBerSet.Create(); end; procedure TBerSet.Encode(const derOut: TStream); var o: IAsn1Encodable; LListAsn1Encodable: TCryptoLibGenericArray<IAsn1Encodable>; begin if ((derOut is TAsn1OutputStream) or (derOut is TBerOutputStream)) then begin (derOut as TDerOutputStream).WriteByte(TAsn1Tags.&Set or TAsn1Tags.Constructed); (derOut as TDerOutputStream).WriteByte($80); LListAsn1Encodable := Self.GetEnumerable; for o in LListAsn1Encodable do begin (derOut as TDerOutputStream).WriteObject(o); end; (derOut as TDerOutputStream).WriteByte($00); (derOut as TDerOutputStream).WriteByte($00); end else begin (Inherited Encode(derOut)); end; end; class function TBerSet.FromVector(const v: IAsn1EncodableVector; needsSorting: Boolean): IBerSet; begin if v.Count < 1 then begin result := Empty; end else begin result := TBerSet.Create(v, needsSorting); end; end; class function TBerSet.FromVector(const v: IAsn1EncodableVector): IBerSet; begin if v.Count < 1 then begin result := Empty; end else begin result := TBerSet.Create(v); end; end; end.
Unit H2MediaList; Interface Uses Windows, Classes,controls, SysUtils,GR32_Image,GR32, gr32_layers,Graphics,generalprocedures; Type PMediaFile=^TMediaFile; TMediaFile=Record Filename:String; name:string; ext:String[4]; Size:Integer; Date:tdatetime; Directory:String; Duration:Int64; Time:string[8]; Title, Artist, Album, Genre:string; hash:string; Year:string[4]; Music:boolean; Video:Boolean; Folder:Boolean; Playlist:Boolean; Rate:Byte; Selected:Boolean; End; PIRecord=^TIrecord; TIRecord=Record dir:String; filename:String; size:Integer; folder:Boolean; End; TH2MediaList = Class(TControl) Private fsrx, fsry, fsrf, frrx, frry, frrf, fx, fy, fwidth, fheight, fcount, findent, ffirst, findex, fitemheight:Integer; fvisible:Boolean; ftype:byte; ftitle, ffile, fdir: String; ffont: tfont; ftitleheight:Integer; fbitmap:tbitmaplayer; fselect:tbitmap32; ffolder:tbitmap32; fdrawmode:tdrawmode; falpha:Cardinal; fitems:tlist; Procedure SetFont(value:tfont); Procedure SetItems(value:tlist); Procedure Setvisible(value:Boolean); Procedure SetItemindex(value:Integer); Procedure Setx(value:Integer); Procedure Sety(value:Integer); Procedure SetWidth(value:Integer); Procedure SetHeight(value:Integer); Procedure SetDir(value:String); Procedure Findfiles(FilesList: TList; StartDir, FileMask: String); Procedure FindDir(DirList:tlist;startdir,filemask:String); Procedure MakeRootItems; Procedure MakeMusicFolders; Public Constructor Create(AOwner: TComponent); Override; Destructor Destroy; Override; Procedure MouseDown(Sender: TObject; Buttons: TMouseButton; Shift: TShiftState; X, Y: Integer); Published Procedure RateUp(item:pmediafile); Procedure RateDown(item:pmediafile); Procedure Find(s:string); Procedure SortByName; Procedure SortByRate; Procedure AddItemstoPlaylist; Procedure AddItemtoPlaylist; Procedure AppendItemstoPlaylist; Procedure LoadSelection(Filename:String); Procedure LoadFolderICO(Filename:String); Procedure Root; Procedure Files; Procedure Select; Procedure FolderUP; Procedure ScrollDown; Procedure ScrollUp; Procedure Clear; Procedure UpdateLV; Property Font:tfont Read ffont Write setfont; Property Alpha:Cardinal Read falpha Write falpha; Property DrawMode:tdrawmode Read fdrawmode Write fdrawmode; Property X:Integer Read fx Write setx; Property Y:Integer Read fy Write sety; Property ListType:byte read ftype write ftype; Property Width:Integer Read fwidth Write setwidth; Property Title:String Read ftitle Write ftitle; Property Filename:String Read ffile Write ffile; Property Height:Integer Read fheight Write setheight; Property TitleHeight:Integer Read ftitleheight Write ftitleheight; Property Bitmap:tbitmaplayer Read fbitmap Write fbitmap; Property Items:tlist Read fitems Write Setitems; Property Visible:Boolean Read fvisible Write setvisible; Property ItemIndex:Integer Read findex Write setitemindex; Property Indent:Integer Read findent Write findent; Property ItemHeight:Integer Read fitemheight Write fitemheight; Property MaxItems:Integer Read fcount Write fcount; Property SizeRx:Integer Read fsrx Write fsrx; Property SizeRy:Integer Read fsry Write fsry; Property SizeRFont:Integer Read fsrf Write fsrf; Property RateRx:Integer Read frrx Write frrx; Property RateRy:Integer Read frry Write frry; Property RateRFont:Integer Read frrf Write frrf; End; function CompareNames(Item1, Item2: Pointer): Integer; function CompareRates(Item1, Item2: Pointer): Integer; Implementation Uses unit1,medialibrary; { TH2MediaList } Procedure TH2MediaList.Select; Begin If findex<0 Then exit; if fitems.count=0 then exit; if ftype=0 then begin If pmediafile(fitems[findex]).folder=False Then Begin if pmediafile(fitems[findex]).Playlist then if pos('ARTIST:',uppercase(pmediafile(fitems[findex]).hash))>0 then begin ftitle:=ftitle+': '+pmediafile(fitems[findex])^.name; unit1.MediaLibrary.ArtistPlaylist(pmediafile(fitems[findex])^.name); clear; fitems.Assign(unit1.MediaLibrary.Playlist); updatelv; exit; end else if pos('ALBUM:',uppercase(pmediafile(fitems[findex]).hash))>0 then begin ftitle:=ftitle+': '+pmediafile(fitems[findex])^.name; unit1.MediaLibrary.albumPlaylist(pmediafile(fitems[findex])^.name); clear; fitems.Assign(unit1.MediaLibrary.Playlist); updatelv; exit; end else if pos('YEAR:',uppercase(pmediafile(fitems[findex]).hash))>0 then begin ftitle:=ftitle+': '+pmediafile(fitems[findex])^.name; unit1.MediaLibrary.yearPlaylist(pmediafile(fitems[findex])^.name); clear; fitems.Assign(unit1.MediaLibrary.Playlist); updatelv; exit; end else if pos('GENRE:',uppercase(pmediafile(fitems[findex]).hash))>0 then begin ftitle:=ftitle+': '+pmediafile(fitems[findex])^.name; unit1.MediaLibrary.genrePlaylist(pmediafile(fitems[findex])^.name); clear; fitems.Assign(unit1.MediaLibrary.Playlist); updatelv; exit; end else if pos('RATE:',uppercase(pmediafile(fitems[findex]).hash))>0 then begin ftitle:=ftitle+': '+pmediafile(fitems[findex])^.name; unit1.MediaLibrary.ratePlaylist(strtoint(pmediafile(fitems[findex])^.name)); clear; fitems.Assign(unit1.MediaLibrary.Playlist); updatelv; exit; end else begin ftitle:=ftitle+': '+pmediafile(fitems[findex])^.name; clear; fitems.Assign(unit1.MediaLibrary.LoadM3U(pmediafile(fitems[findex])^.filename)); updatelv; exit; end; if pmediafile(fitems[findex])^.Music then begin form1.OpenStream(pmediafile(fitems[findex])^.Filename); end; End Else Begin ftitle:='Sort by '+pmediafile(fitems[findex])^.hash; if uppercase(pmediafile(fitems[findex]).hash)='ARTIST' then begin unit1.MediaLibrary.MakeArtistPlaylist(unit1.MediaLibrary.items); clear; fitems.Assign(unit1.MediaLibrary.Playlist); end else if uppercase(pmediafile(fitems[findex])^.hash)='ALBUM' then begin unit1.MediaLibrary.MakeAlbumPlaylist(unit1.MediaLibrary.items); clear; fitems.Assign(unit1.MediaLibrary.Playlist); end else if uppercase(pmediafile(fitems[findex])^.hash)='GENRE' then begin unit1.MediaLibrary.MakeGenrePlaylist(unit1.MediaLibrary.items); clear; fitems.Assign(unit1.MediaLibrary.Playlist); end else if uppercase(pmediafile(fitems[findex])^.hash)='YEAR' then begin unit1.MediaLibrary.MakeYearPlaylist(unit1.MediaLibrary.items); clear; fitems.Assign(unit1.MediaLibrary.Playlist); end else if uppercase(pmediafile(fitems[findex])^.hash)='FAVORITES' then begin unit1.MediaLibrary.MakeFavoritePlaylist(unit1.MediaLibrary.items); clear; fitems.Assign(unit1.MediaLibrary.Playlist); end else if uppercase(pmediafile(fitems[findex])^.hash)='MUSIC FOLDERS' then begin clear; makemusicfolders; end else if pos('FOLDER:',uppercase(pmediafile(fitems[findex])^.hash))>0 then begin ftype:=1; fdir:=IncludeTrailingPathDelimiter(pmediafile(fitems[findex])^.directory); files; end; updatelv; End; end else begin if pmediafile(fitems[findex])^.Folder=true then begin fdir:=fdir+pmediafile(fitems[findex]).filename; fdir:=IncludeTrailingPathDelimiter(fdir); files; end else if pmediafile(fitems[findex])^.Music=true then begin form1.OpenStream(pmediafile(fitems[findex])^.Filename); end; end; End; Procedure TH2MediaList.Clear; Var i:Integer; Begin // For i:=fitems.Count-1 Downto 0 Do dispose(pmediafile(fitems[i])); fitems.Clear; ffirst:=0; findex:=-1; fbitmap.Bitmap.Clear($000000); End; Constructor TH2MediaList.Create(AOwner: TComponent); Var L: TFloatRect; alayer:tbitmaplayer; v:pmediafile; Begin Inherited Create(AOwner); fbitmap:=TBitmapLayer.Create((aowner As timage32).Layers); fbitmap.OnMouseUp:=mousedown; ftitleheight:=15; ffont:=tfont.Create; fdrawmode:=dmblend; falpha:=255; fvisible:=True; fitems:=tlist.Create; ftitle:=''; fdir:='c:\'; ffile:=''; ftype:=0; fx:=0; fy:=0; fwidth:=100; fheight:=100; fbitmap.Bitmap.Width:=fwidth; fbitmap.Bitmap.Height:=fheight; l.Left:=fx; l.Top:=fy; l.Right:=fx+fwidth; l.Bottom:=fy+fheight; fbitmap.Location:=l; fbitmap.Tag:=0; fbitmap.Bitmap.DrawMode:=fdrawmode; fbitmap.Bitmap.MasterAlpha:=falpha; fselect:=tbitmap32.Create; fselect.DrawMode:=fdrawmode; fselect.MasterAlpha:=falpha; ffolder:=tbitmap32.create; ffolder.DrawMode:=fdrawmode; ffolder.MasterAlpha:=falpha; fcount:=5; findent:=0; ffirst:=0; findex:=-1; fitemheight:=20; makerootitems; End; Destructor TH2MediaList.Destroy; Begin //here ffont.Free; fbitmap.Free; ffolder.Free; fitems.Destroy; fselect.Free; Inherited Destroy; End; Procedure TH2MediaList.FindDir(DirList: tlist; startdir, filemask: String); Var SR: TSearchRec; IsFound: Boolean; i: Integer; v:pmediafile; Begin // Build a list of subdirectories IsFound := FindFirst(StartDir+'*.*', faAnyFile, SR) = 0; While IsFound Do Begin If ((SR.Attr And faDirectory) <> 0) And (SR.Name[1] <> '.') Then Begin new(v); v^.directory:=startdir; v^.name:=sr.name; v^.filename:=SR.Name; v^.size:=sr.Size; v^.folder:=True; v^.Music:=false; v^.Playlist:=false; v^.Time:=''; v^.Video:=false; DirList.Add(v); End; IsFound := FindNext(SR) = 0; End; FindClose(SR); End; Procedure TH2MediaList.Findfiles(FilesList: TList; StartDir,FileMask: String); Var SR: TSearchRec; IsFound: Boolean; i: Integer; v:pmediafile; Begin If StartDir[length(StartDir)] <> '\' Then StartDir := StartDir + '\'; { Build a list of the files in directory StartDir (not the directories!) } IsFound := FindFirst(StartDir+FileMask, faAnyFile-faDirectory, SR) = 0; While IsFound Do Begin new(v); v^.Directory:=startdir; v^.name:=SR.Name; v^.Filename:=v^.Directory+v^.name; v^.Size:=sr.Size; v^.folder:=False; v^.Music:=true; v^.Time:=''; FilesList.Add(v); IsFound := FindNext(SR) = 0; End; FindClose(SR); End; Procedure TH2MediaList.files; Begin clear; finddir(fitems,fdir,'*.*'); findfiles(fitems,fdir,'*.mp3'); findfiles(fitems,fdir,'*.ogg'); findfiles(fitems,fdir,'*.wma'); findfiles(fitems,fdir,'*.wav'); ftype:=1; updatelv; End; Procedure TH2MediaList.LoadFolderICO(Filename: String); Var au:Boolean; Begin If fileexists(filename) Then Begin Try LoadPNGintoBitmap32(ffolder,filename,au); Except End; End; End; Procedure TH2MediaList.LoadSelection(Filename: String); Var au:Boolean; L: TFloatRect; Begin If fileexists(filename) Then Begin Try LoadPNGintoBitmap32(fselect,filename,au); Except End; End; End; Procedure TH2MediaList.MouseDown(Sender: TObject; Buttons: TMouseButton; Shift: TShiftState; X, Y: Integer); Var i,c:Integer; Begin If ffirst+fcount>fitems.Count-1 Then c:=fitems.Count-1 Else c:=ffirst+fcount; For i:=ffirst To c Do Begin If (x>=fx+findent) And (x<=fx+fwidth) And (y>=ftitleheight+fy+(fitemheight*(i-ffirst))) And (y<=ftitleheight+fy+(fitemheight*(i-ffirst)+fitemheight)) Then findex:=i; End; updatelv; End; Procedure TH2MediaList.ScrollDown; Var i,d:Integer; Begin If ffirst+fcount>fitems.Count-1 Then exit; ffirst:=ffirst+fcount; updatelv; End; Procedure TH2MediaList.ScrollUp; Var i,d:Integer; Begin If ffirst-fcount<=0 Then ffirst:=0 Else ffirst:=ffirst-fcount; updatelv; End; Procedure TH2MediaList.SetDir(value: String); Var i:Integer; Begin i:=fbitmap.Bitmap.TextWidth(inttostr(findex)+'/'+inttostr(fitems.count)); fdir:=value; ftitle:=mince(value,fwidth-i,fbitmap.Bitmap); End; Procedure TH2MediaList.SetFont(value: tfont); Var Color: Longint; r, g, b: Byte; Begin ffont.Assign(value); Color := ColorToRGB(ffont.Color); r := Color; g := Color Shr 8; b := Color Shr 16; fbitmap.Bitmap.Font.assign(ffont); End; Procedure TH2MediaList.SetHeight(value: Integer); Var L: TFloatRect; Begin fheight:=value; l.Left:=fx; l.Top:=fy; l.Right:=fx+fwidth; l.Bottom:=fy+fheight; fbitmap.Location:=l; fbitmap.Bitmap.Height:=fheight; End; Procedure TH2MediaList.SetItemindex(value: Integer); Begin findex:=value; updatelv; End; Procedure TH2MediaList.SetItems(value: tlist); Begin fitems.Assign(value); findex:=fitems.Count-1; updatelv; End; Procedure TH2MediaList.Setvisible(value: Boolean); Begin fbitmap.Visible:=value; End; Procedure TH2MediaList.SetWidth(value: Integer); Var L: TFloatRect; Begin fwidth:=value; l.Left:=fx; l.Top :=fy; l.Right:=fx+fwidth; l.Bottom:=fy+fheight; fbitmap.Location:=l; fbitmap.Bitmap.Width:=fwidth; End; Procedure TH2MediaList.Setx(value: Integer); Var L: TFloatRect; Begin fx:=value; l.Left:=fx; l.Top:=fy; l.Right:=fx+fwidth; l.Bottom:=fy+fheight; fbitmap.Location:=l; End; Procedure TH2MediaList.Sety(value: Integer); Var L: TFloatRect; Begin fy:=value; l.Left:=fx; l.Top:=fy; l.Right:=fx+fwidth; l.Bottom:=fy+fheight; fbitmap.Location:=l; End; Procedure TH2MediaList.UpdateLV; Var i,c,h:Integer; a:Real; Color: Longint; r, g, b: Byte; s:String; Begin fbitmap.Bitmap.Clear($000000); Color := ColorToRGB(ffont.Color); r := Color; g := Color Shr 8; b := Color Shr 16; fbitmap.Bitmap.Font.Assign(ffont); h:=(ftitleheight Div 2)-(fbitmap.bitmap.TextHeight(inttostr(findex+1)+'/'+inttostr(fitems.Count)) Div 2); c:=fbitmap.bitmap.Textwidth(inttostr(findex+1)+'/'+inttostr(fitems.Count)); fbitmap.Bitmap.Rendertext(fwidth-c,h,inttostr(findex+1)+'/'+inttostr(fitems.Count),0,color32(r,g,b,falpha)); s:=mince(ftitle,fwidth-c,fbitmap.Bitmap); h:=(ftitleheight Div 2)-(fbitmap.bitmap.TextHeight(s) Div 2); fbitmap.Bitmap.Rendertext(2,h,S,0,color32(r,g,b,falpha)); If fitems.Count=0 Then exit; If ffirst+fcount>fitems.Count-1 Then c:=fitems.Count-1 Else c:=ffirst+fcount; For i:=ffirst To c Do Begin If i=findex Then Begin fselect.DrawTo(fbitmap.Bitmap,0,ftitleheight+fitemheight*(i-ffirst)); End; If pmediafile(fitems[i])^.folder=True Then Begin ffolder.DrawTo(fbitmap.Bitmap,0,2+ftitleheight+fitemheight*(i-ffirst)); h:=2; fbitmap.Bitmap.Rendertext(findent,(fitemheight*(i-ffirst))+h+ftitleheight,pmediafile(fitems[i])^.name,0,color32(r,g,b,falpha)); fbitmap.Bitmap.Font.Size:=fbitmap.Bitmap.Font.Size+fsrf; fbitmap.Bitmap.Rendertext(fsrx,(fitemheight*(i-ffirst))+fsry+ftitleheight,'<Folder>',0,color32(r,g,b,falpha)); fbitmap.Bitmap.Font.Size:=fbitmap.Bitmap.Font.Size-fsrf; End Else If pmediafile(fitems[i])^.playlist=true Then Begin h:=2; fbitmap.Bitmap.Rendertext(findent,(fitemheight*(i-ffirst))+h+ftitleheight,pmediafile(fitems[i])^.name,0,color32(r,g,b,falpha)); fbitmap.Bitmap.Font.Size:=fbitmap.Bitmap.Font.Size+fsrf; s:='<Playlist>'; fbitmap.Bitmap.Rendertext(fsrx,(fitemheight*(i-ffirst))+fsry+ftitleheight,s,0,color32(r,g,b,falpha)); fbitmap.Bitmap.Font.Size:=fbitmap.Bitmap.Font.Size-fsrf; End else if pmediafile(fitems[i])^.music=true Then If fileexists(pmediafile(fitems[i])^.filename) Then Begin h:=2; fbitmap.Bitmap.Rendertext(findent,(fitemheight*(i-ffirst))+h+ftitleheight,mince(pmediafile(fitems[i])^.name,fwidth-findent,fbitmap.Bitmap),0,color32(r,g,b,falpha)); fbitmap.Bitmap.Font.Size:=fbitmap.Bitmap.Font.Size+fsrf; if pmediafile(fitems[i])^.music then s:=pmediafile(fitems[i])^.time; fbitmap.Bitmap.Rendertext(findent+fsrx,(fitemheight*(i-ffirst))+fsry+ftitleheight,s,0,color32(r,g,b,falpha)); fbitmap.Bitmap.Font.Size:=fbitmap.Bitmap.Font.Size-fsrf; fbitmap.Bitmap.Font.Size:=fbitmap.Bitmap.Font.Size+frrf; if pmediafile(fitems[i])^.music then s:=inttostr(pmediafile(fitems[i])^.rate)+'/5'; fbitmap.Bitmap.Rendertext(findent+frrx,(fitemheight*(i-ffirst))+frry+ftitleheight,s,0,color32(r,g,b,falpha)); fbitmap.Bitmap.Font.Size:=fbitmap.Bitmap.Font.Size-frrf; End; End; End; Procedure TH2MediaList.FolderUP; Var s:String; MyStr: Pchar; i, Len: Integer; SectPerCls, BytesPerCls, FreeCls, TotCls : DWord; v:pmediafile; Const Size: Integer = 200; Begin if ftype=1 then begin s:=IncludeTrailingPathDelimiter(fdir); ftitle:=s; setcurrentdir(s); If length(s)=3 Then Begin clear; GetMem(MyStr, Size); Len:=GetLogicalDriveStrings(Size, MyStr); For i:=0 To Len-1 Do Begin If (ord(MyStr[i])>=65)And(ord(MyStr[i])<=90) Or (ord(MyStr[i])>=97)And(ord(MyStr[i])<=122) Then Begin new(v); v^.directory:=''; v^.filename:=uppercase(MyStr[i]+':\'); v^.name:=v^.filename; v^.time:=''; v^.size:=0; v^.folder:=True; v^.music:=false; v^.playlist:=false; fitems.Add(v); End; End; FreeMem(MyStr); fdir:=''; updatelv; End Else Begin chdir('..'); If IOResult <> 0 Then Begin End Else Begin s:=getcurrentdir; fdir:=IncludeTrailingPathDelimiter(s); files; End; updatelv; End; end else if unit1.MediaLibrary.SortString='' then begin root; end else begin if unit1.MediaLibrary.Sorttype='ARTIST' then begin ftitle:=copy(ftitle,1,pos(':',ftitle)-1); unit1.MediaLibrary.MakeArtistPlaylist(unit1.MediaLibrary.items); clear; fitems.Assign(unit1.MediaLibrary.Playlist); end else if unit1.MediaLibrary.Sorttype='ALBUM' then begin ftitle:=copy(ftitle,1,pos(':',ftitle)-1); unit1.MediaLibrary.MakealbumPlaylist(unit1.MediaLibrary.items); clear; fitems.Assign(unit1.MediaLibrary.Playlist); end else if unit1.MediaLibrary.Sorttype='YEAR' then begin ftitle:=copy(ftitle,1,pos(':',ftitle)-1); unit1.MediaLibrary.MakeyearPlaylist(unit1.MediaLibrary.items); clear; fitems.Assign(unit1.MediaLibrary.Playlist); end else if unit1.MediaLibrary.Sorttype='RATE' then begin ftitle:=copy(ftitle,1,pos(':',ftitle)-1); unit1.MediaLibrary.MakefavoritePlaylist(unit1.MediaLibrary.items); clear; fitems.Assign(unit1.MediaLibrary.Playlist); end else if unit1.MediaLibrary.Sorttype='GENRE' then begin ftitle:=copy(ftitle,1,pos(':',ftitle)-1); unit1.MediaLibrary.MakegenrePlaylist(unit1.MediaLibrary.items); clear; fitems.Assign(unit1.MediaLibrary.Playlist); end; updatelv; unit1.MediaLibrary.SortString:=''; end; End; procedure TH2MediaList.MakeRootitems; var v:pmediafile; begin ftype:=0; clear; ftitle:='Sort by...'; new(v); v^.name:='Album'; v^.hash:=v.name; v^.Folder:=true; v^.Music:=false; v^.Playlist:=false; fitems.Add(v); new(v); v^.name:='Artist'; v^.hash:=v.name; v^.Folder:=true; v^.Music:=false; v^.Playlist:=false; fitems.Add(v); new(v); v^.name:='Genre'; v^.hash:=v.name; v^.Folder:=true; v^.Music:=false; v^.Playlist:=false; fitems.Add(v); new(v); v^.name:='Year'; v^.hash:=v.name; v^.Folder:=true; v^.Music:=false; v^.Playlist:=false; fitems.Add(v); new(v); v^.name:='Favorites'; v^.hash:=v.name; v^.Folder:=true; v^.Music:=false; v^.Playlist:=false; fitems.Add(v); new(v); v^.name:='Music Folders'; v^.hash:=v.name; v^.Folder:=true; v^.Music:=false; v^.Playlist:=false; fitems.Add(v); end; procedure TH2MediaList.Root; begin makerootitems; updatelv; end; procedure TH2MediaList.MakeMusicFolders; var i:integer; v:pmediafile; begin ftype:=0; clear; if unit1.MediaLibrary.Paths.Count=0 then exit; for i:=0 to unit1.MediaLibrary.Paths.Count-1 do begin new(v); v^.Directory:=unit1.MediaLibrary.Paths[i]; v^.name:=getfoldernamefrompath(v^.Directory); v^.hash:='FOLDER: '+v^.name; v^.folder:=true; v^.Playlist:=false; v^.Video:=false; v^.Music:=false; fitems.Add(v); end; end; procedure TH2MediaList.AddItemstoPlaylist; var i:integer; begin if fitems.Count=0 then exit; unit1.MediaLibrary.Playlist.Clear; for i:=0 to fitems.count-1 do if pmediafile(fitems[i])^.music=true then unit1.MediaLibrary.playlist.add(fitems[i]); end; procedure TH2MediaList.AppendItemstoPlaylist; var i:integer; begin if fitems.Count=0 then exit; for i:=0 to fitems.count-1 do if pmediafile(fitems[i])^.music=true then unit1.MediaLibrary.playlist.add(fitems[i]); end; procedure TH2MediaList.RateUp(item: pmediafile); begin if item=nil then exit; if item^.Music=false then exit; if item^.Rate>=5 then exit; item^.Rate:=item^.Rate+1; end; procedure TH2MediaList.RateDown(item: pmediafile); begin if item=nil then exit; if item^.Music=false then exit; if item^.Rate<=0 then exit; item^.Rate:=item^.Rate-1; end; function CompareNames(Item1, Item2: Pointer): Integer; begin Result := CompareText(pmediafile(item1)^.name, pmediafile(item2)^.Name); end; function CompareRates(Item1, Item2: Pointer): Integer; begin Result := CompareText(inttostr(pmediafile(item1)^.rate), inttostr(pmediafile(item2)^.rate)); end; procedure TH2MediaList.SortByName; begin fitems.Sort(@comparenames); updatelv; end; procedure TH2MediaList.SortByRate; begin fitems.Sort(@comparerates); updatelv; end; procedure TH2MediaList.AddItemtoPlaylist; begin if findex<0 then exit; if pmediafile(fitems[findex])^.music=true then unit1.MediaLibrary.playlist.add(fitems[findex]); end; procedure TH2MediaList.Find(s: string); var i:integer; begin if s='' then exit; if unit1.MediaLibrary.Items.count=0 then exit; clear; for i:=unit1.MediaLibrary.Items.Count-1 downto 0 do if pos(uppercase(s),uppercase(pmediafile(unit1.MediaLibrary.Items[i])^.name))>0 then fitems.Add(unit1.MediaLibrary.Items[i]); updatelv; end; End.
unit NetNumberClass; interface type INumber = interface function GetValue: Integer; procedure SetValue (New: Integer); procedure Increase; end; TNumber = class(TObject, INumber) private fValue: Integer; public constructor Create; function GetValue: Integer; procedure SetValue (New: Integer); procedure Increase; end; implementation { TNumber } constructor TNumber.Create; begin fValue := 10; end; function TNumber.GetValue: Integer; begin Result := fValue; end; procedure TNumber.Increase; begin Inc (fValue); end; procedure TNumber.SetValue(New: Integer); begin fValue := New; end; end.
unit ResidentialTasks; interface uses Tasks, Kernel, Tutorial, Population, BuildFacilitiesTask; const tidTask_BuildResidentials = 'BuildRes'; tidTask_HighClassResidential = 'hiRes'; tidTask_MiddleClassResidential = 'midRes'; tidTask_LowClassResidential = 'lowRes'; type TMetaResidentialsTask = class(TMetaBuildFacilitiesTask) private fKind : TPeopleKind; public property Kind : TPeopleKind read fKind write fKind; end; TBuildResidentialsTask = class(TSuperTask) protected class function GetPriority(MetaTask : TMetaTask; SuperTask : TTask; Context : ITaskContext) : integer; override; end; TBuildSpecificResidentialsTask = class(TBuildFacilitiesTask) protected class function GetPriority(MetaTask : TMetaTask; SuperTask : TTask; Context : ITaskContext) : integer; override; procedure DefineTarget; override; end; // Return how many houses requires this town function HousesRequired(TownHall : TTownHall; kinds : array of TPeopleKind) : integer; procedure RegisterBackup; implementation uses MathUtils, FacIds, BackupInterfaces; type TDemandToHouse = array[TPeopleKind] of integer; TMinPopulation = array[TPeopleKind] of integer; const Demands : TDemandToHouse = (50, 80, 100); MinPeople : TMinPopulation = (50, 100, 300); const MaxResidentialTiBuild = 3; function HousesRequired(TownHall : TTownHall; kinds : array of TPeopleKind) : integer; var rdInput : TInput; wdInput : TInput; i : integer; HsRq : integer; ppd : TFluidValue; rsd : TFluidValue; ratio : single; begin result := 0; for i := low(kinds) to high(kinds) do if TownHall.Unemployment[kinds[i]] = 0 then begin rdInput := TownHall.InputsByName[PeopleKindPrefix[kinds[i]] + tidGate_ResDemand]; wdInput := TownHall.InputsByName[PeopleKindPrefix[kinds[i]] + tidGate_WorkDemand]; if (rdInput <> nil) and (wdInput <> nil) then begin rsd := rdInput.LastValue.Q; ppd := WorkForceToPeople(kinds[i], wdInput.LastValue.Q); if rsd = 0 then ratio := 0 else ratio := ppd/rsd; if ratio >= 0.5 then HsRq := min(3, round((ppd - rsd)/Demands[kinds[i]])) else if TownHall.LastPop[kinds[i]].Q < MinPeople[kinds[i]] then HsRq := 1 else HsRq := 0; inc(result, HsRq); end; end; end; // TBuildResidentialsTask class function TBuildResidentialsTask.GetPriority(MetaTask : TMetaTask; SuperTask : TTask; Context : ITaskContext) : integer; var Town : TInhabitedTown; begin result := inherited GetPriority(MetaTask, SuperTask, Context); if result <> tprIgnoreTask then begin Town := TInhabitedTown(Context.getContext(tcIdx_Town)); if (Town = nil) or (HousesRequired(TTownHall(Town.TownHall.CurrBlock), [pkHigh, pkMiddle, pkLow]) = 0) then result := tprIgnoreTask; end; end; // TBuildSpecificResidentialsTask class function TBuildSpecificResidentialsTask.GetPriority(MetaTask : TMetaTask; SuperTask : TTask; Context : ITaskContext) : integer; var Town : TInhabitedTown; count : integer; begin result := inherited GetPriority(MetaTask, SuperTask, Context); if result <> tprIgnoreTask then begin Town := TInhabitedTown(Context.getContext(tcIdx_Town)); count := HousesRequired(TTownHall(Town.TownHall.CurrBlock), TMetaResidentialsTask(MetaTask).Kind); if count > 0 then result := MetaTask.Priority + count else result := tprIgnoreTask; end; end; procedure TBuildSpecificResidentialsTask.DefineTarget; var Town : TInhabitedTown; begin Town := TInhabitedTown(Context.getContext(tcIdx_Town)); ReqCount := HousesRequired(TTownHall(Town.TownHall.CurrBlock), TMetaResidentialsTask(MetaTask).Kind); end; procedure RegisterBackup; begin RegisterClass( TBuildResidentialsTask ); RegisterClass( TBuildSpecificResidentialsTask ); end; end.
unit Ragna.Types; {$IF DEFINED(FPC)} {$MODE DELPHI}{$H+} {$ENDIF} interface type {$SCOPEDENUMS ON} TOperatorType = (WHERE, &OR, LIKE, EQUALS, ORDER, &AND); {$SCOPEDENUMS OFF} TOperatorTypeHelper = record helper for TOperatorType public function ToString: string; end; implementation function TOperatorTypeHelper.ToString: string; begin case Self of TOperatorType.WHERE: Result := 'WHERE'; TOperatorType.OR: Result := 'OR'; TOperatorType.LIKE: Result := 'LIKE'; TOperatorType.EQUALS: Result := '='; TOperatorType.ORDER: Result := 'ORDER BY'; TOperatorType.AND: Result := 'AND'; end; end; end.
// ------------------------------------ // Missing FSDIVE calls from DIVE.DLL // ------------------------------------ unit FSDIVE; interface uses os2def; {&cdecl+} type pFBINFO=^FBINFO; FBINFO=record ulLength : ULONG; //* Length of FBINFO data structure, in bytes. */ ulCaps : ULONG; //* Specifies the PM Driver capabilities. */ ulBPP : ULONG; //* Screen bits per pel. */ ulXRes : ULONG; //* Number of screen X pels. */ ulYRes : ULONG; //* Number of screen Y pels. */ ulScanLineBytes : ULONG; //* Number of bytes per scanline. */ fccColorEncoding : ULONG; //* Screen color encoding. */ ulNumENDIVEDrivers : ULONG;//* Number of pluggable EnDIVE drivers. */ end; type pAperture=^APERTURE; APERTURE=record //* aperture */ ulPhysAddr : ULONG; //* physical address */ ulApertureSize : ULONG; //* 1 Meg, 4 Meg or 64k */ ulScanLineSize : ULONG; //* this is >= the screen width */ rctlScreen : RECTL; //* device independant co-ordinates */ end; const DIVE_FULLY_VISIBLE = $ffffffff; // Missing from os2mm.pas! procedure DiveFullScreenInit(pNewAperture:pAPERTURE; pNewframeBuffer:pFBINFO); procedure DiveFullScreenTerm; implementation procedure DiveFullScreenInit(pNewAperture:pAPERTURE; pNewframeBuffer:pFBINFO); external 'DIVE' index 16; procedure DiveFullScreenTerm; external 'DIVE' index 17; end.
unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Pessoa; type TForm1 = class(TForm) Memo1: TMemo; Button1: TButton; Memo2: TMemo; Memo3: TMemo; Memo4: TMemo; Button2: TButton; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } FPessoa : TPessoa; public { Public declarations } end; var Form1: TForm1; implementation uses System.RTTI; {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); var ctxRtti : TRttiContext; typRtti : TRttiType; metRtti : TRttiMethod; fldRtti : TRttiField; prpRtti : TRttiProperty; begin ctxRtti := TRttiContext.Create; try typRtti := ctxRtti.GetType(TForm1); for metRtti in typRtti.GetMethods do memo1.Lines.Add(metRtti.Name); for fldRtti in typRtti.GetFields do memo2.Lines.Add(fldRtti.Name); for prpRtti in typRtti.GetProperties do memo3.Lines.Add(prpRtti.Name); finally ctxRtti.Free; end; end; procedure TForm1.Button2Click(Sender: TObject); var ctxRtti : TRttiContext; typRtti : TRttiType; prpRtti : TRttiProperty; begin ctxRtti := TRttiContext.Create; try typRtti := ctxRtti.GetType(FPessoa.ClassType); for prpRtti in typRtti.GetProperties do begin if prpRtti.GetValue(FPessoa).ToString = '' then raise Exception.Create('O campo ' + prpRtti.Name + ' da Classe ' + typRtti.Name + ' não pode ser vazio'); Memo4.Lines.Add(prpRtti.Name +':'+ prpRtti.GetValue(FPessoa).ToString); end; finally ctxRtti.Free; end; end; procedure TForm1.FormCreate(Sender: TObject); begin FPessoa := TPessoa.Create; end; end.
{ Subroutine SST_R_PAS_VPARAM (PROC) * * Apply the VAL_PARAM routine option to the arguments of a routine. PROC * is the descriptor for the routine. } module sst_r_pas_vparam; define sst_r_pas_vparam; %include 'sst_r_pas.ins.pas'; procedure sst_r_pas_vparam ( {apply VAL_PARAM to routine template} in out proc: sst_proc_t); {routine descriptor that will have args fixed} var arg_p: sst_proc_arg_p_t; {points to current argument being processed} dt_p: sst_dtype_p_t; {scratch pointer to data type descriptor} label next_arg; begin arg_p := proc.first_arg_p; {init first argument as current} while arg_p <> nil do begin {once for each call argument} if arg_p^.univ {no effect if UNIV specified} then goto next_arg; if sst_rwflag_write_k in arg_p^.rwflag_ext {value being passed back ?} then goto next_arg; if arg_p^.pass = sst_pass_val_k {already passing by value ?} then goto next_arg; if {too large to pass by value automatically ?} arg_p^.dtype_p^.size_used > sst_config.pass_val_size_max then goto next_arg; dt_p := arg_p^.dtype_p; {get pointer to argument data type descriptor} while {resolve argument's base data type} dt_p^.dtype = sst_dtype_copy_k do dt_p := dt_p^.copy_dtype_p; if dt_p^.dtype = sst_dtype_array_k {argument is an array ?} then goto next_arg; case sst_config.os of {special cases for different target OSs} sys_os_aix_k, {IBM AIX} sys_os_domain_k: begin {Apollo Domain/OS} if dt_p^.dtype = sst_dtype_rec_k then begin {passing a record ?} goto next_arg; {VAL_PARAM doesn't apply to records} end; end; end; {end of particular OS special handling cases} arg_p^.pass := sst_pass_val_k; {argument will be passed by value} arg_p^.rwflag_int := {all access allowed to internal copy} [sst_rwflag_read_k, sst_rwflag_write_k]; arg_p^.rwflag_ext := {caller's argument will not be altered} [sst_rwflag_read_k]; next_arg: {jump here to advance to next call argument} arg_p := arg_p^.next_p; {advance to next call argument} end; {back and process this new call argument} end;
{ Date Created: 5/22/00 11:17:33 AM } unit InfoPULFTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoPULFRecord = record PVSIStatus: String[2]; PModCount: SmallInt; Pname: String[30]; PLoanNumber: String[18]; Pofficer: String[6]; PpolicyNumber: String[10]; End; TInfoPULFBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoPULFRecord end; TEIInfoPULF = (InfoPULFPrimaryKey, InfoPULFSI_Stat, InfoPULFLoanNumber, InfoPULFLoanOfficer, InfoPULFPolicyNumber); TInfoPULFTable = class( TDBISAMTableAU ) private FDFVSIStatus: TStringField; FDFModCount: TSmallIntField; FDFname: TStringField; FDFLoanNumber: TStringField; FDFofficer: TStringField; FDFpolicyNumber: TStringField; procedure SetPVSIStatus(const Value: String); function GetPVSIStatus:String; procedure SetPModCount(const Value: SmallInt); function GetPModCount:SmallInt; procedure SetPname(const Value: String); function GetPname:String; procedure SetPLoanNumber(const Value: String); function GetPLoanNumber:String; procedure SetPofficer(const Value: String); function GetPofficer:String; procedure SetPpolicyNumber(const Value: String); function GetPpolicyNumber:String; function GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; procedure SetEnumIndex(Value: TEIInfoPULF); function GetEnumIndex: TEIInfoPULF; protected function CreateField( const FieldName : string ): TField; procedure CreateFields; virtual; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoPULFRecord; procedure StoreDataBuffer(ABuffer:TInfoPULFRecord); property DFVSIStatus: TStringField read FDFVSIStatus; property DFModCount: TSmallIntField read FDFModCount; property DFname: TStringField read FDFname; property DFLoanNumber: TStringField read FDFLoanNumber; property DFofficer: TStringField read FDFofficer; property DFpolicyNumber: TStringField read FDFpolicyNumber; property PVSIStatus: String read GetPVSIStatus write SetPVSIStatus; property PModCount: SmallInt read GetPModCount write SetPModCount; property Pname: String read GetPname write SetPname; property PLoanNumber: String read GetPLoanNumber write SetPLoanNumber; property Pofficer: String read GetPofficer write SetPofficer; property PpolicyNumber: String read GetPpolicyNumber write SetPpolicyNumber; procedure Validate; virtual; published property Active write SetActive; property EnumIndex: TEIInfoPULF read GetEnumIndex write SetEnumIndex; end; { TInfoPULFTable } procedure Register; implementation function TInfoPULFTable.GenerateNewFieldName( AOwner: TComponent; const DatasetName: string; const FieldName: string ): string; var I: Integer; NewName: string; Done: Boolean; function ComponentExists( AOwner: TComponent; const CompName: string ): Boolean; var I: Integer; begin Result := False; for I := 0 To AOwner.ComponentCount - 1 do begin if AnsiCompareText( CompName, AOwner.Components[ I ].Name ) = 0 then begin Result := True; Break; end; end; end; { ComponentExists } begin { TInfoPULFTable.GenerateNewFieldName } NewName := DatasetName; for I := 1 to Length( FieldName ) do begin if FieldName[ I ] in [ '0'..'9', '_', 'A'..'Z', 'a'..'z' ] then NewName := NewName + FieldName[ I ]; end; if ComponentExists( Owner, NewName ) then begin I := 1; Done := False; repeat Inc( I ); if not ComponentExists( AOwner, NewName + IntToStr( I ) ) then begin Result := NewName + IntToStr( I ); Done := True; end; until Done; end else Result := NewName; end; { TInfoPULFTable.GenerateNewFieldName } function TInfoPULFTable.CreateField( const FieldName : string ): TField; begin { First, try to find an existing field object. FindField is the same } { as FieldByName, but does not raise an exception if the field object } { cannot be found. } Result := FindField( FieldName ); if Result = nil then begin { If an existing field object cannot be found... } { Instruct the FieldDefs object to create a new field object } Result := FieldDefs.Find( FieldName ).CreateField( Owner ); { The new field object must be given a name so that it may appear in } { the Object Inspector. The Delphi default naming convention is used.} Result.Name := GenerateNewFieldName( Owner, Name, FieldName); end; end; { TInfoPULFTable.CreateField } procedure TInfoPULFTable.CreateFields; begin FDFVSIStatus := CreateField( 'VSIStatus' ) as TStringField; FDFModCount := CreateField( 'ModCount' ) as TSmallIntField; FDFname := CreateField( 'name' ) as TStringField; FDFLoanNumber := CreateField( 'LoanNumber' ) as TStringField; FDFofficer := CreateField( 'officer' ) as TStringField; FDFpolicyNumber := CreateField( 'policyNumber' ) as TStringField; end; { TInfoPULFTable.CreateFields } procedure TInfoPULFTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoPULFTable.SetActive } procedure TInfoPULFTable.Validate; begin { Enter Validation Code Here } end; { TInfoPULFTable.Validate } procedure TInfoPULFTable.SetPVSIStatus(const Value: String); begin DFVSIStatus.Value := Value; end; function TInfoPULFTable.GetPVSIStatus:String; begin result := DFVSIStatus.Value; end; procedure TInfoPULFTable.SetPModCount(const Value: SmallInt); begin DFModCount.Value := Value; end; function TInfoPULFTable.GetPModCount:SmallInt; begin result := DFModCount.Value; end; procedure TInfoPULFTable.SetPname(const Value: String); begin DFname.Value := Value; end; function TInfoPULFTable.GetPname:String; begin result := DFname.Value; end; procedure TInfoPULFTable.SetPLoanNumber(const Value: String); begin DFLoanNumber.Value := Value; end; function TInfoPULFTable.GetPLoanNumber:String; begin result := DFLoanNumber.Value; end; procedure TInfoPULFTable.SetPofficer(const Value: String); begin DFofficer.Value := Value; end; function TInfoPULFTable.GetPofficer:String; begin result := DFofficer.Value; end; procedure TInfoPULFTable.SetPpolicyNumber(const Value: String); begin DFpolicyNumber.Value := Value; end; function TInfoPULFTable.GetPpolicyNumber:String; begin result := DFpolicyNumber.Value; end; procedure TInfoPULFTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('VSIStatus, String, 2, N'); Add('ModCount, SmallInt, 0, N'); Add('name, String, 30, N'); Add('LoanNumber, String, 18, N'); Add('officer, String, 6, N'); Add('policyNumber, String, 10, N'); end; end; procedure TInfoPULFTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, VSIStatus;name, Y, Y, N, N'); Add('SI_Stat, VSIStatus;name, N, N, N, N'); Add('LoanNumber, VSIStatus;LoanNumber, N, N, Y, N'); Add('LoanOfficer, VSIStatus;officer, N, N, Y, N'); Add('PolicyNumber, VSIStatus;policyNumber, N, N, Y, N'); end; end; procedure TInfoPULFTable.SetEnumIndex(Value: TEIInfoPULF); begin case Value of InfoPULFPrimaryKey : IndexName := ''; InfoPULFSI_Stat : IndexName := 'SI_Stat'; InfoPULFLoanNumber : IndexName := 'LoanNumber'; InfoPULFLoanOfficer : IndexName := 'LoanOfficer'; InfoPULFPolicyNumber : IndexName := 'PolicyNumber'; end; end; function TInfoPULFTable.GetDataBuffer:TInfoPULFRecord; var buf: TInfoPULFRecord; begin fillchar(buf, sizeof(buf), 0); buf.PVSIStatus := DFVSIStatus.Value; buf.PModCount := DFModCount.Value; buf.Pname := DFname.Value; buf.PLoanNumber := DFLoanNumber.Value; buf.Pofficer := DFofficer.Value; buf.PpolicyNumber := DFpolicyNumber.Value; result := buf; end; procedure TInfoPULFTable.StoreDataBuffer(ABuffer:TInfoPULFRecord); begin DFVSIStatus.Value := ABuffer.PVSIStatus; DFModCount.Value := ABuffer.PModCount; DFname.Value := ABuffer.Pname; DFLoanNumber.Value := ABuffer.PLoanNumber; DFofficer.Value := ABuffer.Pofficer; DFpolicyNumber.Value := ABuffer.PpolicyNumber; end; function TInfoPULFTable.GetEnumIndex: TEIInfoPULF; var iname : string; begin iname := uppercase(indexname); if iname = '' then result := InfoPULFPrimaryKey; if iname = 'SI_STAT' then result := InfoPULFSI_Stat; if iname = 'LOANNUMBER' then result := InfoPULFLoanNumber; if iname = 'LOANOFFICER' then result := InfoPULFLoanOfficer; if iname = 'POLICYNUMBER' then result := InfoPULFPolicyNumber; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoPULFTable, TInfoPULFBuffer ] ); end; { Register } function TInfoPULFBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PVSIStatus; 2 : result := @Data.PModCount; 3 : result := @Data.Pname; 4 : result := @Data.PLoanNumber; 5 : result := @Data.Pofficer; 6 : result := @Data.PpolicyNumber; end; end; end. { InfoPULFTable }
{ Copyright (C) Alexey Torgashin, uvviewsoft.com License: MPL 2.0 or LGPL } unit win32menustyler; {$mode objfpc}{$H+} interface uses Windows, SysUtils, Classes, Graphics, Menus, Forms, LCLType; type TWin32MenuStylerTheme = record ColorBk: TColor; ColorBkSelected: TColor; ColorFont: TColor; ColorFontDisabled: TColor; CharCheckmark: Widechar; CharRadiomark: Widechar; FontName: string; FontSize: integer; IndentX: integer; IndentX2: integer; IndentY: integer; end; type { TWin32MenuStyler } TWin32MenuStyler = class private procedure HandleMenuDrawItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect; AState: TOwnerDrawState); public procedure ApplyToForm(AForm: TForm); end; var MenuStylerTheme: TWin32MenuStylerTheme; MenuStyler: TWin32MenuStyler = nil; implementation procedure TWin32MenuStyler.ApplyToForm(AForm: TForm); var menu: TMainMenu; mi: TMENUINFO; begin menu:= AForm.Menu; if menu=nil then exit; menu.OwnerDraw:= true; menu.OnDrawItem:= @HandleMenuDrawItem; //this is to theme 2-3 pixel frame around menu popups FillChar(mi{%H-}, sizeof(mi), 0); mi.cbSize:= sizeof(mi); mi.fMask:= MIM_BACKGROUND or MIM_APPLYTOSUBMENUS; mi.hbrBack:= CreateSolidBrush(MenuStylerTheme.ColorBk); SetMenuInfo(GetMenu(AForm.Handle), @mi); end; procedure TWin32MenuStyler.HandleMenuDrawItem(Sender: TObject; ACanvas: TCanvas; ARect: TRect; AState: TOwnerDrawState); var mi: TMenuItem; dx, dy: integer; mark: Widechar; BufW: UnicodeString; begin mi:= Sender as TMenuItem; if odDisabled in AState then ACanvas.Font.Color:= MenuStylerTheme.ColorFontDisabled else ACanvas.Font.Color:= MenuStylerTheme.ColorFont; if odSelected in AState then ACanvas.Brush.Color:= MenuStylerTheme.ColorBkSelected else ACanvas.Brush.Color:= MenuStylerTheme.ColorBk; if mi.IsInMenuBar then dx:= MenuStylerTheme.IndentX else dx:= MenuStylerTheme.IndentX2; dy:= MenuStylerTheme.IndentY; ACanvas.FillRect(ARect); ACanvas.Font.Name:= MenuStylerTheme.FontName; ACanvas.Font.Size:= MenuStylerTheme.FontSize; BufW:= UTF8Decode(mi.Caption); Windows.TextOutW(ACanvas.Handle, ARect.Left+dx, ARect.Top+dy, PWideChar(BufW), Length(BufW)); if mi.Checked then begin if mi.RadioItem then mark:= MenuStylerTheme.CharRadiomark else mark:= MenuStylerTheme.CharCheckmark; Windows.TextOutW(ACanvas.Handle, ARect.Left+2, ARect.Top+dy, @mark, 1); end; end; initialization MenuStyler:= TWin32MenuStyler.Create; with MenuStylerTheme do begin ColorBk:= clDkGray; ColorBkSelected:= clNavy; ColorFont:= clWhite; ColorFontDisabled:= clMedGray; CharCheckmark:= #$2713; CharRadiomark:= #$25CF; //#$2022; FontName:= 'default'; FontSize:= 9; IndentX:= 5; IndentX2:= 21; IndentY:= 2; end; finalization FreeAndNil(MenuStyler); end.
unit kwPopEditorScrollBottom; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "ScriptEngine" // Модуль: "w:/common/components/rtl/Garant/ScriptEngine/kwPopEditorScrollBottom.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<ScriptKeyword::Class>> Shared Delphi Scripting::ScriptEngine::EditorFromStackKeyWords::pop_editor_ScrollBottom // // *Формат:* aVeritcal anEditorControl pop:editor:ScrollBottom // *Описание:* Прокручивает документ в самый низ/максимально вправо. aVeritcal - если true, то // скроллируем повертикали. // *Пример:* // {code} // true focused:control:push pop:editor:ScrollBottom // {code} // *Результат:* Прокрутить в самый низ документа. // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\ScriptEngine\seDefine.inc} interface {$If not defined(NoScripts)} uses evCustomEditorWindow, tfwScriptingInterfaces, Controls, Classes ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type {$Include ..\ScriptEngine\kwEditorFromStackWord.imp.pas} TkwPopEditorScrollBottom = {final} class(_kwEditorFromStackWord_) {* *Формат:* aVeritcal anEditorControl pop:editor:ScrollBottom *Описание:* Прокручивает документ в самый низ/максимально вправо. aVeritcal - если true, то скроллируем повертикали. *Пример:* [code] true focused:control:push pop:editor:ScrollBottom [code] *Результат:* Прокрутить в самый низ документа. } protected // realized methods procedure DoWithEditor(const aCtx: TtfwContext; anEditor: TevCustomEditorWindow); override; public // overridden public methods class function GetWordNameForRegister: AnsiString; override; end;//TkwPopEditorScrollBottom {$IfEnd} //not NoScripts implementation {$If not defined(NoScripts)} uses tfwAutoregisteredDiction, tfwScriptEngine, Windows, afwFacade, Forms ; {$IfEnd} //not NoScripts {$If not defined(NoScripts)} type _Instance_R_ = TkwPopEditorScrollBottom; {$Include ..\ScriptEngine\kwEditorFromStackWord.imp.pas} // start class TkwPopEditorScrollBottom procedure TkwPopEditorScrollBottom.DoWithEditor(const aCtx: TtfwContext; anEditor: TevCustomEditorWindow); //#UC START# *4F4CB81200CA_4F4F178600E8_var* var l_Vertical: Boolean; //#UC END# *4F4CB81200CA_4F4F178600E8_var* begin //#UC START# *4F4CB81200CA_4F4F178600E8_impl* if aCtx.rEngine.IsTopBool then l_Vertical := aCtx.rEngine.PopBool else Assert(False, 'Не задана ориентация прокрукти!'); anEditor.View.Scroller[l_Vertical].Bottom; //#UC END# *4F4CB81200CA_4F4F178600E8_impl* end;//TkwPopEditorScrollBottom.DoWithEditor class function TkwPopEditorScrollBottom.GetWordNameForRegister: AnsiString; {-} begin Result := 'pop:editor:ScrollBottom'; end;//TkwPopEditorScrollBottom.GetWordNameForRegister {$IfEnd} //not NoScripts initialization {$If not defined(NoScripts)} {$Include ..\ScriptEngine\kwEditorFromStackWord.imp.pas} {$IfEnd} //not NoScripts end.
unit cCadCargoPessoa; interface uses System.Classes, Vcl.Controls, Vcl.ExtCtrls, Vcl.Dialogs, FireDAC.Comp.Client, System.SysUtils; // LISTA DE UNITS type TCargoPessoa = class private // VARIAVEIS PRIVADA SOMENTE DENTRO DA CLASSE ConexaoDB: TFDConnection; F_cod_carg_pessoa: Integer; F_cod_membro: Integer; F_nome: string; F_cod_cargo: Integer; F_cargo: string; F_cod_congregacao:Integer; F_status: string; public constructor Create(aConexao: TFDConnection); // CONSTRUTOR DA CLASSE destructor Destroy; override; // DESTROI A CLASSE USAR OVERRIDE POR CAUSA function Inserir: Boolean; function Atualizar: Boolean; function Apagar: Boolean; function Selecionar(id: Integer): Boolean; published // VARIAVEIS PUBLICAS UTILAIZADAS PARA PROPRIEDADES DA CLASSE // PARA FORNECER INFORMAÇÕESD EM RUMTIME property cod_carg_pessoa: Integer read F_cod_carg_pessoa write F_cod_carg_pessoa; property cod_cargo: Integer read F_cod_cargo write F_cod_cargo; property cargo: string read F_cargo write F_cargo; property cod_membro: Integer read F_cod_membro write F_cod_membro; property cod_congregacao: Integer read F_cod_congregacao write F_cod_congregacao; property status: string read F_status write F_status; property nome: string read F_nome write F_nome; end; implementation {$REGION 'Constructor and Destructor'} constructor TCargoPessoa.Create; begin ConexaoDB := aConexao; end; destructor TCargoPessoa.Destroy; begin inherited; end; {$ENDREGION} {$REGION 'CRUD'} function TCargoPessoa.Apagar: Boolean; var Qry: TFDQuery; begin if MessageDlg('Apagar o Registro: ' + #13 + #13 + 'Código: ' + IntToStr(F_cod_carg_pessoa) + #13 + 'Descrição: ' + F_nome, mtConfirmation, [mbYes, mbNo], 0) = mrNO then begin Result := false; Abort; end; Try Result := True; Qry := TFDQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('DELETE FROM igreja.tb_obreiro_cargo WHERE COD_CARG_PESSOA=:cod_carg_pessoa'); Qry.ParamByName('cod_carg_pessoa').AsInteger := F_cod_carg_pessoa; try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; except ConexaoDB.Rollback; Result:=false; end; Finally if Assigned(Qry) then FreeAndNil(Qry) End; end; function TCargoPessoa.Atualizar: Boolean; var Qry: TFDQuery; begin try Result := True; Qry := TFDQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('UPDATE igreja.tb_obreiro_cargo '+ ' SET COD_MEMBRO=:COD_MEMBRO, NOME=:NOME, COD_CARGO=:COD_CARGO, CARGO=:CARGO, '+ ' STATUS=:STATUS, COD_CONGREGACAO=:COD_CONGREGACAO WHERE COD_CARG_PESSOA=:COD_CARG_PESSOA'); Qry.ParamByName('COD_CARG_PESSOA').AsInteger := F_cod_carg_pessoa; Qry.ParamByName('COD_CARGO').AsInteger := F_cod_cargo; Qry.ParamByName('CARGO').AsString := F_cargo; Qry.ParamByName('COD_MEMBRO').AsInteger := F_cod_membro; Qry.ParamByName('NOME').AsString := F_nome; Qry.ParamByName('STATUS').AsString := F_status; Qry.ParamByName('COD_CONGREGACAO').AsInteger := F_cod_congregacao; try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; except ConexaoDB.Rollback; Result:=false; end; finally if Assigned(Qry) then FreeAndNil(Qry) end; end; function TCargoPessoa.Inserir: Boolean; var Qry: TFDQuery; begin try Result := True; Qry := TFDQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('INSERT INTO tb_obreiro_cargo '+ ' (COD_MEMBRO, NOME, COD_CARGO, CARGO, STATUS, '+ 'COD_CONGREGACAO) VALUES '+ '(:COD_MEMBRO,:NOME,:COD_CARGO,:CARGO,:STATUS,:COD_CONGREGACAO)'); Qry.ParamByName('COD_CARGO').AsInteger := Self.F_cod_cargo; Qry.ParamByName('CARGO').AsString := Self.F_cargo; Qry.ParamByName('COD_MEMBRO').AsInteger := Self.F_cod_membro; Qry.ParamByName('NOME').AsString := Self.F_nome; Qry.ParamByName('COD_CONGREGACAO').AsInteger := Self.F_cod_congregacao; Qry.ParamByName('STATUS').AsString := Self.F_status; try ConexaoDB.StartTransaction; Qry.ExecSQL; ConexaoDB.Commit; except ConexaoDB.Rollback; Result:=false; end; finally if Assigned(Qry) then FreeAndNil(Qry) end; end; function TCargoPessoa.Selecionar(id: Integer): Boolean; var Qry: TFDQuery; begin try Result := True; Qry := TFDQuery.Create(nil); Qry.Connection := ConexaoDB; Qry.SQL.Clear; Qry.SQL.Add('SELECT COD_CARG_PESSOA, COD_MEMBRO, NOME, COD_CARGO, CARGO, '+ ' STATUS, COD_CONGREGACAO FROM igreja.tb_obreiro_cargo '+ ' WHERE COD_CARG_PESSOA=:cod_carg_pessoa '); Qry.ParamByName('cod_carg_pessoa').AsInteger := id; try Qry.Open; Self.F_cod_carg_pessoa := Qry.FieldByName('COD_CARG_PESSOA').AsInteger; Self.F_cod_cargo := Qry.FieldByName('COD_CARGO').AsInteger; Self.F_nome := Qry.FieldByName('NOME').AsString; Self.F_cod_membro := Qry.FieldByName('COD_MEMBRO').AsInteger; Self.F_cod_congregacao := Qry.FieldByName('COD_CONGREGACAO').AsInteger; Self.F_status := Qry.FieldByName('status').AsString; Except Result := false; end; finally if Assigned(Qry) then FreeAndNil(Qry) end; end; {$ENDREGION} end. { ALTER TABLE igreja.tb_obreiro_cargo MODIFY COLUMN COD_MEMBRO int(10) NULL; ALTER TABLE igreja.tb_obreiro_cargo ADD cod_carg_pessoa INT NOT NULL AUTO_INCREMENT; ALTER TABLE igreja.tb_obreiro_cargo CHANGE cod_carg_pessoa cod_carg_pessoa INT NOT NULL AUTO_INCREMENT FIRST; ALTER TABLE igreja.tb_obreiro_cargo DROP PRIMARY KEY; ALTER TABLE igreja.tb_obreiro_cargo ADD CONSTRAINT tb_obreiro_cargo_pk PRIMARY KEY (cod_carg_pessoa); }
unit LookForFolder; interface uses Windows, SysUtils, Forms; function BrowseDirectory(ActiveForm : TForm; const BrowseTitle : string) : string; implementation const BIF_RETURNONLYFSDIRS = $0001; type TBFFCallBack = function(hwnd : THandle; Msg : UINT; lParam : LPARAM; lpData : LPARAM) : integer; type PShellItemID = ^TShellItemID; TShellItemID = record Count : word; Data : array[0..1] of byte; end; type PItemIDList = ^TItemIDList; TItemIDList = record ID : TShellItemID; end; type PBrowseInfo = ^TBrowseInfo; TBrowseInfo = record Owner : THandle; Root : PItemIDList; DisplayName : pchar; // Return display name of item selected. Title : pchar; // text to go in the banner over the tree. Flags : UINT; // Flags that control the return stuff funct : TBFFCallBack; Param : LPARAM; // extra info that's passed back in callbacks Image : integer; // output var: where to return the Image index. end; function SHBrowseForFolder(lpbi : PBrowseInfo) : PItemIDList; stdcall; external 'Shell32.dll'; function SHGetPathFromIDList(pidl : PItemIDList; Path : pchar) : BOOL; stdcall; external 'Shell32.dll' function BrowseDlg(ActiveForm : TForm; const BrowseTitle : string; RootFolder : PItemIDList; Options : integer) : string; var pidl : PItemIDList; BrowseInfo : TBrowseInfo; SelName : array [0..MAX_PATH] of char; begin with BrowseInfo do begin if ActiveForm <> nil then Owner := ActiveForm.Handle else Owner := Application.Handle; Root := RootFolder; DisplayName := SelName; Title := PCHAR(BrowseTitle); Flags := Options; funct := nil; Param := 0; end; pidl := SHBrowseForFolder(@BrowseInfo); if pidl <> nil then begin SetLength(result, MAX_PATH); if SHGetPathFromIDList(pidl, PCHAR(result)) then SetLength(result, strlen(PCHAR(result))) else SetLength(result, 0); end else result := ''; end; function BrowseDirectory(ActiveForm : TForm; const BrowseTitle : string) : string; begin Result := BrowseDlg(ActiveForm, BrowseTitle, nil, BIF_RETURNONLYFSDIRS); end; end.
{***********************************************************************} { TPlannerDatePicker component } { for Delphi & C++ Builder } { } { written by : } { TMS Software } { copyright © 1999-2010 } { Email : info@tmssoftware.com } { Website : http://www.tmssoftware.com } { } { The source code is given as is. The author is not responsible } { for any possible damage done due to the use of this code. } { The component can be freely used in any application. The source } { code remains property of the writer and may not be distributed } { freely as such. } {***********************************************************************} {$I TMSDEFS.INC} unit PlannerMaskDatePicker; interface uses Windows, Messages, SysUtils, Classes, Controls, Forms, Dialogs, AdvMEdBtn, PlannerCal {$IFDEF DELPHI7_LVL} , MaskUtils {$ENDIF} ; const MAJ_VER = 1; // Major version nr. MIN_VER = 5; // Minor version nr. REL_VER = 1; // Release nr. BLD_VER = 0; // Build nr. // Version history // 1.4.0.0 : Property Calendar.InActiveDays added // 1.5.0.0 : AutoThemeAdapt in Calendar added // : XP style dropdown button added // : Hover date color in Calendar added // 1.5.0.1 : Improved TPlannerDBMaskDatePicker mask handling // 1.5.0.2 : Fixed : issue with use on forms with fsStayOnTop formstyle set // 1.5.0.3 : Fixed : issue with OnInvalidDate event // 1.5.0.4 : Improved : check for empty / incomplete entered dates // 1.5.0.5 : Fixed : issue with persisting calendar settings // 1.5.0.6 : Fixed : issue with position of calendar for runtime created control // 1.5.0.7 : Fixed : issue with updating PlannerDBMaskDatePicker // 1.5.1.0 : New : DroppedDown public property added type {$IFDEF DELPHIXE2_LVL} [ComponentPlatformsAttribute(pidWin32 or pidWin64)] {$ENDIF} TPlannerMaskDatePicker = class(TAdvMaskEditBtn) private FPlannerCalendar: TPlannerCalendar; APlannerCalendar: TPlannerCalendar; PlannerParent : TForm; CancelThisBtnClick : Boolean; FHideCalendarAfterSelection: boolean; FOnDaySelect: TDaySelectEvent; FOnInvalidDate: TNotifyEvent; FDroppedDown: boolean; function GetOnGetDateHint: TGetDateEvent; function GetOnGetDateHintString: TGetDateEventHint; procedure SetOnGetDateHint(const Value: TGetDateEvent); procedure SetOnGetDateHintString(const Value: TGetDateEventHint); procedure HideParent; function GetParentEx: TWinControl; procedure SetParentEx(const Value: TWinControl); function GetOnGetEventProp: TEventPropEvent; procedure SetOnGetEventProp(const Value: TEventPropEvent); function GetOnWeekSelect: TNotifyEvent; procedure SetOnWeekSelect(const Value: TNotifyEvent); function GetOnAllDaySelect: TNotifyEvent; procedure SetOnAllDaySelect(const Value: TNotifyEvent); function GetDate: TDateTime; procedure SetDate(const Value: TDateTime); procedure SetDroppedDown(const Value: boolean); { Private declarations } protected function GetVersionNr: Integer; override; { Protected declarations } procedure InitEvents; virtual; procedure BtnClick(Sender: TObject); override; procedure PlannerParentDeactivate(Sender: TObject); procedure PlannerCalendarDaySelect(Sender: TObject; SelDate: TDateTime); procedure PlannerCalendarKeyPress(Sender: TObject; var Key: Char); procedure PlannerCalendarKeyDown(Sender: TObject; var Key: Integer; Shift: TShiftState); procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS; // methods to do correct streaming, because the planner calendar is // stored on a hidden form function GetChildParent : TComponent; override; function GetChildOwner : TComponent; override; procedure Change; override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure DaySelect; virtual; procedure ValidateError; override; public { Public declarations } constructor Create(AOwner: TComponent); override; procedure CancelBtnClick; destructor Destroy; override; procedure DoExit; override; procedure DropDown; virtual; procedure CreateWnd; override; property Date: TDateTime read GetDate write SetDate; property Parent: TWinControl read GetParentEx write SetParentEx; procedure Loaded; override; procedure GetChildren(Proc: TGetChildProc; Root: TComponent); override; property DroppedDown: boolean read FDroppedDown write SetDroppedDown; published { Published declarations } property Calendar : TPlannerCalendar read FPlannerCalendar write FPlannerCalendar; property HideCalendarAfterSelection : boolean read FHideCalendarAfterSelection write FHideCalendarAfterSelection; property OnGetDateHint: TGetDateEvent read GetOnGetDateHint write SetOnGetDateHint; property OnGetDateHintString: TGetDateEventHint read GetOnGetDateHintString write SetOnGetDateHintString; property OnGetEventProp: TEventPropEvent read GetOnGetEventProp write SetOnGetEventProp; property OnWeekSelect: TNotifyEvent read GetOnWeekSelect write SetOnWeekSelect; property OnAllDaySelect: TNotifyEvent read GetOnAllDaySelect write SetOnAllDaySelect; property OnDaySelect: TDaySelectEvent read FOnDaySelect write FOnDaySelect; property OnInvalidDate: TNotifyEvent read FOnInvalidDate write FOnInvalidDate; end; implementation uses StdCtrls, Graphics; {$I DELPHIXE.INC} { TPlannerDatePicker } procedure TPlannerMaskDatePicker.DropDown; var PlannerPosition : TPoint; r: TRect; function Min(a,b: Integer): Integer; begin if (a > b) then Result := b else Result := a; end; function GetParentWnd: HWnd; var Last, P: HWnd; begin P := GetParent((Owner as TWinControl).Handle); Last := P; while P <> 0 do begin Last := P; P := GetParent(P); end; Result := Last; end; begin PlannerParent.Visible := false; if (Parent is TForm) then begin if (Parent as TForm).FormStyle = fsStayOnTop then PlannerParent.FormStyle := fsStayOnTop; end else PlannerParent.FormStyle := fsStayOnTop; // Set planner position PlannerPosition.x := -2; PlannerPosition.y := Height - 3; PlannerPosition := ClientToScreen(PlannerPosition); SystemParametersInfo(SPI_GETWORKAREA, 0,@r,0); //account for taskbar... if (plannerposition.y + FPlannerCalendar.Height > r.Bottom) then plannerposition.Y := plannerposition.Y - FPlannerCalendar.Height - Height + 3; if (plannerposition.x + FPlannerCalendar.Width > r.right) then plannerposition.x := plannerposition.x - (FPlannerCalendar.Width - Width); PlannerParent.Width := 0; PlannerParent.Height := 0; PlannerParent.Left := - 300; PlannerParent.Top := - 300; PlannerParent.Visible := true; // Set planner date if FPlannerCalendar.MultiSelect then Text := FPlannerCalendar.DatesAsText else begin try if (Text = '') or (Pos(' ',Text) in [1..5]) then FPlannerCalendar.Date := Now else try FPlannerCalendar.Date := StrToDate(Text); except if (FPlannerCalendar.Date = 0) then FPlannerCalendar.Date := Now; //; keep old date set active end; except on Exception do Text := FPlannerCalendar.DatesAsText; end; end; MoveWindow(PlannerParent.Handle, plannerposition.X, plannerposition.Y, 0, 0, true); // PlannerParent.Show; FPlannerCalendar.SetFocus; SendMessage(GetParentWnd, WM_NCACTIVATE, 1, 0); FDroppedDown := true; end; procedure TPlannerMaskDatePicker.BtnClick(Sender: TObject); begin SetFocus; CancelThisBtnClick := False; inherited; // call event OnClick - the user can cancel calendar appearance of calendar by calling .CancelBtnClick if CancelThisBtnClick then Exit; DropDown; end; procedure TPlannerMaskDatePicker.CancelBtnClick; begin CancelThisBtnClick := True; end; constructor TPlannerMaskDatePicker.Create(AOwner: TComponent); begin inherited; // Make planner parent form and a planner, put planner on parent form Text := ''; PlannerParent := TForm.Create(Self); PlannerParent.BorderStyle := bsNone; FPlannerCalendar := TPlannerCalendar.Create(Self); FPlannerCalendar.Parent := PlannerParent; FPlannerCalendar.Name := self.Name +'mcal'+inttostr(AOwner.ComponentCount)+'_'; PlannerParent.Autosize := True; PlannerParent.OnDeactivate := PlannerParentDeactivate; FPlannerCalendar.OnDaySelect := PlannerCalendarDaySelect; Width := FPlannerCalendar.Width; FHideCalendarAfterSelection := True; Button.Glyph.Handle := LoadBitmap(0, MakeIntResource(OBM_COMBO)); // Make the button NOT change the focus Button.FocusControl := nil; end; destructor TPlannerMaskDatePicker.Destroy; begin FPlannerCalendar.Free; PlannerParent.Free; inherited; end; function TPlannerMaskDatePicker.GetChildOwner: TComponent; begin Result := PlannerParent; end; function TPlannerMaskDatePicker.GetChildParent: TComponent; begin Result := PlannerParent; end; procedure TPlannerMaskDatePicker.GetChildren(Proc: TGetChildProc; Root: TComponent); begin inherited; Proc(FPlannerCalendar); FPlannerCalendar.Parent := PlannerParent; end; function TPlannerMaskDatePicker.GetOnGetDateHint: TGetDateEvent; begin Result := FPlannerCalendar.OnGetDateHint; end; function TPlannerMaskDatePicker.GetOnGetDateHintString: TGetDateEventHint; begin Result := FPlannerCalendar.OnGetDateHintString; end; procedure TPlannerMaskDatePicker.HideParent; begin PlannerParent.Hide; try SetFocus; except end; end; procedure TPlannerMaskDatePicker.KeyDown(var Key: Word; Shift: TShiftState); begin inherited; if (key = VK_F4) and not (ssAlt in Shift) and not (ssCtrl in Shift) then if PlannerParent.Visible then HideParent else BtnClick(Self); end; procedure TPlannerMaskDatePicker.InitEvents; begin FPlannerCalendar.OnDaySelect := PlannerCalendarDaySelect; FPlannerCalendar.OnKeyPress := PlannerCalendarKeypress; end; procedure TPlannerMaskDatePicker.Loaded; begin inherited; //if (not (csDesigning in ComponentState)) then if PlannerParent.ComponentCount > 0 then begin APlannerCalendar := (PlannerParent.Components[0] as TPlannerCalendar); APlannerCalendar.OnGetDateHint := FPlannerCalendar.OnGetDateHint; APlannerCalendar.OnGetDateHintString := FPlannerCalendar.OnGetDateHintString; FPlannerCalendar.Free; FPlannerCalendar := APlannerCalendar; InitEvents; end; end; procedure TPlannerMaskDatePicker.PlannerCalendarDaySelect(Sender: TObject; SelDate: TDateTime); begin if not ReadOnly then begin Text := FPlannerCalendar.DatesAsText; end; if FHideCalendarAfterSelection then HideParent; if Assigned(FOnDaySelect) then FOnDaySelect(Self,SelDate); end; procedure TPlannerMaskDatePicker.DaySelect; begin end; procedure TPlannerMaskDatePicker.PlannerCalendarKeyDown(Sender: TObject; var Key: Integer; Shift: TShiftState); begin if Key = VK_F4 then HideParent; end; procedure TPlannerMaskDatePicker.PlannerCalendarKeyPress(Sender: TObject; var Key: Char); begin if (Key = #13) then begin PlannerCalendarDaySelect(Sender, FPlannerCalendar.Date); end; if Key = #27 then begin HideParent; end; end; procedure TPlannerMaskDatePicker.PlannerParentDeactivate(Sender: TObject); begin (Sender as TForm).Hide; FDroppedDown := false; end; procedure TPlannerMaskDatePicker.SetOnGetDateHint(const Value: TGetDateEvent); begin FPlannerCalendar.OnGetDateHint := Value; end; procedure TPlannerMaskDatePicker.SetOnGetDateHintString( const Value: TGetDateEventHint); begin FPlannerCalendar.OnGetDateHintString := Value; end; function TPlannerMaskDatePicker.GetOnGetEventProp: TEventPropEvent; begin Result := FPlannerCalendar.OnGetEventProp; end; procedure TPlannerMaskDatePicker.SetOnGetEventProp( const Value: TEventPropEvent); begin FPlannerCalendar.OnGetEventProp := Value; end; procedure TPlannerMaskDatePicker.WMSetFocus(var Message: TWMSetFocus); begin if EditorEnabled then inherited else Button.SetFocus; end; procedure TPlannerMaskDatePicker.Change; var dt: TDateTime; begin try {$IFDEF DELPHI7_LVL} if IsMasked and (Text = MaskDoFormatText(EditMask,'',MaskGetMaskBlank(EditMask))) then begin Calendar.Date := 0; Exit; end; {$ENDIF} if (Text = '') or (Pos(DateSeparator, Text) = 0) then Calendar.Date := 0 else begin {$IFDEF DELPHI7_LVL} TryStrToDate(Text,dt); {$ENDIF} {$IFNDEF DELPHI7_LVL} dt := StrToDate(Text); {$ENDIF} Calendar.Date := dt; end; except end; inherited; end; procedure TPlannerMaskDatePicker.CreateWnd; begin inherited; InitEvents; end; function TPlannerMaskDatePicker.GetParentEx: TWinControl; begin Result := inherited Parent; end; procedure TPlannerMaskDatePicker.SetParentEx(const Value: TWinControl); begin inherited Parent := Value; InitEvents; end; function TPlannerMaskDatePicker.GetOnWeekSelect: TNotifyEvent; begin Result := FPlannerCalendar.OnWeekSelect; end; procedure TPlannerMaskDatePicker.SetOnWeekSelect(const Value: TNotifyEvent); begin FPlannerCalendar.OnWeekSelect := Value; end; function TPlannerMaskDatePicker.GetOnAllDaySelect: TNotifyEvent; begin Result := FPlannerCalendar.OnAllDaySelect; end; procedure TPlannerMaskDatePicker.SetOnAllDaySelect(const Value: TNotifyEvent); begin FPlannerCalendar.OnAllDaySelect := Value; end; function TPlannerMaskDatePicker.GetDate: TDateTime; begin Result := FPlannerCalendar.Date; end; procedure TPlannerMaskDatePicker.SetDate(const Value: TDateTime); begin FPlannerCalendar.Date := Value; Text := DateToStr(Value); end; procedure TPlannerMaskDatePicker.SetDroppedDown(const Value: boolean); begin FDroppedDown := Value; if DroppedDown then DropDown else SetFocus; end; procedure TPlannerMaskDatePicker.DoExit; var dt: TDateTime; begin inherited; try if (Text <> '') then begin dt := StrToDate(Text); Calendar.Date := dt; end; except if Assigned(FOnInvalidDate) then FOnInvalidDate(Self) end; end; function TPlannerMaskDatePicker.GetVersionNr: Integer; begin Result := MakeLong(MakeWord(BLD_VER,REL_VER),MakeWord(MIN_VER,MAJ_VER)); end; procedure TPlannerMaskDatePicker.ValidateError; begin if Assigned(FOnInvalidDate) then FOnInvalidDate(Self) else inherited; end; initialization RegisterClass(TPlannerMaskDatePicker); end.
{$I ok_sklad.inc} unit EditPriceTypes; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, dxCntner, dxEditor, StdCtrls, ActnList, ssBaseTypes, ssFormStorage, cxCheckBox, cxControls, cxContainer, cxEdit, cxTextEdit, cxLookAndFeelPainters, cxButtons, ssBaseDlg, ssBevel, ImgList, ssSpeedButton, ssPanel, ssGradientPanel, cxMaskEdit, cxDropDownEdit, cxCalc, ssCalcEdit, xButton, cxRadioGroup, cxGroupBox, ssGroupBox, DB, DBClient, ssClientDataSet, ssDBLookupCombo, ssLabel; type TfrmEditPriceTypes = class(TBaseDlg) bvlMain: TssBevel; edName: TcxTextEdit; lName: TLabel; chbDefault: TcxCheckBox; gbType: TssGroupBox; edExtra: TssCalcEdit; rbtExtra: TcxRadioButton; rbtDisc: TcxRadioButton; cdsPriceTypes: TssClientDataSet; dsPriceTypes: TDataSource; lcbPriceTypes: TssDBLookupCombo; lDiscText: TssLabel; edDisc: TssCalcEdit; imgExtra: TImage; imgDisc: TImage; cbExtra: TcxComboBox; lcbPTExtra: TssDBLookupCombo; procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure ActionListUpdate(Action: TBasicAction; var Handled: Boolean); procedure DataModified(Sender: TObject); procedure bvlMainMouseEnter(Sender: TObject); procedure bvlMainMouseLeave(Sender: TObject); procedure rbtExtraClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure cbExtraPropertiesEditValueChanged(Sender: TObject); private procedure GetImages; function CheckParent: Boolean; protected procedure setid(const Value: integer); override; procedure SetParentName(const Value: string); override; public ParentHandle: HWND; procedure SetCaptions; override; { Public declarations } end; var frmEditPriceTypes: TfrmEditPriceTypes; implementation uses ssBaseConst, prConst, ClientData, prFun, ssCallbackConst, fMessageDlg, udebug; var DEBUG_unit_ID: Integer; Debugging: Boolean; DEBUG_group_ID: String = ''; {$R *.dfm} //============================================================================================== procedure TfrmEditPriceTypes.setid(const Value: integer); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelLow, DEBUG_unit_ID, 'TfrmEditPriceTypes.setid') else _udebug := nil;{$ENDIF} if not IsPattern then FID := Value; with newDataSet do try if Value <> 0 then begin if not IsPattern then Self.Caption := rs(ParentNameEx, 'TitleEdit') else Self.Caption := rs(ParentNameEx, 'TitleAdd'); ProviderName := 'pPriceTypes_Get'; FetchParams; Params.ParamByName('PTypeID').AsInteger := Value; Open; if not IsEmpty then begin edName.Text := fieldbyname('Name').asstring; chbDefault.Checked := FieldByName('def').AsInteger = 1; if FieldByName('pptypeid').IsNull then begin rbtExtra.Checked := True; edExtra.Value := FieldByName('onvalue').AsFloat; end else if FieldByName('extratype').AsInteger = 2 then begin rbtExtra.Checked := True; cbExtra.ItemIndex := 1; edExtra.Value := FieldByName('onvalue').AsFloat; lcbPTExtra.KeyValue := FieldByName('pptypeid').AsInteger; end else begin rbtDisc.Checked := True; edDisc.Value := FieldByName('onvalue').AsFloat; lcbPriceTypes.KeyValue := FieldByName('pptypeid').AsInteger; end; end; Close; if not IsPattern then begin btnApply.Enabled := False; chbDefault.Enabled := not chbDefault.Checked; end; end else Self.Caption := rs(ParentNameEx, 'TitleAdd'); finally Free; end; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmEditPriceTypes.FormCloseQuery(Sender: TObject; var CanClose: Boolean); var NewRecord: boolean; {$IFDEF UDEBUG}_udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelLow, DEBUG_unit_ID, 'TfrmEditPriceTypes.FormCloseQuery') else _udebug := nil;{$ENDIF} if ModalResult in [mrOK, mrYes] then begin CanClose := False; if not CheckParent then begin {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} Exit; end; with newDataSet do try TrStart; try NewRecord := (ID = 0); if NewRecord then FID := GetMaxID(dmData.SConnection, 'pricetypes', 'ptypeid'); if chbDefault.Checked then begin ProviderName := 'pPriceTypes_SetDef'; Execute; chbDefault.Enabled := false; end; if NewRecord then ProviderName := 'pPriceTypes_Ins' else ProviderName := 'pPriceTypes_Upd'; FetchParams; Params.ParamByName('ptypeid').AsInteger := FID; Params.ParamByName('num').AsInteger := FID; if rbtExtra.Checked and (cbExtra.ItemIndex = 1) then Params.ParamByName('extratype').AsInteger := 2 else Params.ParamByName('extratype').AsInteger := 0; Params.ParamByName('name').AsString := edName.Text; if rbtExtra.Checked then begin Params.ParamByName('onvalue').AsFloat := edExtra.Value; if cbExtra.ItemIndex = 0 then begin Params.ParamByName('pptypeid').DataType := ftInteger; Params.ParamByName('pptypeid').Clear; end else Params.ParamByName('pptypeid').AsInteger := lcbPTExtra.KeyValue; end else begin Params.ParamByName('onvalue').AsFloat := edDisc.Value; Params.ParamByName('pptypeid').AsInteger := lcbPriceTypes.KeyValue; end; Params.ParamByName('def').AsInteger := Integer(chbDefault.Checked); Execute; TrCommit; SendMessage(MainHandle, WM_REFRESH, ID, 0); if RefreshAllClients then dmData.SConnection.AppServer.q_Add(CA_REFRESH, CA_PRICETYPES); if ModalResult = mrYes then begin if NewRecord then begin if not IsPattern then begin edName.Text := EmptyStr; edExtra.Value := 0; end; edName.SetFocus; FID := 0; end end else CanClose := True; FModified := False; finally Free; end; except on e:exception do begin TrRollback; ssMessageDlg(e.Message, ssmtError, [ssmbOk]); end; end; end; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmEditPriceTypes.ActionListUpdate(Action: TBasicAction; var Handled: Boolean); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditPriceTypes.ActionListUpdate') else _udebug := nil;{$ENDIF} aOk.Enabled := Trim(edName.Text) <> EmptyStr; aApply.Enabled := aOk.Enabled and FModified; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmEditPriceTypes.DataModified(Sender: TObject); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditPriceTypes.DataModified') else _udebug := nil;{$ENDIF} FModified := True; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmEditPriceTypes.SetCaptions; {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditPriceTypes.SetCaptions') else _udebug := nil;{$ENDIF} inherited; with LangMan do begin lName.Caption := GetRS(ParentNameEx, 'Name') + ':'; chbDefault.Properties.Caption := GetRS('Common', 'Default'); with cbExtra do begin Properties.Items.Add(GetRS('fmMaterials', 'ExtraIn')); Properties.Items.Add(GetRS('fmMaterials', 'ExtraPT')); ItemIndex := 0; end; //lExtraText.Caption := GetRS(ParentNameEx, 'ExtraText'); lDiscText.Caption := GetRS(ParentNameEx, 'DiscText'); rbtDisc.Caption := GetRS(ParentNameEx, 'Disc') + ', %:'; rbtExtra.Caption := GetRS(ParentNameEx, 'Extra') + ', %:'; gbType.Caption := ' ' + GetRS(ParentNameEx, 'Type') + ' '; end; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmEditPriceTypes.SetParentName(const Value: string); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditPriceTypes.SetParentName') else _udebug := nil;{$ENDIF} FParentName := Value; SetCaptions; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmEditPriceTypes.bvlMainMouseEnter(Sender: TObject); //{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin (*{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditPriceTypes.bvlMainMouseEnter') else _udebug := nil;{$ENDIF} with Sender as TssBevel do if HotTrack then bvlSep.ColorOuter := HotTrackColor; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} *) end; //============================================================================================== procedure TfrmEditPriceTypes.bvlMainMouseLeave(Sender: TObject); //{$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin (*{$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditPriceTypes.bvlMainMouseLeave') else _udebug := nil;{$ENDIF} with Sender as TssBevel do if HotTrack then bvlSep.ColorOuter := clBtnShadow; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} *) end; //============================================================================================== procedure TfrmEditPriceTypes.rbtExtraClick(Sender: TObject); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditPriceTypes.rbtExtraClick') else _udebug := nil;{$ENDIF} edExtra.Enabled := rbtExtra.Checked; lcbPriceTypes.Enabled := rbtDisc.Checked; cbExtra.Enabled := edExtra.Enabled; lcbPTExtra.Enabled := cbExtra.Enabled; lDiscText.Enabled := rbtDisc.Checked; edDisc.Enabled := lcbPriceTypes.Enabled; GetImages; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmEditPriceTypes.FormCreate(Sender: TObject); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditPriceTypes.FormCreate') else _udebug := nil;{$ENDIF} inherited; cdsPriceTypes.Open; GetImages; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmEditPriceTypes.GetImages; {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditPriceTypes.GetImages') else _udebug := nil;{$ENDIF} if rbtExtra.Checked then begin dmData.Images.GetBitmap(107, imgExtra.Picture.Bitmap); dmData.Images.GetBitmap(161, imgDisc.Picture.Bitmap); end else begin dmData.Images.GetBitmap(162, imgExtra.Picture.Bitmap); dmData.Images.GetBitmap(108, imgDisc.Picture.Bitmap); end; imgDisc.Repaint; imgExtra.Repaint; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== procedure TfrmEditPriceTypes.cbExtraPropertiesEditValueChanged(Sender: TObject); {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditPriceTypes.cbExtraPropertiesEditValueChanged') else _udebug := nil;{$ENDIF} lcbPTExtra.Visible := cbExtra.ItemIndex = 1; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; //============================================================================================== function TfrmEditPriceTypes.CheckParent: Boolean; {$IFDEF UDEBUG}var _udebug: Tdebug;{$ENDIF} begin {$IFDEF UDEBUG}if Debugging then _udebug := Tdebug.Create(debugLevelHigh, DEBUG_unit_ID, 'TfrmEditPriceTypes.CheckParent') else _udebug := nil;{$ENDIF} Result := True; if FID = 0 then begin {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} Exit; end; if (rbtExtra.Checked and (cbExtra.ItemIndex = 1) and (lcbPTExtra.KeyValue = FID)) or (rbtDisc.Checked and (lcbPriceTypes.KeyValue = FID)) then begin Result := False; ssMessageDlg(Format(rs('fmMaterials', 'WrongPType'), [edName.Text]), ssmtError, [ssmbOk]); end; {$IFDEF UDEBUG}if _udebug <> nil then _udebug.Destroy;{$ENDIF} end; initialization {$IFDEF UDEBUG}Debugging := False; DEBUG_unit_ID := debugRegisterUnit('EditPriceTypes', @Debugging, DEBUG_group_ID);{$ENDIF} finalization //{$IFDEF UDEBUG}debugUnregisterUnit(DEBUG_unit_ID);{$ENDIF} end.
unit Button; interface uses DGLE, DGLE_Types, Engine, Types; type TButtonState = (bsNone, bsOver, bsDown); type TButton = class(TObject) private P: TPoint; FLeft: Integer; FTop: Integer; FHeight: Integer; FWidth: Integer; FCaption: AnsiString; FFontColor: TColor4; FState: TButtonState; pButton: array [0..2] of ITexture; FSellected: Boolean; FFontColorSellected: TColor4; FFontColorOver: TColor4; procedure SetLeft(const Value: Integer); procedure SetTop(const Value: Integer); procedure SetHeight(const Value: Integer); procedure SetWidth(const Value: Integer); procedure SetCaption(const Value: AnsiString); procedure SetFontColor(const Value: TColor4); procedure SetState(const Value: TButtonState); procedure SetSellected(const Value: Boolean); procedure SetFontColorSellected(const Value: TColor4); procedure SetFontColorOver(const Value: TColor4); public constructor Create(); destructor Destroy; override; property Top: Integer read FTop write SetTop; property Left: Integer read FLeft write SetLeft; property Width: Integer read FWidth write SetWidth; property Height: Integer read FHeight write SetHeight; property Caption: AnsiString read FCaption write SetCaption; property FontColorOver: TColor4 read FFontColorOver write SetFontColorOver; property FontColorDefault: TColor4 read FFontColor write SetFontColor; property FontColorSellected: TColor4 read FFontColorSellected write SetFontColorSellected; property State: TButtonState read FState write SetState; property Sellected: Boolean read FSellected write SetSellected; function MouseOver(): Boolean; function Click(): Boolean; procedure Render(); procedure Update(); end; implementation uses SysUtils, uBox; { TButton } function TButton.Click(): Boolean; begin Result := LeftButton and MouseOver; if Result then State := bsDown else State := bsNone; end; constructor TButton.Create(); var I: Byte; begin P := Point(0, 0); for I := 0 to High(pButton) do pButton[I] := nil; State := bsNone; Sellected := False; for I := 0 to High(pButton) do pResMan.Load(PAnsiChar(AnsiString('Resources\Sprites\Interface\Button' + IntToStr(I) + '.png')), IEngineBaseObject(pButton[I]), TEXTURE_LOAD_DEFAULT_2D); FontColorSellected := Color4(); FontColorDefault := Color4(); FontColorOver := Color4(); end; destructor TButton.Destroy; var I: Byte; begin for I := 0 to High(pButton) do pButton[I] := nil; inherited; end; function TButton.MouseOver: Boolean; begin Result := (MousePos.X > Left) and (MousePos.X < Left + Width) and (MousePos.Y > Top) and (MousePos.Y < Top + Height); end; procedure TButton.Render; procedure RenderButton(B: ITexture; C: TColor4); var W, H, X, Y: Cardinal; begin pRender2D.DrawTexture(B, Point2(Left + P.X, Top + P.Y), Point2(Width, Height)); pFont24.GetTextDimensions(PAnsiChar(Caption), W, H); X := ((Width div 2) - (Integer(W) div 2)) + (Left + P.X); Y := ((Height div 2) - (Integer(H) div 2)) + (Top + P.Y); pFont24.Draw2DSimple(X, Y, PAnsiChar(Caption), C); end; begin if (State <> bsDown) then if MouseOver and not FSellected then State := bsOver else State := bsNone; if (State = bsDown) and not MouseOver then State := bsNone; case State of bsNone: if FSellected then RenderButton(pButton[2], FontColorSellected) else RenderButton(pButton[0], FontColorDefault); bsOver: RenderButton(pButton[1], FontColorOver); bsDown: if FSellected then RenderButton(pButton[2], FontColorSellected) else RenderButton(pButton[1], FontColorOver); end; end; procedure TButton.Update; begin if Click then P := Point(1, 3) else P := Point(0, 0); end; procedure TButton.SetCaption(const Value: AnsiString); begin FCaption := Value; end; procedure TButton.SetFontColor(const Value: TColor4); begin FFontColor := Value; end; procedure TButton.SetHeight(const Value: Integer); begin FHeight := Value; end; procedure TButton.SetLeft(const Value: Integer); begin FLeft := Value; end; procedure TButton.SetSellected(const Value: Boolean); begin FSellected := Value; end; procedure TButton.SetState(const Value: TButtonState); begin FState := Value; end; procedure TButton.SetTop(const Value: Integer); begin FTop := Value; end; procedure TButton.SetWidth(const Value: Integer); begin FWidth := Value; end; procedure TButton.SetFontColorSellected(const Value: TColor4); begin FFontColorSellected := Value; end; procedure TButton.SetFontColorOver(const Value: TColor4); begin FFontColorOver := Value; end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.4 2004.02.03 5:45:42 PM czhower Name changes Rev 1.3 1/25/2004 2:17:54 PM JPMugaas Should work better. Removed one GPF in S/Key. Rev 1.2 1/21/2004 4:03:18 PM JPMugaas InitComponent Rev 1.1 10/19/2003 5:57:20 PM DSiders Added localization comments. Rev 1.0 5/10/2003 10:08:14 PM JPMugaas SKEY SASL mechanism as defined in RFC 2222. Note that this is obsolete and you should use RFC 2444 for new designs. This is only provided for backwards compatibility. } unit IdSASLSKey; interface {$i IdCompilerDefines.inc} uses IdSASLUserPass, IdSASL; { S/KEY SASL mechanism based on RFC 2222. NOte that this is depreciated and S/Key is a trademark of BelCore. This unit is only provided for backwards compatiability with some older systems. New designs should use IdSASLOTP (RFC 2444) which is more flexible and uses a better hash (MD5 and SHA1). } type TIdSASLSKey = class(TIdSASLUserPass) protected procedure InitComponent; override; public function IsReadyToStart: Boolean; override; class function ServiceName: TIdSASLServiceName; override; function StartAuthenticate(const AChallenge, AHost, AProtocolName : String) : String; override; function ContinueAuthenticate(const ALastResponse, AHost, AProtocolName : String): String; override; end; implementation uses IdBaseComponent, IdFIPS, IdGlobal, IdGlobalProtocols, IdOTPCalculator, IdUserPassProvider, SysUtils; const SKEYSERVICENAME = 'SKEY'; {do not localize} { TIdSASLSKey } function TIdSASLSKey.ContinueAuthenticate(const ALastResponse, AHost, AProtocolName : String): String; var LBuf, LSeed : String; LCount : Cardinal; begin LBuf := Trim(ALastResponse); LCount := IndyStrToInt(Fetch(LBuf), 0); LSeed := Fetch(LBuf); Result := TIdOTPCalculator.GenerateSixWordKey('md4', LSeed, GetPassword, LCount); {do not localize} end; procedure TIdSASLSKey.InitComponent; begin inherited InitComponent; //less than 1000 because MD4 is broken and this is depreciated FSecurityLevel := 900; end; function TIdSASLSKey.IsReadyToStart: Boolean; begin Result := not GetFIPSMode; end; class function TIdSASLSKey.ServiceName: TIdSASLServiceName; begin Result := SKEYSERVICENAME; end; function TIdSASLSKey.StartAuthenticate(const AChallenge, AHost, AProtocolName : String): String; begin Result := GetUsername; end; end.
unit InfoRPTSAVEDTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoRPTSAVEDRecord = record PLenderNumber: String[8]; PType: String[6]; PDescription: String[100]; PUserid: String[5]; PReportDate: String[10]; PTitle: String[100]; PDataIncludedIndex: SmallInt; PUsingWhichDateIndex: SmallInt; PSortOrderIndex: SmallInt; PGroupedbyIndex: SmallInt; PReproIndex: SmallInt; POpenClaimsIndex: SmallInt; PStatementDateIndex: SmallInt; PFromDate: String[10]; PToDate: String[10]; PReportFileName: String[12]; PReportProcessed: Boolean; PBeginningWithIndex: SmallInt; PPrintZeroIndex: SmallInt; PPrintNotesIndex: SmallInt; PStmtDateYYYYMM: String[6]; End; TInfoRPTSAVEDBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoRPTSAVEDRecord; function FieldNameToIndex(s:string):integer;override; function FieldType(index:integer):TFieldType;override; end; TEIInfoRPTSAVED = (InfoRPTSAVEDPrimaryKey, InfoRPTSAVEDType, InfoRPTSAVEDDescription); TInfoRPTSAVEDTable = class( TDBISAMTableAU ) private FDFLenderNumber: TStringField; FDFType: TStringField; FDFDescription: TStringField; FDFUserid: TStringField; FDFReportDate: TStringField; FDFTitle: TStringField; FDFDataIncludedIndex: TSmallIntField; FDFUsingWhichDateIndex: TSmallIntField; FDFSortOrderIndex: TSmallIntField; FDFGroupedbyIndex: TSmallIntField; FDFReproIndex: TSmallIntField; FDFOpenClaimsIndex: TSmallIntField; FDFStatementDateIndex: TSmallIntField; FDFFromDate: TStringField; FDFToDate: TStringField; FDFLenderGroup: TBlobField; FDFCompanyString: TBlobField; FDFLenderString: TBlobField; FDFPrefixString: TBlobField; FDFPolicyString: TBlobField; FDFClaimString: TBlobField; FDFLossCodeString: TBlobField; FDFTranTypeString: TBlobField; FDFSettlementMethodString: TBlobField; FDFAdjusterString: TBlobField; FDFClaimTrackString: TBlobField; FDFTranTrackString: TBlobField; FDFTranStatusString: TBlobField; FDFReportFileName: TStringField; FDFReportProcessed: TBooleanField; FDFBeginningWithIndex: TSmallIntField; FDFPrintZeroIndex: TSmallIntField; FDFPrintNotesIndex: TSmallIntField; FDFStmtDateYYYYMM: TStringField; procedure SetPLenderNumber(const Value: String); function GetPLenderNumber:String; procedure SetPType(const Value: String); function GetPType:String; procedure SetPDescription(const Value: String); function GetPDescription:String; procedure SetPUserid(const Value: String); function GetPUserid:String; procedure SetPReportDate(const Value: String); function GetPReportDate:String; procedure SetPTitle(const Value: String); function GetPTitle:String; procedure SetPDataIncludedIndex(const Value: SmallInt); function GetPDataIncludedIndex:SmallInt; procedure SetPUsingWhichDateIndex(const Value: SmallInt); function GetPUsingWhichDateIndex:SmallInt; procedure SetPSortOrderIndex(const Value: SmallInt); function GetPSortOrderIndex:SmallInt; procedure SetPGroupedbyIndex(const Value: SmallInt); function GetPGroupedbyIndex:SmallInt; procedure SetPReproIndex(const Value: SmallInt); function GetPReproIndex:SmallInt; procedure SetPOpenClaimsIndex(const Value: SmallInt); function GetPOpenClaimsIndex:SmallInt; procedure SetPStatementDateIndex(const Value: SmallInt); function GetPStatementDateIndex:SmallInt; procedure SetPFromDate(const Value: String); function GetPFromDate:String; procedure SetPToDate(const Value: String); function GetPToDate:String; procedure SetPReportFileName(const Value: String); function GetPReportFileName:String; procedure SetPReportProcessed(const Value: Boolean); function GetPReportProcessed:Boolean; procedure SetPBeginningWithIndex(const Value: SmallInt); function GetPBeginningWithIndex:SmallInt; procedure SetPPrintZeroIndex(const Value: SmallInt); function GetPPrintZeroIndex:SmallInt; procedure SetPPrintNotesIndex(const Value: SmallInt); function GetPPrintNotesIndex:SmallInt; procedure SetPStmtDateYYYYMM(const Value: String); function GetPStmtDateYYYYMM:String; procedure SetEnumIndex(Value: TEIInfoRPTSAVED); function GetEnumIndex: TEIInfoRPTSAVED; protected procedure CreateFields; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoRPTSAVEDRecord; procedure StoreDataBuffer(ABuffer:TInfoRPTSAVEDRecord); property DFLenderNumber: TStringField read FDFLenderNumber; property DFType: TStringField read FDFType; property DFDescription: TStringField read FDFDescription; property DFUserid: TStringField read FDFUserid; property DFReportDate: TStringField read FDFReportDate; property DFTitle: TStringField read FDFTitle; property DFDataIncludedIndex: TSmallIntField read FDFDataIncludedIndex; property DFUsingWhichDateIndex: TSmallIntField read FDFUsingWhichDateIndex; property DFSortOrderIndex: TSmallIntField read FDFSortOrderIndex; property DFGroupedbyIndex: TSmallIntField read FDFGroupedbyIndex; property DFReproIndex: TSmallIntField read FDFReproIndex; property DFOpenClaimsIndex: TSmallIntField read FDFOpenClaimsIndex; property DFStatementDateIndex: TSmallIntField read FDFStatementDateIndex; property DFFromDate: TStringField read FDFFromDate; property DFToDate: TStringField read FDFToDate; property DFLenderGroup: TBlobField read FDFLenderGroup; property DFCompanyString: TBlobField read FDFCompanyString; property DFLenderString: TBlobField read FDFLenderString; property DFPrefixString: TBlobField read FDFPrefixString; property DFPolicyString: TBlobField read FDFPolicyString; property DFClaimString: TBlobField read FDFClaimString; property DFLossCodeString: TBlobField read FDFLossCodeString; property DFTranTypeString: TBlobField read FDFTranTypeString; property DFSettlementMethodString: TBlobField read FDFSettlementMethodString; property DFAdjusterString: TBlobField read FDFAdjusterString; property DFClaimTrackString: TBlobField read FDFClaimTrackString; property DFTranTrackString: TBlobField read FDFTranTrackString; property DFTranStatusString: TBlobField read FDFTranStatusString; property DFReportFileName: TStringField read FDFReportFileName; property DFReportProcessed: TBooleanField read FDFReportProcessed; property DFBeginningWithIndex: TSmallIntField read FDFBeginningWithIndex; property DFPrintZeroIndex: TSmallIntField read FDFPrintZeroIndex; property DFPrintNotesIndex: TSmallIntField read FDFPrintNotesIndex; property DFStmtDateYYYYMM: TStringField read FDFStmtDateYYYYMM; property PLenderNumber: String read GetPLenderNumber write SetPLenderNumber; property PType: String read GetPType write SetPType; property PDescription: String read GetPDescription write SetPDescription; property PUserid: String read GetPUserid write SetPUserid; property PReportDate: String read GetPReportDate write SetPReportDate; property PTitle: String read GetPTitle write SetPTitle; property PDataIncludedIndex: SmallInt read GetPDataIncludedIndex write SetPDataIncludedIndex; property PUsingWhichDateIndex: SmallInt read GetPUsingWhichDateIndex write SetPUsingWhichDateIndex; property PSortOrderIndex: SmallInt read GetPSortOrderIndex write SetPSortOrderIndex; property PGroupedbyIndex: SmallInt read GetPGroupedbyIndex write SetPGroupedbyIndex; property PReproIndex: SmallInt read GetPReproIndex write SetPReproIndex; property POpenClaimsIndex: SmallInt read GetPOpenClaimsIndex write SetPOpenClaimsIndex; property PStatementDateIndex: SmallInt read GetPStatementDateIndex write SetPStatementDateIndex; property PFromDate: String read GetPFromDate write SetPFromDate; property PToDate: String read GetPToDate write SetPToDate; property PReportFileName: String read GetPReportFileName write SetPReportFileName; property PReportProcessed: Boolean read GetPReportProcessed write SetPReportProcessed; property PBeginningWithIndex: SmallInt read GetPBeginningWithIndex write SetPBeginningWithIndex; property PPrintZeroIndex: SmallInt read GetPPrintZeroIndex write SetPPrintZeroIndex; property PPrintNotesIndex: SmallInt read GetPPrintNotesIndex write SetPPrintNotesIndex; property PStmtDateYYYYMM: String read GetPStmtDateYYYYMM write SetPStmtDateYYYYMM; published property Active write SetActive; property EnumIndex: TEIInfoRPTSAVED read GetEnumIndex write SetEnumIndex; end; { TInfoRPTSAVEDTable } procedure Register; implementation procedure TInfoRPTSAVEDTable.CreateFields; begin FDFLenderNumber := CreateField( 'LenderNumber' ) as TStringField; FDFType := CreateField( 'Type' ) as TStringField; FDFDescription := CreateField( 'Description' ) as TStringField; FDFUserid := CreateField( 'Userid' ) as TStringField; FDFReportDate := CreateField( 'ReportDate' ) as TStringField; FDFTitle := CreateField( 'Title' ) as TStringField; FDFDataIncludedIndex := CreateField( 'DataIncludedIndex' ) as TSmallIntField; FDFUsingWhichDateIndex := CreateField( 'UsingWhichDateIndex' ) as TSmallIntField; FDFSortOrderIndex := CreateField( 'SortOrderIndex' ) as TSmallIntField; FDFGroupedbyIndex := CreateField( 'GroupedbyIndex' ) as TSmallIntField; FDFReproIndex := CreateField( 'ReproIndex' ) as TSmallIntField; FDFOpenClaimsIndex := CreateField( 'OpenClaimsIndex' ) as TSmallIntField; FDFStatementDateIndex := CreateField( 'StatementDateIndex' ) as TSmallIntField; FDFFromDate := CreateField( 'FromDate' ) as TStringField; FDFToDate := CreateField( 'ToDate' ) as TStringField; FDFLenderGroup := CreateField( 'LenderGroup' ) as TBlobField; FDFCompanyString := CreateField( 'CompanyString' ) as TBlobField; FDFLenderString := CreateField( 'LenderString' ) as TBlobField; FDFPrefixString := CreateField( 'PrefixString' ) as TBlobField; FDFPolicyString := CreateField( 'PolicyString' ) as TBlobField; FDFClaimString := CreateField( 'ClaimString' ) as TBlobField; FDFLossCodeString := CreateField( 'LossCodeString' ) as TBlobField; FDFTranTypeString := CreateField( 'TranTypeString' ) as TBlobField; FDFSettlementMethodString := CreateField( 'SettlementMethodString' ) as TBlobField; FDFAdjusterString := CreateField( 'AdjusterString' ) as TBlobField; FDFClaimTrackString := CreateField( 'ClaimTrackString' ) as TBlobField; FDFTranTrackString := CreateField( 'TranTrackString' ) as TBlobField; FDFTranStatusString := CreateField( 'TranStatusString' ) as TBlobField; FDFReportFileName := CreateField( 'ReportFileName' ) as TStringField; FDFReportProcessed := CreateField( 'ReportProcessed' ) as TBooleanField; FDFBeginningWithIndex := CreateField( 'BeginningWithIndex' ) as TSmallIntField; FDFPrintZeroIndex := CreateField( 'PrintZeroIndex' ) as TSmallIntField; FDFPrintNotesIndex := CreateField( 'PrintNotesIndex' ) as TSmallIntField; FDFStmtDateYYYYMM := CreateField( 'StmtDateYYYYMM' ) as TStringField; end; { TInfoRPTSAVEDTable.CreateFields } procedure TInfoRPTSAVEDTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoRPTSAVEDTable.SetActive } procedure TInfoRPTSAVEDTable.SetPLenderNumber(const Value: String); begin DFLenderNumber.Value := Value; end; function TInfoRPTSAVEDTable.GetPLenderNumber:String; begin result := DFLenderNumber.Value; end; procedure TInfoRPTSAVEDTable.SetPType(const Value: String); begin DFType.Value := Value; end; function TInfoRPTSAVEDTable.GetPType:String; begin result := DFType.Value; end; procedure TInfoRPTSAVEDTable.SetPDescription(const Value: String); begin DFDescription.Value := Value; end; function TInfoRPTSAVEDTable.GetPDescription:String; begin result := DFDescription.Value; end; procedure TInfoRPTSAVEDTable.SetPUserid(const Value: String); begin DFUserid.Value := Value; end; function TInfoRPTSAVEDTable.GetPUserid:String; begin result := DFUserid.Value; end; procedure TInfoRPTSAVEDTable.SetPReportDate(const Value: String); begin DFReportDate.Value := Value; end; function TInfoRPTSAVEDTable.GetPReportDate:String; begin result := DFReportDate.Value; end; procedure TInfoRPTSAVEDTable.SetPTitle(const Value: String); begin DFTitle.Value := Value; end; function TInfoRPTSAVEDTable.GetPTitle:String; begin result := DFTitle.Value; end; procedure TInfoRPTSAVEDTable.SetPDataIncludedIndex(const Value: SmallInt); begin DFDataIncludedIndex.Value := Value; end; function TInfoRPTSAVEDTable.GetPDataIncludedIndex:SmallInt; begin result := DFDataIncludedIndex.Value; end; procedure TInfoRPTSAVEDTable.SetPUsingWhichDateIndex(const Value: SmallInt); begin DFUsingWhichDateIndex.Value := Value; end; function TInfoRPTSAVEDTable.GetPUsingWhichDateIndex:SmallInt; begin result := DFUsingWhichDateIndex.Value; end; procedure TInfoRPTSAVEDTable.SetPSortOrderIndex(const Value: SmallInt); begin DFSortOrderIndex.Value := Value; end; function TInfoRPTSAVEDTable.GetPSortOrderIndex:SmallInt; begin result := DFSortOrderIndex.Value; end; procedure TInfoRPTSAVEDTable.SetPGroupedbyIndex(const Value: SmallInt); begin DFGroupedbyIndex.Value := Value; end; function TInfoRPTSAVEDTable.GetPGroupedbyIndex:SmallInt; begin result := DFGroupedbyIndex.Value; end; procedure TInfoRPTSAVEDTable.SetPReproIndex(const Value: SmallInt); begin DFReproIndex.Value := Value; end; function TInfoRPTSAVEDTable.GetPReproIndex:SmallInt; begin result := DFReproIndex.Value; end; procedure TInfoRPTSAVEDTable.SetPOpenClaimsIndex(const Value: SmallInt); begin DFOpenClaimsIndex.Value := Value; end; function TInfoRPTSAVEDTable.GetPOpenClaimsIndex:SmallInt; begin result := DFOpenClaimsIndex.Value; end; procedure TInfoRPTSAVEDTable.SetPStatementDateIndex(const Value: SmallInt); begin DFStatementDateIndex.Value := Value; end; function TInfoRPTSAVEDTable.GetPStatementDateIndex:SmallInt; begin result := DFStatementDateIndex.Value; end; procedure TInfoRPTSAVEDTable.SetPFromDate(const Value: String); begin DFFromDate.Value := Value; end; function TInfoRPTSAVEDTable.GetPFromDate:String; begin result := DFFromDate.Value; end; procedure TInfoRPTSAVEDTable.SetPToDate(const Value: String); begin DFToDate.Value := Value; end; function TInfoRPTSAVEDTable.GetPToDate:String; begin result := DFToDate.Value; end; procedure TInfoRPTSAVEDTable.SetPReportFileName(const Value: String); begin DFReportFileName.Value := Value; end; function TInfoRPTSAVEDTable.GetPReportFileName:String; begin result := DFReportFileName.Value; end; procedure TInfoRPTSAVEDTable.SetPReportProcessed(const Value: Boolean); begin DFReportProcessed.Value := Value; end; function TInfoRPTSAVEDTable.GetPReportProcessed:Boolean; begin result := DFReportProcessed.Value; end; procedure TInfoRPTSAVEDTable.SetPBeginningWithIndex(const Value: SmallInt); begin DFBeginningWithIndex.Value := Value; end; function TInfoRPTSAVEDTable.GetPBeginningWithIndex:SmallInt; begin result := DFBeginningWithIndex.Value; end; procedure TInfoRPTSAVEDTable.SetPPrintZeroIndex(const Value: SmallInt); begin DFPrintZeroIndex.Value := Value; end; function TInfoRPTSAVEDTable.GetPPrintZeroIndex:SmallInt; begin result := DFPrintZeroIndex.Value; end; procedure TInfoRPTSAVEDTable.SetPPrintNotesIndex(const Value: SmallInt); begin DFPrintNotesIndex.Value := Value; end; function TInfoRPTSAVEDTable.GetPPrintNotesIndex:SmallInt; begin result := DFPrintNotesIndex.Value; end; procedure TInfoRPTSAVEDTable.SetPStmtDateYYYYMM(const Value: String); begin DFStmtDateYYYYMM.Value := Value; end; function TInfoRPTSAVEDTable.GetPStmtDateYYYYMM:String; begin result := DFStmtDateYYYYMM.Value; end; procedure TInfoRPTSAVEDTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('LenderNumber, String, 8, N'); Add('Type, String, 6, N'); Add('Description, String, 100, N'); Add('Userid, String, 5, N'); Add('ReportDate, String, 10, N'); Add('Title, String, 100, N'); Add('DataIncludedIndex, SmallInt, 0, N'); Add('UsingWhichDateIndex, SmallInt, 0, N'); Add('SortOrderIndex, SmallInt, 0, N'); Add('GroupedbyIndex, SmallInt, 0, N'); Add('ReproIndex, SmallInt, 0, N'); Add('OpenClaimsIndex, SmallInt, 0, N'); Add('StatementDateIndex, SmallInt, 0, N'); Add('FromDate, String, 10, N'); Add('ToDate, String, 10, N'); Add('LenderGroup, Blob, 0, N'); Add('CompanyString, Blob, 0, N'); Add('LenderString, Blob, 0, N'); Add('PrefixString, Blob, 0, N'); Add('PolicyString, Blob, 0, N'); Add('ClaimString, Blob, 0, N'); Add('LossCodeString, Blob, 0, N'); Add('TranTypeString, Blob, 0, N'); Add('SettlementMethodString, Blob, 0, N'); Add('AdjusterString, Blob, 0, N'); Add('ClaimTrackString, Blob, 0, N'); Add('TranTrackString, Blob, 0, N'); Add('TranStatusString, Blob, 0, N'); Add('ReportFileName, String, 12, N'); Add('ReportProcessed, Boolean, 0, N'); Add('BeginningWithIndex, SmallInt, 0, N'); Add('PrintZeroIndex, SmallInt, 0, N'); Add('PrintNotesIndex, SmallInt, 0, N'); Add('StmtDateYYYYMM, String, 6, N'); end; end; procedure TInfoRPTSAVEDTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, LenderNumber;Type;Description, Y, Y, N, N'); Add('Type, Type;LenderNumber, N, N, N, N'); Add('Description, Type;Description, N, N, N, N'); end; end; procedure TInfoRPTSAVEDTable.SetEnumIndex(Value: TEIInfoRPTSAVED); begin case Value of InfoRPTSAVEDPrimaryKey : IndexName := ''; InfoRPTSAVEDType : IndexName := 'Type'; InfoRPTSAVEDDescription : IndexName := 'Description'; end; end; function TInfoRPTSAVEDTable.GetDataBuffer:TInfoRPTSAVEDRecord; var buf: TInfoRPTSAVEDRecord; begin fillchar(buf, sizeof(buf), 0); buf.PLenderNumber := DFLenderNumber.Value; buf.PType := DFType.Value; buf.PDescription := DFDescription.Value; buf.PUserid := DFUserid.Value; buf.PReportDate := DFReportDate.Value; buf.PTitle := DFTitle.Value; buf.PDataIncludedIndex := DFDataIncludedIndex.Value; buf.PUsingWhichDateIndex := DFUsingWhichDateIndex.Value; buf.PSortOrderIndex := DFSortOrderIndex.Value; buf.PGroupedbyIndex := DFGroupedbyIndex.Value; buf.PReproIndex := DFReproIndex.Value; buf.POpenClaimsIndex := DFOpenClaimsIndex.Value; buf.PStatementDateIndex := DFStatementDateIndex.Value; buf.PFromDate := DFFromDate.Value; buf.PToDate := DFToDate.Value; buf.PReportFileName := DFReportFileName.Value; buf.PReportProcessed := DFReportProcessed.Value; buf.PBeginningWithIndex := DFBeginningWithIndex.Value; buf.PPrintZeroIndex := DFPrintZeroIndex.Value; buf.PPrintNotesIndex := DFPrintNotesIndex.Value; buf.PStmtDateYYYYMM := DFStmtDateYYYYMM.Value; result := buf; end; procedure TInfoRPTSAVEDTable.StoreDataBuffer(ABuffer:TInfoRPTSAVEDRecord); begin DFLenderNumber.Value := ABuffer.PLenderNumber; DFType.Value := ABuffer.PType; DFDescription.Value := ABuffer.PDescription; DFUserid.Value := ABuffer.PUserid; DFReportDate.Value := ABuffer.PReportDate; DFTitle.Value := ABuffer.PTitle; DFDataIncludedIndex.Value := ABuffer.PDataIncludedIndex; DFUsingWhichDateIndex.Value := ABuffer.PUsingWhichDateIndex; DFSortOrderIndex.Value := ABuffer.PSortOrderIndex; DFGroupedbyIndex.Value := ABuffer.PGroupedbyIndex; DFReproIndex.Value := ABuffer.PReproIndex; DFOpenClaimsIndex.Value := ABuffer.POpenClaimsIndex; DFStatementDateIndex.Value := ABuffer.PStatementDateIndex; DFFromDate.Value := ABuffer.PFromDate; DFToDate.Value := ABuffer.PToDate; DFReportFileName.Value := ABuffer.PReportFileName; DFReportProcessed.Value := ABuffer.PReportProcessed; DFBeginningWithIndex.Value := ABuffer.PBeginningWithIndex; DFPrintZeroIndex.Value := ABuffer.PPrintZeroIndex; DFPrintNotesIndex.Value := ABuffer.PPrintNotesIndex; DFStmtDateYYYYMM.Value := ABuffer.PStmtDateYYYYMM; end; function TInfoRPTSAVEDTable.GetEnumIndex: TEIInfoRPTSAVED; var iname : string; begin iname := uppercase(indexname); if iname = '' then result := InfoRPTSAVEDPrimaryKey; if iname = 'TYPE' then result := InfoRPTSAVEDType; if iname = 'DESCRIPTION' then result := InfoRPTSAVEDDescription; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoRPTSAVEDTable, TInfoRPTSAVEDBuffer ] ); end; { Register } function TInfoRPTSAVEDBuffer.FieldNameToIndex(s:string):integer; const flist:array[1..21] of string = ('LENDERNUMBER','TYPE','DESCRIPTION','USERID','REPORTDATE','TITLE' ,'DATAINCLUDEDINDEX','USINGWHICHDATEINDEX','SORTORDERINDEX','GROUPEDBYINDEX','REPROINDEX' ,'OPENCLAIMSINDEX','STATEMENTDATEINDEX','FROMDATE','TODATE','REPORTFILENAME','REPORTPROCESSED','BEGINNINGWITHINDEX' ,'PRINTZEROINDEX','PRINTNOTESINDEX','STMTDATEYYYYMM' ); var x : integer; begin s := uppercase(s); x := 1; while (x <= 21) and (flist[x] <> s) do inc(x); if x <= 21 then result := x else result := 0; end; function TInfoRPTSAVEDBuffer.FieldType(index:integer):TFieldType; begin result := ftUnknown; case index of 1 : result := ftString; 2 : result := ftString; 3 : result := ftString; 4 : result := ftString; 5 : result := ftString; 6 : result := ftString; 7 : result := ftSmallInt; 8 : result := ftSmallInt; 9 : result := ftSmallInt; 10 : result := ftSmallInt; 11 : result := ftSmallInt; 12 : result := ftSmallInt; 13 : result := ftSmallInt; 14 : result := ftString; 15 : result := ftString; 16 : result := ftString; 17 : result := ftBoolean; 18 : result := ftSmallInt; 19 : result := ftSmallInt; 20 : result := ftSmallInt; 21 : result := ftString; end; end; function TInfoRPTSAVEDBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PLenderNumber; 2 : result := @Data.PType; 3 : result := @Data.PDescription; 4 : result := @Data.PUserid; 5 : result := @Data.PReportDate; 6 : result := @Data.PTitle; 7 : result := @Data.PDataIncludedIndex; 8 : result := @Data.PUsingWhichDateIndex; 9 : result := @Data.PSortOrderIndex; 10 : result := @Data.PGroupedbyIndex; 11 : result := @Data.PReproIndex; 12 : result := @Data.POpenClaimsIndex; 13 : result := @Data.PStatementDateIndex; 14 : result := @Data.PFromDate; 15 : result := @Data.PToDate; 16 : result := @Data.PReportFileName; 17 : result := @Data.PReportProcessed; 18 : result := @Data.PBeginningWithIndex; 19 : result := @Data.PPrintZeroIndex; 20 : result := @Data.PPrintNotesIndex; 21 : result := @Data.PStmtDateYYYYMM; end; end; end.
unit Headquarters; interface uses Protocol, Kernel, ResearchCenter; type TMetaHeadquarterBlock = class( TMetaResearchCenter ) public constructor Create( anId : string; aCapacities : array of TFluidValue; anInventionKind : string; aBlockClass : CBlock ); end; THeadquarterBlock = class( TResearchCenter ) public procedure AutoConnect( loaded : boolean ); override; end; TMetaMainHeadquarter = class( TMetaHeadquarterBlock ) public constructor Create( anId : string; aCapacities : array of TFluidValue; anInventionKind : string; aBlockClass : CBlock ); end; TMainHeadquarter = class( THeadquarterBlock ) private fAdvertisement : TInputData; fLegalServ : TInputData; fCompServ : TInputData; public function GetStatusText( kind : TStatusKind; ToTycoon : TTycoon ) : string; override; end; TMetaAreaHeadQuarter = class(TMetaHeadquarterBlock) public constructor Create( anId : string; aCapacities : array of TFluidValue; anInventionKind : string; aSoftMax : TFluidValue; aLegalMax : TFluidValue; aBlockClass : CBlock ); end; TAreaHeadquarter = class(THeadquarterBlock) end; TMetaPublicAffairsHeadquarter = class( TMetaHeadquarterBlock ) public constructor Create( anId : string; aCapacities : array of TFluidValue; anInventionKind : string; aMaxHits : TFluidValue; aBlockClass : CBlock ); end; TPublicAffairsHeadquarter = class( THeadquarterBlock ) protected function Evaluate : TEvaluationResult; override; public function GetStatusText( kind : TStatusKind; ToTycoon : TTycoon ) : string; override; private fPrestigeBoost : TPrestige; end; procedure RegisterBackup; implementation uses SysUtils, BackupInterfaces, ClassStorage, StdFluids, SimHints, Inventions, MathUtils; // TMetaHeadquarterBlock constructor TMetaHeadquarterBlock.Create( anId : string; aCapacities : array of TFluidValue; anInventionKind : string; aBlockClass : CBlock ); begin inherited Create( anId, aCapacities, anInventionKind, aBlockClass ); end; // THeadquarterBlock procedure THeadquarterBlock.AutoConnect( loaded : boolean ); var i : integer; Inv : TInvention; begin inherited; if not loaded then for i := 0 to pred(TMetaHeadquarterBlock(MetaBlock).InventionCount) do begin Inv := TMetaHeadquarterBlock(MetaBlock).Inventions[i]; if Inv.Basic and not Facility.Company.HasInvention[Inv.NumId] and Inv.Enabled(Facility.Company) then ResearchInvention(Inv, 0); end; end; // TMetaMainHeadquarter const MaxAd = 1000000; MaxLegalServ = 10000; MaxCompServ = 10000; constructor TMetaMainHeadquarter.Create( anId : string; aCapacities : array of TFluidValue; anInventionKind : string; aBlockClass : CBlock ); var Sample : TMainHeadquarter; begin inherited Create( anId, aCapacities, anInventionKind, aBlockClass ); Sample := nil; MetaInputs.Insert( TMetaInput.Create( tidGate_Advertisement, inputZero, InputData(MaxAd, 100), inputZero, MaxUpgrade*MaxAd, TPullInput, TMetaFluid(TheClassStorage.ClassById[tidClassFamily_Fluids, tidFluid_Advertisement]), 5, mglBasic, [mgoptCacheable, mgoptEditable], sizeof(Sample.fAdvertisement), Sample.Offset(Sample.fAdvertisement))); MetaInputs.Insert( TMetaInput.Create( tidGate_LegalServ, inputZero, InputData(MaxLegalServ, 100), inputZero, MaxUpgrade*MaxLegalServ, TPullInput, TMetaFluid(TheClassStorage.ClassById[tidClassFamily_Fluids, tidFluid_LegalServ]), 5, mglBasic, [mgoptCacheable, mgoptEditable], sizeof(Sample.fLegalServ), Sample.Offset(Sample.fLegalServ))); MetaInputs.Insert( TMetaInput.Create( tidGate_CompServ, inputZero, InputData(MaxCompServ, 100), inputZero, MaxUpgrade*MaxCompServ, TPullInput, TMetaFluid(TheClassStorage.ClassById[tidClassFamily_Fluids, tidFluid_CompServ]), 5, mglBasic, [mgoptCacheable, mgoptEditable], sizeof(Sample.fCompServ), Sample.Offset(Sample.fCompServ))); end; function TMainHeadquarter.GetStatusText(kind : TStatusKind; ToTycoon : TTycoon) : string; begin result := inherited GetStatusText(kind, ToTycoon); case kind of sttSecondary : result := result + ' ' + SimHints.GetHintText(mtidImplementationCost.Values[ToTycoon.Language], [MathUtils.FormatMoney(Facility.Company.ResearchCost)]); end; end; // TMetaAreaHeadQuarter constructor TMetaAreaHeadQuarter.Create( anId : string; aCapacities : array of TFluidValue; anInventionKind : string; aSoftMax : TFluidValue; aLegalMax : TFluidValue; aBlockClass : CBlock ); begin inherited Create(anId, aCapacities, anInventionKind, aBlockClass); RegisterCompanyInput(tidFluid_CompServ, aSoftMax, false); RegisterCompanyInput(tidFluid_LegalServ, aLegalMax, false); end; // TMetaPublicAffairsHeadquarter constructor TMetaPublicAffairsHeadquarter.Create( anId : string; aCapacities : array of TFluidValue; anInventionKind : string; aMaxHits : TFluidValue; aBlockClass : CBlock ); begin inherited Create( anId, aCapacities, anInventionKind, aBlockClass ); RegisterCompanyInput(tidFluid_Advertisement, aMaxHits, true); end; // TPublicAffairsHeadquarter function TPublicAffairsHeadquarter.Evaluate : TEvaluationResult; var AdvInput : PCompanyInputData; begin result := inherited Evaluate; AdvInput := CompanyInputs[0]; fPrestigeBoost := AdvInput.Q*AdvInput.K/10000; AdvInput.Max := TMetaCompanyInput(MetaBlock.CompanyInputs[0]).Max; if (Facility.Company <> nil) and (Facility.Company.Owner <> nil) then with Facility.Company.Owner do CurrFacPrestige := CurrFacPrestige + fPrestigeBoost; end; function TPublicAffairsHeadquarter.GetStatusText( kind : TStatusKind; ToTycoon : TTycoon ) : string; begin result := inherited GetStatusText( kind, ToTycoon ); case kind of sttSecondary : result := result + ' ' + //IntToStr(round(fPrestigeBoost)) + ' prestige points from publicity.'; SimHints.GetHintText( mtidCiviHQPrest.Values[ToTycoon.Language], [round(fPrestigeBoost)] ); end; end; // RegisterBackup procedure RegisterBackup; begin BackupInterfaces.RegisterClass( THeadquarterBlock ); BackupInterfaces.RegisterClass( TMainHeadquarter ); BackupInterfaces.RegisterClass( TPublicAffairsHeadquarter ); end; end.
unit tests.generics.queue; {$mode objfpc} interface uses fpcunit, testregistry, Classes, SysUtils, Generics.Defaults, Generics.Collections; Type TMySimpleQueue = Class(Specialize TQueue<String>); {$IFDEF FPC} EList = EListError; {$ENDIF} { TTestSimpleQueue } TTestSimpleQueue = Class(TTestCase) Private FQueue : TMySimpleQueue; FnotifyMessage : String; FCurrentValueNotify : Integer; FExpectValues : Array of String; FExpectValueAction: Array of TCollectionNotification; procedure DoAdd(aCount: Integer; aOffset: Integer=0); procedure DoAdd2; Procedure DoneExpectValues; procedure DoGetValue(Match: String; ExceptionClass: TClass=nil); procedure DoValueNotify(ASender: TObject; {$ifdef fpc}constref{$else}const{$endif} AItem: String; AAction: TCollectionNotification); Public Procedure SetExpectValues(aMessage : string; AKeys : Array of String; AActions : Array of TCollectionNotification; DoReverse : Boolean = False); Procedure SetUp; override; Procedure TearDown; override; Property Queue : TMySimpleQueue Read FQueue; Published Procedure TestEmpty; Procedure TestAdd; Procedure TestClear; Procedure TestGetValue; Procedure TestPeek; Procedure TestDequeue; Procedure TestToArray; Procedure TestEnumerator; procedure TestValueNotification; procedure TestValueNotificationDelete; end; { TMyObject } TMyObject = Class(TObject) Private fOnDestroy : TNotifyEvent; FID : Integer; public Constructor Create(aID : Integer; aOnDestroy : TNotifyEvent); destructor destroy; override; Property ID : Integer Read FID; end; TSingleObjectQueue = Class(Specialize TObjectQueue<TMyObject>); { TTestSingleObjectQueue } TTestSingleObjectQueue = Class(TTestCase) private FOQueue: TSingleObjectQueue; FList : TFPList; procedure DoAdd(aID: Integer); procedure DoDestroy(Sender: TObject); Public Procedure SetUp; override; Procedure TearDown; override; Property Queue : TSingleObjectQueue Read FOQueue; Published Procedure TestEmpty; Procedure TestFreeOnDequeue; Procedure TestNoFreeOnDeQueue; end; implementation { TTestSingleObjectQueue } procedure TTestSingleObjectQueue.SetUp; begin FOQueue:=TSingleObjectQueue.Create(True); FList:=TFPList.Create; inherited SetUp; end; procedure TTestSingleObjectQueue.TearDown; begin FreeAndNil(FOQueue); FreeAndNil(FList); inherited TearDown; end; procedure TTestSingleObjectQueue.TestEmpty; begin AssertNotNull('Have object',Queue); AssertEquals('Have empty object',0,Queue.Count); end; procedure TTestSingleObjectQueue.DoAdd(aID : Integer); Var O : TMyObject; begin O:=TMyObject.Create(aID,@DoDestroy); FOQueue.EnQueue(O); FList.Add(O); end; procedure TTestSingleObjectQueue.DoDestroy(Sender: TObject); Var I : Integer; begin I:=FList.IndexOf(Sender); AssertTrue('Have object in Queue',I<>-1); FList.Delete(I); end; procedure TTestSingleObjectQueue.TestFreeOnDeQueue; begin DoAdd(1); AssertEquals('Have obj',1,FList.Count); Queue.Dequeue; AssertEquals('Have no obj',0,FList.Count); end; procedure TTestSingleObjectQueue.TestNoFreeOnDeQueue; begin Queue.OwnsObjects:=False; DoAdd(1); AssertEquals('Have obj',1,FList.Count); Queue.DeQueue; AssertEquals('Have obj',1,FList.Count); end; { TMyObject } constructor TMyObject.Create(aID: Integer; aOnDestroy: TNotifyEvent); begin FOnDestroy:=aOnDestroy; FID:=AID; end; destructor TMyObject.destroy; begin if Assigned(FOnDestroy) then FOnDestroy(Self); inherited destroy; end; { TTestSimpleQueue } procedure TTestSimpleQueue.SetUp; begin inherited SetUp; FQueue:=TMySimpleQueue.Create; FCurrentValueNotify:=0; FExpectValues:=[]; FExpectValueAction:=[]; end; procedure TTestSimpleQueue.TearDown; begin // So we don't get clear messages FQueue.OnNotify:=Nil; FreeAndNil(FQueue); inherited TearDown; end; procedure TTestSimpleQueue.TestEmpty; begin AssertNotNull('Have dictionary',Queue); AssertEquals('empty dictionary',0,Queue.Count); end; procedure TTestSimpleQueue.DoAdd(aCount : Integer; aOffset : Integer=0); Var I : Integer; begin if aOffset=-1 then aOffset:=Queue.Count; For I:=aOffset+1 to aOffset+aCount do Queue.EnQueue(IntToStr(i)); end; procedure TTestSimpleQueue.TestAdd; begin DoAdd(1); AssertEquals('Count OK',1,Queue.Count); DoAdd(1,1); AssertEquals('Count OK',2,Queue.Count); end; procedure TTestSimpleQueue.TestClear; begin DoAdd(3); AssertEquals('Count OK',3,Queue.Count); Queue.Clear; AssertEquals('Count after clear OK',0,Queue.Count); end; procedure TTestSimpleQueue.DoGetValue(Match: String; ExceptionClass: TClass); Var EC : TClass; A,EM : String; begin EC:=Nil; try A:=Queue.DeQueue; except On E : Exception do begin EC:=E.ClassType; EM:=E.Message; end end; if ExceptionClass=Nil then begin if EC<>Nil then Fail('Got exception '+EC.ClassName+' with message: '+EM); AssertEquals('Value is correct',Match,A) end else begin if EC=Nil then Fail('Expected exception '+ExceptionClass.ClassName+' but got none'); if EC<>ExceptionClass then Fail('Expected exception class '+ExceptionClass.ClassName+' but got '+EC.ClassName+' with message '+EM); end; end; procedure TTestSimpleQueue.DoValueNotify(ASender: TObject; {$ifdef fpc}constref{$else}const{$endif} AItem: String; AAction: TCollectionNotification); begin // Writeln(FnotifyMessage+' value Notification',FCurrentValueNotify); AssertSame(FnotifyMessage+' value Correct sender', FQueue,aSender); if (FCurrentValueNotify>=Length(FExpectValues)) then Fail(FnotifyMessage+' Too many value notificiations'); AssertEquals(FnotifyMessage+' Notification value no '+IntToStr(FCurrentValueNotify),FExpectValues[FCurrentValueNotify],aItem); Inc(FCurrentValueNotify); end; procedure TTestSimpleQueue.SetExpectValues(aMessage: string; AKeys: array of String; AActions: array of TCollectionNotification; DoReverse: Boolean); Var I,L : integer; begin FnotifyMessage:=aMessage; FCurrentValueNotify:=0; L:=Length(aKeys); AssertEquals('SetExpectValues: Lengths arrays equal',l,Length(aActions)); SetLength(FExpectValues,L); SetLength(FExpectValueAction,L); Dec(L); if DoReverse then For I:=0 to L do begin FExpectValues[L-i]:=AKeys[i]; FExpectValueAction[L-i]:=AActions[I]; end else For I:=0 to L do begin FExpectValues[i]:=AKeys[i]; FExpectValueAction[i]:=AActions[I]; end; end; procedure TTestSimpleQueue.TestGetValue; Var I : integer; begin DoAdd(3); For I:=1 to 3 do DoGetValue(IntToStr(I)); DoGetValue('4',EArgumentOutOfRangeException); end; procedure TTestSimpleQueue.TestPeek; Var I : integer; begin DoAdd(3); For I:=1 to 3 do begin AssertEquals('Peek ',IntToStr(I),FQueue.Peek); DoGetValue(IntToStr(I)); end; end; procedure TTestSimpleQueue.DoAdd2; begin Queue.Enqueue('A new 2'); end; procedure TTestSimpleQueue.DoneExpectValues; begin AssertEquals(FnotifyMessage+' Expected number of values seen',Length(FExpectValues),FCurrentValueNotify); end; procedure TTestSimpleQueue.TestDequeue; begin DoAdd(3); AssertEquals('1',Queue.Dequeue); AssertEquals('Count',2,Queue.Count); end; procedure TTestSimpleQueue.TestToArray; Var A : specialize TArray<String>; I : Integer; SI : String; begin DoAdd(3); A:=Queue.ToArray; AssertEquals('Length Ok',3,Length(A)); For I:=1 to 3 do begin SI:=IntToStr(I); AssertEquals('Value '+SI,SI,A[i-1]); end; end; procedure TTestSimpleQueue.TestEnumerator; Var A : String; I : Integer; SI : String; begin DoAdd(3); I:=1; For A in Queue do begin SI:=IntToStr(I); AssertEquals('Value '+SI,SI,A); Inc(I); end; end; procedure TTestSimpleQueue.TestValueNotification; begin Queue.OnNotify:=@DoValueNotify; SetExpectValues('Add',['1','2','3'],[cnAdded,cnAdded,cnAdded]); DoAdd(3); DoneExpectValues; end; procedure TTestSimpleQueue.TestValueNotificationDelete; begin DoAdd(3); Queue.OnNotify:=@DoValueNotify; SetExpectValues('Clear',['1','2','3'],[cnRemoved,cnRemoved,cnRemoved],{$IFDEF FPC}true{$ELSE}False{$endif}); Queue.Clear; DoneExpectValues; end; begin RegisterTests([ TTestSimpleQueue,TTestSingleObjectQueue]); end.
unit fmuSlipOpen; interface uses // VCL Windows, ComCtrls, StdCtrls, Controls, ExtCtrls, Classes, SysUtils, Buttons, Spin, // This untPages, untDriver, Grids, ValEdit, untUtil, untTypes, untTestParams; type { TfmSlipOpen } TfmSlipOpen = class(TPage) btnStdExecute: TBitBtn; lblCount: TLabel; btnExecute: TBitBtn; vleParams: TValueListEditor; btnLoadFromTables: TButton; btnDefaultValues: TButton; btnSaveToTables: TButton; seCount: TSpinEdit; procedure btnExecuteClick(Sender: TObject); procedure btnStdExecuteClick(Sender: TObject); procedure vleParamsDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); procedure btnLoadFromTablesClick(Sender: TObject); procedure btnDefaultValuesClick(Sender: TObject); procedure btnSaveToTablesClick(Sender: TObject); procedure vleParamsSetEditText(Sender: TObject; ACol, ARow: Integer; const Value: String); procedure FormResize(Sender: TObject); private function GetItem(const AName: string): Integer; function GetPickItem(const AName: string): Integer; function LoadFromTables: Integer; function SaveToTables: Integer; public procedure UpdatePage; override; procedure UpdateObject; override; procedure Initialize; override; end; implementation {$R *.DFM} const C_CopyType = 'Дублирование печати'; C_CheckType = 'Тип чека'; C_CopyOffset1 = 'Смещение 1'; C_CopyOffset2 = 'Смещение 2'; C_CopyOffset3 = 'Смещение 3'; C_CopyOffset4 = 'Смещение 4'; C_CopyOffset5 = 'Смещение 5'; C_NumberOfCopies = 'Количество копий'; const OpenSlipParams: array[0..5] of TIntParam =( (Name: C_NumberOfCopies; Value: 1), (Name: C_CopyOffset1; Value: 1), (Name: C_CopyOffset2; Value: 1), (Name: C_CopyOffset3; Value: 1), (Name: C_CopyOffset4; Value: 5), (Name: C_CopyOffset5; Value: 7) ); OpenSlipExParams: array[0..12] of TIntParam =( (Name: 'Шрифт клише'; Value: 1), (Name: 'Шрифт заголовка документа'; Value: 1), (Name: 'Шрифт номера ЭКЛЗ'; Value: 1), (Name: 'Шрифт КПК и номера КПК'; Value: 1), (Name: 'Строка клише'; Value: 1), (Name: 'Строка заголовка документа'; Value: 3), (Name: 'Строка номера ЭКЛЗ'; Value: 4), (Name: 'Строка признака ФП'; Value: 5), (Name: 'Смещение клише'; Value: 1), (Name: 'Смещение заголовка документа'; Value: 1), (Name: 'Смещение номера ЭКЛЗ'; Value: 1), (Name: 'Смещение КПК и номера КПК'; Value: 1), (Name: 'Смещение признака ФП'; Value: 1) ); { TfmSlipOpen } procedure TfmSlipOpen.UpdateObject; function GetVal(Row: Integer): Integer; begin Result := StrToInt(Trim(vleParams.Cells[1, Row + 11])); end; begin // Основные Driver.CopyType := GetPickItem(C_CopyType); Driver.CheckType := GetPickItem(C_CheckType); Driver.CopyOffset1 := GetItem(C_CopyOffset1); Driver.CopyOffset2 := GetItem(C_CopyOffset2); Driver.CopyOffset3 := GetItem(C_CopyOffset3); Driver.CopyOffset4 := GetItem(C_CopyOffset4); Driver.CopyOffset5 := GetItem(C_CopyOffset5); Driver.OperationBlockFirstString := seCount.Value; Driver.NumberOfCopies := GetItem(C_NumberOfCopies); // Дополнительные Driver.ClicheFont := GetVal(0); Driver.HeaderFont := GetVal(1); Driver.EKLZFont := GetVal(2); Driver.KPKFont := GetVal(3); Driver.ClicheStringNumber := GetVal(4); Driver.HeaderStringNumber := GetVal(5); Driver.EKLZStringNumber := GetVal(6); Driver.FMStringNumber := GetVal(7); Driver.ClicheOffset := GetVal(8); Driver.HeaderOffset := GetVal(9); Driver.EKLZOffset := GetVal(10); Driver.KPKOffset := GetVal(11); Driver.FMOffset := GetVal(12); end; procedure TfmSlipOpen.btnExecuteClick(Sender: TObject); var Count: Integer; begin EnableButtons(False); try UpdateObject; Check(Driver.OpenFiscalSlipDocument); Count := Driver.OperationBlockFirstString; Count := Count + Driver.HeaderStringNumber + 3; Driver.OperationBlockFirstString := Count; UpdatePage; finally EnableButtons(True); end; end; procedure TfmSlipOpen.UpdatePage; begin seCount.Value := Driver.OperationBlockFirstString; end; procedure TfmSlipOpen.btnStdExecuteClick(Sender: TObject); var Count: Integer; begin EnableButtons(False); try UpdateObject; Check(Driver.OpenStandardFiscalSlipDocument); Count := Driver.OperationBlockFirstString; Count := Count + Driver.ReadTableDef(12,1,6,6) + 3; Driver.OperationBlockFirstString := Count; UpdatePage; finally EnableButtons(True); end; end; procedure TfmSlipOpen.Initialize; var i: Integer; begin VLE_AddSeparator(vleParams, 'Основные'); VLE_AddPickProperty(vleParams, C_CheckType, 'Продажа', ['Продажа', 'Покупка', 'Возврат продажи', 'Возврат покупки'], [0, 1, 2, 3]); VLE_AddPickProperty(vleParams, C_CopyType, 'Колонки', ['Колонки', 'Блоки строк'], [0, 1]); for i := Low(OpenSlipParams) to High(OpenSlipParams) do VLE_AddProperty(vleParams, OpenSlipParams[i].Name, IntToStr(OpenSlipParams[i].Value) ); VLE_AddSeparator(vleParams, 'Дополнительные'); for i := Low(OpenSlipExParams) to High(OpenSlipExParams) do VLE_AddProperty(vleParams, OpenSlipExParams[i].Name, IntToStr(OpenSlipExParams[i].Value) ); // Если были загружены настройки, записываем их в контрол if TestParams.ParamsLoaded then StringToVLEParams(vleParams, TestParams.SlipOpen.Text) else TestParams.SlipOpen.Text := VLEParamsToString(vleParams); end; function TfmSlipOpen.GetItem(const AName: string): Integer; begin Result := StrToInt(VLE_GetPropertyValue(vleParams, AName)); end; function TfmSlipOpen.GetPickItem(const AName: string): Integer; begin Result := VLE_GetPickPropertyValue(vleParams, AName); end; procedure TfmSlipOpen.vleParamsDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); begin VLE_DrawCell(Sender, ACol, ARow, Rect, State); end; procedure TfmSlipOpen.btnDefaultValuesClick(Sender: TObject); begin vleParams.Strings.Text := ''; Initialize; end; procedure TfmSlipOpen.btnLoadFromTablesClick(Sender: TObject); begin LoadFromTables; end; function TfmSlipOpen.LoadFromTables: Integer; var i: Integer; begin EnableButtons(False); try Driver.TableNumber := 12; Result := Driver.GetTableStruct; if Result <> 0 then Exit; Driver.RowNumber := 1; for i := 1 to Driver.FieldNumber do begin Driver.FieldNumber := i; Result := Driver.ReadTable; if Result = 0 then vleParams.Cells[1, i + 10] := IntToSTr(Driver.ValueOfFieldInteger); end; Updatepage; finally EnableButtons(True); end; end; function TfmSlipOpen.SaveToTables: Integer; var i: Integer; begin EnableButtons(False); try Driver.TableNumber := 12; Result := Driver.GetTableStruct; if Result <> 0 then Exit; Driver.RowNumber := 1; for i := 1 to Driver.FieldNumber do begin Driver.FieldNumber := i; Driver.ValueOfFieldInteger := StrToInt(vleParams.Cells[1, i + 10]); Result := Driver.WriteTable; if Result <> 0 then Exit; end; Updatepage; finally EnableButtons(True); end; end; procedure TfmSlipOpen.btnSaveToTablesClick(Sender: TObject); begin Check(SaveToTables); end; procedure TfmSlipOpen.vleParamsSetEditText(Sender: TObject; ACol, ARow: Integer; const Value: String); begin TestParams.SlipOpen.Text := VLEParamsToString(vleParams); end; procedure TfmSlipOpen.FormResize(Sender: TObject); begin if vleParams.Width > 392 then vleParams.DisplayOptions := vleParams.DisplayOptions + [doAutoColResize] else vleParams.DisplayOptions := vleParams.DisplayOptions - [doAutoColResize]; end; end.
unit mvc.ApplicationController; interface uses {$IFDEF FMX} FMX.Forms, {$ELSE} VCL.Forms, {$ENDIF} System.Classes, System.SysUtils, mvc.Interf; type TApplicationController = class(TInterfacedObject, IApplicationController) public procedure Run(AClass: TComponentClass; var reference; AFunc: TFunc<boolean>); class function New: IApplicationController; end; function ApplicationController: IApplicationController; implementation var FApplication: IApplicationController; function ApplicationController: IApplicationController; begin result := FApplication; end; { TApplicationController } class function TApplicationController.New: IApplicationController; begin result := TApplicationController.Create; end; procedure TApplicationController.Run(AClass: TComponentClass; var reference; AFunc: TFunc<boolean>); var rt: boolean; begin application.Initialize; rt := true; if assigned(AFunc) then rt := AFunc; if rt then begin application.CreateForm(AClass, reference); application.Run; end; end; initialization FApplication := TApplicationController.New; end.
unit ArchiAutoTest; {* Поддержка автоскриптов в Арчи. } // Модуль: "w:\archi\source\projects\Archi\Archi_Insider_Test_Support\ArchiAutoTest.pas" // Стереотип: "SimpleClass" // Элемент модели: "TArchiAutoTest" MUID: (4DE482A503AB) {$Include w:\archi\source\projects\Archi\arDefine.inc} interface {$If Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts)} uses l3IntfUses , ArchiInsiderTest ; type TArchiAutoTest = class(TArchiInsiderTest) {* Поддержка автоскриптов в Арчи. } protected function GetFolder: AnsiString; override; {* Папка в которую входит тест } function ResolveScriptFilePath(const aFileName: AnsiString): AnsiString; override; class function IsScript: Boolean; override; {* Хак для конструктора - из-за хитрой иерархии и кучи конструкторов в TTestSuite. } public constructor Create(const aMethodName: AnsiString; const aFolder: AnsiString); override; end;//TArchiAutoTest {$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts)} uses l3ImplUses , SysUtils , StrUtils //#UC START# *4DE482A503ABimpl_uses* //#UC END# *4DE482A503ABimpl_uses* ; function TArchiAutoTest.GetFolder: AnsiString; {* Папка в которую входит тест } //#UC START# *4C937013031D_4DE482A503AB_var* //#UC END# *4C937013031D_4DE482A503AB_var* begin //#UC START# *4C937013031D_4DE482A503AB_impl* Result := 'Scripts'; //#UC END# *4C937013031D_4DE482A503AB_impl* end;//TArchiAutoTest.GetFolder function TArchiAutoTest.ResolveScriptFilePath(const aFileName: AnsiString): AnsiString; //#UC START# *4DB03121022B_4DE482A503AB_var* //#UC END# *4DB03121022B_4DE482A503AB_var* begin //#UC START# *4DB03121022B_4DE482A503AB_impl* if ANSIStartsText('@\', aFileName) then Result := FileFromCurrent('Common\' + Copy(aFileName, 3, Length(aFileName) - 2)) else if (ExtractFilePath(aFileName) <> '') then Result := aFileName else Result := FileFromCurrent('Auto') + '\'+ aFileName; //#UC END# *4DB03121022B_4DE482A503AB_impl* end;//TArchiAutoTest.ResolveScriptFilePath class function TArchiAutoTest.IsScript: Boolean; {* Хак для конструктора - из-за хитрой иерархии и кучи конструкторов в TTestSuite. } //#UC START# *4DC395670274_4DE482A503AB_var* //#UC END# *4DC395670274_4DE482A503AB_var* begin //#UC START# *4DC395670274_4DE482A503AB_impl* Result := True; //#UC END# *4DC395670274_4DE482A503AB_impl* end;//TArchiAutoTest.IsScript constructor TArchiAutoTest.Create(const aMethodName: AnsiString; const aFolder: AnsiString); //#UC START# *4DC399CA00BC_4DE482A503AB_var* //#UC END# *4DC399CA00BC_4DE482A503AB_var* begin //#UC START# *4DC399CA00BC_4DE482A503AB_impl* inherited Create(aMethodName, aFolder); FMethod := Self.DoIt; //#UC END# *4DC399CA00BC_4DE482A503AB_impl* end;//TArchiAutoTest.Create {$IfEnd} // Defined(nsTest) AND Defined(InsiderTest) AND NOT Defined(NoScripts) end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.5 10/26/2004 9:46:34 PM JPMugaas Updated refs. Rev 1.4 4/19/2004 5:05:48 PM JPMugaas Class rework Kudzu wanted. Rev 1.3 2004.02.03 5:45:28 PM czhower Name changes Rev 1.2 10/19/2003 2:27:22 PM DSiders Added localization comments. Rev 1.1 4/7/2003 04:03:52 PM JPMugaas User can now descover what output a parser may give. Rev 1.0 2/19/2003 05:51:24 PM JPMugaas Parsers ported from old framework. } unit IdFTPListParseMPEiX; interface {$i IdCompilerDefines.inc} uses Classes, IdFTPList, IdFTPListParseBase, IdFTPListTypes; type TIdMPiXFTPListItem = class(TIdRecFTPListItem) protected FLimit : Cardinal; public constructor Create(AOwner: TCollection); override; property RecLength; property RecFormat; property NumberRecs; property Limit : Cardinal read FLimit write FLimit; end; //Anscestor for the MPE/iX Parsers //This is necessary because they both have a second line a function parses //Do not register this one TIdFTPLPMPiXBase = class(TIdFTPListBaseHeader) protected class function MakeNewItem(AOwner : TIdFTPListItems) : TIdFTPListItem; override; class function IsSecondHeader(ACols: TStrings): Boolean; virtual; public class function GetIdent : String; override; end; TIdFTPLPMPiX = class(TIdFTPLPMPiXBase) protected class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override; class function IsHeader(const AData: String): Boolean; override; public class function GetIdent : String; override; end; TIdFTPLPMPiXWithPOSIX = class(TIdFTPLPMPiXBase) protected class function ParseLine(const AItem : TIdFTPListItem; const APath : String = ''): Boolean; override; class function IsHeader(const AData: String): Boolean; override; public class function GetIdent : String; override; end; // RLebeau 2/14/09: this forces C++Builder to link to this unit so // RegisterFTPListParser can be called correctly at program startup... (*$HPPEMIT '#pragma link "IdFTPListParseMPEiX"'*) implementation uses IdGlobal, IdFTPCommon, IdGlobalProtocols, IdStrings, SysUtils; { TIdFTPLPMPiXBase } class function TIdFTPLPMPiXBase.GetIdent: String; begin Result := 'MPE/iX: '; {do not localize} end; class function TIdFTPLPMPiXBase.IsSecondHeader(ACols: TStrings): Boolean; begin Result := (ACols.Count > 3) and (ACols[0] = 'SIZE') and {do not localize} (ACols[1] = 'TYP') and {do not localize} (ACols[2] = 'EOF') and {do not localize} (ACols[3] = 'LIMIT'); {do not localize} if Result and (ACols.Count = 8) then begin Result := (ACols[4] = 'R/B') and {do not localize} (ACols[5] = 'SECTORS') and {do not localize} (ACols[6] = '#X') and {do not localize} (ACols[7] = 'MX') {do not localize} end; { This is for a Not Found banner such as: "@ not found" "./@ not found" } if (not Result) and (ACols.Count = 3) then begin Result := (IndyPos('@', ACols[0]) > 0) and (ACols[1] = 'not') and {do not localize} (ACols[2] = 'found'); {do not localize} end; end; class function TIdFTPLPMPiXBase.MakeNewItem(AOwner: TIdFTPListItems): TIdFTPListItem; begin Result := TIdMPiXFTPListItem.Create(AOwner); end; { TIdFTPLPMPiX } class function TIdFTPLPMPiX.GetIdent: String; begin Result := inherited GetIdent + 'LISTF'; {do not localize} end; class function TIdFTPLPMPiX.IsHeader(const AData: String): Boolean; var LCols : TStrings; LAccP, LGrpP : Integer; begin LAccP := IndyPos('ACCOUNT=', AData); {do not localize} if LAccP = 0 then begin LAccP := IndyPos('ACCOUNT =', AData); {do not localize} end; LGrpP := IndyPos('GROUP=', AData); {do not localize} if LGrpP = 0 then begin LGrpP := IndyPos('GROUP =', AData); {do not localize} end; Result := (LAccP > 0) and (LGrpP > LAccP); if not Result then begin LCols := TStringList.Create; try SplitColumns(Trim(StringReplace(AData, '-', ' ', [rfReplaceAll])), LCols); if not Result then begin Result := (LCols.Count > 3) and (LCols[0] = 'FILENAME') and {do not localize} (LCols[1] = 'CODE') and {do not localize} (LCols[2] = 'LOGICAL') and {do not localize} (LCols[3] = 'RECORD'); {do not localize} if Result and (LCols.Count = 5) then begin Result := (LCols[4] = 'SPACE'); {do not localize} end; end; if not Result then begin Result := IsSecondHeader(LCols); end; finally FreeAndNil(LCols); end; end; end; class function TIdFTPLPMPiX.ParseLine(const AItem: TIdFTPListItem; const APath: String): Boolean; var LCols : TStrings; LBuf : String; LI : TIdMPiXFTPListItem; begin LI := AItem as TIdMPiXFTPListItem; LCols := TStringList.Create; try //According to "HP ARPA File Transfer Protocol, Userís Guide, HP 3000 MPE/iX Computer Systems,Edition 6" //the filename here can be 8 chars long LI.FileName := Trim(Copy(AItem.Data, 1, 8)); LBuf := Copy(AItem.Data, 8, MaxInt); if (Length(LBuf) > 0) and (LBuf[1] <> ' ') then begin Fetch(LBuf); end; SplitColumns(Trim(LBuf), LCols); if LCols.Count > 1 then begin LI.Size := ExtractNumber(LCols[1]); end; //Type if LCols.Count > 2 then begin LI.RecFormat := LCols[2]; end; //record COunt - EOF if LCols.Count > 3 then begin LI.NumberRecs := IndyStrToInt64(LCols[3], 0); end; //Limit if LCols.Count > 4 then begin LI.Limit := IndyStrToInt64(LCols[4], 0); end; { HP3000 is a flat file system where there are no subdirs. There is a file group created by the user but that is mroe logical than anything. There might be a command for obtaining file groups but I have not seen one. Note that file groups can not obtain other groups. } LI.ItemType := ditFile; { Note that HP3000 does not give you the date at all. } LI.ModifiedAvail := False; finally FreeAndNil(LCols); end; Result := True; end; { TIdFTPLPMPiXWithPOSIX } class function TIdFTPLPMPiXWithPOSIX.GetIdent: String; begin Result := inherited GetIdent + 'With POSIX'; {do not localize} end; class function TIdFTPLPMPiXWithPOSIX.IsHeader(const AData: String): Boolean; var LCols : TStrings; begin { Often is something like this (spacing may very): == PATH= /PH/SAPHP/ CODE ------------LOGICAL RECORD----------- ----SPACE---- FILENAME SIZE TYP EOF LIMIT R/B SECTORS #X MX == or maybe this: === ACCOUNT= SYS GROUP= WORK FILENAME CODE ------------LOGICAL RECORD----------- ----SPACE---- === } Result := IndyPos('PATH=', AData) > 0; {do not localize} if not Result then begin LCols := TStringList.Create; try SplitColumns(Trim(StringReplace(AData, '-', ' ', [rfReplaceAll])), LCols); Result := (LCols.Count = 5) and (LCols[0] = 'CODE') and {do not localize} (LCols[1] = 'LOGICAL') and {do not localize} (LCols[2] = 'RECORD') and {do not localize} (LCols[3] = 'SPACE') and {do not localize} (LCols[4] = 'FILENAME'); {do not localize} if not Result then begin Result := IsSecondHeader(LCols); end; finally FreeAndNil(LCols); end; end; end; class function TIdFTPLPMPiXWithPOSIX.ParseLine(const AItem: TIdFTPListItem; const APath: String): Boolean; var LCols : TStrings; LI : TIdMPiXFTPListItem; begin LI := AItem as TIdMPiXFTPListItem; LCols := TStringList.Create; try SplitColumns(Trim(AItem.Data), LCols); if LCols.Count > 0 then begin LI.Size := ExtractNumber(LCols[0]); end; if LCols.Count > 1 then begin LI.RecFormat := LCols[1]; end; if LCols.Count > 2 then begin LI.NumberRecs := IndyStrToInt64(LCols[2], 0); end; if LCols.Count > 3 then begin LI.Limit := IndyStrToInt64(LCols[3], 0); end; if LCols.Count > 8 then begin LI.FileName := LCols[8]; end; { The original HP3000 is a flat file system where there are no subdirs. There is a file group created by the user but that is more logical than anything. There might be a command for obtaining file groups but I have not seen one. Note that file groups can not obtain other groups. More recent versions of HP3000 have Posix support including a hierarchical file system. Verified with test at: jazz.external.hp.com } if TextEndsWith(LI.FileName, '/') then begin LI.ItemType := ditDirectory; LI.FileName := Copy(AItem.FileName, 1, Length(LI.FileName) - 1); end else begin LI.ItemType := ditFile; end; { Note that HP3000 does not give you the date at all. } finally FreeAndNil(LCols); end; Result := True; end; { TIdMPiXFTPListItem } constructor TIdMPiXFTPListItem.Create(AOwner: TCollection); begin inherited Create(AOwner); //MP/iX or HP3000 will not give you a modified date at all ModifiedAvail := False; end; initialization RegisterFTPListParser(TIdFTPLPMPiX); RegisterFTPListParser(TIdFTPLPMPiXWithPOSIX); finalization UnRegisterFTPListParser(TIdFTPLPMPiX); UnRegisterFTPListParser(TIdFTPLPMPiXWithPOSIX); end.
unit TVGeneralSheet; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, VisualControls, ObjectInspectorInterfaces, PercentEdit, GradientBox, FramedButton, SheetHandlers, InternationalizerComponent; const tidSecurityId = 'SecurityId'; tidTrouble = 'Trouble'; tidCurrBlock = 'CurrBlock'; tidHoursOnAir = 'HoursOnAir'; tidComercials = 'Comercials'; tidCost = 'Cost'; tidROI = 'ROI'; const facStoppedByTycoon = $04; type TTVGeneralSheetHandler = class; TTVGeneralSheetViewer = class(TVisualControl) xfer_Name: TEdit; Label1: TLabel; peAdvertisement: TPercentEdit; btnClose: TFramedButton; btnDemolish: TFramedButton; NameLabel: TLabel; lbHourOnAir: TLabel; peHoursOnAir: TPercentEdit; lbAdPerc: TLabel; btnConnect: TFramedButton; Label2: TLabel; xfer_Creator: TLabel; Label6: TLabel; xfer_MetaFacilityName: TLabel; Label8: TLabel; lbCost: TLabel; Label9: TLabel; lbROI: TLabel; InternationalizerComponent1: TInternationalizerComponent; procedure xfer_NameKeyPress(Sender: TObject; var Key: Char); procedure btnCloseClick(Sender: TObject); procedure btnDemolishClick(Sender: TObject); procedure peHoursOnAirChange(Sender: TObject); procedure peHoursOnAirMoveBar(Sender: TObject); procedure peAdvertisementChange(Sender: TObject); procedure btnConnectClick(Sender: TObject); private procedure WMEraseBkgnd(var Message: TMessage); message WM_ERASEBKGND; private fHandler : TTVGeneralSheetHandler; end; TTVGeneralSheetHandler = class(TSheetHandler, IPropertySheetHandler) private fControl : TTVGeneralSheetViewer; fCurrBlock : integer; fOwnsFacility : boolean; private function CreateControl(Owner : TControl) : TControl; override; function GetControl : TControl; override; procedure RenderProperties(Properties : TStringList); override; procedure SetFocus; override; procedure Clear; override; private procedure SetName(str : string); procedure threadedGetProperties(const parms : array of const); procedure threadedRenderProperties(const parms : array of const); procedure threadedChgHourOnAir(const parms : array of const); procedure threadedChgHourAds(const parms : array of const); end; function TVGeneralSheetHandlerCreator : IPropertySheetHandler; stdcall; implementation uses Threads, SheetHandlerRegistry, FiveViewUtils, CacheCommon, Protocol, MathUtils, SheetUtils, Literals; {$R *.DFM} // TTVGeneralSheetHandler function TTVGeneralSheetHandler.CreateControl(Owner : TControl) : TControl; begin fControl := TTVGeneralSheetViewer.Create(Owner); fControl.fHandler := self; result := fControl; end; function TTVGeneralSheetHandler.GetControl : TControl; begin result := fControl; end; procedure TTVGeneralSheetHandler.RenderProperties(Properties : TStringList); var trouble : string; roi : integer; hours : integer; begin LockWindowUpdate(fControl.Handle); try FiveViewUtils.SetViewProp(fControl, Properties); trouble := Properties.Values[tidTrouble]; fOwnsFacility := GrantAccess(fContainer.GetClientView.getSecurityId, Properties.Values[tidSecurityId]); // Properties.Values[tidSecurityId] = fContainer.GetClientView.getSecurityId; if fOwnsFacility then begin fControl.NameLabel.Visible := false; fControl.xfer_Name.Visible := true; fControl.xfer_Name.Enabled := true; end else begin fControl.xfer_Name.Visible := false; fControl.NameLabel.Caption := fControl.xfer_Name.Text; fControl.NameLabel.Visible := true; end; fControl.btnConnect.Enabled := true; fControl.btnClose.Enabled := fOwnsFacility; fControl.btnDemolish.Enabled := fOwnsFacility; fControl.peHoursOnAir.Enabled := fOwnsFacility; fControl.peAdvertisement.Enabled := fOwnsFacility; try hours := StrToInt(Properties.Values[tidHoursOnAir]); except hours := 0; end; fControl.peHoursOnAir.Value := hours; try hours := StrToInt(Properties.Values[tidComercials]); except hours := 0; end; fControl.peAdvertisement.Value := hours; try if (trouble <> '') and (StrToInt(trouble) and facStoppedByTycoon <> 0) then fControl.btnClose.Text := GetLiteral('Literal119') else fControl.btnClose.Text := GetLiteral('Literal120'); except end; fControl.lbCost.Caption := MathUtils.FormatMoneyStr(Properties.Values[tidCost]); try roi := round(StrToFloat(Properties.Values[tidROI])); if roi = 0 then fControl.lbROI.Caption := GetLiteral('Literal121') else if roi > 0 then fControl.lbROI.Caption := GetFormattedLiteral('Literal122', [Properties.Values[tidROI]]) else fControl.lbROI.Caption := GetLiteral('Literal123'); except fControl.lbROI.Caption := GetLiteral('Literal124'); end; finally LockWindowUpdate(0); end; end; procedure TTVGeneralSheetHandler.SetFocus; var Names : TStringList; begin if not fLoaded then begin inherited; Names := TStringList.Create; FiveViewUtils.GetViewPropNames(fControl, Names); Names.Add(tidSecurityId); Names.Add(tidTrouble); Names.Add(tidCurrBlock); Names.Add(tidCost); Names.Add(tidROI); Threads.Fork(threadedGetProperties, priHigher, [Names, fLastUpdate]); end; end; procedure TTVGeneralSheetHandler.Clear; begin inherited; fControl.NameLabel.Caption := NA; fControl.xfer_Name.Text := ''; fControl.xfer_Name.Enabled := false; fControl.xfer_MetaFacilityName.Caption := NA; fControl.xfer_Creator.Caption := NA; fControl.lbCost.Caption := NA; fControl.lbROI.Caption := NA; fControl.btnClose.Enabled := false; fControl.btnDemolish.Enabled := false; fControl.btnConnect.Enabled := false; fControl.peHoursOnAir.Value := 0; fControl.peHoursOnAir.Enabled := false; fControl.peAdvertisement.Value := 0; fControl.peAdvertisement.Enabled := false; fControl.lbHourOnAir.Caption := NA; fControl.lbAdPerc.Caption := NA; end; procedure TTVGeneralSheetHandler.SetName(str : string); var MSProxy : OleVariant; begin try try fControl.Cursor := crHourGlass; MSProxy := fContainer.GetMSProxy; if not VarIsEmpty(MSProxy) and fOwnsFacility and CacheCommon.ValidName(str) then MSProxy.Name := str else Beep; finally fControl.Cursor := crDefault; end; except end; end; procedure TTVGeneralSheetHandler.threadedGetProperties(const parms : array of const); var Names : TStringList absolute parms[0].vPointer; Update : integer; Prop : TStringList; CrBlck : string; MSProxy : OleVariant; hrs : integer; cmm : integer; begin Update := parms[1].vInteger; try try if Update = fLastUpdate then Prop := fContainer.GetProperties(Names) else Prop := nil; finally Names.Free; end; // Get Model propeties if Update = fLastUpdate then begin CrBlck := Prop.Values[tidCurrBlock]; if CrBlck <> '' then fCurrBlock := StrToInt(CrBlck) else fCurrBlock := 0; end else fCurrBlock := 0; if (fCurrBlock <> 0) and (Update = fLastUpdate) then begin MSProxy := fContainer.GetMSProxy; MSProxy.BindTo(fCurrBlock); hrs := MSProxy.HoursOnAir; Prop.Values[tidHoursOnAir] := IntToStr(hrs); MSProxy.BindTo(fCurrBlock); cmm := MSProxy.Commercials; Prop.Values[tidComercials] := IntToStr(cmm); end; if Update = fLastUpdate then Threads.Join(threadedRenderProperties, [Prop, Update]) else Prop.Free; except end; end; procedure TTVGeneralSheetHandler.threadedRenderProperties(const parms : array of const); var Prop : TStringList absolute parms[0].vPointer; begin try try if parms[1].vInteger = fLastUpdate then RenderProperties(Prop); finally Prop.Free; end; except end; end; procedure TTVGeneralSheetHandler.threadedChgHourOnAir(const parms : array of const); var Proxy : OleVariant; begin if (fLastUpdate = parms[0].vInteger) and (fCurrBlock <> 0) and fOwnsFacility then try Proxy := fContainer.GetMSProxy; Proxy.BindTo(fCurrBlock); Proxy.HoursOnAir := parms[1].vInteger; except end end; procedure TTVGeneralSheetHandler.threadedChgHourAds(const parms : array of const); var Proxy : OleVariant; begin if (fLastUpdate = parms[0].vInteger) and (fCurrBlock <> 0) and fOwnsFacility then try Proxy := fContainer.GetMSProxy; Proxy.BindTo(fCurrBlock); Proxy.Commercials := parms[1].vInteger; except end end; // TVGeneralSheetHandlerCreator function TVGeneralSheetHandlerCreator : IPropertySheetHandler; begin result := TTVGeneralSheetHandler.Create; end; procedure TTVGeneralSheetViewer.xfer_NameKeyPress(Sender: TObject; var Key: Char); begin if Key = #13 then fHandler.SetName(xfer_Name.Text) else if Key in NotAllowedChars then Key := #0; end; procedure TTVGeneralSheetViewer.btnCloseClick(Sender: TObject); begin if (fHandler.fCurrBlock <> 0) and fHandler.fOwnsFacility then if btnClose.Text = GetLiteral('Literal125') then begin fHandler.fContainer.GetMSProxy.Stopped := true; btnClose.Text := GetLiteral('Literal126'); end else begin fHandler.fContainer.GetMSProxy.Stopped := false; btnClose.Text := GetLiteral('Literal127'); end; end; procedure TTVGeneralSheetViewer.btnDemolishClick(Sender: TObject); var Proxy : OleVariant; begin if (fHandler.fCurrBlock <> 0) and fHandler.fOwnsFacility then try Proxy := fHandler.fContainer.GetMSProxy; if not VarIsEmpty(Proxy) then begin Proxy.BindTo('World'); if Proxy.RDODelFacility(fHandler.GetContainer.GetXPos, fHandler.GetContainer.GetYPos) <> NOERROR then Beep; end; except end; end; procedure TTVGeneralSheetViewer.WMEraseBkgnd(var Message: TMessage); begin Message.Result := 1; end; procedure TTVGeneralSheetViewer.peHoursOnAirChange(Sender: TObject); begin Threads.Fork(fHandler.threadedChgHourOnAir, priNormal, [fHandler.fLastUpdate, peHoursOnAir.Value]); end; procedure TTVGeneralSheetViewer.peHoursOnAirMoveBar(Sender: TObject); begin lbHourOnAir.Caption := IntToStr(peHoursOnAir.Value); end; procedure TTVGeneralSheetViewer.peAdvertisementChange(Sender: TObject); begin Threads.Fork(fHandler.threadedChgHourAds, priNormal, [fHandler.fLastUpdate, peAdvertisement.Value]); end; procedure TTVGeneralSheetViewer.btnConnectClick(Sender: TObject); var url : string; begin url := 'http://local.asp?frame_Id=MapIsoView&frame_Action=PICKONMAP'; fHandler.GetContainer.HandleURL(url, false); end; initialization SheetHandlerRegistry.RegisterSheetHandler('TVGeneral', TVGeneralSheetHandlerCreator); end.
unit App; { Based on ParticleSystem.c from Book: OpenGL(R) ES 2.0 Programming Guide Authors: Aaftab Munshi, Dan Ginsburg, Dave Shreiner ISBN-10: 0321502795 ISBN-13: 9780321502797 Publisher: Addison-Wesley Professional URLs: http://safari.informit.com/9780321563835 http://www.opengles-book.com } {$INCLUDE 'Sample.inc'} interface uses System.Classes, Neslib.Ooogles, Neslib.FastMath, Sample.App; type TParticleSystemApp = class(TApplication) private const PARTICLE_COUNT = 1024; private type TParticle = record Lifetime: Single; StartPosition: TVector3; EndPosition: TVector3; end; private FProgram: TGLProgram; FAttrLifetime: TGLVertexAttrib; FAttrStartPos: TGLVertexAttrib; FAttrEndPos: TGLVertexAttrib; FUniTime: TGLUniform; FUniCenterPos: TGLUniform; FUniColor: TGLUniform; FUniSampler: TGLUniform; FTexture: TGLTexture; FParticles: array [0..PARTICLE_COUNT - 1] of TParticle; FParticleTime: Single; public procedure Initialize; override; procedure Render(const ADeltaTimeSec, ATotalTimeSec: Double); override; procedure Shutdown; override; procedure KeyDown(const AKey: Integer; const AShift: TShiftState); override; end; implementation uses {$INCLUDE 'OpenGL.inc'} System.UITypes, Sample.Assets, Sample.Texture, Sample.Platform; { TParticleSystemApp } procedure TParticleSystemApp.Initialize; var VertexShader, FragmentShader: TGLShader; I: Integer; Angle, Radius, S, C: Single; Uniform: TGLUniform; begin { Initialize the asset manager } TAssets.Initialize; { Compile vertex and fragment shaders } VertexShader.New(TGLShaderType.Vertex, 'uniform float u_time;'#10+ 'uniform float u_pointScale;'#10+ 'uniform vec3 u_centerPosition;'#10+ 'attribute float a_lifetime;'#10+ 'attribute vec3 a_startPosition;'#10+ 'attribute vec3 a_endPosition;'#10+ 'varying float v_lifetime;'#10+ 'void main()'#10+ '{'#10+ ' if (u_time <= a_lifetime)'#10+ ' {'#10+ ' gl_Position.xyz = a_startPosition + (u_time * a_endPosition);'#10+ ' gl_Position.xyz += u_centerPosition;'#10+ ' gl_Position.w = 1.0;'#10+ ' }'#10+ ' else'#10+ ' {'#10+ ' gl_Position = vec4(-1000, -1000, 0, 0);'#10+ ' }'#10+ ' v_lifetime = 1.0 - (u_time / a_lifetime);'#10+ ' v_lifetime = clamp(v_lifetime, 0.0, 1.0);'#10+ ' gl_PointSize = (v_lifetime * v_lifetime) * u_pointScale;'#10+ '}'); VertexShader.Compile; FragmentShader.New(TGLShaderType.Fragment, 'precision mediump float;'#10+ 'uniform vec4 u_color;'#10+ 'uniform sampler2D s_texture;'#10+ 'varying float v_lifetime;'#10+ 'void main()'#10+ '{'#10+ ' vec4 texColor;'#10+ ' texColor = texture2D(s_texture, gl_PointCoord);'#10+ ' gl_FragColor = vec4(u_color) * texColor;'#10+ ' gl_FragColor.a *= v_lifetime;'#10+ '}'); FragmentShader.Compile; { Link shaders into program } FProgram.New(VertexShader, FragmentShader); FProgram.Link; { We don't need the shaders anymore. Note that the shaders won't actually be deleted until the program is deleted. } VertexShader.Delete; FragmentShader.Delete; { Initialize vertex attributes } FAttrLifetime.Init(FProgram, 'a_lifetime'); FAttrStartPos.Init(FProgram, 'a_startPosition'); FAttrEndPos.Init(FProgram, 'a_endPosition'); { Initialize uniforms } FUniTime.Init(FProgram, 'u_time'); FUniCenterPos.Init(FProgram, 'u_centerPosition'); FUniColor.Init(FProgram, 'u_color'); FUniSampler.Init(FProgram, 's_texture'); { The gl_PointSize vertex shader output does not take screen scale into account. So we scale it ourselves. } FProgram.Use; Uniform.Init(FProgram, 'u_pointScale'); Uniform.SetValue(40.0 * TPlatform.ScreenScale); { Set clear color to black } gl.ClearColor(0, 0, 0, 0); { Fill in particle data array } for I := 0 to PARTICLE_COUNT - 1 do begin FParticles[I].Lifetime := Random; Angle := Random * 2 * Pi; Radius := Random * 2; FastSinCos(Angle, S, C); FParticles[I].EndPosition.Init(S * Radius, C * Radius, 0); Angle := Random * 2 * Pi; Radius := Random * 0.25; FastSinCos(Angle, S, C); FParticles[I].StartPosition.Init(S * Radius, C * Radius, 0); end; FParticleTime := 1; FTexture := LoadTexture('smoke.tga'); end; procedure TParticleSystemApp.KeyDown(const AKey: Integer; const AShift: TShiftState); begin { Terminate app when Esc key is pressed } if (AKey = vkEscape) then Terminate; end; procedure TParticleSystemApp.Render(const ADeltaTimeSec, ATotalTimeSec: Double); var CenterPos: TVector3; Color: TVector4; begin { Clear the color buffer } gl.Clear([TGLClear.Color]); { Use the program } FProgram.Use; { Update uniforms } FParticleTime := FParticleTime + ADeltaTimeSec; if (FParticleTime >= 1) then begin FParticleTime := 0; { Pick a new start location and color } CenterPos.Init(Random - 0.5, Random - 0.5, Random - 0.5); FUniCenterPos.SetValue(CenterPos); { Random color } Color.Init(Random, Random, Random, 0.5); FUniColor.SetValue(Color); end; { Load uniform time variable } FUniTime.SetValue(FParticleTime); { Load the vertex attributes } FAttrLifetime.SetData(TGLDataType.Float, 1, @FParticles[0].Lifetime, SizeOf(TParticle)); FAttrStartPos.SetData(TGLDataType.Float, 3, @FParticles[0].StartPosition, SizeOf(TParticle)); FAttrEndPos.SetData(TGLDataType.Float, 3, @FParticles[0].EndPosition, SizeOf(TParticle)); FAttrLifetime.Enable; FAttrStartPos.Enable; FAttrEndPos.Enable; { Blend particles } gl.Enable(TGLCapability.Blend); gl.BlendFunc(TGLBlendFunc.SrcAlpha, TGLBlendFunc.One); { Bind the texture } FTexture.BindToTextureUnit(0); { Set the sampler texture unit to 0 } FUniSampler.SetValue(0); { Draw the particle points } gl.DrawArrays(TGLPrimitiveType.Points, PARTICLE_COUNT); end; procedure TParticleSystemApp.Shutdown; begin { Release resources } FTexture.Delete; FProgram.Delete; end; end.
unit CodingAnim; interface uses Windows, SysUtils, Classes, MemUtils, ChunkStream, Dibs; type TBufferRec = record Owned : boolean; Header : PDib; ScanLines : pointer; end; type TAnimDecoder = // Renders an animation to a buffer class protected fStream : TChunkStream; fBufferRec : TBufferRec; fCurrentFrame : pointer; fCurrentFrameIndx : integer; fSize : TPoint; fBufferAddr : pointer; fBufferWidth : integer; fWidth : integer; fHeight : integer; fBitCount : integer; fOnFinished : TNotifyEvent; fStartingFrame : integer; fEndingFrame : integer; fKeyFramed : boolean; fFrameCount : integer; fDiskSize : integer; function GetEmpty : boolean; virtual; function GetFrameDelay( FrameIndx : integer ) : longint; virtual; abstract; function GetFirstAnimFrame : integer; virtual; abstract; procedure SeekStart; virtual; abstract; public property Stream : TChunkStream read fStream; property Buffer : TBufferRec read fBufferRec; property CurrentFrame : pointer read fCurrentFrame; property CurrentFrameIndx : integer read fCurrentFrameIndx; property Size : TPoint read fSize; property BufferWidth : integer read fBufferWidth; property Width : integer read fWidth; property Height : integer read fHeight; property BitCount : integer read fBitCount; property DiskSize : longint read fDiskSize; property FrameDelay[ FrameIndx : integer ] : longint read GetFrameDelay; property FrameCount : integer read fFrameCount; property OnFinished : TNotifyEvent read fOnFinished write fOnFinished; property Empty : boolean read GetEmpty; public procedure AttachToDib( x, y : integer; DibHeader : PDib; Pixels : pointer ); virtual; // Here this guy has to take care of: // fBufferRec, fBufferAddr, fBufferWidth procedure Detach; virtual; destructor Destroy; override; procedure LoadFromStream( aStream : TStream ); virtual; abstract; // Here this guy has to take care of: // fStream, fWidth, fHeight, fSize, fFrameCount, fDiskSize, fKeyFramed // fStartingFrame, fEndingFrame -> call ResetFrameRange for it // fCurrentFrame, fCurrentFrameIndx procedure LoadFromFile( const FileName : string ); virtual; procedure SeekFrame( FrameIndx : integer ); virtual; procedure DoFrame; // Just does ProcessFrame; NextFrame; procedure ProcessFrame; virtual; abstract; procedure NextFrame; virtual; procedure SetFrameRange( aStartingFrame, aEndingFrame : integer ); virtual; procedure ResetFrameRange; virtual; property FirstAnimFrame : integer read GetFirstAnimFrame; property StartingFrame : integer read fStartingFrame write fStartingFrame; property EndingFrame : integer read fEndingFrame write fEndingFrame; end; // Defined flags const fLooped = $0001; // Encoder states const esNone = 0; esCreating = 1; esFrames = 2; esClosing = 3; type TAnimEncoder = class protected fCurrentFrame : pointer; fPrevFrame : pointer; fStream : TStream; fFrameCount : integer; fFlags : integer; fState : integer; fDibHeader : PDib; fChangedColors : set of byte; procedure EncodeFrame; virtual; abstract; procedure SaveHeader; virtual; abstract; procedure Close; virtual; function GetFrameSize : integer; virtual; public constructor Create( aWidth, aHeight, aBitCount : integer; aFlags : integer ); virtual; destructor Destroy; override; procedure CreateFile( const Filename : string ); procedure CreateStream( aStream : TStream ); procedure ChangePalette( aIndx, aCount : integer; const RgbQuads ); virtual; procedure SaveFrame( Pixels : pointer ); virtual; property Stream : TStream read fStream write CreateStream; property Flags : integer read fFlags; property FrameCount : integer read fFrameCount; property FrameSize : integer read GetFrameSize; property CurrentFrame : pointer read fCurrentFrame; property PrevFrame : pointer read fPrevFrame; property State : integer read fState; property DibHeader : PDib read fDibHeader; end; procedure BufferCreate( var Buffer : TBufferRec; Width, Height : integer; Bits : integer ); procedure BufferFree( var BufferRec : TBufferRec ); implementation // TBufferRec procedure BufferFree( var BufferRec : TBufferRec ); begin with BufferRec do if Owned and (Header <> nil) then begin DibFree( Header ); Header := nil; end; end; procedure BufferCreate( var Buffer : TBufferRec; Width, Height : integer; Bits : integer ); begin with Buffer do begin Owned := true; Header := DibCreate( Width, -abs(Height), Bits ); ScanLines := DibPtr( Header ); end; end; // TAnimDecoder function TAnimDecoder.GetEmpty : boolean; begin Result := FrameCount = 0; end; procedure TAnimDecoder.DoFrame; begin ProcessFrame; NextFrame; end; procedure TAnimDecoder.ResetFrameRange; begin StartingFrame := FirstAnimFrame; EndingFrame := FrameCount; end; procedure TAnimDecoder.SeekFrame( FrameIndx : integer ); begin assert( FrameIndx <= FrameCount, 'Invalid frame index in CodingAnim.TAnimDecoder.SeekFrame!!' ); if FrameIndx < CurrentFrameIndx then begin SeekStart; fCurrentFrame := Stream.RelockChunk( fCurrentFrame ); end; while CurrentFrameIndx < FrameIndx do DoFrame; end; procedure TAnimDecoder.NextFrame; begin if CurrentFrameIndx > EndingFrame then begin if Assigned( OnFinished ) then OnFinished( Self ); SeekFrame( StartingFrame ); end else begin inc( fCurrentFrameIndx ); fCurrentFrame := Stream.RelockChunk( fCurrentFrame ); end; end; procedure TAnimDecoder.AttachToDib( x, y : integer; DibHeader : PDib; Pixels : pointer ); begin Detach; if DibHeader <> nil then begin fBufferRec.Owned := false; fBufferRec.Header := DibHeader; fBufferRec.ScanLines := pchar(Pixels) + DibPixelOfs( DibHeader, x, y ); end else BufferCreate( fBufferRec, Width, Height, 8 ); with fBufferRec do begin fBufferWidth := DwordAlign( Header.biWidth ); fBufferAddr := Pixels; end; end; procedure TAnimDecoder.Detach; begin BufferFree( fBufferRec ); end; destructor TAnimDecoder.Destroy; begin Detach; if Assigned( Stream ) then begin Stream.Unlock( fCurrentFrame ); Stream.free; end; inherited; end; procedure TAnimDecoder.SetFrameRange( aStartingFrame, aEndingFrame : integer ); begin StartingFrame := aStartingFrame; EndingFrame := aEndingFrame; end; procedure TAnimDecoder.LoadFromFile( const FileName : string ); begin LoadFromStream( TFileStream.Create( FileName, fmOpenRead or fmShareDenyWrite ) ); end; // TAnimEncoder procedure TAnimEncoder.CreateFile( const Filename : string ); begin CreateStream( TFileStream.Create( Filename, fmCreate ) ); end; procedure TAnimEncoder.CreateStream( aStream : TStream ); begin if Assigned( Stream ) then Close; fStream := aStream; fFrameCount := 0; fState := esCreating; SaveHeader; fState := esFrames; end; procedure TAnimEncoder.ChangePalette( aIndx, aCount : integer; const RgbQuads ); begin Move( RgbQuads, DibColors(fDibHeader)[aIndx], aCount * sizeof( TRgbQuad ) ); fChangedColors := fChangedColors + [aIndx, aIndx + aCount - 1]; end; function TAnimEncoder.GetFrameSize : integer; begin Result := DibSizeImage( DibHeader ); end; procedure TAnimEncoder.SaveFrame( Pixels : pointer ); begin inc( fFrameCount ); if Assigned( fCurrentFrame ) then begin if not Assigned( fPrevFrame ) then GetMem( fPrevFrame, FrameSize ); Move( fCurrentFrame^, fPrevFrame^, FrameSize ); end; fCurrentFrame := Pixels; EncodeFrame; end; constructor TAnimEncoder.Create( aWidth, aHeight, aBitCount : integer; aFlags : integer ); begin inherited Create; fFlags := aFlags; fDibHeader := DibNewHeader( aWidth, aHeight, aBitCount ); end; procedure TAnimEncoder.Close; begin Stream.Seek( 0, soFromBeginning ); fState := esClosing; SaveHeader; FreeObject( fStream ); end; destructor TAnimEncoder.Destroy; begin Close; FreeMem( fPrevFrame ); inherited; end; end.
unit uFrmConsulta; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.Buttons, Vcl.StdCtrls, Vcl.ExtCtrls, uLembreteDAO, System.Generics.Collections, uLembrete, uDM, uFrmInserirLembrete, FireDAC.DApt, uFrmEditarLembrete; type TFormConsulta = class(TForm) Panel1: TPanel; Panel2: TPanel; EdtBuscaTitulo: TEdit; BtnBuscar: TSpeedButton; ListView1: TListView; Panel3: TPanel; BtnNovo: TSpeedButton; BtnEditar: TSpeedButton; BtnExcluir: TSpeedButton; Label1: TLabel; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure BtnNovoClick(Sender: TObject); procedure BtnEditarClick(Sender: TObject); procedure BtnBuscarClick(Sender: TObject); procedure ListView1DblClick(Sender: TObject); procedure BtnExcluirClick(Sender: TObject); private { Private declarations } LembreteDAO: TLembreteDAO; procedure CarregarColecao; procedure PreencherListView(pListaLembrete: TList<TLembrete>); public { Public declarations } end; var FormConsulta: TFormConsulta; implementation {$R *.dfm} { TForm1 } procedure TFormConsulta.BtnBuscarClick(Sender: TObject); begin LembreteDAO.ListarPorTitulo(EdtBuscaTitulo.Text); CarregarColecao; end; procedure TFormConsulta.BtnEditarClick(Sender: TObject); begin try FrmEditarLembrete := TFrmEditar.Create(Self, TLembrete(ListView1.ItemFocused.Data)); FrmEditarLembrete.ShowModal; CarregarColecao; finally FreeAndNil(FrmEditarLembrete); ListView1.Clear end; end; procedure TFormConsulta.BtnExcluirClick(Sender: TObject); begin if ListView1.ItemIndex > -1 then if LembreteDAO.Deletar(TLembrete(TLembrete(ListView1.ItemFocused.Data))) then begin ShowMessage('Registro Deletado'); CarregarColecao; end; end; procedure TFormConsulta.BtnNovoClick(Sender: TObject); begin try FrmInserirLembrete := TFrmInserirLembrete.Create(Self); FrmInserirLembrete.ShowModal; CarregarColecao; finally FreeAndNil(FrmInserirLembrete); end; end; procedure TFormConsulta.CarregarColecao; begin Try PreencherListView(LembreteDAO.ListarPorTitulo(EdtBuscaTitulo.Text)); except on e: exception do raise exception.Create(e.Message); End; end; procedure TFormConsulta.FormCreate(Sender: TObject); begin DM := TDM.Create(Self); LembreteDAO := TLembreteDAO.Create; CarregarColecao; end; procedure TFormConsulta.FormDestroy(Sender: TObject); begin Try if Assigned(LembreteDAO) then FreeAndNil(LembreteDAO); if Assigned(DM) then FreeAndNil(DM); Except on e: exception do raise exception.Create(e.Message); End; end; procedure TFormConsulta.ListView1DblClick(Sender: TObject); begin try FrmEditarLembrete := TFrmEditar.Create(Self, TLembrete(ListView1.ItemFocused.Data)); FrmEditarLembrete.ShowModal; CarregarColecao; finally FreeAndNil(FrmEditarLembrete); end; end; procedure TFormConsulta.PreencherListView(pListaLembrete: TList<TLembrete>); var I: integer; tempItem: TListItem; begin if Assigned(pListaLembrete) then begin ListView1.Clear; for I := 0 to pListaLembrete.Count - 1 do begin tempItem := ListView1.Items.Add; tempItem.Caption := IntToStr(TLembrete(pListaLembrete[I]).IDLembrete); tempItem.SubItems.Add(TLembrete(pListaLembrete[I]).titulo); tempItem.SubItems.Add(FormatDateTime('dd/mm/yyyy HH:mm', TLembrete(pListaLembrete[I]).data)); tempItem.Data := TLembrete(pListaLembrete[I]); end; end else ShowMessage('Nada Encontrado'); end; end.
unit LanderTypes; interface uses Windows, Graphics, GameTypes; const idNone = -1; type TLandOption = (loGrated, loGlassed, loShaded, loRedShaded, loColorShaded, loBlackShaded, loUpProjected, loNoClip, loReddened, loColorTinted, loGrayed, loRedded, loGreened, loDarkened); TLandOptions = set of TLandOption; TLandState = (lsFocusable, lsGrounded, lsOverlayedGround, lsOverlayed, lsDoubleOverlayed, lsHighLand); TLandStates = set of TLandState; type TObjInfo = object id : integer; angle : TAngle; frame : integer; Options : TLandOptions; Caption : string; shadeid : integer; end; type TOffsetedObjInfo = object(TObjInfo) x, y : integer; end; const cMaxItemOverlays = 10; type TItemOverlayInfo = record count : integer; objects : array [1..cMaxItemOverlays] of TOffsetedObjInfo; end; type TItemInfo = object(TObjInfo) r, c : integer; Size : integer; States : TLandStates; Overlays : TItemOverlayInfo; end; const cMaxAirObjs = 20; type TAirObjInfo = object(TOffsetedObjInfo) r, c : integer; end; type TAirObjsInfo = record count : integer; objects : array [0..pred(cMaxAirObjs)] of TAirObjInfo; end; {$IFDEF SHOWCNXS} type TCnxKind = (cnxkNone, cnxkOutputs, cnxkInputs); type TCnxInfo = record r, c : integer; color : TColor; end; type PCnxInfoArray = ^TCnxInfoArray; TCnxInfoArray = array [0..0] of TCnxInfo; type TCnxsInfo = record cnxkind : TCnxKind; r, c : integer; cnxcount : integer; cnxs : PCnxInfoArray; end; {$ENDIF} type ICoordinateConverter = interface function ObjectToMap(const view : IGameView; x, y : integer; out i, j : integer; checkbase : boolean) : boolean; function ScreenToMap(const view : IGameView; x, y : integer; out i, j : integer) : boolean; function MapToScreen(const view : IGameView; i, j : integer; out x, y : integer) : boolean; end; type IImager = interface function GetObjectImage(id : integer; angle : TAngle) : TGameImage; function GetSpareImage : TGameImage; function GetDownloadImage : TGameImage; function GetShadeImage : TGameImage; function GetRedShadeImage : TGameImage; function GetBlackShadeImage : TGameImage; procedure SetImageSuit( ImageSuit : integer ); function GetImageSuit : integer; end; type IWorldMap = interface function GetRows : integer; function GetColumns : integer; function GetGroundInfo(i, j : integer; const focus : IGameFocus; out which : TObjInfo) : boolean; function GetGroundOverlayInfo(i, j : integer; const focus : IGameFocus; out which : TItemInfo) : boolean; function GetItemInfo(i, j : integer; const focus : IGameFocus; out which : TItemInfo) : boolean; function GetItemOverlayInfo(i, j : integer; const focus : IGameFocus; out which : TItemOverlayInfo) : boolean; function GetFocusObjectInfo(const focus : IGameFocus; const R : TRect; out which : TOffsetedObjInfo) : boolean; function CreateFocus(const view : IGameView) : IGameFocus; function GetImager(const focus : IGameFocus) : IImager; procedure SetImageSuit( ImageSuit : integer ); function GetImageSuit : integer; end; implementation end.
unit Thread.ImportaRespostasCTNC; interface uses System.Classes, Dialogs, Windows, Forms, SysUtils, Messages, Controls, System.DateUtils, System.StrUtils, Generics.Collections, Control.Sistema, FireDAC.Comp.Client, Common.ENum, Control.PlanilhaRespostaCTNC, Control.ContatosBases, Control.Entregas, Model.PlanilhaRespostaCTNC, Control.CCEPDistribuidor; type Thread_ImportaRespostasCTNC = class(TThread) private { Private declarations } bCancel: Boolean; sMensagem: String; FdPos: Double; iPos : Integer; iLinha : Integer; contatos : TContatosBasesControls; entregas: TEntregasControl; ccep: TCCEPDistribuidorControl; planilha : TPlanilhaRespostaCTNCControl; planilhas : TObjectList<TPlanilhaRespostaCTNC>; iAgente : Integer; protected procedure Execute; override; procedure IniciaProcesso; procedure AtualizaProgress; procedure TerminaProcesso; procedure AtualizaLOG; public FFile: String; end; implementation { Important: Methods and properties of objects in visual components can only be used in a method called using Synchronize, for example, Synchronize(UpdateCaption); and UpdateCaption could look like, procedure THRead_ImportaRespostasCTNC.UpdateCaption; begin Form1.Caption := 'Updated in a thread'; end; or Synchronize( procedure begin Form1.Caption := 'Updated in thread via an anonymous method' end ) ); where an anonymous method is passed. Similarly, the developer can call the Queue method with similar parameters as above, instead passing another TThread class as the first parameter, putting the calling thread in a queue with the other thread. } uses Common.Utils, Global.Parametros, View.EnvioRespostaCTNC, Data.SisGeF; { THRead_ImportaRespostasCTNC } procedure Thread_ImportaRespostasCTNC.AtualizaLOG; begin view_EnvioRespostaCTNC.memLOG.Lines.Add(sMensagem); view_EnvioRespostaCTNC.memLOG.Lines.Add(''); iLinha := view_EnvioRespostaCTNC.memLOG.Lines.Count - 1; view_EnvioRespostaCTNC.memLOG.Refresh; end; procedure Thread_ImportaRespostasCTNC.AtualizaProgress; begin view_EnvioRespostaCTNC.pbImportacao.Position := FdPos; view_EnvioRespostaCTNC.pbImportacao.Properties.Text := FormatFloat('0.00%',FdPos); view_EnvioRespostaCTNC.pbImportacao.Refresh; view_EnvioRespostaCTNC.memLOG.Lines[iLinha] := ' >>> ' + IntToStr(iPos) + ' registros processados'; view_EnvioRespostaCTNC.memLOG.Refresh; end; procedure Thread_ImportaRespostasCTNC.Execute; var Contador, I, LinhasTotal, iRet: Integer; Linha, campo, codigo, sMess, sData: String; d: Real; aParam: array of Variant; iTotal : Integer; sCCEP: String; sEMail: String; FDQuery : TFDQuery; begin { Place thread code here } Synchronize(IniciaProcesso); contatos := TContatosBasesControls.Create; entregas := TEntregasControl.Create; planilha := TPlanilhaRespostaCTNCControl.Create; planilhas := TObjectList<TPlanilhaRespostaCTNC>.Create; ccep := TCCEPDistribuidorControl.Create; try try // Carregando o arquivo ... planilhas := planilha.GetPlanilha(FFile); if planilhas.Count > 0 then begin iPos := 0; FdPos := 0; iTotal := planilhas.Count; if Data_Sisgef.mtbRespostas.Active then Data_Sisgef.mtbRespostas.Close; Data_Sisgef.mtbRespostas.Open; for I := 0 to planilhas.Count - 1 do begin if planilhas[i].Flag = '0' then begin Data_Sisgef.mtbRespostas.Insert; Data_Sisgef.mtbRespostasdom_flag.AsString := planilhas[i].Flag; Data_Sisgef.mtbRespostasdat_retorno.AsString := planilhas[i].Data; Data_Sisgef.mtbRespostasnum_nossonumero.AsString := planilhas[i].NN; Data_Sisgef.mtbRespostasdes_resposta.AsString := planilhas[i].Resposta; Data_Sisgef.mtbRespostascod_embarcador.AsString := planilhas[i].CodigoEmbarcador; Data_Sisgef.mtbRespostasnom_embarcador.AsString := planilhas[i].NomeEmbarcador; Data_Sisgef.mtbRespostasnum_pedido.AsString := planilhas[i].Pedido; Data_Sisgef.mtbRespostasnom_consumidor.AsString := planilhas[i].Consumidor; Data_Sisgef.mtbRespostasnum_telefone.AsString := planilhas[i].Telefone; Data_Sisgef.mtbRespostasdat_atribuicao.AsString := planilhas[i].Atribuicao; Data_Sisgef.mtbRespostasnom_entregador.AsString := planilhas[i].Entregador; Data_Sisgef.mtbRespostasdat_previsao.AsString := planilhas[i].Previsao; Data_Sisgef.mtbRespostasdat_leitura.AsString := planilhas[i].Leitura; Data_Sisgef.mtbRespostasnom_usuario.AsString := planilhas[i].Usuario; Data_Sisgef.mtbRespostasnum_sequencia.AsString := planilhas[i].Sequencia; Data_Sisgef.mtbRespostasnom_cidade.AsString := planilhas[i].Cidade; SetLength(aParam,2); aParam[0] := 'NN'; aParam[1] := planilhas[i].NN; FDQuery := TSistemaControl.GetInstance.Conexao.ReturnQuery(); FDQuery := entregas.Localizar(aParam); Finalize(aParam); if not FDQuery.IsEmpty then begin sCCEP := Copy(FDQuery.FieldByName('num_cep').AsString,1,3); end else begin sCCEP := ''; end; FDquery.Close; if not sCCEP.IsEmpty then begin SetLength(aParam,2); aParam[0] := 'CCEP'; aParam[1] := sCCEP; FDQuery := ccep.Localizar(aParam); Finalize(aParam); sEmail := ''; iAgente := 0; if not FDQuery.IsEmpty then begin iAgente := FDQuery.FieldByName('cod_agente').AsInteger; end; FDQuery.Close; if iAgente > 0 then begin SetLength(aParam,2); aParam[0] := 'AGENTE'; aParam[1] := iAgente; FDQuery := contatos.Localizar(aParam); if not FDQuery.IsEmpty then FDQuery.First; while not FDQuery.Eof do begin if FDQuery.FieldByName('des_email').AsString <> '' then begin sEMail := sEmail + FDQuery.FieldByName('des_email').AsString + ';'; end; FDQuery.Next; end; FDQuery.Close; end; end; Data_Sisgef.mtbRespostasdes_email.AsString := sEmail; Data_Sisgef.mtbRespostas.Post; end; iPos := iPos + 1; FdPos := (iPos / iTotal) * 100; if not(Self.Terminated) then begin Synchronize(AtualizaProgress); end else begin Abort; end; end; end; Except on E: Exception do begin Application.MessageBox(PChar('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message), 'Erro', MB_OK + MB_ICONERROR); bCancel := True; end; end; finally if bCancel then begin sMensagem := FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' importação cancelada ...'; Synchronize(AtualizaLog); Application.MessageBox('Importação cancelada!', 'Importação de Entregas', MB_OK + MB_ICONWARNING); end else begin sMensagem := FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' importação concluída com sucesso'; Synchronize(AtualizaLog); Application.MessageBox('Importação concluída com sucesso!', 'Importação de Respostas', MB_OK + MB_ICONINFORMATION); end; Synchronize(TerminaProcesso); entregas.Free; planilha.Free; planilhas.Free; contatos.Free; if FDQuery.Active then FDQuery.Close; FDQuery.Connection.Close; FDQuery.Free; end; end; procedure Thread_ImportaRespostasCTNC.IniciaProcesso; begin bCancel := False; view_EnvioRespostaCTNC.actFechar.Enabled := False; view_EnvioRespostaCTNC.actImportar.Enabled := False; view_EnvioRespostaCTNC.actAbrir.Enabled := False; view_EnvioRespostaCTNC.dxLayoutItem7.Visible := True; sMensagem := FormatDateTime('yyyy/mm/dd hh:mm:ss', Now) + ' iniciando importação do arquivo ' + FFile + ' aguarde...'; AtualizaLOG; end; procedure Thread_ImportaRespostasCTNC.TerminaProcesso; begin view_EnvioRespostaCTNC.actFechar.Enabled := True; view_EnvioRespostaCTNC.actImportar.Enabled := True; view_EnvioRespostaCTNC.actAbrir.Enabled := True; view_EnvioRespostaCTNC.edtArquivo.Clear; view_EnvioRespostaCTNC.pbImportacao.Position := 0; view_EnvioRespostaCTNC.pbImportacao.Clear; view_EnvioRespostaCTNC.dxLayoutItem7.Visible := False; if not Data_Sisgef.mtbRespostas.IsEmpty then begin view_EnvioRespostaCTNC.actEnviar.Enabled := True; end else begin view_EnvioRespostaCTNC.actEnviar.Enabled := False; end; end; end.
unit my_bloody_chart; interface uses ExtCtrls,graphics,SysUtils; type Talign=(alLeft,alCenter,alRight); Tvalign=(valTop,valCenter,valBottom); bloody_chart=class public x_offset,y_offset: Integer; //отступы сверху и слева grid_number: Integer; //сколько будет минимум линий сетки labels_number: Integer; //сколько цифр-подписей Font_size: Integer; //размер шрифта для подписей scale: Real; //масштаб (по обеим осям один - мне так и надо) image: TImage; //куда все рисовать xmin,xmax,ymin,ymax: Real; //мин и макс значения величин по осям x_range, y_range: Integer; grid_color: TColor; major_grid_color: TColor; major_grid_width: Integer; lines_width: Integer; bounds: Boolean; center_axis_names: boolean; xname,yname: string; procedure point(x: Real; y: Real; color: TColor); procedure circle(x: Real; y: Real; r: Integer); procedure LineTo(x: Real; y:Real); procedure MoveTo(x: Real; y:Real); procedure TextOut(x: Real; y:Real; s:string; align: TAlign; valign: TValign); procedure init; constructor Create; end; implementation constructor bloody_chart.Create; begin inherited Create; x_offset:=40; y_offset:=40; Font_size:=25; grid_number:=9; labels_number:=3; grid_color:=clGray; major_grid_color:=clBlack; major_grid_width:=2; xname:='x'; yname:='y'; center_axis_names:=true; end; procedure bloody_chart.init; var xscale,yscale: Real; grid_x,ticks: Real; i: Integer; s: string; last_x_tick,last_y_tick: Integer; max_y_tick_width,max_x_tick_height: Integer; begin yscale:=(image.ClientHeight-2*y_offset)/(ymax-ymin); xscale:=(image.ClientWidth-2*x_offset)/(xmax-xmin); image.Picture.Bitmap.Height:=image.ClientHeight; image.Picture.Bitmap.Width:=image.ClientWidth; if yscale>xscale then begin //будет широкий график x_range:=image.ClientWidth-2*x_offset; y_range:=Round(xscale/yscale*(image.ClientHeight-2*y_offset)); grid_x:=(ymax-ymin)/(grid_number-1); ticks:=(ymax-ymin)/(labels_number-1); scale:=xscale; end else begin y_range:=image.ClientHeight-2*y_offset; x_range:=Round(yscale/xscale*(image.ClientWidth-2*x_offset)); grid_x:=(xmax-xmin)/(grid_number-1); ticks:=(xmax-xmin)/(labels_number-1); scale:=yscale; end; image.Canvas.Brush.Color:=clWhite; image.Canvas.FillRect(image.ClientRect); image.Canvas.Pen.Color:=clBlack; image.Canvas.Rectangle(x_offset,y_offset,x_offset+x_range,y_offset+y_range); //нарисовали границы графика. Теперь: сетку image.Canvas.Pen.Color:=grid_color; image.Canvas.Pen.Width:=1; i:=1; repeat image.Canvas.MoveTo(x_offset+round(i*grid_x*scale),y_offset); image.Canvas.LineTo(x_offset+round(i*grid_x*scale),y_offset+y_range); inc(i) until i*grid_x*scale>=x_range; i:=1; repeat image.Canvas.MoveTo(x_offset,y_offset+y_range-round(i*grid_x*scale)); image.Canvas.LineTo(x_offset+x_range,y_offset+y_range-round(i*grid_x*scale)); inc(i) until i*grid_x*scale>=y_range; //теперь подписи и "тики" Image.Canvas.Pen.Width:=major_grid_width; Image.Canvas.Pen.Color:=major_grid_color; Image.Canvas.Font.Size:=font_size; i:=0; //пошли по оси X max_x_tick_height:=0; repeat image.Canvas.MoveTo(x_offset+round(i*ticks*scale),y_offset); image.Canvas.LineTo(x_offset+round(i*ticks*scale),y_offset+y_range+5); // s:=FloatToStrF(xmin+i*ticks,ffFixed,5,1); s:=FloatToStr(xmin+i*ticks); last_x_tick:=image.Canvas.TextWidth(s) div 2; if image.Canvas.TextHeight(s)>max_x_tick_height then max_x_tick_height:=image.Canvas.TextHeight(s); image.Canvas.TextOut(x_offset+round(i*ticks*scale)-last_x_tick,y_offset+y_range+15,s); inc(i) until i*ticks*scale-x_range>1; i:=0; max_y_tick_width:=0; repeat image.Canvas.MoveTo(x_offset+x_range,y_offset+y_range-round(i*ticks*scale)); image.Canvas.LineTo(x_offset-5,y_offset+y_range-round(i*ticks*scale)); // s:=FloatToStrF(ymin+i*ticks,ffFixed,5,1); s:=FloatToStr(ymin+i*ticks); last_y_tick:=image.Canvas.TextHeight(s) div 2; if image.Canvas.TextWidth(s)>max_y_tick_width then max_y_tick_width:=image.Canvas.TextWidth(s); image.Canvas.TextOut(x_offset-5-image.Canvas.TextWidth(s),y_offset+y_range-round(i*ticks*scale)-last_y_tick,s); inc(i) until i*ticks*scale-y_range>1; //ну еще подписи осей if center_axis_names then begin image.Canvas.TextOut(x_offset+(x_range div 2)-(image.Canvas.TextWidth(xname) div 2),y_offset+y_range+max_x_tick_height+10,xname); image.Canvas.TextOut(x_offset-(image.Canvas.TextWidth(yname))-max_y_tick_width-10,y_offset+(y_range div 2)-(image.Canvas.TextHeight(yname) div 2),yname); end else begin image.Canvas.TextOut(x_offset+x_range+last_x_tick+(x_range div 10)-(image.Canvas.TextWidth(xname) div 2),y_offset+y_range+15,xname); image.Canvas.TextOut(x_offset-5-image.Canvas.TextWidth(yname),y_offset-last_y_tick-(image.Canvas.TextHeight(yname) div 2)-(y_range div 10),yname); end; Image.Canvas.Pen.Width:=1; end; procedure bloody_chart.point(x: Real; y:Real;color: TColor); begin if (x<xmax) and (x>xmin) and (y<ymax) and (y>ymin) then image.Canvas.Pixels[x_offset+Round((x-xmin)*scale),y_offset+y_range-Round((y-ymin)*scale)]:=color; end; procedure bloody_chart.circle(x: Real; y: Real; r:Integer); begin image.Canvas.Brush.Color:=clBlack; image.Canvas.Pen.Color:=clBlack; if (x<xmax) and (x>xmin) and (y<ymax) and (y>ymin) then image.Canvas.Ellipse(x_offset+Round((x-xmin)*scale)-r,y_offset+y_range-Round((y-ymin)*scale)-r,x_offset+Round((x-xmin)*scale)+r,y_offset+y_range-Round((y-ymin)*scale)+r); end; procedure bloody_chart.LineTo(x: Real; y:Real); begin image.Canvas.Pen.Width:=lines_Width; if (not bounds) or ((x<=xmax) and (x>=xmin) and (y<=ymax) and (y>=ymin)) then image.Canvas.LineTo(x_offset+Round((x-xmin)*scale),y_offset+y_range-Round((y-ymin)*scale)); end; procedure bloody_chart.MoveTo(x:Real; y:Real); begin if (not bounds) or ((x<=xmax) and (x>=xmin) and (y<=ymax) and (y>=ymin)) then image.Canvas.MoveTo(x_offset+Round((x-xmin)*scale),y_offset+y_range-Round((y-ymin)*scale)); end; procedure bloody_chart.TextOut(x: Real; y:Real; s:string; align: TAlign; valign: TValign); var px,py: Integer; begin if (not bounds) or ((x<xmax) and (x>xmin) and (y<ymax) and (y>ymin)) then begin px:=x_offset+Round((x-xmin)*scale); if align=alCenter then px:=px-(image.Canvas.TextWidth(s) div 2) else if align=alRight then px:=px-image.Canvas.TextWidth(s); py:=y_offset+y_range-Round((y-ymin)*scale); if valign=valCenter then py:=py-(image.Canvas.TextHeight(s) div 2) else if valign=valBottom then py:=py-image.Canvas.TextHeight(s); // image.Canvas.Brush.Color:=clWhite; image.Canvas.Brush.Style:=bsClear; image.Canvas.TextOut(px,py,s); end; end; end.
unit M_UK; interface const JMFILE='data\osob.dat'; JMSZ='data\seznam\helplist.txt'; POC_NAROD=42; {pocet narodnosti} POC_PRACE_M=15; {pocet povolani} POC_PRACE_Z=13; {typ predstavujici osobu databaze} type T_PRACE_M=array[1..POC_PRACE_M] of string[20]; {mnozina povolani} T_PRACE_Z=array[1..POC_PRACE_Z] of string[20]; T_NAROD=array[1..POC_NAROD] of string[20]; {mnozina narodu} T_SEX=array[1..2] of string[20]; {muz zena} type T_PERSON=record JMENO:string[20]; SEX:string[20]; ROK_NAR:string[20]; MISTO_NAR:string[20]; NAROD:string[20]; PRACE:string[20]; end; T_ukos=^T_osoba; T_osoba=record tam,zpet:T_ukos; os:T_PERSON; end; var OSOBA,pomuk:T_ukos; REC:T_PERSON; procedure ADD(var UK:T_ukos;REC:T_PERSON); {prida do seznamu dalsi zaznam} procedure SH_vlevo(UK:T_ukos;var P:T_ukos;var REC:T_PERSON); {ukaze zaznam vlevo} procedure SH_vpravo(UK:T_ukos;var P:T_ukos;var REC:T_PERSON); {ukaze zaznam vpravo} procedure uklid(var UK:T_ukos); {zlikviduje seznam} implementation procedure ADD(var UK:T_ukos;REC:T_PERSON); var pom:T_ukos; begin {vytvoreni noveho} new(pom); pom^.os:=REC; {napojeni noveho} pom^.zpet:=UK^.zpet; pom^.tam:=UK; {uprava vazeb} pom^.zpet^.tam:=pom; UK^.zpet:=pom; end; procedure SH_vlevo(UK:T_ukos;var P:T_ukos;var REC:T_PERSON); begin if P<>UK then P:=P^.zpet; REC:=P^.os; end; procedure SH_vpravo(UK:T_ukos;var P:T_ukos;var REC:T_PERSON); begin if P<>UK^.zpet then P:=P^.tam; REC:=P^.os; end; procedure uklid(var UK:T_ukos); var pom:T_ukos; begin while UK^.zpet<>UK do begin pom:=UK^.zpet^.zpet; dispose(UK^.zpet); UK^.zpet:=pom; end; dispose(UK); end; begin end.
unit ntvPageControls; {** * This file is part of the "Mini Library" * * @url http://www.sourceforge.net/projects/minilib * @license modifiedLGPL (modified of http://www.gnu.org/licenses/lgpl.html) * See the file COPYING.MLGPL, included in this distribution, * @author Belal Alhamed <belalhamed at gmail dot com> * @author Zaher Dirkey *} {$mode objfpc}{$H+} interface uses Classes, Messages, Controls, SysUtils, Contnrs, Graphics, Forms, Types, LMessages, LCLType, LCLIntf, LCLProc, ntvTabs, ntvTabSets, ntvUtils; type TntvPageControl = class; TntvPageItem = class; { TntvPageItem } TntvPageItem = class(TntvTabItem) private FControl: TControl; procedure SetControl(const Value: TControl); function GetPageControl: TntvPageControl; protected procedure SetIndex(Value: Integer); override; public constructor Create(vCollection: TCollection); override; destructor Destroy; override; procedure Assign(Source: TPersistent); override; property PageControl: TntvPageControl read GetPageControl; published property Control: TControl read FControl write SetControl; end; TntvPageItemClass = class of TntvPageItem; { TntvPages } TntvPages = class(TntvTabSetItems) private function GetItem(Index: Integer): TntvPageItem; function GetPageControl: TntvPageControl; procedure SetItem(Index: Integer; Value: TntvPageItem); protected property PageControl: TntvPageControl read GetPageControl; public function GetOwner: TPersistent; override; function Add: TntvPageItem; function FindControl(vControl: TControl): TntvPageItem; function IndexOf(vControl: TControl): Integer; function AddControl(vControl: TControl; vShow: Boolean = True): TntvPageItem; function ExtractControl(vControl: TControl): TControl; property Items[Index: Integer]: TntvPageItem read GetItem write SetItem stored False; default; published end; { TntvPageControl } TntvPageControl = class(TntvCustomTabSet) private FMargin: Integer; procedure CMControlChange(var Message: TCMControlChange); message CM_CONTROLCHANGE; procedure SetMargin(const Value: Integer); procedure SetActiveControl(const Value: TControl); function GetActiveControl: TControl; function GetItems: TntvPages; procedure SetItems(Value: TntvPages); function GetPageItem(vControl: TControl): TntvPageItem; protected procedure Loaded; override; procedure Notification(AComponent: TComponent; Operation: TOperation); override; procedure CreateParams(var Params: TCreateParams); override; function CreateTabs: TntvTabs; override; procedure ShowControl(AControl: TControl); override; procedure AlignControls(AControl: TControl; var Rect: TRect); override; function GetPageRect: TRect; virtual; procedure BringControl(vControl: TControl; vSetFocus: Boolean); procedure DoTabShow(Index: Integer; vSetfocus: Boolean); override; procedure DoTabShowed(Index: Integer; vSetfocus: Boolean); override; class function GetControlClassDefaultSize: TSize; override; procedure WMKillFocus(var Msg: TWMKillFocus); message WM_KILLFOCUS; procedure WMSetFocus(var Msg: TLMSetFocus); message WM_SETFOCUS; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; function ActivableControl: TWinControl; procedure ActivateControl; property ActiveControl: TControl read GetActiveControl write SetActiveControl; property Page[Control: TControl]: TntvPageItem read GetPageItem; published property Margin: Integer read FMargin write SetMargin default 3; property ChildSizing; property BorderSpacing; property StoreIndex; property ShowButtons; property ShowTabs; property ShowBorder; property ItemIndex; property ImageList; property Items: TntvPages read GetItems write SetItems; property OnTabSelected; property OnTabSelect; property TabStyle; property TabPosition; property Align; property Anchors; property BiDiMode; property Color; property Constraints; property DockSite; property DragCursor; property DragKind; property DragMode; property Enabled; property Font; property ParentBiDiMode; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property TabOrder; property TabStop; property Visible; property OnClick; property OnContextPopup; property OnDblClick; property OnDragDrop; property OnDockDrop; property OnDockOver; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnGetSiteInfo; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDock; property OnStartDrag; property OnUnDock; end; implementation { TntvPageControl } constructor TntvPageControl.Create(AOwner: TComponent); begin inherited Create(AOwner); FMargin := 3; with GetControlClassDefaultSize do SetInitialBounds(0, 0, CX, CY); end; destructor TntvPageControl.Destroy; begin inherited; end; function TntvPageControl.ActivableControl: TWinControl; var aList: TFPList; i: Integer; begin Result := nil; if (ActiveControl is TWinControl) and (ActiveControl as TWinControl).CanFocus then begin aList := TFPList.Create; try (ActiveControl as TWinControl).GetTabOrderList(aList); aList.Add(ActiveControl as TWinControl); for i := 0 to aList.Count - 1 do begin if (TControl(aList[i]) as TWinControl).CanFocus and (TControl(aList[i]) as TWinControl).TabStop then begin Result := TControl(aList[i]) as TWinControl; break; end; end; finally aList.Free; end; end end; procedure TntvPageControl.ActivateControl; var ParentForm: TCustomForm; aList: TFPList; i: Integer; aControl: TWinControl; begin ParentForm := GetParentForm(Self); if ParentForm <> nil then begin aControl := ActivableControl; if aControl <> nil then ParentForm.ActiveControl := aControl end; end; procedure TntvPageControl.CreateParams(var Params: TCreateParams); begin inherited CreateParams(Params); with Params do begin Style := Style or WS_CLIPCHILDREN; WindowClass.style := WindowClass.style or (CS_HREDRAW or CS_VREDRAW); end; end; function TntvPageControl.CreateTabs: TntvTabs; begin Result := TntvPages.Create(TntvPageItem); (Result as TntvPages).Control := Self; end; procedure TntvPageControl.ShowControl(AControl: TControl); var i: Integer; begin if (AControl <> nil) and (AControl is TControl) then begin i := Items.IndexOf(AControl as TControl); if i >=0 then begin SelectTab(I); Exit; end; end; inherited; end; procedure TntvPageControl.AlignControls(AControl: TControl; var Rect: TRect); begin Rect := GetPageRect; inherited; end; procedure TntvPageControl.BringControl(vControl: TControl; vSetFocus: Boolean); begin if vControl <> nil then with vControl do begin BringToFront; Visible := True; if vControl.Parent = Self then Align := alClient; if not (csLoading in ComponentState) and (vSetFocus) and (not Self.Focused) and (vControl is TWinControl) then begin if not (csDesigning in ComponentState) then ActivateControl; end; end; end; procedure TntvPageControl.DoTabShow(Index: Integer; vSetfocus: Boolean); var i: Integer; begin inherited; if not (csDesigning in ComponentState) then for i := 0 to Items.Visibles.Count - 1 do //To sure all tabs controls is hidden if (Items.Visibles[i] as TntvPageItem).Control <> nil then (Items.Visibles[i] as TntvPageItem).Control.Visible := False; end; procedure TntvPageControl.DoTabShowed(Index: Integer; vSetfocus: Boolean); begin inherited; BringControl((Items.Visibles[Index] as TntvPageItem).Control, vSetfocus); end; procedure TntvPageControl.Notification(AComponent: TComponent; Operation: TOperation); begin inherited; if (Operation = opRemove) and (AComponent <> Self) and (AComponent is TControl) and (Items.FindControl((AComponent as TControl)) <> nil) then begin Items.ExtractControl(AComponent as TControl); end; end; procedure TntvPageControl.CMControlChange(var Message: TCMControlChange); begin inherited; with Message do begin if not (csLoading in ComponentState) then if Inserting then begin Items.AddControl(Control); ShowControl(Control); if Control.Parent = Self then Control.Align := alClient; Result := 1; end end; end; procedure TntvPageControl.SetMargin(const Value: Integer); begin if FMargin <> Value then begin FMargin := Value; Realign; end; end; function TntvPageControl.GetPageRect: TRect; begin Result := ClientRect; if ShowTabs then begin case TabPosition of tbpTop: Inc(Result.Top, GetHeaderHeight); tbpBottom: Dec(Result.Bottom, GetHeaderHeight); end; end; InflateRect(Result, -FMargin, -FMargin); end; procedure TntvPageControl.SetActiveControl(const Value: TControl); var i: Integer; begin for i := 0 to Items.Visibles.Count - 1 do begin if (Items.Visibles[i] as TntvPageItem).Control = Value then begin SelectTab(i, True); Break; end; end; end; function TntvPageControl.GetActiveControl: TControl; begin if (ItemIndex >= 0) and (ItemIndex < Items.Visibles.Count) then Result := (Items.Visibles[ItemIndex] as TntvPageItem).Control else Result := nil; end; procedure TntvPageItem.Assign(Source: TPersistent); begin if Source is TntvPageItem then begin end; inherited; end; constructor TntvPageItem.Create(vCollection: TCollection); begin inherited; if (vCollection <> nil) then begin if not (csLoading in PageControl.ComponentState) then begin Name := Format(PageControl.Name + '_Item%d', [Index]); Caption := Name; end; end; end; destructor TntvPageItem.Destroy; begin inherited; end; function TntvPageItem.GetPageControl: TntvPageControl; begin if Collection <> nil then Result := (Collection as TntvPages).FControl as TntvPageControl else Result := nil; end; procedure TntvPageItem.SetControl(const Value: TControl); begin if (FControl <> Value) then begin FControl := Value; if (Value <> nil) and (Value.Parent = PageControl) then FControl.Align := alClient; end; end; function TntvPageControl.GetPageItem(vControl: TControl): TntvPageItem; var i: Integer; begin Result := nil; for i := 0 to Items.Count - 1 do if Items[i].Control = vControl then begin Result := Items[i]; Break; end; end; procedure TntvPageControl.Loaded; begin inherited Loaded; end; function TntvPageControl.GetItems: TntvPages; begin Result := (inherited Items) as TntvPages; end; procedure TntvPageControl.SetItems(Value: TntvPages); begin inherited Items := Value; end; class function TntvPageControl.GetControlClassDefaultSize: TSize; begin Result.cx := 200; Result.cy := 240; end; procedure TntvPageControl.WMKillFocus(var Msg: TWMKillFocus); begin inherited; Invalidate; end; procedure TntvPageControl.WMSetFocus(var Msg: TLMSetFocus); begin inherited; Invalidate; end; { TntvPages } function TntvPages.Add: TntvPageItem; begin Result := TntvPageItem(inherited Add); end; function TntvPages.AddControl(vControl: TControl; vShow: Boolean): TntvPageItem; begin if vControl <> nil then begin BeginUpdate; try Result := TntvPageItem.Create(Self); with Result do begin Name := vControl.Name; Caption := Name; Control := vControl; // Collection := Self; //Add to Pages list; Or when Create(Self) the page Control.FreeNotification(PageControl); if (Control is TWinControl) and (Control.Parent = PageControl) then Control.Align := alClient; if not (csDesigning in Control.ComponentState) then begin if vShow then Control.Show end; end; finally EndUpdate; end; end else Result := nil; end; function TntvPages.ExtractControl(vControl: TControl): TControl; var i: Integer; c: Integer; begin Result := nil; for i := 0 to Count - 1 do if Items[i].Control = vControl then begin Result := Items[i].Control; Items[i].Control := nil; Delete(i); if not (csDestroying in Control.ComponentState) then begin c := i; if c > 0 then c := c - 1; PageControl.ShowTab(c); end; Break; end; end; function TntvPages.FindControl(vControl: TControl): TntvPageItem; var i: Integer; begin Result := nil; for i := 0 to Count - 1 do if Items[i].Control = vControl then begin Result := Items[i]; Break; end; end; function TntvPages.GetItem(Index: Integer): TntvPageItem; begin Result := (inherited Items[Index] as TntvPageItem); end; function TntvPages.GetPageControl: TntvPageControl; begin Result := Control as TntvPageControl; end; function TntvPages.GetOwner: TPersistent; begin Result := Control as TntvPageControl; end; procedure TntvPages.SetItem(Index: Integer; Value: TntvPageItem); begin inherited SetItem(Index, Value); end; function TntvPages.IndexOf(vControl: TControl): Integer; var i: Integer; begin Result := -1; for i := 0 to Count -1 do begin if Items[i].Control = vControl then begin Result := i; break; end; end; end; procedure TntvPageItem.SetIndex(Value: Integer); var ShowSelf: Boolean; begin if PageControl <> nil then ShowSelf := PageControl.ItemIndex = Index else ShowSelf := False; inherited; if PageControl <> nil then begin if ShowSelf then begin PageControl.ShowTab(Index, True); end else PageControl.ShowTab(PageControl.ItemIndex, True); end; end; end.
unit Main; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, System.Generics.Collections, System.IOUtils, Quick.Config.Json, FMX.StdCtrls, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo; type TMyPriority = (msLow, msMed, msHigh); TWinPos = record public PosX : Integer; PosY : Integer; end; TProcessType = record Id : Integer; Priority : TMyPriority; Redundant : Boolean; end; TWorker = class private fName : string; fActive : Boolean; published property Name : string read fName write fName; property Active : Boolean read fActive write fActive; end; TMyConfig = class(TAppConfigJson) private fTitle : string; fHidden : Boolean; fSessionName: string; fSizes : TArray<Integer>; fLastFilename : string; fWindowPos : TWinPos; fHistory : TArray<TProcessType>; fComplex : TProcessType; fModifyDate : TDateTime; fWorkList : TObjectList<TWorker>; published property Sizes : TArray<Integer> read fSizes write fSizes; property LastFilename : string read fLastFilename write fLastFilename; property WindowPos : TWinPos read fWindowPos write fWindowPos; property History : TArray<TProcessType> read fHistory write fHistory; property Complex : TProcessType read fComplex write fComplex; property ModifyDate : TDateTime read fModifyDate write fModifyDate; property Title : string read fTitle write fTitle; property SessionName : string read fSessionName write fSessionName; property WorkList : TObjectList<TWorker> read fWorkList write fWorkList; public destructor Destroy; override; procedure Init; override; procedure DefaultValues; override; end; TMainForm = class(TForm) meInfo: TMemo; Panel1: TPanel; btnLoadJson: TSpeedButton; btnSaveJson: TSpeedButton; procedure FormCreate(Sender: TObject); procedure SetConfig(cConfig: TMyConfig); function TestConfig(cConfig1, cConfig2 : TMyConfig) : Boolean; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnLoadJsonClick(Sender: TObject); procedure btnSaveJsonClick(Sender: TObject); procedure OnConfigFileModified; procedure OnConfigReloaded; end; var MainForm: TMainForm; ConfigTest : TMyConfig; ConfigJson : TMyConfig; implementation {$R *.fmx} procedure TMainForm.btnLoadJsonClick(Sender: TObject); var NewConfig : TMyConfig; begin meInfo.Lines.Add('Load ConfigReg'); NewConfig := TMyConfig.Create(ConfigJson.Provider.Filename,ConfigJson.Provider.ReloadIfFileChanged); try NewConfig.Load; meInfo.Lines.Add(NewConfig.ToJSON); if TestConfig(configtest,NewConfig) then meInfo.Lines.Add('Test passed successfully!'); finally NewConfig.Free; end; end; procedure TMainForm.btnSaveJsonClick(Sender: TObject); begin SetConfig(ConfigJson); ConfigJson.Save; meInfo.Lines.Add('Saved Config in Registry at ' + DateTimeToStr(ConfigJson.LastSaved)); end; procedure TMainForm.SetConfig(cConfig : TMyConfig); var winpos : TWinpos; protype : TProcessType; i : Integer; worker : TWorker; begin cConfig.LastFilename := 'library.txt'; cConfig.Sizes := [23,11,554,12,34,29,77,30,48,59,773,221,98,3,22,983,122,231,433,12,31,987]; winpos.PosX := 640; winpos.PosX := 480; cConfig.WindowPos := winpos; protype.Priority := msHigh; protype.Redundant := False; cConfig.Complex := protype; cConfig.Title := 'a fresh title'; cConfig.SessionName := 'First Session'; for I := 0 to 22 do begin worker := TWorker.Create; worker.Name := 'Process ' + i.ToString; worker.Active := Boolean(Random(1)); cConfig.WorkList.Add(worker); end; for i := 0 to 15 do begin protype.Id := i; protype.Priority := msLow; protype.Redundant := True; cConfig.History := cConfig.History + [protype]; end; cConfig.ModifyDate := Now(); end; function TMainForm.TestConfig(cConfig1, cConfig2 : TMyConfig) : Boolean; var i : Integer; begin Result := False; try Assert(cConfig1.LastFilename = cConfig2.LastFilename); for i := Low(cConfig1.Sizes) to High(cConfig1.Sizes) do Assert(cConfig1.Sizes[i] = cConfig2.Sizes[i]); Assert(cConfig1.WindowPos.PosX = cConfig2.WindowPos.PosX); Assert(cConfig1.WindowPos.PosX = cConfig2.WindowPos.PosX); Assert(cConfig1.Complex.Priority = cConfig2.Complex.Priority); Assert(cConfig1.Complex.Redundant = cConfig2.Complex.Redundant); Assert(cConfig1.Title = cConfig2.Title); for i := 0 to cConfig1.WorkList.Count - 1 do begin Assert(cConfig1.WorkList[i].Name = cConfig2.WorkList[i].Name); Assert(cConfig1.WorkList[i].Active = cConfig2.WorkList[i].Active); end; for i := 0 to High(cConfig1.History) do begin Assert(cConfig1.History[i].Priority = cConfig2.History[i].Priority); Assert(cConfig1.History[i].Redundant = cConfig2.History[i].Redundant); end; Result := True; except ShowMessage('Configuration not has been saved previously or has a corruption problem'); end; end; procedure TMainForm.FormClose(Sender: TObject; var Action: TCloseAction); begin if Assigned(ConfigJson) then ConfigJson.Free; if Assigned(ConfigTest) then ConfigTest.Free; end; procedure TMainForm.FormCreate(Sender: TObject); begin {$IF Defined(NEXTGEN) OR Defined(OSX)} ConfigJson := TMyConfig.Create(TPath.GetDocumentsPath + '/config.json'); {$ELSE} ConfigJson := TMyConfig.Create('.\config.json'); {$ENDIF} ConfigJson.Provider.OnFileModified := OnConfigFileModified; ConfigJson.Provider.OnConfigReloaded := OnConfigReloaded; ConfigJson.Provider.ReloadIfFileChanged := True; //create config test to compare later ConfigTest := TMyConfig.Create(''); SetConfig(ConfigTest); end; procedure TMainForm.OnConfigFileModified; begin meInfo.Lines.Add('Config modified'); end; procedure TMainForm.OnConfigReloaded; begin meInfo.Lines.Add('Config reloaded'); end; { TMyConfig } procedure TMyConfig.Init; begin inherited; WorkList := TObjectList<TWorker>.Create(True); end; procedure TMyConfig.DefaultValues; begin inherited; fTitle := 'Default value'; end; destructor TMyConfig.Destroy; begin if Assigned(WorkList) then WorkList.Free; inherited; end; end.
unit MemoChannel; { Copyright (C) 2006 Luiz Américo Pereira Câmara TMemoChannel contributed by Avra (Жељко Аврамовић). TMemoChannel was based on TFileChannel. This library is free software; you can redistribute it and/or modify it under the terms of the FPC modified LGPL licence which can be found at: http://wiki.lazarus.freepascal.org/FPC_modified_LGPL } {$ifdef fpc} {$mode objfpc}{$H+} {$endif} interface uses {$ifndef fpc}fpccompat,{$endif} Classes, SysUtils, StdCtrls, Forms, Math, MultiLog; const MEMO_MINIMAL_NUMBER_OF_TOTAL_LINES = 200; MEMO_MINIMAL_NUMBER_OF_LINES_TO_DELETE_AT_ONCE = 100; // must be lower or equal to MEMO_MINIMAL_NUMBER_OF_TOTAL_LINES type TLogMsgData = record Text: string; end; PLogMsgData = ^TLogMsgData; TMemoChannelOption = (mcoShowHeader, mcoShowPrefix, mcoShowTime, mcoUnlimitedBuffer, mcoRotateBuffer); TMemoChannelOptions = set of TMemoChannelOption; { TMemoChannel } TMemoChannel = class(TLogChannel) private FMemo: TMemo; FRelativeIdent: Integer; FBaseIdent: Integer; FShowHeader: Boolean; FShowTime: Boolean; FShowPrefix: Boolean; FUnlimitedBuffer: Boolean; FRotateBuffer: Boolean; FTimeFormat: String; FLogLinesLimit: Integer; FWrapper: TLogChannelWrapper; procedure SetLogLinesLimit(AValue: Integer); procedure SetShowTime(const AValue: Boolean); procedure UpdateIdentation; procedure Write(const AMsg: string); procedure WriteStrings(AStream: TStream); procedure WriteComponent(AStream: TStream); public constructor Create(AMemo: TMemo; AChannelOptions: TMemoChannelOptions = [mcoShowHeader, mcoShowTime]); destructor Destroy; override; procedure WriteAsyncQueue(Data: PtrInt); procedure Deliver(const AMsg: TLogMessage); override; procedure Init; override; procedure Clear; override; property ShowHeader: boolean read FShowHeader write FShowHeader; property ShowPrefix: boolean read FShowPrefix write FShowPrefix; property ShowTime: boolean read FShowTime write SetShowTime; property LogLinesLimit: integer read FLogLinesLimit write SetLogLinesLimit; property TimeFormat: String read FTimeFormat write FTimeFormat; end; implementation const LogPrefixes: array [ltInfo..ltCounter] of string = ( 'INFO', 'ERROR', 'WARNING', 'VALUE', '>>ENTER METHOD', '<<EXIT METHOD', 'CONDITIONAL', 'CHECKPOINT', 'STRINGS', 'CALL STACK', 'OBJECT', 'EXCEPTION', 'BITMAP', 'HEAP INFO', 'MEMORY', '', '', '', '', '', 'WATCH', 'COUNTER'); { TMemoChannel } constructor TMemoChannel.Create(AMemo: TMemo; AChannelOptions: TMemoChannelOptions); begin FMemo := AMemo; FWrapper := TLogChannelWrapper.Create(nil); FWrapper.Channel := Self; AMemo.FreeNotification(FWrapper); FShowPrefix := mcoShowPrefix in AChannelOptions; FShowTime := mcoShowTime in AChannelOptions; FShowHeader := mcoShowHeader in AChannelOptions; FUnlimitedBuffer := mcoUnlimitedBuffer in AChannelOptions; FRotateBuffer := mcoRotateBuffer in AChannelOptions; Active := True; FLogLinesLimit := MEMO_MINIMAL_NUMBER_OF_TOTAL_LINES; FTimeFormat := 'hh:nn:ss:zzz'; end; destructor TMemoChannel.Destroy; begin FWrapper.Destroy; inherited Destroy; end; procedure TMemoChannel.Write(const AMsg: string); var LogMsgToSend: PLogMsgData; begin New(LogMsgToSend); LogMsgToSend^.Text := AMsg; Application.QueueAsyncCall(@WriteAsyncQueue, PtrInt(LogMsgToSend)); // put log msg into queue that will be processed from the main thread after all other messages end; procedure TMemoChannel.WriteAsyncQueue(Data: PtrInt); var // called from main thread after all other messages have been processed to allow thread safe TMemo access ReceivedLogMsg: TLogMsgData; LineCount: Integer; begin ReceivedLogMsg := PLogMsgData(Data)^; try if (FMemo <> nil) and (not Application.Terminated) then begin if FMemo.Lines.Count > LogLinesLimit then begin if FRotateBuffer then begin FMemo.Lines.BeginUpdate; try // less flickering compared to deleting first line for each newly added line for LineCount := 1 to Max(LoglinesLimit div 10, MEMO_MINIMAL_NUMBER_OF_LINES_TO_DELETE_AT_ONCE) do FMemo.Lines.Delete(0); finally FMemo.Lines.EndUpdate; end; end else if not FUnlimitedBuffer then FMemo.Clear; // clear whole buffer when limit is reached end; FMemo.Append(ReceivedLogMsg.Text) end; finally Dispose(PLogMsgData(Data)); end; end; procedure TMemoChannel.UpdateIdentation; var S: string; begin S := ''; if FShowTime then S := FormatDateTime(FTimeFormat, Time); FBaseIdent := Length(S) + 3; end; procedure TMemoChannel.SetShowTime(const AValue: Boolean); begin FShowTime := AValue; UpdateIdentation; end; procedure TMemoChannel.SetLogLinesLimit(AValue: Integer); begin FLogLinesLimit := Max(Abs(AValue), MEMO_MINIMAL_NUMBER_OF_TOTAL_LINES); end; procedure TMemoChannel.WriteStrings(AStream: TStream); var i: integer; begin if AStream.Size = 0 then Exit; with TStringList.Create do try AStream.Position := 0; LoadFromStream(AStream); for i := 0 to Count - 1 do Write(Space(FRelativeIdent + FBaseIdent) + Strings[i]); finally Destroy; end; end; procedure TMemoChannel.WriteComponent(AStream: TStream); var TextStream: TStringStream; begin TextStream := TStringStream.Create(''); AStream.Seek(0, soFromBeginning); ObjectBinaryToText(AStream, TextStream); //todo: better handling of format Write(TextStream.DataString); TextStream.Destroy; end; procedure TMemoChannel.Deliver(const AMsg: TLogMessage); var WholeMsg: string; begin WholeMsg := ''; //Exit method identation must be set before if (AMsg.MsgType = ltExitMethod) and (FRelativeIdent >= 2) then Dec(FRelativeIdent, 2); try if FShowTime then WholeMsg := FormatDateTime(FTimeFormat, AMsg.MsgTime) + ' '; WholeMsg := WholeMsg + Space(FRelativeIdent); if FShowPrefix then WholeMsg := WholeMsg + (LogPrefixes[AMsg.MsgType] + ': '); Write(WholeMsg + AMsg.MsgText); if AMsg.Data <> nil then begin case AMsg.MsgType of ltStrings, ltCallStack, ltHeapInfo, ltException: WriteStrings(AMsg.Data); ltObject: WriteComponent(AMsg.Data); end; end; finally //Update enter method identation if AMsg.MsgType = ltEnterMethod then Inc(FRelativeIdent, 2); end; end; procedure TMemoChannel.Init; var BufferLimitedStr: string; begin if FRotateBuffer or not FUnlimitedBuffer then BufferLimitedStr := ' (buffer limited to ' + IntToStr(LogLinesLimit) + ' lines)' else BufferLimitedStr := ''; if FShowHeader then Write('=== Log Session Started at ' + DateTimeToStr(Now) + ' by ' + ApplicationName + BufferLimitedStr + ' ==='); UpdateIdentation; end; procedure TMemoChannel.Clear; begin // no need to implement this abstract method in TMemoChannel end; end.
unit nsDownloadService; interface uses Classes, l3ProtoObject, nsDownloaderInterfaces, nsAsyncDownloaderList, nsDownloadProgressDialogList; type TnsDownloadService = class(Tl3ProtoObject, InsDownloaderObserver) private FDownloaders: TnsAsyncDownloaderList; FProgressDialogs: TnsDownloadProgressDialogList; function GetProgressDialog(const ADownloader: InsAsyncDownloader): InsDownloadProgressDialog; procedure StartProgressDialog(const ADownloader: InsAsyncDownloader); procedure StopProgressDialog(const ADownloader: InsAsyncDownloader); procedure OpenFileIfNeeded(const ADownloader: InsAsyncDownloader); procedure DeleteFileIfNeeded(const ADownloader: InsAsyncDownloader); procedure DeleteDownloader(const ADownloader: InsAsyncDownloader); constructor Create; protected // InsDownloaderObserver procedure OnBeginDownloadData(const ADownloader: InsAsyncDownloader; var ACancel: Boolean); procedure OnProgress(const ADownloader: InsAsyncDownloader; AProgressValue: Integer; ATotalValue: Integer; var ACancel: Boolean); procedure OnEndDownloadData(const ADownloader: InsAsyncDownloader); procedure OnDownloadingCancelled(const ADownloader: InsAsyncDownloader); procedure Cleanup; override; public procedure DownloadFile(const AURL: String); class function Instance: TnsDownloadService; end; implementation uses SysUtils, Windows, ShellAPI, l3Base, nsDownloadManager, nsDownloaderGUIService, nsProgressDialog; var g_TnsDownloadServiceInstance: TnsDownloadService = nil; procedure TnsDownloadService_Free; begin FreeAndNil(g_TnsDownloadServiceInstance); end; function TnsDownloadService.GetProgressDialog(const ADownloader: InsAsyncDownloader): InsDownloadProgressDialog; var l_Index: Integer; l_Dlg: InsDownloadProgressDialog; begin Result := nil; for l_Index := Pred(FProgressDialogs.Count) downto 0 do begin l_Dlg := FProgressDialogs[l_Index] as InsDownloadProgressDialog; if (Pointer(l_Dlg.Downloader) = Pointer(ADownloader)) then begin Result := l_Dlg; Exit; end; end; end; procedure TnsDownloadService.StartProgressDialog(const ADownloader: InsAsyncDownloader); var l_Dlg: InsDownloadProgressDialog; begin l_Dlg := GetProgressDialog(ADownloader); end; procedure TnsDownloadService.StopProgressDialog(const ADownloader: InsAsyncDownloader); var l_Dlg: InsDownloadProgressDialog; begin l_Dlg := GetProgressDialog(ADownloader); Assert(l_Dlg <> nil); l_Dlg.StopProgressDialog; FProgressDialogs.Remove(l_Dlg); end; procedure TnsDownloadService.OpenFileIfNeeded(const ADownloader: InsAsyncDownloader); procedure lp_ShellExecute(const AFileName: string); var l_ShellExecuteInfo: {$IfDef XE}TShellExecuteInfoA{$Else}TShellExecuteInfo{$EndIf}; l_Handle: THandle; l_FindData: {$IfDef XE}TWin32FindDataA{$Else}TWin32FindData{$EndIf}; begin l3FillChar(l_ShellExecuteInfo, SizeOf(l_ShellExecuteInfo), 0); //http://mdp.garant.ru/pages/viewpage.action?pageId=431371899 with l_ShellExecuteInfo do begin cbSize := SizeOf(l_ShellExecuteInfo); lpFile := PAnsiChar(AFileName); nShow := SW_SHOWNORMAL; end;//with l_ShellExecuteInfo ShellExecuteExA(@l_ShellExecuteInfo); end; var l_FileName: String; begin if (ADownloader.DownloadParams.FileAction = dfaOpen) then begin l_FileName := ADownloader.DownloadParams.FileName; if FileExists(l_FileName) then lp_ShellExecute(l_FileName); end; end; procedure TnsDownloadService.DeleteFileIfNeeded(const ADownloader: InsAsyncDownloader); begin DeleteFile(PChar(ADownloader.DownloadParams.FileName)); end; procedure TnsDownloadService.DeleteDownloader(const ADownloader: InsAsyncDownloader); begin FDownloaders.Remove(ADownloader); end; constructor TnsDownloadService.Create; begin inherited; FDownloaders := TnsAsyncDownloaderList.Create; FProgressDialogs := TnsDownloadProgressDialogList.Create; end; procedure TnsDownloadService.OnBeginDownloadData(const ADownloader: InsAsyncDownloader; var ACancel: Boolean); begin StartProgressDialog(ADownloader); end; procedure TnsDownloadService.OnProgress(const ADownloader: InsAsyncDownloader; AProgressValue: Integer; ATotalValue: Integer; var ACancel: Boolean); begin with ADownloader.State do begin Total := ATotalValue; Current := AProgressValue; if CancelledByUser then ACancel := True; end; end; procedure TnsDownloadService.OnEndDownloadData(const ADownloader: InsAsyncDownloader); begin StopProgressDialog(ADownloader); OpenFileIfNeeded(ADownloader); ADownloader.Unsubscribe(Self); DeleteDownloader(ADownloader); end; procedure TnsDownloadService.OnDownloadingCancelled(const ADownloader: InsAsyncDownloader); begin StopProgressDialog(ADownloader); DeleteFileIfNeeded(ADownloader); ADownloader.Unsubscribe(Self); DeleteDownloader(ADownloader); end; procedure TnsDownloadService.Cleanup; begin FreeAndNil(FDownloaders); FreeAndNil(FProgressDialogs); inherited; end; procedure TnsDownloadService.DownloadFile(const AURL: String); var l_Params: InsDownloadParams; l_Downloader: InsAsyncDownloader; l_ProgressDialog: InsDownloadProgressDialog; begin Assert(FDownloaders <> nil); l_Params := TnsDownloadParams.Make(AURL, dfaOpen); if TnsDownloaderGUIService.Instance.EditParams(l_Params) then begin if (l_Params.FileAction = dfaSaveAs) then Exit; l_Downloader := TnsAsyncDownloader.Make(l_Params); Assert(l_Downloader <> nil); FDownloaders.Add(l_Downloader); l_Downloader.Subscribe(Self); l_ProgressDialog := TnsDownloadProgressDialog.Make(l_Downloader); FProgressDialogs.Add(l_ProgressDialog); l_Downloader.StartDownload; end; end; class function TnsDownloadService.Instance: TnsDownloadService; begin if (g_TnsDownloadServiceInstance = nil) then begin g_TnsDownloadServiceInstance := Create; l3System.AddExitProc(TnsDownloadService_Free); end; Result := g_TnsDownloadServiceInstance; end; end.
unit ufrmPenerimaanBarang; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufrmDefault, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, ActnList, dxBar, cxClasses, ExtCtrls, dxStatusBar, ComCtrls, StdCtrls, cxContainer, cxEdit, cxMemo, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, cxMaskEdit, cxCalendar, cxTextEdit, cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridLevel, cxGrid, cxCurrencyEdit, ImgList, uModel, ClientClassesUnit, DB, cxDBData, cxGridDBTableView, cxDBExtLookupComboBox, Provider, DBClient, cxNavigator, dxCore, cxDateUtils, System.Actions, dxBarExtDBItems, cxCheckBox, cxBarEditItem, System.ImageList, dxBarExtItems, cxCalc, dxBarBuiltInMenu, Vcl.Menus, cxButtons, cxPC,uDMReport, Data.FireDACJSONReflect, uPenerimaanBarang, uSupplier; type TfrmPenerimaanBarang = class(TfrmDefault) pnlTransaksi: TPanel; pgcHeader: TPageControl; tsHeader: TTabSheet; lblNoBukti: TLabel; lblTglBukti: TLabel; lblSupplier: TLabel; lblKeterangan: TLabel; pgcDetail: TPageControl; tsDetailPenerimaan: TTabSheet; cxgrdlvlPenerimaanBarang: TcxGridLevel; cxGridDBPenerimaanBarang: TcxGrid; cxGridTablePenerimaanBarang: TcxGridTableView; cxGridTablePenerimaanBarangColumnSKU: TcxGridColumn; cxGridTablePenerimaanBarangColumnNama: TcxGridColumn; cxGridTablePenerimaanBarangColumnSatuan: TcxGridColumn; cxGridTablePenerimaanBarangColumnHarga: TcxGridColumn; cxGridTablePenerimaanBarangColumnQty: TcxGridColumn; cxGridTablePenerimaanBarangColumnDiskon: TcxGridColumn; cxGridTablePenerimaanBarangColumnPPN: TcxGridColumn; cxGridTablePenerimaanBarangColumnTotal: TcxGridColumn; edNoBukti: TcxTextEdit; edTglBukti: TcxDateEdit; memKeterangan: TcxMemo; cxGridDBTableSupplier: TcxGridDBTableView; cxgrdbclmnGridDBTableSupplierColumnNama: TcxGridDBColumn; cxgrdbclmnGridDBTableSupplierColumnKode: TcxGridDBColumn; cbbSupplier: TcxExtLookupComboBox; cxGridDBTableSKU: TcxGridDBTableView; cxgrdbclmnGridDBTableSKUColumnSKU: TcxGridDBColumn; cxgrdbclmnGridDBTableSKUColumnNama: TcxGridDBColumn; cxGridDBTableUOM: TcxGridDBTableView; cxgrdbclmnGridDBTableUOMColumnUOM: TcxGridDBColumn; cxGridTablePenerimaanBarangColumnDiskonRp: TcxGridColumn; cxGridTablePenerimaanBarangColumnPPNRp: TcxGridColumn; cxGridTablePenerimaanBarangColumnSubTotalRp: TcxGridColumn; pnlFilterBarang: TPanel; dsPB: TDataSource; ProvPB: TDataSetProvider; cdsPB: TClientDataSet; DSPSlip: TDataSetProvider; cdsSlip: TClientDataSet; cxgrdbclmnGridDBTableUOMColumnID: TcxGridDBColumn; lblGudang: TLabel; cbbGudang: TcxExtLookupComboBox; cxGridDBTableGudang: TcxGridDBTableView; cxGridColGudangKode: TcxGridDBColumn; cxGridColGudangNama: TcxGridDBColumn; lblJenisPembayaran: TLabel; lblTempo: TLabel; edTempo: TcxCalcEdit; cbbJenisPembayaran: TcxComboBox; procedure actCetakExecute(Sender: TObject); procedure ActionBaruExecute(Sender: TObject); procedure ActionHapusExecute(Sender: TObject); procedure ActionRefreshExecute(Sender: TObject); procedure ActionSimpanExecute(Sender: TObject); procedure cbbJenisPembayaranExit(Sender: TObject); procedure FormShow(Sender: TObject); procedure cxGridTablePenerimaanBarangColumnSKUPropertiesValidate( Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); procedure cxGridTablePenerimaanBarangColumnNamaPropertiesValidate( Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); procedure cxGridTablePenerimaanBarangColumnHargaPropertiesValidate( Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); procedure cxGridTablePenerimaanBarangColumnQtyPropertiesValidate( Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); procedure cxGridTablePenerimaanBarangColumnDiskonPropertiesValidate( Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); procedure cxGridTablePenerimaanBarangColumnPPNPropertiesValidate( Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); procedure cxGridDBTableDaftarPBEditing(Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem; var AAllow: Boolean); procedure cxGridTablePenerimaanBarangColumnSatuanPropertiesInitPopup( Sender: TObject); procedure cbbJenisPembayaranPropertiesChange(Sender: TObject); procedure cxGridDBTableOverviewCellDblClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); private FPenerimaanBarang: TPenerimaanBarang; function GetPenerimaanBarang: TPenerimaanBarang; procedure HitungNilaiNilaiPerBaris(dNilai: Double; Acolumn : Integer); procedure InisialisasiSupplier; procedure InisialisasiSKU; procedure InisialisasiGudang; procedure InisialisasiUOM; function IsBisaHapus : Boolean; function IsBisaSimpan: Boolean; function IsDetailValid: Boolean; { Private declarations } protected procedure CetakSlip; override; property PenerimaanBarang: TPenerimaanBarang read GetPenerimaanBarang write FPenerimaanBarang; public procedure LoadDataPenerimaanBarang(ANoBukti : String); { Public declarations } end; var frmPenerimaanBarang: TfrmPenerimaanBarang; implementation uses ClientModule, uDBUtils, uAppUtils, uBarangUtils, uReport,System.Math; {$R *.dfm} procedure TfrmPenerimaanBarang.actCetakExecute(Sender: TObject); begin inherited; // CetakSlip; // lReport := TTSReport.Create(Self); // try // if cxPCData.ActivePageIndex = 0 then // DSPSlip.DataSet := ClientDataModule.ServerPenerimaanBarangClient.RetrieveCDSlip(cxGridDBTableOverview.DS.FieldByName('ID').AsString) // else // DSPSlip.DataSet := ClientDataModule.ServerPenerimaanBarangClient.RetrieveCDSlip(PenerimaanBarang.ID); // // cdsSlip := TClientDataSet.Create(lReport); // cdsSlip.SetProvider(DSPSlip); // cdsSlip.Open; // // // // cxGridDBTableDaftarPB.SetDataset(cdsSlip); // lReport.AddDataset(TDBUtils.OpenDataset('select * from tcabang')); // lReport.AddDataset(cdsSlip); // lReport.ShowReport('SlipPenerimaanBarang'); // finally // lReport.Free; // end; end; procedure TfrmPenerimaanBarang.ActionBaruExecute(Sender: TObject); begin inherited; with TServerPenerimaanBarangClient.Create(ClientDataModule.DSRestConnection, False) do begin try // FID := ''; edNoBukti.Text := GenerateNoBukti(edTglBukti.Date, ClientDataModule.Cabang.Kode); cbbJenisPembayaran.ItemIndex := 0; edTempo.Value := 0; edTempo.Visible := False; lblTempo.Visible := False; cxGridTablePenerimaanBarang.ClearRows; memKeterangan.Clear; FreeAndNil(FPenerimaanBarang); finally Free; end; end; end; procedure TfrmPenerimaanBarang.ActionHapusExecute(Sender: TObject); begin inherited; if not IsBisaHapus then Exit; if ClientDataModule.ServerPenerimaanBarangClient.Delete(PenerimaanBarang) then begin ActionRefreshExecute(Sender); ActionBaruExecute(Sender); end; end; procedure TfrmPenerimaanBarang.ActionRefreshExecute(Sender: TObject); var lcds: TClientDataSet; begin inherited; if chkKonsolidasi1.Checked then lcds := TDBUtils.DSToCDS(ClientDataModule.ServerPenerimaanBarangClient.RetrievePenerimaan(dtpAwal.DateTime, dtpAkhir.DateTime, ''), Self) else lcds := TDBUtils.DSToCDS(ClientDataModule.ServerPenerimaanBarangClient.RetrievePenerimaan(dtpAwal.DateTime, dtpAkhir.DateTime, ClientDataModule.Cabang.ID), Self); cxGridDBTableOverview.SetDataset(lcds, True); cxGridDBTableOverview.ApplyBestFit(); cxGridDBTableOverview.SetVisibleColumns(['ID', 'CABANGID'], False); end; procedure TfrmPenerimaanBarang.ActionSimpanExecute(Sender: TObject); var i: Integer; lPenerimaanBarangItem: TPenerimaanBarangItem; begin inherited; if not IsBisaSimpan then Exit; with TServerPenerimaanBarangClient.Create(ClientDataModule.DSRestConnection, False) do begin try // PenerimaanBarang.ID := FID; PenerimaanBarang.NoBukti := edNoBukti.Text; PenerimaanBarang.Keterangan := memKeterangan.Text; PenerimaanBarang.Supplier := TSupplier.CreateID(cbbSupplier.EditValue); PenerimaanBarang.Gudang := TGudang.CreateID(cbbGudang.EditValue); PenerimaanBarang.TglBukti := edTglBukti.Date; PenerimaanBarang.JenisPembayaran := cbbJenisPembayaran.Text; if PenerimaanBarang.JenisPembayaran = 'CASH' then PenerimaanBarang.Tempo := 0 else PenerimaanBarang.Tempo := Floor(EdTempo.Value); PenerimaanBarang.Cabang := TCabang.CreateID(ClientDataModule.Cabang.ID); PenerimaanBarang.PenerimaanBarangItems.Clear; for i := 0 to cxGridTablePenerimaanBarang.DataController.RecordCount - 1 do begin lPenerimaanBarangItem := TPenerimaanBarangItem.Create; lPenerimaanBarangItem.Barang := TBarang.Create; lPenerimaanBarangItem.Barang.ID := cxGridTablePenerimaanBarang.GetString(i, cxGridTablePenerimaanBarangColumnSKU.Index); lPenerimaanBarangItem.Diskon := cxGridTablePenerimaanBarang.GetDouble(i, cxGridTablePenerimaanBarangColumnDiskon.Index); lPenerimaanBarangItem.HargaBeli := cxGridTablePenerimaanBarang.GetDouble(i, cxGridTablePenerimaanBarangColumnHarga.Index); lPenerimaanBarangItem.PPN := cxGridTablePenerimaanBarang.GetDouble(i, cxGridTablePenerimaanBarangColumnPPN.Index); lPenerimaanBarangItem.Qty := cxGridTablePenerimaanBarang.GetDouble(i, cxGridTablePenerimaanBarangColumnQty.Index); lPenerimaanBarangItem.UOM := TUOM.Create; lPenerimaanBarangItem.UOM.ID := cxGridTablePenerimaanBarang.GetString(i, cxGridTablePenerimaanBarangColumnSatuan.Index); lPenerimaanBarangItem.Konversi := TBarangUtils.KonversiUOM(lPenerimaanBarangItem.Barang.ID, lPenerimaanBarangItem.UOM.ID); lPenerimaanBarangItem.PenerimaanBarang := PenerimaanBarang; PenerimaanBarang.PenerimaanBarangItems.Add(lPenerimaanBarangItem); end; if Save(PenerimaanBarang) then begin ActionBaruExecute(Sender); end; finally FreeAndNil(FPenerimaanBarang); Free; end; end; end; procedure TfrmPenerimaanBarang.cbbJenisPembayaranExit(Sender: TObject); begin inherited; edTempo.Visible := cbbJenisPembayaran.ItemIndex = 1; lblTempo.Visible:= cbbJenisPembayaran.ItemIndex = 1; end; procedure TfrmPenerimaanBarang.cbbJenisPembayaranPropertiesChange( Sender: TObject); begin inherited; edTempo.Visible := cbbJenisPembayaran.ItemIndex = 1; lblTempo.Visible:= cbbJenisPembayaran.ItemIndex = 1; end; procedure TfrmPenerimaanBarang.CetakSlip; var lcds: TFDJSONDataSets; // lcds: TClientDataSet; begin inherited; with dmReport do begin AddReportVariable('UserCetak', UserAplikasi.UserName); if cxPCData.ActivePageIndex = 0 then lcds := ClientDataModule.ServerPenerimaanBarangClient.RetrieveCDSlip(cxGridDBTableOverview.DS.FieldByName('ID').AsString) else lcds := ClientDataModule.ServerPenerimaanBarangClient.RetrieveCDSlip(PenerimaanBarang.ID); ExecuteReport( 'Reports/Slip_PenerimaanBarang' , lcds ); end; end; procedure TfrmPenerimaanBarang.cxGridDBTableDaftarPBEditing( Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem; var AAllow: Boolean); begin inherited; AAllow := False; end; procedure TfrmPenerimaanBarang.cxGridDBTableOverviewCellDblClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); begin inherited; LoadDataPenerimaanBarang(cxGridDBTableOverview.DS.FieldByName('ID').AsString); cxPCData.ActivePageIndex := 1; end; procedure TfrmPenerimaanBarang.cxGridTablePenerimaanBarangColumnDiskonPropertiesValidate( Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); var dNilai: Double; begin inherited; dNilai := DisplayValue; HitungNilaiNilaiPerBaris(dNilai, cxGridTablePenerimaanBarangColumnDiskon.Index); end; procedure TfrmPenerimaanBarang.cxGridTablePenerimaanBarangColumnHargaPropertiesValidate( Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); var dNilai: Double; begin inherited; dNilai := DisplayValue; HitungNilaiNilaiPerBaris(dNilai, cxGridTablePenerimaanBarangColumnHarga.Index); end; procedure TfrmPenerimaanBarang.cxGridTablePenerimaanBarangColumnNamaPropertiesValidate( Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); var sID: string; begin inherited; sID := cxGridDBTableSKU.DataController.DataSource.DataSet.FieldByName('ID').AsString; cxGridTablePenerimaanBarang.DataController.Values[cxGridTablePenerimaanBarang.DataController.FocusedRecordIndex, cxGridTablePenerimaanBarangColumnSKU.Index] := sID; end; procedure TfrmPenerimaanBarang.cxGridTablePenerimaanBarangColumnPPNPropertiesValidate( Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); var dNilai: Double; begin inherited; dNilai := DisplayValue; HitungNilaiNilaiPerBaris(dNilai, cxGridTablePenerimaanBarangColumnPPN.Index); end; procedure TfrmPenerimaanBarang.cxGridTablePenerimaanBarangColumnQtyPropertiesValidate( Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); var dNilai: Double; begin inherited; dNilai := DisplayValue; HitungNilaiNilaiPerBaris(dNilai, cxGridTablePenerimaanBarangColumnQty.Index); end; procedure TfrmPenerimaanBarang.cxGridTablePenerimaanBarangColumnSatuanPropertiesInitPopup( Sender: TObject); var lBrg: TBarang; sIDBarang: string; i: Integer; begin inherited; sIDBarang := cxGridTablePenerimaanBarang.GetString(cxGridTablePenerimaanBarang.DataController.FocusedRecordIndex, cxGridTablePenerimaanBarangColumnSKU.Index); if sIDBarang = '' then Exit; with cxGridDBTableUOM.DataController.Filter do begin BeginUpdate; lBrg := TBarang.Create; TDBUtils.LoadFromDB(lBrg, sIDBarang); try Root.Clear; Root.BoolOperatorKind := fboOr; for i := 0 to lBrg.BarangSatuanItems.Count - 1 do begin Root.AddItem(cxgrdbclmnGridDBTableUOMColumnID, foEqual,lBrg.BarangSatuanItems[i].UOM.ID, lBrg.BarangSatuanItems[i].UOM.ID); end; DataController.Filter.Active := True; finally EndUpdate; lBrg.Free; end; end; end; procedure TfrmPenerimaanBarang.cxGridTablePenerimaanBarangColumnSKUPropertiesValidate( Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); var sID: string; begin inherited; sID := cxGridDBTableSKU.DataController.DataSource.DataSet.FieldByName('ID').AsString; cxGridTablePenerimaanBarang.DataController.Values[cxGridTablePenerimaanBarang.DataController.FocusedRecordIndex, cxGridTablePenerimaanBarangColumnNama.Index] := sID; end; procedure TfrmPenerimaanBarang.FormShow(Sender: TObject); begin inherited; InisialisasiSupplier; InisialisasiSKU; InisialisasiUOM; InisialisasiGudang; edTglBukti.Date := Now; ActionBaruExecute(Sender); end; function TfrmPenerimaanBarang.GetPenerimaanBarang: TPenerimaanBarang; begin if FPenerimaanBarang = nil then FPenerimaanBarang := TPenerimaanBarang.Create; Result := FPenerimaanBarang; end; procedure TfrmPenerimaanBarang.HitungNilaiNilaiPerBaris(dNilai: Double; Acolumn : Integer); var dDiskon: Double; dHarga: Double; dPPN: Double; dQty: Double; begin dHarga := 0; dQty := 0; dDiskon := 0; dPPN := 0; // Exit; with cxGridTablePenerimaanBarang do begin if Acolumn = cxGridTablePenerimaanBarangColumnHarga.Index then begin dHarga := dNilai; dQty := GetDouble(DataController.FocusedRecordIndex, cxGridTablePenerimaanBarangColumnQty.Index); dDiskon := GetDouble(DataController.FocusedRecordIndex, cxGridTablePenerimaanBarangColumnDiskon.Index); dPPN := GetDouble(DataController.FocusedRecordIndex, cxGridTablePenerimaanBarangColumnPPN.Index); end else if Acolumn = cxGridTablePenerimaanBarangColumnQty.Index then begin dHarga := GetDouble(DataController.FocusedRecordIndex, cxGridTablePenerimaanBarangColumnHarga.Index); dQty := dNilai; dDiskon := GetDouble(DataController.FocusedRecordIndex, cxGridTablePenerimaanBarangColumnDiskon.Index); dPPN := GetDouble(DataController.FocusedRecordIndex, cxGridTablePenerimaanBarangColumnPPN.Index); end else if Acolumn = cxGridTablePenerimaanBarangColumnDiskon.Index then begin dHarga := GetDouble(DataController.FocusedRecordIndex, cxGridTablePenerimaanBarangColumnHarga.Index); dQty := GetDouble(DataController.FocusedRecordIndex, cxGridTablePenerimaanBarangColumnQty.Index); dDiskon := dNilai; dPPN := GetDouble(DataController.FocusedRecordIndex, cxGridTablePenerimaanBarangColumnPPN.Index); end else if Acolumn = cxGridTablePenerimaanBarangColumnPPN.Index then begin dHarga := GetDouble(DataController.FocusedRecordIndex, cxGridTablePenerimaanBarangColumnHarga.Index); dQty := GetDouble(DataController.FocusedRecordIndex, cxGridTablePenerimaanBarangColumnQty.Index); dDiskon := GetDouble(DataController.FocusedRecordIndex, cxGridTablePenerimaanBarangColumnDiskon.Index); dPPN := dNilai; end; SetValue(DataController.FocusedRecordIndex, cxGridTablePenerimaanBarangColumnSubTotalRp.Index, dHarga * dQty); SetValue(DataController.FocusedRecordIndex, cxGridTablePenerimaanBarangColumnDiskonRp.Index, dHarga * dDiskon / 100 * dQty); SetValue(DataController.FocusedRecordIndex, cxGridTablePenerimaanBarangColumnPPNRp.Index, dHarga * (100 - dDiskon) / 100 * dQty * dPPN / 100); SetValue(DataController.FocusedRecordIndex, cxGridTablePenerimaanBarangColumnTotal.Index, dHarga * (100 - dDiskon) / 100 * dQty * (dPPN + 100) / 100); end; end; procedure TfrmPenerimaanBarang.InisialisasiSKU; var sSQL: string; begin sSQL := 'select * from tBarang'; cxGridDBTableSKU.SetDataset(sSQL); end; procedure TfrmPenerimaanBarang.InisialisasiSupplier; var sSQL: string; begin sSQL := 'select * from tsupplier'; cxGridDBTableSupplier.SetDataset(sSQL); end; procedure TfrmPenerimaanBarang.InisialisasiGudang; var sSQL: string; begin sSQL := 'select * from tgudang' + ' where cabang = ' + QuotedStr(ClientDataModule.Cabang.ID); cxGridDBTableGudang.SetDataset(sSQL); end; procedure TfrmPenerimaanBarang.InisialisasiUOM; var sSQL: string; begin sSQL := 'select * from tuom'; cxGridDBTableUOM.SetDataset(sSQL); end; function TfrmPenerimaanBarang.IsBisaHapus: Boolean; begin Result := False; if not TAppUtils.Confirm('Anda yakin akan menghapus Data ?') then Exit; Result := True; end; function TfrmPenerimaanBarang.IsBisaSimpan: Boolean; begin Result := False; if not ValidateEmptyCtrl([1]) then Exit; if cbbSupplier.EditValue = null then begin TAppUtils.Warning('Supplier Belum Dipilih'); Exit; end else if cbbGudang.EditValue = null then begin TAppUtils.Warning('Gudang Belum Dipilih'); Exit; end else if not IsDetailValid then begin Exit; end; Result := True; end; function TfrmPenerimaanBarang.IsDetailValid: Boolean; var I: Integer; begin Result := False; if cxGridTablePenerimaanBarang.DataController.RecordCount <= 0 then begin TAppUtils.Warning('Detail Penerimaan Belum Diisi'); Exit; end else begin for I := 0 to cxGridTablePenerimaanBarang.DataController.RecordCount - 1 do begin if cxGridTablePenerimaanBarang.DataController.Values[i, cxGridTablePenerimaanBarangColumnSKU.Index] = null then begin TAppUtils.Warning('SKU Baris ke ' + IntToStr(i+1) + ' Belum Diisi'); Exit; end else if cxGridTablePenerimaanBarang.DataController.Values[i, cxGridTablePenerimaanBarangColumnSatuan.Index] = null then begin TAppUtils.Warning('UOM Baris ke ' + IntToStr(i+1) + ' Belum Diisi'); Exit; end else if cxGridTablePenerimaanBarang.DataController.Values[i, cxGridTablePenerimaanBarangColumnHarga.Index] = null then begin TAppUtils.Warning('Harga Baris ke ' + IntToStr(i+1) + ' Belum Diisi'); Exit; end else if cxGridTablePenerimaanBarang.DataController.Values[i, cxGridTablePenerimaanBarangColumnHarga.Index] <= 0 then begin TAppUtils.Warning('Harga Baris ke ' + IntToStr(i+1) + ' Belum Diisi'); Exit; end else if cxGridTablePenerimaanBarang.DataController.Values[i, cxGridTablePenerimaanBarangColumnQty.Index] = null then begin TAppUtils.Warning('Qty Baris ke ' + IntToStr(i+1) + ' Belum Diisi'); Exit; end else if cxGridTablePenerimaanBarang.DataController.Values[i, cxGridTablePenerimaanBarangColumnQty.Index] <= 0 then begin TAppUtils.Warning('Qty Baris ke ' + IntToStr(i+1) + ' Belum Diisi'); Exit; end; end; end; Result := True; end; procedure TfrmPenerimaanBarang.LoadDataPenerimaanBarang(ANoBukti : String); var i: Integer; begin with TServerPenerimaanBarangClient.Create(ClientDataModule.DSRestConnection, False) do begin try FreeAndNil(FPenerimaanBarang); FPenerimaanBarang := Retrieve(ANoBukti); // FID := PenerimaanBarang.ID; if PenerimaanBarang <> nil then begin edNoBukti.Text := PenerimaanBarang.NoBukti; edTglBukti.Date:= PenerimaanBarang.TglBukti; if PenerimaanBarang.Supplier.ID <> '' then cbbSupplier.EditValue := PenerimaanBarang.Supplier.ID; if PenerimaanBarang.Gudang.ID <> '' then cbbGudang.EditValue := PenerimaanBarang.Gudang.ID; memKeterangan.Lines.Text := PenerimaanBarang.Keterangan; edTempo.Value := PenerimaanBarang.Tempo; cbbJenisPembayaran.ItemIndex := cbbJenisPembayaran.Properties.Items.IndexOf(PenerimaanBarang.JenisPembayaran); cxGridTablePenerimaanBarang.ClearRows; for i := 0 to PenerimaanBarang.PenerimaanBarangItems.Count - 1 do begin cxGridTablePenerimaanBarang.DataController.RecordCount := i + 1; cxGridTablePenerimaanBarang.SetValue(i, cxGridTablePenerimaanBarangColumnSKU.Index, FPenerimaanBarang.PenerimaanBarangItems[i].Barang.ID); cxGridTablePenerimaanBarang.SetValue(i, cxGridTablePenerimaanBarangColumnNama.Index, FPenerimaanBarang.PenerimaanBarangItems[i].Barang.ID); cxGridTablePenerimaanBarang.SetValue(i, cxGridTablePenerimaanBarangColumnSatuan.Index, FPenerimaanBarang.PenerimaanBarangItems[i].UOM.ID); cxGridTablePenerimaanBarang.SetDouble(i, cxGridTablePenerimaanBarangColumnHarga.Index, FPenerimaanBarang.PenerimaanBarangItems[i].HargaBeli); cxGridTablePenerimaanBarang.SetDouble(i, cxGridTablePenerimaanBarangColumnQty.Index, FPenerimaanBarang.PenerimaanBarangItems[i].Qty); cxGridTablePenerimaanBarang.SetDouble(i, cxGridTablePenerimaanBarangColumnDiskon.Index,FPenerimaanBarang.PenerimaanBarangItems[i].Diskon); cxGridTablePenerimaanBarang.SetDouble(i, cxGridTablePenerimaanBarangColumnPPN.Index, FPenerimaanBarang.PenerimaanBarangItems[i].PPN); cxGridTablePenerimaanBarang.DataController.FocusedRecordIndex := i; HitungNilaiNilaiPerBaris(FPenerimaanBarang.PenerimaanBarangItems[i].PPN, cxGridTablePenerimaanBarangColumnPPN.Index); end; end; finally Free; end; end; end; end.
unit newmemo; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ComCtrls; const KEYWORDLIST_SIZE = 1; KeywordList : array [0..KEYWORDLIST_SIZE] of String = ('^XA', '^XZ'); type // Interjected Class TMemo = class(stdctrls.TMemo) private procedure WMPaint(var Message: TWMPaint); message WM_PAINT; procedure WMSize(var Message: TWMSize); message WM_SIZE; procedure WMMove(var Message: TWMMove); message WM_MOVE; procedure WMVScroll(var Message: TWMMove); message WM_VSCROLL; procedure WMMousewheel(var Message: TWMMove); message WM_MOUSEWHEEL; protected procedure Change; override; procedure KeyDown(var Key: Word; Shift: TShiftState); override; procedure KeyUp(var Key: Word; Shift: TShiftState); override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; public PosLabel: TLabel; procedure Update_label; procedure GotoXY(mCol, mLine: Integer); function Line: Integer; function Col: Integer; function TopLine: Integer; function VisibleLines: Integer; end; implementation //////////////////////////////////////////////////////////////////////////////// // functions for managing keywords and numbers of each line of TMemo /////////// //////////////////////////////////////////////////////////////////////////////// function IsSeparator(Car: Char): Boolean; begin case Car of '.', ';', ',', ':', '¡', '!', '·', '"', '''', '^', '+', '-', '*', '/', '\', '¨', ' ', '`', '[', ']', '(', ')', 'º', 'ª', '{', '}', '?', '¿', '%', '=': Result := True; else Result := False; end; end; //////////////////////////////////////////////////////////////////////////////// function NextWord(var s: string; var PrevWord: string): string; begin Result := ''; PrevWord := ''; if s = '' then Exit; while (s <> '') and IsSeparator(s[1]) do begin PrevWord := PrevWord + s[1]; Delete(s, 1,1); end; while (s <> '') and not IsSeparator(s[1]) do begin Result := Result + s[1]; Delete(s, 1,1); end; end; //////////////////////////////////////////////////////////////////////////////// function IsKeyWord(s: string): Boolean; var i : byte; begin Result := False; if s = '' then Exit; for i := 0 to KEYWORDLIST_SIZE do begin if KeywordList[i] = s then Result := True; end; end; //////////////////////////////////////////////////////////////////////////////// function IsNumber(s: string): Boolean; var i: Integer; begin Result := False; for i := 1 to Length(s) do case s[i] of '0'..'9':; else Exit; end; Result := True; end; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // New or overrided methods and properties for TMemo using Interjected Class /// // Technique /////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// function TMemo.VisibleLines: Integer; begin Result := Height div (Abs(Self.Font.Height) + 2); end; //////////////////////////////////////////////////////////////////////////////// procedure TMemo.GotoXY(mCol, mLine: Integer); begin Dec(mLine); SelStart := 0; SelLength := 0; SelStart := mCol + Self.Perform(EM_LINEINDEX, mLine, 0); SelLength := 0; SetFocus; end; //////////////////////////////////////////////////////////////////////////////// procedure TMemo.Update_label; begin if PosLabel = nil then Exit; PosLabel.Caption := '(' + IntToStr(Line + 1) + ',' + IntToStr(Col) + ')'; end; //////////////////////////////////////////////////////////////////////////////// function TMemo.TopLine: Integer; begin Result := SendMessage(Self.Handle, EM_GETFIRSTVISIBLELINE, 0, 0); end; //////////////////////////////////////////////////////////////////////////////// function TMemo.Line: Integer; begin Result := SendMessage(Self.Handle, EM_LINEFROMCHAR, Self.SelStart, 0); end; //////////////////////////////////////////////////////////////////////////////// function TMemo.Col: Integer; begin Result := Self.SelStart - SendMessage(Self.Handle, EM_LINEINDEX, SendMessage(Self.Handle, EM_LINEFROMCHAR, Self.SelStart, 0), 0); end; //////////////////////////////////////////////////////////////////////////////// procedure TMemo.WMVScroll(var Message: TWMMove); begin Update_label; Invalidate; inherited; end; //////////////////////////////////////////////////////////////////////////////// procedure TMemo.WMSize(var Message: TWMSize); begin Invalidate; inherited; end; //////////////////////////////////////////////////////////////////////////////// procedure TMemo.WMMove(var Message: TWMMove); begin Invalidate; inherited; end; //////////////////////////////////////////////////////////////////////////////// procedure TMemo.WMMousewheel(var Message: TWMMove); begin Invalidate; inherited; end; //////////////////////////////////////////////////////////////////////////////// procedure TMemo.Change; begin Update_label; Invalidate; inherited Change; end; //////////////////////////////////////////////////////////////////////////////// procedure TMemo.KeyDown(var Key: Word; Shift: TShiftState); begin Update_label; inherited KeyDown(Key, Shift); end; //////////////////////////////////////////////////////////////////////////////// procedure TMemo.KeyUp(var Key: Word; Shift: TShiftState); begin Update_label; inherited KeyUp(Key, Shift); end; //////////////////////////////////////////////////////////////////////////////// procedure TMemo.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin Update_label; inherited MouseDown(Button, Shift, X, Y); end; //////////////////////////////////////////////////////////////////////////////// procedure TMemo.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin Update_label; inherited MouseUp(Button, Shift, X, Y); end; //////////////////////////////////////////////////////////////////////////////// procedure TMemo.WMPaint(var Message: TWMPaint); var PS: TPaintStruct; DC: HDC; Canvas: TCanvas; i: Integer; X, Y: Integer; OldColor: TColor; Size: TSize; Max: Integer; s, Palabra, PrevWord: string; begin DC := Message.DC; if DC = 0 then DC := BeginPaint(Handle, PS); Canvas := TCanvas.Create; try OldColor := Font.Color; Canvas.Handle := DC; Canvas.Font.Name := Font.Name; Canvas.Font.Size := Font.Size; with Canvas do begin Max := TopLine + VisibleLines; if Max > Pred(Lines.Count) then Max := Pred(Lines.Count); //Limpio la sección visible Brush.Color := Self.Color; FillRect(Self.ClientRect); Y := 1; for i := TopLine to Max do begin X := 2; s := Lines[i]; //Detecto todas las palabras de esta línea Palabra := NextWord(s, PrevWord); while Palabra <> '' do begin Font.Color := OldColor; TextOut(X, Y, PrevWord); GetTextExtentPoint32(DC, PChar(PrevWord), Length(PrevWord), Size); Inc(X, Size.cx); Font.Color := clBlack; if IsKeyWord(Palabra) then begin Font.Color := clHighlight; TextOut(X, Y, Palabra); { //Draw dot underline Pen.Color := clHighlight; Pen.Style := psDot; PolyLine([ Point(X,Y+13), Point(X+TextWidth(Palabra),Y+13)]); } end else if IsNumber(Palabra) then begin Font.Color := $000000DD; TextOut(X, Y, Palabra); end else TextOut(X, Y, Palabra); GetTextExtentPoint32(DC, PChar(Palabra), Length(Palabra), Size); Inc(X, Size.cx); Palabra := NextWord(s, PrevWord); if (s = '') and (PrevWord <> '') then begin Font.Color := OldColor; TextOut(X, Y, PrevWord); end; end; if (s = '') and (PrevWord <> '') then begin Font.Color := OldColor; TextOut(X, Y, PrevWord); end; s := 'W'; GetTextExtentPoint32(DC, PChar(s), Length(s), Size); Inc(Y, Size.cy); end; end; finally if Message.DC = 0 then EndPaint(Handle, PS); end; Canvas.Free; inherited; end; //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// end.
unit SizeRecord; interface type TSizeRecord = record Width : integer; Height : integer; end; implementation end.
{$REGION 'Copyright (C) CMC Development Team'} { ************************************************************************** Copyright (C) 2015 CMC Development Team CMC is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 2 of the License, or (at your option) any later version. CMC is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with CMC. If not, see <http://www.gnu.org/licenses/>. ************************************************************************** } { ************************************************************************** Additional Copyright (C) for this modul: Chromaprint: Audio fingerprinting toolkit Copyright (C) 2010-2012 Lukas Lalinsky <lalinsky@gmail.com> Lomont FFT: Fast Fourier Transformation Original code by Chris Lomont, 2010-2012, http://www.lomont.org/Software/ ************************************************************************** } {$ENDREGION} {$REGION 'Notes'} { ************************************************************************** See CP.Chromaprint.pas for more information ************************************************************************** } unit CP.IntegralImage; {$IFDEF FPC} {$MODE delphi} {$ENDIF} interface uses Classes, SysUtils, CP.Image; { * * Image transformation that allows us to quickly calculate the sum of * values in a rectangular area. * * http://en.wikipedia.org/wiki/Summed_area_table * } type { TIntegralImage } TIntegralImage = class(TObject) private FImage: TImage; procedure Transform; public { Construct the integral image. Note that will modify the original image in-place, so it will not be usable afterwards. } constructor Create(Image: TImage); destructor Destroy; override; function Area(x1, y1, x2, y2: integer): double; function NumColumns: integer; function NumRows: integer; function GetData(Row, Column: integer): double; end; implementation { TIntegralImage } procedure TIntegralImage.Transform; var lColumns, lRows: integer; m, n: integer; begin // c++ is a pain; // in Pascal you know what you're doing lColumns := FImage.NumColumns; lRows := FImage.NumRows; for m := 1 to lColumns - 1 do begin // First column - add value on top FImage.SetData(0, m, FImage.GetData(0, m) + FImage.GetData(0, m - 1)); end; for n := 1 to lRows - 1 do begin // First row - add value on left FImage.SetData(n, 0, FImage.GetData(n, 0) + FImage.GetData(n - 1, 0)); for m := 1 to lColumns - 1 do begin FImage.SetData(n, m, FImage.GetData(n, m) + FImage.GetData(n - 1, m) + FImage.GetData(n, m - 1) - FImage.GetData(n - 1, m - 1)); end; end; end; constructor TIntegralImage.Create(Image: TImage); begin FImage := Image; Transform; end; destructor TIntegralImage.Destroy; begin FImage := nil; inherited; end; function TIntegralImage.GetData(Row, Column: integer): double; begin result := FImage.GetData(Row, Column); end; function TIntegralImage.Area(x1, y1, x2, y2: integer): double; var lArea: double; begin if (x2 < x1) or (y2 < y1) then begin result := 0.0; Exit; end; lArea := FImage.GetData(x2, y2); if (x1 > 0) then begin lArea := lArea - FImage.GetData(x1 - 1, y2); if (y1 > 0) then begin lArea := lArea + FImage.GetData(x1 - 1, y1 - 1); end; end; if (y1 > 0) then begin lArea := lArea - FImage.GetData(x2, y1 - 1); end; result := lArea; end; function TIntegralImage.NumColumns: integer; begin result := FImage.NumColumns; end; function TIntegralImage.NumRows: integer; begin result := FImage.NumRows; end; end.
unit MatrixLayer; interface uses Collection, TransportInterfaces, Transport, SyncObjs; const MaxSize = 10000; type PCargoMap = ^TCargoMap; TCargoMap = array[0..MaxSize*MaxSize] of TCargoValue; // Rendering maps type TRenderMapCell = record value : TCargoValue; defined : boolean; end; PRenderMap = ^TRenderMap; TRenderMap = array[0..MaxSize*MaxSize] of TRenderMapCell; type TMatrixLayer = class( TCargoLayer ) protected constructor Create( aCargoType : TCargoType; aCargoSystem : TCargoSystem ); override; public destructor Destroy; override; private fMap : PCargoMap; fLock : TCriticalSection; protected procedure Render( Quality : TRenderQuality ); override; function GetCargoValue( x, y : integer ) : TCargoValue; override; function GetCargoSlope( x, y, dx, dy : integer ) : single; override; private srcMapN : PRenderMap; srcMapT : PRenderMap; end; implementation uses MathUtils, Logs, SysUtils; const tidLog_Survival = 'Survival'; // Map utils type TIterationOrder = (itNormal, itTransverse); PCargoValue = ^TCargoValue; PRenderMapCell = ^TRenderMapCell; function GetItem ( i, j, xSize, ySize : integer; Matrix : PCargoMap; Order : TIterationOrder ) : PCargoValue; forward; function GetRenderItem( i, j, xSize, ySize : integer; Matrix : PRenderMap; Order : TIterationOrder ) : PRenderMapCell; forward; // TMatrixLayer constructor TMatrixLayer.Create( aCargoType : TCargoType; aCargoSystem : TCargoSystem ); begin inherited; getmem( fMap, CargoSystem.xSize*CargoSystem.ySize*sizeof(fMap[0]) ); getmem( srcMapN, CargoSystem.xSize*CargoSystem.ySize*sizeof(srcMapN[0]) ); getmem( srcMapT, CargoSystem.xSize*CargoSystem.ySize*sizeof(srcMapT[0]) ); fLock := TCriticalSection.Create; end; destructor TMatrixLayer.Destroy; begin try Logs.Log( 'Demolition', TimeToStr(Now) + ' - ' + ClassName ); except end; fLock.Free; freemem( fMap, CargoSystem.xSize*CargoSystem.ySize*sizeof(fMap[0]) ); freemem( srcMapN, CargoSystem.xSize*CargoSystem.ySize*sizeof(srcMapN[0]) ); freemem( srcMapT, CargoSystem.xSize*CargoSystem.ySize*sizeof(srcMapT[0]) ); inherited; end; procedure TMatrixLayer.Render( Quality : TRenderQuality ); procedure InitSourceMap( Map : PRenderMap ); var i, j : integer; cell : PRenderMapCell; P : TCargoPoint; begin for i := 0 to pred(CargoSystem.ySize) do for j := 0 to pred(CargoSystem.xSize) do begin cell := GetRenderItem( i, j, CargoSystem.xSize, CargoSystem.ySize, Map, itNormal ); cell.value := 0; cell.defined := (i = 0) or (j = 0) or (i = pred(CargoSystem.ySize)) or (j = pred(CargoSystem.xSize)); end; Points.Lock; try for i := 0 to pred(Points.Count) do begin P := TCargoPoint(Points[i]); cell := GetRenderItem( P.yPos, P.xPos, CargoSystem.xSize, CargoSystem.ySize, Map, itNormal ); cell.value := P.Value; cell.defined := true; end; finally Points.Unlock; end; end; procedure SmoothSourceMap( Map : PRenderMap ); const SuperCellSize = 5; var si, sj : integer; i, j : integer; cell : PRenderMapCell; sum : integer; count : integer; avg : TCargoValue; begin for si := 0 to pred(CargoSystem.ySize div SuperCellSize) do for sj := 0 to pred(CargoSystem.xSize div SuperCellSize) do begin sum := 0; count := 0; for i := SuperCellSize*si to SuperCellSize*si + SuperCellSize do for j := SuperCellSize*sj to SuperCellSize*sj + SuperCellSize do begin cell := GetRenderItem( i, j, CargoSystem.xSize, CargoSystem.ySize, Map, itNormal ); if cell.defined and not ((i = 0) or (j = 0) or (i = pred(CargoSystem.ySize)) or (j = pred(CargoSystem.xSize))) then begin sum := sum + cell.value; inc( count ); end; end; if count > 1 then begin avg := sum div count; //min( high(avg), sum ); for i := SuperCellSize*si to SuperCellSize*si + SuperCellSize do for j := SuperCellSize*sj to SuperCellSize*sj + SuperCellSize do begin cell := GetRenderItem( i, j, CargoSystem.xSize, CargoSystem.ySize, Map, itNormal ); if cell.defined and not ((i = 0) or (j = 0) or (i = pred(CargoSystem.ySize)) or (j = pred(CargoSystem.xSize))) then cell.value := avg; end; end; end; end; procedure SmoothStrings( Map : PRenderMap; Order : TIterationOrder ); var lastVal : TCargoValue; lastPos : integer; xSize : integer; ySize : integer; i, j, k : integer; cell : PRenderMapCell; icell : PRenderMapCell; slope : single; shift : single; begin if Order = itNormal then begin xSize := CargoSystem.xSize; ySize := CargoSystem.ySize; end else begin xSize := CargoSystem.ySize; ySize := CargoSystem.xSize; end; for j := 1 to xSize - 2 do begin lastVal := 0; lastPos := 0; for i := 1 to pred(ySize) do begin cell := GetRenderItem( i, j, CargoSystem.xSize, CargoSystem.ySize, Map, Order ); if cell.defined and ((lastPos <> 0) or (i <> pred(ySize))) then begin slope := (cell.value - lastVal)/(i - lastPos); shift := lastVal - slope*lastPos; for k := lastPos + 1 to i - 1 do begin icell := GetRenderItem( k, j, CargoSystem.xSize, CargoSystem.ySize, Map, Order ); icell.value := round( slope*k + shift ); icell.defined := true; end; lastVal := cell.value; lastPos := i; end; end end; end; procedure AverageMaps( srcMapN, srcMapT : PRenderMap; fMap : PCargoMap ); var i, j : integer; srcCellN, srcCellT : PRenderMapCell; cell : PCargoValue; begin for i := 0 to pred(CargoSystem.ySize) do for j := 0 to pred(CargoSystem.xSize) do begin srcCellN := GetRenderItem( i, j, CargoSystem.xSize, CargoSystem.ySize, srcMapN, itNormal ); srcCellT := GetRenderItem( i, j, CargoSystem.xSize, CargoSystem.ySize, srcMapT, itNormal ); cell := GetItem( i, j, CargoSystem.xSize, CargoSystem.ySize, fMap, itNormal ); cell^ := (integer(srcCellN.value) + integer(srcCellT.value)) div 2; end; end; procedure CopyMap( srcMap : PRenderMap; fMap : PCargoMap ); var i, j : integer; srcCell : PRenderMapCell; cell : PCargoValue; begin for i := 0 to pred(CargoSystem.ySize) do for j := 0 to pred(CargoSystem.xSize) do begin srcCell := GetRenderItem( i, j, CargoSystem.xSize, CargoSystem.ySize, srcMap, itNormal ); cell := GetItem( i, j, CargoSystem.xSize, CargoSystem.ySize, fMap, itNormal ); cell^ := srcCell.value; end; end; begin try try InitSourceMap( srcMapN ); // SmoothSourceMap( srcMapN ); SmoothStrings( srcMapN, itNormal ); SmoothStrings( srcMapN, itTransverse ); if Quality = rqHigh then begin try InitSourceMap( srcMapT ); // SmoothSourceMap( srcMapT ); SmoothStrings( srcMapT, itTransverse ); SmoothStrings( srcMapT, itNormal ); fLock.Enter; try AverageMaps( srcMapN, srcMapT, fMap ); finally fLock.Leave; end; finally end end else begin fLock.Enter; try CopyMap( srcMapN, fMap ); finally fLock.Leave; end; end finally end; except on E : Exception do Logs.Log( tidLog_Survival, DateTimeToStr(Now) + ' ERROR in Cargo Surface: ' + E.Message ); end end; function TMatrixLayer.GetCargoValue( x, y : integer ) : TCargoValue; begin fLock.Enter; try result := GetItem( y, x, CargoSystem.xSize, CargoSystem.ySize, fMap, itNormal )^; finally fLock.Leave; end; end; function TMatrixLayer.GetCargoSlope( x, y, dx, dy : integer ) : single; begin result := 0; end; // Util functs function GetItem( i, j, xSize, ySize : integer; Matrix : PCargoMap; Order : TIterationOrder ) : PCargoValue; begin if Order = itNormal then result := @Matrix[xSize*i + j] else result := @Matrix[xSize*j + i] end; function GetRenderItem( i, j, xSize, ySize : integer; Matrix : PRenderMap; Order : TIterationOrder ) : PRenderMapCell; begin if Order = itNormal then result := @Matrix[xSize*i + j] else result := @Matrix[xSize*j + i] end; end.
// Main confiuration form for Macro Templates // Original Author: Piotr Likus unit GX_MacroTemplates; {$I GX_CondDefine.inc} interface uses Classes, Controls, Forms, ComCtrls, ExtCtrls, StdCtrls, Menus, Dialogs, ActnList, StdActns, GX_ConfigurationInfo, GX_MacroFile, GX_EnhancedEditor, GX_GenericUtils, GX_BaseForm, Actions; const DefaultMacroFileName = 'MacroTemplates.xml'; MinExpandDelay = 100; // ms DefExpandDelay = 500; // ms ExpandDelayNumerator = 100; type // Programmer-specific static data TProgrammerInfo = record FullName: string; Initials: string; end; // Stores the configuration settings for the Macro Templates expert TTemplateSettings = class private FExpandWithChar: Boolean; FExpandDelay: Integer; procedure SetExpandWithChar(const Value: Boolean); procedure SetExpandDelay(const Value: Integer); protected FOwner: TObject; FForm: TCustomForm; FMacroFileName: string; FProgrammerName: string; FProgrammerInitials: string; procedure SetProgrammerName(const AValue: string); virtual; procedure SetProgrammerInitials(const AValue: string); virtual; procedure Changed; virtual; public constructor Create(const AOwner: TObject); procedure LoadSettings; virtual; procedure SaveSettings; virtual; procedure Reload; virtual; property ProgrammerName: string read FProgrammerName write SetProgrammerName; property ProgrammerInitials: string read FProgrammerInitials write SetProgrammerInitials; property ExpandWithChar: Boolean read FExpandWithChar write SetExpandWithChar; property ExpandDelay: Integer read FExpandDelay write SetExpandDelay; property MacroFileName: string read FMacroFileName; property Form: TCustomForm read FForm write FForm; end; TMacroTemplatesIni = class(TGExpertsSettings) protected FBaseKey: string; public constructor Create; end; TfmMacroTemplates = class(TfmBaseForm) PageControl: TPageControl; pmMacros: TPopupMenu; PROCNAMEMacro1: TMenuItem; PROCCLASS1: TMenuItem; N1: TMenuItem; PROJECTDIRMacro1: TMenuItem; PROJECTNAME1: TMenuItem; UNITMacro1: TMenuItem; N2: TMenuItem; DATETIMEMacro1: TMenuItem; DATE1: TMenuItem; N3: TMenuItem; USER1: TMenuItem; INPUTVARMacro1: TMenuItem; N4: TMenuItem; miCopy: TMenuItem; miCut: TMenuItem; miPaste: TMenuItem; OpenDialog: TOpenDialog; SaveDialog: TSaveDialog; PROGRAMMERNAMEMacro1: TMenuItem; PROGRAMMERINITIALSMacro1: TMenuItem; pmUses: TPopupMenu; miAddToUses: TMenuItem; miDeleteUses: TMenuItem; tabTemplates: TTabSheet; tabConfig: TTabSheet; edProgrammerName: TEdit; edInitials: TEdit; pnlList: TPanel; lvTemplates: TListView; Panel2: TPanel; splTemplates: TSplitter; pnlMacroDetails: TPanel; pnlEditMacro: TPanel; splUses: TSplitter; pnlMacroText: TPanel; pnlUses: TPanel; pnlFooter: TPanel; pnlFooterButtons: TPanel; PGENMacro1: TMenuItem; CLASSMacro1: TMenuItem; DateMacros1: TMenuItem; TimeMacros1: TMenuItem; YEARMacro1: TMenuItem; MONTHMacro1: TMenuItem; DAYMacro1: TMenuItem; HOURMacro1: TMenuItem; MINUTEMacro1: TMenuItem; SECONDMacro1: TMenuItem; PROJECTGROUPNAMEMacro1: TMenuItem; PROJECTGROUPDIRMacro1: TMenuItem; N6: TMenuItem; MONTHSHORTNAMEMacro1: TMenuItem; MONTHLONGNAMEMacro1: TMenuItem; DAYSHORTNAMEMacro1: TMenuItem; DAYLONGNAMEMacro1: TMenuItem; IDENTMacro1: TMenuItem; ProjectMacros1: TMenuItem; grpSequenceNumber: TGroupBox; lblCurrentValue: TLabel; edGenValue: TEdit; btnChange: TButton; btnAdd: TButton; btnEdit: TButton; btnDelete: TButton; btnExport: TButton; btnImport: TButton; btnClear: TButton; btnOK: TButton; btnCancel: TButton; INTERFACEMacro1: TMenuItem; pnlUsesImplementation: TPanel; lbLocalUses: TListBox; pnlImplementationHeader: TPanel; pnlUsesInterface: TPanel; lbGlobalUses: TListBox; pnlInterfaceHeader: TPanel; mitNone: TMenuItem; mitPas: TMenuItem; mitCPP: TMenuItem; mitHTML: TMenuItem; mitSQL: TMenuItem; Actions: TActionList; actSyntaxNone: TAction; actSyntaxPas: TAction; actSyntaxCPP: TAction; actSyntaxHTML: TAction; actSyntaxSQL: TAction; actEditCopy: TEditCopy; actEditCut: TEditCut; actEditPaste: TEditPaste; UserIDMacros1: TMenuItem; Other1: TMenuItem; BEFORE1: TMenuItem; VersionMacros1: TMenuItem; VERPRODUCTVERSIONMacro1: TMenuItem; VERFILEVERSION1: TMenuItem; VERMAJORMacro1: TMenuItem; VERMINORMacro1: TMenuItem; VERRELEASEMacro1: TMenuItem; VERBUILD1: TMenuItem; VERPRODUCTNAME1: TMenuItem; VERINTERNALNAME1: TMenuItem; VERFILEDESCRIPTIONMacro1: TMenuItem; N7: TMenuItem; actInsertCursorPos: TAction; actInsertUnitStart: TAction; actInsertLineStart: TAction; actInsertLineEnd: TAction; N8: TMenuItem; CLIPBOARDMacro1: TMenuItem; SELECTIONMacro1: TMenuItem; N5: TMenuItem; grpUserDetails: TGroupBox; actAdd: TAction; actEdit: TAction; actDelete: TAction; actImport: TAction; actExport: TAction; actClear: TAction; lblFullName: TLabel; lblInitials: TLabel; btnHelp: TButton; Procedurefunctionheader1: TMenuItem; ARGUMENTSMacro1: TMenuItem; RESULTMacro1: TMenuItem; N9: TMenuItem; BEGINPARAMLISTMacro1: TMenuItem; ENDPARAMLISTMacro1: TMenuItem; N10: TMenuItem; PARAMNAMEMacro1: TMenuItem; PARAMTYPEMacro1: TMenuItem; PARAMDEFMacro1: TMenuItem; N11: TMenuItem; CLIPBOARD1Macro1: TMenuItem; COPYSELECTIONMacro1: TMenuItem; gbxExpansion: TGroupBox; lblExpandDelay: TLabel; lb01Sec: TLabel; lbl2Sec: TLabel; cbExpandWithChar: TCheckBox; tbExpandDelay: TTrackBar; lbl1Sec: TLabel; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure TemplateCodeEnter(Sender: TObject); procedure TemplateCodeExit(Sender: TObject); procedure InsertMacroClick(Sender: TObject); procedure INPUTVARMacro1Click(Sender: TObject); procedure miCopyClick(Sender: TObject); procedure miCutClick(Sender: TObject); procedure miPasteClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure pmUsesPopup(Sender: TObject); procedure miAddToUsesClick(Sender: TObject); procedure miDeleteUsesClick(Sender: TObject); procedure lbUsesDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); procedure lbUsesDragDrop(Sender, Source: TObject; X, Y: Integer); procedure lvTemplatesClick(Sender: TObject); procedure edProgrammerNameChange(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure lvTemplatesSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); procedure btnChangeClick(Sender: TObject); procedure SetHighlighterClick(Sender: TObject); procedure ActionsUpdate(Action: TBasicAction; var Handled: Boolean); procedure pmMacrosPopup(Sender: TObject); procedure actInsertExecute(Sender: TObject); procedure pnlUsesResize(Sender: TObject); procedure lvTemplatesDblClick(Sender: TObject); procedure actAddExecute(Sender: TObject); procedure actEditExecute(Sender: TObject); procedure actDeleteExecute(Sender: TObject); procedure actImportExecute(Sender: TObject); procedure actExportExecute(Sender: TObject); procedure actClearExecute(Sender: TObject); procedure btnHelpClick(Sender: TObject); private FSettings: TTemplateSettings; FMacroFile: TMacroFile; FCurrentSyntaxMode: TGXSyntaxHighlighter; FTemplateText: TGXEnhancedEditor; FTemplateShortCut: TShortCut; FModified: Boolean; FTextModified: Boolean; procedure UpdateMacroValues(AMacroIndex: Integer); procedure ReadMacroValues(AMacroIndex: Integer); procedure ClearMacro; procedure ClearAllMacros; procedure ChangeMacro; procedure ClearControls; procedure FillControls; procedure ImportMacros(ASourceFile: TMacroFile; AAppend: Boolean); function CreateMacroObject: TMacroObject; procedure ChangeSeqValue; procedure SetupTemplateMemo; procedure SetEditing(AFlag: Boolean); function GetInsertPos: TTemplateInsertPos; procedure SetInsertPos(APos: TTemplateInsertPos); procedure SaveFormLayout; procedure LoadFormLayout; procedure SetCurrentSyntaxMode(const Value: TGXSyntaxHighlighter); procedure SetHighlighter(AIndex: Integer); procedure UpdateSyntaxMenus; function IsEmptySelection: Boolean; procedure SelectMacro(Index: Integer); procedure MarkModified; procedure ClearModified; procedure MarkTextModified; protected procedure SaveSettings; procedure LoadSettings; procedure SaveMacroFile(const AFilename: string); procedure LoadMacroFile(const AFilename: string; AAppend: Boolean); procedure AddUses(AUnits: TStringList; AListBox: TListBox); procedure LoadUsesToMacroObject(AUnits: TStringList; AListBox: TListBox); procedure SaveTemplateChanges; procedure AddMacroToControls(AMacroObject: TMacroObject); procedure UpdateMacroListValues(AMacroIndex: Integer; AMacroObject: TMacroObject); procedure DeleteMacro(AMacroIndex: Integer); function SelectedIndex: Integer; procedure SetSettings(const AValue: TTemplateSettings); function WindowPosKey: string; procedure TemplateTextChanged(Sender: TObject); public property Settings: TTemplateSettings read FSettings write SetSettings; property CurrentSyntaxMode: TGXSyntaxHighlighter read FCurrentSyntaxMode write SetCurrentSyntaxMode; end; TGetProgrammerInfo = function(var VInfo: TProgrammerInfo): Boolean of object; procedure RegisterProgrammerInfoProc(AProc: TGetProgrammerInfo); function GetProgrammerInfo(var VInfo: TProgrammerInfo): Boolean; function GetInitials(const AFullName: string): string; function GenProgrammerSeq: Integer; function GenSeqNewValue(const ASeqName: string): Integer; function MacroTemplatesBaseKey: string; implementation {$R *.dfm} uses SysUtils, Windows, Graphics, Clipbrd, GX_SharedImages, GX_GxUtils, GX_MacroParser, GX_MacroTemplateEdit, GX_OtaUtils, GX_IdeUtils, Math; var ProgInfoProc: TGetProgrammerInfo; InternalMacroLibrary: TBasicMacroLibrary = nil; const SequenceConfigurationKey = 'Sequences'; resourcestring SConfirmClear = 'Are you sure you want to delete all macros ?'; type TProgrammerMacroLibrary = class(TBasicMacroLibrary) public function GetUserNameTag: string; function ParseMacro(AMacroText: string; var VResult: string): Boolean; override; end; procedure RegisterProgrammerInfoProc(AProc: TGetProgrammerInfo); begin ProgInfoProc := AProc; end; // Returns True if the programmer information was accessible and VInfo is filled function GetProgrammerInfo(var VInfo: TProgrammerInfo): Boolean; begin if @ProgInfoProc <> nil then Result := ProgInfoProc(VInfo) else Result := False; end; // Returns the initials of a full name function GetInitials(const AFullName: string): string; var WorkCopy, NamePart: string; begin Result := ''; WorkCopy := AFullName; repeat NamePart := RemoveCharsBefore(WorkCopy, ' '); if NamePart <> '' then Result := Result + NamePart[1]; until WorkCopy = ''; end; // Returns name of the registry key for a programmer's sequence number function GetProgrammerSeqKey: string; var PrgInfo: TProgrammerInfo; begin if GetProgrammerInfo(PrgInfo) then Result := 'PGEN_' + PrgInfo.Initials else Result := ''; end; // Gets a programmer's sequence number function ReadSeqValue(const ASeqName: string): Integer; begin with TMacroTemplatesIni.Create do try Result := ReadInteger(SequenceConfigurationKey, ASeqName, 0); finally Free; end; end; function ReadProgrammerSeqValue: Integer; begin Result := ReadSeqValue(GetProgrammerSeqKey); end; // Returns the sequence value for the current programmer function GenProgrammerSeq: Integer; var PrgInfo: TProgrammerInfo; begin if GetProgrammerInfo(PrgInfo) then Result := GenSeqNewValue('PGEN_' + PrgInfo.Initials) else Result := -1; end; // Generate new sequence number function GenSeqNewValue(const ASeqName: string): Integer; begin with TMacroTemplatesIni.Create do try Result := ReadInteger(SequenceConfigurationKey, ASeqName, 0); Inc(Result); WriteInteger(SequenceConfigurationKey, ASeqName, Result); finally Free; end; end; procedure SetSeqValue(const ASeqName: string; ANewValue: Integer); begin with TMacroTemplatesIni.Create do try WriteInteger(SequenceConfigurationKey, ASeqName, ANewValue); finally Free; end; end; function MacroTemplatesBaseKey: string; begin Result := ConfigInfo.GExpertsIdeRootRegistryKey + PathDelim + 'EditorExperts' + PathDelim + 'MacroTemplates'; end; { TTemplateSettings } constructor TTemplateSettings.Create(const AOwner: TObject); begin inherited Create; FOwner := AOwner; end; procedure TTemplateSettings.Reload; begin // empty - non-required method end; procedure TTemplateSettings.SetProgrammerName(const AValue: string); begin if AValue <> FProgrammerName then begin FProgrammerName := AValue; Changed; end; end; procedure TTemplateSettings.SetProgrammerInitials(const AValue: string); begin if AValue <> FProgrammerInitials then begin FProgrammerInitials := AValue; Changed; end; end; procedure TTemplateSettings.Changed; begin // Empty (abstract not supported in BCB ?) end; procedure TTemplateSettings.LoadSettings; begin // Empty (abstract not supported in BCB ?) end; procedure TTemplateSettings.SaveSettings; begin // Empty (abstract not supported in BCB ?) end; procedure TTemplateSettings.SetExpandWithChar(const Value: Boolean); begin if FExpandWithChar <> Value then begin FExpandWithChar := Value; Changed; end; end; procedure TTemplateSettings.SetExpandDelay(const Value: Integer); begin if FExpandDelay <> Value then begin FExpandDelay := Value; Changed; end; end; { TfmMacroTemplates } procedure TfmMacroTemplates.FormCreate(Sender: TObject); begin SetupTemplateMemo; pnlMacroText.Caption := ''; // hide design-time text PageControl.ActivePage := PageControl.Pages[0]; LoadSettings; pmMacros.AutoHotKeys := maManual; pnlUsesResize(pnlUses); end; procedure TfmMacroTemplates.FormDestroy(Sender: TObject); begin FreeAndNil(FMacroFile); inherited; end; procedure TfmMacroTemplates.AddMacroToControls(AMacroObject: TMacroObject); var ListItem: TListItem; begin ListItem := lvTemplates.Items.Add; ListItem.Caption := AMacroObject.Name; ListItem.SubItems.Add(AMacroObject.Desc); ListItem.SubItems.Add(ShortCutToText(AMacroObject.ShortCut)); ListItem.SubItems.Add(InsertPosToText(AMacroObject.InsertPos)); ListItem.Data := AMacroObject; end; procedure TfmMacroTemplates.UpdateMacroListValues(AMacroIndex: Integer; AMacroObject: TMacroObject); var ListItem: TListItem; begin ListItem := lvTemplates.Items[AMacroIndex]; ListItem.Caption := AMacroObject.Name; ListItem.SubItems[0] := AMacroObject.Desc; ListItem.SubItems[1] := ShortCutToText(AMacroObject.ShortCut); ListItem.SubItems[2] := InsertPosToText(AMacroObject.InsertPos); end; procedure TfmMacroTemplates.DeleteMacro(AMacroIndex: Integer); begin lvTemplates.Items[AMacroIndex].Delete; end; function TfmMacroTemplates.CreateMacroObject: TMacroObject; begin Result := TMacroObject.Create(''); end; function TfmMacroTemplates.SelectedIndex: Integer; begin Result := -1; if lvTemplates.Selected <> nil then Result := lvTemplates.Selected.Index; end; procedure TfmMacroTemplates.btnOKClick(Sender: TObject); begin SaveSettings; ModalResult := mrOk; Close; end; procedure TfmMacroTemplates.FormClose(Sender: TObject; var Action: TCloseAction); begin SaveFormLayout; Action := caFree; if Assigned(FSettings) then FSettings.Form := nil; end; // Populates the controls with a macro's values procedure TfmMacroTemplates.ReadMacroValues(AMacroIndex: Integer); var MacroObject: TMacroObject; begin if AMacroIndex < 0 then Exit; MacroObject := TMacroObject(lvTemplates.Items[AMacroIndex].Data); if MacroObject <> nil then begin FTemplateText.AsString := MacroObject.Text; AddUses(MacroObject.PubUnits, lbGlobalUses); AddUses(MacroObject.PrivUnits, lbLocalUses); SetEditing(True); SetInsertPos(MacroObject.InsertPos); FTemplateShortCut := MacroObject.ShortCut; ClearModified; end; end; // Update a macro's data with values from controls procedure TfmMacroTemplates.UpdateMacroValues(AMacroIndex: Integer); var MacroObject: TMacroObject; MacroText: string; begin if AMacroIndex < 0 then Exit; MacroObject := TMacroObject(lvTemplates.Items[AMacroIndex].Data); if MacroObject <> nil then begin MacroText := FTemplateText.Text; MacroObject.Text := MacroText; LoadUsesToMacroObject(MacroObject.PubUnits, lbGlobalUses); LoadUsesToMacroObject(MacroObject.PrivUnits, lbLocalUses); MacroObject.InsertPos := GetInsertPos; MacroObject.ShortCut := FTemplateShortCut; end; end; // The selected macro changed procedure TfmMacroTemplates.ChangeMacro; var Index: Integer; begin Index := SelectedIndex; if Index > -1 then ReadMacroValues(Index); end; procedure TfmMacroTemplates.lvTemplatesClick(Sender: TObject); begin ChangeMacro; end; procedure TfmMacroTemplates.TemplateCodeEnter(Sender: TObject); begin btnOK.Default := False; end; procedure TfmMacroTemplates.TemplateCodeExit(Sender: TObject); begin SaveTemplateChanges; btnOK.Default := True; end; procedure TfmMacroTemplates.SaveTemplateChanges; var Index: Integer; MacroObject: TMacroObject; begin if not FModified then Exit; Index := SelectedIndex; if Index > -1 then begin UpdateMacroValues(Index); MacroObject := TMacroObject(lvTemplates.Items[Index].Data); if MacroObject = nil then Exit; UpdateMacroListValues(Index, MacroObject); ClearModified; end; end; // Display the list of macros procedure TfmMacroTemplates.FillControls; var i: Integer; begin ClearControls; for i := 0 to FMacroFile.MacroCount - 1 do AddMacroToControls(FMacroFile.MacroItems[i]); SelectMacro(0); end; procedure TfmMacroTemplates.ClearAllMacros; begin if FMacroFile <> nil then FMacroFile.Clear; ClearControls; end; // Unselect the template and clear the controls // No template is selected after this operation procedure TfmMacroTemplates.ClearMacro; begin lvTemplates.Selected := nil; FTemplateText.Clear; FTemplateShortCut := EmptyShortCut; lbGlobalUses.Items.Clear; lbLocalUses.Items.Clear; SetEditing(False); end; // Clear the data in the macro controls procedure TfmMacroTemplates.ClearControls; var Idx: Integer; begin Idx := SelectedIndex; lvTemplates.Items.Clear; if Idx > 0 then lvTemplates.Selected := nil; FTemplateText.Clear; SetEditing(False); end; procedure TfmMacroTemplates.LoadFormLayout; begin // do not localize with TGExpertsSettings.Create(MacroTemplatesBaseKey) do try LoadForm(Self, WindowPosKey); pnlList.Height := ReadInteger(WindowPosKey, 'ListSplitter', pnlList.Height); pnlUses.Width := ReadInteger(WindowPosKey, 'UsesSplitter', pnlUses.Width); pnlUsesImplementation.Height := ReadInteger(WindowPosKey, 'UsesSecSplitter', pnlUsesImplementation.Height); lvTemplates.Columns[0].Width := ReadInteger(WindowPosKey, 'NameWidth', lvTemplates.Columns[0].Width); lvTemplates.Columns[1].Width := ReadInteger(WindowPosKey, 'DescriptionWidth', lvTemplates.Columns[1].Width); lvTemplates.Columns[2].Width := ReadInteger(WindowPosKey, 'ShortCutWidth', lvTemplates.Columns[2].Width); CurrentSyntaxMode := TGXSyntaxHighlighter(ReadEnumerated(WindowPosKey, 'SyntaxHighlighter', TypeInfo(TGXSyntaxHighlighter), Ord(FCurrentSyntaxMode))); finally Free; end; EnsureFormVisible(Self); end; procedure TfmMacroTemplates.SaveFormLayout; begin // do not localize with TGExpertsSettings.Create(MacroTemplatesBaseKey) do try if WindowState = wsNormal then begin // Save only if not maximized/minimized SaveForm(Self, WindowPosKey); WriteInteger(WindowPosKey, 'ListSplitter', pnlList.Height); WriteInteger(WindowPosKey, 'UsesSplitter', pnlUses.Width); WriteInteger(WindowPosKey, 'UsesSecSplitter', pnlUsesImplementation.Height); WriteInteger(WindowPosKey, 'NameWidth', lvTemplates.Columns[0].Width); WriteInteger(WindowPosKey, 'DescriptionWidth', lvTemplates.Columns[1].Width); WriteInteger(WindowPosKey, 'ShortCutWidth', lvTemplates.Columns[2].Width); WriteInteger(WindowPosKey, 'SyntaxHighlighter', Ord(FCurrentSyntaxMode)); end; finally Free; end; end; procedure TfmMacroTemplates.LoadSettings; begin LoadFormLayout; ClearAllMacros; if Settings <> nil then begin if FileExists(Settings.MacroFileName) then LoadMacroFile(Settings.MacroFileName, False); Settings.LoadSettings; edProgrammerName.Text := Settings.ProgrammerName; edInitials.Text := Settings.ProgrammerInitials; edGenValue.Text := IntToStr(ReadProgrammerSeqValue); cbExpandWithChar.Checked := Settings.ExpandWithChar; if Settings.ExpandDelay >= 0 then tbExpandDelay.Position := Settings.ExpandDelay else tbExpandDelay.Position := DefExpandDelay div ExpandDelayNumerator; end; end; procedure TfmMacroTemplates.SaveSettings; begin if Settings <> nil then begin SaveMacroFile(Settings.MacroFileName); SetSeqValue(GetProgrammerSeqKey, StrToInt(edGenValue.Text)); Settings.ProgrammerName := edProgrammerName.Text; Settings.ProgrammerInitials := edInitials.Text; Settings.ExpandWithChar := cbExpandWithChar.Checked; Settings.ExpandDelay := tbExpandDelay.Position; Settings.SaveSettings; Settings.Reload; end; end; procedure TfmMacroTemplates.LoadMacroFile(const AFilename: string; AAppend: Boolean); var ImportFile: TMacroFile; begin if FileExists(AFilename) then begin ImportFile := TMacroFile.Create; try ImportFile.FileName := AFilename; ImportFile.LoadFromFile; ImportMacros(ImportFile, AAppend); FillControls; finally FreeAndNil(ImportFile); end; end else MessageDlg('Unable to load macro templates file from:' + sLineBreak + AFileName, mtError, [mbOk], 0); end; // Add macros from the file to the internal list of macros procedure TfmMacroTemplates.ImportMacros(ASourceFile: TMacroFile; AAppend: Boolean); // Add a new macro to current list (with copy) procedure AddMacroToFile(ASourceObj: TMacroObject); begin FMacroFile.AddMacro(ASourceObj); end; var AskOverwrite: Boolean; i: Integer; ImportName: string; Idx: Integer; FoundMacro: TMacroObject; DialogResult: Integer; begin if not AAppend then FMacroFile.Clear; AskOverwrite := True; for i := 0 to ASourceFile.MacroCount - 1 do begin ImportName := ASourceFile[i].Name; Idx := FMacroFile.IndexOf(ImportName); if Idx >= 0 then begin FoundMacro := FMacroFile[Idx]; if AskOverwrite then DialogResult := MessageDlg('A macro named "' + ImportName + '" already exists in list of macros.' + sLineBreak + 'Do you want to replace it ?', mtConfirmation, [mbYes, mbYesToAll, mbIgnore, mbAbort], 0) else DialogResult := mrYes; case DialogResult of mrYes, mrYesToAll: begin FMacroFile.RemoveMacro(FoundMacro); if DialogResult = mrYesToAll then AskOverwrite := False; AddMacroToFile(ASourceFile[i]); end; mrIgnore: ; // do nothing mrAbort: Break; end; // case end else // not found AddMacroToFile(ASourceFile[i]); end; // for i end; // ImportMacros procedure TfmMacroTemplates.SetEditing(AFlag: Boolean); begin FTemplateText.ReadOnly := not AFlag; end; procedure TfmMacroTemplates.SetInsertPos(APos: TTemplateInsertPos); begin actInsertCursorPos.Checked := (APos = tipCursorPos); actInsertUnitStart.Checked := (APos = tipUnitStart); actInsertLineStart.Checked := (APos = tipLineStart); actInsertLineEnd.Checked := (APos = tipLineEnd); end; function TfmMacroTemplates.GetInsertPos: TTemplateInsertPos; begin Result := tipCursorPos; if actInsertUnitStart.Checked then Result := tipUnitStart else if actInsertLineStart.Checked then Result := tipLineStart else if actInsertLineEnd.Checked then Result := tipLineEnd; end; procedure TfmMacroTemplates.InsertMacroClick(Sender: TObject); var MacroName: string; begin if FTemplateText.ReadOnly then Exit; MacroName := (Sender as TMenuItem).Caption; MacroName := StringReplace(MacroName, '&', '', [rfReplaceAll]); MacroName := Copy(MacroName, 1, Pos(' ', MacroName) - 1); MacroName := '%' + MacroName + '%'; FTemplateText.SelText := MacroName; end; procedure TfmMacroTemplates.INPUTVARMacro1Click(Sender: TObject); var VarCaption, MacroText, VarName: string; begin if FTemplateText.ReadOnly then Exit; VarCaption := InputBox('Variable Prompt Message', 'Variable Prompt Message', 'Variable Value'); if VarCaption = '' then Exit; VarName := InputBox('Variable Name', 'Variable Name', ''); if VarName = '' then Exit; MacroText := '%' + InputVarName + ',' + AnsiUpperCase(VarName) + ',' + VarCaption + '%'; FTemplateText.SelText := MacroText; end; procedure TfmMacroTemplates.miCopyClick(Sender: TObject); begin FTemplateText.CopyToClipboard; end; procedure TfmMacroTemplates.miCutClick(Sender: TObject); begin FTemplateText.CutToClipboard; end; procedure TfmMacroTemplates.miPasteClick(Sender: TObject); begin FTemplateText.PasteFromClipboard; end; procedure TfmMacroTemplates.FormShow(Sender: TObject); begin // Loading executed here, because file name is a property (not added to Create) if FMacroFile = nil then FMacroFile := TMacroFile.Create; LoadSettings; end; procedure TfmMacroTemplates.pmUsesPopup(Sender: TObject); resourcestring SAddToInterface = 'Add to Interface'; SAddToImplementation = 'Add to Implementation'; var DeleteEnabled, TemplateReadOnly: Boolean; lb: TListBox; begin lb := (pmUses.PopupComponent as TListBox); DeleteEnabled := (lb.ItemIndex <> -1); TemplateReadOnly := FTemplateText.ReadOnly; miDeleteUses.Enabled := DeleteEnabled and (not TemplateReadOnly); miAddToUses.Enabled := not TemplateReadOnly; if lb = lbGlobalUses then miAddToUses.Caption := SAddToInterface else if lb = lbLocalUses then miAddToUses.Caption := SAddToImplementation; end; procedure TfmMacroTemplates.miAddToUsesClick(Sender: TObject); var lb: TListBox; UnitName: string; begin lb := (pmUses.PopupComponent as TListBox); UnitName := InputBox('Unit Name', 'Unit Name', ''); if UnitName <> '' then begin lb.Items.Add(UnitName); MarkModified; end; end; procedure TfmMacroTemplates.miDeleteUsesClick(Sender: TObject); var lb: TListBox; idx: Integer; begin lb := (pmUses.PopupComponent as TListBox); idx := lb.ItemIndex; if idx <> -1 then begin lb.Items.Delete(Idx); MarkModified; end; end; procedure TfmMacroTemplates.lbUsesDragOver(Sender, Source: TObject; X, Y: Integer; State: TDragState; var Accept: Boolean); begin Accept := Source is TListBox; end; procedure TfmMacroTemplates.lbUsesDragDrop(Sender, Source: TObject; X, Y: Integer); var SourceList, DestList: TListBox; Idx: Integer; begin if (Sender is TListBox) and (Source is TListBox) then begin SourceList := Source as TListBox; Idx := SourceList.ItemIndex; if Idx = -1 then Exit; DestList := Sender as TListBox; DestList.Items.Add(SourceList.Items[Idx]); SourceList.Items.Delete(Idx); MarkModified; SaveTemplateChanges; end; end; procedure TfmMacroTemplates.AddUses(AUnits: TStringList; AListBox: TListBox); begin AListBox.Items := AUnits; end; // Copy uses list from from AListsView to AUnits procedure TfmMacroTemplates.LoadUsesToMacroObject(AUnits: TStringList; AListBox: TListBox); begin AUnits.Assign(AListBox.Items); end; procedure TfmMacroTemplates.SaveMacroFile(const AFilename: string); begin FMacroFile.SaveToFile(AFilename); end; procedure TfmMacroTemplates.SetSettings(const AValue: TTemplateSettings); begin if FSettings <> AValue then begin if Assigned(FSettings) and (FSettings.Form = Self) then FSettings.Form := nil; FSettings := AValue; if Assigned(FSettings) then FSettings.Form := Self; end; end; procedure TfmMacroTemplates.edProgrammerNameChange(Sender: TObject); begin edInitials.Text := GetInitials(edProgrammerName.Text); end; procedure TfmMacroTemplates.lvTemplatesSelectItem(Sender: TObject; Item: TListItem; Selected: Boolean); begin ChangeMacro; end; procedure TfmMacroTemplates.btnChangeClick(Sender: TObject); begin ChangeSeqValue; end; // Changes the value of the sequence number procedure TfmMacroTemplates.ChangeSeqValue; var SeqValue: string; SeqValueInt: Integer; begin SeqValue := IntToStr(ReadProgrammerSeqValue); SeqValue := InputBox('New Sequence Value', 'Value', SeqValue); SeqValueInt := StrToInt(SeqValue); edGenValue.Text := IntToStr(SeqValueInt); end; procedure TfmMacroTemplates.SetupTemplateMemo; begin if RunningCPPBuilder or GxOtaCurrentProjectIsNativeCpp then FCurrentSyntaxMode := gxpCPP else FCurrentSyntaxMode := gxpPas; FTemplateText := TGXEnhancedEditor.Create(Self); FTemplateText.Highlighter := FCurrentSyntaxMode; FTemplateText.Align := alClient; FTemplateText.PopupMenu := pmMacros; FTemplateText.OnExit := TemplateCodeExit; FTemplateText.OnEnter := TemplateCodeEnter; FTemplateText.Parent := pnlMacroText; FTemplateText.ReadOnly := True; FTemplateText.Font.Height := -11; FTemplateText.Font.Name := 'Courier New'; FTemplateText.WantTabs := True; FTemplateText.OnChange := TemplateTextChanged; end; procedure TfmMacroTemplates.SetHighlighterClick(Sender: TObject); begin SetHighlighter((Sender as TComponent).Tag); end; procedure TfmMacroTemplates.SetHighlighter(AIndex: Integer); const HIGHLIGHTERS: array[0..4] of TGXSyntaxHighlighter = (gxpNone, gxpPAS, gxpCPP, gxpHTML, gxpSQL); begin CurrentSyntaxMode := HIGHLIGHTERS[AIndex]; end; procedure TfmMacroTemplates.UpdateSyntaxMenus; begin actSyntaxNone.Checked := (FCurrentSyntaxMode = gxpNone); actSyntaxPas.Checked := (FCurrentSyntaxMode = gxpPAS); actSyntaxCpp.Checked := (FCurrentSyntaxMode = gxpCPP); actSyntaxHtml.Checked := (FCurrentSyntaxMode = gxpHTML); actSyntaxSql.Checked := (FCurrentSyntaxMode = gxpSQL); end; procedure TfmMacroTemplates.SetCurrentSyntaxMode(const Value: TGXSyntaxHighlighter); begin if FCurrentSyntaxMode <> Value then begin FCurrentSyntaxMode := Value; if Assigned(FTemplateText) then FTemplateText.Highlighter := FCurrentSyntaxMode; end; end; procedure TfmMacroTemplates.ActionsUpdate(Action: TBasicAction; var Handled: Boolean); var MacroSelected: Boolean; FileEmpty: Boolean; TextSelected: Boolean; begin TextSelected := Length(FTemplateText.SelText) > 0; MacroSelected := (SelectedIndex > -1); FileEmpty := (Assigned(FMacroFile) and (FMacroFile.MacroCount > 0)); actEditCut.Enabled := TextSelected; actEditCopy.Enabled := TextSelected; actEditPaste.Enabled := (Clipboard.HasFormat(CF_TEXT) and (not FTemplateText.ReadOnly)); UpdateSyntaxMenus; actEdit.Enabled := MacroSelected; actDelete.Enabled := MacroSelected; actClear.Enabled := FileEmpty; actExport.Enabled := FileEmpty; Handled := True; end; // Returns True if no macro is selected function TfmMacroTemplates.IsEmptySelection: Boolean; begin Result := FTemplateText.ReadOnly; end; procedure TfmMacroTemplates.pmMacrosPopup(Sender: TObject); begin if IsEmptySelection then Abort; end; procedure TfmMacroTemplates.actInsertExecute(Sender: TObject); begin SetInsertPos(TTemplateInsertPos((Sender as TComponent).Tag)); SaveTemplateChanges; end; procedure TfmMacroTemplates.SelectMacro(Index: Integer); begin if Index <= (lvTemplates.Items.Count - 1) then begin lvTemplates.Selected := lvTemplates.Items[Index]; lvTemplates.Selected.MakeVisible(False); lvTemplates.ItemFocused := lvTemplates.Selected; end; end; function TfmMacroTemplates.WindowPosKey: string; begin Result := 'ConfigWindow'; end; procedure TfmMacroTemplates.MarkModified; begin FModified := True; end; procedure TfmMacroTemplates.TemplateTextChanged(Sender: TObject); begin MarkTextModified; end; procedure TfmMacroTemplates.ClearModified; begin FModified := False; FTextModified := False; end; procedure TfmMacroTemplates.MarkTextModified; begin FTextModified := True; FModified := True; end; { TMacroTemplatesIni } constructor TMacroTemplatesIni.Create; begin FBaseKey := MacroTemplatesBaseKey; inherited Create(FBaseKey); end; { TProgrammerMacroLibrary } function TProgrammerMacroLibrary.GetUserNameTag: string; begin Result := GetCurrentUser; if Trim(Result) = '' then Result := GetUnknownNameResult; end; function TProgrammerMacroLibrary.ParseMacro(AMacroText: string; var VResult: string): Boolean; var UpMacroText: string; PrgInfo: TProgrammerInfo; begin Result := True; UpMacroText := AnsiUpperCase(AMacroText); if UpMacroText = '%PROGRAMMERNAME%' then begin if GetProgrammerInfo(PrgInfo) then VResult := PrgInfo.FullName else VResult := GetUserNameTag; end else if UpMacroText = '%PROGRAMMERINITIALS%' then begin if GetProgrammerInfo(PrgInfo) then VResult := PrgInfo.Initials else VResult := GetInitials(GetUserNameTag); end else if UpMacroText = '%PGEN%' then VResult := IntToStr(GenProgrammerSeq) else Result := False; end; procedure TfmMacroTemplates.pnlUsesResize(Sender: TObject); begin pnlUsesImplementation.Height := Max(Trunc(pnlUses.ClientHeight / 2) - 4, 0); end; procedure TfmMacroTemplates.lvTemplatesDblClick(Sender: TObject); begin actEdit.Execute; end; procedure TfmMacroTemplates.actAddExecute(Sender: TObject); var NewMacro, RealMacroObject: TMacroObject; MacroFound: Boolean; begin NewMacro := CreateMacroObject; try {$IFNDEF GX_VER310_up} MacroFound := False; {$ENDIF} repeat if not EditMacroObject(NewMacro) then Break; MacroFound := (FMacroFile.IndexOf(NewMacro.Name) > -1); if MacroFound then MessageDlg('Macro names must be unique', mtWarning, [mbOK], 0) else begin RealMacroObject := FMacroFile.AddMacro(NewMacro); AddMacroToControls(RealMacroObject); lvTemplates.Selected := lvTemplates.FindCaption(0, NewMacro.Name, False, True, False); FTemplateText.Text := ''; FTemplateText.SetFocus; SetEditing(True); Exit; end; until not MacroFound; finally FreeAndNil(NewMacro); end; end; procedure TfmMacroTemplates.actEditExecute(Sender: TObject); var MacroObject: TMacroObject; MacroIdx: Integer; begin MacroIdx := SelectedIndex; if MacroIdx < 0 then Exit; MacroObject := TMacroObject(lvTemplates.Items[MacroIdx].Data); if MacroObject = nil then Exit; if EditMacroObject(MacroObject) then begin UpdateMacroListValues(MacroIdx, MacroObject); MarkModified; end; end; procedure TfmMacroTemplates.actDeleteExecute(Sender: TObject); var Idx: Integer; begin Idx := SelectedIndex; if Idx > -1 then begin FMacroFile.RemoveMacro(TMacroObject(lvTemplates.Items[Idx].Data)); DeleteMacro(Idx); if Idx > 0 then begin lvTemplates.Selected := lvTemplates.Items[Idx - 1]; lvTemplates.Selected.MakeVisible(False); end else begin lvTemplates.Selected := nil; ClearMacro; end; lvTemplates.ItemFocused := lvTemplates.Selected; end; end; procedure TfmMacroTemplates.actImportExecute(Sender: TObject); var ImportFileName: string; begin OpenDialog.FileName := DefaultMacroFileName; if OpenDialog.Execute then begin ImportFileName := OpenDialog.FileName; LoadMacroFile(ImportFileName, True); end; end; procedure TfmMacroTemplates.actExportExecute(Sender: TObject); var SaveFileName: string; begin SaveDialog.FileName := DefaultMacroFileName; if SaveDialog.Execute then begin SaveFileName := SaveDialog.FileName; SaveMacroFile(SaveFileName); end; end; procedure TfmMacroTemplates.actClearExecute(Sender: TObject); begin if MessageDlg(SConfirmClear, mtConfirmation, [mbYes, mbNo], 0) = mrYes then ClearAllMacros; end; procedure TfmMacroTemplates.btnHelpClick(Sender: TObject); begin GxContextHelp(Self, 40); end; initialization InternalMacroLibrary := TProgrammerMacroLibrary.Create; RegisterMacroLibrary(InternalMacroLibrary); finalization UnregisterMacroLibrary(InternalMacroLibrary); FreeAndNil(InternalMacroLibrary); end.
unit WaveIn; interface uses Windows, MMSystem, Messages, Classes; type TOnDataProc = function (var Data; Size : integer) : integer of object; TWaveRecorder = class public constructor Create; destructor Destroy; override; public function CanRecord : boolean; procedure DoRecord; procedure Stop; private fDevice : dword; fSamplingRate : integer; fChannels : integer; fBitsPerSample : integer; fBufferSize : integer; private function GetBlockAlign : integer; public property Device : dword read fDevice write fDevice; property SamplingRate : integer read fSamplingRate write fSamplingRate; property Channels : integer read fChannels write fChannels; property BitsPerSample : integer read fBitsPerSample write fBitsPerSample; property BlockAlign : integer read GetBlockAlign; property BufferSize : integer read fBufferSize write fBufferSize; private fSignalWnd : hWnd; fAutoStop : boolean; fManualStop : boolean; private fInHandle : hWaveIn; fFirstBuffer : TWaveHdr; fSecondBuffer : TWaveHdr; private procedure StopIt; procedure CloseHandles; public function MsToSamples(aMs : integer) : integer; protected procedure SignalWndProc(var Msg : TMessage); procedure FeedData(var aHeader : TWaveHdr); function DataArrived(var Data; Size : integer) : integer; virtual; private fOnData : TOnDataProc; fOnStop : TNotifyEvent; public property OnData : TOnDataProc read fOnData write fOnData; property OnStop : TNotifyEvent read fOnStop write fOnStop; end; implementation uses SysUtils, Forms, WaveHdrs, MMCheck; const DefaultSamplingRate = 8000; DefaultChannels = 1; DefaultBitsPerSample = 16; DefaultBufferSize = 250; // 250 ms constructor TWaveRecorder.Create; begin inherited; fDevice := WAVE_MAPPER; fSamplingRate := DefaultSamplingRate; fChannels := DefaultChannels; fBitsPerSample := DefaultBitsPerSample; fBufferSize := DefaultBufferSize; fSignalWnd := AllocatehWnd(SignalWndProc); end; destructor TWaveRecorder.Destroy; begin Stop; fOnStop := nil; DeallocateBuffer(fFirstBuffer); DeallocateBuffer(fSecondBuffer); DeallocateHWND(fSignalWnd); inherited; end; function TWaveRecorder.CanRecord : boolean; var Format : TWaveFormatEx; begin with Format do begin wFormatTag := WAVE_FORMAT_PCM; nChannels := fChannels; wBitsPerSample := fBitsPerSample; nSamplesPerSec := fSamplingRate; nBlockAlign := BlockAlign; nAvgBytesPerSec := nSamplesPerSec * nBlockAlign; cbSize := 0; end; Result := waveInOpen(nil, fDevice, @Format, 0, 0, CALLBACK_NULL or WAVE_FORMAT_QUERY) = MMSYSERR_NOERROR; end; procedure TWaveRecorder.DoRecord; var Format : TWaveFormatEx; BufferBytes : integer; begin Stop; DeallocateBuffer(fFirstBuffer); DeallocateBuffer(fSecondBuffer); with Format do begin wFormatTag := WAVE_FORMAT_PCM; nChannels := fChannels; wBitsPerSample := fBitsPerSample; nSamplesPerSec := fSamplingRate; nBlockAlign := BlockAlign; nAvgBytesPerSec := nSamplesPerSec * nBlockAlign; cbSize := 0; end; BufferBytes := MsToSamples(fBufferSize) * BlockAlign; AllocateBuffer(fFirstBuffer, BufferBytes); try AllocateBuffer(fSecondBuffer, BufferBytes); try TryMM(waveInOpen(@fInHandle, fDevice, @Format, fSignalWnd, DWORD(Self), CALLBACK_WINDOW)); try TryMM(waveInPrepareHeader(fInHandle, @fFirstBuffer, sizeof(fFirstBuffer))); try TryMM(waveInPrepareHeader(fInHandle, @fSecondBuffer, sizeof(fSecondBuffer))); try TryMM(waveInAddBuffer(fInHandle, @fFirstBuffer, sizeof(fFirstBuffer))); TryMM(waveInAddBuffer(fInHandle, @fSecondBuffer, sizeof(fSecondBuffer))); fManualStop := false; fAutoStop := false; TryMM(WaveInStart(fInHandle)); except waveInUnprepareHeader(fInHandle, @fSecondBuffer, sizeof(fSecondBuffer)); raise; end; except waveInUnprepareHeader(fInHandle, @fFirstBuffer, sizeof(fFirstBuffer)); raise; end; except waveInClose(fInHandle); fInHandle := 0; raise; end; except DeallocateBuffer(fSecondBuffer); raise; end; except DeallocateBuffer(fFirstBuffer); raise; end; end; procedure TWaveRecorder.Stop; begin fManualStop := true; //StopIt; CloseHandles; end; function TWaveRecorder.GetBlockAlign : integer; begin Result := (fBitsPerSample div 8) * fChannels; end; procedure TWaveRecorder.StopIt; begin CloseHandles; if assigned(fOnStop) then fOnStop(Self); end; procedure TWaveRecorder.CloseHandles; begin if fInHandle <> 0 then begin WaveInStop(fInHandle); WaveInReset(fInHandle); waveInUnprepareHeader(fInHandle, @fSecondBuffer, sizeof(fSecondBuffer)); waveInUnprepareHeader(fInHandle, @fFirstBuffer, sizeof(fFirstBuffer)); waveInClose(fInHandle); fInHandle := 0; end; end; function TWaveRecorder.MsToSamples(aMs : integer) : integer; begin Result := MulDiv(aMs, fSamplingRate, 1000); end; procedure TWaveRecorder.SignalWndProc(var Msg : TMessage); begin with Msg do if Msg = WIM_DATA then FeedData(PWaveHdr(lParam)^) else Result := DefWindowProc(fSignalWnd, Msg, wParam, lParam); end; procedure TWaveRecorder.FeedData(var aHeader : TWaveHdr); var Fed : dword; begin with aHeader do begin if dwBytesRecorded > 0 then Fed := DataArrived(lpData^, dwBytesRecorded) else Fed := dwBytesRecorded; if not fAutoStop then if (Fed = dwBytesRecorded) and not fManualStop then waveInAddBuffer(fInHandle, @aHeader, sizeof(aHeader)) else fAutoStop := true else StopIt; end; end; function TWaveRecorder.DataArrived(var Data; Size : integer) : integer; begin if assigned(fOnData) then try Result := fOnData(Data, Size); except Result := 0; end else Result := 0; end; end.
{ Clever Internet Suite Copyright (C) 2014 Clever Components All Rights Reserved www.CleverComponents.com } unit clSshUtils; interface {$I ..\common\clVer.inc} uses {$IFNDEF DELPHIXE2} Classes, SysUtils, Windows, {$ELSE} System.Classes, System.SysUtils, Winapi.Windows, {$ENDIF} clUtils; type EclSshError = class(Exception) private FErrorCode: Integer; public constructor Create(const AErrorMsg: string; AErrorCode: Integer; ADummy: Boolean = False); property ErrorCode: Integer read FErrorCode; end; resourcestring UnknownError = 'SSH error occurred'; InvalidPacketSize = 'Invalid packet size'; MacError = 'MAC Error'; DisconnectOccurred = 'Disconnect occurred'; InvalidVersion = 'Invalid server''s version string'; InvalidProtocol = 'Invalid protocol'; InvalidKexProtocol = 'Invalid kex protocol'; InvalidNewKeysProtocol = 'Invalid newkyes protocol'; ChannelOpenError = 'Unable to open channel'; RequestSubsystemError = 'Unable to request channel subsystem'; AlgorithmNegotiationError = 'Algorithm negotiation fail'; KexNextError = 'Verify: kex.next is False'; AuthMethodError = 'Auth method is not supported'; UserAuthError = 'User authentication failed'; HostKeyRejected = 'HostKey rejected'; const UnknownErrorCode = -1; InvalidPacketSizeCode = -2; MacErrorCode = -3; InvalidVersionCode = -4; RequestSubsystemErrorCode = -5; AlgorithmNegotiationErrorCode = -6; KexNextErrorCode = -7; AuthMethodErrorCode = -8; UserAuthErrorCode = -9; HostKeyRejectedCode = -10; DefaultSshAgent = 'Clever_Internet_Suite'; SSH_MSG_DISCONNECT = 1; SSH_MSG_IGNORE = 2; SSH_MSG_UNIMPLEMENTED = 3; SSH_MSG_DEBUG = 4; SSH_MSG_SERVICE_REQUEST = 5; SSH_MSG_SERVICE_ACCEPT = 6; SSH_MSG_KEXINIT = 20; SSH_MSG_NEWKEYS = 21; SSH_MSG_KEXDH_INIT = 30; SSH_MSG_KEXDH_REPLY = 31; SSH_MSG_USERAUTH_REQUEST = 50; SSH_MSG_USERAUTH_FAILURE = 51; SSH_MSG_USERAUTH_SUCCESS = 52; SSH_MSG_USERAUTH_BANNER = 53; SSH_MSG_USERAUTH_INFO_REQUEST = 60; SSH_MSG_USERAUTH_INFO_RESPONSE = 61; SSH_MSG_USERAUTH_PK_OK = 60; SSH_MSG_GLOBAL_REQUEST = 80; SSH_MSG_REQUEST_SUCCESS = 81; SSH_MSG_REQUEST_FAILURE = 82; SSH_MSG_CHANNEL_OPEN = 90; SSH_MSG_CHANNEL_OPEN_CONFIRMATION = 91; SSH_MSG_CHANNEL_OPEN_FAILURE = 92; SSH_MSG_CHANNEL_WINDOW_ADJUST = 93; SSH_MSG_CHANNEL_DATA = 94; SSH_MSG_CHANNEL_EXTENDED_DATA = 95; SSH_MSG_CHANNEL_EOF = 96; SSH_MSG_CHANNEL_CLOSE = 97; SSH_MSG_CHANNEL_REQUEST = 98; SSH_MSG_CHANNEL_SUCCESS = 99; SSH_MSG_CHANNEL_FAILURE = 100; SSH_MSG_KEX_DH_GEX_GROUP = 31; SSH_MSG_KEX_DH_GEX_INIT = 32; SSH_MSG_KEX_DH_GEX_REPLY = 33; SSH_RSA = 0; SSH_DSS = 1; implementation { EclSshError } constructor EclSshError.Create(const AErrorMsg: string; AErrorCode: Integer; ADummy: Boolean); begin inherited Create(AErrorMsg); FErrorCode := AErrorCode; end; end.
unit TntSysUtils; interface function WideExtractFileName(const FN: WideString): WideString; function WideExtractFileDir(const FN: WideString): WideString; function WideExtractFileExt(const FN: WideString): WideString; function WideExtractFileDrive(const FN: WideString): WideString; function WideChangeFileExt(const FN, Ext: WideString): WideString; implementation uses SysUtils; function WideExtractFileName(const FN: WideString): WideString; begin Result := ExtractFileName(FN); end; function WideExtractFileDir(const FN: WideString): WideString; begin Result := ExtractFileDir(FN); end; function WideExtractFileExt(const FN: WideString): WideString; begin Result := ExtractFileExt(FN); end; function WideExtractFileDrive(const FN: WideString): WideString; begin Result := ExtractFileDrive(FN); end; function WideCreateDir(const FN: WideString): Boolean; begin Result := CreateDir(FN); end; function WideChangeFileExt(const FN, Ext: WideString): WideString; begin Result := ChangeFileExt(FN, Ext); end; function WideDirectoryExists(const FN: WideString): Boolean; begin Result := DirectoryExists(FN); end; function Tnt_WideLowerCase(const S: WideString): WideString; begin Result := WideLowerCase(S); end; function Tnt_WideUpperCase(const S: WideString): WideString; begin Result := WideUpperCase(S); end; function WideIncludeTrailingBackslash(const S: WideString): WideString; begin Result := IncludeTrailingBackslash(S); end; end.
unit Q_ADS; interface procedure enqueue(e : integer); function dequeue : integer; function isEmpty : boolean; procedure init; procedure disposeQueue; procedure reallocQueue; procedure removeElementAt(pos : integer); implementation type intArray = array [1..1] of integer; VAR arrPtr : ^intArray; capacity : integer; top : integer; (* index of top element *) procedure init; begin if(arrPtr <> NIL) then begin writeln('Can''t initialize non-empty queue!'); halt; end; top := 0; capacity := 10; GetMem(arrPtr, SIZEOF(integer) * capacity); end; procedure enqueue(e : integer); begin if top >= capacity then reallocQueue; inc(top); (*$R-*) arrPtr^[top] := e; (*$R+*) end; function dequeue : integer; begin if isEmpty then begin writeln('Queue is empty'); halt; end; (*$R-*) dequeue := arrPtr^[1]; (*$R+*) removeElementAt(1); end; function isEmpty : boolean; begin isEmpty := top = 0; end; procedure disposeQueue; begin if arrPtr = NIL then begin writeln('Can''t dispose a uninitialized queue!'); halt; end; FreeMem(arrPtr, SIZEOF(integer) * capacity); arrPtr := NIL; end; procedure reallocQueue; var newArray : ^intArray; i : integer; begin GetMem(newArray, SIZEOF(INTEGER) * 2 * capacity); for i := 1 to top do begin (*$R-*) newArray^[i] := arrPtr^[i]; (*$R+*) end; FreeMem(arrPtr, SIZEOF(integer) * capacity); capacity := 2 * capacity; arrPtr := newArray; end; procedure removeElementAt(pos : integer); var element : integer; begin element := pos + 1; while element <= top do begin (*$R-*) arrPtr^[element - 1] := arrPtr^[element]; (*$R+*) inc(element); end; (*$R-*) arrPtr^[top] := 0; (*$R+*) dec(top); end; begin arrPtr := NIL; end.
program RunBackgroundTasks; {$IFDEF MSWINDOWS} {$APPTYPE CONSOLE} {$ENDIF} {$MODE DELPHI} uses {$IFDEF UNIX} cthreads, {$ENDIF} SysUtils, DateUtils, Quick.Commons, Quick.Console, Quick.Threads; type TMyTask = class private fId : Integer; fName : string; public property Id : Integer read fId write fId; property Name : string read fName write fName; procedure DoJob(task : ITask); procedure Retry(task : ITask; aException : Exception; var vStopRetries : Boolean); procedure Failed(task : ITask; aException : Exception); procedure Finished(task : ITask); end; var backgroundtasks : TBackgroundTasks; mytask : TMyTask; i : Integer; { TMyTask } procedure TMyTask.DoJob(task : ITask); var a, b, i : Integer; begin cout('[%s] task "%s" doing a %s job...',[DateTimeToStr(Now()),fName,task.Param[0].AsString],etInfo); Sleep(Random(1000)); a := Random(100); b := Random(5) + 1; i := a div b; cout('task "%s" result %d / %d = %d',[fName,a,b,i],etSuccess); end; procedure TMyTask.Retry(task : ITask; aException : Exception; var vStopRetries : Boolean); begin cout('task "%s" retrying (%s)',[fName,aException.Message],etWarning); end; procedure TMyTask.Failed(task : ITask; aException : Exception); begin cout('task "%s" failed (%s)',[fName,aException.Message],etError); end; procedure TMyTask.Finished(task : ITask); begin cout('task "%s" finished',[fName],etDebug); end; begin Console.LogVerbose := LOG_DEBUG; try backgroundtasks := TBackgroundTasks.Create(10); for i := 1 to 100 do begin mytask := TMyTask.Create; mytask.Id := i; mytask.Name := 'Task' + i.ToString; backgroundtasks.AddTask(['blue'],True,mytask.DoJob ).WaitAndRetry(10,100 ).OnRetry(mytask.Retry ).OnException(mytask.Failed ).OnTerminated(mytask.Finished ).Run; end; backgroundtasks.Start; cout('Running tasks in background!',etInfo); ConsoleWaitForEnterKey; backgroundtasks.Free; except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; end.
unit ce_mru; {$I ce_defines.inc} interface uses Classes, SysUtils, ce_interfaces, ce_observer, ce_project, ce_synmemo; type (** * 'Most Recently Used' list for strings. *) TCEMruList = class(TStringList) private fMaxCount: Integer; fObj: TObject; protected fChecking: boolean; procedure clearOutOfRange; procedure setMaxCount(aValue: Integer); function checkItem(const S: string): boolean; virtual; procedure Put(Index: Integer; const S: string); override; procedure InsertItem(Index: Integer; const S: string); override; published property maxCount: Integer read fMaxCount write setMaxCount; public constructor Create; virtual; procedure Insert(Index: Integer; const S: string); override; property objectTag: TObject read fObj write fObj; end; (** * MRU list for filenames. *) TCEMRUFileList = class(TCEMruList) protected function checkItem(const S: string): boolean; override; public procedure assign(src: TPersistent); override; end; (** * MRU list for D/text files. * Insertion is automatic (ICEMultiDocObserver). *) TCEMRUDocumentList = class(TCEMRUFileList, ICEMultiDocObserver) private procedure docNew(aDoc: TCESynMemo); procedure docFocused(aDoc: TCESynMemo); procedure docChanged(aDoc: TCESynMemo); procedure docClosing(aDoc: TCESynMemo); public constructor create; override; destructor destroy; override; end; (** * MRU list for the ceodit projects. * Insertion is automatic (ICEProjectObserver). *) TCEMRUProjectList = class(TCEMRUFileList, ICEProjectObserver) private procedure projNew(aProject: TCEProject); procedure projChanged(aProject: TCEProject); procedure projClosing(aProject: TCEProject); procedure projFocused(aProject: TCEProject); procedure projCompiling(aProject: TCEProject); public constructor create; override; destructor destroy; override; end; implementation constructor TCEMruList.Create; begin fMaxCount := 10; end; procedure TCEMruList.clearOutOfRange; begin while Count > fMaxCount do delete(Count-1); end; procedure TCEMruList.setMaxCount(aValue: Integer); begin if aValue < 0 then aValue := 0; if fMaxCount = aValue then exit; fMaxCount := aValue; clearOutOfRange; end; function TCEMruList.checkItem(const S: string): boolean; var i: NativeInt; begin i := indexOf(S); if i = -1 then exit(true); if i = 0 then exit(false); if Count < 2 then exit(false); exchange(i, i-1); exit( false); end; procedure TCEMruList.Put(Index: Integer; const S: string); begin if not (checkItem(S)) then exit; inherited; clearOutOfRange; end; procedure TCEMruList.InsertItem(Index: Integer; const S: string); begin if not (checkItem(S)) then exit; inherited; clearOutOfRange; end; procedure TCEMruList.Insert(Index: Integer; const S: string); begin if not (checkItem(S)) then exit; inherited; clearOutOfRange; end; procedure TCEMRUFileList.assign(src: TPersistent); var i: Integer; begin inherited; for i := Count-1 downto 0 do if not fileExists(Strings[i]) then Delete(i); end; function TCEMRUFileList.checkItem(const S: string): boolean; begin exit( inherited checkItem(S) and fileExists(S)); end; constructor TCEMRUDocumentList.create; begin inherited; EntitiesConnector.addObserver(self); end; destructor TCEMRUDocumentList.destroy; begin EntitiesConnector.removeObserver(self); inherited; end; procedure TCEMRUDocumentList.docNew(aDoc: TCESynMemo); begin end; procedure TCEMRUDocumentList.docFocused(aDoc: TCESynMemo); begin end; procedure TCEMRUDocumentList.docChanged(aDoc: TCESynMemo); begin end; procedure TCEMRUDocumentList.docClosing(aDoc: TCESynMemo); begin if FileExists(aDoc.fileName) and (aDoc.fileName <> aDoc.tempFilename) then Insert(0, aDoc.fileName); end; constructor TCEMRUProjectList.create; begin inherited; EntitiesConnector.addObserver(self); end; destructor TCEMRUProjectList.destroy; begin EntitiesConnector.removeObserver(self); inherited; end; procedure TCEMRUProjectList.projNew(aProject: TCEProject); begin end; procedure TCEMRUProjectList.projFocused(aProject: TCEProject); begin end; procedure TCEMRUProjectList.projChanged(aProject: TCEProject); begin end; procedure TCEMRUProjectList.projCompiling(aProject: TCEProject); begin end; procedure TCEMRUProjectList.projClosing(aProject: TCEProject); begin if FileExists(aProject.fileName) then Insert(0, aProject.fileName); end; initialization RegisterClasses([TCEMRUList, TCEMRUFileList, TCEMRUProjectList, TCEMRUDocumentList]); end.
{$MODE OBJFPC} {$INLINE ON} {$R-,Q-,S-,I-} {$OPTIMIZATION LEVEL3} {$DEFINE USEFILEIO} // remove this line in case of STD IO program SmartDog; const {$IFDEF USEFILEIO} InputFile = 'SMARTDOG.INP'; OutputFile = 'SMARTDOG.OUT'; {$ELSE} // use stdio InputFile = ''; OutputFile = ''; {$ENDIF} maxN = Round(1E5); maxXY = 2 * Round(1E3) + 1; type TPoint = record x, y, c: Integer; end; TRangeTree1DNode = record loc, glo: Integer; end; TRangeTree1D = array [1 .. maxXY] of TRangeTree1DNode; TRangeTree2DNode = packed record loc, glo: TRangeTree1D; end; TRangeTree2D = array [1 .. maxXY] of TRangeTree2DNode; var P: array [0 .. maxN] of TPoint; key, pos, l, h: array [1 .. maxXY] of Integer; Tree: TRangeTree2D; n, k: Integer; res, range: Integer; procedure Enter; var f: TextFile; i: Integer; minX, minY: Integer; begin AssignFile(f, InputFile); Reset(f); try ReadLn(f, n, k); P[0].x := 0; P[0].y := 0; minX := 0; minY := 0; for i := 1 to n do with P[i] do begin ReadLn(f, x, y, c); Inc(x, y); y := x - 2 * y; if x < minX then minX := x; if y < minY then minY := y; end; range := 0; for i := 0 to n do with P[i] do begin Dec(x, minX - 1); Dec(y, minY - 1); if x > range then range := x; if y > range then range := y; end; finally CloseFile(f); end; end; function Maximize(var target: Integer; value: Integer): Boolean; inline; begin Result := target < value; if Result then target := value; end; procedure Init; var count: Integer; procedure Build(x: Integer); begin if x > Range then Exit; l[x] := count + 1; Build(x * 2); Inc(count); key[x] := count; pos[count] := x; Build(x * 2 + 1); h[x] := count; end; begin count := 0; Build(1); FillChar(Tree, SizeOf(Tree), $FF); end; procedure UpdateY(var T: TRangeTree1D; y: Integer; f: Integer); inline; var node: Integer; begin node := pos[y]; if not Maximize(T[node].loc, f) then Exit; repeat if not Maximize(T[node].glo, f) then Break; node := node shr 1; until node = 0; end; procedure UpdateXY(x, y: Integer; f: Integer); inline; var node: Integer; begin node := pos[x]; UpdateY(Tree[node].loc, y, f); repeat UpdateY(Tree[node].glo, y, f); node := node shr 1; until node = 0; end; function QueryY(const T: TRangeTree1D; loy, hiy: Integer): Integer; function Request(node: Integer): Integer; begin if (node > Range) or (l[node] > hiy) or (h[node] < loy) then Exit(-1); if (l[node] >= loy) and (h[node] <= hiy) then Exit(T[node].glo); Result := Request(node shl 1); if (loy <= key[node]) and (key[node] <= hiy) then Maximize(Result, T[node].loc); Maximize(Result, Request(node shl 1 + 1)); end; begin Result := Request(1); end; function Query(lox, loy, hix, hiy: Integer): Integer; function Request(node: Integer): Integer; begin if (node > Range) or (l[node] > hix) or (h[node] < lox) then Exit(-1); if (l[node] >= lox) and (h[node] <= hix) then Exit(QueryY(Tree[node].glo, loy, hiy)); Result := Request(node shl 1); if (lox <= key[node]) and (key[node] <= hix) then Maximize(Result, QueryY(Tree[node].loc, loy, hiy)); Maximize(Result, Request(node shl 1 + 1)); end; begin Result := Request(1); end; procedure Optimize; var i, j: Integer; f: Integer; begin res := 0; with P[0] do UpdateXY(x, y, 0); for i := 1 to n do with P[i] do begin f := Query(x - k, y - k, x + k, y + k); if f >= 0 then begin UpdateXY(x, y, f + c); Maximize(res, f + c); end; end; end; procedure PrintResult; var f: TextFile; begin AssignFile(f, OutputFile); Rewrite(f); try write(f, res); finally CloseFile(f); end; end; begin Enter; Init; Optimize; PrintResult; end.
unit debugAnalysis; interface uses SysUtils, System.Classes, System.IOUtils, FMX.Types, System.DateUtils, FMX.Controls, FMX.Layouts, System.Generics.Collections , System.Diagnostics , FMX.Edit, FMX.StdCtrls, FMX.Clipboard, FMX.Platform, FMX.Objects, System.Types, StrUtils, FMX.Dialogs {$IF DEFINED(MSWINDOWS)} , System.Win.Registry, Windows {$ENDIF} {$IFDEF ANDROID}, Androidapi.JNI.GraphicsContentViewText, Androidapi.JNI.JavaTypes, Androidapi.Helpers, Androidapi.JNI.Net, Androidapi.JNI.Os, Androidapi.JNI.Webkit, Androidapi.JNIBridge {$ENDIF} ; {$IF DEFINED(ANDROID) OR DEFINED(IOS) OR DEFINED(LINUX)} const StrStartIteration = {$IFNDEF LINUX} 0 {$ELSE}1{$ENDIF}; type AnsiString = string; type WideString = string; type AnsiChar = Char; {$ELSE} const StrStartIteration = 1; {$ENDIF} type timeLogger = class private map : TDictionary< AnsiString , TStopwatch >; logList : TStringList; public procedure StartLog( name : AnsiString ); function GetInterval( name : AnsiString ): single; procedure AddToLog( name : AnsiString ); constructor Create( ); destructor Destroy(); override; end; var logData: TStringList; LOG_FILE_PATH: AnsiString; procedure assert(value: boolean; msg: AnsiString; sender: TObject = nil); procedure ExceptionHandler(sender: TObject; E: Exception); procedure saveLogFile(); procedure addLog(msg: AnsiString); procedure SendReport(url: AnsiString; msg: AnsiString); procedure SendUserReport(msg: AnsiString; SendLog, SendDeviceInfo: boolean); procedure SendAutoReport(msg: AnsiString; Stack: AnsiString; sender: AnsiString = ''); function getdeviceInfo(): AnsiString; function getDetailedData(): AnsiString; function memLeakAnsiString( v : AnsiString ): AnsiString; function RefCount(const _s: AnsiString): integer; procedure showRefCount(const _s: AnsiString); implementation uses misc; procedure showRefCount(const _s: AnsiString); begin tthread.Synchronize(nil , procedure begin showmessage( intToStr( refcount( _s ) ) ); end); end; function RefCount(const _s: AnsiString): integer; var ptr: PLongWord; begin ptr := Pointer(_s); Dec(Ptr, 2); Result := ptr^; end; function memLeakAnsiString( v : AnsiString ): AnsiString; var i: integer; a: integer; x: integer; b: integer; n, c: integer; output: AnsiString; sb: System.UInt8; S: array of System.UInt8; const Codes58: AnsiString = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; begin SetLength(S, (Length(V) * 2)); for i := 1 to (Length(V) div 2) do begin sb := System.UInt8(StrToInt('$' + Copy(V, ((i - 1) * 2) + 1, 2))); S[i] := sb; end; n := 34; SetLength(output, 34); while n > 0 do begin c := 0; for i := 1 to 25 do begin c := c * 256 + ord(S[i]); S[i] := System.UInt8(c div 58); c := c mod 58; end; output[n] := Codes58[c + 1]; dec(n); end; for n := 2 to Length(output) do begin if output[n] = '1' then begin Delete(output, n, 1); continue; end; break; end; result := output; //S := nil; Delete(output , low(output) , length(output) ); //Delete(S , low(S) , length(S) ); SetLength(output,0); //SetLength(S,0); SetLength(V,0); end; function getDetailedData(): AnsiString; {$IF DEFINED(MSWINDOWS)} var Reg: TRegistry; begin REsult := ''; Reg := TRegistry.Create(KEY_READ); if Reg.Access = KEY_READ then begin end; try Reg.RootKey := HKEY_LOCAL_MACHINE; if Reg.OpenKey('\HARDWARE\DESCRIPTION\System\CentralProcessor\0', False) then REsult := Reg.ReadString('ProcessorNameString'); finally Reg.Free; end; end; {$ENDIF} {$IF DEFINED(ANDROID)} var temp: AnsiString; begin temp := Format('Device Type: %s', [JStringToString(TJBuild.JavaClass.MODEL)]); temp := temp + Format('OS: %s', [JStringToString(TJBuild_VERSION.JavaClass.RELEASE)]); temp := temp + Format('OS Version: %s', [JStringToString(TJBuild_VERSION.JavaClass.RELEASE)]); REsult := temp; end; {$ENDIF} {$IF DEFINED(LINUX)} begin REsult := ''; end; {$ENDIF} {$IF DEFINED(IOS)} begin REsult := ''; end; {$ENDIF} // function CPUType: string; /// //////////////////////////////////////////////////// function getdeviceInfo(): AnsiString; var temp: AnsiString; begin REsult := ''; temp := misc.SYSTEM_NAME; if temp <> '' then REsult := REsult + 'os=' + temp; temp := getDetailedData; if temp <> '' then REsult := REsult + '&more=' + temp; end; procedure SendAutoReport(msg: AnsiString; Stack: AnsiString; sender: AnsiString = ''); var temp: AnsiString; begin if msg = '' then msg := 'empty'; if Stack = '' then Stack := 'empty'; if sender = '' then sender := 'empty'; temp := 'msg=' + msg + '&' + 'stack=' + Stack + '&' + 'sender=' + sender + '&' + 'ver=' + StringReplace(CURRENT_VERSION, '.', 'x', [rfReplaceAll]) + '&' + getdeviceInfo(); tthread.CreateAnonymousThread( procedure begin SendReport('https://hodler1.nq.pl/autoreport.php', temp); end).Start; end; procedure SendReport(url: AnsiString; msg: AnsiString); var StringURL: STRING; StringMSG: String; begin StringURL := url; StringMSG := msg; postDataOverHTTP(StringURL, StringMSG, False, true); end; procedure SendUserReport(msg: AnsiString; SendLog, SendDeviceInfo: boolean); var path: AnsiString; errorList, tmpTsl: TStringList; temp, log, DeviceInfo: AnsiString; begin if SendLog then begin errorList := TStringList.Create(); tmpTsl := TStringList.Create(); if Tdirectory.Exists( LOG_FILE_PATH ) then for path in TDirectory.GetFiles(LOG_FILE_PATH) do begin temp := ExtractFileName(path); temp := leftStr(temp, 3); if temp = 'LOG' then begin tmpTsl.LoadFromFile(path); errorList.Add(tmpTsl.DelimitedText); end; end; log := errorList.DelimitedText; tmpTsl.Free; errorList.Free; end else log := 'empty'; if SendDeviceInfo then begin DeviceInfo := getdeviceInfo(); end else DeviceInfo := 'empty'; temp := 'msg=' + msg + '&errlist=' + log + '&more=' + DeviceInfo; tthread.CreateAnonymousThread( procedure begin SendReport('https://hodler1.nq.pl/userreport.php', temp); end).Start; end; procedure addLog(msg: AnsiString); var timeStamp: String; begin if logData = nil then begin logData := TStringList.Create(); end; DateTimeToString(timeStamp, '[c]', Now); logData.Add(timeStamp + ':' + msg); end; procedure saveLogFile(); var temp: TStringList; Y, m, d: Word; begin {$IF DEFINED(MSWINDOWS) } if (logData <> nil) and (logData.Count > 0) then begin { temp := TStringList.Create(); temp.load } DecodeDate(Now, Y, m, d); // Format('%d.%d.%d', [Y, m, d]) if not TDirectory.Exists(LOG_FILE_PATH) then TDirectory.CreateDirectory( LOG_file_PATh ); logData.SaveToFile(System.IOUtils.TPath.combine(LOG_FILE_PATH, 'LOG_' + IntToStr(DateTimeToUnix(Now)) + '.log')); logData.DisposeOf; logData := nil; end; {$ENDIF} end; procedure ExceptionHandler(sender: TObject; E: Exception); begin addLog('------ERROR------'); addLog(E.Message); addLog('------STACK TRACE------'); addLog(E.StackTrace); addLog('------END------'); // showmessage( Exception.GetStackInfoStringProc( ExceptAddr ) ); if USER_ALLOW_TO_SEND_DATA then SendAutoReport(E.Message, E.StackTrace, sender.ClassName + ' ' + sender.UnitName); saveLogFile(); end; procedure assert(value: boolean; msg: AnsiString; sender: TObject = nil); begin {$IFDEF DEBUG} if value then begin raise Exception.Create(msg); end; {$ENDIF} end; { timeLogger } constructor timeLogger.Create( ); begin Inherited ; map := TDictionary< AnsiString , TStopwatch>.create(); logList := TStringList.Create(); end; destructor timeLogger.Destroy; begin map.Free; logList.Free; inherited destroy; end; procedure timeLogger.StartLog( name : AnsiString ); begin map.AddOrSetValue( name , TStopwatch.StartNew ); end; function timeLogger.GetInterval( name : AnsiString ): Single; var temp : TStopwatch; begin result := 0; if map.TryGetValue( name , temp ) then begin result := temp.Elapsed.TotalSeconds; end; end; procedure timeLogger.AddToLog( name : AnsiString ); begin Loglist.Add(name +': ' + floatToStr(GetInterval(name)) ) end; end.
unit Dt_Tasks; { $Id: Dt_Tasks.pas,v 1.2 2005/11/29 13:09:47 narry Exp $ } // $Log: Dt_Tasks.pas,v $ // Revision 1.2 2005/11/29 13:09:47 narry // - обновление: реализация конкретных типов задач // // Revision 1.1 2005/11/18 15:52:28 step // занесено в CVS // {$I DtDefine.inc} interface uses Windows, Messages, SysUtils, Classes, Contnrs, IdGlobal, IdIOHandler, l3Base, l3Stream, dt_Types; type TTaskType = (ttExport, ttImport, ttExportIncludedDocs, ttExportAnnotation); TTask = class(Tl3Base) private FUserID: Integer; protected procedure Init(aStream: TStream); virtual; abstract; procedure Store(aStream: TStream); virtual; abstract; procedure WriteString(aStream: TStream; const Str: String); public procedure ReadString(aStream: TStream; out aStr: String); procedure SaveTo(aIOHandler: TIdIOHandler); overload; procedure SaveTo(aStream: TStream); overload; class function RestoreFrom(aIOHandler: TIdIOHandler): TTask; overload; // как конструктор class function RestoreFrom(aStream: TStream): TTask; overload; // как конструктор class function TaskType: TTaskType; virtual; abstract; property UserID: Integer read FUserID write FUserID; end; TClassOfTask = class of TTask; TExportTask = class(TTask) private FAnnoTopicFileName: string; FDiapasonType: TDiapType; FDocID: Integer; FDocumentFileNameMask: string; FExportAnnoTopics: Boolean; FExportDirectory: string; FExportDocImage: Boolean; FExportDocument: Boolean; FExportEmpty: Boolean; FExportKW: Boolean; FExportRTFBody: Boolean; FFamily: Integer; FInternalFormat: Boolean; FKWFileName: string; FMultiUser: Boolean; FNumListFileName: string; FObjTopicFileName: string; FOnlyStructure: Boolean; FOutFileType: Longint; FOutputFileSize: LongInt; FReferenceFileNameMask: string; FSeparateFiles: Longint; protected class function TaskType: TTaskType; override; procedure Init(aStream: TStream); override; procedure Store(aStream: TStream); override; public {* - функция очистки объекта. Для перекрытия в потомках. } procedure Assign(P: TPersistent); override; property AnnoTopicFileName: string read FAnnoTopicFileName write FAnnoTopicFileName; property DiapasonType: TDiapType read FDiapasonType write FDiapasonType; property DocID: Integer read FDocID write FDocID; property DocumentFileNameMask: string read FDocumentFileNameMask write FDocumentFileNameMask; property ExportAnnoTopics: Boolean read FExportAnnoTopics write FExportAnnoTopics; property ExportDirectory: string read FExportDirectory write FExportDirectory; property ExportDocImage: Boolean read FExportDocImage write FExportDocImage; property ExportDocument: Boolean read FExportDocument write FExportDocument; property ExportEmpty: Boolean read FExportEmpty write FExportEmpty; property ExportKW: Boolean read FExportKW write FExportKW; property ExportRTFBody: Boolean read FExportRTFBody write FExportRTFBody; property Family: Integer read FFamily write FFamily; property InternalFormat: Boolean read FInternalFormat write FInternalFormat; property KWFileName: string read FKWFileName write FKWFileName; property MultiUser: Boolean read FMultiUser write FMultiUser; property NumListFileName: string read FNumListFileName write FNumListFileName; property ObjTopicFileName: string read FObjTopicFileName write FObjTopicFileName; property OnlyStructure: Boolean read FOnlyStructure write FOnlyStructure; property OutFileType: Longint read FOutFileType write FOutFileType; property OutputFileSize: LongInt read FOutputFileSize write FOutputFileSize; property ReferenceFileNameMask: string read FReferenceFileNameMask write FReferenceFileNameMask; property SeparateFiles: Longint read FSeparateFiles write FSeparateFiles; end; TImportTask = class(TTask) private FDeleteIncluded: Boolean; FIsAnnotation: Boolean; FIsRegion: Boolean; FSourceFolder: string; protected class function TaskType: TTaskType; override; procedure Init(aStream: TStream); override; procedure Store(aStream: TStream); override; public property DeleteIncluded: Boolean read FDeleteIncluded write FDeleteIncluded; property IsAnnotation: Boolean read FIsAnnotation write FIsAnnotation; property IsRegion: Boolean read FIsRegion write FIsRegion; property SourceFolder: string read FSourceFolder write FSourceFolder; end; TExportIncludedDocsTask = class(TTask) private protected class function TaskType: TTaskType; override; end; TExportAnnotationTask = class(TTask) private protected class function TaskType: TTaskType; override; end; implementation uses l3Memory; const c_TaskTypeToTaskClassMap: array[Low(TTaskType) .. High(TTaskType)] of TClassOfTask = ( TExportTask, TImportTask, TExportIncludedDocsTask, TExportAnnotationTask ); function TaskClassOf(const aTaskType: TTaskType): TClassOfTask; begin Result := c_TaskTypeToTaskClassMap[aTaskType]; end; { TTask } class function TTask.RestoreFrom(aIOHandler: TIdIOHandler): TTask; var l_TaskType: TTaskType; l_Stream: TStream; begin l_TaskType := TTaskType(aIOHandler.ReadInteger); Result := TaskClassOf(l_TaskType).Create; Result.UserID := aIOHandler.ReadInteger; l_Stream := Tl3MemoryStream.Create; try aIOHandler.ReadStream(l_Stream); l_Stream.Seek(0, 0); Result.Init(l_Stream); finally l3Free(l_Stream); end; end; procedure TTask.SaveTo(aIOHandler: TIdIOHandler); var l_Stream: TStream; begin aIOHandler.Write(Integer(Ord(TaskType))); aIOHandler.Write(USerID); l_Stream := Tl3MemoryStream.Create; try Store(l_Stream); aIOHandler.Write(l_Stream, 0, True); finally l3Free(l_Stream); end; end; class function TTask.RestoreFrom(aStream: TStream): TTask; var l_TaskType: Integer; l_UserID : Integer; begin aStream.Read(l_TaskType, SizeOf(Integer)); Result := TaskClassOf(TTaskType(l_TaskType)).Create; aStream.Read(l_UserID, SizeOf(Integer)); Result.UserID := l_UserID; Result.Init(aStream); end; procedure TTask.SaveTo(aStream: TStream); var l_TaskType: Integer; begin l_TaskType := Ord(TaskType); aStream.Write(l_TaskType, SizeOf(Integer)); aStream.Write(UserID, SizeOf(Integer)); Store(aStream); end; procedure TTask.WriteString(aStream: TStream; const Str: String); var l_Len: Integer; begin l_Len := Length(Str); aStream.Write(l_Len, SizeOf(l_Len)); if l_Len > 0 then aStream.Write(Str[1], l_Len); end; procedure TTask.ReadString(aStream: TStream; out aStr: String); var l_Len: Integer; begin aStream.Read(l_Len, SizeOf(l_Len)); SetLength(aStr, l_Len); if l_Len > 0 then aStream.Read(aStr[1], l_Len); end; procedure TExportTask.Assign(P: TPersistent); begin inherited; if (P Is TExportTask) then begin AnnoTopicFileName:= TExportTask(P).AnnoTopicFileName; DiapasonType:= TExportTask(P).DiapasonType; DocID:= TExportTask(P).DocID; DocumentFileNameMask:= TExportTask(P).DocumentFileNameMask; ExportAnnoTopics:= TExportTask(P).ExportAnnoTopics; ExportDirectory:= TExportTask(P).ExportDirectory; ExportDocImage:= TExportTask(P).ExportDocImage; ExportDocument:= TExportTask(P).ExportDocument; ExportEmpty:= TExportTask(P).ExportEmpty; ExportKW:= TExportTask(P).ExportKW; ExportRTFBody:= TExportTask(P).ExportRTFBody; Family:= TExportTask(P).Family; InternalFormat:= TExportTask(P).InternalFormat; KWFileName:= TExportTask(P).KWFileName; MultiUser:= TExportTask(P).MultiUser; NumListFileName:= TExportTask(P).NumListFileName; ObjTopicFileName:= TExportTask(P).ObjTopicFileName; OnlyStructure:= TExportTask(P).OnlyStructure; OutFileType:= TExportTask(P).OutFileType; OutputFileSize:= TExportTask(P).OutputFileSize; ReferenceFileNameMask:= TExportTask(P).ReferenceFileNameMask; SeparateFiles:= TExportTask(P).SeparateFiles; end; // if (P Is TExportTask) end; { TExportTask } procedure TExportTask.Init(aStream: TStream); var l_Value: Integer; begin with aStream do begin ReadString(aStream, FAnnoTopicFileName); Read(l_Value, SizeOf(Integer)); FDiapasonType := TDiapType(l_Value); Read(FDOcID, SizeOf(Integer)); ReadString(aStream, FDocumentFileNameMask); Read(FExportAnnoTopics, SizeOf(Boolean)); ReadString(aStream, FExportDirectory); Read(FExportDocImage, SizeOf(Boolean)); Read(FExportDocument, SizeOf(Boolean)); Read(FExportEmpty, SizeOf(Boolean)); Read(FExportKW, SizeOf(Boolean)); Read(FExportRTFBody, SizeOF(Boolean)); Read(FFamily, SizeOf(Integer)); Read(FInternalFormat, SizeOf(Boolean)); ReadString(aStream, FKWFileName); Read(FMultiUser, SizeOf(Boolean)); ReadString(aStream, FNumListFileName); ReadString(aStream, FObjTopicFileName); Read(FOnlyStructure, SizeOf(Boolean)); Read(FOutFileType, SizeOf(Longint)); Read(FOutputFileSize, SizeOf(LongInt)); ReadString(aStream, FReferenceFileNameMask); Read(FSeparateFiles, SizeOf(Longint)); end; // with aStream end; procedure TExportTask.Store(aStream: TStream); var l_Value : Integer; begin with aStream do begin WriteString(aStream, FAnnoTopicFileName); l_Value := Integer(Ord(FDiapasonType)); Write(l_Value, SizeOf(Integer)); Write(FDocID, SizeOf(FDocID)); WriteString(aStream, FDocumentFileNameMask); Write(FExportAnnoTopics, SizeOf(Boolean)); WriteString(aStream, FExportDirectory); Write(FExportDocImage, SizeOf(Boolean)); Write(FExportDocument, SizeOf(Boolean)); Write(FExportEmpty, SizeOf(Boolean)); Write(FExportKW, SizeOf(Boolean)); Write(FExportRTFBody, SizeOF(Boolean)); write(FFamily, SizeOf(Integer)); Write(FInternalFormat, SizeOf(Boolean)); WriteString(aStream, FKWFileName); Write(FMultiUser, SizeOf(Boolean)); WriteString(aStream, FNumListFileName); WriteString(aStream, FObjTopicFileName); Write(FOnlyStructure, SizeOf(Boolean)); Write(FOutFileType, SizeOf(Longint)); Write(FOutputFileSize, SizeOf(LongInt)); WriteString(aStream, FReferenceFileNameMask); Write(FSeparateFiles, SizeOf(Longint)); end; // with aStream end; class function TExportTask.TaskType: TTaskType; begin Result := ttExport; end; procedure TImportTask.Init(aStream: TStream); begin aStream.Read(FDeleteIncluded, SizeOf(Boolean)); aStream.Read(FIsAnnotation, SizeOf(Boolean)); aStream.Read(FIsRegion, SizeOf(Boolean)); ReadString(aStream, FSourceFolder); end; procedure TImportTask.Store(aStream: TStream); begin aStream.Write(FDeleteIncluded, SizeOf(Boolean)); aStream.Write(FIsAnnotation, SizeOf(Boolean)); aStream.Write(FIsRegion, SizeOf(Boolean)); WriteString(aStream, FSourceFolder); end; class function TImportTask.TaskType: TTaskType; begin Result := ttImport; end; class function TExportIncludedDocsTask.TaskType: TTaskType; begin Result := ttExportIncludedDocs; end; class function TExportAnnotationTask.TaskType: TTaskType; begin Result := ttExportAnnotation; end; end.
{$I tdl_dire.inc} {$IFDEF USEOVERLAYS} {$O+,F+} {$ENDIF} unit tdl_tset; { Unit to handle "title sets": Data structures that contain a set of 16-bit word title IDs. The main menu screen "title picker" works against a title set. The initial title set contains all titleIDs in the index (ie. everything). Later, if the user wants to see only favorites via CTRL-F, a new title set is built from only titles marked as a favorite, and then that title set becomes the active title set. Title sets are also used with search-as-you-type: Each successful word input by the user is used to build subsequent title sets that narrow down the filter results. If the user's filter goes backwards by the user backspacing, previous title sets can be cached so that the results display updates instantly. The intrepid coder will no doubt be wondering at this point why there are no .insert() or .delete() or other routines in the TTitleSet object other than init() and done: This is because we need to be able to build and tear down title sets very quickly, and populating a 1000-item title set using 1000 .insert() CALLs on a 4.77 MHz system is not going to fly here. So, the object mostly serves to correctly alloc/dealloc title set arrays. } interface uses objects, tdl_glob; const maxTitleSets=16; activeSet:byte=0; type PTitleSet=^TTitleSet; TTitleSet=object(TObject) PUBLIC numTitles:word; TitleIDs:PTitleArray; Constructor Init(numElements:word); Destructor Done; VIRTUAL; end; implementation Constructor TTitleSet.Init; begin Inherited Init; numTitles:=numElements; getmem(TitleIDs,numTitles * sizeof(word)); end; Destructor TTitleSet.Done; begin freemem(TitleIDs,numTitles * sizeof(word)); Inherited Done; end; end.
unit DBFToolsUnit; {$IFDEF FPC} {$mode objfpc}{$H+} {$ENDIF} interface uses Classes, SysUtils, toolsunit, db, Dbf; type { TDBFDBConnector } TDBFDBConnector = class(TDBConnector) protected procedure CreateNDatasets; override; procedure CreateFieldDataset; override; procedure DropNDatasets; override; procedure DropFieldDataset; override; Function InternalGetNDataset(n : integer) : TDataset; override; Function InternalGetFieldDataset : TDataSet; override; public function GetTraceDataset(AChange : Boolean) : TDataset; override; end; { TDbfTraceDataset } TDbfTraceDataset = class(Tdbf) protected procedure SetCurrentRecord(Index: Longint); override; procedure RefreshInternalCalcFields(Buffer: PChar); override; procedure InternalInitFieldDefs; override; procedure CalculateFields(Buffer: PChar); override; procedure ClearCalcFields(Buffer: PChar); override; end; implementation procedure TDBFDBConnector.CreateNDatasets; var countID,n : integer; begin for n := 0 to MaxDataSet do begin with TDbf.Create(nil) do begin FilePath := dbname; TableName := 'fpdev_'+inttostr(n)+'.db'; FieldDefs.Add('ID',ftInteger); FieldDefs.Add('NAME',ftString,50); CreateTable; Open; if n > 0 then for countId := 1 to n do begin Append; FieldByName('ID').AsInteger := countID; FieldByName('NAME').AsString := 'TestName'+inttostr(countID); // Explicitly call .post, since there could be a bug which disturbs // the automatic call to post. (example: when TDataset.DataEvent doesn't // work properly) Post; end; if state = dsinsert then Post; Close; Free; end; end; end; procedure TDBFDBConnector.CreateFieldDataset; var i : integer; begin with TDbf.Create(nil) do begin FilePath := dbname; TableName := 'fpdev_field.db'; FieldDefs.Add('ID',ftInteger); FieldDefs.Add('FSTRING',ftString,10); FieldDefs.Add('FSMALLINT',ftSmallint); FieldDefs.Add('FINTEGER',ftInteger); // FieldDefs.Add('FWORD',ftWord); FieldDefs.Add('FBOOLEAN',ftBoolean); FieldDefs.Add('FFLOAT',ftFloat); // FieldDefs.Add('FCURRENCY',ftCurrency); // FieldDefs.Add('FBCD',ftBCD); FieldDefs.Add('FDATE',ftDate); // FieldDefs.Add('FTIME',ftTime); FieldDefs.Add('FDATETIME',ftDateTime); FieldDefs.Add('FLARGEINT',ftLargeint); CreateTable; Open; for i := 0 to testValuesCount-1 do begin Append; FieldByName('ID').AsInteger := i; FieldByName('FSTRING').AsString := testStringValues[i]; FieldByName('FSMALLINT').AsInteger := testSmallIntValues[i]; FieldByName('FINTEGER').AsInteger := testIntValues[i]; FieldByName('FBOOLEAN').AsBoolean := testBooleanValues[i]; FieldByName('FFLOAT').AsFloat := testFloatValues[i]; ShortDateFormat := 'yyyy-mm-dd'; FieldByName('FDATE').AsDateTime := StrToDate(testDateValues[i]); FieldByName('FLARGEINT').AsLargeInt := testLargeIntValues[i]; Post; end; Close; end; end; procedure TDBFDBConnector.DropNDatasets; var n : integer; begin for n := 0 to MaxDataSet do DeleteFile(ExtractFilePath(dbname)+PathDelim+'fpdev_'+inttostr(n)+'.db'); end; procedure TDBFDBConnector.DropFieldDataset; begin DeleteFile(ExtractFilePath(dbname)+PathDelim+'fpdev_field.db'); end; function TDBFDBConnector.InternalGetNDataset(n: integer): TDataset; begin Result := TDbf.Create(nil); with (result as TDbf) do begin FilePath := dbname; TableName := 'fpdev_'+inttostr(n)+'.db'; end; end; function TDBFDBConnector.InternalGetFieldDataset: TDataSet; begin Result := TDbf.Create(nil); with (result as TDbf) do begin FilePath := dbname; TableName := 'fpdev_field.db'; end; end; function TDBFDBConnector.GetTraceDataset(AChange: Boolean): TDataset; var ADS, AResDS : TDbf; begin ADS := GetNDataset(AChange,15) as TDbf; AResDS := TDbfTraceDataset.Create(nil); AResDS.FilePath:=ADS.FilePath; AResDs.TableName:=ADS.TableName; Result:=AResDS; end; { TDbfTraceDataset } procedure TDbfTraceDataset.SetCurrentRecord(Index: Longint); begin DataEvents := DataEvents + 'SetCurrentRecord' + ';'; inherited SetCurrentRecord(Index); end; procedure TDbfTraceDataset.RefreshInternalCalcFields(Buffer: PChar); begin DataEvents := DataEvents + 'RefreshInternalCalcFields' + ';'; inherited RefreshInternalCalcFields(Buffer); end; procedure TDbfTraceDataset.InternalInitFieldDefs; var i : integer; IntCalcFieldName : String; begin // To fake a internal calculated field, set it's fielddef InternalCalcField // property to true, before the dataset is opened. // This procedure takes care of setting the automatically created fielddef's // InternalCalcField property to true. (works for only one field) IntCalcFieldName:=''; for i := 0 to FieldDefs.Count -1 do if fielddefs[i].InternalCalcField then IntCalcFieldName := FieldDefs[i].Name; inherited InternalInitFieldDefs; if IntCalcFieldName<>'' then with FieldDefs.find(IntCalcFieldName) do begin InternalCalcField := True; end; end; procedure TDbfTraceDataset.CalculateFields(Buffer: PChar); begin DataEvents := DataEvents + 'CalculateFields' + ';'; inherited CalculateFields(Buffer); end; procedure TDbfTraceDataset.ClearCalcFields(Buffer: PChar); begin DataEvents := DataEvents + 'ClearCalcFields' + ';'; inherited ClearCalcFields(Buffer); end; initialization RegisterClass(TDBFDBConnector); end.
unit fEnemyProperties; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, GR32_Image, DanHexEdit, cMegaROM, cConfiguration; type TfrmEnemyScreenChanger = class(TForm) imgEnemyPortrait: TImage32; lblEnemy: TLabel; cbEnemies: TComboBox; cmdCancel: TButton; cmdOK: TButton; lblScreenNumber: TLabel; bitmap32list: TBitmap32List; cbScreens: TComboBox; lblX: TLabel; lblY: TLabel; txtX: TDanHexEdit; txtY: TDanHexEdit; procedure FormShow(Sender: TObject); procedure cbEnemiesChange(Sender: TObject); procedure cmdOKClick(Sender: TObject); private _ROMData : TMegamanROM; _EditorConfig : TRRConfig; _ID : Integer; _PrevID : Byte; procedure LoadEnemyBitmap(pID : Integer); { Private declarations } public property ID : Integer read _ID write _ID; property ROMData : TMegamanROM read _ROMData write _ROMData; property EditorConfig : TRRConfig read _EditorConfig write _EditorConfig; { Public declarations } end; var frmEnemyScreenChanger: TfrmEnemyScreenChanger; implementation {$R *.dfm} procedure TfrmEnemyScreenChanger.FormShow(Sender: TObject); var i : Integer; begin LoadEnemyBitmap(_ROMData.CurrLevel.Enemies[_ID].ID); cbEnemies.Items := _ROMData.EnemyDescriptions; cbEnemies.ItemIndex := _ROMData.CurrLevel.Enemies[_ID].ID; txtX.Text := IntToHex(_ROMData.CurrLevel.Enemies[_ID].X,2); txtY.Text := IntToHex(_ROMData.CurrLevel.Enemies[_ID].Y,2); { if _EditorConfig.UseStandardScrolllengths = true then begin for i := _ROMData.CurrLevel.Properties['ScreenStartCheck1'].Value to _ROMData.CurrLevel.Properties['ScreenStartCheck1'].Value + _ROMData.CurrLevel.RoomAmount do cbScreens.Items.Add(IntToHex(i,2)); end else begin} for i := _ROMData.CurrLevel.Properties['ScreenStartCheck1'].Value to $2F do cbScreens.Items.Add(IntToHex(i,2)); // end; cbScreens.ItemIndex := cbScreens.Items.IndexOf (IntToHex( _ROMData.CurrLevel.Enemies[_ID].ScreenID,2)); _PrevID := _ROMData.CurrLevel.Enemies[_ID].ID; end; procedure TfrmEnemyScreenChanger.LoadEnemyBitmap(pID : Integer); var Bitmap : TBitmap; begin if FileExists(ExtractFileDir(Application.ExeName) + '\Data\EnemyGFX\' + IntToHex(pID,2) + '.bmp') = True then begin Bitmap := TBitmap.Create; try Bitmap.LoadFromFile(ExtractFileDir(Application.ExeName) + '\Data\EnemyGFX\' + IntToHex(pID,2) + '.bmp'); imgEnemyPortrait.ClientWidth := Bitmap.Width; imgEnemyPortrait.ClientHeight := Bitmap.Height; finally FreeAndNil(Bitmap); end; self.ClientWidth := imgEnemyPortrait.Left + imgEnemyPortrait.Width + 7; imgEnemyPortrait.Bitmap.LoadFromFile(ExtractFileDir(Application.ExeName) + '\Data\EnemyGFX\' + IntToHex(pID,2) + '.bmp'); end else begin imgEnemyPortrait.ClientWidth := bitmap32list.Bitmap[0].Width; imgEnemyPortrait.ClientHeight := bitmap32list.Bitmap[0].Height; ClientWidth := imgEnemyPortrait.Left + imgEnemyPortrait.Width + 7; imgEnemyPortrait.Bitmap := bitmap32list.Bitmap[0]; end; end; procedure TfrmEnemyScreenChanger.cbEnemiesChange(Sender: TObject); begin _PrevID := cbEnemies.ItemIndex; LoadEnemyBitmap(cbEnemies.ItemIndex); end; procedure TfrmEnemyScreenChanger.cmdOKClick(Sender: TObject); begin if _ROMData.CurrLevel.Enemies[_ID].ScreenID <> StrToInt('$' + cbScreens.Items[cbScreens.ItemIndex]) then _ROMData.Changed := True; _ROMData.CurrLevel.Enemies[_ID].ScreenID := StrToInt('$' + cbScreens.Items[cbScreens.ItemIndex]); if _ROMData.CurrLevel.Enemies[_ID].ID <> cbEnemies.ItemIndex then _ROMData.Changed := True; _ROMData.CurrLevel.Enemies[_ID].ID := cbEnemies.ItemIndex; _ROMData.CurrLevel.Enemies[_ID].X := StrToInt('$' + txtX.Text); _ROMData.CurrLevel.Enemies[_ID].Y := StrToInt('$' + txtY.Text); { if chkFollow.Checked = True then _ROMData.Room := StrToInt('$' + cbScreens.Items[cbScreens.ItemIndex]);} end; end.
{ ************************************************************************************************** } { } { Unit uDelphiVersions } { unit retrieves the delphi ide installed versions for the Delphi IDE Theme Editor } { } { The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); } { you may not use this file except in compliance with the License. You may obtain a copy of the } { License at http://www.mozilla.org/MPL/ } { } { Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF } { ANY KIND, either express or implied. See the License for the specific language governing rights } { and limitations under the License. } { } { The Original Code is uDelphiVersions.pas. } { } { The Initial Developer of the Original Code is Rodrigo Ruz V. } { Portions created by Rodrigo Ruz V. are Copyright (C) 2011-2023 Rodrigo Ruz V. } { All Rights Reserved. } { } { ************************************************************************************************** } unit uDelphiVersions; interface uses Graphics, SysUtils, Classes, ComCtrls; {$DEFINE OLDEVERSIONS_SUPPORT} type TDelphiVersions = ( {$IFDEF OLDEVERSIONS_SUPPORT} Delphi5, Delphi6, {$ENDIF} Delphi7, Delphi8, Delphi2005, Delphi2006, Delphi2007, Delphi2009, Delphi2010, DelphiXE); const {$IFDEF OLDEVERSIONS_SUPPORT} DelphiOldVersions = 2; DelphiOldVersionNumbers: array [0 .. DelphiOldVersions - 1] of TDelphiVersions = (Delphi5, Delphi6); DelphiOldColorsCount = 16; { BGR Color0=$000000 Color1=$000080 Color2=$008000 Color3=$008080 Color4=$800000 Color5=$800080 Color6=$808000 Color7=$C0C0C0 Color8=$808080 Color9=$0000FF Color10=$00FF00 Color11=$00FFFF Color12=$FF0000 Color13=$FF00FF Color14=$FFFF00 Color15=$FFFFFF } DelphiOldColorsList: array [0 .. DelphiOldColorsCount - 1] of TColor = ($000000, $000080, $008000, $008080, $800000, $800080, $808000, $C0C0C0, $808080, $0000FF, $00FF00, $00FFFF, $FF0000, $FF00FF, $FFFF00, $FFFFFF) { ( $000000,$800000,$008000,$808000, $000080,$800080,$008080,$C0C0C0, $808080,$FF0000,$00FF00,$FFFF00, $0000FF,$FF00FF,$00FFFF,$FFFFFF ) } ; {$ENDIF} DelphiVersionsNames: array [TDelphiVersions] of string = ( {$IFDEF OLDEVERSIONS_SUPPORT} 'Delphi 5', 'Delphi 6', {$ENDIF} 'Delphi 7', 'Delphi 8', 'BDS 2005', 'BDS 2006', 'RAD Studio 2007', 'RAD Studio 2009', 'RAD Studio 2010', 'RAD Studio XE'); DelphiVersionNumbers: array [TDelphiVersions] of double = ( {$IFDEF OLDEVERSIONS_SUPPORT} 13, // 'Delphi 5', 14, // 'Delphi 6', {$ENDIF} 15, // 'Delphi 7', 16, // 'Delphi 8', 17, // 'BDS 2005', 18, // 'BDS 2006', 18.5, // 'RAD Studio 2007', 20, // 'RAD Studio 2009', 21, // 'RAD Studio 2010', 22 // 'RAD Studio XE' ); DelphiRegPaths: array [TDelphiVersions] of string = ( {$IFDEF OLDEVERSIONS_SUPPORT} '\Software\Borland\Delphi\5.0', '\Software\Borland\Delphi\6.0', {$ENDIF} '\Software\Borland\Delphi\7.0', '\Software\Borland\BDS\2.0', '\Software\Borland\BDS\3.0', '\Software\Borland\BDS\4.0', '\Software\Borland\BDS\5.0', '\Software\CodeGear\BDS\6.0', '\Software\CodeGear\BDS\7.0', '\Software\Embarcadero\BDS\8.0'); procedure FillListViewDelphiVersions(ListView: TListView); function IsDelphiIDERunning(const DelphiIDEPath: TFileName): boolean; function GetFileVersion(const exeName: string): string; {$IFDEF OLDEVERSIONS_SUPPORT} function DelphiIsOldVersion(DelphiVersion: TDelphiVersions): boolean; function GetIndexClosestColor(AColor: TColor): Integer; {$ENDIF} function GetDelphiVersionMappedColor(AColor: TColor; DelphiVersion: TDelphiVersions): TColor; { [HKEY_CURRENT_USER\Software\Embarcadero\BDS\8.0\Editor\Highlight\Attribute Names] "Bold"="False" "Italic"="False" "Underline"="False" "Default Foreground"="False" "Default Background"="False" "Foreground Color New"="$00DE4841" "Background Color New"="$00272727" } implementation uses PsAPI, tlhelp32, Controls, ImgList, CommCtrl, ShellAPI, Windows, uRegistry, Registry; {$IFDEF OLDEVERSIONS_SUPPORT} function DelphiIsOldVersion(DelphiVersion: TDelphiVersions): boolean; var i: Integer; begin Result := False; for i := 0 to DelphiOldVersions - 1 do if DelphiVersion = DelphiOldVersionNumbers[i] then begin Result := True; exit; end; end; function GetIndexClosestColor(AColor: TColor): Integer; var SqrDist, SmallSqrDist: double; i, R1, G1, B1, R2, G2, B2: Integer; begin Result := 0; SmallSqrDist := Sqrt(SQR(255) * 3); R1 := GetRValue(AColor); G1 := GetGValue(AColor); B1 := GetBValue(AColor); for i := 0 to DelphiOldColorsCount - 1 do begin R2 := GetRValue(DelphiOldColorsList[i]); G2 := GetGValue(DelphiOldColorsList[i]); B2 := GetBValue(DelphiOldColorsList[i]); SqrDist := Sqrt(SQR(R1 - R2) + SQR(G1 - G2) + SQR(B1 - B2)); if SqrDist < SmallSqrDist then begin Result := i; SmallSqrDist := SqrDist; end end end; {$ENDIF} function GetDelphiVersionMappedColor(AColor: TColor; DelphiVersion: TDelphiVersions): TColor; begin Result := AColor; {$IFDEF OLDEVERSIONS_SUPPORT} if DelphiIsOldVersion(DelphiVersion) then Result := DelphiOldColorsList[GetIndexClosestColor(AColor)]; {$ENDIF} end; function GetFileVersion(const exeName: string): string; const c_StringInfo = 'StringFileInfo\040904E4\FileVersion'; var n, Len: cardinal; Buf, Value: PChar; begin Result := ''; n := GetFileVersionInfoSize(PChar(exeName), n); if n > 0 then begin Buf := AllocMem(n); try GetFileVersionInfo(PChar(exeName), 0, n, Buf); if VerQueryValue(Buf, PChar(c_StringInfo), Pointer(Value), Len) then begin Result := Trim(Value); end; finally FreeMem(Buf, n); end; end; end; function ProcessFileName(PID: DWORD): string; var Handle: THandle; begin Result := ''; Handle := OpenProcess(PROCESS_QUERY_INFORMATION or PROCESS_VM_READ, False, PID); if Handle <> 0 then try SetLength(Result, MAX_PATH); if GetModuleFileNameEx(Handle, 0, PChar(Result), MAX_PATH) > 0 then SetLength(Result, StrLen(PChar(Result))) else Result := ''; finally CloseHandle(Handle); end; end; function IsDelphiIDERunning(const DelphiIDEPath: TFileName): boolean; var HandleSnapShot: cardinal; EntryParentProc: TProcessEntry32; begin Result := False; HandleSnapShot := CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if HandleSnapShot = INVALID_HANDLE_VALUE then exit; try EntryParentProc.dwSize := SizeOf(EntryParentProc); if Process32First(HandleSnapShot, EntryParentProc) then repeat if CompareText(ExtractFileName(DelphiIDEPath), EntryParentProc.szExeFile) = 0 then if CompareText(ProcessFileName(EntryParentProc.th32ProcessID), DelphiIDEPath) = 0 then begin Result := True; break; end; until not Process32Next(HandleSnapShot, EntryParentProc); finally CloseHandle(HandleSnapShot); end; end; procedure ExtractIconFileToImageList(ImageList: TCustomImageList; const Filename: string); var FileInfo: TShFileInfo; begin if FileExists(Filename) then begin FillChar(FileInfo, SizeOf(FileInfo), 0); SHGetFileInfo(PChar(Filename), 0, FileInfo, SizeOf(FileInfo), SHGFI_ICON or SHGFI_SMALLICON); if FileInfo.hIcon <> 0 then begin ImageList_AddIcon(ImageList.Handle, FileInfo.hIcon); DestroyIcon(FileInfo.hIcon); end; end; end; procedure FillListViewDelphiVersions(ListView: TListView); var DelphiComp: TDelphiVersions; Filename: string; Found: boolean; Item: TListItem; begin for DelphiComp := Low(TDelphiVersions) to High(TDelphiVersions) do begin Found := RegKeyExists(DelphiRegPaths[DelphiComp], HKEY_CURRENT_USER); if Found then Found := RegReadStr(DelphiRegPaths[DelphiComp], 'App', Filename, HKEY_CURRENT_USER) and FileExists(Filename); if not Found then begin Found := RegKeyExists(DelphiRegPaths[DelphiComp], HKEY_LOCAL_MACHINE); if Found then Found := RegReadStr(DelphiRegPaths[DelphiComp], 'App', Filename, HKEY_LOCAL_MACHINE) and FileExists(Filename); end; if Found then begin ExtractIconFileToImageList(ListView.SmallImages, Filename); Item := ListView.Items.Add; Item.ImageIndex := ListView.SmallImages.Count - 1; Item.Caption := DelphiVersionsNames[DelphiComp]; Item.SubItems.Add(Filename); Item.Data := Pointer(Ord(DelphiComp)); end; end; end; end.
unit XMLDemo; {*************************************************************************} { } { Hitsoft Xml Object Library } { } { Copyright (C) 2009 Hitsoft LLC. (http://opensource.hitsoft-it.com) } { } { This program is free software: you can redistribute it and/or modify } { it under the terms of the GNU General Public License as published by } { the Free Software Foundation, either version 3 of the License, or } { (at your option) any later version. } { } { This program is distributed in the hope that it will be useful, } { but WITHOUT ANY WARRANTY; without even the implied warranty of } { MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the } { GNU General Public License for more details. } { } { You should have received a copy of the GNU General Public License } { along with this program. If not, see <http://www.gnu.org/licenses/>. } { } {*************************************************************************} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, RttiClasses; type TForm1 = class(TForm) Panel1: TPanel; Button1: TButton; Button2: TButton; Panel2: TPanel; mmo1: TMemo; lbl1: TLabel; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation uses XMLFile, XMLModel; {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); var Model: TDemoModel; begin Model := TDemoModel.Create; Model.Number := 1; Model.Caption := 'Hello'; Model.Birthday := Now; Model.Price := 235.04; Model.SubNode.Hello := '2008 Year'; Model.InsertInterval(12.5); Model.InsertInterval(12.5 * 2); Model.InsertInterval(12.5 * 3); Model.InsertInterval(12.5 * 4); Model.InsertInterval(12.5 * 5); SaveToFile('demo.xml', Model); end; procedure TForm1.Button2Click(Sender: TObject); var Model: TDemoModel; begin Model := TDemoModel.Create; if FileExists('demo.xml') then begin LoadFromFile('demo.xml', Model); mmo1.Lines.Text := SaveToString(Model); end; end; end.
unit uDespesas; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, UFrmPadrao, Data.DB, Vcl.StdCtrls, ZDataset, Vcl.ComCtrls, Vcl.DBCtrls, Vcl.Buttons, Vcl.ExtCtrls, RxToolEdit, RxCurrEdit,uDtmPrincipal,uDespesa,uEnun,uUsuarioLogado, ZAbstractRODataset, ZAbstractDataset, Vcl.Mask, Vcl.Grids, Vcl.DBGrids; type TfrmDespesas = class(TfrmPadrao) cbDespesa: TComboBox; edtDescricao: TLabeledEdit; edtValor: TCurrencyEdit; Label11: TLabel; edtDataPrevisao: TDateEdit; Label9: TLabel; lkpDespesa: TDBLookupComboBox; Label1: TLabel; zqTipoDespesa: TZQuery; dsTipoDespesa: TDataSource; Label2: TLabel; edtCodigo: TLabeledEdit; zqTipoDespesaTIPODR_Cod: TIntegerField; zqTipoDespesaTIPODR_Tipo: TWideStringField; zqTipoDespesaTIPODR_Desc: TWideStringField; zqPrincipalDesp_Cod: TIntegerField; zqPrincipalDesp_Tipo: TIntegerField; zqPrincipalDesp_Descricao: TWideStringField; zqPrincipalDesp_dataVencimento: TDateTimeField; zqPrincipalDesp_Valor: TFloatField; zqPrincipalDesp_Status: TWideStringField; procedure FormShow(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnAlterarClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } vDespesa:TDespesa; vUsuarioLogado : TUsuarioLogado; //vGrupo:TGrupo; function Apagar:Boolean; override; function Gravar(EstadoDoCadastro:TEstadoCadastro):Boolean; override; end; var frmDespesas: TfrmDespesas; implementation {$R *.dfm} { TfrmDespesas } function TfrmDespesas.Apagar: Boolean; begin if vDespesa.Selecionar(zqPrincipal.FieldByName('DESP_Cod').AsInteger) then begin Result:= vDespesa.Apagar; end; end; procedure TfrmDespesas.btnAlterarClick(Sender: TObject); begin inherited; if vDespesa.Selecionar(zqPrincipal.FieldByName('DESP_Cod').AsInteger) then begin edtCodigo.Text :=IntToStr(vDespesa.Codigo); lkpDespesa.KeyValue :=vDespesa.Tipo; edtDescricao.Text :=vDespesa.Descricao; cbDespesa.text :=vDespesa.Status; edtDataPrevisao.date :=vDespesa.DataVencimento; edtValor.Text :=FloatToStr(vDespesa.Valor); end else begin btnCancelar.Click; Abort; end; end; procedure TfrmDespesas.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; if Assigned(vDespesa) then FreeAndNil(vDespesa); if Assigned(zqTipoDespesa) then FreeAndNil(zqTipoDespesa); end; procedure TfrmDespesas.FormCreate(Sender: TObject); begin inherited; vDespesa := TDespesa.Create(DtmPrincipal.ConexaoDB); //vGrupo := TGrupo.Create(DtmPrincipal.ConexaoDB); IndiceAtual :='DESP_TIPO'; end; procedure TfrmDespesas.FormShow(Sender: TObject); begin inherited; zqPrincipal.Open; zqTipoDespesa.Open; end; function TfrmDespesas.Gravar(EstadoDoCadastro: TEstadoCadastro): Boolean; begin if edtCodigo.Text<>EmptyStr then vDespesa.Codigo:=StrToInt(edtCodigo.Text) else vDespesa.Codigo:=0; vDespesa.Tipo :=lkpDespesa.KeyValue; vDespesa.Descricao :=edtDescricao.Text; vDespesa.DataVencimento := edtDataPrevisao.date; vDespesa.valor := StrToFloat(edtValor.text); vDespesa.Status := cbDespesa.text; if (EstadoDoCadastro=ecInserir) then Result:=vDespesa.Inserir else if (EstadoDoCadastro=ecAlterar) then Result:=vDespesa.Atualizar; end; end.
// *************************************************************************** // // FMXComponents: Firemonkey Opensource Components Set // // TFMXToast is a toast component using pure fmx // // 该控件参考了Aone的文章 // http://www.cnblogs.com/onechen/p/7130227.html // // https://github.com/zhaoyipeng/FMXComponents // // *************************************************************************** // // 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. // // *************************************************************************** } // version history // 2017-09-27, v0.1.0.0 : // first release unit FMX.Toast; interface uses System.Classes, System.Types, System.UITypes, FMX.Types, FMX.Layouts, FMX.Objects, FMX.Graphics, FMX.Ani, FMX.ComponentsCommon; type [ComponentPlatformsAttribute(TFMXPlatforms)] TFMXToast = class(TComponent) private FToastContainer: TLayout; FToastText: TText; FToastRect: TRectangle; FToastAnimation: TFloatAnimation; FToastMessage: string; FFontColor: TAlphaColor; FBackColor: TAlphaColor; FFontSize: Single; FDelay: Single; FIsBlock: Boolean; FIsShowIng: Boolean; FAlign: TTextAlign; procedure SetToastMessage(const Value: string); procedure SetFontColor(const Value: TAlphaColor); procedure SetBackColor(const Value: TAlphaColor); procedure SetFontSize(const Value: Single); procedure CreateContainer; procedure OnAnimationFinish(Sender: TObject); procedure SetDelay(const Value: Single); procedure SetIsBlock(const Value: Boolean); procedure SetAlign(const Value: TTextAlign); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Show(AOwner: TFmxObject); procedure Close; property IsShowing: Boolean read FIsShowing; published property Align: TTextAlign read FAlign write SetAlign default TTextAlign.Trailing; property FontSize: Single read FFontSize write SetFontSize; property FontColor: TAlphaColor read FFontColor write SetFontColor default TAlphaColors.White; property BackColor: TAlphaColor read FBackColor write SetBackColor default TAlphaColors.Gray; property ToastMessage: string read FToastMessage write SetToastMessage; property Delay: Single read FDelay write SetDelay; property IsBlock: Boolean read FIsBlock write SetIsBlock default False; end; implementation { TFMXToast } procedure TFMXToast.Close; begin if FIsShowing then begin FToastAnimation.Stop; end; end; constructor TFMXToast.Create(AOwner: TComponent); begin inherited; FToastContainer := nil; FFontSize := 16; FFontColor := TAlphaColors.White; FBackColor := TAlphaColors.Gray; FDelay := 2.0; FToastMessage := 'Toast'; FIsBlock := False; FIsShowing := False; FAlign := TTextAlign.Trailing; end; destructor TFMXToast.Destroy; begin inherited; end; procedure TFMXToast.OnAnimationFinish(Sender: TObject); begin FToastContainer.DisposeOf; FIsShowing := False; end; procedure TFMXToast.SetAlign(const Value: TTextAlign); begin FAlign := Value; end; procedure TFMXToast.SetBackColor(const Value: TAlphaColor); begin FBackColor := Value; end; procedure TFMXToast.SetDelay(const Value: Single); begin FDelay := Value; end; procedure TFMXToast.SetFontColor(const Value: TAlphaColor); begin FFontColor := Value; end; procedure TFMXToast.SetFontSize(const Value: Single); begin FFontSize := Value; end; procedure TFMXToast.SetIsBlock(const Value: Boolean); begin FIsBlock := Value; end; procedure TFMXToast.SetToastMessage(const Value: string); begin FToastMessage := Value; end; procedure TFMXToast.Show(AOwner: TFmxObject); var R: TRectF; begin if FIsShowing then begin FToastContainer.DisposeOf; end; FIsShowing := True; CreateContainer; AOwner.AddObject(FToastContainer); R := RectF(0, 0, 10000, 10000); FToastText.Canvas.Font.Size := FFontSize; FToastText.Canvas.MeasureText(R, FToastMessage, False, [], TTextAlign.Leading, TTextAlign.Leading); FToastRect.Height := R.Height * 1.8; FToastRect.Width := R.Width + FToastContainer.Width - 48; case FAlign of TTextAlign.Leading: begin FToastRect.Align := TAlignLayout.Top; FToastRect.Margins.Top := 24; end; TTextAlign.Trailing: begin FToastRect.Align := TAlignLayout.Bottom; FToastRect.Margins.Bottom := 24; end; TTextAlign.Center: FToastRect.Align := TAlignLayout.VertCenter; end; FToastRect.Fill.Color := FBackColor; FToastRect.XRadius := FToastRect.Height * 0.15; FToastRect.YRadius := FToastRect.XRadius; FToastText.Color := FontColor; FToastText.Text := FToastMessage; FToastText.TextSettings.Font.Size := FontSize; FToastContainer.Opacity := 0; TAnimator.AnimateFloat(FToastContainer, 'Opacity', 1); FToastAnimation.Delay := FDelay; FToastAnimation.StartValue := 1; FToastAnimation.StopValue := 0; FToastAnimation.Start; end; procedure TFMXToast.CreateContainer; begin FToastContainer := TLayout.Create(nil); FToastContainer.Align := TAlignLayout.Contents; FToastContainer.HitTest := FIsBlock; FToastRect := TRectangle.Create(FToastContainer); FToastRect.Stroke.Kind := TBrushKind.None; FToastRect.Margins.Left := 24; FToastRect.Margins.Right := 24; FToastRect.Parent := FToastContainer; FToastRect.CornerType := TCornerType.Round; FToastRect.Fill.Color := BackColor; FToastRect.XRadius := 16; FToastRect.YRadius := FToastRect.XRadius; FToastText := TText.Create(FToastContainer); FToastText.HitTest := False; FToastText.Align := TAlignLayout.Client; FToastText.TextSettings.WordWrap := False; FToastText.Parent := FToastRect; FToastAnimation := TFloatAnimation.Create(FToastContainer); FToastAnimation.Parent := FToastContainer; FToastAnimation.Duration := 0.2; FToastAnimation.PropertyName := 'Opacity'; FToastAnimation.StartValue := 1.0; FToastAnimation.StopValue := 0.0; FToastAnimation.OnFinish := OnAnimationFinish; end; end.
unit vulkan.util; (* * Vulkan Samples * * Copyright (C) 2015-2016 Valve Corporation * Copyright (C) 2015-2016 LunarG, Inc. * Copyright (C) 2015-2016 Google, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *) interface //#################################################################### ■ uses vulkan_core, LUX.Code.C, LUX.D1, LUX.D2, LUX.D2x2, LUX.D3, LUX.D3x3, LUX.D4x4; type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% T_texture_object (* * structure to track all objects related to a texture. *) T_texture_object = record sampler :VkSampler; image :VkImage; imageLayout :VkImageLayout; needs_staging :T_bool; buffer :VkBuffer; buffer_size :VkDeviceSize; image_memory :VkDeviceMemory; buffer_memory :VkDeviceMemory; view :VkImageView; tex_width :T_int32_t; tex_height :T_int32_t; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% T_swap_chain_buffer (* * Keep each of our swap chain buffers' image, command buffer and view in one * spot *) T_swap_chain_buffer = record image :VkImage; view :VkImageView; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% T_layer_properties (* * A layer can expose extensions, keep track of those * extensions here. *) T_layer_properties = record properties :VkLayerProperties; instance_extensions :TArray<VkExtensionProperties>; device_extensions :TArray<VkExtensionProperties>; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% T_sample_info (* * Structure for tracking information used / created / modified * by utility functions. *) P_sample_info = ^T_sample_info; T_sample_info = record private const APP_NAME_STR_LEN = 80; public {$IFDEF MSWINDOWS } connection :T_HINSTANCE; // hInstance - Windows Instance name :array [ 0..APP_NAME_STR_LEN-1 ] of T_char; // Name to put on the window/icon window :T_HWND; // hWnd - window handle {$ELSEIF Defined( VK_USE_PLATFORM_METAL_EXT ) } caMetalLayer :P_void; {$ELSEIF Android } fpCreateAndroidSurfaceKHR :PFN_vkCreateAndroidSurfaceKHR; {$ELSEIF Defined( VK_USE_PLATFORM_WAYLAND_KHR ) } display :P_wl_display; registry :P_wl_registry ; compositor :P_wl_compositor; window :P_wl_surface; shell :P_wl_shell; shell_surface :P_wl_shell_surface; {$ELSE} connection :P_xcb_connection_t; screen :P_xcb_screen_t; window :T_xcb_window_t; atom_wm_delete_window :P_xcb_intern_atom_reply_t; {$ENDIF} // MSWINDOWS surface :VkSurfaceKHR; prepared :T_bool; use_staging_buffer :T_bool; save_images :T_bool; instance_layer_names :TArray<P_char>; instance_extension_names :TArray<P_char>; instance_layer_properties :TArray<T_layer_properties>; instance_extension_properties :TArray<VkExtensionProperties> ; inst :VkInstance; device_extension_names :TArray<P_char>; device_extension_properties :TArray<VkExtensionProperties>; gpus :TArray<VkPhysicalDevice>; device :VkDevice; graphics_queue :VkQueue; present_queue :VkQueue; graphics_queue_family_index :T_uint32_t; present_queue_family_index :T_uint32_t; gpu_props :VkPhysicalDeviceProperties; queue_props :TArray<VkQueueFamilyProperties>; memory_properties :VkPhysicalDeviceMemoryProperties; framebuffers :TArray<VkFramebuffer>; width :T_int; height :T_int; format :VkFormat; swapchainImageCount :T_uint32_t; swap_chain :VkSwapchainKHR; buffers :TArray<T_swap_chain_buffer>; imageAcquiredSemaphore :VkSemaphore; cmd_pool :VkCommandPool; depth :record format :VkFormat; image :VkImage; mem :VkDeviceMemory; view :VkImageView; end; textures :TArray<T_texture_object>; uniform_data :record buf :VkBuffer; mem :VkDeviceMemory; buffer_info :VkDescriptorBufferInfo; end; texture_data :record image_info :VkDescriptorImageInfo; end; vertex_buffer :record buf :VkBuffer; mem :VkDeviceMemory; buffer_info :VkDescriptorBufferInfo; end; vi_binding :VkVertexInputBindingDescription; vi_attribs :array [ 0..2-1 ] of VkVertexInputAttributeDescription; Projection :TSingleM4; View :TSingleM4; Model :TSingleM4; Clip :TSingleM4; MVP :TSingleM4; cmd :VkCommandBuffer; // Buffer for initialization commands pipeline_layout :VkPipelineLayout; desc_layout :TArray<VkDescriptorSetLayout>; pipelineCache :VkPipelineCache; render_pass :VkRenderPass; pipeline :VkPipeline; shaderStages : array [ 0..2-1 ] of VkPipelineShaderStageCreateInfo; desc_pool :VkDescriptorPool; desc_set :TArray<VkDescriptorSet>; dbgCreateDebugReportCallback :PFN_vkCreateDebugReportCallbackEXT; dbgDestroyDebugReportCallback :PFN_vkDestroyDebugReportCallbackEXT; dbgBreakCallback :PFN_vkDebugReportMessageEXT; debug_report_callbacks :TArray<VkDebugReportCallbackEXT>; current_buffer :T_uint32_t; queue_family_count :T_uint32_t; viewport :VkViewport; scissor :VkRect2D; end; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】 (* Number of samples needs to be the same at image creation, *) (* renderpass creation and pipeline creation. *) NUM_SAMPLES = VK_SAMPLE_COUNT_1_BIT; (* Number of descriptor sets needs to be the same at alloc, *) (* pipeline layout creation, and descriptor set layout creation *) NUM_DESCRIPTOR_SETS = 1; (* Amount of time, in nanoseconds, to wait for a command buffer to complete *) FENCE_TIMEOUT = 100000000; (* Number of viewports and number of scissors have to be the same *) (* at pipeline creation and in any call to set them dynamically *) (* They also have to be the same as each other *) NUM_VIEWPORTS = 1; NUM_SCISSORS = NUM_VIEWPORTS; //var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 function memory_type_from_properties( var info:T_sample_info; typeBits:T_uint32_t; requirements_mask:VkFlags; var typeIndex:T_uint32_t ) :T_bool; //////////////////////////////////////////////////////////////////////////////// 15-draw_cube function optionMatch( const option_:String; optionLine_:String ) :T_bool; procedure process_command_line_args( var info_:T_sample_info ); procedure wait_seconds( seconds_:T_int ); procedure set_image_layout( var info_:T_sample_info; image_:VkImage; aspectMask_:VkImageAspectFlags; old_image_layout_:VkImageLayout; new_image_layout_:VkImageLayout; src_stages_:VkPipelineStageFlags; dest_stages_:VkPipelineStageFlags ); procedure write_ppm( var info_:T_sample_info; const basename_:String ); //////////////////////////////////////////////////////////////////////////////// draw_textured_cube function read_ppm( const filename_:String; var width_:T_int; var height_:T_int; rowPitch_:T_uint64_t; dataPtr_:P_unsigned_char ) :T_bool; implementation //############################################################### ■ uses System.SysUtils, System.Classes, FMX.Types; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 function memory_type_from_properties( var info:T_sample_info; typeBits:T_uint32_t; requirements_mask:VkFlags; var typeIndex:T_uint32_t ) :T_bool; var i :T_uint32_t; begin // Search memtypes to find first index with those properties for i := 0 to info.memory_properties.memoryTypeCount-1 do begin if ( typeBits and 1 ) = 1 then begin // Type is available, does it match user properties? if info.memory_properties.memoryTypes[i].propertyFlags and requirements_mask = requirements_mask then begin typeIndex := i; Exit( True ); end; end; typeBits := typeBits shr 1; end; // No memory types matched, return failure Result := False; end; //////////////////////////////////////////////////////////////////////////////// 15-draw_cube function optionMatch( const option_:String; optionLine_:String ) :T_bool; begin if option_ = optionLine_ then Result := True else Result := False; end; procedure process_command_line_args( var info_:T_sample_info ); var i :T_int; begin for i := 1 to ParamCount-1 do begin if optionMatch( '--save-images', ParamStr( i ) ) then info_.save_images := true else if optionMatch( '--help', ParamStr( i ) ) or optionMatch( '-h', ParamStr( i ) ) then begin Log.d( #10'Other options:' ); Log.d( #9'--save-images'#10 + #9#9'Save tests images as ppm files in current working ' + 'directory.' ); Exit; end else begin Log.d( #10'Unrecognized option: ' + ParamStr( i ) ); Log.d( #10'Use --help or -h for option list.' ); Exit; end; end; end; procedure wait_seconds( seconds_:T_int ); begin Sleep( seconds_ * 1000 ); end; procedure set_image_layout( var info_:T_sample_info; image_:VkImage; aspectMask_:VkImageAspectFlags; old_image_layout_:VkImageLayout; new_image_layout_:VkImageLayout; src_stages_:VkPipelineStageFlags; dest_stages_:VkPipelineStageFlags ); var image_memory_barrier :VkImageMemoryBarrier; begin (* DEPENDS on info.cmd and info.queue initialized *) Assert( NativeInt( info_.cmd ) <> VK_NULL_HANDLE ); Assert( NativeInt( info_.graphics_queue ) <> VK_NULL_HANDLE ); image_memory_barrier.sType := VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; image_memory_barrier.pNext := nil; image_memory_barrier.srcAccessMask := 0; image_memory_barrier.dstAccessMask := 0; image_memory_barrier.oldLayout := old_image_layout_; image_memory_barrier.newLayout := new_image_layout_; image_memory_barrier.srcQueueFamilyIndex := VK_QUEUE_FAMILY_IGNORED; image_memory_barrier.dstQueueFamilyIndex := VK_QUEUE_FAMILY_IGNORED; image_memory_barrier.image := image_; image_memory_barrier.subresourceRange.aspectMask := aspectMask_; image_memory_barrier.subresourceRange.baseMipLevel := 0; image_memory_barrier.subresourceRange.levelCount := 1; image_memory_barrier.subresourceRange.baseArrayLayer := 0; image_memory_barrier.subresourceRange.layerCount := 1; case old_image_layout_ of VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL: image_memory_barrier.srcAccessMask := Ord( VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT ); VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL: image_memory_barrier.srcAccessMask := Ord( VK_ACCESS_TRANSFER_WRITE_BIT ); VK_IMAGE_LAYOUT_PREINITIALIZED: image_memory_barrier.srcAccessMask := Ord( VK_ACCESS_HOST_WRITE_BIT ); end; case new_image_layout_ of VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL: image_memory_barrier.dstAccessMask := Ord( VK_ACCESS_TRANSFER_WRITE_BIT ); VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL: image_memory_barrier.dstAccessMask := Ord( VK_ACCESS_TRANSFER_READ_BIT ); VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL: image_memory_barrier.dstAccessMask := Ord( VK_ACCESS_SHADER_READ_BIT ); VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL: image_memory_barrier.dstAccessMask := Ord( VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT ); VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL: image_memory_barrier.dstAccessMask := Ord( VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT ); end; vkCmdPipelineBarrier( info_.cmd, src_stages_, dest_stages_, 0, 0, nil, 0, nil, 1, @image_memory_barrier ); end; procedure write_ppm( var info_:T_sample_info; const basename_:String ); var filename :String; x, y :T_int; res :VkResult; image_create_info :VkImageCreateInfo; mem_alloc :VkMemoryAllocateInfo; mappableImage :VkImage; mappableMemory :VkDeviceMemory; mem_reqs :VkMemoryRequirements; pass :T_bool; cmd_buf_info :VkCommandBufferBeginInfo; copy_region :VkImageCopy; cmd_bufs :array [ 0..1-1 ] of VkCommandBuffer; fenceInfo :VkFenceCreateInfo; cmdFence :VkFence; submit_info :array [ 0..1-1 ] of VkSubmitInfo; subres :VkImageSubresource; sr_layout :VkSubresourceLayout; ptr :P_char; F :TFileStream; S :String; row :P_uint32_t; swapped :T_uint32_t; begin image_create_info.sType := VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; image_create_info.pNext := nil; image_create_info.imageType := VK_IMAGE_TYPE_2D; image_create_info.format := info_.format; image_create_info.extent.width := info_.width; image_create_info.extent.height := info_.height; image_create_info.extent.depth := 1; image_create_info.mipLevels := 1; image_create_info.arrayLayers := 1; image_create_info.samples := VK_SAMPLE_COUNT_1_BIT; image_create_info.tiling := VK_IMAGE_TILING_LINEAR; image_create_info.initialLayout := VK_IMAGE_LAYOUT_UNDEFINED; image_create_info.usage := Ord( VK_IMAGE_USAGE_TRANSFER_DST_BIT ); image_create_info.queueFamilyIndexCount := 0; image_create_info.pQueueFamilyIndices := nil; image_create_info.sharingMode := VK_SHARING_MODE_EXCLUSIVE; image_create_info.flags := 0; mem_alloc.sType := VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; mem_alloc.pNext := nil; mem_alloc.allocationSize := 0; mem_alloc.memoryTypeIndex := 0; (* Create a mappable image *) res := vkCreateImage( info_.device, @image_create_info, nil, @mappableImage ); Assert( res = VK_SUCCESS ); vkGetImageMemoryRequirements( info_.device, mappableImage, @mem_reqs ); mem_alloc.allocationSize := mem_reqs.size; (* Find the memory type that is host mappable *) pass := memory_type_from_properties( info_, mem_reqs.memoryTypeBits, Ord( VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT ) or Ord( VK_MEMORY_PROPERTY_HOST_COHERENT_BIT ), mem_alloc.memoryTypeIndex ); Assert( pass, 'No mappable, coherent memory' ); (* allocate memory *) res := vkAllocateMemory( info_.device, @mem_alloc, nil, @mappableMemory ); Assert( res = VK_SUCCESS ); (* bind memory *) res := vkBindImageMemory( info_.device, mappableImage, mappableMemory, 0 ); Assert( res = VK_SUCCESS ); cmd_buf_info.sType := VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; cmd_buf_info.pNext := nil; cmd_buf_info.flags := 0; cmd_buf_info.pInheritanceInfo := nil; res := vkBeginCommandBuffer( info_.cmd, @cmd_buf_info ); Assert( res = VK_SUCCESS ); set_image_layout( info_, mappableImage, Ord( VK_IMAGE_ASPECT_COLOR_BIT ), VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, Ord( VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT ), Ord( VK_PIPELINE_STAGE_TRANSFER_BIT ) ); set_image_layout( info_, info_.buffers[info_.current_buffer].image, Ord( VK_IMAGE_ASPECT_COLOR_BIT ), VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, Ord( VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT ), Ord( VK_PIPELINE_STAGE_TRANSFER_BIT ) ); copy_region.srcSubresource.aspectMask := Ord( VK_IMAGE_ASPECT_COLOR_BIT ); copy_region.srcSubresource.mipLevel := 0; copy_region.srcSubresource.baseArrayLayer := 0; copy_region.srcSubresource.layerCount := 1; copy_region.srcOffset.x := 0; copy_region.srcOffset.y := 0; copy_region.srcOffset.z := 0; copy_region.dstSubresource.aspectMask := Ord( VK_IMAGE_ASPECT_COLOR_BIT ); copy_region.dstSubresource.mipLevel := 0; copy_region.dstSubresource.baseArrayLayer := 0; copy_region.dstSubresource.layerCount := 1; copy_region.dstOffset.x := 0; copy_region.dstOffset.y := 0; copy_region.dstOffset.z := 0; copy_region.extent.width := info_.width; copy_region.extent.height := info_.height; copy_region.extent.depth := 1; (* Put the copy command into the command buffer *) vkCmdCopyImage( info_.cmd, info_.buffers[info_.current_buffer].image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, mappableImage, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, @copy_region); set_image_layout( info_, mappableImage, Ord( VK_IMAGE_ASPECT_COLOR_BIT ), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_GENERAL, Ord( VK_PIPELINE_STAGE_TRANSFER_BIT ), Ord( VK_PIPELINE_STAGE_HOST_BIT ) ); res := vkEndCommandBuffer( info_.cmd ); Assert( res = VK_SUCCESS ); cmd_bufs[0] := info_.cmd; fenceInfo.sType := VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fenceInfo.pNext := nil; fenceInfo.flags := 0; vkCreateFence( info_.device, @fenceInfo, nil, @cmdFence ); submit_info[0].pNext := nil; submit_info[0].sType := VK_STRUCTURE_TYPE_SUBMIT_INFO; submit_info[0].waitSemaphoreCount := 0; submit_info[0].pWaitSemaphores := nil; submit_info[0].pWaitDstStageMask := nil; submit_info[0].commandBufferCount := 1; submit_info[0].pCommandBuffers := @cmd_bufs[0]; submit_info[0].signalSemaphoreCount := 0; submit_info[0].pSignalSemaphores := nil; (* Queue the command buffer for execution *) res := vkQueueSubmit( info_.graphics_queue, 1, @submit_info[0], cmdFence ); Assert( res = VK_SUCCESS ); (* Make sure command buffer is finished before mapping *) repeat res := vkWaitForFences( info_.device, 1, @cmdFence, VK_TRUE, FENCE_TIMEOUT ); until res <> VK_TIMEOUT; Assert( res = VK_SUCCESS ); vkDestroyFence( info_.device, cmdFence, nil ); filename := basename_ + '.ppm'; subres.aspectMask := Ord( VK_IMAGE_ASPECT_COLOR_BIT ); subres.mipLevel := 0; subres.arrayLayer := 0; vkGetImageSubresourceLayout( info_.device, mappableImage, @subres, @sr_layout ); res := vkMapMemory( info_.device, mappableMemory, 0, mem_reqs.size, 0, @ptr ); Assert( res = VK_SUCCESS ); Inc( ptr, sr_layout.offset ); F := TFileStream.Create( filename, fmCreate ); S := 'P6' + #13#10; F.Write( BytesOf( S ), Length( S ) ); S := info_.width.ToString + ' ' + info_.height.ToString + #13#10; F.Write( BytesOf( S ), Length( S ) ); S := '255' + #13#10; F.Write( BytesOf( S ), Length( S ) ); for y := 0 to info_.height-1 do begin row := P_uint32_t( ptr ); if ( info_.format = VK_FORMAT_B8G8R8A8_UNORM ) or ( info_.format = VK_FORMAT_B8G8R8A8_SRGB ) then begin for x := 0 to info_.width-1 do begin swapped := ( row^ and $ff00ff00 ) or ( row^ and $000000ff ) shl 16 or ( row^ and $00ff0000 ) shr 16; F.Write( swapped, 3 ); Inc( row ); end; end else if info_.format = VK_FORMAT_R8G8B8A8_UNORM then begin for x := 0 to info_.width-1 do begin F.Write( row^, 3 ); Inc( row ); end; end else begin Log.d( 'Unrecognized image format - will not write image files' ); Break; end; Inc( ptr, sr_layout.rowPitch ); end; F.Free; vkUnmapMemory( info_.device, mappableMemory ); vkDestroyImage( info_.device, mappableImage, nil ); vkFreeMemory( info_.device, mappableMemory, nil ); end; //////////////////////////////////////////////////////////////////////////////// draw_textured_cube function read_ppm( const filename_:String; var width_:T_int; var height_:T_int; rowPitch_:T_uint64_t; dataPtr_:P_unsigned_char ) :T_bool; type T_ReadHeader = reference to function( var S:String ) :Boolean; const saneDimension :T_int = 32768; //?? var magicStr :String; heightStr :String; widthStr :String; formatStr :String; fPtr :TFileStream; ReadHeader :T_ReadHeader; count :T_int; x, y :T_int; rowPtr :P_unsigned_char; begin // PPM format expected from http://netpbm.sourceforge.net/doc/ppm.html // 1. magic number // 2. whitespace // 3. width // 4. whitespace // 5. height // 6. whitespace // 7. max color value // 8. whitespace // 7. data // Comments are not supported, but are detected and we kick out // Only 8 bits per channel is supported // If dataPtr is nullptr, only width and height are returned // Read in values from the PPM file as characters to check for comments magicStr := ''; widthStr := ''; heightStr := ''; formatStr := ''; try fPtr := TFileStream.Create( filename_, fmOpenRead or fmShareDenyWrite ); try // Read the four values from file, accounting with any and all whitepace ReadHeader := function( var S:String ) :Boolean var C :T_char; begin while fPtr.Read( C, 1 ) = 1 do begin if C in [ #09, #10, #13, #32 ] then Exit( True ); S := S + Char( C ); end; Result := False; end; Assert( ReadHeader( magicStr ) ); Assert( ReadHeader( widthStr ) ); Assert( ReadHeader( heightStr ) ); Assert( ReadHeader( formatStr ) ); // Kick out if comments present if ( magicStr.Chars[0] = '#' ) or ( widthStr.Chars[0] = '#' ) or ( heightStr.Chars[0] = '#' ) or ( formatStr.Chars[0] = '#' ) then begin Log.d( 'Unhandled comment in PPM file' ); Exit( False ); end; // Only one magic value is valid if magicStr <> 'P6' then begin Log.d( 'Unhandled PPM magic number: ' + magicStr ); Exit( False ); end; width_ := StrToInt( widthStr ); height_ := StrToInt( heightStr ); // Ensure we got something sane for width/height if ( width_ <= 0 ) or ( width_ > saneDimension ) then begin Log.d( 'Width seems wrong. Update read_ppm if not: ' + width_.ToString ); Exit( False ); end; if ( height_ <= 0 ) or ( height_ > saneDimension ) then begin Log.d( 'Height seems wrong. Update read_ppm if not: ' + height_.ToString ); Exit( False ); end; if dataPtr_ = nil then begin // If no destination pointer, caller only wanted dimensions Exit( True ); end; // Now read the data for y := 0 to height_-1 do begin rowPtr := dataPtr_; for x := 0 to width_-1 do begin count := fPtr.Read( rowPtr^, 3 ); Assert( count = 3 ); Inc( rowPtr, 3 ); rowPtr^ := 255; (* Alpha of 1 *) Inc( rowPtr ); end; Inc( dataPtr_, rowPitch_ ); end; Result := True; finally fPtr.Free; end; except Log.d( 'Bad filename in read_ppm: ' + filename_ ); Result := False; end; end; end. //######################################################################### ■
unit tcItemList; interface uses l3Interfaces, l3CacheableBase, tcInterfaces ; type TtcItemList = class(Tl3CacheableBase, ItcItemList) private f_List: Il3StringsEx; protected // ItcItemList function pm_GetCount: Integer; function pm_GetItem(Index: Integer): ItcItem; function Add(const anID: Il3CString): ItcItem; procedure AddExisting(const anItem: ItcItem); virtual; protected procedure Cleanup; override; function MakeItem(const anID: Il3CString): ItcItem; virtual; abstract; procedure AssignToItem(const aSource, aTarget: ItcItem); virtual; public constructor Create; reintroduce; end; implementation uses SysUtils, l3VCLStrings, l3StringListPrim; { TtcItemList } function TtcItemList.Add(const anID: Il3CString): ItcItem; var l_Index: Integer; begin l_Index := f_List.IndexOf(anID); if l_Index = -1 then begin Result := MakeItem(anID); Result._AddRef; f_List.AddObject(anID, TObject(Pointer(Result))); end else Result := pm_GetItem(l_Index); end; procedure TtcItemList.AddExisting(const anItem: ItcItem); var l_Index: Integer; begin l_Index := f_List.IndexOf(anItem.ID); if l_Index = -1 then begin anItem._AddRef; f_List.AddObject(anItem.ID, TObject(Pointer(anItem))); end else AssignToItem(anItem, pm_GetItem(l_Index)); end; procedure TtcItemList.AssignToItem(const aSource, aTarget: ItcItem); begin aTarget.Caption := aSource.Caption; end; procedure TtcItemList.Cleanup; var l_IDX: Integer; begin if Assigned(f_List) then begin for l_IDX := 0 to f_List.Count - 1 do begin pm_GetItem(l_IDX)._Release; f_List.Objects[l_IDX] := nil; end; end; f_List := nil; inherited Cleanup; end; constructor TtcItemList.Create; var l_Strings: Tl3Strings; begin inherited Create; l_Strings := Tl3Strings.MakeSorted; try f_List := l_Strings; finally FreeAndNil(l_Strings); end; end; function TtcItemList.pm_GetCount: Integer; begin Result := f_List.Count; end; function TtcItemList.pm_GetItem(Index: Integer): ItcItem; begin Result := ItcItem(Integer(f_List.Objects[Index])); end; end.
unit SenhaUser; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TForm3 = class(TForm) BtnSave: TButton; BtnCancel: TButton; EdtSenha: TEdit; EdtConfirm: TEdit; Senha: TLabel; Label1: TLabel; Label2: TLabel; EdtLogin: TEdit; procedure BtnSaveClick(Sender: TObject); procedure BtnCancelClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form3: TForm3; implementation {$R *.dfm} { TForm3 } procedure TForm3.BtnSaveClick(Sender: TObject); var _salvar : integer; begin if Trim(EdtLogin.text) = EmptyStr then begin MessageDlg('Não é possível salvar o registro. Dados em branco', mtError,[mbOK], 0); Exit; end; if EdtSenha.Text <> EdtConfirm.Text then MessageDlg('Senhas estão diferentes', mtWarning, [mbOk], 0); Exit; begin _salvar := MessageDlg('Deseja salvar registro? ', mtConfirmation,[mbYes, mbNo], 0); if _salvar = 7 then Exit; EdtLogin.text := ''; EdtSenha.Text := ''; EdtConfirm.Text := ''; ShowMessage('Registro salvo com sucesso!'); end; end; procedure TForm3.BtnCancelClick(Sender: TObject); var _cancelar: integer; begin _cancelar := MessageDlg('Deseja cancelar operação', mtConfirmation,[mbYes, mbNo], 0); if _cancelar = 6 then Close; end; end.
{ Routines for handling errors in parsing code. } module sst_r_syn_err; define sst_r_syn_err_check; %include 'sst_r_syn.ins.pas'; { ******************************************************************************** * * Subroutine SST_R_SYN_ERR_CHECK * * Check for end of error re-parse has been encountered. If so, then a jump * will be taken to the error label, pointed to by LABEL_ERR_P. This label is * created here the first time an error check is performed. The error exit * code at the label is not written later if the label was not created. * * If end of error re-parse is detected, then the syntax parsing function will * be aborted and will return FALSE. } procedure sst_r_syn_err_check; {check for err reparse end in syntax checking code} val_param; const max_msg_parms = 1; {max parameters we can pass to a message} var name: string_var32_t; {label name} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; stat: sys_err_t; {completion status} begin name.max := size_char(name.str); {init local var string} { * Make sure the label for the error exit code exists. It is created here if * not. } if label_err_p = nil then begin {label to jump to doesn't exist yet ?} string_vstring (name, 'err'(0), -1); {set the label name} sst_symbol_new_name ( {create the label symbol} name, {label name} label_err_p, {returned pointer to the new symbol} stat); sys_msg_parm_vstr (msg_parm[1], name); sys_error_abort (stat, 'sst_syn_read', 'symbol_label_create', msg_parm, 1); label_err_p^.symtype := sst_symtype_label_k; {this symbol is a label} label_err_p^.label_opc_p := nil; {opcode for this label not written yet} end; { * Write the conditional goto to the error label. } sst_opcode_new; {create opcode for the conditional} sst_opc_p^.opcode := sst_opc_if_k; {opcode type} sst_opc_p^.str_h.first_char.crange_p := nil; sst_opc_p^.str_h.first_char.ofs := 0; sst_opc_p^.str_h.last_char := sst_opc_p^.str_h.first_char; sst_opc_p^.if_exp_p := sym_error_p; {expression to evaluate} sst_opc_p^.if_false_p := nil; {no FALSE case code} sst_opcode_pos_push (sst_opc_p^.if_true_p); {set up for writing TRUE case code} sst_opcode_new; {create GOTO opcode} sst_opc_p^.opcode := sst_opc_goto_k; sst_opc_p^.str_h.first_char.crange_p := nil; sst_opc_p^.str_h.first_char.ofs := 0; sst_opc_p^.str_h.last_char := sst_opc_p^.str_h.first_char; sst_opc_p^.goto_sym_p := label_err_p; {label to jump to} sst_opcode_pos_pop; {done writing TRUE case opcodes} end;
var HSVUpdate, RGBUpdate : Boolean; procedure TxMainForm.xClearButtonClick(Sender: TObject); begin RED_O.Value := 0; GREEN_O.Value := 0; BLUE_O.Value := 0; end; function Module (X, Y, Z : Real) : Real; begin Result := Sqrt(x * x + y * y + z * z); end; function Arg(xa, ya : Real) : Real; begin Result := 0; if (xa = 0) and (ya = 0) then begin Result := 0; Exit; end; if (xa = 0) and (ya >= 0) then begin Result := Pi / 2; Exit; end; if (ya = 0) and (xa < 0) then begin Result := Pi; Exit; end; if (xa = 0) and (ya < 0) then begin Result := -Pi / 2; Exit; end; if (xa > 0) then begin Result := ArcTan(ya / xa); Exit; end; if (xa < 0) and (ya >= 0) then Result := Pi - ArcTan(-ya / xa); if (xa < 0) and (ya < 0) then Result := -Pi + ArcTan(-ya / -xa); end; procedure RGBtoHSV(); var Temp, xa, ya, Hue, Saturation, Value : Real; begin Temp := (xRedSlider.Value + xGreenSlider.Value + xBlueSlider.Value) / 3; xa := (xGreenSlider.Value - xRedSlider.Value) / sqrt(2); ya := (2 * xBlueSlider.Value - xRedSlider.Value - xGreenSlider.Value) / sqrt(6); Hue := Arg(xa, ya) * 180 / Pi + 150; Saturation := Arg(Temp, Module(xRedSlider.Value - Temp, xGreenSlider.Value - Temp, xBlueSlider.Value - Temp)) * 100 / ArcTan(Sqrt(6)); Value := Temp / 2.55; if (Saturation = 0) or (Value = 0) then Hue := 0; if (Hue < 0) then Hue := Hue + 360; if (Hue >= 360) then Hue := Hue - 360; xHueSlider.Value := Hue; xSaturationSlider.Value := Saturation; xValueSlider.Value := Value; end; procedure HSVtoRGB(); var Angle, Ur, Radius, Vr, Wr : Real; Red, Green Blue : Real; Rdim : Real; begin Angle := (xHueSlider.Value - 150) * Pi / 180; Ur := xValueSlider.Value * 2.55; Radius := Ur * Tan(xSaturationSlider.Value * ArcTan(Sqrt(6)/100)); Vr := Radius * Cos(Angle) / Sqrt(2); Wr := Radius * Sin(Angle) / Sqrt(6); Red := Ur - Vr - Wr; Green := Ur + Vr - Wr; Blue := Ur + Wr + Wr; if Red < 0 then begin Rdim := Ur / (Vr + Wr); Red := 0; Green := Ur + (Vr - Wr) * Rdim; Blue := Ur + 2 * Wr * Rdim; end; if Green < 0 then begin Rdim := -Ur / (Vr - Wr); Red := Ur - (Vr + Wr) * Rdim; Green := 0; Blue := Ur + 2 * Wr * Rdim; end; if Blue < 0 then begin Rdim := -Ur / (Wr + Wr); Red := Ur - (Vr + Wr) * Rdim; Green := Ur + (Vr - Wr) * Rdim; Blue := 0; end; if Red > 255 then begin Rdim := (Ur - 255) / (Vr + Wr); Red := 255; Green := Ur + (Vr - Wr) * Rdim; Blue := Ur + 2 * Wr * Rdim; end; if Green > 255 then begin Rdim := (255 - Ur) / (Vr - Wr); Red := Ur - (Vr + Wr) * Rdim; Green := 255; Blue := Ur + 2 * Wr * Rdim; end; if Blue > 255 then begin Rdim := (255 - Ur) / (Wr + Wr); Red := Ur - (Vr + Wr) * Rdim; Green := Ur + (Vr - Wr) * Rdim; Blue := 255; end; xRedSlider.Value := Red; xGreenSlider.Value := Green; xBlueSlider.Value := Blue; end; procedure TxMainForm.RGBChange(Sender: TObject); begin //Don't do anything if in the middle of an HSV change if HSVUpdate = True then Exit; RGBUpdate := True; RGBtoHSV(); RGBUpdate := False; end; procedure TxMainForm.HSVChange(Sender: TObject); begin //Don't do anything if in the middle of an RGB change if RGBUpdate = True then Exit; HSVUpdate := True; HSVtoRGB(); HSVUpdate := False; end; procedure TxMainForm.FormEnter(Sender: TObject); begin HSVUpdate := False; RGBUpdate := False; end;
unit K466751465; {* [Requestlink:466751465] } // Модуль: "w:\common\components\rtl\Garant\Daily\K466751465.pas" // Стереотип: "TestCase" // Элемент модели: "K466751465" MUID: (51D2AB4E0353) // Имя типа: "TK466751465" {$Include w:\common\components\rtl\Garant\Daily\TestDefine.inc.pas} interface {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3IntfUses , RTFtoEVDWriterTest ; type TK466751465 = class(TRTFtoEVDWriterTest) {* [Requestlink:466751465] } protected function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TK466751465 {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3ImplUses , TestFrameWork //#UC START# *51D2AB4E0353impl_uses* //#UC END# *51D2AB4E0353impl_uses* ; function TK466751465.GetFolder: AnsiString; {* Папка в которую входит тест } begin Result := '7.9'; end;//TK466751465.GetFolder function TK466751465.GetModelElementGUID: AnsiString; {* Идентификатор элемента модели, который описывает тест } begin Result := '51D2AB4E0353'; end;//TK466751465.GetModelElementGUID initialization TestFramework.RegisterTest(TK466751465.Suite); {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) end.
unit PrimToolbarMenu_Module; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "View" // Автор: Люлин А.В. // Модуль: "w:/common/components/gui/Garant/VCM/View/ToolbarMenu/PrimToolbarMenu_Module.pas" // Начат: 13.09.2010 18:24 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<VCMFormsPack::Class>> Shared Delphi Operations::VCMCustomization::View::ToolbarMenu::PrimToolbarMenu // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! interface uses Classes {$If not defined(NoVCM)} , vcmToolbarsInterfaces {$IfEnd} //not NoVCM {$If not defined(NoVCM)} , vcmUserControls {$IfEnd} //not NoVCM , l3ProtoDataContainer {$If not defined(NoVCM)} , vcmBaseMenuManager {$IfEnd} //not NoVCM , l3StringIDEx, PrimCustomizeTools_Form {$If not defined(NoScripts)} , tfwInteger {$IfEnd} //not NoScripts {$If not defined(NoScripts)} , tfwControlString {$IfEnd} //not NoScripts , CustomizeTools_Form, l3Types, l3Memory, l3Interfaces, l3Core, l3Except, vcmExternalInterfaces {a}, vcmInterfaces {a}, vcmModule {a}, vcmBase {a} ; type _ItemType_ = IvcmToolbarsCustomizeListener; _l3InterfacePtrList_Parent_ = Tl3ProtoDataContainer; {$Define l3Items_IsProto} {$Include w:\common\components\rtl\Garant\L3\l3InterfacePtrList.imp.pas} TIvcmToolbarsCustomizeListenerPtrList = class(_l3InterfacePtrList_) {* Список указателей на IvcmToolbarsCustomizeListener } end;//TIvcmToolbarsCustomizeListenerPtrList TPrimToolbarMenuModule = {abstract formspack} class(TvcmModule {$If not defined(NoVCM)}, IvcmToolbarsCustomizeNotify{$IfEnd} //not NoVCM {$If not defined(NoVCM)}, IvcmToolbarsCustomize{$IfEnd} //not NoVCM ) private // private fields f_MenuManager : TvcmBaseMenuManager; {* Поле для свойства MenuManager} protected procedure Loaded; override; class procedure GetEntityForms(aList : TvcmClassList); override; private // private methods procedure opCustomizeTest(const aParams: IvcmTestParamsPrim); {* Настройка... } procedure opCustomize(const aParams: IvcmExecuteParamsPrim); {* Настройка... } {$If not defined(Admin) AND not defined(Monitorings)} procedure opAvailableOperationsTest(const aParams: IvcmTestParamsPrim); {* Доступные операции... } {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} procedure opAvailableOperations(const aParams: IvcmExecuteParamsPrim); {* Доступные операции... } {$IfEnd} //not Admin AND not Monitorings procedure opIconsSizeTest(const aParams: IvcmTestParamsPrim); {* Размер кнопок } procedure opIconsSize(const aParams: IvcmExecuteParamsPrim); {* Размер кнопок } procedure opFastenTest(const aParams: IvcmTestParamsPrim); {* Закрепить панели инструментов } procedure opFasten(const aParams: IvcmExecuteParamsPrim); {* Закрепить панели инструментов } protected // realized methods {$If not defined(NoVCM)} procedure AddListener(const aListener: IvcmToolbarsCustomizeListener); {$IfEnd} //not NoVCM {$If not defined(NoVCM)} procedure RemoveListener(const aListener: IvcmToolbarsCustomizeListener); {$IfEnd} //not NoVCM {$If not defined(NoVCM)} function pm_GetNotify: IvcmToolbarsCustomizeNotify; {$IfEnd} //not NoVCM protected // overridden protected methods procedure Cleanup; override; {* Функция очистки полей объекта. } public // overridden public methods constructor Create(AOwner: TComponent); override; protected // protected fields f_CustomizeVisible : Boolean; f_LargeIconsVisible : Boolean; f_Listeners : TIvcmToolbarsCustomizeListenerPtrList; protected // protected methods procedure DoNotify; procedure PmToolbarPopup(Sender: TObject); public // public properties property MenuManager: TvcmBaseMenuManager read f_MenuManager write f_MenuManager; end;//TPrimToolbarMenuModule implementation uses l3MessageID, l3Base, l3MinMax, RTLConsts, SysUtils, afwFacade {$If not defined(NoVCM)} , vcmToolbarMenuRes {$IfEnd} //not NoVCM {$If not defined(NoVCM)} , vcmMenuManager {$IfEnd} //not NoVCM , Controls {$If not defined(NoVCM)} , vcmCustomizeAvailableToolbarOps {$IfEnd} //not NoVCM {$If not defined(NoVCM)} , vcmEntityForm {$IfEnd} //not NoVCM {$If not defined(NoVCM)} , vcmMenus {$IfEnd} //not NoVCM , kw_ToolbarMenu_Customize, kw_ToolbarMenu_AvailableOperations, kw_ToolbarMenu_IconsSize, kw_ToolbarMenu_Fasten, vcmFormSetFactory {a}, StdRes {a}, vcmModuleDef {a} ; type Tkw_Form_CustomizeTools = class(TtfwControlString) {* Слово словаря для идентификатора формы CustomizeTools ---- *Пример использования*: [code] 'aControl' форма::CustomizeTools TryFocus ASSERT [code] } protected // overridden protected methods {$If not defined(NoScripts)} function GetString: AnsiString; override; {$IfEnd} //not NoScripts end;//Tkw_Form_CustomizeTools // start class Tkw_Form_CustomizeTools {$If not defined(NoScripts)} function Tkw_Form_CustomizeTools.GetString: AnsiString; {-} begin Result := 'CustomizeToolsForm'; end;//Tkw_Form_CustomizeTools.GetString {$IfEnd} //not NoScripts procedure TPrimToolbarMenuModule.opCustomizeTest(const aParams: IvcmTestParamsPrim); //#UC START# *4C8E3A170399_4C8E340C0148test_var* //#UC END# *4C8E3A170399_4C8E340C0148test_var* begin //#UC START# *4C8E3A170399_4C8E340C0148test_impl* aParams.Op.Flag[vcm_ofVisible] := f_CustomizeVisible; //#UC END# *4C8E3A170399_4C8E340C0148test_impl* end;//TPrimToolbarMenuModule.opCustomizeTest procedure TPrimToolbarMenuModule.opCustomize(const aParams: IvcmExecuteParamsPrim); //#UC START# *4C8E3A170399_4C8E340C0148exec_var* //#UC END# *4C8E3A170399_4C8E340C0148exec_var* begin //#UC START# *4C8E3A170399_4C8E340C0148exec_impl* DoNotify; {$IfNDef DesignTimeLibrary} TvcmCustomizeToolsForm.Execute(MenuManager, MenuManager.ToolbarPopup.PopupComponent); {$EndIf DesignTimeLibrary} //#UC END# *4C8E3A170399_4C8E340C0148exec_impl* end;//TPrimToolbarMenuModule.opCustomize {$If not defined(Admin) AND not defined(Monitorings)} procedure TPrimToolbarMenuModule.opAvailableOperationsTest(const aParams: IvcmTestParamsPrim); //#UC START# *4C8E3A290341_4C8E340C0148test_var* //#UC END# *4C8E3A290341_4C8E340C0148test_var* begin //#UC START# *4C8E3A290341_4C8E340C0148test_impl* aParams.Op.Flag[vcm_ofVisible] := f_CustomizeVisible {$If not Defined(Nemesis) OR Defined(NewGen)} and afw.Application.IsInternal {$IfEnd} ; //#UC END# *4C8E3A290341_4C8E340C0148test_impl* end;//TPrimToolbarMenuModule.opAvailableOperationsTest {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} procedure TPrimToolbarMenuModule.opAvailableOperations(const aParams: IvcmExecuteParamsPrim); //#UC START# *4C8E3A290341_4C8E340C0148exec_var* {$IfNDef Admin} {$IfNDef Monitorings} var l_Toolbar : TComponent; l_Form : IvcmEntityForm; {$EndIf Monitorings} {$EndIf Admin} //#UC END# *4C8E3A290341_4C8E340C0148exec_var* begin //#UC START# *4C8E3A290341_4C8E340C0148exec_impl* {$IfNDef Admin} {$IfNDef Monitorings} l_Toolbar := MenuManager.ToolbarPopup.PopupComponent; while (l_Toolbar <> nil) and not (l_Toolbar is TvcmToolbarDef) do l_Toolbar := TControl(l_Toolbar).Parent; if (l_Toolbar <> nil) then begin Assert(l_Toolbar.Owner is TvcmEntityForm); if not Supports(l_Toolbar.Owner, IvcmEntityForm, l_Form) then Assert(False); TdmStdRes.CustomizePanel(TvcmCustAvailableToolbarOps.Make(l_Form)); end;//l_Toolbar <> nil {$EndIf Monitorings} {$EndIf Admin} //#UC END# *4C8E3A290341_4C8E340C0148exec_impl* end;//TPrimToolbarMenuModule.opAvailableOperations {$IfEnd} //not Admin AND not Monitorings procedure TPrimToolbarMenuModule.opIconsSizeTest(const aParams: IvcmTestParamsPrim); //#UC START# *4C8E3A3E011D_4C8E340C0148test_var* var l_Strings: IvcmItems; //#UC END# *4C8E3A3E011D_4C8E340C0148test_var* begin //#UC START# *4C8E3A3E011D_4C8E340C0148test_impl* with aParams do begin Op.Flag[vcm_ofEnabled] := true; Op.Flag[vcm_ofVisible] := f_LargeIconsVisible; l_Strings := Op.SubItems; if (l_Strings <> nil) and (l_Strings.Count = 0) then vcmIconSizeMapHelper.FillStrings(l_Strings); Op.SelectedString := vcmIconSizeMap[(g_MenuManager as TvcmCustomMenuManager).GlyphSize].AsCStr; end; //#UC END# *4C8E3A3E011D_4C8E340C0148test_impl* end;//TPrimToolbarMenuModule.opIconsSizeTest procedure TPrimToolbarMenuModule.opIconsSize(const aParams: IvcmExecuteParamsPrim); //#UC START# *4C8E3A3E011D_4C8E340C0148exec_var* //#UC END# *4C8E3A3E011D_4C8E340C0148exec_var* begin //#UC START# *4C8E3A3E011D_4C8E340C0148exec_impl* (g_MenuManager as TvcmCustomMenuManager).GlyphSize := vcmIconSizeMapHelper.DisplayNameToValue(aParams.SelectedString); (g_MenuManager as TvcmCustomMenuManager).StoreGlyphSize; //#UC END# *4C8E3A3E011D_4C8E340C0148exec_impl* end;//TPrimToolbarMenuModule.opIconsSize procedure TPrimToolbarMenuModule.opFastenTest(const aParams: IvcmTestParamsPrim); //#UC START# *4C8E3A5002FF_4C8E340C0148test_var* //#UC END# *4C8E3A5002FF_4C8E340C0148test_var* begin //#UC START# *4C8E3A5002FF_4C8E340C0148test_impl* aParams.Op.Flag[vcm_ofChecked] := (g_MenuManager as TvcmCustomMenuManager). GetFastenMode; //#UC END# *4C8E3A5002FF_4C8E340C0148test_impl* end;//TPrimToolbarMenuModule.opFastenTest procedure TPrimToolbarMenuModule.opFasten(const aParams: IvcmExecuteParamsPrim); //#UC START# *4C8E3A5002FF_4C8E340C0148exec_var* //#UC END# *4C8E3A5002FF_4C8E340C0148exec_var* begin //#UC START# *4C8E3A5002FF_4C8E340C0148exec_impl* g_MenuManager.FastenToolbars; //#UC END# *4C8E3A5002FF_4C8E340C0148exec_impl* end;//TPrimToolbarMenuModule.opFasten procedure TPrimToolbarMenuModule.DoNotify; //#UC START# *4C90B2F500F9_4C8E340C0148_var* var l_Index: Integer; //#UC END# *4C90B2F500F9_4C8E340C0148_var* begin //#UC START# *4C90B2F500F9_4C8E340C0148_impl* if f_Listeners <> nil then for l_Index := 0 to Pred(f_Listeners.Count) do f_Listeners.Items[l_Index].BeforeCustomize; //#UC END# *4C90B2F500F9_4C8E340C0148_impl* end;//TPrimToolbarMenuModule.DoNotify procedure TPrimToolbarMenuModule.PmToolbarPopup(Sender: TObject); //#UC START# *4C90C066016F_4C8E340C0148_var* Var l_Component : TComponent; l_Control : TControl; l_Form : TvcmEntityForm; l_DocDef : TvcmDockDef; l_Idx : Integer; function lp_GetForm(const aControl: TControl): TvcmEntityForm; var l_Control: TControl; begin l_Control := aControl; Result := nil; if not (l_Control is TvcmDockDef) then begin while (l_Control <> nil) and not (l_Control is TvcmToolbarDef) do l_Control := l_Control.Parent; if (l_Control <> nil) and ((l_Control as TvcmToolbarDef).Owner <> nil) and ((l_Control as TvcmToolbarDef).Owner is TvcmEntityForm) then Result := (l_Control as TvcmToolbarDef).Owner as TvcmEntityForm; end; end; function lp_CalcLargeIconsVisible(const aForm: TvcmEntityForm; const aControl: TControl): Boolean; begin Result := False; if aControl is TvcmToolbarDef then begin with aForm.Style.Toolbars do case TvcmToolbarDef(aControl).Pos of vcm_tbpTop: Result := Top.ImageSize = isNone; vcm_tbpBottom: Result := Bottom.ImageSize = isNone; vcm_tbpLeft: Result := Left.ImageSize = isNone; vcm_tbpRight: Result := Right.ImageSize = isNone; end;//case aToolbar.DockPos of end; end; var l_UserType: IvcmUserTypeDef; //#UC END# *4C90C066016F_4C8E340C0148_var* begin //#UC START# *4C90C066016F_4C8E340C0148_impl* l_Component := MenuManager.ToolbarPopup.PopupComponent; f_CustomizeVisible := False; f_LargeIconsVisible := False; l_Form := nil; if (l_Component <> nil) and (l_Component is TControl) then begin l_Control := l_Component as TControl; if not (l_Control is TvcmDockDef) then begin l_Form := lp_GetForm(l_Control); if Assigned(l_Form) then begin l_UserType := l_Form.CurUseToolbarOfUserType; if (l_UserType = nil) then {$If not Defined(Nemesis) OR Defined(NewGen)} f_CustomizeVisible := true {$Else} f_CustomizeVisible := false {$IfEnd} else f_CustomizeVisible := TvcmUserTypeInfo.AllowCustomizeToolbars(l_UserType); f_LargeIconsVisible := lp_CalcLargeIconsVisible(l_Form, l_COntrol); end;//Assigned(l_Form) end//not (l_Control is TvcmDockDef) else begin l_DocDef := l_Control as TvcmDockDef; for l_Idx := 0 to l_DocDef.ControlCount - 1 do begin l_Form := lp_GetForm(l_DocDef.Controls[l_Idx]); if Assigned(l_Form) then f_LargeIconsVisible := f_LargeIconsVisible or lp_CalcLargeIconsVisible(l_Form, l_DocDef.Controls[l_Idx]); end;//for l_Idx end;//not (l_Control is TvcmDockDef) end;//(l_Component <> nil) and (l_Component is TControl) //#UC END# *4C90C066016F_4C8E340C0148_impl* end;//TPrimToolbarMenuModule.PmToolbarPopup type _Instance_R_ = TIvcmToolbarsCustomizeListenerPtrList; {$Include w:\common\components\rtl\Garant\L3\l3InterfacePtrList.imp.pas} // start class TPrimToolbarMenuModule {$If not defined(NoVCM)} procedure TPrimToolbarMenuModule.AddListener(const aListener: IvcmToolbarsCustomizeListener); //#UC START# *4992FC7A0212_4C8E340C0148_var* //#UC END# *4992FC7A0212_4C8E340C0148_var* begin //#UC START# *4992FC7A0212_4C8E340C0148_impl* if f_Listeners = nil then f_Listeners := TIvcmToolbarsCustomizeListenerPtrList.Make; if f_Listeners.IndexOf(aListener) = -1 then f_Listeners.Add(aListener); //#UC END# *4992FC7A0212_4C8E340C0148_impl* end;//TPrimToolbarMenuModule.AddListener {$IfEnd} //not NoVCM {$If not defined(NoVCM)} procedure TPrimToolbarMenuModule.RemoveListener(const aListener: IvcmToolbarsCustomizeListener); //#UC START# *4992FC8900E1_4C8E340C0148_var* //#UC END# *4992FC8900E1_4C8E340C0148_var* begin //#UC START# *4992FC8900E1_4C8E340C0148_impl* if (f_Listeners <> nil) then f_Listeners.Remove(aListener); //#UC END# *4992FC8900E1_4C8E340C0148_impl* end;//TPrimToolbarMenuModule.RemoveListener {$IfEnd} //not NoVCM {$If not defined(NoVCM)} function TPrimToolbarMenuModule.pm_GetNotify: IvcmToolbarsCustomizeNotify; //#UC START# *4992FCAD02D1_4C8E340C0148get_var* //#UC END# *4992FCAD02D1_4C8E340C0148get_var* begin //#UC START# *4992FCAD02D1_4C8E340C0148get_impl* Result := Self; //#UC END# *4992FCAD02D1_4C8E340C0148get_impl* end;//TPrimToolbarMenuModule.pm_GetNotify {$IfEnd} //not NoVCM procedure TPrimToolbarMenuModule.Cleanup; //#UC START# *479731C50290_4C8E340C0148_var* //#UC END# *479731C50290_4C8E340C0148_var* begin //#UC START# *479731C50290_4C8E340C0148_impl* FreeAndNil(f_Listeners); inherited; //#UC END# *479731C50290_4C8E340C0148_impl* end;//TPrimToolbarMenuModule.Cleanup constructor TPrimToolbarMenuModule.Create(AOwner: TComponent); //#UC START# *47D1602000C6_4C8E340C0148_var* //#UC END# *47D1602000C6_4C8E340C0148_var* begin //#UC START# *47D1602000C6_4C8E340C0148_impl* inherited; Assert(g_ToolbarsCustomize = nil); g_ToolbarsCustomize := Self; MenuManager := g_MenuManager; Assert(MenuManager <> nil); MenuManager.ToolbarPopup.OnPopup := pmToolbarPopup; // Это нужно чтобы был найден группирующий элемент MenuManager.ToolbarPopup.Items.Caption := vcmStr(ModuleDef.ModuleDef.Caption); // Контекстные операции модуля vcmMakeModuleMenu(MenuManager.ToolbarPopup.Items, ModuleDef.ModuleDef, [{vcm_ooShowInContextMenu}], False); //#UC END# *47D1602000C6_4C8E340C0148_impl* end;//TPrimToolbarMenuModule.Create procedure TPrimToolbarMenuModule.Loaded; begin inherited; PublishOp('opCustomize', opCustomize, opCustomizeTest); ShowInToolbar('opCustomize', false); {$If not defined(Admin) AND not defined(Monitorings)} PublishOp('opAvailableOperations', opAvailableOperations, opAvailableOperationsTest); ShowInToolbar('opAvailableOperations', false); {$IfEnd} //not Admin AND not Monitorings PublishOp('opIconsSize', opIconsSize, opIconsSizeTest); ShowInToolbar('opIconsSize', false); PublishOp('opFasten', opFasten, opFastenTest); ShowInToolbar('opFasten', false); end; class procedure TPrimToolbarMenuModule.GetEntityForms(aList : TvcmClassList); begin inherited; aList.Add(TCustomizeToolsForm); end; initialization // Регистрация Tkw_Form_CustomizeTools Tkw_Form_CustomizeTools.Register('форма::CustomizeTools', TCustomizeToolsForm); end.
{ lzRichEdit Copyright (C) 2010 Elson Junio elsonjunio@yahoo.com.br This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version with the following modification: As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules,and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your 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 Library General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. } unit WSRichBox; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Controls, WSStdCtrls, WSRichBoxFactory, Graphics, RichBox; type { TWSCustomRichBox } TWSCustomRichBox = class(TWSCustomMemo) class function Font_GetCharset(const AWinControl: TWinControl): TFontCharset; virtual; class function Font_GetColor(const AWinControl: TWinControl): TColor; virtual; class function Font_GetName(const AWinControl: TWinControl): TFontName; virtual; class function Font_GetPitch(const AWinControl: TWinControl): TFontPitch; virtual; class function Font_GetProtected(const AWinControl: TWinControl): Boolean; virtual; class function Font_GetSize(const AWinControl: TWinControl): Integer; virtual; class function Font_GetStyle(const AWinControl: TWinControl): TFontStyles; virtual; // class function Para_GetAlignment(const AWinControl: TWinControl): TAlignment; virtual; class function Para_GetFirstIndent(const AWinControl: TWinControl): Longint; virtual; class function Para_GetLeftIndent(const AWinControl: TWinControl): Longint; virtual; class function Para_GetRightIndent(const AWinControl: TWinControl): Longint; virtual; class function Para_GetNumbering(const AWinControl: TWinControl): TNumberingStyle; virtual; class function Para_GetTab(const AWinControl: TWinControl; Index: Byte): Longint; virtual; class function Para_GetTabCount(const AWinControl: TWinControl): Integer; virtual; // class procedure Font_SetCharset(const AWinControl: TWinControl; Value: TFontCharset); virtual; class procedure Font_SetColor(const AWinControl: TWinControl; Value: TColor); virtual; class procedure Font_SetName(const AWinControl: TWinControl; Value: TFontName); virtual; class procedure Font_SetPitch(const AWinControl: TWinControl; Value: TFontPitch); virtual; class procedure Font_SetProtected(const AWinControl: TWinControl; Value: Boolean); virtual; class procedure Font_SetSize(const AWinControl: TWinControl; Value: Integer); virtual; class procedure Font_SetStyle(const AWinControl: TWinControl; Value: TFontStyles); virtual; // class procedure Para_SetAlignment(const AWinControl: TWinControl; Value: TAlignment); virtual; class procedure Para_SetFirstIndent(const AWinControl: TWinControl; Value: Longint); virtual; class procedure Para_SetLeftIndent(const AWinControl: TWinControl; Value: Longint); virtual; class procedure Para_SetRightIndent(const AWinControl: TWinControl; Value: Longint); virtual; class procedure Para_SetNumbering(const AWinControl: TWinControl; Value: TNumberingStyle); virtual; class procedure Para_SetTab(const AWinControl: TWinControl; Index: Byte; Value: Longint); virtual; class procedure Para_SetTabCount(const AWinControl: TWinControl; Value: Integer); virtual; // class procedure SaveToStream (const AWinControl: TWinControl; var Stream: TStream); virtual; class procedure LoadFromStream (const AWinControl: TWinControl; const Stream: TStream); virtual; // class function GetTextBuf (const AWinControl: TWinControl):String; virtual; class function GetTextSel (const AWinControl: TWinControl):String; virtual; end; TWSCustomRichBoxClass = class of TWSCustomRichBox; { WidgetSetRegistration } procedure RegisterCustomRichBox; implementation procedure RegisterCustomRichBox; const Done: Boolean = False; begin if Done then exit; WSRegisterCustomRichBox; Done := True; end; { TWSCustomRichBox } class function TWSCustomRichBox.Font_GetCharset(const AWinControl: TWinControl ): TFontCharset; begin end; class function TWSCustomRichBox.Font_GetColor(const AWinControl: TWinControl ): TColor; begin end; class function TWSCustomRichBox.Font_GetName(const AWinControl: TWinControl ): TFontName; begin end; class function TWSCustomRichBox.Font_GetPitch(const AWinControl: TWinControl ): TFontPitch; begin end; class function TWSCustomRichBox.Font_GetProtected(const AWinControl: TWinControl ): Boolean; begin end; class function TWSCustomRichBox.Font_GetSize(const AWinControl: TWinControl ): Integer; begin end; class function TWSCustomRichBox.Font_GetStyle(const AWinControl: TWinControl ): TFontStyles; begin end; class function TWSCustomRichBox.Para_GetAlignment(const AWinControl: TWinControl ): TAlignment; begin end; class function TWSCustomRichBox.Para_GetFirstIndent( const AWinControl: TWinControl): Longint; begin end; class function TWSCustomRichBox.Para_GetLeftIndent( const AWinControl: TWinControl): Longint; begin end; class function TWSCustomRichBox.Para_GetRightIndent( const AWinControl: TWinControl): Longint; begin end; class function TWSCustomRichBox.Para_GetNumbering(const AWinControl: TWinControl ): TNumberingStyle; begin end; class function TWSCustomRichBox.Para_GetTab(const AWinControl: TWinControl; Index: Byte): Longint; begin end; class function TWSCustomRichBox.Para_GetTabCount(const AWinControl: TWinControl ): Integer; begin end; class procedure TWSCustomRichBox.Font_SetCharset( const AWinControl: TWinControl; Value: TFontCharset); begin end; class procedure TWSCustomRichBox.Font_SetColor(const AWinControl: TWinControl; Value: TColor); begin end; class procedure TWSCustomRichBox.Font_SetName(const AWinControl: TWinControl; Value: TFontName); begin end; class procedure TWSCustomRichBox.Font_SetPitch(const AWinControl: TWinControl; Value: TFontPitch); begin end; class procedure TWSCustomRichBox.Font_SetProtected( const AWinControl: TWinControl; Value: Boolean); begin end; class procedure TWSCustomRichBox.Font_SetSize(const AWinControl: TWinControl; Value: Integer); begin end; class procedure TWSCustomRichBox.Font_SetStyle(const AWinControl: TWinControl; Value: TFontStyles); begin end; class procedure TWSCustomRichBox.Para_SetAlignment( const AWinControl: TWinControl; Value: TAlignment); begin end; class procedure TWSCustomRichBox.Para_SetFirstIndent( const AWinControl: TWinControl; Value: Longint); begin end; class procedure TWSCustomRichBox.Para_SetLeftIndent( const AWinControl: TWinControl; Value: Longint); begin end; class procedure TWSCustomRichBox.Para_SetRightIndent( const AWinControl: TWinControl; Value: Longint); begin end; class procedure TWSCustomRichBox.Para_SetNumbering( const AWinControl: TWinControl; Value: TNumberingStyle); begin end; class procedure TWSCustomRichBox.Para_SetTab(const AWinControl: TWinControl; Index: Byte; Value: Longint); begin end; class procedure TWSCustomRichBox.Para_SetTabCount( const AWinControl: TWinControl; Value: Integer); begin end; class procedure TWSCustomRichBox.SaveToStream(const AWinControl: TWinControl; var Stream: TStream); begin end; class procedure TWSCustomRichBox.LoadFromStream(const AWinControl: TWinControl; const Stream: TStream); begin end; class function TWSCustomRichBox.GetTextBuf(const AWinControl: TWinControl ): String; begin end; class function TWSCustomRichBox.GetTextSel(const AWinControl: TWinControl ): String; begin end; end.
unit DAO.PlanilhaRespostaCTNC; interface uses Generics.Collections, System.Classes, System.SysUtils, Forms, Windows, Model.PlanilhaRespostaCTNC; type TPlanilhaRespostaCTNCDAO = class public function GetPlanilha(sFile: String): TObjectList<TPlanilhaRespostaCTNC>; end; implementation { TPlanilhaRespostaCTNCDAO } function TPlanilhaRespostaCTNCDAO.GetPlanilha(sFile: String): TObjectList<TPlanilhaRespostaCTNC>; var ArquivoCSV: TextFile; sLinha: String; sDetalhe: TStringList; respostas : TObjectList<TPlanilhaRespostaCTNC>; i : Integer; begin try respostas := TObjectList<TPlanilhaRespostaCTNC>.Create; if not FileExists(sFile) then begin Application.MessageBox(PChar('Arquivo ' + sFile + ' não foi encontrado!'), 'Atenção', MB_ICONWARNING + MB_OK); Exit; end; AssignFile(ArquivoCSV, sFile); if sFile.IsEmpty then Exit; sDetalhe := TStringList.Create; sDetalhe.StrictDelimiter := True; sDetalhe.Delimiter := ';'; Reset(ArquivoCSV); Readln(ArquivoCSV, sLinha); sDetalhe.DelimitedText := sLinha; i := 0; if sDetalhe[0] <> 'RESPOSTAS PARA ENTREGA' then begin Application.MessageBox('Arquivo informado não foi identificado como a Planilha de de Respostas de CTNC!', 'Atenção', MB_ICONWARNING + MB_OK); Exit; end; while not Eoln(ArquivoCSV) do begin Readln(ArquivoCSV, sLinha); sDetalhe.DelimitedText := sLinha; if sDetalhe[0] = '0' then begin respostas.Add(TPlanilhaRespostaCTNC.Create); i := respostas.Count - 1; respostas[i].Flag := sDetalhe[0]; respostas[i].Data := sDetalhe[1]; respostas[i].NN := sDetalhe[2]; respostas[i].Resposta := sDetalhe[3]; respostas[i].CodigoEmbarcador := sDetalhe[4]; respostas[i].NomeEmbarcador := sDetalhe[5]; respostas[i].Pedido := sDetalhe[6]; respostas[i].Consumidor := sDetalhe[7]; respostas[i].Telefone := sDetalhe[8]; respostas[i].Atribuicao := sDetalhe[9]; respostas[i].Entregador := sDetalhe[10]; respostas[i].Previsao := sDetalhe[11]; respostas[i].Leitura := sDetalhe[12]; respostas[i].Usuario := sDetalhe[13]; respostas[i].Sequencia := sDetalhe[14]; respostas[i].Cidade := sDetalhe[15]; end; end; Result := respostas; finally CloseFile(ArquivoCSV); end; end; end.
program WhileProgram5309; var n, s: integer; begin n := 50; s := 1; Writeln('S', #9, 'N'); while s < 1000 do begin s := s * 2; n := n + 10; Writeln(S, #9, n); end; Write('n = ', n); end.
unit StrForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) EditResemble1: TEdit; EditResemble2: TEdit; ButtonResemble: TButton; ListBoxMatch: TListBox; EditMatch: TEdit; ButtonMatches: TButton; ButtonIndex: TButton; EditSample: TEdit; ButtonTriplicate: TButton; ButtonReverse: TButton; ButtonRandom: TButton; btnPos2: TButton; bntPos1: TButton; procedure ButtonResembleClick(Sender: TObject); procedure ButtonMatchesClick(Sender: TObject); procedure ButtonIndexClick(Sender: TObject); procedure ButtonTriplicateClick(Sender: TObject); procedure ButtonReverseClick(Sender: TObject); procedure ButtonRandomClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure bntPos1Click(Sender: TObject); procedure btnPos2Click(Sender: TObject); private strArray: array of string; public { Public declarations } end; var Form1: TForm1; implementation {$R *.DFM} uses StrUtils; procedure TForm1.ButtonResembleClick(Sender: TObject); begin ShowMessage (BoolToStr (AnsiResemblesText (EditResemble1.Text, EditResemble2.Text), True)); end; procedure TForm1.ButtonMatchesClick(Sender: TObject); begin ShowMessage (BoolToStr (AnsiMatchText(EditMatch.Text, strArray), True)); end; procedure TForm1.ButtonIndexClick(Sender: TObject); var nMatch: Integer; begin nMatch := AnsiIndexText(EditMatch.Text, strArray); ShowMessage (IfThen (nMatch >= 0, 'Matches the string number ' + IntToStr (nMatch), 'No match')); end; procedure TForm1.ButtonTriplicateClick(Sender: TObject); begin ShowMessage (DupeString (EditSample.Text, 3)); end; procedure TForm1.ButtonReverseClick(Sender: TObject); begin ShowMessage (ReverseString (EditSample.Text)); end; procedure TForm1.ButtonRandomClick(Sender: TObject); begin ShowMessage (RandomFrom (strArray)); end; procedure TForm1.FormCreate(Sender: TObject); var I: Integer; begin SetLength (strArray, ListBoxMatch.Items.Count); for I := 0 to ListBoxMatch.Items.Count - 1 do strArray [I] := ListBoxMatch.Items [I]; // set the random seed, for the RandomFrom calls Randomize; end; function CountSubstr (text, sub: string): Integer; var nPos: Integer; begin Result := 0; nPos := Pos (sub, text); while nPos > 0 do begin Inc (Result); text := Copy (text, nPos + Length (sub), MaxInt); nPos := Pos (sub, text); end; end; function CountSubstrEx (text, sub: string): Integer; var nPos: Integer; begin Result := 0; nPos := PosEx (sub, text, 1); // default while nPos > 0 do begin Inc (Result); nPos := PosEx (sub, text, nPos + Length (sub)); end; end; procedure TForm1.bntPos1Click(Sender: TObject); begin ShowMessage ('Count = ' + IntToStr ( CountSubstr (ListBoxMatch.Items.Text, 'e'))); end; procedure TForm1.btnPos2Click(Sender: TObject); begin ShowMessage ('Count = ' + IntToStr ( CountSubstrEx (ListBoxMatch.Items.Text, 'e'))); end; end.
unit arEditorDebugInfo; {* Класс для вывода информаци о состоянии редактора в лог. } // Модуль: "w:\archi\source\projects\Archi\Main\arEditorDebugInfo.pas" // Стереотип: "SimpleClass" // Элемент модели: "TarEditorDebugInfo" MUID: (52A7FD0E002D) {$Include w:\archi\source\projects\Archi\arDefine.inc} interface {$If Defined(AppClientSide)} uses l3IntfUses , l3ProtoObject , l3Interfaces , l3Core ; type TarEditorDebugInfo = class(Tl3ProtoObject, Il3GetMessageListener) {* Класс для вывода информаци о состоянии редактора в лог. } protected procedure GetMessageListenerNotify(Code: Integer; aWParam: WPARAM; Msg: PMsg; var theResult: Tl3HookProcResult); procedure Cleanup; override; {* Функция очистки полей объекта. } procedure InitFields; override; public class function Instance: TarEditorDebugInfo; {* Метод получения экземпляра синглетона TarEditorDebugInfo } class function Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } end;//TarEditorDebugInfo {$IfEnd} // Defined(AppClientSide) implementation {$If Defined(AppClientSide)} uses l3ImplUses , Main , CustEditWin , Windows , Messages {$If NOT Defined(NoVCL)} , Forms {$IfEnd} // NOT Defined(NoVCL) , Classes , l3ListenersManager , SysUtils , l3Base //#UC START# *52A7FD0E002Dimpl_uses* //#UC END# *52A7FD0E002Dimpl_uses* ; var g_TarEditorDebugInfo: TarEditorDebugInfo = nil; {* Экземпляр синглетона TarEditorDebugInfo } procedure TarEditorDebugInfoFree; {* Метод освобождения экземпляра синглетона TarEditorDebugInfo } begin l3Free(g_TarEditorDebugInfo); end;//TarEditorDebugInfoFree procedure TarEditorDebugInfo.GetMessageListenerNotify(Code: Integer; aWParam: WPARAM; Msg: PMsg; var theResult: Tl3HookProcResult); //#UC START# *4F62032D0058_52A7FD0E002D_var* var l_Editor: TCustomEditorWindow; //#UC END# *4F62032D0058_52A7FD0E002D_var* begin //#UC START# *4F62032D0058_52A7FD0E002D_impl* if (Msg.Message = WM_KEYDOWN) and (Msg.wParam = VK_F11) and (KeyDataToShiftState(Msg.lParam) = [ssShift, ssAlt, ssCtrl]) then if MainForm.ActiveMDIChild is TCustomEditorWindow then begin l_Editor := MainForm.ActiveMDIChild as TCustomEditorWindow; l_Editor.SaveState2Log; end; // if MainForm.ActiveMDIChild is TCustomEditorWindow then //#UC END# *4F62032D0058_52A7FD0E002D_impl* end;//TarEditorDebugInfo.GetMessageListenerNotify class function TarEditorDebugInfo.Instance: TarEditorDebugInfo; {* Метод получения экземпляра синглетона TarEditorDebugInfo } begin if (g_TarEditorDebugInfo = nil) then begin l3System.AddExitProc(TarEditorDebugInfoFree); g_TarEditorDebugInfo := Create; end; Result := g_TarEditorDebugInfo; end;//TarEditorDebugInfo.Instance class function TarEditorDebugInfo.Exists: Boolean; {* Проверяет создан экземпляр синглетона или нет } begin Result := g_TarEditorDebugInfo <> nil; end;//TarEditorDebugInfo.Exists procedure TarEditorDebugInfo.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_52A7FD0E002D_var* //#UC END# *479731C50290_52A7FD0E002D_var* begin //#UC START# *479731C50290_52A7FD0E002D_impl* Tl3ListenersManager.RemoveGetMessageListener(Self); inherited; //#UC END# *479731C50290_52A7FD0E002D_impl* end;//TarEditorDebugInfo.Cleanup procedure TarEditorDebugInfo.InitFields; //#UC START# *47A042E100E2_52A7FD0E002D_var* //#UC END# *47A042E100E2_52A7FD0E002D_var* begin //#UC START# *47A042E100E2_52A7FD0E002D_impl* inherited; Tl3ListenersManager.AddGetMessageListener(Self); //#UC END# *47A042E100E2_52A7FD0E002D_impl* end;//TarEditorDebugInfo.InitFields initialization //#UC START# *52A81A6E009E* TarEditorDebugInfo.Instance; //#UC END# *52A81A6E009E* {$IfEnd} // Defined(AppClientSide) end.
unit Computer; interface uses Collectible; type TBitsComputer = (bits8, bits16, bits32); TComputer = class(TCollectible) private Fmanufacturer: String; Fmodel: String; Fbits: TBitsComputer; FRAM: SmallInt; FROM: SmallInt; Fworks: Boolean; public constructor Create(name: String); property Manufacturer: String read Fmanufacturer write Fmanufacturer; property Model: String read Fmodel write Fmodel; property Bits: TBitsComputer read Fbits write Fbits; property RAM: SmallInt read FRAM write FRAM; property ROM: SmallInt read FROM write FROM; property ItWorks: Boolean read Fworks write Fworks; end; implementation constructor TComputer.Create(name: String); begin inherited Create(name); Fbits := bits8; FRAM := 64; FROM := 32; Fworks := True; end; end.
unit nevInterfaces; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "Everest" // Автор: Люлин А.В. // Модуль: "w:/common/components/gui/Garant/Everest/new/nevInterfaces.pas" // Начат: 01.03.2010 14:30 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<UtilityPack::Class>> Shared Delphi::Everest::nevInterfaces::nevInterfaces // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include ..\new\nevDefine.inc} interface uses l3StringIDEx ; var { Локализуемые строки TnevMiscMessages } str_nevmmSaveText : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmmSaveText'; rValue : 'Сохранение текста'); { 'Сохранение текста' } str_nevmmSaveFormattedText : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmmSaveFormattedText'; rValue : 'Сохранение текста в формате "%s"'); { 'Сохранение текста в формате "%s"' } str_nevmmReference : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmmReference'; rValue : 'Справка: %s'); { 'Справка: %s' } str_nevmmPageCounter : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmmPageCounter'; rValue : 'Страница %d из %d'); { 'Страница %d из %d' } str_nevmmDocumentCount : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmmDocumentCount'; rValue : 'Документ %d из %d'); { 'Документ %d из %d' } str_nevmmDocumentCountInt : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmmDocumentCountInt'; rValue : 'Документ %d из %d, выделено %d'); { 'Документ %d из %d, выделено %d' } str_nevmmComment : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmmComment'; rValue : ' Мой комментарий '); { ' Мой комментарий ' } str_nevmmReplace : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmmReplace'; rValue : 'Замена'); { 'Замена' } str_nevmmFragment : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmmFragment'; rValue : '%s (фрагмент)'); { '%s (фрагмент)' } str_nevmmSearch : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmmSearch'; rValue : 'Поиск'); { 'Поиск' } str_nevmmLongOperation : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmmLongOperation'; rValue : 'Выполняется длительная операция...'); { 'Выполняется длительная операция...' } str_nevmmCommentFolder : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmmCommentFolder'; rValue : ' Мой комментарий '); { ' Мой комментарий ' } str_nevmmAnnotation : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmmAnnotation'; rValue : 'Аннотация: %s'); { 'Аннотация: %s' } str_nevmmTranslation : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmmTranslation'; rValue : 'Перевод: %s'); { 'Перевод: %s' } str_nevmmJurorComment : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmmJurorComment'; rValue : ' Комментарий ГАРАНТа '); { ' Комментарий ГАРАНТа ' } str_nevmmJurorCommentDecorate : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmmJurorCommentDecorate'; rValue : 'Комментарий ГАРАНТа'); { 'Комментарий ГАРАНТа' } str_nevmmTOC : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmmTOC'; rValue : 'Оглавление'); { 'Оглавление' } str_nevmmPageCounterNew : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmmPageCounterNew'; rValue : 'Объем распечатки в листах: %d'); { 'Объем распечатки в листах: %d' } var { Локализуемые строки TnevTextFormats } str_nevtfANSI : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevtfANSI'; rValue : 'ANSI-текст'); { 'ANSI-текст' } str_nevtfUnicode : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevtfUnicode'; rValue : 'Unicode-текст'); { 'Unicode-текст' } str_nevtfOEM : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevtfOEM'; rValue : 'OEM-текст'); { 'OEM-текст' } {$If defined(evMyEditor)} str_nevtfThyEditor : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevtfThyEditor'; rValue : 'Моего редактора'); { 'Моего редактора' } {$IfEnd} //evMyEditor {$If defined(Nemesis)} str_nevtfGarant : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevtfGarant'; rValue : 'Документ ГАРАНТа'); { 'Документ ГАРАНТа' } {$IfEnd} //Nemesis {$If not defined(Nemesis)} str_nevtfEverestBin : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevtfEverestBin'; rValue : 'Эверест (binary)'); { 'Эверест (binary)' } {$IfEnd} //not Nemesis {$If not defined(Nemesis)} str_nevtfEverest : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevtfEverest'; rValue : 'Эверест'); { 'Эверест' } {$IfEnd} //not Nemesis str_nevtfRtf : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevtfRtf'; rValue : 'RTF'); { 'RTF' } var { Локализуемые строки TnevPrintMessages } str_nevpmTimeLeft : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevpmTimeLeft'; rValue : ', %d секунд осталось'); { ', %d секунд осталось' } str_nevpmCounting : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevpmCounting'; rValue : 'Подсчет числа страниц... %d (~%d)'); { 'Подсчет числа страниц... %d (~%d)' } str_nevpmPreparing : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevpmPreparing'; rValue : 'Подготовка просмотра печати... %d страниц подготовлено'); { 'Подготовка просмотра печати... %d страниц подготовлено' } str_nevpmPreparingExt : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevpmPreparingExt'; rValue : 'Подготовка просмотра печати... %d страниц из %s%d подготовлено'); { 'Подготовка просмотра печати... %d страниц из %s%d подготовлено' } str_nevpmPrinting : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevpmPrinting'; rValue : 'Печать документа'); { 'Печать документа' } str_nevpmDocumentList : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevpmDocumentList'; rValue : 'Список документов'); { 'Список документов' } str_nevpmDefaultColontitul : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevpmDefaultColontitul'; rValue : '%s Страниц: %s Напечатан: %s'); { '%s Страниц: %s Напечатан: %s' } str_nevpmUndefinedSize : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevpmUndefinedSize'; rValue : 'Не определен'); { 'Не определен' } str_nevpmUndefinedTopic : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevpmUndefinedTopic'; rValue : 'Не определен'); { 'Не определен' } str_nevpmProcessText : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevpmProcessText'; rValue : 'Обработка текста'); { 'Обработка текста' } str_nevpmProcessPreview : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevpmProcessPreview'; rValue : 'Обработка просмотра печати'); { 'Обработка просмотра печати' } var { Локализуемые строки TnevCommentParaHint } str_nevcphExpand : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevcphExpand'; rValue : 'Развернуть комментарий'); { 'Развернуть комментарий' } str_nevcphCollapse : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevcphCollapse'; rValue : 'Свернуть комментарий'); { 'Свернуть комментарий' } str_nevcphSelect : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevcphSelect'; rValue : 'Выделить комментарий'); { 'Выделить комментарий' } str_nevcphMove : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevcphMove'; rValue : 'Переместить комментарий'); { 'Переместить комментарий' } str_nevcphChangeTopBorder : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevcphChangeTopBorder'; rValue : 'Изменить верхнюю границу комментария'); { 'Изменить верхнюю границу комментария' } str_nevcphChangeBottomBorder : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevcphChangeBottomBorder'; rValue : 'Изменить нижнюю границу комментария'); { 'Изменить нижнюю границу комментария' } str_nevcphProperties : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevcphProperties'; rValue : 'Свойства комментария'); { 'Свойства комментария' } var { Локализуемые строки TnevMemoContextMenu } str_nevmcmUndo : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmcmUndo'; rValue : 'Отменить'); { 'Отменить' } str_nevmcmCut : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmcmCut'; rValue : 'Вырезать'); { 'Вырезать' } str_nevmcmCopy : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmcmCopy'; rValue : 'Копировать'); { 'Копировать' } str_nevmcmPaste : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmcmPaste'; rValue : 'Вставить'); { 'Вставить' } str_nevmcmDelete : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmcmDelete'; rValue : 'Удалить'); { 'Удалить' } var { Локализуемые строки TnevDocumentPartHint } str_nevdphExpand : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevdphExpand'; rValue : 'Развернуть блок'); { 'Развернуть блок' } str_nevdphCollapse : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevdphCollapse'; rValue : 'Свернуть блок'); { 'Свернуть блок' } str_nevdphSelect : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevdphSelect'; rValue : 'Выделить блок'); { 'Выделить блок' } str_nevdphMove : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevdphMove'; rValue : 'Переместить блок'); { 'Переместить блок' } str_nevdphChangeTopBorder : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevdphChangeTopBorder'; rValue : 'Изменить верхнюю границу блока'); { 'Изменить верхнюю границу блока' } str_nevdphChangeBottomBorder : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevdphChangeBottomBorder'; rValue : 'Изменить нижнюю границу блока'); { 'Изменить нижнюю границу блока' } str_nevdphProperties : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevdphProperties'; rValue : 'Свойства блока'); { 'Свойства блока' } var { Локализуемые строки TnevMiscHotspotHints } str_nevmhhBlockParams : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmhhBlockParams'; rValue : 'Параметры раздела.'); { 'Параметры раздела.' } str_nevmhhTableCell : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmhhTableCell'; rValue : 'Ячейка таблицы'); { 'Ячейка таблицы' } str_nevmhhTableSize : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmhhTableSize'; rValue : 'Размер таблицы'); { 'Размер таблицы' } str_nevmhhColumnSize : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmhhColumnSize'; rValue : 'Размер столбца'); { 'Размер столбца' } str_nevmhhTableColumn : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmhhTableColumn'; rValue : 'Колонка таблицы'); { 'Колонка таблицы' } str_nevmhhTableRow : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmhhTableRow'; rValue : 'Строка таблицы'); { 'Строка таблицы' } str_nevmhhLeftHyperlinkBorder : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmhhLeftHyperlinkBorder'; rValue : 'Левая граница ссылки'); { 'Левая граница ссылки' } str_nevmhhRightHyperlinkBorder : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmhhRightHyperlinkBorder'; rValue : 'Правая граница ссылки'); { 'Правая граница ссылки' } var { Локализуемые строки TnevMarkerHint } str_nevmhLeftIndent : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmhLeftIndent'; rValue : 'Левый отступ'); { 'Левый отступ' } str_nevmhRightIndent : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmhRightIndent'; rValue : 'Правый отступ'); { 'Правый отступ' } str_nevmhRedLineIndent : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmhRedLineIndent'; rValue : 'Отступ красной строки'); { 'Отступ красной строки' } str_nevmhCellSize : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmhCellSize'; rValue : 'Размер ячейки'); { 'Размер ячейки' } str_nevmhTableIndent : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmhTableIndent'; rValue : 'Отступ таблицы'); { 'Отступ таблицы' } str_nevmhPaperSize : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmhPaperSize'; rValue : 'Размер бумаги'); { 'Размер бумаги' } str_nevmhLeftDocMargin : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmhLeftDocMargin'; rValue : 'Левое поле'); { 'Левое поле' } str_nevmhRightDocMargin : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmhRightDocMargin'; rValue : 'Правое поле'); { 'Правое поле' } str_nevmhTabIndent : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'nevmhTabIndent'; rValue : 'По разделителю'); { 'По разделителю' } implementation uses l3MessageID ; initialization // Инициализация str_nevmmSaveText str_nevmmSaveText.Init; // Инициализация str_nevmmSaveFormattedText str_nevmmSaveFormattedText.Init; // Инициализация str_nevmmReference str_nevmmReference.Init; // Инициализация str_nevmmPageCounter str_nevmmPageCounter.Init; // Инициализация str_nevmmDocumentCount str_nevmmDocumentCount.Init; // Инициализация str_nevmmDocumentCountInt str_nevmmDocumentCountInt.Init; // Инициализация str_nevmmComment str_nevmmComment.Init; // Инициализация str_nevmmReplace str_nevmmReplace.Init; // Инициализация str_nevmmFragment str_nevmmFragment.Init; // Инициализация str_nevmmSearch str_nevmmSearch.Init; // Инициализация str_nevmmLongOperation str_nevmmLongOperation.Init; // Инициализация str_nevmmCommentFolder str_nevmmCommentFolder.Init; // Инициализация str_nevmmAnnotation str_nevmmAnnotation.Init; // Инициализация str_nevmmTranslation str_nevmmTranslation.Init; // Инициализация str_nevmmJurorComment str_nevmmJurorComment.Init; // Инициализация str_nevmmJurorCommentDecorate str_nevmmJurorCommentDecorate.Init; // Инициализация str_nevmmTOC str_nevmmTOC.Init; // Инициализация str_nevmmPageCounterNew str_nevmmPageCounterNew.Init; // Инициализация str_nevtfANSI str_nevtfANSI.Init; // Инициализация str_nevtfUnicode str_nevtfUnicode.Init; // Инициализация str_nevtfOEM str_nevtfOEM.Init; {$If defined(evMyEditor)} // Инициализация str_nevtfThyEditor str_nevtfThyEditor.Init; {$IfEnd} //evMyEditor {$If defined(Nemesis)} // Инициализация str_nevtfGarant str_nevtfGarant.Init; {$IfEnd} //Nemesis {$If not defined(Nemesis)} // Инициализация str_nevtfEverestBin str_nevtfEverestBin.Init; {$IfEnd} //not Nemesis {$If not defined(Nemesis)} // Инициализация str_nevtfEverest str_nevtfEverest.Init; {$IfEnd} //not Nemesis // Инициализация str_nevtfRtf str_nevtfRtf.Init; // Инициализация str_nevpmTimeLeft str_nevpmTimeLeft.Init; // Инициализация str_nevpmCounting str_nevpmCounting.Init; // Инициализация str_nevpmPreparing str_nevpmPreparing.Init; // Инициализация str_nevpmPreparingExt str_nevpmPreparingExt.Init; // Инициализация str_nevpmPrinting str_nevpmPrinting.Init; // Инициализация str_nevpmDocumentList str_nevpmDocumentList.Init; // Инициализация str_nevpmDefaultColontitul str_nevpmDefaultColontitul.Init; // Инициализация str_nevpmUndefinedSize str_nevpmUndefinedSize.Init; // Инициализация str_nevpmUndefinedTopic str_nevpmUndefinedTopic.Init; // Инициализация str_nevpmProcessText str_nevpmProcessText.Init; // Инициализация str_nevpmProcessPreview str_nevpmProcessPreview.Init; // Инициализация str_nevcphExpand str_nevcphExpand.Init; // Инициализация str_nevcphCollapse str_nevcphCollapse.Init; // Инициализация str_nevcphSelect str_nevcphSelect.Init; // Инициализация str_nevcphMove str_nevcphMove.Init; // Инициализация str_nevcphChangeTopBorder str_nevcphChangeTopBorder.Init; // Инициализация str_nevcphChangeBottomBorder str_nevcphChangeBottomBorder.Init; // Инициализация str_nevcphProperties str_nevcphProperties.Init; // Инициализация str_nevmcmUndo str_nevmcmUndo.Init; // Инициализация str_nevmcmCut str_nevmcmCut.Init; // Инициализация str_nevmcmCopy str_nevmcmCopy.Init; // Инициализация str_nevmcmPaste str_nevmcmPaste.Init; // Инициализация str_nevmcmDelete str_nevmcmDelete.Init; // Инициализация str_nevdphExpand str_nevdphExpand.Init; // Инициализация str_nevdphCollapse str_nevdphCollapse.Init; // Инициализация str_nevdphSelect str_nevdphSelect.Init; // Инициализация str_nevdphMove str_nevdphMove.Init; // Инициализация str_nevdphChangeTopBorder str_nevdphChangeTopBorder.Init; // Инициализация str_nevdphChangeBottomBorder str_nevdphChangeBottomBorder.Init; // Инициализация str_nevdphProperties str_nevdphProperties.Init; // Инициализация str_nevmhhBlockParams str_nevmhhBlockParams.Init; // Инициализация str_nevmhhTableCell str_nevmhhTableCell.Init; // Инициализация str_nevmhhTableSize str_nevmhhTableSize.Init; // Инициализация str_nevmhhColumnSize str_nevmhhColumnSize.Init; // Инициализация str_nevmhhTableColumn str_nevmhhTableColumn.Init; // Инициализация str_nevmhhTableRow str_nevmhhTableRow.Init; // Инициализация str_nevmhhLeftHyperlinkBorder str_nevmhhLeftHyperlinkBorder.Init; // Инициализация str_nevmhhRightHyperlinkBorder str_nevmhhRightHyperlinkBorder.Init; // Инициализация str_nevmhLeftIndent str_nevmhLeftIndent.Init; // Инициализация str_nevmhRightIndent str_nevmhRightIndent.Init; // Инициализация str_nevmhRedLineIndent str_nevmhRedLineIndent.Init; // Инициализация str_nevmhCellSize str_nevmhCellSize.Init; // Инициализация str_nevmhTableIndent str_nevmhTableIndent.Init; // Инициализация str_nevmhPaperSize str_nevmhPaperSize.Init; // Инициализация str_nevmhLeftDocMargin str_nevmhLeftDocMargin.Init; // Инициализация str_nevmhRightDocMargin str_nevmhRightDocMargin.Init; // Инициализация str_nevmhTabIndent str_nevmhTabIndent.Init; end.
{ Subroutine SST_R_PAS_ITEM_EVAL (VAL) * * Evaluate an ITEM syntax. The ITEM must resolve to a constant that can be * evaluated at compile time. VAL is returned as the constant value. } module sst_r_pas_ITEM_EVAL; define sst_r_pas_item_eval; %include 'sst_r_pas.ins.pas'; procedure sst_r_pas_item_eval ( {find constant value of ITEM syntax} out val: sst_var_value_t); {returned value of ITEM} var tag: sys_int_machine_t; {syntax tag ID} str_h: syo_string_t; {handle to string associated with TAG} tag2: sys_int_machine_t; {syntax tag to avoid corrupting TAG} str2_h: syo_string_t; {string handle associated with TAG2} tag_unadic: sys_int_machine_t; {tag for preceding unadic operator, if any} str_h_unadic: syo_string_t; {handle to string associated with TAG_UNADIC} token: string_var80_t; {scratch string for number conversion} str: string_var8192_t; {for building string constant} size: sys_int_adr_t; {amount of memory needed} sym_p: sst_symbol_p_t; {points to symbol from symbol table} msg_parm: {message parameter references} array[1..4] of sys_parm_msg_t; stat: sys_err_t; label unadic_not_match; begin token.max := sizeof(token.str); {init local var strings} str.max := sizeof(str.str); syo_level_down; {down into ITEM syntax level} syo_get_tag_msg (tag_unadic, str_h_unadic, 'sst_pas_read', 'constant_bad', nil, 0); syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'constant_bad', nil, 0); case tag of { ******************************** * * Floating point number. } 1: begin syo_get_tag_string (str_h, token); {get string of real number} string_t_fp2 (token, val.float_val, stat); {make floating point from string} syo_error_abort (stat, str_h, 'sst_pas_read', 'constant_bad', nil, 0); val.dtype := sst_dtype_float_k; end; { ******************************** * * Integer. } 2: begin sst_r_pas_integer (val.int_val); {get integer value} val.dtype := sst_dtype_int_k; {set data type for this item} end; { ******************************** * * Literal string. } 3: begin sst_r_pas_lit_string (str); {get value of literal string constant} if str.len = 1 then begin {string has one char, make CHAR data type} val.char_val := str.str[1]; val.dtype := sst_dtype_char_k; end else begin {not just one char, make STRING data type} size := {amount of mem needed for string constant} sizeof(string_var4_t) {size of string with 4 chars} - 4 + str.len; {adjust for size of our string} sst_mem_alloc_scope (size, val.ar_str_p); {allocate memory for returned string} val.ar_str_p^.max := str.len; {set returned string} string_copy (str, val.ar_str_p^); val.dtype := sst_dtype_array_k; end ; end; { ******************************** * * Nested expression in parenthesis. } 4: begin sst_r_pas_exp_eval (val); {return nested expression value} end; { ******************************** * * SET value. } 5: begin writeln ('SET constant expression have not been implemented yet.'); syo_error (str_h, '', '', nil, 0); end; { ******************************** * * Variable, CONST, function, or array. } 6: begin syo_level_down; {down into VARIABLE syntax} syo_get_tag_msg ( {get variable name tag} tag, str_h, 'sst_pas_read', 'constant_bad', nil, 0); syo_get_tag_msg (tag2, str2_h, 'sst_pas_read', 'constant_bad', nil, 0); if tag2 <> syo_tag_end_k then begin syo_error (str2_h, 'sst_pas_read', 'var_not_simple', nil, 0); end; syo_level_up; {back to ITEM syntax level from VARIABLE} sst_symbol_lookup (str_h, sym_p, stat); {look up symbol name in symbol table} syo_error_abort (stat, str_h, '', '', nil, 0); syo_get_tag_msg (tag, str_h, 'sst_pas_read', 'constant_bad', nil, 0); case tag of {what follows the symbol name ?} 1: begin {nothing follows the symbol name} case sym_p^.symtype of {what kind of symbol is this ?} sst_symtype_const_k: begin {symbol is a constant} val := sym_p^.const_exp_p^.val; {copy value of constant} end; sst_symtype_enum_k: begin {symbol is value of an enumerated type} val.enum_p := sym_p; {pass back pointer to symbol} val.dtype := sst_dtype_enum_k; {indicate this is value of enumerated type} end; otherwise {this symbol type can not have a constant val} sys_msg_parm_vstr (msg_parm[1], sym_p^.name_in_p^); syo_error (str_h, 'sst_pas_read', 'symbol_not_value', msg_parm, 1); end; {end of symbol data type cases} end; {end of symbol with nothing following} 2: begin {symbol is followed by function arguments} if sym_p^.symtype <> sst_symtype_front_k then begin {not intrinsic function ?} sys_msg_parm_vstr (msg_parm[1], sym_p^.name_in_p^); syo_error (str_h, 'sst_pas_read', 'func_not_intrinsic', msg_parm, 1); end; writeln ('"', sym_p^.name_in_p^.str:sym_p^.name_in_p^.len, '" is unimplemented intrinsic function in SST_R_PAS_ITEM_EVAL.'); syo_error (str_h, '', '', nil, 0); end; {end of ITEM is function with args case} otherwise syo_error_tag_unexp (tag, str_h); end; {done with what follows symbol cases} end; {end of VAR, CONST, function, or array case} { ******************************** * * Boolean constant TRUE. } 7: begin val.dtype := sst_dtype_bool_k; val.bool_val := true; end; { ******************************** * * Boolean constant FALSE. } 8: begin val.dtype := sst_dtype_bool_k; val.bool_val := false; end; { ******************************** * * Pointer constant NIL. } 9: begin val.dtype := sst_dtype_pnt_k; val.pnt_dtype_p := sst_dtype_uptr_p; val.pnt_exp_p := nil; end; { ******************************** * * Unexpected TAG value for second tag in ITEM. } otherwise syo_error_tag_unexp (tag, str_h); end; {done with second ITEM tag cases} { * VAL is all set except for handling the unadic operator, if any. } if tag_unadic <> 1 then begin {there was a preceeding unadic operator ?} case val.dtype of sst_dtype_int_k: begin {integer} case tag_unadic of 2: ; {+} 3: val.int_val := -val.int_val; {-} 5: val.int_val := ~val.int_val; {~} otherwise goto unadic_not_match; end; end; sst_dtype_float_k: begin {floating point} case tag_unadic of 2: ; {+} 3: val.float_val := -val.float_val; {-} otherwise goto unadic_not_match; end; end; sst_dtype_bool_k: begin {boolean} case tag_unadic of 4: val.bool_val := not val.bool_val; {not} otherwise goto unadic_not_match; end; end; otherwise goto unadic_not_match; {all other combinations are invalid} end; {end of data type cases} end; {done handling preceeding unadic operator} syo_level_up; {up from ITEM syntax level} return; unadic_not_match: {unadic operator not match item data type} syo_error (str_h_unadic, 'sst_pas_read', 'unadic_not_match', nil, 0); end;
unit Tests.TObervable; interface uses DUnitX.TestFramework, System.Classes, System.SysUtils, Patterns.Observable; {$M+} type [TestFixture] TObervableTests = class(TObject) private FObservable: TObservable; public [Setup] procedure Setup; [TearDown] procedure TearDown; published // ------------- procedure TestCountZero; procedure TestAddObserver_One; procedure TestAddObserver_Two; procedure TestDeleteObserver_Add2_Delete1; procedure TestDeleteObservers; // ------------- procedure TestChanged_InitialNotChanged; procedure TestChanged_SetChanged; procedure TestChanged_SetAndClearChanged; // ------------- procedure TestNotify_OneObserver; procedure TestNotify_NotNotifedWithoutSetChanged; procedure TestNotify_NotNotifedAfterSetAndClearChanged; end; implementation // ------------------------------------------------------------------------ // TBaseObserver class // ------------------------------------------------------------------------ {$REGION 'TBaseObserver implementation'} type TBaseObserver = class(TInterfacedObject, IObserver) strict private FIsUpdated: boolean; public procedure OnObserverUpdate(AObservable: TObservable; AObject: TObject); function IsUpdated: boolean; end; function TBaseObserver.IsUpdated: boolean; begin Result := FIsUpdated; end; procedure TBaseObserver.OnObserverUpdate(AObservable: TObservable; AObject: TObject); begin FIsUpdated := True; end; {$ENDREGION} // ------------------------------------------------------------------------ // Setup and TearDown // ------------------------------------------------------------------------ {$REGION 'Setup and tear down'} procedure TObervableTests.Setup; begin FObservable := TObservable.Create; end; procedure TObervableTests.TearDown; begin FreeAndNil(FObservable); end; {$ENDREGION} // ------------------------------------------------------------------------ // Basic tests // ------------------------------------------------------------------------ {$REGION 'Basic tests'} procedure TObervableTests.TestCountZero; begin Assert.AreEqual(0, FObservable.countObservers); end; procedure TObervableTests.TestAddObserver_One; begin FObservable.addObserver(TBaseObserver.Create); Assert.AreEqual(1, FObservable.countObservers); end; procedure TObervableTests.TestAddObserver_Two; begin FObservable.addObserver(TBaseObserver.Create); FObservable.addObserver(TBaseObserver.Create); Assert.AreEqual(2, FObservable.countObservers); end; procedure TObervableTests.TestDeleteObserver_Add2_Delete1; var o1: IObserver; begin o1 := TBaseObserver.Create; FObservable.addObserver(o1); FObservable.addObserver(TBaseObserver.Create); FObservable.deleteObserver(o1); Assert.AreEqual(1, FObservable.countObservers); end; procedure TObervableTests.TestDeleteObservers; begin FObservable.addObserver(TBaseObserver.Create); FObservable.addObserver(TBaseObserver.Create); FObservable.deleteObservers; Assert.AreEqual(0, FObservable.countObservers); end; {$ENDREGION} // ------------------------------------------------------------------------ // Tests Changed // ------------------------------------------------------------------------ {$REGION 'Tests Changed'} procedure TObervableTests.TestChanged_InitialNotChanged; begin Assert.IsFalse(FObservable.hasChanged); end; procedure TObervableTests.TestChanged_SetChanged; begin FObservable.setChanged; Assert.IsTrue(FObservable.hasChanged); end; procedure TObervableTests.TestChanged_SetAndClearChanged; begin FObservable.setChanged; FObservable.clearChanged; Assert.IsFalse(FObservable.hasChanged); end; {$ENDREGION} // ------------------------------------------------------------------------ // Tests NotifyObservers // ------------------------------------------------------------------------ {$REGION 'Tests NotifyObservers'} procedure TObervableTests.TestNotify_OneObserver; var o1: TBaseObserver; begin o1 := TBaseObserver.Create; FObservable.addObserver(o1); FObservable.setChanged; FObservable.notifyObservers; Assert.IsTrue(o1.IsUpdated); end; procedure TObervableTests.TestNotify_NotNotifedWithoutSetChanged; var o1: TBaseObserver; begin o1 := TBaseObserver.Create; FObservable.addObserver(o1); FObservable.notifyObservers; Assert.IsFalse(o1.IsUpdated); end; procedure TObervableTests.TestNotify_NotNotifedAfterSetAndClearChanged; var o1: TBaseObserver; begin o1 := TBaseObserver.Create; FObservable.addObserver(o1); FObservable.setChanged; FObservable.clearChanged; FObservable.notifyObservers; Assert.IsFalse(o1.IsUpdated); end; {$ENDREGION} // ------------------------------------------------------------------------ initialization TDUnitX.RegisterTestFixture(TObervableTests); end.
unit MFichas.View.Dialog.ConfirmarProduto; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Graphics, FMX.Controls, FMX.Forms, FMX.Dialogs, FMX.StdCtrls, FMX.Edit, FMX.Objects, FMX.Controls.Presentation, FMX.Layouts; type TFrameConfirmacaoProduto = class(TFrame) LayoutPrincipal: TLayout; RectangleSombra: TRectangle; RectanglePrincipal: TRectangle; LayoutRectangleTop: TLayout; LabelTitulo: TLabel; LayoutRectangleClient: TLayout; LayoutRectangleBottom: TLayout; LayoutDireita: TLayout; RoundRectBotaoConfirmar: TRoundRect; LabelBotaoConfirmar: TLabel; LayoutEsquerda: TLayout; RoundRectBotaoCancelar: TRoundRect; LabelBotaoCancelar: TLabel; Layout1: TLayout; Layout2: TLayout; Layout3: TLayout; Layout4: TLayout; Image1: TImage; Layout5: TLayout; Layout6: TLayout; Image2: TImage; Layout7: TLayout; Layout8: TLayout; EditQuantidade: TEdit; Layout9: TLayout; Label1: TLabel; LabelValorProduto: TLabel; LabelDescricaoProduto: TLabel; procedure Image2Click(Sender: TObject); procedure Image1Click(Sender: TObject); private FValorOriginalDoProduto: String; procedure SetValorOriginalDoProduto(const Value: String); function ValorDoProdutoxQuantidade(AQuantidade: Integer): String; { Private declarations } public { Public declarations } property ValorOriginalDoProduto: String read FValorOriginalDoProduto write SetValorOriginalDoProduto; procedure ConfigurarTamanhoDoModal(AParent: TForm); end; implementation {$R *.fmx} procedure TFrameConfirmacaoProduto.ConfigurarTamanhoDoModal(AParent: TForm); begin Self.Align := TAlignLayout.Contents; Self.Visible := False; Self.Parent := AParent; Self.RectanglePrincipal.Margins.Top := AParent.Height / 3.8; Self.RectanglePrincipal.Margins.Bottom := AParent.Height / 3.8; Self.RectanglePrincipal.Margins.Left := AParent.Width / 10; Self.RectanglePrincipal.Margins.Right := AParent.Width / 10; Self.Visible := True; end; procedure TFrameConfirmacaoProduto.Image1Click(Sender: TObject); var LQuantidadeItem: Integer; begin LQuantidadeItem := StrToInt(EditQuantidade.Text); if LQuantidadeItem > 1 then begin LQuantidadeItem := StrToInt(EditQuantidade.Text) - 1; EditQuantidade.Text := IntToStr(LQuantidadeItem); end; LabelValorProduto.Text := ValorDoProdutoxQuantidade(LQuantidadeItem); end; procedure TFrameConfirmacaoProduto.Image2Click(Sender: TObject); var LQuantidadeItem: Integer; begin LQuantidadeItem := StrToInt(EditQuantidade.Text); if LQuantidadeItem < 99 then begin LQuantidadeItem := StrToInt(EditQuantidade.Text) + 1; EditQuantidade.Text := IntToStr(LQuantidadeItem); end; LabelValorProduto.Text := ValorDoProdutoxQuantidade(LQuantidadeItem); end; procedure TFrameConfirmacaoProduto.SetValorOriginalDoProduto(const Value: String); begin FValorOriginalDoProduto := Value; end; function TFrameConfirmacaoProduto.ValorDoProdutoxQuantidade( AQuantidade: Integer): String; begin Result := FormatCurr( '#,##0.00', (AQuantidade * StrToFloat(FValorOriginalDoProduto)) ); end; end.
unit msmBaseModelElement; // Модуль: "w:\common\components\gui\Garant\msm\msmBaseModelElement.pas" // Стереотип: "SimpleClass" // Элемент модели: "TmsmBaseModelElement" MUID: (57AB17E6022C) {$Include w:\common\components\msm.inc} interface uses l3IntfUses , l3CProtoObject , msmModelElements {$If NOT Defined(NoScripts)} , tfwDictionaryEx {$IfEnd} // NOT Defined(NoScripts) {$If NOT Defined(NoScripts)} , tfwScriptingInterfaces {$IfEnd} // NOT Defined(NoScripts) , l3Interfaces ; type TmsmBaseModelElement = {abstract} class(Tl3CProtoObject, ImsmBaseModelElement) private f_Name: Il3CString; f_Dictionary: TtfwDictionaryEx; f_MainWord: TtfwWord; protected function Get_Name: Il3CString; function Get_UID: Il3CString; procedure Cleanup; override; {* Функция очистки полей объекта. } procedure ClearFields; override; public constructor Create(aMainWord: TtfwWord); reintroduce; public property Dictionary: TtfwDictionaryEx read f_Dictionary; property MainWord: TtfwWord read f_MainWord; end;//TmsmBaseModelElement implementation uses l3ImplUses , msmModelElementMethodCaller //#UC START# *57AB17E6022Cimpl_uses* , SysUtils , l3InterfacesMisc //#UC END# *57AB17E6022Cimpl_uses* ; constructor TmsmBaseModelElement.Create(aMainWord: TtfwWord); //#UC START# *57AA08D80358_57AB17E6022C_var* var l_KW : TtfwKeyWord; //#UC END# *57AA08D80358_57AB17E6022C_var* begin //#UC START# *57AA08D80358_57AB17E6022C_impl* inherited Create; aMainWord.SetRefTo(f_MainWord); l_KW := f_MainWord.Key As TtfwKeyWord; if (l_KW = nil) then begin // - возможно это UP (IsSummoned) трансформированное в переменную f_Dictionary := nil; Assert(false, 'Элемент без словаря'); end//l_KW = nil else if (l_KW.Dictionary Is TtfwDictionaryEx) then (l_KW.Dictionary As TtfwDictionaryEx).SetRefTo(f_Dictionary) else f_Dictionary := nil; //#UC END# *57AA08D80358_57AB17E6022C_impl* end;//TmsmBaseModelElement.Create function TmsmBaseModelElement.Get_Name: Il3CString; //#UC START# *57A9FE9400E7_57AB17E6022Cget_var* //#UC END# *57A9FE9400E7_57AB17E6022Cget_var* begin //#UC START# *57A9FE9400E7_57AB17E6022Cget_impl* if (f_Name = nil) then f_Name := TmsmModelElementMethodCaller.CallAndGetString(f_MainWord, 'NameInModel'); Result := f_Name; //#UC END# *57A9FE9400E7_57AB17E6022Cget_impl* end;//TmsmBaseModelElement.Get_Name function TmsmBaseModelElement.Get_UID: Il3CString; //#UC START# *57AADF560165_57AB17E6022Cget_var* //#UC END# *57AADF560165_57AB17E6022Cget_var* begin //#UC START# *57AADF560165_57AB17E6022Cget_impl* Result := TmsmModelElementMethodCaller.CallAndGetString(f_MainWord, 'UID'); //#UC END# *57AADF560165_57AB17E6022Cget_impl* end;//TmsmBaseModelElement.Get_UID procedure TmsmBaseModelElement.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_57AB17E6022C_var* //#UC END# *479731C50290_57AB17E6022C_var* begin //#UC START# *479731C50290_57AB17E6022C_impl* FreeAndNil(f_Dictionary); FreeAndNil(f_MainWord); inherited; //#UC END# *479731C50290_57AB17E6022C_impl* end;//TmsmBaseModelElement.Cleanup procedure TmsmBaseModelElement.ClearFields; begin f_Name := nil; inherited; end;//TmsmBaseModelElement.ClearFields end.
unit ValidateSessionResponseUnit; interface uses REST.Json.Types, GenericParametersUnit; type TValidateSessionResponse = class(TGenericParameters) private [JSONName('authenticated')] FAuthenticated: boolean; [JSONName('member_id')] FMemberId: integer; public property Authenticated: boolean read FAuthenticated write FAuthenticated; property MemberId: integer read FMemberId write FMemberId; end; implementation end.
unit SelectInstallFolder; interface uses Windows, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, FileCtrl; type TProductType = (ptUnknown, ptDesktop, ptMobile, ptNetware, ptWorking, ptClient, ptSuperMobile); TSelectInstallFolderForm = class(TForm) f_BackgroundFormImage: TImage; f_BottomBevel: TBevel; f_CancelButton: TButton; f_ContinueButton: TButton; f_ImagePanel: TPanel; f_PanelImage: TImage; f_MainPanel: TPanel; f_FolderEdit: TEdit; f_MainPanelFirstLabel: TLabel; f_MainPanelSecondLabel: TLabel; f_ResetDefaultFolderButton: TButton; f_SelectInstallFolderButton: TButton; f_SelectInstallFolderFormLabel: TLabel; // procedure FormCreate(a_Sender: TObject); procedure FormCloseQuery(a_Sender: TObject; var a_CanClose: Boolean); // procedure ResetDefaultFolderButtonClick(a_Sender: TObject); procedure SelectInstallFolderButtonClick(a_Sender: TObject); private f_DefaultPath: string; f_ExecuteRoot: string; f_ProductType: TProductType; f_RequiredSize: Int64; // procedure OnShowNotifyEvent(a_Sender: TObject); // procedure pm_SetDefaultPath(const a_Value: string); function pm_GetInstallPath: string; procedure pm_SetProductType(const a_Value: TProductType); public property DefaultPath: string read f_DefaultPath write pm_SetDefaultPath; property ExecuteRoot: string read f_ExecuteRoot write f_ExecuteRoot; property InstallPath: string read pm_GetInstallPath; property ProductType: TProductType read f_ProductType write pm_SetProductType; property RequiredSize: Int64 read f_RequiredSize write f_RequiredSize; end; var SelectInstallFolderForm: TSelectInstallFolderForm; implementation {$R *.DFM} uses SysUtils , LocaleMessages ; procedure TSelectInstallFolderForm.FormCreate(a_Sender: TObject); begin f_MainPanelSecondLabel.Caption := GetCurrentLocaleMessage(c_GarantSelectInstallFolderFormMainPanelSecondLabelCaption); f_SelectInstallFolderFormLabel.Caption := GetCurrentLocaleMessage(c_GarantSelectInstallFolderFormSelectInstallFolderFormLabelCaption); // f_ResetDefaultFolderButton.Caption := GetCurrentLocaleMessage(c_GarantSelectInstallFolderFormResetDefaultFolderButtonCaption); f_SelectInstallFolderButton.Caption := GetCurrentLocaleMessage(c_GarantSelectInstallFolderFormSelectInstallFolderButtonCaption); // f_CancelButton.Caption := GetCurrentLocaleMessage(c_GarantSelectInstallFolderFormCancelButtonCaption); f_ContinueButton.Caption := GetCurrentLocaleMessage(c_GarantSelectInstallFolderFormContinueButtonCaption); // Caption := Application.Title; // ExecuteRoot := ''; // ProductType := ptUnknown; RequiredSize := 0; // OnShow := OnShowNotifyEvent; end; procedure TSelectInstallFolderForm.FormCloseQuery(a_Sender: TObject; var a_CanClose: Boolean); // function CheckFreeSpace(const a_Directory: string; const a_RequiredSize: Int64): Boolean; // function GetFreeSize(const a_Directory: string): Int64; type TGetDiskFreeSpaceEx = function ( a_Directory: PChar ; a_FreeBytesAvailableToCaller: PULargeInteger ; a_TotalNumberOfBytes: PULargeInteger ; a_TotalNumberOfFreeBytes: PULargeInteger ): BOOL; stdcall; var l_Directory: string; l_Length: Integer; // l_GetDiskFreeSpaceEx: TGetDiskFreeSpaceEx; l_Kernel32ModuleHandle: THandle; // l_FreeBytesAvailableToCaller: TULargeInteger; l_TotalNumberOfBytes: TULargeInteger; l_TotalNumberOfFreeBytes: TULargeInteger; // l_BytesPerSector: DWORD; l_NumberOfFreeClusters: DWORD; l_SectorsPerCluster: DWORD; l_TotalNumberOfClusters: DWORD; begin @l_GetDiskFreeSpaceEx := nil; // l_Kernel32ModuleHandle := GetModuleHandle('kernel32.dll'); if (l_Kernel32ModuleHandle <> THandle(0)) then @l_GetDiskFreeSpaceEx := GetProcAddress(l_Kernel32ModuleHandle, 'GetDiskFreeSpaceExA'); // l_Length := Length(a_Directory); if ((l_Length <> 0) and (a_Directory [l_Length] <> '\')) then l_Directory := Format('%s\', [a_Directory]) else l_Directory := a_Directory; // if (@l_GetDiskFreeSpaceEx <> nil) then begin Win32Check(l_GetDiskFreeSpaceEx(PChar(l_Directory), @l_FreeBytesAvailableToCaller, @l_TotalNumberOfBytes, @l_TotalNumberOfFreeBytes)); Result := Int64(l_FreeBytesAvailableToCaller.QuadPart); end else begin Win32Check(GetDiskFreeSpace(PChar(Format('%s\', [ExtractFileDrive(l_Directory)])), l_SectorsPerCluster, l_BytesPerSector, l_NumberOfFreeClusters, l_TotalNumberOfClusters)); Result := Int64(l_SectorsPerCluster*l_BytesPerSector*l_NumberOfFreeClusters); end; end; // var l_FreeSize: Int64; begin l_FreeSize := GetFreeSize(a_Directory); // if (((l_FreeSize < 0) and (a_RequiredSize >= 0)) or ((l_FreeSize >= 0) and (a_RequiredSize < 0))) then Result := (l_FreeSize <= a_RequiredSize) else Result := (l_FreeSize >= a_RequiredSize); end; // function IsDirectoryReadOnly(const a_Directory: string): Boolean; var l_Directory: string; l_Length: Integer; begin l_Directory := a_Directory; l_Length := Length(l_Directory); if ((l_Length > 0) and (l_Directory[l_Length] = '\')) then SetLength(l_Directory, Pred(l_Length)); // Result := False; try Win32Check(CloseHandle(CreateFile(PChar(Format('%s\{A3D11BA5-A77C-4352-9508-F485FE04F328}', [l_Directory])), GENERIC_WRITE, DWORD(0), PSecurityAttributes(nil), CREATE_ALWAYS, FILE_ATTRIBUTE_HIDDEN or FILE_FLAG_DELETE_ON_CLOSE, THandle(0)))); except Result := True; end; end; // var l_Directory: string; begin if (ModalResult <> mrCancel) then begin l_Directory := f_FolderEdit.Text; // if ((ExecuteRoot <> '') and (Pos(Format('%s\', [AnsiUpperCase(ExecuteRoot)]), Format('%s\', [AnsiUpperCase(l_Directory)])) <> 0)) then begin a_CanClose := False; // MessageBox(Handle, PChar(GetCurrentLocaleMessage(c_GarantSelectInstallFolderFormUnableSelectFolder)), PChar(Application.Title), MB_OK+MB_ICONERROR); end else if not(DirectoryExists(l_Directory)) and not(ForceDirectories(l_Directory)) then begin a_CanClose := False; // MessageBox(Handle, PChar(GetCurrentLocaleMessage(c_GarantSelectInstallFolderFormUnableCreateFolder)), PChar(Application.Title), MB_OK+MB_ICONERROR); end else if IsDirectoryReadOnly(l_Directory) then begin a_CanClose := False; // MessageBox(Handle, PChar(GetCurrentLocaleMessage(c_GarantSelectInstallFolderFormUnwritableFolder)), PChar(Application.Title), MB_OK+MB_ICONERROR); end else if ((RequiredSize <> 0) and not(CheckFreeSpace(l_Directory, RequiredSize))) then begin a_CanClose := False; // MessageBox(Handle, PChar(GetCurrentLocaleMessage(c_GarantSelectInstallFolderFormNotEnoughFreeSpaceInFolder)), PChar(Application.Title), MB_OK+MB_ICONERROR); end; end; end; procedure TSelectInstallFolderForm.ResetDefaultFolderButtonClick(a_Sender: TObject); begin f_FolderEdit.Text := DefaultPath; end; procedure TSelectInstallFolderForm.SelectInstallFolderButtonClick(a_Sender: TObject); var l_Directory: string; // l_DefaultTail: string; l_CurrentTail: string; begin if SelectDirectory(f_MainPanelSecondLabel.Caption, '', l_Directory) then begin l_DefaultTail := ExtractFileName(f_DefaultPath); l_CurrentTail := ExtractFileName(l_Directory); // if (AnsiUpperCase(l_DefaultTail) <> AnsiUpperCase(l_CurrentTail)) then l_Directory := Format('%s\%s', [l_Directory, l_DefaultTail]); // f_FolderEdit.Text := l_Directory; end; end; procedure TSelectInstallFolderForm.OnShowNotifyEvent(a_Sender: TObject); begin SetWindowLong(Handle, GWL_EXSTYLE, GetWindowLong(Handle, GWL_EXSTYLE) or WS_EX_APPWINDOW and not(WS_EX_TOOLWINDOW)); end; procedure TSelectInstallFolderForm.pm_SetDefaultPath(const a_Value: string); begin f_DefaultPath := a_Value; ResetDefaultFolderButtonClick(nil); end; function TSelectInstallFolderForm.pm_GetInstallPath: string; begin Result := f_FolderEdit.Text; end; procedure TSelectInstallFolderForm.pm_SetProductType(const a_Value: TProductType); begin f_ProductType := a_Value; // with f_MainPanelFirstLabel do case a_Value of ptClient: Caption := GetCurrentLocaleMessage(c_GarantSelectInstallFolderFormFirstRunClientProduct); ptDesktop: Caption := GetCurrentLocaleMessage(c_GarantSelectInstallFolderFormFirstRunDesktopProduct); ptMobile: Caption := GetCurrentLocaleMessage(c_GarantSelectInstallFolderFormFirstRunMobileProduct); ptNetware: Caption := GetCurrentLocaleMessage(c_GarantSelectInstallFolderFormFirstRunNetwareProduct); ptWorking: Caption := GetCurrentLocaleMessage(c_GarantSelectInstallFolderFormFirstRunWorkingProduct); ptSuperMobile: Caption := GetCurrentLocaleMessage(c_GarantSelectInstallFolderFormFirstRunSuperMobileProduct); else Caption := GetCurrentLocaleMessage(c_GarantSelectInstallFolderFormFirstRunUnknownProduct); end; end; end.
{ DBAExplorer - Oracle Admin Management Tool Copyright (C) 2008 Alpaslan KILICKAYA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. } unit OraSynonym; interface uses Classes, SysUtils, Ora, OraStorage, DB,DBQuery, Forms, Dialogs, VirtualTable; type Synonym = record Owner, SynonymName, TableOwner, TableName, DDLink: string; isPublic: boolean; end; TSynonym = ^Synonym; TSynonyms = class(TObject) private FSYNONYM_NAME, FSYNONYM_OWNER, FTABLE_OWNER, FTABLE_NAME, FDB_LINK, FOBJECT_TYPE: string; FOraSession: TOraSession; function GetStatus: string; public property SYNONYM_NAME: string read FSYNONYM_NAME write FSYNONYM_NAME; property SYNONYM_OWNER: string read FSYNONYM_OWNER write FSYNONYM_OWNER; property TABLE_OWNER: string read FTABLE_OWNER write FTABLE_OWNER; property TABLE_NAME: string read FTABLE_NAME write FTABLE_NAME; property DB_LINK: string read FDB_LINK write FDB_LINK; property OBJECT_TYPE: string read FOBJECT_TYPE write FOBJECT_TYPE; property Status: String read GetStatus; property OraSession: TOraSession read FOraSession write FOraSession; procedure SetDDL; function GetDDL: string; function DropSynonym: boolean; constructor Create; destructor Destroy; override; end; TSynonymList = class(TObject) private FSynonymList: TList; FOraSession: TOraSession; FTableOwner, FTableName: string; FObjectType: TDBFormType; FDSSynonymList: TVirtualTable; function GetSynonym(Index: Integer): TSynonym; procedure SetSynonym(Index: Integer; Synonym: TSynonym); function GetSynonymCount: Integer; public property SynonymCount: Integer read GetSynonymCount; property SynonymItems[Index: Integer]: TSynonym read GetSynonym write SetSynonym; property TableOwner: string read FTableOwner write FTableOwner; property TableName: string read FTableName write FTableName; property ObjectType: TDBFormType read FObjectType write FObjectType; property DSSynonymList: TVirtualTable read FDSSynonymList; property OraSession: TOraSession read FOraSession write FOraSession; procedure SynonymAdd(Synonym: TSynonym); procedure SynonymDelete(Index: Integer); procedure CopyFrom(SynonymList: TSynonymList); procedure SetDDL; function FindBySynonyms(SynonymName: string): integer; function GetDDL: string; function CreateSynonym(SynonymScript: string) : boolean; function DropSynonym: boolean; constructor Create; destructor Destroy; override; end; function GetSynonyms(OwnerName: string): string; function GetOraSynonyms: string; const SynonymTablePrivilege: array[1..11] of string = ('Select','Delete','Insert','Update','Alter','References','Index','OnCommitRefresh','QueryRewrite','Debug','Flashback'); implementation uses util, frmSchemaBrowser, oraScripts, Languages; resourcestring strSynonymsDrop = 'Synonym %s has been dropped.'; strSynonymsCreated = 'Synonym has been created.'; strSynonymDrop = 'Synonym %s has been dropped.'; {*************************** TSynonym ******************************************} function GetSynonyms(OwnerName: string): string; begin result := 'select OWNER, SYNONYM_NAME, TABLE_OWNER, TABLE_NAME, DB_LINK ' +' from ALL_SYNONYMS ' +' WHERE OWNER = '+Str(OwnerName) +' order by SYNONYM_NAME'; end; function GetOraSynonym: string; begin result := 'select OWNER, SYNONYM_NAME, TABLE_OWNER, TABLE_NAME, DB_LINK ' +' from ALL_SYNONYMS ' +' WHERE OWNER = :pOwner ' +' AND SYNONYM_NAME = :pName '; end; constructor TSynonyms.Create; begin end; destructor TSynonyms.Destroy; begin inherited; end; procedure TSynonyms.SetDDL; var q: TOraQuery; begin if FSYNONYM_NAME = '' then exit; q := TOraQuery.Create(nil); q.Session := FOraSession; q.SQL.Text := GetOraSynonym; q.ParamByName('pOwner').AsString := FSYNONYM_OWNER; q.ParamByName('pName').AsString := FSYNONYM_NAME; q.Open; FTABLE_OWNER := q.FieldByName('Table_OWNER').AsString; FTABLE_NAME := q.FieldByName('Table_Name').AsString; FDB_LINK := q.FieldByName('DB_LINK').AsString; q.Close; q.SQL.Text := GetObjectType; q.ParamByName('pOName').AsString := FTABLE_NAME; q.ParamByName('pOwner').AsString := FTABLE_OWNER; q.Open; FOBJECT_TYPE := q.FieldByName('OBJECT_TYPE').AsString; q.close; end; function TSynonyms.GetDDL: string; begin result := 'CREATE OR REPLACE SYNONYM '+FSYNONYM_OWNER+'.'+FSYNONYM_NAME +' FOR ' +FTABLE_OWNER+'.'+FTABLE_NAME+';'; end; function TSynonyms.GetStatus: string; var q1: TOraQuery; begin q1 := TOraQuery.Create(nil); q1.Session := OraSession; q1.SQL.Text := GetObjectStatusSQL; q1.ParamByName('pOName').AsString := FSYNONYM_NAME; q1.ParamByName('pOType').AsString := 'SYNONYM'; q1.ParamByName('pOwner').AsString := FSYNONYM_OWNER; q1.Open; result := FSYNONYM_NAME+' ( Created: '+q1.FieldByName('CREATED').AsString +' Last DDL: '+q1.FieldByName('LAST_DDL_TIME').AsString +' Status: '+q1.FieldByName('STATUS').AsString +' )'; q1.Close; end; function TSynonyms.DropSynonym: boolean; var FSQL: string; begin result := false; if FSYNONYM_NAME = '' then exit; FSQL := 'drop synonym '+FSYNONYM_OWNER+'.'+FSYNONYM_NAME; result := ExecSQL(FSQL,Format(ChangeSentence('strSynonymDrop',strSynonymDrop),[FSYNONYM_NAME]) , FOraSession); end; {************************** TSynonymList ***************************************} function GetOraSynonyms: string; begin result := 'select OWNER, SYNONYM_NAME, TABLE_OWNER, TABLE_NAME, DB_LINK ' +' from ALL_SYNONYMS ' +' WHERE TABLE_OWNER = :pOwner ' +' AND TABLE_NAME = :pTable '; end; constructor TSynonymList.Create; begin FSynonymList := TList.Create; FDSSynonymList := TVirtualTable.Create(nil); end; destructor TSynonymList.Destroy; var i : Integer; FSynonym: TSynonym; begin try if FSynonymList.Count > 0 then begin for i := FSynonymList.Count - 1 downto 0 do begin FSynonym := FSynonymList.Items[i]; Dispose(FSynonym); end; end; finally FSynonymList.Free; end; FDSSynonymList.Free; inherited; end; procedure TSynonymList.SynonymAdd(Synonym: TSynonym); begin FSynonymList.Add(Synonym); end; procedure TSynonymList.SynonymDelete(Index: Integer); var FSynonym: TSynonym; begin FSynonym := FSynonymList.Items[Index]; Dispose(FSynonym); FSynonymList.Delete(Index); end; function TSynonymList.GetSynonym(Index: Integer): TSynonym; begin Result := FSynonymList.Items[Index]; end; procedure TSynonymList.SetSynonym(Index: Integer; Synonym: TSynonym); begin if Assigned(Synonym) then FSynonymList.Items[Index] := Synonym end; function TSynonymList.GetSynonymCount: Integer; begin Result := FSynonymList.Count; end; function TSynonymList.FindBySynonyms(SynonymName: string): integer; var i: integer; begin result := -1; for i := 0 to FSynonymList.Count -1 do begin if (TSynonym(FSynonymList[i]).SynonymName = SynonymName) then begin result := i; exit; end; end; end; procedure TSynonymList.CopyFrom(SynonymList: TSynonymList); var i: integer; begin FOraSession := SynonymList.OraSession; FTableName := SynonymList.TableName; FTableOwner := SynonymList.TableOwner; for i := 0 to SynonymList.SynonymCount -1 do begin FSynonymList.Add(TSynonym(SynonymList.SynonymItems[i])); end; end; procedure TSynonymList.SetDDL; var FSynonym: TSynonym; q: TOraQuery; begin if FTableName = '' then exit; q := TOraQuery.Create(nil); q.Session := FOraSession; q.SQL.Text := GetOraSynonyms; q.ParamByName('pOwner').AsString := FTableOwner; q.ParamByName('pTable').AsString := FTableName; q.Open; CopyDataSet(q, FDSSynonymList); while not q.Eof do begin new(FSynonym); FSynonym^.Owner := q.FieldByName('OWNER').AsString; FSynonym^.SynonymName := q.FieldByName('Synonym_NAME').AsString; FSynonym^.TableOwner:= q.FieldByName('Table_OWNER').AsString; FSynonym^.TableName := q.FieldByName('Table_Name').AsString; FSynonym^.DDLink := q.FieldByName('DB_LINK').AsString; SynonymAdd(FSynonym); q.Next; end; q.Close; end; function TSynonymList.GetDDL: string; var strHeader: string; i: integer; begin with self do begin for i := 0 to GetSynonymCount -1 do begin strHeader := strHeader + 'CREATE '; if SynonymItems[i].isPublic then strHeader := strHeader + 'PUBLIC '; strHeader := strHeader + 'SYNONYM '+SynonymItems[i].Owner+'.' +SynonymItems[i].SynonymName +' FOR ' +SynonymItems[i].TableOwner+'.' +SynonymItems[i].TableName; if SynonymItems[i].DDLink <> '' then strHeader := strHeader + ' @'+SynonymItems[i].DDLink; strHeader := strHeader + ';'+ln; end; end; //with self result := strHeader; end; function TSynonymList.CreateSynonym(SynonymScript: string) : boolean; begin result := false; if FTableName = '' then exit; result := ExecSQL(SynonymScript, ChangeSentence('strSynonymsCreated', strSynonymsCreated), FOraSession); end; function TSynonymList.DropSynonym: boolean; var FSQL: string; begin result := false; if FSynonymList.Count < 0 then exit; FSQL := 'drop synonym '+TSynonym(FSynonymList[0]).Owner+'.'+TSynonym(FSynonymList[0]).SynonymName; result := ExecSQL(FSQL, Format(ChangeSentence('strSynonymsDrop',strSynonymsDrop),[TSynonym(FSynonymList[0]).SynonymName]), FOraSession); end; end.
// AKTools akLogUtils unit. // Модуль, содержащий функции по работе с логами. //============================================================================= unit akLogUtils; interface uses SysUtils, Classes; // типы журналируемых событий const LOG_ERROR = 0; LOG_WARNING = 1; LOG_INFORM = 2; LOG_SUCCESS = 3; LOG_FAILURE = 4; LOG_REPORT = 5; type TReportItem = class(TCollectionItem) private fDate: TDateTime; fDesc: string; public property RpDate: TDateTime read fDate write fDate; property RpDesc: string read fDesc write fDesc; procedure SetItem(Desc: string); end; // Коллекция строк рапорта TRepCollection = class(TCollection) protected function GetItem(Index: Integer): TReportItem; procedure SetItem(Index: Integer; const Value: TReportItem); public constructor Create; destructor Destroy; override; function Add: TReportItem; function FindItemID(ID: Integer): TReportItem; function Insert(Index: Integer): TReportItem; property Items[Index: Integer]: TReportItem read GetItem write SetItem; default; end; // Класс для работы с файловыми логами. // Рекомендуется создавать при старте программы и удалять по выходу из нее. TFileLog = class(TObject) private fName: string; fLineTimeFmt: string; fLineSep: string; fDateLineFormat: string; fAttribChars: string; fCreateLineFmt: string; fRunAppMessage: string; fRecentlyRun: Boolean; fPrevDate: TDateTime; fLogDisabled: Boolean; function MakeLogStr(wType: Integer; Desc: string): string; protected procedure AfterCreate; public constructor Create(fn: string); destructor Destroy; override; procedure ReportEvent(wType: Integer; Desc: string); procedure ReportEventFmt(wType: Integer; Desc: string; arr: array of const); procedure GetReportLines(lines: TRepCollection); property LogDisabled: Boolean read fLogDisabled write fLogDisabled; published property CreateLineFormat: string read fCreateLineFmt write fCreateLineFmt; property ShortTimeFormat: string read fLineTimeFmt write fLineTimeFmt; property LineSep: string read fLineSep write fLineSep; property DateLineFormat: string read fDateLineFormat write fDateLineFormat; property AttribChars: string read fAttribChars write fAttribChars; property RunAppMessage: string read fRunAppMessage write fRunAppMessage; end; procedure LogClearTimer(); procedure AddLineToLog(fn, str: string; benchmark:integer=0); implementation uses windows, akFileUtils; var benchmark_timer:DWORD; procedure LogClearTimer(); begin benchmark_timer := GetTickCount; end; procedure AddLineToLog(fn, str: string; benchmark:integer); var f: TextFile; duration: DWORD; display: boolean; begin if benchmark_timer = 0 then LogClearTimer(); duration := GetTickCount - benchmark_timer; if (benchmark>0) then begin display := duration>benchmark; end else display := true; benchmark_timer := GetTickCount; if not display then exit; CreateFileIfNotExists(fn); AssignFile(f, fn); try Append(f); if (benchmark>0) then Write(f, duration: 5, '] '); Write(f, DateTimeToStr(Now): 20, ' ', str); Writeln(f); finally Closefile(f); end; end; //============================================================================== //****************************************************************************** // TFileLog //****************************************************************************** //============================================================================== procedure TFileLog.AfterCreate; begin ReportEvent(0, ''); end; constructor TFileLog.Create(fn: string); var dir: string; begin fLogDisabled := false; CreateLineFormat := ' hh:mm | ======================[ dd.mmmm.yyyy ]===================='; DateLineFormat := ' hh:mm | --------------------- [ dd.mmmm.yyyy ] -------------------'; ShortTimeFormat := ' hh:mm'; RunAppMessage := ' ########## Application started ##########'; LineSep := ' | '; AttribChars := '!* >! '; GetDir(0, dir); fRecentlyRun := True; fName := CompletePath(fn, dir); // AfterCreate; end; destructor TFileLog.Destroy; begin inherited; end; procedure TFileLog.GetReportLines(lines: TRepCollection); var f: TextFile; ln: string; repps: Integer; ritem: TReportItem; RepSt: string; RepStLen: Integer; begin try lines.Clear; if not FileExists(fName) then exit; AssignFile(f, fName); Reset(f); while not EOF(f) do begin Readln(f, ln); RepSt := LineSep + '<REP '; RepStLen := Length(RepSt); repps := Pos(RepSt, ln); if (repps <> 0) and (repps < 20) then begin ritem := lines.Add; ritem.RpDate := StrToDateTime(Copy(ln, repps + RepStLen, Pos('>', ln) - repps - RepStLen)); ritem.RpDesc := Copy(ln, Pos('>', ln) + 1, MaxInt); end; end; CloseFile(f); except {} end; end; function TFileLog.MakeLogStr(wType: Integer; Desc: string): string; var rp, dt: string; begin Result := ''; if Desc = '' then Exit; if Date <> fPrevDate then begin Result := FormatDateTime(DateLineFormat, Now) + #13#10; end; dt := FormatDateTime(ShortTimeFormat, Now); if wType = LOG_REPORT then rp := '<REP ' + DateTimeToStr(Now) + '> ' else rp := ''; Result := Result + Copy(AttribChars, wType + 1, 1) + dt + LineSep + rp + Desc; fPrevDate := Date; end; procedure TFileLog.ReportEvent(wType: Integer; Desc: string); var f: TextFile; begin if LogDisabled then exit; try AssignFile(f, fName); if FileExists(fName) then Append(f) else begin Rewrite(f); fPrevDate := Date; Writeln(f, FormatDateTime(CreateLineFormat, Now)); end; Writeln(f, MakeLogStr(wType, Desc)); if fRecentlyRun then begin Writeln(f, MakeLogStr(LOG_INFORM, '')); Writeln(f, MakeLogStr(LOG_INFORM, RunAppMessage)); fRecentlyRun := False; end; CloseFile(f); except {} end; end; procedure TFileLog.ReportEventFmt(wType: Integer; Desc: string; arr: array of const); begin ReportEvent(wType, Format(Desc, Arr)); end; //============================================================================== //****************************************************************************** // TReportItem //****************************************************************************** //============================================================================== procedure TReportItem.SetItem(Desc: string); begin fDate := Now; fDesc := Desc; end; { TRepCollection } function TRepCollection.Add: TReportItem; begin Result := TReportItem(inherited Add); end; constructor TRepCollection.Create; begin inherited Create(TReportItem); end; destructor TRepCollection.Destroy; begin inherited; end; function TRepCollection.FindItemID(ID: Integer): TReportItem; begin Result := TReportItem(inherited FindItemID(ID)); end; function TRepCollection.GetItem(Index: Integer): TReportItem; begin Result := TReportItem(inherited GetItem(Index)); end; function TRepCollection.Insert(Index: Integer): TReportItem; begin Result := TReportItem(inherited Insert(Index)); end; procedure TRepCollection.SetItem(Index: Integer; const Value: TReportItem); begin inherited SetItem(Index, Value); end; initialization benchmark_timer := 0; end.
unit uRemoteDM; interface uses System.SysUtils, System.Classes, System.Types, ufmMain, uUtils, fib, FIBDatabase, pFIBDatabase, pFIBSQLLog, SIBEABase, SIBFIBEA, FIBSQLMonitor, pFIBErrorHandler, Data.DB, FIBDataSet, Forms, pFIBDataSet, FIBQuery, pFIBQuery, RegularExpressions, ZInterbaseAnalyser, ZInterbaseToken, ZSelectSchema, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, IdNetworkCalculator, System.Variants, IdCustomTransparentProxy, IdSocks, IdStack, IdIPWatch, IdIPAddrMon, IdRawBase, IdRawClient, IdIcmpClient, Winsock, Dialogs, uDMConfig, fileinfo; type TTableFieldInfo = class(TObject) private public isNullable: boolean; Description: string; ID: word; Position: word; Name: string; Table: string; end; type TRemoteDataModule = class(TDataModule) FIBDatabase: TpFIBDatabase; FIBTransaction: TpFIBTransaction; FIBUpdateTransaction: TpFIBTransaction; FibErrorHandler: TpFibErrorHandler; FIBSQLMonitor: TFIBSQLMonitor; FIBEventAlerter: TSIBfibEventAlerter; FIBSQLLogger: TFIBSQLLogger; TableListDataSet: TpFIBDataSet; TableListDataSetTABLE_NAME: TFIBWideStringField; MenuTreeDataSet: TpFIBDataSet; MenuTreeDataSource: TDataSource; MenuTreeDataSetID: TFIBBCDField; MenuTreeDataSetCAPTION: TFIBWideStringField; MenuTreeDataSetSUB_ID: TFIBBCDField; MenuTreeDataSetGLYPH_ID: TFIBSmallIntField; MenuTreeDataSetCLASS_NAME: TFIBWideStringField; GlobalConfigurationDataSet: TpFIBDataSet; GlobalConfigurationDataSetID: TFIBBCDField; GlobalConfigurationDataSetKEY_NAME: TFIBWideStringField; GlobalConfigurationDataSetVALUE_DATA: TFIBMemoField; EventsListDataSet: TpFIBDataSet; EventsListDataSetID: TFIBBCDField; EventsListDataSetEVENT_NAME: TFIBWideStringField; procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); procedure FibErrorHandlerFIBErrorEvent(Sender: TObject; ErrorValue: EFIBError; KindIBError: TKindIBError; var DoRaise: Boolean); procedure FIBSQLMonitorSQL(EventText: string; EventTime: TDateTime); procedure FIBEventAlerterEventAlert(Sender: TObject; EventName: string; EventCount: Integer); published function getDatabase: TpFIBDatabase; function getTransaction: TpFIBTransaction; private FDataSetList: TList; FTablesList: TStringList; public function ConnectDataBase: boolean; function getFieldInfo(const ATable: string; AField: string; AType: string = 'FIELD_DESCRIPTION') : string; function getFields(const ATable: string) : string; function getFieldsList(const ATable: string) : TStringList; function createDataSet: TpFIBDataSet; function createQuery: TpFIBQuery; function createTransaction: TpFIBTransaction; function registerDataSet(const ADataSet: TpFIBDataSet): boolean; function unregisterDataSet(const ADataSet: TpFIBDataSet): boolean; function notifyDataSets(const ATableName: string): boolean; function generateGroups(const ATable: string): boolean; function preloadTablesData: boolean; function subscribeEvents: boolean; function FindDatabaseServer(AHost: string = 'localhost'; APort: Word = 3050; ATimeOut: Word = 100): string; function tryLocalDatabaseServer: boolean; function getGlobalConfigData(AKeyName: string): variant; function checkDataBaseVersion: boolean; end; var RemoteDataModule: TRemoteDataModule; const DBPort: Word = 3050; const DBHost: String = 'localhost'; const DBUser: String = 'SYSDBA'; const DBPassword: String = 'masterkey'; const DBLocation: string = 'C:\db\notar.fdb'; const DBCharset: string = 'UTF8'; const MainDataBaseFile: string = 'notar.fdb'; const MainDataBaseLocationDrives: array[0..23] of string = ( 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ); const MainDataBaseLocations: array[0..3] of string = ( 'db', 'db\notar', 'data\notar', 'Program Files\Notar\data' ); implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} { TRemoteDataModule } function TRemoteDataModule.FindDatabaseServer(AHost: string; APort: Word; ATimeOut: Word): string; var I, I2: Integer; IdTCPClient: TIdTCPClient; IdIPAddrMon: TIdIPAddrMon; IdNetworkCalculator: TIdNetworkCalculator; begin Result := AHost; IdTCPClient := TIdTCPClient.Create(Self); IdTCPClient.ConnectTimeout := ATimeout; IdTCPClient.ReadTimeout := ATimeout; IdTCPClient.Host := AHost; IdTCPClient.Port := APort; try IdTCPClient.Connect; except end; if IdTCPClient.Connected then begin Result := AHost; IdTCPClient.Disconnect; IdTCPClient.Free; Exit; end else begin //not connected end; IdNetworkCalculator := TIdNetworkCalculator.Create(Self); IdNetworkCalculator.NetworkMaskLength := 24; IdIPAddrMon := TIdIPAddrMon.Create(Self); IdIPAddrMon.ForceCheck; for I := 0 to IdIPAddrMon.IPAddresses.Count -1 do begin IdNetworkCalculator.NetworkAddress.AsString := IdIPAddrMon.IPAddresses[I]; for I2 := 0 to IdNetworkCalculator.ListIP.Count -1 do begin IdTCPClient.Host := IdNetworkCalculator.ListIP[I2]; try IdTCPClient.Connect; except end; if IdTCPClient.Connected then begin Result := IdNetworkCalculator.ListIP[I2]; IdTCPClient.Disconnect; Exit; end else begin //not connected end; Application.ProcessMessages; end; end; IdTCPClient.Free; IdIPAddrMon.Free; IdNetworkCalculator.Free; end; function TRemoteDataModule.checkDataBaseVersion: boolean; var V1, V2, V3, V4: Word; FileVersion: String; DBVersion: String; begin GetBuildInfo(V1, V2, V3, V4); FileVersion := Format('%s.%s.%s.%s', [IntToStr(V1), IntToStr(V2), IntToStr(V3), IntToStr(V4)]); DBVersion := VarToStr(getGlobalConfigData('DB_VERSION')); Result := FileVersion = DBVersion; end; function TRemoteDataModule.ConnectDataBase: boolean; var I, I2: Word; DBServer: string; DBLocation: string; DBDrive: string; isConnected: boolean; begin try if tryLocalDatabaseServer then begin Result := True; FIBUpdateTransaction.Active:= True; FIBTransaction.Active:= True; TableListDataSet.Open; MenuTreeDataSet.Open; Exit; end; DBServer := FindDatabaseServer(DBHost, DBPort); isConnected := False; TfmMain(Application.MainForm).Log('Database @ ' + DBServer); for I := Low(MainDataBaseLocationDrives) to High(MainDataBaseLocationDrives) do begin if isConnected then break; for I2 := Low(MainDataBaseLocations) to High(MainDataBaseLocations) do begin DBDrive := MainDataBaseLocationDrives[I]; DBLocation := MainDataBaseLocations[I2]; FIBDatabase.Close; FIBDatabase.DBName := Format('%s/%s:%s:\%s\%s', [DBServer, IntToStr(DBPort), DBDrive, DBLocation, MainDataBaseFile]); try FIBDatabase.Open; except TfmMain(Application.MainForm).Log('Database file @ ' + FIBDatabase.DBName + ' is not found'); end; if FIBDatabase.Connected then begin FIBDatabase.AutoReconnect := True; isConnected := True; Config.WriteString('Database', 'Host', DBServer); Config.WriteInteger('Database', 'Port', DBPort); Config.WriteString('Database', 'Location', Format('%s:\%s\%s', [DBDrive, DBLocation, MainDataBaseFile])); Config.UpdateFile; break; end; end; end; TfmMain(Application.MainForm).Log('DSN: ' + FIBDatabase.DBName); FIBUpdateTransaction.Active:= True; FIBTransaction.Active:= True; TableListDataSet.Open; MenuTreeDataSet.Open; finally Result := FIBDatabase.Connected; end; end; function TRemoteDataModule.createDataSet: TpFIBDataSet; var DataSet: TpFIBDataSet; begin DataSet := TpFIBDataSet.Create(self); DataSet.Database := FIBDatabase; DataSet.Transaction := FIBTransaction; DataSet.UpdateTransaction := FIBUpdateTransaction; DataSet.Close; registerDataSet(DataSet); Result := DataSet; end; function TRemoteDataModule.createQuery: TpFIBQuery; var DataSet: TpFIBQuery; begin DataSet := TpFIBQuery.Create(self); DataSet.Database := FIBDatabase; DataSet.Transaction := FIBTransaction; DataSet.Close; Result := DataSet; end; function TRemoteDataModule.createTransaction: TpFIBTransaction; var Transaction: TpFIBTransaction; begin Transaction := TpFIBTransaction.Create(self); Transaction.DefaultDatabase := FIBDatabase; Result := Transaction; end; procedure TRemoteDataModule.DataModuleCreate(Sender: TObject); begin FIBDatabase.Close; FDataSetList := TList.Create; FTablesList := TStringList.Create; end; procedure TRemoteDataModule.DataModuleDestroy(Sender: TObject); var DataSetItem: Pointer; iTablesList: word; iFieldsList: word; begin { if FDataSetList.Count >0 then begin for DataSetItem in FDataSetList do begin try if not Assigned(ValidateObj(DataSetItem)) then begin unregisterDataSet(DataSetItem); Continue; end; TpFIBDataSet(DataSetItem).Close; except unregisterDataSet(DataSetItem); end; end; end; } if FDataSetList.Count >0 then begin for DataSetItem in FDataSetList do begin try unregisterDataSet(DataSetItem); TpFIBDataSet(DataSetItem).Close; except end; end; end; if FTablesList.Count >0 then begin for iTablesList := 0 to FTablesList.Count -1 do begin for iFieldsList := 0 to TStringList(FTablesList.Objects[iTablesList]).Count -1 do begin try TTableFieldInfo(TStringList(FTablesList.Objects[iTablesList]).Objects[iFieldsList]).Free; except end; end; try TStringList(FTablesList.Objects[iTablesList]).Free; except end; end; end; FDataSetList.Free; FTablesList.Free; FIBDatabase.Close; end; procedure TRemoteDataModule.FibErrorHandlerFIBErrorEvent(Sender: TObject; ErrorValue: EFIBError; KindIBError: TKindIBError; var DoRaise: Boolean); begin Log(ErrorValue.Msg); Log(ErrorValue.CustomMessage); Log(ErrorValue.IBMessage); Log(ErrorValue.SQLMessage); Log(ErrorValue.RaiserName); end; procedure TRemoteDataModule.FIBEventAlerterEventAlert(Sender: TObject; EventName: string; EventCount: Integer); var TableName: string; begin TfmMain(Application.MainForm).Log('Received event: ' + EventName); if AnsiPos('UPDATE_', EventName) >0 then begin TableName := EventName; Delete(TableName, 1, 7); notifyDataSets(TableName); end; end; procedure TRemoteDataModule.FIBSQLMonitorSQL(EventText: string; EventTime: TDateTime); var tmpStr: string; tableName: string; regex: TRegEx; mc: TMatchCollection; begin log(EventText); regex := TRegEx.Create('\s\s'); tmpStr := regex.Replace(EventText, '[\n\r\t]', ' '); mc := regex.Matches(tmpStr, '\[Execute\]\s(.*?)$', [roMultiLine, roExplicitCapture]); if mc.Count > 0 then begin tmpStr := mc.Item[0].Value; tmpStr := regex.Replace(tmpStr, '\[Execute\]\s', ''); tmpStr := regex.Replace(tmpStr, '^\s', ''); tmpStr := regex.Replace(tmpStr, '\s$', ''); while regex.IsMatch(tmpStr) do tmpStr := regex.Replace(tmpStr, '\s\s', ' '); tmpStr := UpperCase(tmpStr); //INSERT INTO TABLE_NAME if Pos('INSERT', tmpStr) = 1 then begin tmpStr := regex.Replace(tmpStr, '^INSERT\sINTO\s', ''); tableName := Copy(tmpStr, 1, Pos('(', tmpStr) -1); notifyDataSets(tableName); end; //UPDATE TABLE_NAME if Pos('UPDATE', tmpStr) = 1 then begin tmpStr := regex.Replace(tmpStr, '^UPDATE\s', ''); tableName := Copy(tmpStr, 1, Pos(' ', tmpStr) -1); notifyDataSets(tableName); end; //DELETE FROM TABLE_NAME if Pos('DELETE', tmpStr) = 1 then begin tmpStr := regex.Replace(tmpStr, '^DELETE\sFROM\s', ''); tableName := Copy(tmpStr, 1, Pos(' ', tmpStr) -1); notifyDataSets(tableName); end; //SELECT FIELDS FROM TABLE_NAME if Pos('SELECT', tmpStr) = 1 then begin tmpStr := regex.Replace(tmpStr, '^(.*?)\sFROM\s', ''); tableName := Copy(tmpStr, 1, Pos(' ', tmpStr) -1); end; end; end; function TRemoteDataModule.generateGroups(const ATable: string): boolean; var fields: TStringList; i: byte; s: string; begin fields := getFieldsList(ATable); for I := 0 to fields.Count -1 do begin s := Format('CREATE OR ALTER VIEW CAT_NOTR_%s(%s) AS SELECT %s FROM CATALOG_NOTARIES GROUP BY %s ORDER BY %s;', [fields[i], fields[i], fields[i], fields[i], fields[i]]); log(s); end; end; function TRemoteDataModule.getDatabase: TpFIBDatabase; begin Result := FIBDatabase; end; function TRemoteDataModule.getFieldInfo(const ATable: string; AField, AType: string): string; var FieldsList: TStringList; FieldInfo: TTableFieldInfo; begin FieldsList := getFieldsList(ATable); FieldInfo := TTableFieldInfo(FieldsList.Objects[FieldsList.IndexOf(AField)]); if AType = 'FIELD_ID' then Result := IntToStr(FieldInfo.ID); if AType = 'FIELD_POSITION' then Result := IntToStr(FieldInfo.Position); if AType = 'FIELD_NULL_FLAG' then Result := IntToStr(Byte(FieldInfo.isNullable)); if AType = 'FIELD_DESCRIPTION' then Result := FieldInfo.Description; end; function TRemoteDataModule.getFields(const ATable: string): string; var FieldsList: TStringList; begin FieldsList := getFieldsList(ATable); Result := FieldsList.CommaText; FieldsList.Free; end; function TRemoteDataModule.getFieldsList(const ATable: string): TStringList; var FieldsListDataSet: TpFIBDataSet; FieldsList: TStringList; FieldsListResult: TStringList; FieldInfo: TTableFieldInfo; begin FieldsListResult := TStringList.Create; if FTablesList.IndexOf(ATable) <0 then begin FieldsList := TStringList.Create; FieldsListDataSet := createDataSet; FieldsListDataSet.SQLs.SelectSQL.Text := 'SELECT TABLE_NAME, FIELD_NAME, FIELD_POSITION, FIELD_ID, FIELD_DESCRIPTION, FIELD_NULL_FLAG FROM VIEW_TABLE_FIELDS WHERE TABLE_NAME = :TABLE_NAME'; FieldsListDataSet.ParamByName('TABLE_NAME').AsString := ATable; FieldsListDataSet.Open; FieldsListDataSet.First; while not FieldsListDataSet.Eof do begin FieldInfo := TTableFieldInfo.Create; FieldInfo.Table := ATable; FieldInfo.ID := FieldsListDataSet.FieldByName('FIELD_ID').AsLargeInt; FieldInfo.Name := FieldsListDataSet.FieldByName('FIELD_NAME').AsString; FieldInfo.Description := FieldsListDataSet.FieldByName('FIELD_DESCRIPTION').AsString; FieldInfo.Position := FieldsListDataSet.FieldByName('FIELD_POSITION').AsLargeInt; FieldInfo.isNullable := not FieldsListDataSet.FieldByName('FIELD_POSITION').AsInteger = 1; FieldsList.AddObject(FieldsListDataSet.FieldByName('FIELD_NAME').AsString, FieldInfo); // FieldsList.Append(FieldsListDataSet.FieldByName('FIELD_NAME').AsString); FieldsListDataSet.Next; end; FTablesList.AddObject(ATable, FieldsList); FieldsListDataSet.Close; FieldsListDataSet.Free; end; FieldsListResult.Assign(TStringList(FTablesList.Objects[FTablesList.IndexOf(ATable)])); Result := FieldsListResult; end; function TRemoteDataModule.getGlobalConfigData(AKeyName: string): variant; begin GlobalConfigurationDataSet.Close; GlobalConfigurationDataSet.ParamByName('KEY').AsString := AKeyName; GlobalConfigurationDataSet.Open; Result := GlobalConfigurationDataSetVALUE_DATA.AsVariant; GlobalConfigurationDataSet.Close; end; function TRemoteDataModule.getTransaction: TpFIBTransaction; begin Result := FIBTransaction; end; function TRemoteDataModule.notifyDataSets(const ATableName: string): boolean; var DataSetItem: Pointer; begin log('notifycation: ' + ATableName); if FDataSetList.Count =0 then Exit; for DataSetItem in FDataSetList do begin try //if not Assigned(ValidateObj(DataSetItem)) then if Length(TpFIBDataSet(DataSetItem).Description) = 0 then begin unregisterDataSet(DataSetItem); Continue; end; if UpperCase(TpFIBDataSet(DataSetItem).Description) = UpperCase(ATableName) then begin if TpFIBDataSet(DataSetItem).Active then begin //TpFIBDataSet(FDataSetList[iDataSet]).Refresh; //TpFIBDataSet(DataSetItem).Close; //TpFIBDataSet(DataSetItem).Open; //TpFIBDataSet(DataSetItem).CloseOpen(true); TpFIBDataSet(DataSetItem).FullRefresh; //TpFIBDataSet(DataSetItem).FetchAll; Log('Refresh table ' + ATableName); end; end; except Log('Error while table refresh ' + ATableName); unregisterDataSet(DataSetItem); end; end; end; function TRemoteDataModule.preloadTablesData: boolean; begin TableListDataSet.Open; while not TableListDataSet.Eof do begin getFieldsList(TableListDataSetTABLE_NAME.AsString); TableListDataSet.Next; end; TableListDataSet.Close; end; function TRemoteDataModule.registerDataSet(const ADataSet: TpFIBDataSet): boolean; begin FDataSetList.Add(ADataSet); end; function TRemoteDataModule.subscribeEvents: boolean; begin EventsListDataSet.Open; EventsListDataSet.First; while not EventsListDataSet.Eof do begin FIBEventAlerter.Events.Add(EventsListDataSetEVENT_NAME.AsString); TfmMain(Application.MainForm).Log('Subscribed to event: ' + EventsListDataSetEVENT_NAME.AsString); EventsListDataSet.Next; end; EventsListDataSet.Close; FIBEventAlerter.AutoRegister := True; end; function TRemoteDataModule.tryLocalDatabaseServer: boolean; var I, I2: Word; tDBServer: string; tDBLocation: string; tDBDrive: string; isConnected: boolean; tDBPort: Word; tDBHost: String; tDBUser: String; tDBPassword: String; tDBCharset: string; begin Result := False; try tDBServer := Config.ReadString('Database', 'Host', 'localhost'); tDBPort := Config.ReadInteger('Database', 'Port', 3050); tDBUser := Config.ReadString('Database', 'User', 'SYSDBA'); tDBPassword := Config.ReadString('Database', 'Password', 'masterkey'); tDBLocation := Config.ReadString('Database', 'Location', 'C:\db\notar.fdb'); tDBCharset := Config.ReadString('Database', 'Charset', 'UTF8'); isConnected := False; FIBDatabase.Close; FIBDatabase.ConnectParams.UserName := tDBUser; FIBDatabase.ConnectParams.Password := tDBPassword; FIBDatabase.ConnectParams.CharSet := tDBCharset; FIBDatabase.DBName := Format('%s/%s:%s', [tDBServer, IntToStr(tDBPort), tDBLocation]); TfmMain(Application.MainForm).Log('Database probe from configuration @ ' + FIBDatabase.DBName); try FIBDatabase.Open; except TfmMain(Application.MainForm).Log('Database file from configuration @ ' + FIBDatabase.DBName + ' is not found'); end; if FIBDatabase.Connected then begin FIBDatabase.AutoReconnect := True; Result := True; Exit; end; for I := Low(MainDataBaseLocationDrives) to High(MainDataBaseLocationDrives) do begin if isConnected then break; for I2 := Low(MainDataBaseLocations) to High(MainDataBaseLocations) do begin tDBDrive := MainDataBaseLocationDrives[I]; tDBLocation := MainDataBaseLocations[I2]; FIBDatabase.Close; FIBDatabase.DBName := Format('%s/%s:%s:\%s\%s', [tDBServer, IntToStr(tDBPort), tDBDrive, tDBLocation, MainDataBaseFile]); try FIBDatabase.Open; except TfmMain(Application.MainForm).Log('Database file @ ' + FIBDatabase.DBName + ' is not found'); end; if FIBDatabase.Connected then begin FIBDatabase.AutoReconnect := True; isConnected := True; Config.WriteString('Database', 'Host', tDBServer); Config.WriteInteger('Database', 'Port', tDBPort); Config.WriteString('Database', 'Location', Format('%s:\%s\%s', [tDBDrive, tDBLocation, MainDataBaseFile])); Config.UpdateFile; break; end; end; end; TfmMain(Application.MainForm).Log('DSN: ' + FIBDatabase.DBName); finally Result := FIBDatabase.Connected; end; end; function TRemoteDataModule.unregisterDataSet(const ADataSet: TpFIBDataSet): boolean; begin FDataSetList.Remove(ADataSet); end; end.
program HelloWorld(output); begin Write('Hello, world!') {no ";" is required after the last statement of a block - adding one adds a "null statement" to the program;} end. procedure ThingOne; begin while a <> b do WriteLn('Waiting'); if a > b then WriteLn('Condition met') {no semicolon allowed!} else WriteLn('Condition not met'); for i := 1 to 10 do {no semicolon for single statements allowed!} WriteLn('Iteration: ', i); repeat a := a + 1 until a = 10; case i of 0 : Write('zero'); 1 : Write('one'); 2 : Write('two'); 3,4,5,6,7,8,9,10: Write('?') end; end.
unit IRCCommandTests; {$mode objfpc}{$H+} interface uses Classes, SysUtils, IRCCommands, fpcunit, testutils, testregistry; type { TIRCCommandsTests } TIRCCommandsTests = class(TTestCase) private FSUT: TIRCCommand; protected procedure SetUp; override; procedure TearDown; override; published procedure ConvertToRaw; procedure JoinAliasJ; procedure RawCommand; procedure FixChannelNameOnJoin; end; implementation procedure TIRCCommandsTests.ConvertToRaw; begin CheckEquals('JOIN #ubuntu', FSUT.GetRawCommand('/join #ubuntu')); CheckEquals('MSG fsapo', FSUT.GetRawCommand('/msg fsapo')); CheckEquals('', FSUT.GetRawCommand('Not a command')); end; procedure TIRCCommandsTests.JoinAliasJ; begin CheckEquals('JOIN #ubuntu', FSUT.GetRawCommand('/j #ubuntu')); end; procedure TIRCCommandsTests.RawCommand; begin CheckEquals('AWAY', FSUT.GetRawCommand('/away')); CheckEquals('AWAY brb', FSUT.GetRawCommand('/away brb')); end; procedure TIRCCommandsTests.FixChannelNameOnJoin; begin CheckEquals('JOIN #ubuntu', FSUT.GetRawCommand('/j ubuntu')); CheckEquals('JOIN #ubuntu', FSUT.GetRawCommand('/join ubuntu')); CheckEquals('JOIN #ubuntu', FSUT.GetRawCommand('/join #ubuntu')); CheckEquals('JOIN #join', FSUT.GetRawCommand('/join join')); end; procedure TIRCCommandsTests.SetUp; begin FSUT.Create; end; procedure TIRCCommandsTests.TearDown; begin FSUT.Free; end; initialization RegisterTest(TIRCCommandsTests); end.
unit evControlContainer; // Модуль: "w:\common\components\gui\Garant\Everest\qf\evControlContainer.pas" // Стереотип: "SimpleClass" // Элемент модели: "TevControlContainer" MUID: (47CFEE9E02E1) {$Include w:\common\components\gui\Garant\Everest\evDefine.inc} interface uses l3IntfUses , evCustomControlTool , nevTools , evQueryCardInt , evQueryGroupList , nevBase , l3Variant , Messages , l3Interfaces ; type TevControlContainer = class(TevCustomControlTool, InevControlListener, IevQueryCard) private f_InsertRowMode: Boolean; {* Флаг режима вставки новой строки реквизита. } f_PasteOperation: Boolean; {* Была начата операция вставки. } f_LimitErrorControl: IevEditorControl; {* Была ошибка о превышении количества символов. } f_GroupList: TevQueryGroupList; {* Список групп, входящих в КЗ (IevQueryGroup). } f_QueryContainer: InevQueryDocumentContainer; {* Указатель на контейнер. } f_AdapterModel: Pointer; {* //IevAdapterModel Ссылка на внешнюю модель. } f_UpperButtons: IevCustomEditorControl; {* Кнопки с состоянием Flat. } f_StartFocusControl: IevEditorControl; {* Виджет для получения курсора после его создания. } protected f_CurrPara: InevPara; {* Параграф виджета, который имеет фокус. f_CurrPara используется исключительно для "истории" переходов. } f_StateControl: IevCustomEditorControl; {* Виджет, по которому определяем состояния меню. } protected procedure DoHideDroppedControl(CanSetFocus: Boolean); virtual; abstract; function DoMouseWheel(aDown: Boolean): Boolean; virtual; abstract; function GetFirstVisible(const aGroup: IevQueryGroup; anOnlyFields: Boolean; anExpanedeOnly: Boolean): IevCustomEditorControl; function GetLastVisible(const aGroup: IevQueryGroup; anOnlyFields: Boolean; anExpanedeOnly: Boolean): IevCustomEditorControl; function GetFirstControl(const aReq: IevReq; anOnlyFields: Boolean): IevCustomEditorControl; function GetLastControl(const aReq: IevReq; anOnlyFields: Boolean): IevCustomEditorControl; function GetNextReq(const aReq: IevReq; anExpandedOnly: Boolean; out aFirstReq: Boolean): IevReq; {* Возвращает следующий реквизит или nil, если такого нет. } function GetPrevReq(const aReq: IevReq; anExpandedOnly: Boolean; out aLastReq: Boolean): IevReq; {* Возвращает предыдущий реквизит. } function DoGetNode(anIndex: Integer): InevSimpleNode; virtual; procedure DoDeleteOnUndo(aTag: Tl3Tag); virtual; procedure DoChangePara(const aCurPara: InevPara); virtual; function DoKeyDown(const aView: InevView; var Msg: TWMKeyDown; aCurPara: Tl3Tag): Boolean; virtual; {* Посылка сообщений о нажатии клавиш. } function CanInsertPara: Boolean; {* Разрешено ли вставлять параграф. } procedure InsertOnUndo(aPrev: Tl3Variant; aChild: Tl3Variant; anAdd: Boolean); {* Реакция на вставку при откатке. } procedure DeleteOnUndo(aTag: Tl3Variant); {* Реакция удаления при откатке. } procedure HideDroppedControl(CanSetFocus: Boolean); {* Обработчик изменения события состояния редактора (нужно для выпадающего контрола). } function MouseWheel(aDown: Boolean): Boolean; {* Событие прокрутки мыши. } function KeyDown(const aView: InevView; var Msg: TWMKeyDown; aCurPara: Tl3Variant): Boolean; {* Посылка сообщений о нажатии клавиш. } procedure ChangePara(const aCurPara: InevPara); {* Событие смена текуего параграфа. } procedure BeforeRMouseClick; {* Событие, вызываемое перед обработкой мыши. } procedure ClearUpper; function NeedKey(aPara: Tl3Variant; var aKeyCode: Word): Boolean; {* Контрол/Поле перехватывает курсор. } procedure CursorCreate; {* Обновить курсор после создания. } procedure UpdateState; function IsLastField(aPara: Tl3Variant): Boolean; {* Проверяет является ли параграф последним для передачи фокуса. } function IsFirstField(aPara: Tl3Variant): Boolean; {* Проверяет является ли параграф первым для передачи фокуса. } procedure StartPaste; {* Скобки для операции вставки. } procedure FinishPaste; {* Скобки для операции вставки. } function IsPasting: Boolean; {* Внутри скобок для операции вставки. } function GetFirstPara(OnlyFields: Boolean): InevPara; {* Получить первый параграф, в который может получить фокус. } function GetLastPara(OnlyFields: Boolean): InevPara; {* Получить последний параграф, в который может получить фокус. } procedure SetCurrPara(const aCurPara: InevPara); function GetDocumentContainer: InevQueryDocumentContainer; {* Получить контейнер документа. } procedure RememberFocusControl(const aValue: IevEditorControl); {* Запомнить контрол для установки фокуса. } procedure BeforeDelete; {* Вызывается перед удалением поля. } procedure UpperChange(const aButton: IevCustomEditorControl); {* Вызывается после установки Upper у кнопки в True. } function GetNode(anIndex: Integer): InevSimpleNode; {* Возвращает узел по номеру. } procedure CardClear; {* Обработчик очистки КЗ. } procedure StartLongOperation; {* Скобки для блокировки перерисовок в редакторе. } procedure EndLongOperation; {* Скобки для блокировки перерисовок в редакторе. } procedure ChangeStateAll(anExpand: Boolean); {* Выставляет признак развернутости/свернутости всем группам. } procedure AfterCollapsed(const aGroup: IevQueryGroup); procedure LimitCharsReached(const aControl: IevEditorControl); {* Обработчик достижения максимального числа символов в параграфе. } procedure RememberState(const aControl: IevCustomEditorControl); {* Запомнить состояние для контекстного меню. } function GetStateControl: IevCustomEditorControl; {* Возвращает контрол, который был активным при вызове контекстного меню. } function GetFocusedControl(aCurPara: Tl3Variant): IevEditorControl; {* Возвращает контрол, имеющий фокус ввода. } procedure LinkView(const aQueryContainer: InevQueryDocumentContainer); {* Инициализации модели. } procedure LinkListener(const aListener: IevAdapterModel); {* Подключить объект из внешней модели. } function AdapterModel: IevAdapterModel; procedure ReleaseListeners; {* Отключить объект из внешней модели. } function FindDescriptionReq(const aReqName: Tl3WString): IevDescriptionReq; {* Получение реквизита по имени. } procedure StartSetFocus; {* Возвращает первое доступное для редактирования поле в контроле. } function Get_QueryGroup(anIndex: Integer): IevQueryGroup; function Get_GroupCount: Integer; function pm_GetEditor: InevControl; function Get_InsertRowMode: Boolean; procedure Set_InsertRowMode(aValue: Boolean); function pm_GetCardType: TevQueryType; function GetControlIterator(const aCurrentControl: IevCustomEditorControl): IevControlIterator; procedure Cleanup; override; {* Функция очистки полей объекта. } public class function Make: IevQueryCard; reintroduce; constructor Create; reintroduce; virtual; end;//TevControlContainer implementation uses l3ImplUses , l3CProtoObject , k2Tags , evControlParaTools , evControlParaConst , SysUtils , evdTypes , l3Base , Windows , evQueryCardConst , nevFacade , ControlPara_Const , ControlsBlock_Const , evControlGroup //#UC START# *47CFEE9E02E1impl_uses* //#UC END# *47CFEE9E02E1impl_uses* ; type TevControlIterator = class(Tl3CProtoObject, IevControlIterator) private f_CurrentControl: IevCustomEditorControl; {* Текущий контрол. Используется при итерации по контролам. } f_QueryCard: TevControlContainer; protected function GetNextVisible(OnlyFields: Boolean): IevCustomEditorControl; {* Возвращает следующий видимый контрол или nil, если такого нет. } function GetPrevVisible(OnlyFields: Boolean): IevCustomEditorControl; {* Возвращает предыдущий видимый контрол или nil, если такого нет. } procedure Cleanup; override; {* Функция очистки полей объекта. } {$If NOT Defined(DesignTimeLibrary)} class function IsCacheable: Boolean; override; {* функция класса, определяющая могут ли объекты данного класса попадать в кэш повторного использования. } {$IfEnd} // NOT Defined(DesignTimeLibrary) public class function Make(const aControl: IevCustomEditorControl; aQueryCard: TevControlContainer): IevControlIterator; reintroduce; constructor Create(const aControl: IevCustomEditorControl; aQueryCard: TevControlContainer); reintroduce; end;//TevControlIterator class function TevControlIterator.Make(const aControl: IevCustomEditorControl; aQueryCard: TevControlContainer): IevControlIterator; var l_Inst : TevControlIterator; begin l_Inst := Create(aControl, aQueryCard); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TevControlIterator.Make constructor TevControlIterator.Create(const aControl: IevCustomEditorControl; aQueryCard: TevControlContainer); //#UC START# *48B7FB0A0266_48B7FA9403B1_var* //#UC END# *48B7FB0A0266_48B7FA9403B1_var* begin //#UC START# *48B7FB0A0266_48B7FA9403B1_impl* inherited Create; f_CurrentControl := aControl; l3Set(f_QueryCard, aQueryCard); //#UC END# *48B7FB0A0266_48B7FA9403B1_impl* end;//TevControlIterator.Create function TevControlIterator.GetNextVisible(OnlyFields: Boolean): IevCustomEditorControl; {* Возвращает следующий видимый контрол или nil, если такого нет. } //#UC START# *47CD77A200FE_48B7FA9403B1_var* var l_EditorControl : IevEditorControl; l_Group : IevQueryGroup; l_IsLast : Boolean; //#UC END# *47CD77A200FE_48B7FA9403B1_var* begin //#UC START# *47CD77A200FE_48B7FA9403B1_impl* Result := nil; if (f_CurrentControl <> nil) then if Supports(f_CurrentControl, IevEditorControl, l_EditorControl) then begin Result := l_EditorControl.Req.GetNextVisible(l_EditorControl, OnlyFields, l_IsLast); //Пытаемся получить следующий доступный для перехода контрол if l_IsLast then //В реквизите нет больше контролов, на которые можно перейти Result := f_QueryCard.GetFirstControl(l_EditorControl.Req, OnlyFields); end else if Supports(f_CurrentControl, IevQueryGroup, l_Group) then Result := f_QueryCard.GetFirstVisible(l_Group, OnlyFields, False); //#UC END# *47CD77A200FE_48B7FA9403B1_impl* end;//TevControlIterator.GetNextVisible function TevControlIterator.GetPrevVisible(OnlyFields: Boolean): IevCustomEditorControl; {* Возвращает предыдущий видимый контрол или nil, если такого нет. } //#UC START# *47CD77B1038D_48B7FA9403B1_var* var l_EditorControl : IevEditorControl; l_Group : IevQueryGroup; l_IsFirst : Boolean; //#UC END# *47CD77B1038D_48B7FA9403B1_var* begin //#UC START# *47CD77B1038D_48B7FA9403B1_impl* Result := nil; if (f_CurrentControl <> nil) then if Supports(f_CurrentControl, IevEditorControl, l_EditorControl) then begin Result := l_EditorControl.Req.GetPrevVisible(l_EditorControl, OnlyFields, l_IsFirst); if l_IsFirst then Result := f_QueryCard.GetLastControl(l_EditorControl.Req, OnlyFields); end else if Supports(f_CurrentControl, IevQueryGroup, l_Group) then Result := f_QueryCard.GetLastVisible(l_Group, OnlyFields, False); //#UC END# *47CD77B1038D_48B7FA9403B1_impl* end;//TevControlIterator.GetPrevVisible procedure TevControlIterator.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_48B7FA9403B1_var* //#UC END# *479731C50290_48B7FA9403B1_var* begin //#UC START# *479731C50290_48B7FA9403B1_impl* f_CurrentControl := nil; l3Free(f_QueryCard); inherited; //#UC END# *479731C50290_48B7FA9403B1_impl* end;//TevControlIterator.Cleanup {$If NOT Defined(DesignTimeLibrary)} class function TevControlIterator.IsCacheable: Boolean; {* функция класса, определяющая могут ли объекты данного класса попадать в кэш повторного использования. } //#UC START# *47A6FEE600FC_48B7FA9403B1_var* //#UC END# *47A6FEE600FC_48B7FA9403B1_var* begin //#UC START# *47A6FEE600FC_48B7FA9403B1_impl* Result := true; //#UC END# *47A6FEE600FC_48B7FA9403B1_impl* end;//TevControlIterator.IsCacheable {$IfEnd} // NOT Defined(DesignTimeLibrary) class function TevControlContainer.Make: IevQueryCard; var l_Inst : TevControlContainer; begin l_Inst := Create; try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TevControlContainer.Make constructor TevControlContainer.Create; //#UC START# *47CFF63F02B6_47CFEE9E02E1_var* //#UC END# *47CFF63F02B6_47CFEE9E02E1_var* begin //#UC START# *47CFF63F02B6_47CFEE9E02E1_impl* inherited Create(nil); f_GroupList := TevQueryGroupList.Make; f_InsertRowMode := False; //#UC END# *47CFF63F02B6_47CFEE9E02E1_impl* end;//TevControlContainer.Create function TevControlContainer.GetFirstVisible(const aGroup: IevQueryGroup; anOnlyFields: Boolean; anExpanedeOnly: Boolean): IevCustomEditorControl; //#UC START# *47D0045001C3_47CFEE9E02E1_var* var i, k : Integer; l_Index : Integer; l_Group : IevQueryGroup; l_ReqCount : Integer; //#UC END# *47D0045001C3_47CFEE9E02E1_var* begin //#UC START# *47D0045001C3_47CFEE9E02E1_impl* Result := nil; l_Index := f_GroupList.IndexOf(aGroup); if not aGroup.Expanded then //Если группа развернута, то можно просто получить первый контрол if not anExpanedeOnly then Inc(l_Index); if l_Index < f_GroupList.Count then for i := l_Index to f_GroupList.Count - 1 do begin l_Group := f_GroupList[i]; if not anOnlyFields and not aGroup.Expanded then begin Result := l_Group; Break; end; l_ReqCount := l_Group.ReqCount - 1; for k := 0 to l_ReqCount do begin Result := l_Group.Req[k].GetFirstVisible(anOnlyFields); if Result <> nil then Break; end; if Result <> nil then Break; end; //#UC END# *47D0045001C3_47CFEE9E02E1_impl* end;//TevControlContainer.GetFirstVisible function TevControlContainer.GetLastVisible(const aGroup: IevQueryGroup; anOnlyFields: Boolean; anExpanedeOnly: Boolean): IevCustomEditorControl; //#UC START# *47D0048E01F2_47CFEE9E02E1_var* var i, k : Integer; l_Index : Integer; l_Group : IevQueryGroup; l_ReqCount : Integer; //#UC END# *47D0048E01F2_47CFEE9E02E1_var* begin //#UC START# *47D0048E01F2_47CFEE9E02E1_impl* Result := nil; l_Index := f_GroupList.IndexOf(aGroup); if not anExpanedeOnly then Dec(l_Index); if l_Index >= 0 then for i := l_Index downto 0 do begin l_Group := f_GroupList[i]; if not anOnlyFields and not l_Group.Expanded then begin Result := l_Group; Break; end; l_ReqCount := l_Group.ReqCount - 1; for k := l_ReqCount downto 0 do begin Result := l_Group.Req[k].GetLastVisible(anOnlyFields); if Result <> nil then Break; end; if Result <> nil then Break; end; //#UC END# *47D0048E01F2_47CFEE9E02E1_impl* end;//TevControlContainer.GetLastVisible function TevControlContainer.GetFirstControl(const aReq: IevReq; anOnlyFields: Boolean): IevCustomEditorControl; //#UC START# *47D0074B0107_47CFEE9E02E1_var* var l_Req : IevReq; l_Last : Boolean; //#UC END# *47D0074B0107_47CFEE9E02E1_var* begin //#UC START# *47D0074B0107_47CFEE9E02E1_impl* Result := nil; l_Req := aReq; while l_Req <> nil do begin l_Req := GetNextReq(l_Req, anOnlyFields, l_Last); if (l_Req <> nil) and not anOnlyFields and l_Last then //Переход по всем контролам begin Result := l_Req.Group; Break; end else //Только по полям - группы игнорируются! if (l_Req <> nil) and l_Req.Group.Expanded then begin Result := l_Req.GetFirstVisible(anOnlyFields); if Result <> nil then Break; end else Result := nil; end; //#UC END# *47D0074B0107_47CFEE9E02E1_impl* end;//TevControlContainer.GetFirstControl function TevControlContainer.GetLastControl(const aReq: IevReq; anOnlyFields: Boolean): IevCustomEditorControl; //#UC START# *47D0075D03DF_47CFEE9E02E1_var* var l_Req : IevReq; l_First : Boolean; //#UC END# *47D0075D03DF_47CFEE9E02E1_var* begin //#UC START# *47D0075D03DF_47CFEE9E02E1_impl* Result := nil; l_Req := aReq; while l_Req <> nil do begin l_Req := GetPrevReq(l_Req, anOnlyFields, l_First); if not anOnlyFields and l_First then //Переход по всем контролам begin Result := aReq.Group; Break; end else if l_Req <> nil then begin Result := l_Req.GetLastVisible(anOnlyFields); if anOnlyFields and (Result = nil) then Continue else Break; end else Result := nil; end; //#UC END# *47D0075D03DF_47CFEE9E02E1_impl* end;//TevControlContainer.GetLastControl function TevControlContainer.GetNextReq(const aReq: IevReq; anExpandedOnly: Boolean; out aFirstReq: Boolean): IevReq; {* Возвращает следующий реквизит или nil, если такого нет. } //#UC START# *47D009D1009A_47CFEE9E02E1_var* //Функция возращает указатель на следующий реквизит. Если он является последним //в группе, то возвращается первый в следующей группе (aFirstReq выставляется //в True). Если группа последняя, то возвращается nil. Если выставлен //anExpandedOnly = True, то проверяются только развернутые группы и игнорируются //свернутые. var l_Req : IevReq; l_Group : IevQueryGroup; l_Index : Integer; //#UC END# *47D009D1009A_47CFEE9E02E1_var* begin //#UC START# *47D009D1009A_47CFEE9E02E1_impl* aFirstReq := False; l_Group := aReq.Group; l_Req := l_Group.GetNextReq(aReq); try if l_Req <> nil then Result := l_Req else if (f_GroupList.Last <> l_Group) then begin aFirstReq := True; l_Index := f_GroupList.IndexOf(l_Group); while l_Index < (f_GroupList.Count - 1) do begin Inc(l_Index); l_Group := f_GroupList[l_Index]; if anExpandedOnly then if l_Group.Expanded then Break else l_Group := nil else Break; end; if l_Group <> nil then Result := l_Group.Req[0] else Result := nil; end else Result := nil; finally l_Group := nil; l_Req := nil; end; //#UC END# *47D009D1009A_47CFEE9E02E1_impl* end;//TevControlContainer.GetNextReq function TevControlContainer.GetPrevReq(const aReq: IevReq; anExpandedOnly: Boolean; out aLastReq: Boolean): IevReq; {* Возвращает предыдущий реквизит. } //#UC START# *47D00A370286_47CFEE9E02E1_var* var l_Req : IevReq; l_Group : IevQueryGroup; l_Index : Integer; //#UC END# *47D00A370286_47CFEE9E02E1_var* begin //#UC START# *47D00A370286_47CFEE9E02E1_impl* aLastReq := False; l_Group := aReq.Group; l_Req := l_Group.GetPrevReq(aReq); try if l_Req <> nil then Result := l_Req else if (f_GroupList.First <> l_Group) then begin aLastReq := True; l_Index := f_GroupList.IndexOf(l_Group); while l_Index > 0 do begin Dec(l_Index); l_Group := f_GroupList[l_Index]; if anExpandedOnly then if l_Group.Expanded then Break else l_Group := nil else Break; end; if l_Group <> nil then Result := l_Group.LastReq else Result := nil; end else begin aLastReq := l_Group.FirstReq = aReq; Result := nil; end; finally l_Group := nil; l_Req := nil; end; //#UC END# *47D00A370286_47CFEE9E02E1_impl* end;//TevControlContainer.GetPrevReq function TevControlContainer.DoGetNode(anIndex: Integer): InevSimpleNode; //#UC START# *47D010D10193_47CFEE9E02E1_var* //#UC END# *47D010D10193_47CFEE9E02E1_var* begin //#UC START# *47D010D10193_47CFEE9E02E1_impl* Result := nil; //#UC END# *47D010D10193_47CFEE9E02E1_impl* end;//TevControlContainer.DoGetNode procedure TevControlContainer.DoDeleteOnUndo(aTag: Tl3Tag); //#UC START# *47D0111400DC_47CFEE9E02E1_var* var l_Control : IevEditorControl; l_Req : IevReq; //#UC END# *47D0111400DC_47CFEE9E02E1_var* begin //#UC START# *47D0111400DC_47CFEE9E02E1_impl* l_Control := evGetEditorControl(aTag.Child[0].Child[0]); l_Req := l_Control.Req; if (l_Req <> nil) then l_Req.DeleteFromModel(nil, l_Control, True); f_CurrPara := nil; //#UC END# *47D0111400DC_47CFEE9E02E1_impl* end;//TevControlContainer.DoDeleteOnUndo procedure TevControlContainer.DoChangePara(const aCurPara: InevPara); //#UC START# *47D011870105_47CFEE9E02E1_var* var l_Control: IevEditorControl; //#UC END# *47D011870105_47CFEE9E02E1_var* begin //#UC START# *47D011870105_47CFEE9E02E1_impl* if (aCurPara <> nil) {and aCurPara.IsKindOf(k2_typLeafPara)} then f_CurrPara := aCurPara else f_CurrPara := nil; if f_CurrPara <> nil then begin if f_CurrPara.AsObject.IsKindOf(k2_typControlPara) then begin l_Control := evGetEditorControl(f_CurrPara.AsObject); if (l_Control <> nil) and (l_Control.ControlType in evEditControls) then begin RememberFocusControl(l_Control); RememberState(l_Control); end; end; end; //#UC END# *47D011870105_47CFEE9E02E1_impl* end;//TevControlContainer.DoChangePara function TevControlContainer.DoKeyDown(const aView: InevView; var Msg: TWMKeyDown; aCurPara: Tl3Tag): Boolean; {* Посылка сообщений о нажатии клавиш. } //#UC START# *47D0135901AC_47CFEE9E02E1_var* //#UC END# *47D0135901AC_47CFEE9E02E1_var* begin //#UC START# *47D0135901AC_47CFEE9E02E1_impl* Result := False; //Мы не забираем обработку на себя, а только обрабатываем событие if (Msg.CharCode = VK_APPS) then f_StateControl := GetFocusedControl(aCurPara); //#UC END# *47D0135901AC_47CFEE9E02E1_impl* end;//TevControlContainer.DoKeyDown function TevControlContainer.CanInsertPara: Boolean; {* Разрешено ли вставлять параграф. } //#UC START# *47C6BE3B027A_47CFEE9E02E1_var* //#UC END# *47C6BE3B027A_47CFEE9E02E1_var* begin //#UC START# *47C6BE3B027A_47CFEE9E02E1_impl* Result := f_InsertRowMode; //#UC END# *47C6BE3B027A_47CFEE9E02E1_impl* end;//TevControlContainer.CanInsertPara procedure TevControlContainer.InsertOnUndo(aPrev: Tl3Variant; aChild: Tl3Variant; anAdd: Boolean); {* Реакция на вставку при откатке. } //#UC START# *47C7C8EE0193_47CFEE9E02E1_var* var l_Control : IevEditorControl; l_Req : IevReq; //#UC END# *47C7C8EE0193_47CFEE9E02E1_var* begin //#UC START# *47C7C8EE0193_47CFEE9E02E1_impl* l_Control := evGetEditorControl(aPrev.Child[0].Child[0]); l_Req := l_Control.Req; l_Req.InsertToModel(nil, l_Control, aChild, True, anAdd); //#UC END# *47C7C8EE0193_47CFEE9E02E1_impl* end;//TevControlContainer.InsertOnUndo procedure TevControlContainer.DeleteOnUndo(aTag: Tl3Variant); {* Реакция удаления при откатке. } //#UC START# *47C7C9070379_47CFEE9E02E1_var* //#UC END# *47C7C9070379_47CFEE9E02E1_var* begin //#UC START# *47C7C9070379_47CFEE9E02E1_impl* DoDeleteOnUndo(aTag); //#UC END# *47C7C9070379_47CFEE9E02E1_impl* end;//TevControlContainer.DeleteOnUndo procedure TevControlContainer.HideDroppedControl(CanSetFocus: Boolean); {* Обработчик изменения события состояния редактора (нужно для выпадающего контрола). } //#UC START# *47C7C91E0277_47CFEE9E02E1_var* //#UC END# *47C7C91E0277_47CFEE9E02E1_var* begin //#UC START# *47C7C91E0277_47CFEE9E02E1_impl* DoHideDroppedControl(CanSetFocus) //#UC END# *47C7C91E0277_47CFEE9E02E1_impl* end;//TevControlContainer.HideDroppedControl function TevControlContainer.MouseWheel(aDown: Boolean): Boolean; {* Событие прокрутки мыши. } //#UC START# *47C7C9A4014C_47CFEE9E02E1_var* //#UC END# *47C7C9A4014C_47CFEE9E02E1_var* begin //#UC START# *47C7C9A4014C_47CFEE9E02E1_impl* Result := DoMouseWheel(aDown); //#UC END# *47C7C9A4014C_47CFEE9E02E1_impl* end;//TevControlContainer.MouseWheel function TevControlContainer.KeyDown(const aView: InevView; var Msg: TWMKeyDown; aCurPara: Tl3Variant): Boolean; {* Посылка сообщений о нажатии клавиш. } //#UC START# *47C7CA230160_47CFEE9E02E1_var* //#UC END# *47C7CA230160_47CFEE9E02E1_var* begin //#UC START# *47C7CA230160_47CFEE9E02E1_impl* Result := DoKeyDown(aView, Msg, aCurPara); //#UC END# *47C7CA230160_47CFEE9E02E1_impl* end;//TevControlContainer.KeyDown procedure TevControlContainer.ChangePara(const aCurPara: InevPara); {* Событие смена текуего параграфа. } //#UC START# *47C7CA350361_47CFEE9E02E1_var* //#UC END# *47C7CA350361_47CFEE9E02E1_var* begin //#UC START# *47C7CA350361_47CFEE9E02E1_impl* DoChangePara(aCurPara); //#UC END# *47C7CA350361_47CFEE9E02E1_impl* end;//TevControlContainer.ChangePara procedure TevControlContainer.BeforeRMouseClick; {* Событие, вызываемое перед обработкой мыши. } //#UC START# *47C7CA4500E7_47CFEE9E02E1_var* //#UC END# *47C7CA4500E7_47CFEE9E02E1_var* begin //#UC START# *47C7CA4500E7_47CFEE9E02E1_impl* f_StateControl := nil; //#UC END# *47C7CA4500E7_47CFEE9E02E1_impl* end;//TevControlContainer.BeforeRMouseClick procedure TevControlContainer.ClearUpper; //#UC START# *47C7CA5402D0_47CFEE9E02E1_var* //#UC END# *47C7CA5402D0_47CFEE9E02E1_var* begin //#UC START# *47C7CA5402D0_47CFEE9E02E1_impl* if f_UpperButtons <> nil then begin f_UpperButtons.Upper := False; f_UpperButtons := nil; end; //#UC END# *47C7CA5402D0_47CFEE9E02E1_impl* end;//TevControlContainer.ClearUpper function TevControlContainer.NeedKey(aPara: Tl3Variant; var aKeyCode: Word): Boolean; {* Контрол/Поле перехватывает курсор. } //#UC START# *47C7CA670121_47CFEE9E02E1_var* var l_Field : IevEditorControlField; l_FieldWithTree: IevEditorFieldWithTree; //#UC END# *47C7CA670121_47CFEE9E02E1_var* begin //#UC START# *47C7CA670121_47CFEE9E02E1_impl* Result := False; l_Field := evGetField(aPara); if (l_Field <> nil) and (aKeyCode in [VK_SUBTRACT, VK_ADD]) then begin Supports(l_Field, IevEditorFieldWithTree, l_FieldWithTree); if (l_FieldWithTree = nil) or l_FieldWithTree.IsList or (l_FieldWithTree.ComboStyle <> ev_cbFilterable) then begin if aKeyCode = VK_SUBTRACT then aKeyCode := cMinusKeyCode else aKeyCode := cPlusKeyCode; Result := True; end; end; //#UC END# *47C7CA670121_47CFEE9E02E1_impl* end;//TevControlContainer.NeedKey procedure TevControlContainer.CursorCreate; {* Обновить курсор после создания. } //#UC START# *47C7CB490100_47CFEE9E02E1_var* //#UC END# *47C7CB490100_47CFEE9E02E1_var* begin //#UC START# *47C7CB490100_47CFEE9E02E1_impl* if f_StartFocusControl <> nil then begin with pm_GetEditor do if (Selection <> nil) and not Selection.Point.MostInner.Obj.AsObject.IsSame(f_StartFocusControl.Para.MakePoint.MostInner.Obj^.AsObject) then Selection.SelectPoint(f_StartFocusControl.Para.MakePoint, False); f_StartFocusControl := nil; end; //#UC END# *47C7CB490100_47CFEE9E02E1_impl* end;//TevControlContainer.CursorCreate procedure TevControlContainer.UpdateState; //#UC START# *47C7CB5403D4_47CFEE9E02E1_var* var l_Field: IevEditorControlField; l_GroupIdx: Integer; l_ReqIdx: Integer; l_FieldIdx: Integer; l_FieldWithTree: IevEditorFieldWithTree; l_op: InevOp; //#UC END# *47C7CB5403D4_47CFEE9E02E1_var* begin //#UC START# *47C7CB5403D4_47CFEE9E02E1_impl* l_op := f_QueryContainer.Processor.StartOp(0,True); try if (f_StateControl <> nil) and Supports(f_StateControl, IevEditorControlField, l_Field) then begin l_Field.Req.Group.Para.OwnerPara.Invalidate([]); l_Field.Req.SetFocus(l_Field); end; l_op.SaveUndo := False; for l_GroupIdx := 0 to Get_GroupCount-1 do with Get_QueryGroup(l_GroupIdx) do for l_ReqIdx := 0 to ReqCount-1 do with Req[l_ReqIdx] do for l_FieldIdx := 0 to FieldsCount-1 do begin if Supports(Fields[l_FieldIdx], IevEditorFieldWithTree, l_FieldWithTree) then l_FieldWithTree.CheckTextVersusValue; UpdateState(Fields[l_FieldIdx], l_op); end; finally l_op := nil; end; //#UC END# *47C7CB5403D4_47CFEE9E02E1_impl* end;//TevControlContainer.UpdateState function TevControlContainer.IsLastField(aPara: Tl3Variant): Boolean; {* Проверяет является ли параграф последним для передачи фокуса. } //#UC START# *47C7CB5D0311_47CFEE9E02E1_var* var l_Control : IevCustomEditorControl; l_Group : IevQueryGroup; //#UC END# *47C7CB5D0311_47CFEE9E02E1_var* begin //#UC START# *47C7CB5D0311_47CFEE9E02E1_impl* if aPara.TagType.IsSame(k2_typControlPara) then begin l_Control := evGetCustomControl(aPara); if l_Control <> nil then begin l_Control := GetControlIterator(l_Control).GetNextVisible(False); end; Result := l_Control = nil; end else begin l_Group := evGetQueryGroup(aPara); Result := f_GroupList.IndexOf(l_Group) = f_GroupList.Count - 1; end; //#UC END# *47C7CB5D0311_47CFEE9E02E1_impl* end;//TevControlContainer.IsLastField function TevControlContainer.IsFirstField(aPara: Tl3Variant): Boolean; {* Проверяет является ли параграф первым для передачи фокуса. } //#UC START# *47C7CBC903AE_47CFEE9E02E1_var* var l_Control : IevCustomEditorControl; l_Group : IevQueryGroup; //#UC END# *47C7CBC903AE_47CFEE9E02E1_var* begin //#UC START# *47C7CBC903AE_47CFEE9E02E1_impl* if aPara.TagType.IsSame(k2_typControlPara) then begin l_Control := evGetCustomControl(aPara); if l_Control <> nil then begin l_Control := GetControlIterator(l_Control).GetPrevVisible(False); end; Result := l_Control = nil; end else begin l_Group := evGetQueryGroup(aPara); Result := f_GroupList.IndexOf(l_Group) = 0; end; //#UC END# *47C7CBC903AE_47CFEE9E02E1_impl* end;//TevControlContainer.IsFirstField procedure TevControlContainer.StartPaste; {* Скобки для операции вставки. } //#UC START# *47C7CBDE0030_47CFEE9E02E1_var* //#UC END# *47C7CBDE0030_47CFEE9E02E1_var* begin //#UC START# *47C7CBDE0030_47CFEE9E02E1_impl* f_PasteOperation := True; //#UC END# *47C7CBDE0030_47CFEE9E02E1_impl* end;//TevControlContainer.StartPaste procedure TevControlContainer.FinishPaste; {* Скобки для операции вставки. } //#UC START# *47C7CBEA02E3_47CFEE9E02E1_var* //#UC END# *47C7CBEA02E3_47CFEE9E02E1_var* begin //#UC START# *47C7CBEA02E3_47CFEE9E02E1_impl* f_PasteOperation := False; if Assigned(f_LimitErrorControl) then IevAdapterModel(f_AdapterModel).LimitCharsReached(f_LimitErrorControl); f_LimitErrorControl := nil; //#UC END# *47C7CBEA02E3_47CFEE9E02E1_impl* end;//TevControlContainer.FinishPaste function TevControlContainer.IsPasting: Boolean; {* Внутри скобок для операции вставки. } //#UC START# *47C7CBF803D7_47CFEE9E02E1_var* //#UC END# *47C7CBF803D7_47CFEE9E02E1_var* begin //#UC START# *47C7CBF803D7_47CFEE9E02E1_impl* Result := f_PasteOperation; //#UC END# *47C7CBF803D7_47CFEE9E02E1_impl* end;//TevControlContainer.IsPasting function TevControlContainer.GetFirstPara(OnlyFields: Boolean): InevPara; {* Получить первый параграф, в который может получить фокус. } //#UC START# *47C7CC09021A_47CFEE9E02E1_var* var i : Integer; l_Count : Integer; l_Control : IevCustomEditorControl; //#UC END# *47C7CC09021A_47CFEE9E02E1_var* begin //#UC START# *47C7CC09021A_47CFEE9E02E1_impl* l_Count := f_GroupList.Count - 1; for i := 0 to l_Count do begin l_Control := GetFirstVisible(f_GroupList[i], False, True); if l_Control <> nil then Break; end; if l_Control <> nil then Result := l_Control.Para else Result := nil; //#UC END# *47C7CC09021A_47CFEE9E02E1_impl* end;//TevControlContainer.GetFirstPara function TevControlContainer.GetLastPara(OnlyFields: Boolean): InevPara; {* Получить последний параграф, в который может получить фокус. } //#UC START# *47C7CC480009_47CFEE9E02E1_var* var i : Integer; l_Count : Integer; l_Control : IevCustomEditorControl; //#UC END# *47C7CC480009_47CFEE9E02E1_var* begin //#UC START# *47C7CC480009_47CFEE9E02E1_impl* l_Count := f_GroupList.Count - 1; for i := l_Count downto 0 do begin l_Control := GetLastVisible(f_GroupList[i], False, True); if l_Control <> nil then Break; end; if l_Control <> nil then Result := l_Control.Para else Result := nil; //#UC END# *47C7CC480009_47CFEE9E02E1_impl* end;//TevControlContainer.GetLastPara procedure TevControlContainer.SetCurrPara(const aCurPara: InevPara); //#UC START# *47CD829A0262_47CFEE9E02E1_var* //#UC END# *47CD829A0262_47CFEE9E02E1_var* begin //#UC START# *47CD829A0262_47CFEE9E02E1_impl* f_CurrPara := aCurPara; //#UC END# *47CD829A0262_47CFEE9E02E1_impl* end;//TevControlContainer.SetCurrPara function TevControlContainer.GetDocumentContainer: InevQueryDocumentContainer; {* Получить контейнер документа. } //#UC START# *47CD82A70217_47CFEE9E02E1_var* //#UC END# *47CD82A70217_47CFEE9E02E1_var* begin //#UC START# *47CD82A70217_47CFEE9E02E1_impl* Result := f_QueryContainer; //#UC END# *47CD82A70217_47CFEE9E02E1_impl* end;//TevControlContainer.GetDocumentContainer procedure TevControlContainer.RememberFocusControl(const aValue: IevEditorControl); {* Запомнить контрол для установки фокуса. } //#UC START# *47CD82BA01D2_47CFEE9E02E1_var* //#UC END# *47CD82BA01D2_47CFEE9E02E1_var* begin //#UC START# *47CD82BA01D2_47CFEE9E02E1_impl* f_StartFocusControl := aValue; RememberState(aValue); //#UC END# *47CD82BA01D2_47CFEE9E02E1_impl* end;//TevControlContainer.RememberFocusControl procedure TevControlContainer.BeforeDelete; {* Вызывается перед удалением поля. } //#UC START# *47CD82C800FB_47CFEE9E02E1_var* //#UC END# *47CD82C800FB_47CFEE9E02E1_var* begin //#UC START# *47CD82C800FB_47CFEE9E02E1_impl* ClearUpper; f_StateControl := nil; f_CurrPara := nil; //#UC END# *47CD82C800FB_47CFEE9E02E1_impl* end;//TevControlContainer.BeforeDelete procedure TevControlContainer.UpperChange(const aButton: IevCustomEditorControl); {* Вызывается после установки Upper у кнопки в True. } //#UC START# *47CD82DD0015_47CFEE9E02E1_var* //#UC END# *47CD82DD0015_47CFEE9E02E1_var* begin //#UC START# *47CD82DD0015_47CFEE9E02E1_impl* if (f_UpperButtons <> aButton) then begin if (f_UpperButtons <> nil) then f_UpperButtons.Upper := False; if aButton <> nil then f_UpperButtons := aButton else f_UpperButtons := nil; end; //#UC END# *47CD82DD0015_47CFEE9E02E1_impl* end;//TevControlContainer.UpperChange function TevControlContainer.GetNode(anIndex: Integer): InevSimpleNode; {* Возвращает узел по номеру. } //#UC START# *47CD82ED006B_47CFEE9E02E1_var* //#UC END# *47CD82ED006B_47CFEE9E02E1_var* begin //#UC START# *47CD82ED006B_47CFEE9E02E1_impl* Result := DoGetNode(anIndex); //#UC END# *47CD82ED006B_47CFEE9E02E1_impl* end;//TevControlContainer.GetNode procedure TevControlContainer.CardClear; {* Обработчик очистки КЗ. } //#UC START# *47CD82FE0071_47CFEE9E02E1_var* //#UC END# *47CD82FE0071_47CFEE9E02E1_var* begin //#UC START# *47CD82FE0071_47CFEE9E02E1_impl* f_QueryContainer.ClearCard; //#UC END# *47CD82FE0071_47CFEE9E02E1_impl* end;//TevControlContainer.CardClear procedure TevControlContainer.StartLongOperation; {* Скобки для блокировки перерисовок в редакторе. } //#UC START# *47CD830E0357_47CFEE9E02E1_var* //#UC END# *47CD830E0357_47CFEE9E02E1_var* begin //#UC START# *47CD830E0357_47CFEE9E02E1_impl* f_QueryContainer.Lock.Lock(Self); //#UC END# *47CD830E0357_47CFEE9E02E1_impl* end;//TevControlContainer.StartLongOperation procedure TevControlContainer.EndLongOperation; {* Скобки для блокировки перерисовок в редакторе. } //#UC START# *47CD831A0092_47CFEE9E02E1_var* //#UC END# *47CD831A0092_47CFEE9E02E1_var* begin //#UC START# *47CD831A0092_47CFEE9E02E1_impl* f_QueryContainer.Lock.Unlock(Self); //#UC END# *47CD831A0092_47CFEE9E02E1_impl* end;//TevControlContainer.EndLongOperation procedure TevControlContainer.ChangeStateAll(anExpand: Boolean); {* Выставляет признак развернутости/свернутости всем группам. } //#UC START# *47CD83410138_47CFEE9E02E1_var* var i : Integer; l_Count : Integer; //#UC END# *47CD83410138_47CFEE9E02E1_var* begin //#UC START# *47CD83410138_47CFEE9E02E1_impl* l_Count := f_GroupList.Count - 1; for i := 0 to l_Count do f_GroupList[i].Expanded := anExpand; //#UC END# *47CD83410138_47CFEE9E02E1_impl* end;//TevControlContainer.ChangeStateAll procedure TevControlContainer.AfterCollapsed(const aGroup: IevQueryGroup); //#UC START# *47CD835002FB_47CFEE9E02E1_var* //#UC END# *47CD835002FB_47CFEE9E02E1_var* begin //#UC START# *47CD835002FB_47CFEE9E02E1_impl* if not aGroup.Expanded then f_CurrPara := aGroup.Para; f_QueryContainer.AfterCollapsed; //#UC END# *47CD835002FB_47CFEE9E02E1_impl* end;//TevControlContainer.AfterCollapsed procedure TevControlContainer.LimitCharsReached(const aControl: IevEditorControl); {* Обработчик достижения максимального числа символов в параграфе. } //#UC START# *47CD83830353_47CFEE9E02E1_var* //#UC END# *47CD83830353_47CFEE9E02E1_var* begin //#UC START# *47CD83830353_47CFEE9E02E1_impl* if f_PasteOperation then f_LimitErrorControl := aControl else IevAdapterModel(f_AdapterModel).LimitCharsReached(aControl); //#UC END# *47CD83830353_47CFEE9E02E1_impl* end;//TevControlContainer.LimitCharsReached procedure TevControlContainer.RememberState(const aControl: IevCustomEditorControl); {* Запомнить состояние для контекстного меню. } //#UC START# *47CD839201D4_47CFEE9E02E1_var* //#UC END# *47CD839201D4_47CFEE9E02E1_var* begin //#UC START# *47CD839201D4_47CFEE9E02E1_impl* f_StateControl := aControl; //#UC END# *47CD839201D4_47CFEE9E02E1_impl* end;//TevControlContainer.RememberState function TevControlContainer.GetStateControl: IevCustomEditorControl; {* Возвращает контрол, который был активным при вызове контекстного меню. } //#UC START# *47CD83A1034C_47CFEE9E02E1_var* //#UC END# *47CD83A1034C_47CFEE9E02E1_var* begin //#UC START# *47CD83A1034C_47CFEE9E02E1_impl* Result := f_StateControl; //#UC END# *47CD83A1034C_47CFEE9E02E1_impl* end;//TevControlContainer.GetStateControl function TevControlContainer.GetFocusedControl(aCurPara: Tl3Variant): IevEditorControl; {* Возвращает контрол, имеющий фокус ввода. } //#UC START# *47CD83B10329_47CFEE9E02E1_var* var l_Group: IevQueryGroup; //#UC END# *47CD83B10329_47CFEE9E02E1_var* begin //#UC START# *47CD83B10329_47CFEE9E02E1_impl* aCurPara.QT(InevPara, f_CurrPara); if f_CurrPara <> nil then begin Result := evGetEditorControl(f_CurrPara.AsObject); if Result <> nil then if Result.ControlType = ev_ctCollapsedPanel then if Supports(Result, IevQueryGroup, l_Group) then Result := l_Group.FirstReq.FirstField; end else Result := nil; //#UC END# *47CD83B10329_47CFEE9E02E1_impl* end;//TevControlContainer.GetFocusedControl procedure TevControlContainer.LinkView(const aQueryContainer: InevQueryDocumentContainer); {* Инициализации модели. } //#UC START# *47CD83C8037F_47CFEE9E02E1_var* function GetChildBlock(const aChild : InevPara; anIndex : Integer): Boolean; var l_CG : IevQueryGroup; l_Tbl : InevPara; l_Index : Integer; l_List : InevParaList; begin Result := True; with aChild do if AsObject.IsKindOf(k2_typControlsBlock) then begin l_List := aChild.AsList; // for l_Index := 0 to l_List.ChildrenCount - 1 do begin l_CG := TevControlGroup.Make(aChild, Self); try for l_Index := 0 to l_List.AsObject.ChildrenCount - 1 do // - ведь таблиц внутри группы может быть сколько угодно begin l_Tbl := l_List.Para[l_Index]; try l_CG.InitModel(l_Tbl); finally l_Tbl := nil; end;//try..finally end;//for l_Index f_GroupList.Add(l_CG); finally l_CG := nil; end; //try..finally end;//for l_Index end;//if IsKindOf(k2_typControlBlock) end;//GetChildBlock //#UC END# *47CD83C8037F_47CFEE9E02E1_var* begin //#UC START# *47CD83C8037F_47CFEE9E02E1_impl* if (f_GroupList <> nil) then f_GroupList.Clear; f_QueryContainer := aQueryContainer; with aQueryContainer do begin LinkListener(Self); Assert(Obj.AsPara.AsObject.ChildrenCount <> 0, 'Нет дочерних параграфов!!!'); with Obj do if AsObject.IsValid then begin with AsPara.AsList do IterateParaF(nevL2PIA(@GetChildBlock)); Set_Para(AsPara); end;//if IsValid end;//with aQueryContainer StartSetFocus; //#UC END# *47CD83C8037F_47CFEE9E02E1_impl* end;//TevControlContainer.LinkView procedure TevControlContainer.LinkListener(const aListener: IevAdapterModel); {* Подключить объект из внешней модели. } //#UC START# *47CD83DC0133_47CFEE9E02E1_var* //#UC END# *47CD83DC0133_47CFEE9E02E1_var* begin //#UC START# *47CD83DC0133_47CFEE9E02E1_impl* f_AdapterModel := Pointer(aListener); //#UC END# *47CD83DC0133_47CFEE9E02E1_impl* end;//TevControlContainer.LinkListener function TevControlContainer.AdapterModel: IevAdapterModel; //#UC START# *47CD83EE0268_47CFEE9E02E1_var* //#UC END# *47CD83EE0268_47CFEE9E02E1_var* begin //#UC START# *47CD83EE0268_47CFEE9E02E1_impl* Result := IevAdapterModel(f_AdapterModel); //#UC END# *47CD83EE0268_47CFEE9E02E1_impl* end;//TevControlContainer.AdapterModel procedure TevControlContainer.ReleaseListeners; {* Отключить объект из внешней модели. } //#UC START# *47CD840002F7_47CFEE9E02E1_var* //#UC END# *47CD840002F7_47CFEE9E02E1_var* begin //#UC START# *47CD840002F7_47CFEE9E02E1_impl* f_AdapterModel := nil; //#UC END# *47CD840002F7_47CFEE9E02E1_impl* end;//TevControlContainer.ReleaseListeners function TevControlContainer.FindDescriptionReq(const aReqName: Tl3WString): IevDescriptionReq; {* Получение реквизита по имени. } //#UC START# *47CD842102B4_47CFEE9E02E1_var* var i : Integer; l_Count : Integer; l_Group : IevQueryGroup; //#UC END# *47CD842102B4_47CFEE9E02E1_var* begin //#UC START# *47CD842102B4_47CFEE9E02E1_impl* l_Count := f_GroupList.Count - 1; for i := 0 to l_Count do begin l_Group := f_GroupList[i]; try Result := l_Group.FindDescriptionReq(aReqName); if Result <> nil then Break; finally l_Group := nil; end; end; //#UC END# *47CD842102B4_47CFEE9E02E1_impl* end;//TevControlContainer.FindDescriptionReq procedure TevControlContainer.StartSetFocus; {* Возвращает первое доступное для редактирования поле в контроле. } //#UC START# *47CD843F005D_47CFEE9E02E1_var* var l_Control: IevEditorControl; //#UC END# *47CD843F005D_47CFEE9E02E1_var* begin //#UC START# *47CD843F005D_47CFEE9E02E1_impl* l_Control := evGetEditorControl(GetDocumentContainer.GetCurrPara); if Assigned(l_Control) and (l_Control.ControlType in evEditControls) then RememberFocusControl(l_Control) else if f_AdapterModel <> nil then IevAdapterModel(f_AdapterModel).FocusStartField else if f_GroupList.Count > 0 then f_GroupList.First.FirstReq.FirstField.SetFocus //#UC END# *47CD843F005D_47CFEE9E02E1_impl* end;//TevControlContainer.StartSetFocus function TevControlContainer.Get_QueryGroup(anIndex: Integer): IevQueryGroup; //#UC START# *47CD84520292_47CFEE9E02E1get_var* //#UC END# *47CD84520292_47CFEE9E02E1get_var* begin //#UC START# *47CD84520292_47CFEE9E02E1get_impl* Result := f_GroupList[anIndex]; //#UC END# *47CD84520292_47CFEE9E02E1get_impl* end;//TevControlContainer.Get_QueryGroup function TevControlContainer.Get_GroupCount: Integer; //#UC START# *47CD8478024F_47CFEE9E02E1get_var* //#UC END# *47CD8478024F_47CFEE9E02E1get_var* begin //#UC START# *47CD8478024F_47CFEE9E02E1get_impl* Result := f_GroupList.Count; //#UC END# *47CD8478024F_47CFEE9E02E1get_impl* end;//TevControlContainer.Get_GroupCount function TevControlContainer.pm_GetEditor: InevControl; //#UC START# *47CD84A1019A_47CFEE9E02E1get_var* var l_Containter : InevDocumentContainer; //#UC END# *47CD84A1019A_47CFEE9E02E1get_var* begin //#UC START# *47CD84A1019A_47CFEE9E02E1get_impl* //!!!Stub: Если нужно будет отображать документ в нескольких окнах, то это место нужно переделать! if (f_QueryContainer <> nil) and Supports(f_QueryContainer, InevDocumentContainer, l_Containter) then l_Containter.TextSource.CastAnyEditorTo(InevControl, Result) else Result := nil; //#UC END# *47CD84A1019A_47CFEE9E02E1get_impl* end;//TevControlContainer.pm_GetEditor function TevControlContainer.Get_InsertRowMode: Boolean; //#UC START# *47CD84BB0044_47CFEE9E02E1get_var* //#UC END# *47CD84BB0044_47CFEE9E02E1get_var* begin //#UC START# *47CD84BB0044_47CFEE9E02E1get_impl* Result := f_InsertRowMode; //#UC END# *47CD84BB0044_47CFEE9E02E1get_impl* end;//TevControlContainer.Get_InsertRowMode procedure TevControlContainer.Set_InsertRowMode(aValue: Boolean); //#UC START# *47CD84BB0044_47CFEE9E02E1set_var* //#UC END# *47CD84BB0044_47CFEE9E02E1set_var* begin //#UC START# *47CD84BB0044_47CFEE9E02E1set_impl* f_InsertRowMode := aValue; //#UC END# *47CD84BB0044_47CFEE9E02E1set_impl* end;//TevControlContainer.Set_InsertRowMode function TevControlContainer.pm_GetCardType: TevQueryType; //#UC START# *47CD84CC027E_47CFEE9E02E1get_var* //#UC END# *47CD84CC027E_47CFEE9E02E1get_var* begin //#UC START# *47CD84CC027E_47CFEE9E02E1get_impl* Result := TevQueryType(Para.AsObject.IntA[k2_tiCardType]); //#UC END# *47CD84CC027E_47CFEE9E02E1get_impl* end;//TevControlContainer.pm_GetCardType function TevControlContainer.GetControlIterator(const aCurrentControl: IevCustomEditorControl): IevControlIterator; //#UC START# *48B7F005003D_47CFEE9E02E1_var* //#UC END# *48B7F005003D_47CFEE9E02E1_var* begin //#UC START# *48B7F005003D_47CFEE9E02E1_impl* Result := TevControlIterator.Make(aCurrentControl, Self); //#UC END# *48B7F005003D_47CFEE9E02E1_impl* end;//TevControlContainer.GetControlIterator procedure TevControlContainer.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_47CFEE9E02E1_var* //#UC END# *479731C50290_47CFEE9E02E1_var* begin //#UC START# *479731C50290_47CFEE9E02E1_impl* f_LimitErrorControl := nil; f_UpperButtons := nil; f_StateControl := nil; f_StartFocusControl := nil; f_CurrPara := nil; if (f_QueryContainer <> nil) then f_QueryContainer.UnlinkListener(Self); f_QueryContainer := nil; f_AdapterModel := nil; l3Free(f_GroupList); inherited; //#UC END# *479731C50290_47CFEE9E02E1_impl* end;//TevControlContainer.Cleanup end.
unit Unit1; {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, EditBtn, LazFileUtils //CleanAndExpandDirectory ; type { TForm1 } TForm1 = class(TForm) ButtonStart: TButton; DirectoryEdit: TDirectoryEdit; Memo1: TMemo; procedure ButtonStartClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FindFilesRecursive(aPath: string); private fileCount : Longint; public end; const ROOTDIR='C:\lazarus\packages\Indy10'; OLD_PATTERN_1 = '{.$DEFINE FREE_ON_FINAL}'; NEW_PATTERN_1 = '{$DEFINE FREE_ON_FINAL}'; OLD_PATTERN_2 = '{$UNDEF FREE_ON_FINAL}'; NEW_PATTERN_2 = '{.$UNDEF FREE_ON_FINAL}'; var Form1: TForm1; implementation {$R *.lfm} { TForm1 } procedure DoEdit(sourceFile: string); var aList: TStringList; s: string; begin aList:=TStringList.Create; CopyFile(sourceFile, sourceFile + '.original'); try aList.LoadFromFile(sourceFile); s := aList.Text; s := StringReplace(s, OLD_PATTERN_1, NEW_PATTERN_1, [rfReplaceAll]); s := StringReplace(s, OLD_PATTERN_2, NEW_PATTERN_2, [rfReplaceAll]); aList.Text := s; aList.SaveToFile(sourceFile); finally aList.Free; end; end; procedure TForm1.FindFilesRecursive(aPath: string); var Info: TSearchRec; sourceFile: String; begin aPath:=CleanAndExpandDirectory(aPath); If FindFirst(aPath+GetAllFilesMask, faAnyFile, Info)=0 then begin repeat with Info do begin if (Name<>'.') and (Name<>'..') and (Name<>'') then begin If (Attr and faDirectory) >0 then begin sourceFile:=ExtractFilePath(aPath)+Name; FindFilesRecursive(sourceFile); end else begin sourceFile:=ExtractFilePath(aPath)+Name; if Name = 'IdCompilerDefines.inc' then begin Memo1.Append(sourceFile); DoEdit(sourceFile); Inc(fileCount); end; end; end; end; until FindNext(info)<>0; end; FindClose(Info); end; procedure TForm1.ButtonStartClick(Sender: TObject); var aPath: string; begin fileCount:=0; Memo1.Clear; aPath:=DirectoryEdit.Text; FindFilesRecursive(aPath); Memo1.Append(Format('Total Files Edited: %d Files',[fileCount])); end; procedure TForm1.FormShow(Sender: TObject); begin DirectoryEdit.Text:=ROOTDIR; end; end.
unit vcmBaseMenuManagerRes; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "VCM" // Автор: Люлин А.В. // Модуль: "w:/common/components/gui/Garant/VCM/implementation/vcmBaseMenuManagerRes.pas" // Начат: 04.03.2010 13:42 // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<UtilityPack::Class>> Shared Delphi::VCM::vcmL10nImpl::vcmBaseMenuManagerRes // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\common\components\gui\Garant\VCM\vcmDefine.inc} interface {$If not defined(NoVCM)} uses l3StringIDEx ; var { Локализуемые строки Local } str_vcmShowTab : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vcmShowTab'; rValue : 'Показать вкладку "%s"'); { 'Показать вкладку "%s"' } str_vcmHideTab : Tl3StringIDEx = (rS : -1; rLocalized : false; rKey : 'vcmHideTab'; rValue : 'Скрыть вкладку "%s"'); { 'Скрыть вкладку "%s"' } {$IfEnd} //not NoVCM implementation {$If not defined(NoVCM)} uses l3MessageID ; {$IfEnd} //not NoVCM initialization {$If not defined(NoVCM)} // Инициализация str_vcmShowTab str_vcmShowTab.Init; {$IfEnd} //not NoVCM {$If not defined(NoVCM)} // Инициализация str_vcmHideTab str_vcmHideTab.Init; {$IfEnd} //not NoVCM end.
{******************************************************************************} { } { Delphi FB4D Library } { Copyright (c) 2018-2023 Christoph Schneider } { Schneider Infosystems AG, Switzerland } { https://github.com/SchneiderInfosystems/FB4D } { } {******************************************************************************} { } { Licensed under the Apache License, Version 2.0 (the "License"); } { you may not use this file except in compliance with the License. } { You may obtain a copy of the License at } { } { http://www.apache.org/licenses/LICENSE-2.0 } { } { Unless required by applicable law or agreed to in writing, software } { distributed under the License is distributed on an "AS IS" BASIS, } { WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. } { See the License for the specific language governing permissions and } { limitations under the License. } { } {******************************************************************************} unit FB4D.Interfaces; interface uses System.Classes, System.Types, System.SysUtils, System.JSON, {$IFNDEF LINUX64} System.Sensors, {$ENDIF} System.Generics.Collections, {$IFDEF TOKENJWT} JOSE.Core.JWT, {$ENDIF} REST.Types, FB4D.VisionMLDefinition; {$IFDEF LINUX64} {$I LinuxTypeDecl.inc} {$ENDIF} const cDefaultCacheSpaceInBytes = 536870912; // 500 MByte cDefaultDatabaseID = '(default)'; cRegionUSCent1 = 'us-central1'; // Iowa cRegionUSEast1 = 'us-east1'; // South Carolina cRegionUSEast4 = 'us-east4'; // Nothern Virginia cRegionUSWest2 = 'us-west2'; // Los Angeles cRegionUSWest3 = 'us-west3'; // Salt Lake City cRegionUSWest4 = 'us-west4'; // Las Vegas cRegionUSNoEa1 = 'northamerica-northeast1'; // Montreal cRegionUSSoEa1 = 'southamerica-east1'; // Sao Paulo cRegionEUWest1 = 'europe-west1'; // Belgium cRegionEUWest2 = 'europe-west2'; // London cRegionEUWest3 = 'europe-west3'; // Frankfurt cRegionEUWest6 = 'europe-west6'; // Zürich cRegionEUCent2 = 'europe-central2'; // Warsaw cRegionAUSoEa1 = 'australia-southeast1'; // Sydney cRegionASEast1 = 'asia-east1'; // Taiwan cRegionASEast2 = 'asia-east2'; // Hong Kong cRegionASNoEa1 = 'asia-northeast1'; // Tokyo cRegionASNoEa2 = 'asia-northeast2'; // Osaka cRegionASSout1 = 'asia-south1'; // Mumbai cRegionASSoEa1 = 'asia-southeast1'; // Singapore cRegionASSoEa2 = 'asia-southeast2'; // Jakarta cRegionASSoEa3 = 'asia-southeast3'; // Seoul type /// <summary> /// Firebase returns timestamps in UTC time zone (tzUTC). FB4D offers the /// or convertion into local time by tzLocalTime. /// </summary> TTimeZone = (tzUTC, tzLocalTime); /// <summary> /// Exception for IFirebaseRespone /// </summary> EFirebaseResponse = class(Exception); IFirebaseUser = interface; IFirebaseResponse = interface; IFirestoreDocument = interface; IFirestoreDocuments = interface; IStorageObject = interface; TOnRequestError = procedure(const RequestID, ErrMsg: string) of object; TRequestResourceParam = TStringDynArray; TOnFirebaseResp = procedure(const RequestID: string; Response: IFirebaseResponse) of object; TFirebaseUserList = TList<IFirebaseUser>; TPasswordVerificationResult = (pvrOpNotAllowed, pvrPassed, pvrpvrExpired, pvrInvalid); TOnUserResponse = procedure(const Info: string; User: IFirebaseUser) of object; TOnFetchProviders = procedure(const RequestID: string; IsRegistered: boolean; Providers: TStrings) of object; TOnPasswordVerification = procedure(const Info: string; Result: TPasswordVerificationResult) of object; TOnGetUserData = procedure(FirebaseUserList: TFirebaseUserList) of object; TOnTokenRefresh = procedure(TokenRefreshed: boolean) of object; TOnRTDBValue = procedure(ResourceParams: TRequestResourceParam; Val: TJSONValue) of object; TOnRTDBDelete = procedure(Params: TRequestResourceParam; Success: boolean) of object; TOnRTDBServerVariable = procedure(const ServerVar: string; Val: TJSONValue) of object; TOnDocument = procedure(const Info: string; Document: IFirestoreDocument) of object; TOnDocuments = procedure(const Info: string; Documents: IFirestoreDocuments) of object; TFirestoreReadTransaction = string; // A base64 encoded ID TOnBeginReadTransaction = procedure(Transaction: TFirestoreReadTransaction) of object; IFirestoreCommitTransaction = interface function CommitTime(TimeZone: TTimeZone = tzUTC): TDateTime; function NoUpdates: cardinal; function UpdateTime(Index: cardinal; TimeZone: TTimeZone = tzUTC): TDateTime; end; TOnCommitWriteTransaction = procedure(Transaction: IFirestoreCommitTransaction) of object; TObjectName = string; TOnStorage = procedure(Obj: IStorageObject) of object; TOnStorageDeprecated = procedure(const ObjectName: TObjectName; Obj: IStorageObject) of object; TOnStorageError = procedure(const ObjectName: TObjectName; const ErrMsg: string) of object; TOnDeleteStorage = procedure(const ObjectName: TObjectName) of object; TOnFunctionSuccess = procedure(const Info: string; ResultObj: TJSONObject) of object; IVisionMLResponse = interface; TOnAnnotate = procedure(Res: IVisionMLResponse) of object; TOnSuccess = record type TOnSuccessCase = (oscUndef, oscFB, oscUser, oscFetchProvider, oscPwdVerification, oscGetUserData, oscRefreshToken, oscRTDBValue, oscRTDBDelete, oscRTDBServerVariable, oscDocument, oscDocuments, oscBeginReadTransaction, oscCommitWriteTransaction, oscStorage, oscStorageDeprecated, oscStorageUpload, oscStorageGetAndDown, oscDelStorage, oscFunctionSuccess, oscVisionML); constructor Create(OnResp: TOnFirebaseResp); constructor CreateUser(OnUserResp: TOnUserResponse); constructor CreateFetchProviders(OnFetchProvidersResp: TOnFetchProviders); constructor CreatePasswordVerification( OnPasswordVerificationResp: TOnPasswordVerification); constructor CreateGetUserData(OnGetUserDataResp: TOnGetUserData); constructor CreateRefreshToken(OnRefreshTokenResp: TOnTokenRefresh); constructor CreateRTDBValue(OnRTDBValueResp: TOnRTDBValue); constructor CreateRTDBDelete(OnRTDBDeleteResp: TOnRTDBDelete); constructor CreateRTDBServerVariable( OnRTDBServerVariableResp: TOnRTDBServerVariable); constructor CreateFirestoreDoc(OnDocumentResp: TOnDocument); constructor CreateFirestoreDocs(OnDocumentsResp: TOnDocuments); constructor CreateFirestoreReadTransaction( OnBeginReadTransactionResp: TOnBeginReadTransaction); constructor CreateFirestoreCommitWriteTransaction( OnCommitTransaction: TOnCommitWriteTransaction); constructor CreateStorage(OnStorageResp: TOnStorage); constructor CreateStorageDeprecated(OnStorageResp: TOnStorageDeprecated); constructor CreateStorageGetAndDownload(OnStorageResp: TOnStorage; OnStorageErrorResp: TOnRequestError; Stream: TStream); constructor CreateStorageUpload(OnStorageResp: TOnStorage; Stream: TStream); constructor CreateDelStorage(OnDelStorageResp: TOnDeleteStorage); constructor CreateFunctionSuccess(OnFunctionSuccessResp: TOnFunctionSuccess); constructor CreateVisionML(OnAnnotateResp: TOnAnnotate); {$IFNDEF AUTOREFCOUNT} case OnSuccessCase: TOnSuccessCase of oscFB: (OnResponse: TOnFirebaseResp); oscUser: (OnUserResponse: TOnUserResponse); oscFetchProvider: (OnFetchProviders: TOnFetchProviders); oscPwdVerification: (OnPasswordVerification: TOnPasswordVerification); oscGetUserData: (OnGetUserData: TOnGetUserData); oscRefreshToken: (OnRefreshToken: TOnTokenRefresh); oscRTDBValue: (OnRTDBValue: TOnRTDBValue); oscRTDBDelete: (OnRTDBDelete: TOnRTDBDelete); oscRTDBServerVariable: (OnRTDBServerVariable: TOnRTDBServerVariable); oscDocument: (OnDocument: TOnDocument); oscDocuments: (OnDocuments: TOnDocuments); oscBeginReadTransaction: (OnBeginReadTransaction: TOnBeginReadTransaction); oscCommitWriteTransaction: (OnCommitWriteTransaction: TOnCommitWriteTransaction); oscStorage: (OnStorage: TOnStorage); oscStorageDeprecated: (OnStorageDeprecated: TOnStorageDeprecated); oscStorageGetAndDown: (OnStorageGetAndDown: TOnStorage; OnStorageError: TOnRequestError; DownStream: TStream); oscStorageUpload: (OnStorageUpload: TOnStorage; UpStream: TStream); oscDelStorage: (OnDelStorage: TOnDeleteStorage); oscFunctionSuccess: (OnFunctionSuccess: TOnFunctionSuccess); oscVisionML: (OnAnnotate: TOnAnnotate); {$ELSE} var OnSuccessCase: TOnSuccessCase; OnResponse: TOnFirebaseResp; OnUserResponse: TOnUserResponse; OnFetchProviders: TOnFetchProviders; OnPasswordVerification: TOnPasswordVerification; OnGetUserData: TOnGetUserData; OnRefreshToken: TOnTokenRefresh; OnRTDBValue: TOnRTDBValue; OnRTDBDelete: TOnRTDBDelete; OnRTDBServerVariable: TOnRTDBServerVariable; OnDocument: TOnDocument; OnDocuments: TOnDocuments; OnBeginReadTransaction: TOnBeginReadTransaction; OnCommitWriteTransaction: TOnCommitWriteTransaction; OnStorage: TOnStorage; OnStorageDeprecated: TOnStorageDeprecated; OnStorageGetAndDown: TOnStorage; OnStorageError: TOnRequestError; DownStream: TStream; OnStorageUpload: TOnStorage; UpStream: TStream; OnDelStorage: TOnDeleteStorage; OnFunctionSuccess: TOnFunctionSuccess; OnAnnotate: TOnAnnotate; {$ENDIF} end; /// <summary> /// Interface for handling REST response from all Firebase Services /// </summary> IFirebaseResponse = interface(IInterface) function ContentAsString: string; function GetContentAsJSONObj: TJSONObject; function GetContentAsJSONArr: TJSONArray; function GetContentAsJSONVal: TJSONValue; procedure CheckForJSONObj; function IsJSONObj: boolean; procedure CheckForJSONArr; function StatusOk: boolean; function StatusIsUnauthorized: boolean; function StatusNotFound: boolean; function StatusCode: integer; function StatusText: string; function ErrorMsg: string; function ErrorMsgOrStatusText: string; function GetServerTime(TimeZone: TTimeZone): TDateTime; function GetOnSuccess: TOnSuccess; function GetOnError: TOnRequestError; function HeaderValue(const HeaderName: string): string; property OnSuccess: TOnSuccess read GetOnSuccess; property OnError: TOnRequestError read GetOnError; end; TQueryParams = TDictionary<string, TStringDynArray>; TTokenMode = (tmNoToken, tmBearer, tmAuthParam); IFirebaseRequest = interface; IFirebaseRequest = interface(IInterface) procedure SendRequest(ResourceParams: TRequestResourceParam; Method: TRESTRequestMethod; Data: TJSONValue; QueryParams: TQueryParams; TokenMode: TTokenMode; OnResponse: TOnFirebaseResp; OnRequestError: TOnRequestError; OnSuccess: TOnSuccess); overload; procedure SendRequest(ResourceParams: TRequestResourceParam; Method: TRESTRequestMethod; Data: TStream; ContentType: TRESTContentType; QueryParams: TQueryParams; TokenMode: TTokenMode; OnResponse: TOnFirebaseResp; OnRequestError: TOnRequestError; OnSuccess: TOnSuccess); overload; function SendRequestSynchronous(ResourceParams: TRequestResourceParam; Method: TRESTRequestMethod; Data: TJSONValue = nil; QueryParams: TQueryParams = nil; TokenMode: TTokenMode = tmBearer): IFirebaseResponse; overload; function SendRequestSynchronous(ResourceParams: TRequestResourceParam; Method: TRESTRequestMethod; Data: TStream; ContentType: TRESTContentType; QueryParams: TQueryParams = nil; TokenMode: TTokenMode = tmBearer): IFirebaseResponse; overload; end; IFirebaseEvent = interface(IInterface) procedure StopListening(MaxTimeOutInMS: cardinal = 500); overload; procedure StopListening(const NodeName: string; MaxTimeOutInMS: cardinal = 500); overload; deprecated; function GetResourceParams: TRequestResourceParam; function GetLastReceivedMsg: TDateTime; // Local time function IsStopped: boolean; end; TOnReceiveEvent = procedure(const Event: string; Params: TRequestResourceParam; JSONObj: TJSONObject) of object; TOnStopListenEvent = TNotifyEvent; TOnAuthRevokedEvent = procedure(TokenRenewPassed: boolean) of object; TOnConnectionStateChange = procedure(ListenerConnected: boolean) of object; ERTDBListener = class(Exception); IRealTimeDB = interface(IInterface) procedure Get(ResourceParams: TRequestResourceParam; OnGetValue: TOnRTDBValue; OnRequestError: TOnRequestError; QueryParams: TQueryParams = nil); function GetSynchronous(ResourceParams: TRequestResourceParam; QueryParams: TQueryParams = nil): TJSONValue; // The caller has to free the TJSONValue procedure Put(ResourceParams: TRequestResourceParam; Data: TJSONValue; OnPutValue: TOnRTDBValue; OnRequestError: TOnRequestError; QueryParams: TQueryParams = nil); function PutSynchronous(ResourceParams: TRequestResourceParam; Data: TJSONValue; QueryParams: TQueryParams = nil): TJSONValue; // The caller has to free the TJSONValue procedure Post(ResourceParams: TRequestResourceParam; Data: TJSONValue; OnPostValue: TOnRTDBValue; OnRequestError: TOnRequestError; QueryParams: TQueryParams = nil); function PostSynchronous(ResourceParams: TRequestResourceParam; Data: TJSONValue; QueryParams: TQueryParams = nil): TJSONValue; // The caller has to free the TJSONValue procedure Patch(ResourceParams: TRequestResourceParam; Data: TJSONValue; OnPatchValue: TOnRTDBValue; OnRequestError: TOnRequestError; QueryParams: TQueryParams = nil); function PatchSynchronous(ResourceParams: TRequestResourceParam; Data: TJSONValue; QueryParams: TQueryParams = nil): TJSONValue; // The caller has to free the TJSONValue procedure Delete(ResourceParams: TRequestResourceParam; OnDelete: TOnRTDBDelete; OnRequestError: TOnRequestError; QueryParams: TQueryParams); overload; deprecated 'Use delete method without QueryParams instead'; procedure Delete(ResourceParams: TRequestResourceParam; OnDelete: TOnRTDBDelete; OnRequestError: TOnRequestError); overload; function DeleteSynchronous(ResourceParams: TRequestResourceParam; QueryParams: TQueryParams): boolean; overload; deprecated 'Use delete method without QueryParams instead'; function DeleteSynchronous( ResourceParams: TRequestResourceParam): boolean; overload; // long time running request function ListenForValueEvents(ResourceParams: TRequestResourceParam; ListenEvent: TOnReceiveEvent; OnStopListening: TOnStopListenEvent; OnError: TOnRequestError; OnAuthRevoked: TOnAuthRevokedEvent = nil; OnConnectionStateChange: TOnConnectionStateChange = nil; DoNotSynchronizeEvents: boolean = false): IFirebaseEvent; // To retrieve server variables like timestamp and future variables procedure GetServerVariables(const ServerVarName: string; ResourceParams: TRequestResourceParam; OnServerVariable: TOnRTDBServerVariable = nil; OnError: TOnRequestError = nil); function GetServerVariablesSynchronous(const ServerVarName: string; ResourceParams: TRequestResourceParam): TJSONValue; end; EFirestoreDocument = class(Exception); TJSONObjects = array of TJSONObject; TFirestoreFieldType = (fftNull, fftBoolean, fftInteger, fftDouble, fftTimeStamp, fftString, fftBytes, fftReference, fftGeoPoint, fftArray, fftMap); IFirestoreDocument = interface(IInterface) function DocumentName(FullPath: boolean): string; function DocumentFullPath: TRequestResourceParam; function DocumentPathWithinDatabase: TRequestResourceParam; function CreateTime(TimeZone: TTimeZone = tzUTC): TDateTime; function UpdateTime(TimeZone: TTimeZone = tzUTC): TDatetime; function CountFields: integer; function FieldName(Ind: integer): string; function FieldByName(const FieldName: string): TJSONObject; function FieldValue(Ind: integer): TJSONObject; function FieldType(Ind: integer): TFirestoreFieldType; function FieldTypeByName(const FieldName: string): TFirestoreFieldType; function AllFields: TStringDynArray; function GetValue(Ind: integer): TJSONValue; overload; function GetValue(const FieldName: string): TJSONValue; overload; function GetStringValue(const FieldName: string): string; function GetStringValueDef(const FieldName, Default: string): string; function GetIntegerValue(const FieldName: string): integer; function GetIntegerValueDef(const FieldName: string; Default: integer): integer; function GetInt64Value(const FieldName: string): Int64; function GetInt64ValueDef(const FieldName: string; Default: Int64): Int64; function GetDoubleValue(const FieldName: string): double; function GetDoubleValueDef(const FieldName: string; Default: double): double; function GetBoolValue(const FieldName: string): boolean; function GetBoolValueDef(const FieldName: string; Default: boolean): boolean; function GetTimeStampValue(const FieldName: string; TimeZone: TTimeZone = tzUTC): TDateTime; function GetTimeStampValueDef(const FieldName: string; Default: TDateTime; TimeZone: TTimeZone = tzUTC): TDateTime; function GetGeoPoint(const FieldName: string): TLocationCoord2D; function GetReference(const FieldName: string): string; function GetBytes(const FieldName: string): TBytes; function GetArrayValues(const FieldName: string): TJSONObjects; function GetArrayMapValues(const FieldName: string): TJSONObjects; function GetArrayStringValues(const FieldName: string): TStringDynArray; function GetArraySize(const FieldName: string): integer; function GetArrayType(const FieldName: string; Index: integer): TFirestoreFieldType; function GetArrayItem(const FieldName: string; Index: integer): TJSONPair; function GetArrayValue(const FieldName: string; Index: integer): TJSONValue; function GetMapSize(const FieldName: string): integer; function GetMapType(const FieldName: string; Index: integer): TFirestoreFieldType; function GetMapSubFieldName(const FieldName: string; Index: integer): string; function GetMapValue(const FieldName: string; Index: integer): TJSONObject; overload; function GetMapValue(const FieldName, SubFieldName: string): TJSONObject; overload; function GetMapValues(const FieldName: string): TJSONObjects; function AddOrUpdateField(Field: TJSONPair): IFirestoreDocument; overload; function AddOrUpdateField(const FieldName: string; Val: TJSONValue): IFirestoreDocument; overload; function AsJSON: TJSONObject; function Clone: IFirestoreDocument; property Fields[Index: integer]: TJSONObject read FieldValue; end; IFirestoreDocuments = interface(IEnumerable<IFirestoreDocument>) function Count: integer; function Document(Ind: integer): IFirestoreDocument; function ServerTimeStamp(TimeZone: TTimeZone): TDateTime; function SkippedResults: integer; function MorePagesToLoad: boolean; function PageToken: string; procedure AddPageTokenToNextQuery(Query: TQueryParams); end; TWhereOperator = (woUnspecific, woLessThan, woLessThanOrEqual, woGreaterThan, woGreaterThanOrEqual, woEqual, woArrayContains); IQueryFilter = interface(IInterface) procedure AddPair(const Str: string; Val: TJSONValue); overload; procedure AddPair(const Str, Val: string); overload; function AsJSON: TJSONObject; function GetInfo: string; end; TCompostiteOperation = (coUnspecific, coAnd); TOrderDirection = (odUnspecified, odAscending, odDescending); IStructuredQuery = interface(IInterface) function Select(FieldRefs: TRequestResourceParam): IStructuredQuery; function Collection(const CollectionId: string; IncludesDescendants: boolean = false): IStructuredQuery; function QueryForFieldFilter(Filter: IQueryFilter): IStructuredQuery; function QueryForCompositeFilter(CompostiteOperation: TCompostiteOperation; Filters: array of IQueryFilter): IStructuredQuery; function OrderBy(const FieldRef: string; Direction: TOrderDirection): IStructuredQuery; function StartAt(Cursor: IFirestoreDocument; Before: boolean): IStructuredQuery; function EndAt(Cursor: IFirestoreDocument; Before: boolean): IStructuredQuery; function Limit(limit: integer): IStructuredQuery; function Offset(offset: integer): IStructuredQuery; function AsJSON: TJSONObject; function GetInfo: string; function HasSelect: boolean; function HasColSelector: boolean; function HasFilter: boolean; function HasOrder: boolean; function HasStartAt: boolean; function HasEndAt: boolean; end; TOnChangedDocument = procedure(ChangedDocument: IFirestoreDocument) of object; TOnDeletedDocument = procedure(const DeleteDocumentPath: string; TimeStamp: TDateTime) of object; IFirestoreWriteTransaction = interface procedure UpdateDoc(Document: IFirestoreDocument); procedure PatchDoc(Document: IFirestoreDocument; UpdateMask: TStringDynArray); end; EFirestoreListener = class(Exception); EFirestoreDatabase = class(Exception); IFirestoreDatabase = interface(IInterface) procedure RunQuery(StructuredQuery: IStructuredQuery; OnDocuments: TOnDocuments; OnRequestError: TOnRequestError; QueryParams: TQueryParams = nil); overload; procedure RunQuery(DocumentPath: TRequestResourceParam; StructuredQuery: IStructuredQuery; OnDocuments: TOnDocuments; OnRequestError: TOnRequestError; QueryParams: TQueryParams = nil); overload; function RunQuerySynchronous(StructuredQuery: IStructuredQuery; QueryParams: TQueryParams = nil): IFirestoreDocuments; overload; function RunQuerySynchronous(DocumentPath: TRequestResourceParam; StructuredQuery: IStructuredQuery; QueryParams: TQueryParams = nil): IFirestoreDocuments; overload; procedure Get(Params: TRequestResourceParam; QueryParams: TQueryParams; OnDocuments: TOnDocuments; OnRequestError: TOnRequestError); function GetSynchronous(Params: TRequestResourceParam; QueryParams: TQueryParams = nil): IFirestoreDocuments; function GetAndAddSynchronous(var Docs: IFirestoreDocuments; Params: TRequestResourceParam; QueryParams: TQueryParams = nil): boolean; procedure CreateDocument(DocumentPath: TRequestResourceParam; QueryParams: TQueryParams; OnDocument: TOnDocument; OnRequestError: TOnRequestError); function CreateDocumentSynchronous(DocumentPath: TRequestResourceParam; QueryParams: TQueryParams = nil): IFirestoreDocument; procedure InsertOrUpdateDocument(DocumentPath: TRequestResourceParam; Document: IFirestoreDocument; QueryParams: TQueryParams; OnDocument: TOnDocument; OnRequestError: TOnRequestError); function InsertOrUpdateDocumentSynchronous( DocumentPath: TRequestResourceParam; Document: IFirestoreDocument; QueryParams: TQueryParams = nil): IFirestoreDocument; procedure PatchDocument(DocumentPath: TRequestResourceParam; DocumentPart: IFirestoreDocument; UpdateMask: TStringDynArray; OnDocument: TOnDocument; OnRequestError: TOnRequestError; Mask: TStringDynArray = []); function PatchDocumentSynchronous(DocumentPath: TRequestResourceParam; DocumentPart: IFirestoreDocument; UpdateMask: TStringDynArray; Mask: TStringDynArray = []): IFirestoreDocument; procedure Delete(Params: TRequestResourceParam; QueryParams: TQueryParams; OnDeleteResponse: TOnFirebaseResp; OnRequestError: TOnRequestError); function DeleteSynchronous(Params: TRequestResourceParam; QueryParams: TQueryParams = nil): IFirebaseResponse; // Listener subscription function SubscribeDocument(DocumentPath: TRequestResourceParam; OnChangedDoc: TOnChangedDocument; OnDeletedDoc: TOnDeletedDocument): cardinal; function SubscribeQuery(Query: IStructuredQuery; OnChangedDoc: TOnChangedDocument; OnDeletedDoc: TOnDeletedDocument; DocPath: TRequestResourceParam = []): cardinal; procedure Unsubscribe(TargetID: cardinal); procedure StartListener(OnStopListening: TOnStopListenEvent; OnError: TOnRequestError; OnAuthRevoked: TOnAuthRevokedEvent = nil; OnConnectionStateChange: TOnConnectionStateChange = nil; DoNotSynchronizeEvents: boolean = false); procedure StopListener(RemoveAllSubscription: boolean = true); function GetTimeStampOfLastAccess: TDateTime; // local time // Transaction procedure BeginReadTransaction( OnBeginReadTransaction: TOnBeginReadTransaction; OnRequestError: TOnRequestError); function BeginReadTransactionSynchronous: TFirestoreReadTransaction; function BeginWriteTransaction: IFirestoreWriteTransaction; function CommitWriteTransactionSynchronous( Transaction: IFirestoreWriteTransaction): IFirestoreCommitTransaction; procedure CommitWriteTransaction(Transaction: IFirestoreWriteTransaction; OnCommitWriteTransaction: TOnCommitWriteTransaction; OnRequestError: TOnRequestError); end; {$IFDEF TOKENJWT} ETokenJWT = class(Exception); /// <summary> /// Usually you do not need to create an instance of the class TTokenJWT by /// yourself because you get an object with this interface in by the getter /// method IFirebaseAuthentication.TokenJWT /// </summary> ITokenJWT = interface(IInterface) function VerifySignature: boolean; function GetHeader: TJWTHeader; function GetClaims: TJWTClaims; property Header: TJWTHeader read GetHeader; property Claims: TJWTClaims read GetClaims; end; {$ENDIF} EFirebaseUser = class(Exception); TThreeStateBoolean = (tsbTrue, tsbFalse, tsbUnspecified); TProviderInfo = record ProviderId: string; FederatedId: string; RawId: string; DisplayName: string; Email: string; ScreenName: string; end; /// <summary> /// The IFirebaseUser interface provides only getter functions that are used /// to retrieve details of the user profile and the access token. /// </summary> IFirebaseUser = interface(IInterface) // Get User Identification function UID: string; // Get EMail Address function IsEMailAvailable: boolean; function IsEMailRegistered: TThreeStateBoolean; function IsEMailVerified: TThreeStateBoolean; function EMail: string; // Get User Display Name function DisplayName: string; function IsDisplayNameAvailable: boolean; // Get Photo URL for User Avatar or Photo function IsPhotoURLAvailable: boolean; function PhotoURL: string; // Get User Account State and Timestamps function IsDisabled: TThreeStateBoolean; function IsNewSignupUser: boolean; function IsLastLoginAtAvailable: boolean; function LastLoginAt(TimeZone: TTimeZone = tzLocalTime): TDateTime; function IsCreatedAtAvailable: boolean; function CreatedAt(TimeZone: TTimeZone = tzLocalTime): TDateTime; // Provider User Info function ProviderCount: integer; function Provider(ProviderNo: integer): TProviderInfo; // In case of OAuth sign-in function OAuthFederatedId: string; function OAuthProviderId: string; function OAuthIdToken: string; function OAuthAccessToken: string; function OAuthTokenSecret: string; function OAuthRawUserInfo: string; // Get Token Details and Claim Fields function Token: string; {$IFDEF TOKENJWT} function TokenJWT: ITokenJWT; function ClaimFieldNames: TStrings; function ClaimField(const FieldName: string): TJSONValue; {$ENDIF} function ExpiresAt: TDateTime; // local time function RefreshToken: string; end; EFirebaseAuthentication = class(Exception); /// <summary> /// The interface IFirebaseAuthentication provides all functions for accessing /// the Firebase Authentication Service. The interface will be created by the /// constructor of the class TFirebaseAuthentication in the unit /// FB4D.Authentication. The constructor expects the web API key of the /// Firebase project as parameter. /// </summary> IFirebaseAuthentication = interface(IInterface) // Create new User with email and password procedure SignUpWithEmailAndPassword(const Email, Password: string; OnUserResponse: TOnUserResponse; OnError: TOnRequestError); function SignUpWithEmailAndPasswordSynchronous(const Email, Password: string): IFirebaseUser; // Login procedure SignInWithEmailAndPassword(const Email, Password: string; OnUserResponse: TOnUserResponse; OnError: TOnRequestError); function SignInWithEmailAndPasswordSynchronous(const Email, Password: string): IFirebaseUser; procedure SignInAnonymously(OnUserResponse: TOnUserResponse; OnError: TOnRequestError); function SignInAnonymouslySynchronous: IFirebaseUser; // Link new email/password access to anonymous user procedure LinkWithEMailAndPassword(const EMail, Password: string; OnUserResponse: TOnUserResponse; OnError: TOnRequestError); function LinkWithEMailAndPasswordSynchronous(const EMail, Password: string): IFirebaseUser; // Login by using OAuth from Facebook, Twitter, Google, etc. procedure LinkOrSignInWithOAuthCredentials(const OAuthTokenName, OAuthToken, ProviderID, RequestUri: string; OnUserResponse: TOnUserResponse; OnError: TOnRequestError); function LinkOrSignInWithOAuthCredentialsSynchronous(const OAuthTokenName, OAuthToken, ProviderID, RequestUri: string): IFirebaseUser; // Logout procedure SignOut; // Send EMail for EMail Verification procedure SendEmailVerification(OnResponse: TOnFirebaseResp; OnError: TOnRequestError); procedure SendEmailVerificationSynchronous; // Providers procedure FetchProvidersForEMail(const EMail: string; OnFetchProviders: TOnFetchProviders; OnError: TOnRequestError); function FetchProvidersForEMailSynchronous(const EMail: string; Providers: TStrings): boolean; // returns true if EMail is registered procedure DeleteProviders(Providers: TStrings; OnProviderDeleted: TOnFirebaseResp; OnError: TOnRequestError); function DeleteProvidersSynchronous(Providers: TStrings): boolean; // Reset Password procedure SendPasswordResetEMail(const Email: string; OnResponse: TOnFirebaseResp; OnError: TOnRequestError); procedure SendPasswordResetEMailSynchronous(const Email: string); procedure VerifyPasswordResetCode(const ResetPasswortCode: string; OnPasswordVerification: TOnPasswordVerification; OnError: TOnRequestError); function VerifyPasswordResetCodeSynchronous(const ResetPasswortCode: string): TPasswordVerificationResult; procedure ConfirmPasswordReset(const ResetPasswortCode, NewPassword: string; OnResponse: TOnFirebaseResp; OnError: TOnRequestError); procedure ConfirmPasswordResetSynchronous(const ResetPasswortCode, NewPassword: string); // Change password, Change email, Update Profile Data // let field empty which shall not be changed procedure ChangeProfile(const EMail, Password, DisplayName, PhotoURL: string; OnResponse: TOnFirebaseResp; OnError: TOnRequestError); procedure ChangeProfileSynchronous(const EMail, Password, DisplayName, PhotoURL: string); // Delete signed in user account procedure DeleteCurrentUser(OnResponse: TOnFirebaseResp; OnError: TOnRequestError); procedure DeleteCurrentUserSynchronous; // Get User Data procedure GetUserData(OnGetUserData: TOnGetUserData; OnError: TOnRequestError); function GetUserDataSynchronous: TFirebaseUserList; // Token refresh procedure RefreshToken(OnTokenRefresh: TOnTokenRefresh; OnError: TOnRequestError); overload; procedure RefreshToken(const LastRefreshToken: string; OnTokenRefresh: TOnTokenRefresh; OnError: TOnRequestError); overload; function CheckAndRefreshTokenSynchronous( IgnoreExpiryCheck: boolean = false): boolean; // register call back in all circumstances when the token will be refreshed procedure InstallTokenRefreshNotification(OnTokenRefresh: TOnTokenRefresh); // Getter methods function Authenticated: boolean; function Token: string; {$IFDEF TOKENJWT} function TokenJWT: ITokenJWT; {$ENDIF} function TokenExpiryDT: TDateTime; // local time function NeedTokenRefresh: boolean; function GetRefreshToken: string; function GetTokenRefreshCount: cardinal; function GetLastServerTime(TimeZone: TTimeZone = tzLocalTime): TDateTime; end; EFirebaseFunctions = class(Exception); IFirebaseFunctions = interface(IInterface) procedure CallFunction(OnSuccess: TOnFunctionSuccess; OnRequestError: TOnRequestError; const FunctionName: string; Params: TJSONObject = nil); function CallFunctionSynchronous(const FunctionName: string; Params: TJSONObject = nil): TJSONObject; end; TOnDownload = procedure(Obj: IStorageObject) of object; TOnDownloadDeprecated = procedure(const ObjectName: TObjectName; Obj: IStorageObject) of object; TOnDownloadError = procedure(Obj: IStorageObject; const ErrorMsg: string) of object; EStorageObject = class(Exception); IStorageObject = interface(IInterface) procedure DownloadToStream(Stream: TStream; OnSuccess: TOnDownload; OnError: TOnDownloadError); overload; procedure DownloadToStream(Stream: TStream; OnSuccess: TOnDownload; OnError: TOnStorageError); overload; procedure DownloadToStream(const ObjectName: TObjectName; Stream: TStream; OnSuccess: TOnDownloadDeprecated; OnError: TOnDownloadError); overload; deprecated 'Use method without ObjectName instead'; procedure DownloadToStreamSynchronous(Stream: TStream); function ObjectName(IncludePath: boolean = true): string; function Path: string; function LastPathElement: string; function ContentType: string; function Size: Int64; function Bucket: string; function createTime(TimeZone: TTimeZone = tzLocalTime): TDateTime; function updateTime(TimeZone: TTimeZone = tzLocalTime): TDatetime; function DownloadUrl: string; function DownloadToken: string; function MD5HashCode: string; function storageClass: string; function etag: string; function generation: Int64; function metaGeneration: Int64; function CacheFileName: string; end; IFirebaseStorage = interface(IInterface) procedure Get(const ObjectName: TObjectName; OnGetStorage: TOnStorage; OnGetError: TOnStorageError); overload; procedure Get(const ObjectName, RequestID: string; OnGetStorage: TOnStorageDeprecated; OnGetError: TOnRequestError); overload; deprecated 'Use method without RequestID instead'; function GetSynchronous(const ObjectName: TObjectName): IStorageObject; procedure GetAndDownload(const ObjectName: TObjectName; Stream: TStream; OnGetStorage: TOnStorage; OnGetError: TOnRequestError); function GetAndDownloadSynchronous(const ObjectName: TObjectName; Stream: TStream): IStorageObject; procedure Delete(const ObjectName: TObjectName; OnDelete: TOnDeleteStorage; OnDelError: TOnStorageError); procedure DeleteSynchronous(const ObjectName: TObjectName); procedure UploadFromStream(Stream: TStream; const ObjectName: TObjectName; ContentType: TRESTContentType; OnUpload: TOnStorage; OnUploadError: TOnStorageError); function UploadSynchronousFromStream(Stream: TStream; const ObjectName: TObjectName; ContentType: TRESTContentType): IStorageObject; // Long-term storage (beyond the runtime of the app) of loaded storage files procedure SetupCacheFolder(const FolderName: string; MaxCacheSpaceInBytes: Int64 = cDefaultCacheSpaceInBytes); function IsCacheInUse: boolean; function IsCacheScanFinished: boolean; function GetObjectFromCache(const ObjectName: TObjectName): IStorageObject; function GetFileFromCache(const ObjectName: TObjectName): TStream; procedure ClearCache; function CacheUsageInPercent: extended; function IsCacheOverflowed: boolean; end; TVisionMLFeature = (vmlUnspecific, vmlFaceDetection, vmlLandmarkDetection, vmlLogoDetection, vmlLabelDetection, vmlTextDetection, vmlDocTextDetection, vmlSafeSearchDetection, vmlImageProperties, vmlCropHints, vmlWebDetection, vmlProductSearch, vmlObjectLocalization); TVisionMLFeatures = set of TVisionMLFeature; IVisionMLResponse = interface(IInterface) function GetFormatedJSON: string; function GetNoPages: integer; function GetPageAsFormatedJSON(PageNo: integer = 0): string; function GetError(PageNo: integer = 0): TErrorStatus; function LabelAnnotations(PageNo: integer = 0): TAnnotationList; function LandmarkAnnotations(PageNo: integer = 0): TAnnotationList; function LogoAnnotations(PageNo: integer = 0): TAnnotationList; function TextAnnotations(PageNo: integer = 0): TAnnotationList; function FullTextAnnotations(PageNo: integer = 0): TTextAnnotation; function ImagePropAnnotation( PageNo: integer = 0): TImagePropertiesAnnotation; function CropHintsAnnotation(PageNo: integer = 0): TCropHintsAnnotation; function WebDetection(PageNo: integer = 0): TWebDetection; function SafeSearchAnnotation(PageNo: integer = 0): TSafeSearchAnnotation; function FaceAnnotation(PageNo: integer = 0): TFaceAnnotationList; function LocalizedObjectAnnotation( PageNo: integer = 0): TLocalizedObjectList; function ProductSearchAnnotation( PageNo: integer = 0): TProductSearchAnnotation; function ImageAnnotationContext( PageNo: integer = 0): TImageAnnotationContext; end; TVisionModel = (vmUnset, vmStable, vmLatest); IVisionML = interface(IInterface) function AnnotateFileSynchronous(const FileAsBase64, ContentType: string; Features: TVisionMLFeatures; MaxResultsPerFeature: integer = 50; Model: TVisionModel = vmStable): IVisionMLResponse; procedure AnnotateFile(const FileAsBase64, ContentType: string; Features: TVisionMLFeatures; OnAnnotate: TOnAnnotate; OnAnnotateError: TOnRequestError; const RequestID: string = ''; MaxResultsPerFeature: integer = 50; Model: TVisionModel = vmStable); function AnnotateStorageSynchronous(const RefStorageCloudURI, ContentType: string; Features: TVisionMLFeatures; MaxResultsPerFeature: integer = 50; Model: TVisionModel = vmStable): IVisionMLResponse; procedure AnnotateStorage(const RefStorageCloudURI, ContentType: string; Features: TVisionMLFeatures; OnAnnotate: TOnAnnotate; OnAnnotateError: TOnRequestError; MaxResultsPerFeature: integer = 50; Model: TVisionModel = vmStable); end; /// <summary> /// The interface IFirebaseConfiguration provides a class factory for /// accessing all interfaces to the Firebase services. The interface will be /// created by the constructors of the class TFirebaseConfiguration in the /// unit FB4D.Configuration. The first constructor requires all secrets of the /// Firebase project as ApiKey and Project ID and when using the Storage also /// the storage Bucket. The second constructor parses the google-services.json /// file that shall be loaded from the Firebase Console after adding an App in /// the project settings. /// </summary> EFirebaseConfiguration = class(Exception); IFirebaseConfiguration = interface(IInterface) function ProjectID: string; function Auth: IFirebaseAuthentication; function RealTimeDB: IRealTimeDB; function Database( const DatabaseID: string = cDefaultDatabaseID): IFirestoreDatabase; function Storage: IFirebaseStorage; function Functions: IFirebaseFunctions; function VisionML: IVisionML; procedure SetBucket(const Bucket: string); end; const cFirestoreDocumentPath = 'projects/%s/databases/%s/documents%s'; // Params at TQueryParams cGetQueryParamOrderBy = 'orderBy'; cGetQueryParamLimitToFirst = 'limitToFirst'; cGetQueryParamLimitToLast = 'limitToLast'; cGetQueryParamStartAt = 'startAt'; cGetQueryParamEndAt = 'endAt'; cGetQueryParamEqualTo = 'equalTo'; cFirestorePageSize = 'pageSize'; cFirestorePageToken = 'pageToken'; cFirestoreTransaction = 'transaction'; // Vars at GetServerVariables cServerVariableTimeStamp = 'timestamp'; // Events at TOnReceiveEvent cEventPut = 'put'; cEventPatch = 'patch'; cEventCancel = 'cancel'; // Nodes in JSONObj at TOnReceiveEvent cData = 'data'; cPath = 'path'; implementation {$IFDEF LINUX64} {$I LinuxTypeImpl.inc} {$ENDIF} { TOnSuccess } constructor TOnSuccess.Create(OnResp: TOnFirebaseResp); begin if assigned(OnResp) then OnSuccessCase := oscFB else OnSuccessCase := oscUndef; {$IFDEF AUTOREFCOUNT} OnUserResponse := nil; OnFetchProviders := nil; OnPasswordVerification := nil; OnGetUserData := nil; OnRefreshToken := nil; OnRTDBValue := nil; OnRTDBDelete := nil; OnRTDBServerVariable := nil; OnDocument := nil; OnDocuments := nil; OnBeginTransaction := nil; OnStorage := nil; OnStorageGetAndDown := nil; OnStorageUpload := nil; OnDelStorage := nil; OnFunctionSuccess := nil; {$ENDIF} OnStorageError := nil; DownStream := nil; UpStream := nil; OnResponse := OnResp; end; constructor TOnSuccess.CreateUser(OnUserResp: TOnUserResponse); begin Create(nil); OnSuccessCase := oscUser; OnUserResponse := OnUserResp; end; constructor TOnSuccess.CreateFetchProviders( OnFetchProvidersResp: TOnFetchProviders); begin Create(nil); OnSuccessCase := oscFetchProvider; OnFetchProviders := OnFetchProvidersResp; end; constructor TOnSuccess.CreatePasswordVerification( OnPasswordVerificationResp: TOnPasswordVerification); begin Create(nil); OnSuccessCase := oscPwdVerification; OnPasswordVerification := OnPasswordVerificationResp; end; constructor TOnSuccess.CreateGetUserData(OnGetUserDataResp: TOnGetUserData); begin Create(nil); OnSuccessCase := oscGetUserData; OnGetUserData := OnGetUserDataResp; end; constructor TOnSuccess.CreateRefreshToken(OnRefreshTokenResp: TOnTokenRefresh); begin Create(nil); OnSuccessCase := oscRefreshToken; OnRefreshToken := OnRefreshTokenResp; end; constructor TOnSuccess.CreateRTDBValue(OnRTDBValueResp: TOnRTDBValue); begin Create(nil); OnSuccessCase := oscRTDBValue; OnRTDBValue := OnRTDBValueResp; end; constructor TOnSuccess.CreateRTDBDelete(OnRTDBDeleteResp: TOnRTDBDelete); begin Create(nil); OnSuccessCase := oscRTDBDelete; OnRTDBDelete := OnRTDBDeleteResp; end; constructor TOnSuccess.CreateRTDBServerVariable( OnRTDBServerVariableResp: TOnRTDBServerVariable); begin Create(nil); OnSuccessCase := oscRTDBServerVariable; OnRTDBServerVariable := OnRTDBServerVariableResp; end; constructor TOnSuccess.CreateFirestoreDoc(OnDocumentResp: TOnDocument); begin Create(nil); OnSuccessCase := oscDocument; OnDocument := OnDocumentResp; end; constructor TOnSuccess.CreateFirestoreDocs(OnDocumentsResp: TOnDocuments); begin Create(nil); OnSuccessCase := oscDocuments; OnDocuments := OnDocumentsResp; end; constructor TOnSuccess.CreateFirestoreReadTransaction( OnBeginReadTransactionResp: TOnBeginReadTransaction); begin Create(nil); OnSuccessCase := oscBeginReadTransaction; OnBeginReadTransaction := OnBeginReadTransactionResp; end; constructor TOnSuccess.CreateFirestoreCommitWriteTransaction( OnCommitTransaction: TOnCommitWriteTransaction); begin Create(nil); OnSuccessCase := oscCommitWriteTransaction; OnCommitTransaction := OnCommitTransaction; end; constructor TOnSuccess.CreateStorage(OnStorageResp: TOnStorage); begin Create(nil); OnSuccessCase := oscStorage; OnStorage := OnStorageResp; end; constructor TOnSuccess.CreateStorageDeprecated( OnStorageResp: TOnStorageDeprecated); begin Create(nil); OnSuccessCase := oscStorageDeprecated; OnStorageDeprecated := OnStorageResp; end; constructor TOnSuccess.CreateStorageGetAndDownload(OnStorageResp: TOnStorage; OnStorageErrorResp: TOnRequestError; Stream: TStream); begin Create(nil); OnSuccessCase := oscStorageGetAndDown; OnStorageGetAndDown := OnStorageResp; OnStorageError := OnStorageErrorResp; DownStream := Stream; end; constructor TOnSuccess.CreateStorageUpload(OnStorageResp: TOnStorage; Stream: TStream); begin Create(nil); OnSuccessCase := oscStorageUpload; OnStorageUpload := OnStorageResp; UpStream := Stream; end; constructor TOnSuccess.CreateDelStorage(OnDelStorageResp: TOnDeleteStorage); begin Create(nil); OnSuccessCase := oscDelStorage; OnDelStorage := OnDelStorageResp; end; constructor TOnSuccess.CreateFunctionSuccess( OnFunctionSuccessResp: TOnFunctionSuccess); begin Create(nil); OnSuccessCase := oscFunctionSuccess; OnFunctionSuccess := OnFunctionSuccessResp; end; constructor TOnSuccess.CreateVisionML(OnAnnotateResp: TOnAnnotate); begin Create(nil); OnSuccessCase := oscVisionML; OnAnnotate := OnAnnotateResp; end; end.
unit tmsUXlsColInfo; {$INCLUDE ..\FLXCOMPILER.INC} interface uses Classes, SysUtils, tmsUXlsBaseRecords, tmsUXlsBaseList, tmsXlsMessages, tmsUFlxMessages, tmsUXlsOtherRecords, tmsUOle2Impl; type TColInfoDat=packed record FirstColumn: word; LastColumn: word; Width: word; XF: word; Options: word; Reserved: Word; end; PColInfoDat=^TColInfoDat; TColInfo=class public Column: word; Width: Word; XF: Word; Options: Word; constructor Create (const aColumn, aWidth, aXF, aOptions: word); function IsEqual(const aColInfo: TColInfo): boolean; procedure SetColOutlineLevel(Level: integer); function GetColOutlineLevel: integer; end; TColInfoRecord=class(TBaseRecord) function D: TColInfoDat; end; TColInfoList= class(TBaseList) //Items are TColInfo {$INCLUDE TColInfoListHdr.inc} private procedure SaveOneRecord(const i, k: integer; const DataStream: TOle2File); procedure SaveToStreamExt(const DataStream: TOle2File; const FirstRecord, RecordCount: integer); procedure CalcIncludedRangeRecords(const CellRange: TXlsCellRange; var FirstRecord, RecordCount: integer); function TotalSizeExt(const FirstRecord, RecordCount:integer): int64; public procedure CopyFrom(const aColInfoList: TColInfoList); procedure AddRecord(const R: TColInfoRecord); procedure SaveToStream(const DataStream: TOle2File); procedure SaveRangeToStream(const DataStream: TOle2File; const CellRange: TXlsCellRange); function TotalSize: int64; function TotalRangeSize(const CellRange: TXlsCellRange): int64; procedure ArrangeInsertCols(const DestCol: integer; const aColCount: integer; const SheetInfo: TSheetInfo); procedure CopyCols(const FirstCol, LastCol: integer; const DestCol: integer; const aColCount: integer; const SheetInfo: TSheetInfo); procedure CalcGuts(const Guts: TGutsRecord); end; implementation {$INCLUDE TColInfoListImp.inc} { TColInfoList } procedure TColInfoList.AddRecord(const R: TColInfoRecord); var i: integer; begin for i:=R.D.FirstColumn to R.D.LastColumn do Add(TColInfo.Create(i, R.D.Width, R.D.XF, R.D.Options )); R.Free; end; procedure TColInfoList.CalcIncludedRangeRecords( const CellRange: TXlsCellRange; var FirstRecord, RecordCount: integer); var LastRecord, i: integer; begin Sort; //just in case... FirstRecord:=-1; LastRecord:=-1; for i:=0 to Count-1 do begin if (FirstRecord<0) and (Items[i].Column>=CellRange.Left) then FirstRecord:=i; if Items[i].Column<=CellRange.Right then LastRecord:=i; end; if (FirstRecord>=0) and (LastRecord>=0) and (FirstRecord<=LastRecord) then RecordCount:=LastRecord-FirstRecord+1 else begin FirstRecord:=0; RecordCount:=0; end; end; procedure TColInfoList.CopyFrom(const aColInfoList: TColInfoList); var i: integer; begin Clear; for i:=0 to aColInfoList.Count-1 do Add(TColInfo.Create(aColInfoList[i].Column, aColInfoList[i].Width, aColInfoList[i].XF, aColInfoList[i].Options)); end; procedure TColInfoList.SaveOneRecord(const i,k: integer; const DataStream: TOle2File); var RecordHeader: TRecordHeader; Info: TColInfoDat; begin RecordHeader.Id:= xlr_COLINFO; RecordHeader.Size:=SizeOf(TColInfoDat); DataStream.WriteMem(RecordHeader, SizeOf(RecordHeader)); Info.FirstColumn:=Items[i].Column; Info.LastColumn:=Items[k].Column; if Info.LastColumn > Max_Columns + 1 then Info.LastColumn := Max_Columns + 1; //LastColumn must not be bigger than 256. Info.Width:=Items[i].Width; Info.XF:=Items[i].XF; Info.Options:=Items[i].Options; Info.Reserved:=0; DataStream.WriteMem(Info, SizeOf(Info)); end; procedure TColInfoList.SaveToStreamExt(const DataStream: TOle2File; const FirstRecord, RecordCount: integer); var i,k: integer; begin //Mix similar columns Sort; i:=FirstRecord; while i<RecordCount do begin k:=i+1; while (k<FirstRecord+RecordCount) and Items[i].IsEqual(Items[k]) and (Items[k].Column=Items[k-1].Column+1) do inc(k); //We need to ensure this[i] is not bigger than Maxcolumns. this[k] can be=Maxcolumns+1. if Items[i].Column > Max_Columns then exit; SaveOneRecord(i, k-1,DataStream); i:=k; end; end; procedure TColInfoList.SaveRangeToStream(const DataStream: TOle2File; const CellRange: TXlsCellRange); var FirstRecord, RecordCount: integer; begin CalcIncludedRangeRecords(CellRange, FirstRecord, RecordCount); SaveToStreamExt(DataStream, FirstRecord, RecordCount); end; procedure TColInfoList.SaveToStream(const DataStream: TOle2File); begin SaveToStreamExt(DataStream, 0, Count); end; function TColInfoList.TotalSize: int64; var i,k: integer; begin Sort; //just in case Result:=0; //Mix similar columns i:=0; while i<Count do begin k:=i+1; while (k<Count) and Items[i].IsEqual(Items[k]) and (Items[k].Column=Items[k-1].Column+1) do inc(k); //We need to ensure this[i] is not bigger than Maxcolumns. this[k] can be=Maxcolumns+1. if Items[i].Column > Max_Columns then exit; inc(Result, SizeOf(TRecordHeader)+SizeOf(TColInfoDat)); i:=k; end; end; function TColInfoList.TotalSizeExt(const FirstRecord, RecordCount: integer): int64; var i,k: integer; begin Sort; //just in case Result:=0; //Mix similar columns i:=FirstRecord; while i<FirstRecord+RecordCount do begin k:=i+1; while (k<Count) and Items[i].IsEqual(Items[k])and (Items[k].Column=Items[k-1].Column+1) do inc(k); //We need to ensure this[i] is not bigger than Maxcolumns. this[k] can be=Maxcolumns+1. if Items[i].Column > Max_Columns then exit; inc(Result, SizeOf(TRecordHeader)+SizeOf(TColInfoDat)); i:=k; end; end; function TColInfoList.TotalRangeSize(const CellRange: TXlsCellRange): int64; var FirstRecord, RecordCount: integer; begin CalcIncludedRangeRecords(CellRange, FirstRecord, RecordCount); Result:=TotalSizeExt(FirstRecord, RecordCount); end; procedure TColInfoList.CalcGuts(const Guts: TGutsRecord); var MaxGutsLevel: integer; GutsLevel: integer; i: integer; begin MaxGutsLevel:=0; for i:=0 to Count-1 do begin if (Items[i]<>nil) then begin GutsLevel:=items[i].GetColOutlineLevel; if GutsLevel>MaxGutsLevel then MaxGutsLevel:=GutsLevel; end; end; Guts.ColLevel:=MaxGutsLevel; end; procedure TColInfoList.ArrangeInsertCols(const DestCol, aColCount: integer; const SheetInfo: TSheetInfo); var i: integer; begin if SheetInfo.FormulaSheet <> SheetInfo.InsSheet then exit; Sort; //just in case for i := Count - 1 downto 0 do begin if (Items[i].Column >= DestCol) then inc (Items[i].Column, aColCount) else break; end; end; procedure TColInfoList.CopyCols(const FirstCol, LastCol, DestCol, aColCount: integer; const SheetInfo: TSheetInfo); var k: integer; i: integer; C: TColInfo; Index: integer; NewCol: integer; begin //ArrangeInsertCols(SourceRange.Offset(SourceRange.Top, DestCol), aColCount, SheetInfo); //This has already been called. for k := 0 to aColCount - 1 do begin i := 0; while i < Count do begin try C := Items[i]; if (C = nil) then continue; if (C.Column < FirstCol) then continue; if (C.Column > LastCol) then break; NewCol := ((DestCol + C.Column) - FirstCol) + (k * (LastCol - FirstCol + 1)); if ((NewCol >= 0)) and (NewCol <> C.Column) and (NewCol <= (Max_Columns + 1)) then begin Index := -1; if Find(NewCol, Index) then Delete(Index) else if Index <= i then inc(i); Insert(Index, TColInfo.Create(NewCol, C.Width, C.XF, C.Options)); end; finally inc(i); end; end; end; end; { TColInfoRecord } function TColInfoRecord.D: TColInfoDat; begin Result:= PColInfoDat(Data)^; end; { TColInfo } constructor TColInfo.Create(const aColumn, aWidth, aXF, aOptions: word); begin inherited Create; Column:=aColumn; Width:=aWidth; XF:=aXF; Options:=aOptions; end; function TColInfo.GetColOutlineLevel: integer; begin Result:=hi(word(Options)) and 7; end; function TColInfo.IsEqual(const aColInfo: TColInfo): boolean; begin Result:= // don't compare the column .... (Column = aColInfo.Column) and (Width = aColInfo.Width) and (XF = aColInfo.XF) and (Options= acolInfo.Options); end; procedure TColInfo.SetColOutlineLevel(Level: integer); begin Options:= (Options and not (7 shl 8)) or ((Level and 7) shl 8); end; end.
{ 12/10/1999 8:41:41 AM > [Bill on BILL] checked out /Change Table Types to TTS } unit ActiveState; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, sBitBtn, sGroupBox; type TfrmActiveState = class(TForm) rgActiveState: TsRadioGroup; btnOk: TsBitBtn; btnCancel: TsBitBtn; procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure rgActiveStateClick(Sender: TObject); private FActiveStatus: string; procedure SetActiveStatus(const Value: string); { Private declarations } public { Public declarations } property ActiveStatus:string read FActiveStatus write SetActiveStatus; end; var frmActiveState: TfrmActiveState; implementation {$R *.DFM} procedure TfrmActiveState.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if (Shift = []) and (Key = VK_Escape) then btnCancel.Click; end; procedure TfrmActiveState.SetActiveStatus(const Value: string); begin FActiveStatus := uppercase(Value); rgActiveState.ItemIndex := pos(FActiveStatus,'AYN') - 1; if rgActiveState.ItemIndex < 0 then rgActiveState.ItemIndex := 0; end; procedure TfrmActiveState.rgActiveStateClick(Sender: TObject); begin case rgActiveState.ItemIndex of 0 : FActiveStatus := 'A'; 1 : FActiveStatus := 'Y'; 2 : FActiveStatus := 'N'; end; end; end.
unit DispatchUnsignedAsSignedPatch; {$D-,L-} { DispatchUnsignedAsSignedPatch replaces the Variants.GetDispatchInvokeArgs by a bug fixed version that handles DispatchUnsignedAsSigned with varRef parameters. Bug was introduced in Update 4 for Delphi XE2. Bug was fixed in XE4 More info: http://qc.embarcadero.com/wc/qcmain.aspx?d=111277 } interface implementation uses Windows, SysConst, SysUtils, Variants; const {$IFDEF CPUX64} HookByteCount = 5; {$ELSE} HookByteCount = 6; {$ENDIF CPUX64} var _EmptyBSTR: PWideChar = nil; AddrOfGetDispatchInvokeArgs: PByte; HookedOpCodes: array[0..HookByteCount - 1] of Byte; function Replacement_GetDispatchInvokeArgs(CallDesc: PCallDesc; Params: Pointer; var Strings: TStringRefList; OrderLTR : Boolean): TVarDataArray; {$IFDEF CPUX64} function _GetXMM3: Double; asm MOVDQA XMM0, XMM3 end; function _GetXMM3AsSingle: Single; asm MOVDQA XMM0, XMM3 end; {$ENDIF} const { Parameter type masks - keep in sync with decl.h/ap* enumerations} atString = $48; atUString = $4A; atVarMask = $3F; atTypeMask = $7F; atByRef = $80; var I: Integer; ArgType: Byte; PVarParm: PVarData; StringCount: Integer; begin //InitEmptyBSTR; StringCount := 0; SetLength(Result, CallDesc^.ArgCount); for I := 0 to CallDesc^.ArgCount-1 do begin ArgType := CallDesc^.ArgTypes[I]; if OrderLTR then PVarParm := @Result[I] else PVarParm := @Result[CallDesc^.ArgCount-I-1]; if (ArgType and atByRef) = atByRef then begin if (ArgType and atTypeMask) = atString then begin PVarData(PVarParm)^.VType := varByRef or varOleStr; PVarData(PVarParm)^.VPointer := Strings[StringCount].FromAnsi(PAnsiString(Params^)); Inc(StringCount); end else if (ArgType and atTypeMask) = atUString then begin PVarData(PVarParm)^.VType := varByRef or varOleStr; PVarData(PVarParm)^.VPointer := Strings[StringCount].FromUnicode(PUnicodeString(Params^)); Inc(StringCount); end else begin if ((ArgType and atTypeMask) = varVariant) and ((PVarData(Params^)^.VType = varString) or (PVarData(Params^)^.VType = varUString)) then VarCast(PVariant(Params^)^, PVariant(Params^)^, varOleStr); {<Bugfix>} //PVarData(PVarParm)^.VType := varByRef or (ArgType and atTypeMask); ArgType := ArgType and atTypeMask; if DispatchUnsignedAsSigned then case ArgType of varUInt64: ArgType := varInt64; varLongWord: ArgType := varInteger; varWord: ArgType := varSmallint; varByte: ArgType := varShortInt; end; PVarData(PVarParm)^.VType := varByRef or ArgType; {</Bugfix>} PVarData(PVarParm)^.VPointer := PPointer(Params)^; end; Inc(PByte(Params), SizeOf(Pointer)); end else // ByVal begin PVarParm^.VType := ArgType; case ArgType of varEmpty, varNull: ; // Only need to set VType varSmallint: PVarParm^.VSmallInt := PSmallInt(Params)^; varInteger: PVarParm^.VInteger := PInteger(Params)^; varSingle: {$IFDEF CPUX64} if I = 0 then PVarParm^.VSingle := _GetXMM3AsSingle else {$ENDIF} PVarParm^.VSingle := PSingle(Params)^; varDouble: {$IFDEF CPUX64} if I = 0 then PVarParm^.VDouble := _GetXMM3 else {$ENDIF} PVarParm^.VDouble := PDouble(Params)^; varCurrency: PVarParm^.VCurrency := PCurrency(Params)^; varDate: {$IFDEF CPUX64} if I = 0 then PVarParm^.VDate := _GetXMM3 else {$ENDIF} PVarParm^.VDate := PDateTime(Params)^; varOleStr: PVarParm^.VPointer := PPointer(Params)^; varDispatch: PVarParm^.VDispatch := PPointer(Params)^; varError: PVarParm^.VError := HRESULT($80020004); //DISP_E_PARAMNOTFOUND; varBoolean: PVarParm^.VBoolean := PBoolean(Params)^; varVariant: begin PVarParm^.VType := varEmpty; {$IFDEF CPUX64} PVariant(PVarParm)^ := PVariant(Params^)^; {$ELSE} PVariant(PVarParm)^ := PVariant(Params)^; {$ENDIF} end; varUnknown: PVarParm^.VUnknown := PPointer(Params)^; varShortInt: PVarParm^.VShortInt := PShortInt(Params)^; varByte: PVarParm^.VByte := PByte(Params)^; varWord: begin if DispatchUnsignedAsSigned then begin PVarParm^.VType := varInteger; PVarParm^.VInteger := Integer(PWord(Params)^); end else PVarParm^.VWord := PWord(Params)^; end; varLongWord: begin if DispatchUnsignedAsSigned then begin PVarParm^.VType := varInteger; PVarParm^.VInteger := Integer(PLongWord(Params)^); end else PVarParm^.VLongWord := PLongWord(Params)^; end; varInt64: PVarParm^.VInt64 := PInt64(Params)^; varUInt64: begin if DispatchUnsignedAsSigned then begin PVarParm^.VType := varInt64; PVarParm^.VInt64 := Int64(PInt64(Params)^); end else PVarParm^.VUInt64 := PUInt64(Params)^; end; atString: begin PVarParm^.VType := varOleStr; if PAnsiString(Params)^ <> '' then begin PVarParm^.VPointer := PWideChar(Strings[StringCount].FromAnsi(PAnsiString(Params))^); Strings[StringCount].Ansi := nil; Inc(StringCount); end else PVarParm^.VPointer := _EmptyBSTR; end; atUString: begin PVarParm^.VType := varOleStr; if PUnicodeString(Params)^ <> '' then begin PVarParm^.VPointer := PWideChar(Strings[StringCount].FromUnicode(PUnicodeString(Params))^); Strings[StringCount].Unicode := nil; Inc(StringCount); end else PVarParm^.VPointer := _EmptyBSTR; end; else // Unsupported Var Types //varDecimal = $000E; { vt_decimal 14 } {UNSUPPORTED as of v6.x code base} //varUndef0F = $000F; { undefined 15 } {UNSUPPORTED per Microsoft} //varRecord = $0024; { VT_RECORD 36 } //varString = $0100; { Pascal string 256 } {not OLE compatible } //varAny = $0101; { Corba any 257 } {not OLE compatible } //varUString = $0102; { Unicode string 258 } {not OLE compatible } //_DispInvokeError; raise EVariantDispatchError.CreateRes(@SDispatchError); end; case ArgType of varError: ; // don't increase param pointer {$IFDEF CPUX86} varDouble, varCurrency, varDate, varInt64, varUInt64: Inc(PByte(Params), 8); varVariant: Inc(PByte(Params), SizeOf(Variant)); {$ENDIF} else Inc(PByte(Params), SizeOf(Pointer)); end; end; end; end; function GetActualAddr(Proc: Pointer): Pointer; type PWin9xDebugThunk = ^TWin9xDebugThunk; TWin9xDebugThunk = packed record PUSH: Byte; Addr: Pointer; JMP: Byte; Rel: Integer; end; PAbsoluteIndirectJmp = ^TAbsoluteIndirectJmp; TAbsoluteIndirectJmp = packed record OpCode: Word; Addr: ^Pointer; end; begin Result := Proc; if Result <> nil then begin {$IFDEF CPUX64} if PAbsoluteIndirectJmp(Result).OpCode = $25FF then Result := PPointer(PByte(@PAbsoluteIndirectJmp(Result).OpCode) + SizeOf(TAbsoluteIndirectJmp) + Integer(PAbsoluteIndirectJmp(Result).Addr))^; {$ELSE} if (Win32Platform <> VER_PLATFORM_WIN32_NT) and (PWin9xDebugThunk(Result).PUSH = $68) and (PWin9xDebugThunk(Result).JMP = $E9) then Result := PWin9xDebugThunk(Result).Addr; if PAbsoluteIndirectJmp(Result).OpCode = $25FF then Result := PAbsoluteIndirectJmp(Result).Addr^; {$ENDIF CPUX64} end; end; procedure Init; var Buffer: array[0..HookByteCount - 1] of Byte; P: PByte; n: SIZE_T; Success: Boolean; begin P := GetActualAddr(@GetDispatchInvokeArgs); {$IFDEF CPUX64} Success := (P[0] = $55) and // push rbp (P[1] = $41) and (P[2] = $55) and // push r13 (P[3] = $57) and // push rdi (P[4] = $56); // push rsi {$ELSE} Buffer[5] := $90; // nop Success := (P[0] = $55) and // push ebp (P[1] = $8B) and (P[2] = $EC) and // mov ebp, esp (P[3] = $83) and (P[4] = $C4) and (P[5] = $EC); // add esp, -$14 {$ENDIF CPUX64} if Success then begin Move(P^, HookedOpCodes, SizeOf(HookedOpCodes)); // backup opcodes Buffer[0] := $E9; // jmp rel32 PInteger(@Buffer[1])^ := PByte(@Replacement_GetDispatchInvokeArgs) - (P + 5); Success := WriteProcessMemory(GetCurrentProcess, P, @Buffer, SizeOf(Buffer), n) and (n = SizeOf(Buffer)); end; if not Success then raise EVariantInvalidOpError.Create('GetDispatchInvokeArgs patching failed'); AddrOfGetDispatchInvokeArgs := P; _EmptyBSTR := StringToOleStr(''); // leaks memory end; procedure Fini; var n: SIZE_T; begin // Restore original opcodes if AddrOfGetDispatchInvokeArgs <> nil then WriteProcessMemory(GetCurrentProcess, AddrOfGetDispatchInvokeArgs, @HookedOpCodes, SizeOf(HookedOpCodes), n); end; initialization Init; finalization Fini; end.
unit Checking; {$mode objfpc}{$H+} interface uses Classes, SysUtils, Windows, Transformation, Figure, Math; function Check (Figure: TFigure; Point1, Point2: MegaPoint): boolean; implementation procedure Swap (var a, b: double); var Buf: double; begin Buf := a; a := b; b := Buf; end; function Intersect (a, b, c, d: MegaPoint): boolean; function IntersectAux (a, b, c, d: double): boolean; begin if (a > b) then swap (a, b); if (c > d) then swap (c, d); Result := max (a, c) <= min (b, d); end; function Area (a, b, c: MegaPoint): double; begin Result := (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x); end; begin Result := IntersectAux (a.x, b.x, c.x, d.x) and IntersectAux (a.y, b.y, c.y, d.y) and (Area (a, b, c) * Area (a, b, d) <= 0) and (Area (c, d, a) * Area (c, d, b) <= 0); end; function Check (Figure: TFigure; Point1, Point2: MegaPoint): boolean; var Region: HRGN; i: integer; Points: PointArray; Center: TPoint; x0, y0, r, angle: double; begin SetLength (Points, Length (Figure.FWorldPoints)); if Figure is TPencil then begin if Point1.X = Point2.X then begin Point1.X -= Round (5 / scale); Point1.Y -= Round (5 / scale); Point2.X += Round (5 / scale); Point2.Y += Round (5 / scale); end; for i := 0 to High (Figure.FWorldPoints) - 1 do begin if Intersect (Figure.FWorldPoints[i], Figure.FWorldPoints[i + 1], PointW (Point1.X, Point1.Y), PointW (Point1.X, Point2.Y)) or Intersect (Figure.FWorldPoints[i], Figure.FWorldPoints[i + 1], PointW (Point1.X, Point2.Y), PointW (Point2.X, Point2.Y)) or Intersect (Figure.FWorldPoints[i], Figure.FWorldPoints[i + 1], PointW (Point2.X, Point2.Y), PointW (Point2.X, Point1.Y)) or Intersect (Figure.FWorldPoints[i], Figure.FWorldPoints[i + 1], PointW (Point2.X, Point1.Y), PointW (Point1.X, Point1.Y)) or ((Figure.FWorldPoints[i].X < max (Point1.X, Point2.X)) and (Figure.FWorldPoints[i].X > min (Point1.X, Point2.X)) and (Figure.FWorldPoints[i].Y < max (Point1.Y, Point2.Y)) and (Figure.FWorldPoints[i].Y > min (Point1.Y, Point2.Y))) then begin Exit (True); DeleteObject (Region); end; end; end; for i := 0 to High (Figure.FWorldPoints) do Points[i] := WorldToScreen (Figure.FWorldPoints[i]); if Figure is TPolygon then begin for i := 0 to High (Figure.FWorldPoints) do Points[i] := WorldToScreen (Figure.FWorldPoints[i]); Region := CreatePolygonRgn (Points[0], Length (Points), WINDING); if RectInRegion (Region, ConstructRect (WorldToScreen (Point2), WorldToScreen (Point1))) then begin Exit (True); DeleteObject (Region); end; end; if Figure is TRoundRectangl then begin for i := 0 to High (Figure.FWorldPoints) do Points[i] := WorldToScreen (Figure.FWorldPoints[i]); for i := 0 to High (Figure.FWorldPoints) - 1 do begin Region := CreateRoundRectRgn (Points[i].X, Points[i].Y, Points[i + 1].X, Points[i + 1].Y, (Figure as TRoundRectangl).RoundX, (Figure as TRoundRectangl).RoundY); if RectInRegion (Region, ConstructRect (WorldToScreen (Point2), WorldToScreen (Point1))) then begin Exit (True); DeleteObject (Region); end; end; end; if Figure is TEllipse then begin for i := 0 to High (Figure.FWorldPoints) do Points[i] := WorldToScreen (Figure.FWorldPoints[i]); for i := 0 to High (Figure.FWorldPoints) - 1 do begin Region := CreateEllipticRgn (Points[0].X, Points[0].Y, Points[1].X, Points[1].Y); if RectInRegion (Region, ConstructRect (WorldToScreen (Point2), WorldToScreen (Point1))) then begin Exit (True); DeleteObject (Region); end; end; end; if Figure is TRectangl then begin for i := 0 to High (Figure.FWorldPoints) do Points[i] := WorldToScreen (Figure.FWorldPoints[i]); for i := 0 to High (Figure.FWorldPoints) - 1 do begin Region := CreateRectRgn (Points[0].X, Points[0].Y, Points[2].X, Points[2].Y); if RectInRegion (Region, ConstructRect (WorldToScreen (Point2), WorldToScreen (Point1))) then begin Exit (True); DeleteObject (Region); end; end; end; if Figure is TText then begin for i := 0 to High (Figure.FWorldPoints) do Points[i] := WorldToScreen (Figure.FWorldPoints[i]); for i := 0 to High (Figure.FWorldPoints) - 1 do begin Region := CreateRectRgn (Points[0].X, Points[0].Y, Points[1].X, Points[1].Y); if RectInRegion (Region, ConstructRect (WorldToScreen (Point2), WorldToScreen (Point1))) then begin Exit (True); DeleteObject (Region); end; end; end; if Figure is TRegularPolygon then begin SetLength (Points, (Figure as TRegularPolygon).Tops); Center := WorldToScreen (Figure.FWorldPoints[0]); x0 := WorldToScreen (Figure.FWorldPoints[1]).X - Center.X; y0 := WorldToScreen (Figure.FWorldPoints[1]).Y - Center.Y; r := sqrt (x0 * x0 + y0 * y0); if r = 0 then Exit; angle := arccos (x0 / r); if y0 < 0 then angle *= -1; for i := 0 to (Figure as TRegularPolygon).Tops - 1 do begin angle += 2 * pi / (Figure as TRegularPolygon).Tops; Points[i].X := Round (r * cos (angle) + Center.X); Points[i].Y := Round (r * sin (angle) + Center.Y); end; Region := CreatePolygonRgn (Points[0], Length (Points), WINDING); if RectInRegion (Region, ConstructRect (WorldToScreen (Point2), WorldToScreen (Point1))) then begin Exit (True); DeleteObject (Region); end; end; if Figure is TSprey then begin for i := 0 to High (Figure.FWorldPoints) do Points[i] := WorldToScreen (Figure.FWorldPoints[i]); for i := 0 to High (Figure.FWorldPoints) do begin Region := CreateEllipticRgn (Points[i].X + (Figure as TSprey).Size, Points[i].Y + (Figure as TSprey).Size, Points[i].X - (Figure as TSprey).Size, Points[i].Y - (Figure as TSprey).Size); if RectInRegion (Region, ConstructRect (WorldToScreen (Point2), WorldToScreen (Point1))) then begin Exit (True); DeleteObject (Region); end; DeleteObject (Region); end; end; DeleteObject (Region); Result := False; end; end.
{ DBAExplorer - Oracle Admin Management Tool Copyright (C) 2008 Alpaslan KILICKAYA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. } unit OraQueryThread; interface uses Windows, Messages, Db, Classes, SysUtils, Ora, OraClasses, OraBarConn, forms, OraError; const WM_ORA_THREAD_NOTIFY = WM_USER+100; // Thread notification events MQE_INITED = 0; // initialized MQE_STARTED = 1; // query started MQE_SUCCESS = 2; // query finished MQE_FAIL = 3; // query finished type TOraQueryThread = class(TThread) private FDataSource : TDataSource; FOraSession : TOraSession; FDataSet: TOraQuery; FSql : String; FQuery: TOraQuery; FStatus: Integer; FCancelled : boolean; FQueryException : string; FException : Exception; protected procedure Execute; override; procedure SetDataSet; procedure ShowQryError; public constructor Create (ADataSource: TDataSource; AOraSession: TOraSession; ASql : String); overload; constructor Create (AOraSession: TOraSession; ASql : String; var Error: string); overload; procedure CancelQuery; destructor Destroy; override; property Status : Integer read FStatus write FStatus; property QueryException : string read FQueryException; property Session : TOraSession read FOraSession write FOraSession; property Query: TOraQuery read FQuery; property DataSource: TDataSource read FDataSource; end; implementation uses Dialogs, Util; constructor TOraQueryThread.Create(ADataSource: TDataSource; AOraSession: TOraSession; ASql : String); begin Inherited Create(True); FDataSource := ADataSource; FSql := ASql; FOraSession := AOraSession; FCancelled := false; FStatus := MQE_INITED; FQueryException := ''; FreeOnTerminate := True; Resume; end; constructor TOraQueryThread.Create (AOraSession: TOraSession; ASql : String; var Error: string); begin Inherited Create(True); FDataSet := TOraQuery.Create(nil); FSql := ASql; FOraSession := AOraSession; FCancelled := false; FStatus := MQE_INITED; FQueryException := Error; FreeOnTerminate := True; Resume; end; destructor TOraQueryThread.Destroy; begin // FreeAndNil (FQuery); inherited Destroy; end; procedure TOraQueryThread.CancelQuery; begin FCancelled := true; try FOraSession.Disconnect; finally Application.ProcessMessages; if not FOraSession.Connected then FOraSession.Connect; FQuery := nil; end; Application.ProcessMessages; end; procedure TOraQueryThread.Execute; begin try if not FOraSession.Connected then FOraSession.Connect(); except on E: Exception do begin FException := ExceptObject as Exception; Synchronize(ShowQryError); exit; end; end; if FOraSession.Connected then begin try FStatus := MQE_STARTED; FQuery := TOraQuery.Create(nil); FQuery.Session := FOraSession; FQuery.SQL.Text := FSql; FQuery.FetchRows := 500; FQueryException := ''; if ExpectResultSet(FSql) then begin FQuery.Open; Synchronize(SetDataSet); end else FQuery.ExecSQL(); FStatus := MQE_SUCCESS; except on E: Exception do begin FException := ExceptObject as Exception; Synchronize(ShowQryError); abort; end; on E: EOraError do begin FException := ExceptObject as Exception; Synchronize(ShowQryError); abort; end; end; end; end; procedure TOraQueryThread.SetDataSet; begin if assigned(FDataSource) then FDataSource.Dataset := FQuery else FDataSet.Assign(FQuery); end; procedure TOraQueryThread.ShowQryError; begin FDataSet := nil; FQueryException := FException.Message; FStatus := MQE_FAIL; //Application.ShowException(FException); // raise Exception.Create(FException.Message); { try inherited; except on E: EOraError do begin raise EOraError.Create(E.ErrorCode, E.Message); end else raise; end; } end; end.
unit ConfigFEx; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, FileCtrl, ExtCtrls, Mask, JvExMask, JvToolEdit, Inifiles, JvSpin; type TFConfigFex = class(TForm) rgRegien: TRadioGroup; lblCert: TLabel; lblClave: TLabel; bOK: TButton; bAnular: TButton; jvCertif: TJvFilenameEdit; jvPrivada: TJvFilenameEdit; cbDepura: TCheckBox; Label1: TLabel; jvPunto: TJvSpinEdit; Label2: TLabel; edServicioAFIP: TEdit; cbPrueba: TCheckBox; procedure FormCreate(Sender: TObject); procedure bOKClick(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } FIni: TIniFile; FEmiteFE: Boolean; FFExpo: Boolean; FFLog: Boolean; procedure SetEmiteFE(const Value: Boolean); procedure SetFExpo(const Value: Boolean); procedure SetFLog(const Value: Boolean); public { Public declarations } property EmiteFEx: Boolean read FEmiteFE write SetEmiteFE; property FExpoEx: Boolean read FFExpo write SetFExpo; property FLogEx: Boolean read FFLog write SetFLog; end; function getFacturaEx: Boolean; function getClaveEx: string; function getCertifEx: string; function getExpoEx: Boolean; function getEstadoLogEx: Boolean; function getPuntoVentaEx: integer; function getServicioEx: string; function getHomologacionEx: boolean; var FConfigFex: TFConfigFex; implementation uses DMIng; {$R *.dfm} function getExpoEx: Boolean; begin FConfigFEx := TFConfigFex.Create(application); try Result := FConfigFex.FExpoEx; finally FConfigFex.Free; end; end; function getEstadoLogEx: Boolean; begin FConfigFEx := TFConfigFex.Create(application); try Result := FConfigFex.cbDepura.Checked; finally FConfigFex.Free; end; end; function getFacturaEx: Boolean; begin FConfigFEx := TFConfigFex.Create(application); try Result := FConfigFex.EmiteFEx; finally FConfigFex.Free; end; end; function getClaveEx: string; begin FConfigFEx := TFConfigFex.Create(application); try Result := FConfigFex.jvPrivada.FileName; finally FConfigFex.Free; end; end; function getCertifEx: string; begin FConfigFEx := TFConfigFex.Create(application); try Result := FConfigFex.jvCertif.FileName; finally FConfigFex.Free; end; end; function getPuntoVentaEx: integer; begin FConfigFEx := TFConfigFex.Create(application); try Result := FConfigFex.jvPunto.AsInteger; finally FConfigFex.Free; end; end; function getServicioEx: string; begin FConfigFEx := TFConfigFex.Create(application); try Result := FConfigFex.edServicioAFIP.Text; finally FConfigFex.Free; end; end; function getHomologacionEx: boolean; begin FConfigFEx := TFConfigFex.Create(application); try Result := FConfigFex.cbPrueba.checked; finally FConfigFex.Free; end; end; procedure TFConfigFex.bOKClick(Sender: TObject); begin FFExpo := (rgRegien.ItemIndex=0); FEmiteFE := not (rgRegien.ItemIndex=1); FIni.WriteBool('FEX', 'EXPO', FFExpo ); FIni.WriteBool('FEX', 'NOUSA', not FEmiteFE ); FIni.WriteString('FEX', 'CERTIFICADO', jvCertif.FileName ); FIni.WriteString('FEX', 'CLAVE', jvPrivada.FileName ); FIni.WriteBool('FEX', 'DEPURACION', cbDepura.Checked ); FIni.WriteInteger('FEX', 'PUNTODEVENTA', jvPunto.AsInteger ); FIni.WriteString('FEX', 'SERVICIO', edServicioAFIP.Text ); FIni.WriteBool('FEX', 'HOMOLOGACION', cbPrueba.Checked ); end; procedure TFConfigFex.FormCreate(Sender: TObject); var FBase: string; begin FBase := DataIng.getBase; FIni := TIniFile.Create(ExtractFilePath( Application.ExeName) + 'Conf\fact_ele_expo' + FBase + '.ini' ); if (FIni.ReadBool('FEX', 'EXPO', false )=true) then rgRegien.ItemIndex := 0 else if (FIni.ReadBool('FEX', 'NOUSA', false )=true) then rgRegien.ItemIndex := 1; FEmiteFE := rgRegien.ItemIndex<>1; jvCertif.filename := FIni.ReadString('FEX', 'CERTIFICADO', '' ); jvPrivada.FileName := FIni.ReadString('FEX', 'CLAVE', '' ); cbDepura.Checked := FIni.ReadBool('FEX', 'DEPURACION', false ); jvPunto.value := FIni.ReadInteger('FEX', 'PUNTODEVENTA', 1 ); edServicioAFIP.Text := FIni.ReadString('FEX', 'SERVICIO', 'wsfex' ); cbPrueba.Checked := FIni.ReadBool('FEX', 'HOMOLOGACION', false ); end; procedure TFConfigFex.FormDestroy(Sender: TObject); begin FIni.Free; end; procedure TFConfigFex.SetEmiteFE(const Value: Boolean); begin FEmiteFE := Value; end; procedure TFConfigFex.SetFExpo(const Value: Boolean); begin FFExpo := Value; end; procedure TFConfigFex.SetFLog(const Value: Boolean); begin FFLog := Value; end; end.
unit daParam; // Модуль: "w:\common\components\rtl\Garant\DA\daParam.pas" // Стереотип: "SimpleClass" // Элемент модели: "TdaParam" MUID: (5555AD2A0004) {$Include w:\common\components\rtl\Garant\DA\daDefine.inc} interface uses l3IntfUses , l3ProtoObject , daInterfaces , daTypes , l3Date ; type TdaParam = class(Tl3ProtoObject, IdaParam) private f_Description: IdaParamDescription; f_Converter: IdaDataConverter; f_Buffer: Pointer; protected function Get_Name: AnsiString; function IsSameType(const aDesc: IdaParamDescription): Boolean; function Get_AsInteger: LongInt; procedure Set_AsInteger(aValue: LongInt); function Get_DataBuffer: Pointer; function Get_AsLargeInt: LargeInt; procedure Set_AsLargeInt(aValue: LargeInt); function Get_AsString: AnsiString; procedure Set_AsString(const aValue: AnsiString); function Get_AsStDate: TStDate; procedure Set_AsStDate(const aValue: TStDate); function Get_AsStTime: TStTime; procedure Set_AsStTime(const aValue: TStTime); function Get_ParamType: TdaParamType; function Get_AsByte: Byte; procedure Set_AsByte(aValue: Byte); procedure Cleanup; override; {* Функция очистки полей объекта. } public constructor Create(const aConverter: IdaDataConverter; const aDesc: IdaParamDescription); reintroduce; class function Make(const aConverter: IdaDataConverter; const aDesc: IdaParamDescription): IdaParam; reintroduce; end;//TdaParam implementation uses l3ImplUses //#UC START# *5555AD2A0004impl_uses* //#UC END# *5555AD2A0004impl_uses* ; constructor TdaParam.Create(const aConverter: IdaDataConverter; const aDesc: IdaParamDescription); //#UC START# *5555AD6F0065_5555AD2A0004_var* //#UC END# *5555AD6F0065_5555AD2A0004_var* begin //#UC START# *5555AD6F0065_5555AD2A0004_impl* inherited Create; f_Description := aDesc; f_Converter := aConverter; f_Buffer := f_Converter.AllocateParamBuffer(f_Description); //#UC END# *5555AD6F0065_5555AD2A0004_impl* end;//TdaParam.Create class function TdaParam.Make(const aConverter: IdaDataConverter; const aDesc: IdaParamDescription): IdaParam; var l_Inst : TdaParam; begin l_Inst := Create(aConverter, aDesc); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end;//TdaParam.Make function TdaParam.Get_Name: AnsiString; //#UC START# *5555CC750283_5555AD2A0004get_var* //#UC END# *5555CC750283_5555AD2A0004get_var* begin //#UC START# *5555CC750283_5555AD2A0004get_impl* Result := f_Description.Name; //#UC END# *5555CC750283_5555AD2A0004get_impl* end;//TdaParam.Get_Name function TdaParam.IsSameType(const aDesc: IdaParamDescription): Boolean; //#UC START# *5555D4F5030D_5555AD2A0004_var* //#UC END# *5555D4F5030D_5555AD2A0004_var* begin //#UC START# *5555D4F5030D_5555AD2A0004_impl* Result := (f_Description.DataType = aDesc.DataType) and (f_Description.Size = aDesc.Size); //#UC END# *5555D4F5030D_5555AD2A0004_impl* end;//TdaParam.IsSameType function TdaParam.Get_AsInteger: LongInt; //#UC START# *5555E85C00B8_5555AD2A0004get_var* //#UC END# *5555E85C00B8_5555AD2A0004get_var* begin //#UC START# *5555E85C00B8_5555AD2A0004get_impl* f_Converter.ParamFromDataBase(f_Description, da_dtInteger, f_Buffer, @Result); //#UC END# *5555E85C00B8_5555AD2A0004get_impl* end;//TdaParam.Get_AsInteger procedure TdaParam.Set_AsInteger(aValue: LongInt); //#UC START# *5555E85C00B8_5555AD2A0004set_var* //#UC END# *5555E85C00B8_5555AD2A0004set_var* begin //#UC START# *5555E85C00B8_5555AD2A0004set_impl* f_Converter.ParamToDataBase(f_Description, da_dtInteger, @aValue, f_Buffer); //#UC END# *5555E85C00B8_5555AD2A0004set_impl* end;//TdaParam.Set_AsInteger function TdaParam.Get_DataBuffer: Pointer; //#UC START# *555D928D00E0_5555AD2A0004get_var* //#UC END# *555D928D00E0_5555AD2A0004get_var* begin //#UC START# *555D928D00E0_5555AD2A0004get_impl* Result := f_Buffer; //#UC END# *555D928D00E0_5555AD2A0004get_impl* end;//TdaParam.Get_DataBuffer function TdaParam.Get_AsLargeInt: LargeInt; //#UC START# *55FA75FD01D3_5555AD2A0004get_var* //#UC END# *55FA75FD01D3_5555AD2A0004get_var* begin //#UC START# *55FA75FD01D3_5555AD2A0004get_impl* f_Converter.ParamFromDataBase(f_Description, da_dtQWord, f_Buffer, @Result); //#UC END# *55FA75FD01D3_5555AD2A0004get_impl* end;//TdaParam.Get_AsLargeInt procedure TdaParam.Set_AsLargeInt(aValue: LargeInt); //#UC START# *55FA75FD01D3_5555AD2A0004set_var* //#UC END# *55FA75FD01D3_5555AD2A0004set_var* begin //#UC START# *55FA75FD01D3_5555AD2A0004set_impl* f_Converter.ParamToDataBase(f_Description, da_dtQWord, @aValue, f_Buffer); //#UC END# *55FA75FD01D3_5555AD2A0004set_impl* end;//TdaParam.Set_AsLargeInt function TdaParam.Get_AsString: AnsiString; //#UC START# *560CEA210293_5555AD2A0004get_var* //#UC END# *560CEA210293_5555AD2A0004get_var* begin //#UC START# *560CEA210293_5555AD2A0004get_impl* f_Converter.ParamFromDataBase(f_Description, da_dtChar, f_Buffer, @Result); //#UC END# *560CEA210293_5555AD2A0004get_impl* end;//TdaParam.Get_AsString procedure TdaParam.Set_AsString(const aValue: AnsiString); //#UC START# *560CEA210293_5555AD2A0004set_var* //#UC END# *560CEA210293_5555AD2A0004set_var* begin //#UC START# *560CEA210293_5555AD2A0004set_impl* f_Converter.ParamToDataBase(f_Description, da_dtChar, @aValue, f_Buffer); //#UC END# *560CEA210293_5555AD2A0004set_impl* end;//TdaParam.Set_AsString function TdaParam.Get_AsStDate: TStDate; //#UC START# *563C8B50016A_5555AD2A0004get_var* //#UC END# *563C8B50016A_5555AD2A0004get_var* begin //#UC START# *563C8B50016A_5555AD2A0004get_impl* f_Converter.ParamFromDataBase(f_Description, da_dtDate, f_Buffer, @Result); //#UC END# *563C8B50016A_5555AD2A0004get_impl* end;//TdaParam.Get_AsStDate procedure TdaParam.Set_AsStDate(const aValue: TStDate); //#UC START# *563C8B50016A_5555AD2A0004set_var* //#UC END# *563C8B50016A_5555AD2A0004set_var* begin //#UC START# *563C8B50016A_5555AD2A0004set_impl* f_Converter.ParamToDataBase(f_Description, da_dtDate, @aValue, f_Buffer); //#UC END# *563C8B50016A_5555AD2A0004set_impl* end;//TdaParam.Set_AsStDate function TdaParam.Get_AsStTime: TStTime; //#UC START# *564C37CF00C4_5555AD2A0004get_var* //#UC END# *564C37CF00C4_5555AD2A0004get_var* begin //#UC START# *564C37CF00C4_5555AD2A0004get_impl* f_Converter.ParamFromDataBase(f_Description, da_dtTime, f_Buffer, @Result); //#UC END# *564C37CF00C4_5555AD2A0004get_impl* end;//TdaParam.Get_AsStTime procedure TdaParam.Set_AsStTime(const aValue: TStTime); //#UC START# *564C37CF00C4_5555AD2A0004set_var* //#UC END# *564C37CF00C4_5555AD2A0004set_var* begin //#UC START# *564C37CF00C4_5555AD2A0004set_impl* f_Converter.ParamToDataBase(f_Description, da_dtTime, @aValue, f_Buffer); //#UC END# *564C37CF00C4_5555AD2A0004set_impl* end;//TdaParam.Set_AsStTime function TdaParam.Get_ParamType: TdaParamType; //#UC START# *5666822101CA_5555AD2A0004get_var* //#UC END# *5666822101CA_5555AD2A0004get_var* begin //#UC START# *5666822101CA_5555AD2A0004get_impl* Result := f_Description.ParamType; //#UC END# *5666822101CA_5555AD2A0004get_impl* end;//TdaParam.Get_ParamType function TdaParam.Get_AsByte: Byte; //#UC START# *578625FB03A1_5555AD2A0004get_var* //#UC END# *578625FB03A1_5555AD2A0004get_var* begin //#UC START# *578625FB03A1_5555AD2A0004get_impl* f_Converter.ParamFromDataBase(f_Description, da_dtByte, f_Buffer, @Result); //#UC END# *578625FB03A1_5555AD2A0004get_impl* end;//TdaParam.Get_AsByte procedure TdaParam.Set_AsByte(aValue: Byte); //#UC START# *578625FB03A1_5555AD2A0004set_var* //#UC END# *578625FB03A1_5555AD2A0004set_var* begin //#UC START# *578625FB03A1_5555AD2A0004set_impl* f_Converter.ParamToDataBase(f_Description, da_dtByte, @aValue, f_Buffer); //#UC END# *578625FB03A1_5555AD2A0004set_impl* end;//TdaParam.Set_AsByte procedure TdaParam.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_5555AD2A0004_var* //#UC END# *479731C50290_5555AD2A0004_var* begin //#UC START# *479731C50290_5555AD2A0004_impl* f_Converter.FreeParamBuffer(f_Description, f_Buffer); f_Description := nil; f_Converter := nil; inherited; //#UC END# *479731C50290_5555AD2A0004_impl* end;//TdaParam.Cleanup end.
unit GX_MenuActions; {$I GX_CondDefine.inc} interface uses GX_Actions, GX_Experts; type IGxMenuActionManager = interface(IUnknown) ['{79950A81-D020-11D3-A941-B048DE000000}'] function GetAlphabetical: Boolean; procedure SetAlphabetical(const DoAlphabetize: Boolean); function GetPlaceGxMainMenuInToolsMenu: Boolean; function GetHideWindowMenu: Boolean; procedure SetHideWindowMenu(const Value: Boolean); function GetMoveComponentMenu: Boolean; procedure SetMoveComponentMenu(const Value: Boolean); function RequestMenuExpertAction(Expert: TGX_Expert): IGxAction; procedure ArrangeMenuItems; procedure MoveMainMenuItems; property Alphabetical: Boolean read GetAlphabetical write SetAlphabetical; property PlaceGxMainMenuInToolsMenu: Boolean read GetPlaceGxMainMenuInToolsMenu; property HideWindowMenu: Boolean read GetHideWindowMenu write SetHideWindowMenu; property MoveComponentMenu: Boolean read GetMoveComponentMenu write SetMoveComponentMenu; end; function GXMenuActionManager: IGxMenuActionManager; procedure CreateGXMenuActionManager; procedure FreeGXMenuActionManager; implementation uses {$IFOPT D+} GX_DbugIntf, {$ENDIF} SysUtils, Windows, Classes, Graphics, ActnList, Menus, GX_GenericClasses, GX_ActionBroker, GX_ConfigurationInfo, GX_GExperts, GX_GenericUtils, GX_IdeUtils, GX_OtaUtils, Math, GX_KbdShortCutBroker; // We can enable a hack / kludge to get around // menu shortcut an initialization issue in // the IDE. {$DEFINE GX_UseMenuShortCutInitializationWorkAround} // **************************************************************************** // Implement a lookup table that allows for "historical" // ordering of expert menu item entries. type TMenuItemArray = array of TMenuItem; TGXMenuActionManager = class(TSingletonInterfacedObject, IGxMenuActionManager) private FConfigAction: IGxAction; FAboutAction: IGxAction; FMoreAction: IGxAction; FGExpertsTopLevelMenu: TMenuItem; procedure ConfigClick(Sender: TObject); procedure AboutClick(Sender: TObject); {$IFDEF GX_UseMenuShortCutInitializationWorkAround} procedure TopLevelMenuClick(Sender: TObject); {$ENDIF GX_UseMenuShortCutInitializationWorkAround} private function GetAlphabetical: Boolean; function GetPlaceGxMainMenuInToolsMenu: Boolean; procedure SetAlphabetical(const DoAlphabetize: Boolean); function CreateAction(const ACaption, AName: string; OnExecute: TNotifyEvent; Bitmap: Graphics.TBitmap; ShortCut: TShortCut; ExpertIndex, MenuItemIndex: Integer): IGxAction; procedure GetMenuItems(out MenuItems: TMenuItemArray; SkipMoreItems: Boolean = True); procedure MoreActionExecute(Sender: TObject); procedure SortMenuItems(var MenuItems: TMenuItemArray); procedure NormalizeMenuItems; protected // IGxMenuActionManager function RequestMenuExpertAction(Expert: TGX_Expert): IGxAction; function GetToolsMenuItem(Items: TMenuItem; out ToolsMenuItem: TMenuItem): Boolean; function GetMatchingMenuItem(Items: TMenuItem; const MenuName: string; out ItemIdx: Integer): Boolean; overload; function GetMatchingMenuItem(Items: TMenuItem; const MenuName: string; out MenuItem: TMenuItem): Boolean; overload; function GetHideWindowMenu: boolean; procedure SetHideWindowMenu(const Value: boolean); function GetMoveComponentMenu: Boolean; procedure SetMoveComponentMenu(const Value: Boolean); public constructor Create; virtual; destructor Destroy; override; procedure ArrangeMenuItems; procedure MoveMainMenuItems; property Alphabetical: Boolean read GetAlphabetical write SetAlphabetical; property PlaceGxMainMenuInToolsMenu: Boolean read GetPlaceGxMainMenuInToolsMenu; property HideWindowMenu: boolean read GetHideWindowMenu write SetHideWindowMenu; property MoveComponentMenu: Boolean read GetMoveComponentMenu write SetMoveComponentMenu; end; var PrivateGXMenuActionManager: TGXMenuActionManager = nil; const NonExpertItemTagStart = MaxInt - 100; MoreItemTag = NonExpertItemTagStart; SepItemTag = NonExpertItemTagStart + 1; ConfigItemTag = NonExpertItemTagStart + 2; AboutItemTag = NonExpertItemTagStart + 3; MoreMenuItemName = 'GExpertsMoreMenuItem'; function GXMenuActionManager: IGxMenuActionManager; begin Assert(PrivateGXMenuActionManager <> nil, 'PrivateGXMenuActionManager is nil'); Result := PrivateGXMenuActionManager; end; procedure CreateGXMenuActionManager; begin Assert(PrivateGXMenuActionManager = nil, 'PrivateGXMenuActionManager is not nil upon creation'); PrivateGXMenuActionManager := TGXMenuActionManager.Create; end; procedure FreeGXMenuActionManager; begin // Anything else would be an error in assumptions; // nothing fatal, but not good. {$IFOPT D+}Assert(PrivateGXMenuActionManager <> nil, 'PrivateGXMenuActionManager is nil');{$ENDIF} FreeAndNil(PrivateGXMenuActionManager); end; { TGXMenuActionManager } constructor TGXMenuActionManager.Create; resourcestring SGxConfigMenu = '&Configuration...'; SGxAboutMenu = 'About...'; var MainMenu: TMainMenu; Separator, ToolsMenuItem: TMenuItem; begin inherited Create; // Create GExperts drop down menu. FGExpertsTopLevelMenu := TMenuItem.Create(nil); {$IFDEF GX_UseMenuShortCutInitializationWorkAround} FGExpertsTopLevelMenu.OnClick := TopLevelMenuClick; {$ENDIF GX_UseMenuShortCutInitializationWorkAround} FMoreAction := GxActionBroker.RequestAction('GExpertsMoreAction', nil); // Do not localize. FMoreAction.Caption := 'More'; FMoreAction.OnExecute := MoreActionExecute; FGExpertsTopLevelMenu.Caption := 'GE&xperts'; // Do not localize. FGExpertsTopLevelMenu.Name := 'GExperts'; // Do not localize. // Now insert three menu items that are always appended to // the GExperts main menu item. // Insert separator. Separator := TMenuItem.Create(FGExpertsTopLevelMenu); Separator.Caption := '-'; // Do not localize. Separator.Name := 'GX_Sep1'; // Do not localize. Separator.Tag := SepItemTag; FGExpertsTopLevelMenu.Add(Separator); // Add hard-coded actions. FConfigAction := CreateAction(SGxConfigMenu, 'Configuration', ConfigClick, nil, 0, ConfigItemTag, 1); // Do not localize. FAboutAction := CreateAction(SGxAboutMenu, 'About', AboutClick, nil, 0, AboutItemTag, 2); // Do not localize. MainMenu := GxOtaGetIdeMainMenu; Assert(Assigned(MainMenu), 'MainMenu component not found'); // Insert GExperts drop down menu. if PlaceGxMainMenuInToolsMenu and GetToolsMenuItem(MainMenu.Items, ToolsMenuItem) then ToolsMenuItem.Insert(0, FGExpertsTopLevelMenu) else MainMenu.Items.Insert(MainMenu.Items.Count - 2, FGExpertsTopLevelMenu); Assert(FGExpertsTopLevelMenu.Count = 3); end; destructor TGXMenuActionManager.Destroy; begin // Release our main menu actions. FConfigAction := nil; FAboutAction := nil; FMoreAction := nil; // Free the top-level GExperts menu item. // This also frees also actions and contained // menu items. FreeAndNil(FGExpertsTopLevelMenu); inherited Destroy; end; procedure TGXMenuActionManager.ConfigClick(Sender: TObject); begin ShowGXConfigurationForm; end; procedure TGXMenuActionManager.AboutClick(Sender: TObject); begin ShowGXAboutForm; end; {$IFDEF GX_UseMenuShortCutInitializationWorkAround} procedure TGXMenuActionManager.TopLevelMenuClick(Sender: TObject); var i: Integer; Item: TMenuItem; AttachedAction: TCustomAction; MenuItems: TMenuItemArray; begin GetMenuItems(MenuItems); for i := 0 to (Length(MenuItems) - 1) do begin Item := MenuItems[i]; if Item.Action is TCustomAction then begin AttachedAction := TCustomAction(Item.Action); if Item.ShortCut <> AttachedAction.ShortCut then Item.ShortCut := AttachedAction.ShortCut; end; end; end; {$ENDIF GX_UseMenuShortCutInitializationWorkAround} function TGXMenuActionManager.GetAlphabetical: Boolean; begin Result := ConfigInfo.AlphabetizeMenu; end; procedure TGXMenuActionManager.SetAlphabetical(const DoAlphabetize: Boolean); begin if DoAlphabetize = Self.Alphabetical then Exit; ConfigInfo.AlphabetizeMenu := DoAlphabetize; // ArrangeMenuItems is called later end; function TGXMenuActionManager.GetHideWindowMenu: boolean; begin Result := ConfigInfo.HideWindowMenu; end; procedure TGXMenuActionManager.SetHideWindowMenu(const Value: boolean); var WindowMenu: TMenuItem; begin if not GetMatchingMenuItem(GxOtaGetIdeMainMenu.Items, 'WindowsMenu', WindowMenu) then Exit; WindowMenu.Visible := not Value; ConfigInfo.HideWindowMenu := Value; end; function TGXMenuActionManager.GetMoveComponentMenu: Boolean; begin Result := ConfigInfo.MoveComponentMenu; end; procedure TGXMenuActionManager.SetMoveComponentMenu(const Value: Boolean); var MainMenu: TMainMenu; Idx: Integer; ComponentMenu: TMenuItem; ToolsMenu: TMenuItem; begin MainMenu := GxOtaGetIdeMainMenu; if not GetToolsMenuItem(MainMenu.Items, ToolsMenu) then Exit; if Value then begin if not GetMatchingMenuItem(MainMenu.Items, 'ComponentMenu', Idx) then Exit; ComponentMenu := MainMenu.Items[Idx]; MainMenu.Items.Delete(Idx); // We cannot just append it because the IDE itself changes the tools menu, which might // remove the Component item again. If that happens, we won't be able to retrieve it, // should the user decide he wants it back in the main menu. So, we insert it at position // 2, just above the divider. ToolsMenu.Insert(2, ComponentMenu); ConfigInfo.MoveComponentMenu := True; end else begin if not GetMatchingMenuItem(ToolsMenu, 'ComponentMenu', Idx) then Exit; ComponentMenu := ToolsMenu.Items[Idx]; ToolsMenu.Delete(Idx); Idx := ToolsMenu.MenuIndex; if not PlaceGxMainMenuInToolsMenu then Dec(Idx); MainMenu.Items.Insert(Idx, ComponentMenu); ConfigInfo.MoveComponentMenu := False; end; end; function TGXMenuActionManager.RequestMenuExpertAction(Expert: TGX_Expert): IGxAction; begin Assert(Expert <> nil, 'Invalid nil Expert parameter for RequestMenuExpertAction'); // Create the action. Result := CreateAction(Expert.GetActionCaption, Expert.GetActionName, Expert.Execute, Expert.GetBitmap, Expert.ShortCut, Expert.ExpertIndex, 0); end; // Create an action and add it to the GExperts menu. function TGXMenuActionManager.CreateAction(const ACaption, AName: string; OnExecute: TNotifyEvent; Bitmap: Graphics.TBitmap; ShortCut: TShortCut; ExpertIndex, MenuItemIndex: Integer): IGxAction; var TempMenuItem: TMenuItem; begin Assert(Assigned(FGExpertsTopLevelMenu)); // Create the action with a linked menu item Result := GxActionBroker.RequestMenuAction(AName, Bitmap); TempMenuItem := (Result as IGxMenuAction).AssociatedMenuItem; Assert(Assigned(TempMenuItem)); // Save the associated expert's index into the menu // item for later sorting. TempMenuItem.Tag := ExpertIndex; // Insert the menu item. FGExpertsTopLevelMenu.Insert(MenuItemIndex, TempMenuItem); Result.Caption := ACaption; Result.Hint := StripHotkey(ACaption); Result.OnExecute := OnExecute; Result.ShortCut := ShortCut; end; function TGXMenuActionManager.GetPlaceGxMainMenuInToolsMenu: Boolean; begin Result := ConfigInfo.PlaceGxMainMenuInToolsMenu; end; function TGXMenuActionManager.GetMatchingMenuItem(Items: TMenuItem; const MenuName: string; out MenuItem: TMenuItem): Boolean; var Idx: Integer; begin Result := GetMatchingMenuItem(Items, MenuName, Idx); if Result then MenuItem := Items[Idx]; end; function TGXMenuActionManager.GetMatchingMenuItem(Items: TMenuItem; const MenuName: string; out ItemIdx: Integer): Boolean; var i: Integer; begin Result := False; for i := Items.Count - 1 downto 0 do begin if Items[i].Name = MenuName then begin Result := True; ItemIdx := i; Break; end; end; end; function TGXMenuActionManager.GetToolsMenuItem(Items: TMenuItem; out ToolsMenuItem: TMenuItem): Boolean; begin Result := GetMatchingMenuItem(Items, 'ToolsMenu', ToolsMenuItem); end; procedure TGXMenuActionManager.ArrangeMenuItems; function NewMoreItem(Num: Integer): TMenuItem; begin Result := TMenuItem.Create(FGExpertsTopLevelMenu); Result.Caption := 'More'; Result.Action := FMoreAction.GetAction; Result.Name := MoreMenuItemName + IntToStr(Num); Result.Tag := MoreItemTag; end; var i: Integer; ScreenRect: TRect; ScreenHeight: Integer; MaxMenuItems: Integer; MoreMenuItem: TMenuItem; ParentItem: TMenuItem; Item: TMenuItem; CurrentIndex: Integer; MenuItems: TMenuItemArray; function GetMenuItem(const ActName: string): TMenuItem; var j: Integer; FullActName: string; begin FullActName := GxActionBroker.GenerateMenuActionName(ActName); Result := nil; for j := 0 to Length(MenuItems) - 1 do begin if Assigned(MenuItems[j].Action) and (MenuItems[j].Action.Name = FullActName) then begin Result := MenuItems[j]; Break; end; end; end; begin {$IFOPT D+} SendDebug('Arranging menu items'); {$ENDIF} NormalizeMenuItems; GetMenuItems(MenuItems); if Assigned(MenuItems) then SortMenuItems(MenuItems); ScreenRect := GetScreenWorkArea(GetIdeMainForm); ScreenHeight := ScreenRect.Bottom - ScreenRect.Top - 75; if RunningDelphi7OrGreater then begin MaxMenuItems := ScreenHeight div GetMainMenuItemHeight; { TODO -oanybody -cbug : if the IDE window is not at the top of the screen, there is less space for the menu than the screen height. Depending on how far down it is, the menu will be drawn upwards, so at least half screen height is always available. If the menu needs more space, it will overlap the main menu item and releasing the mouse after clicking on the main menu item will trigger a click on the item then under the mouse. We could try to figure out how much space really is available and set MaxMenuItems to that number. } MaxMenuItems := Max(8, MaxMenuItems); end else MaxMenuItems := ScreenHeight; ParentItem := FGExpertsTopLevelMenu; CurrentIndex := 0; for i := 0 to Length(MenuItems) - 1 do begin Item := MenuItems[i]; if (CurrentIndex = MaxMenuItems - 1) and (i < (Length(MenuItems) - 1)) then begin MoreMenuItem := NewMoreItem(i); ParentItem.Add(MoreMenuItem); ParentItem := MoreMenuItem; CurrentIndex := 0; end; if Item.Parent <> ParentItem then begin Item.Parent.Remove(Item); ParentItem.Add(Item); end; Item.MenuIndex := CurrentIndex; Inc(CurrentIndex); end; for i := 0 to GExpertsInst.ExpertCount - 1 do begin ParentItem := GetMenuItem(GExpertsInst.ExpertList[i].GetActionName); if Assigned(ParentItem) then GExpertsInst.ExpertList[i].DoCreateSubMenuItems(ParentItem); end; end; procedure TGXMenuActionManager.MoveMainMenuItems; begin HideWindowMenu := HideWindowMenu; //FI:W503 - Assignment has side effects MoveComponentMenu := MoveComponentMenu; //FI:W503 - Assignment has side effects end; procedure TGXMenuActionManager.MoreActionExecute(Sender: TObject); begin // This is only here to enable the menu item end; procedure TGXMenuActionManager.GetMenuItems(out MenuItems: TMenuItemArray; SkipMoreItems: Boolean); procedure AddMenuItemsForParent(Parent: TMenuItem); var i: Integer; Item: TMenuItem; begin if Parent = nil then Exit; for i := 0 to Parent.Count - 1 do begin Item := Parent.Items[i]; if (not SkipMoreItems) or (Item.Tag <> MoreItemTag) then begin SetLength(MenuItems, Length(MenuItems) + 1); MenuItems[Length(MenuItems) - 1] := Item; end; end; for i := 0 to Parent.Count - 1 do begin Item := Parent.Items[i]; if (Item.Count > 0) and (Item.Tag = MoreItemTag) then AddMenuItemsForParent(Item); end; end; begin Assert(Assigned(FGExpertsTopLevelMenu)); AddMenuItemsForParent(FGExpertsTopLevelMenu); end; procedure TGXMenuActionManager.SortMenuItems(var MenuItems: TMenuItemArray); var i, j: Integer; TempItem: TMenuItem; Condition: Boolean; begin Assert(Assigned(MenuItems)); for i := 0 to Length(MenuItems) - 1 do begin for j := i to Length(MenuItems) - 1 do begin if Alphabetical then Condition := (MenuItems[j].Tag < NonExpertItemTagStart) and (AnsiCompareText(StripHotkey(MenuItems[i].Caption), StripHotkey(MenuItems[j].Caption)) > 0) else Condition := MenuItems[i].Tag > MenuItems[j].Tag; if Condition then begin TempItem := MenuItems[i]; MenuItems[i] := MenuItems[j]; MenuItems[j] := TempItem; end; end; end; end; procedure TGXMenuActionManager.NormalizeMenuItems; var MenuItems: TMenuItemArray; i: Integer; Item: TMenuItem; begin GetMenuItems(MenuItems, False); for i := 0 to Length(MenuItems) - 1 do begin Item := MenuItems[i]; if Item.Parent <> FGExpertsTopLevelMenu then begin Item.Parent.Remove(Item); FGExpertsTopLevelMenu.Add(Item); end; end; for i := 0 to Length(MenuItems) - 1 do begin if MenuItems[i].Tag = MoreItemTag then MenuItems[i].Free; end; end; initialization finalization // When Delphi itself crashes just before shutdown (common in D5-D7 when // writing the DSK and DOF files), this assertion just compounds problems. {$IFOPT D+}Assert(PrivateGXMenuActionManager = nil, 'PrivateGXMenuActionManager is not nil during finalization');{$ENDIF} end.
unit InputSearchHandler; interface uses Classes, VoyagerServerInterfaces, VoyagerInterfaces, Controls, InputSearchHandlerViewer, VCLUtils; const tidParmName_xPos = 'x'; tidParmName_yPos = 'y'; tidParmName_Fluid = 'Fluid'; tidParmName_Town = 'Town'; tidParmName_Owner = 'Owner'; tidParmName_Roles = 'Roles'; tidParmName_Count = 'Count'; tidParmName_World = 'WorldName'; const htmlAction_FindInputs = 'FINDCLIENTS'; type TMetaInputSearchHandler = class( TInterfacedObject, IMetaURLHandler ) public constructor Create; destructor Destroy; override; private function getName : string; function getOptions : TURLHandlerOptions; function getCanHandleURL( URL : TURL ) : THandlingAbility; function Instantiate : IURLHandler; end; TInputSearchHandler = class( TInterfacedObject, IURLHandler ) private constructor Create(MetaHandler : TMetaInputSearchHandler); destructor Destroy; override; private fMasterURLHandler : IMasterURLHandler; fControl : TInputSearchViewer; fClientView : IClientView; fxPos : integer; fyPos : integer; fFluid : string; fWorld : string; { fTown : string; fOwner : string; fRoles : integer; fCount : integer; } private function HandleURL( URL : TURL ) : TURLHandlingResult; function HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult; function getControl : TControl; procedure setMasterURLHandler( const URLHandler : IMasterURLHandler ); end; implementation uses SysUtils, URLParser, ServerCnxHandler, ServerCnxEvents, Events, Protocol; // TMetaInputSearchHandler constructor TMetaInputSearchHandler.Create; begin inherited; end; destructor TMetaInputSearchHandler.Destroy; begin inherited; end; function TMetaInputSearchHandler.getName : string; begin result := tidHandlerName_ClientFinder; end; function TMetaInputSearchHandler.getOptions : TURLHandlerOptions; begin result := [hopCacheable]; end; function TMetaInputSearchHandler.getCanHandleURL( URL : TURL ) : THandlingAbility; begin result := 0; end; function TMetaInputSearchHandler.Instantiate : IURLHandler; begin result := TInputSearchHandler.Create(self); end; // TInputSearchHandler constructor TInputSearchHandler.Create(MetaHandler : TMetaInputSearchHandler); begin inherited Create; fControl := TInputSearchViewer.Create( nil ); //fControl.URLHadler := self; end; destructor TInputSearchHandler.Destroy; begin RemoveComponentFreeAndNil(fControl); //.rag inherited; end; function TInputSearchHandler.HandleURL( URL : TURL ) : TURLHandlingResult; begin try if GetURLAction(URL) = htmlAction_FindInputs then try fXPos := StrToInt(GetParmValue(URL, tidParmName_xPos)); fYPos := StrToInt(GetParmValue(URL, tidParmName_yPos)); fFluid := GetParmValue(URL, tidParmName_Fluid); fWorld := GetParmValue(URL, tidParmName_World); fControl.InitViewer(fClientView, fXPos, fYPos, fWorld, fFluid); fControl.MasterURLHandler := fMasterURLHandler; result := urlHandled; except result := urlNotHandled; end else result := urlNotHandled; except result := urlNotHandled; end; end; function TInputSearchHandler.HandleEvent( EventId : TEventId; var info ) : TEventHandlingResult; var msg : TLinkSearchMsg; begin result := evnNotHandled; case EventId of evnRenderOutputClients : begin msg := TLinkSearchMsg(info); fControl.RenderResults(msg.Fluid, msg.Result); result := evnHandled; end; evnShutDown : //.rag begin fMasterURLHandler := nil; RemoveComponentFreeAndNil(fControl); //.rag fClientView := nil; end; end; end; function TInputSearchHandler.getControl : TControl; begin result := fControl; end; procedure TInputSearchHandler.setMasterURLHandler( const URLHandler : IMasterURLHandler ); begin fMasterURLHandler := URLHandler; fControl.MasterURLHandler := URLHandler; URLHandler.HandleEvent( evnAnswerClientView, fClientView ); end; end.
unit Control.CadastroRH; interface uses System.SysUtils, FireDAC.Comp.Client, Forms, Windows, Common.ENum, Model.CadastroRH; type TCadastroRHControl = class private FCadastro : TCadastroRH; public constructor Create; destructor Destroy; override; property RH: TCadastroRH read FCadastro write FCadastro; function Localizar(aParam: array of variant): boolean; function Gravar(): Boolean; function ValidaCampos(): Boolean; function SetupClass(FDQuery: TFDquery): boolean; function ClearClass(): boolean; end; implementation { TCadastroRHControl } function TCadastroRHControl.ClearClass: boolean; begin Result := FCadastro.ClearClass; end; constructor TCadastroRHControl.Create; begin FCadastro := TCadastroRH.Create; end; destructor TCadastroRHControl.Destroy; begin FCadastro.Free; inherited; end; function TCadastroRHControl.Gravar: Boolean; begin Result := False; if not ValidaCampos() then Exit; Result := FCadastro.Gravar; end; function TCadastroRHControl.Localizar(aParam: array of variant): Boolean; begin Result := FCadastro.Localizar(aParam); end; function TCadastroRHControl.SetupClass(FDQuery: TFDquery): boolean; begin Result := FCadastro.SetupClass(FDQuery); end; function TCadastroRHControl.ValidaCampos: Boolean; begin Result := False; if FCadastro.Funcao = 0 then begin Application.MessageBox('Informe a função deste colaborador.', 'Atenção', MB_OK + MB_ICONEXCLAMATION); Exit; end; if FCadastro.Adminissao = 0 then begin Application.MessageBox('Informe a data de admissão deste colaborador.', 'Atenção', MB_OK + MB_ICONEXCLAMATION); Exit; end; if not Fcadastro.NumeroCTPS.IsEmpty then begin if FCadastro.SerieCTPS.IsEmpty then begin Application.MessageBox('Informe a série da CTPS deste colaborador.', 'Atenção', MB_OK + MB_ICONEXCLAMATION); Exit; end; if FCadastro.UFCTPS.IsEmpty then begin Application.MessageBox('Informe a UF da CTPS deste colaborador.', 'Atenção', MB_OK + MB_ICONEXCLAMATION); Exit; end; end; if not Fcadastro.NumeroTituloEleitor.IsEmpty then begin if FCadastro.ZonaTituloEleitor.IsEmpty then begin Application.MessageBox('Informe Zona Eleitoral deste colaborador.', 'Atenção', MB_OK + MB_ICONEXCLAMATION); Exit; end; if FCadastro.SecaoTituloEleitor.IsEmpty then begin Application.MessageBox('Informe a Secão Eleitoral deste colaborador.', 'Atenção', MB_OK + MB_ICONEXCLAMATION); Exit; end; if FCadastro.MunicipioTituloEleitor.IsEmpty then begin Application.MessageBox('Informe Municipio Eleitoral deste colaborador.', 'Atenção', MB_OK + MB_ICONEXCLAMATION); Exit; end; if FCadastro.UFTituloEleitor.IsEmpty then begin Application.MessageBox('Informe a UF Eleitoral deste colaborador.', 'Atenção', MB_OK + MB_ICONEXCLAMATION); Exit; end; end; Result := True; end; end.
unit SendForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons; type TSenderForm = class(TForm) Button1: TButton; Memo1: TMemo; BitBtn1: TBitBtn; Button2: TButton; CheckBox1: TCheckBox; Edit1: TEdit; procedure ShowSender(Sender: TObject); private { Private declarations } public { Public declarations } end; var SenderForm: TSenderForm; implementation {$R *.DFM} procedure TSenderForm.ShowSender(Sender: TObject); begin Memo1.Lines.Add ('Class Name: ' + Sender.ClassName); if Sender.ClassParent <> nil then Memo1.Lines.Add ('Parent Class: ' + Sender.ClassParent.ClassName); Memo1.Lines.Add ('Instance Size: ' + IntToStr (Sender.InstanceSize)); // if the object is (exactly) of the TButton type if Sender.ClassType = TButton then Memo1.Lines.Add ('TButton ClassType'); // if the object is a given object if Sender = Button1 then Memo1.Lines.Add ('This is Button1'); if Sender.InheritsFrom (TButton) then Memo1.Lines.Add ('Sender inherits from TButton'); if Sender is TButton then Memo1.Lines.Add ('Sender is a TButton'); // leave a blank line Memo1.Lines.Add (''); end; end.
PROGRAM ConvertingNumber(INPUT, OUTPUT); VAR Number, Base, MultiplicationResult, AdditionResult, Remainder: INTEGER; BEGIN {ConvertingNumber} READ(Number, Base); IF ((Number >= 1) AND (Number <= 109)) AND ((Base >= 2) AND (Base <= 10)) THEN BEGIN MultiplicationResult := 1; AdditionResult := 0; WHILE Number >= Base DO BEGIN Remainder := Number MOD Base; MultiplicationResult := MultiplicationResult * Remainder; AdditionResult := AdditionResult + Remainder; Number := Number DIV Base END; MultiplicationResult := MultiplicationResult * Number; AdditionResult := AdditionResult + Number; WRITELN(MultiplicationResult - AdditionResult) END ELSE WRITELN('Введите корректное значение') END. {ConvertingNumber}
unit UOperationBlock; interface uses UAccountKey, URawBytes; type TOperationBlock = Record block: Cardinal; account_key: TAccountKey; reward: UInt64; fee: UInt64; protocol_version: Word; // Protocol version protocol_available: Word; // Used to upgrade protocol timestamp: Cardinal; // Timestamp creation compact_target: Cardinal; // Target in compact form nonce: Cardinal; // Random value to generate a new P-o-W block_payload : TRawBytes; // RAW Payload that a miner can include to a blockchain initial_safe_box_hash: TRawBytes; // RAW Safe Box Hash value (32 bytes, it's a Sha256) operations_hash: TRawBytes; // RAW sha256 (32 bytes) of Operations proof_of_work: TRawBytes; // RAW Double Sha256 end; var CT_OperationBlock_NUL : TOperationBlock; // initialized in initilization section implementation initialization Initialize(CT_OperationBlock_NUL); end.