text
stringlengths
14
6.51M
unit ManSoy.StrSub; interface uses windows, SysUtils, StrUtils; type TArrayString = array of string; //获取SubStr在Str中左边的部分字符串,从左起搜索 function GetLeftStr(SubStr, Str: string): string; //获取SubStr在Str中右边的部分字符串,从左起搜索 function GetRightStr(SubStr, Str: string): string; //获取SubStr在Str中左边的部分字符串,从右起搜索 function GetLeftEndStr(SubStr, Str: string): string; //获取SubStr在Str中右边的部分字符串,从右起搜索 function GetRightEndStr(SubStr, Str: string): string; //取得在LeftStr和RightStr中间的字符串,从左起搜索 function GetStr(LeftStr, RightStr, Str: string): string; //取得在LeftStr和RightStr中间的字符串,从右起搜索 function GetEndStr(LeftStr, RightStr, Str: string): string; //替换LeftStr与RighStr中间的字符串为ReplaceStr function ReplaceStr(LeftStr,RighStr,ReplaceStr,Str:string) : string; //取字符串左边长度为count的子串 function LeftStr(SourceStr : string; count : Integer):string; //取字符串右边长度为count的子串 function RightStr(SourceStr : string; count : Integer):string; //字符串截头 function _TrimLeft(SourceStr:string;TrimChar:Char):string; //字符串截尾 function _TrimRight(SourceStr:string;TrimChar:Char):string; //字符串截头尾 function _Trim(SourceStr:string;TrimChar:Char):string; //字符串分割 function SplitString(const Source,ch:string):TArrayString; function unicode2gb( unicodestr:string):string; implementation function unicode2gb( unicodestr:string):string; var SourceLength:integer; DoneLength:integer; AscNo:integer; Byte1,Byte2,Byte3:integer; GbStr:string; begin result:=''; if Trim(unicodestr)='' then exit; SourceLength:=Length(UnicodeStr); DoneLength:=1; repeat AscNo:=ord(UnicodeStr[DoneLength]); case (AscNo and $E0) of $E0:begin Byte1:=(AscNo and $0f) shl 12; Inc(DoneLength); if DoneLength>SourceLength then break; AscNo:=ord(UnicodeStr[DoneLength]); Byte2:=(AscNo and $3f) shl 6; Inc(DoneLength); if DoneLength>SourceLength then break; AscNo:=ord(UnicodeStr[DoneLength]); Byte3:=AscNo and $3f; end; $C0:begin Byte1:=(AscNo and $1f) shl 6; Inc(DoneLength); if DoneLength>SourceLength then break; AscNo:=ord(UnicodeStr[DoneLength]); Byte2:=(AscNo and $3f); Byte3:=0; end; 0..$bf:begin Byte1:=AscNo; Byte2:=0; Byte3:=0; end; end; //case; GbStr:=GBStr+widechar(Byte1+Byte2+Byte3); Inc(DoneLength); if DoneLength>SourceLength then break; until DoneLength>SourceLength; result:=GbStr; end; function GetLeftStr(SubStr, Str: string): string; begin Result := Copy(Str, 1, Pos(SubStr, Str) - 1); end; //------------------------------------------- function GetRightStr(SubStr, Str: string): string; var i: integer; begin i := pos(SubStr, Str); if i > 0 then Result := Copy(Str , i + Length(SubStr) , Length(Str) - i - Length(SubStr) + 1) else Result := ''; end; //------------------------------------------- function GetLeftEndStr(SubStr, Str: string): string; var i: integer; S: string; begin S := Str; Result := ''; repeat i := Pos(SubStr, S); if i > 0 then begin if Result <> '' then Result := Result + SubStr + GetLeftStr(SubStr, S) else Result := GetLeftStr(SubStr, S); S := GetRightStr(SubStr, S); end; until i <= 0; end; //------------------------------------------- function GetRightEndStr(SubStr, Str: string): string; var i: integer; begin Result := Str; repeat i := Pos(SubStr, Result); if i > 0 then begin Result := GetRightStr(SubStr, Result); end; until i <= 0; end; //------------------------------------------- function GetStr(LeftStr, RightStr, Str: string): string; begin Result := GetLeftStr(RightStr, GetRightStr(LeftStr, Str)); end; //------------------------------------------- function GetEndStr(LeftStr, RightStr, Str: string): string; begin Result := GetRightEndStr(LeftStr, GetLeftEndStr(RightStr, Str)); end; function ReplaceStr(LeftStr,RighStr,ReplaceStr,Str:string) : string; var I : Integer; szStr : string; szMidStr : string; begin I := Pos(LeftStr,Str); if I > 0 then begin szStr := GetRightStr(LeftStr,Str); szMidStr := GetLeftStr(RighStr,szStr); if Length(szMidStr) = 0 then begin Result := ''; end else begin szStr := LeftStr + szMidStr + RighStr; Result := StringReplace(Str,szStr,ReplaceStr,[]); end; end else begin Result := ''; end; end; //取字符串左边长度为count的子串 function LeftStr(SourceStr : string; count : Integer):string; var subCount : Integer; begin if count > Length(SourceStr) then begin subCount := Length(SourceStr); end else begin subCount := count; end; Result := Copy(SourceStr,0,subCount); end; //取字符串右边长度为count的子串 function RightStr(SourceStr : string; count : Integer):string; var subCount : Integer; begin if count > Length(SourceStr) then begin subCount := Length(SourceStr); end else begin subCount := count; end; Result := Copy(SourceStr,Length(SourceStr) - subCount + 1,subCount); end; function _TrimLeft(SourceStr:string;TrimChar:Char):string; var temStr : string; begin temStr := SourceStr; while temStr[1] = TrimChar do begin temStr := Copy(temStr,2,Length(temStr)-1); end; Result := temStr; end; function _TrimRight(SourceStr:string;TrimChar:Char):string; var temStr : string; begin temStr := SourceStr; while temStr[Length(temStr)] = TrimChar do begin temStr := Copy(temStr,1,Length(temStr)-1); end; Result := temStr; end; function _Trim(SourceStr:string;TrimChar:Char):string; var temStr : string; begin temStr := SourceStr; Result := _TrimRight(_TrimLeft(temStr,TrimChar),TrimChar); end; function SplitString(const Source,ch:string):TArrayString; var temp:String; i,index:Integer; begin index := 0; SetLength(Result,0); if Source='' then exit; temp:=Source; i:=pos(ch,Source); while i<>0 do begin SetLength(Result,index + 1); Result[index] := copy(temp,0,i-1); Delete(temp,1,i+ Length(ch) -1); i:=pos(ch,temp); Inc(index); end; SetLength(Result,index + 1); Result[index] := temp; end; end.
unit roIni; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, IniFiles; procedure GetIniSections(IniList, SectionsList : TStringList); procedure GetIniSection(const Section: string; Sections, Strings: TStrings); function ReadIniInteger(IniList, SectionsList : TStringList; const Section, Ident: string; Default: Longint): Longint; function ReadIniString(IniList, SectionsList : TStringList; const Section, Ident, Default: string): string; implementation procedure GetIniSections(IniList, SectionsList : TStringList); var I: Integer; S: string; Strings: TStrings; begin SectionsList.Clear; Strings := nil; for I := 0 to IniList.Count - 1 do begin S := IniList[I]; if (S <> '') and (S[1] <> ';') then begin if (S[1] = '[') and (S[Length(S)] = ']') then begin Strings := TStringList.Create; try SectionsList.AddObject(Copy(S, 2, Length(S) - 2), Strings); except FreeAndNil(Strings); end; end else begin if Strings <> nil then Strings.Add(S); end; end; end; end; procedure GetIniSection(const Section: string; Sections, Strings: TStrings); var I, J: Integer; SectionStrings: TStrings; begin Strings.BeginUpdate; try Strings.Clear; I := Sections.IndexOf(Section); if I >= 0 then begin SectionStrings := TStrings(Sections.Objects[I]); for J := 0 to SectionStrings.Count - 1 do Strings.Add(SectionStrings.Names[J]); end; finally Strings.EndUpdate; end; end; function ReadIniString(IniList, SectionsList : TStringList; const Section, Ident, Default: string): string; var I: Integer; Strings: TStrings; begin I := SectionsList.IndexOf(Section); if I >= 0 then begin Strings := TStrings(SectionsList.Objects[I]); I := Strings.IndexOfName(Ident); if I >= 0 then begin Result := Copy(Strings[I], Length(Ident) + 2, Maxint); Exit; end; end; Result := Default; end; function ReadIniInteger(IniList, SectionsList : TStringList; const Section, Ident: string; Default: Longint): Longint; var IntStr: string; begin IntStr := ReadIniString(IniList, SectionsList, Section, Ident, ''); if (Length(IntStr) > 2) and (IntStr[1] = '0') and ((IntStr[2] = 'X') or (IntStr[2] = 'x')) then IntStr := '$' + Copy(IntStr, 3, Maxint); Result := StrToIntDef(IntStr, Default); end; end.
unit pbv1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Menus, ComCtrls, ExtCtrls, StdCtrls, ProtBufParse; type TfrmProtBufViewMain = class(TForm) tvFields: TTreeView; MainMenu1: TMainMenu; File1: TMenuItem; Open1: TMenuItem; N1: TMenuItem; Exit1: TMenuItem; odBuffer: TOpenDialog; txtValue: TMemo; Splitter1: TSplitter; Openproto1: TMenuItem; Panel1: TPanel; cbMessages: TComboBox; odProto: TOpenDialog; procedure Exit1Click(Sender: TObject); procedure Open1Click(Sender: TObject); procedure tvFieldsDeletion(Sender: TObject; Node: TTreeNode); procedure tvFieldsChange(Sender: TObject; Node: TTreeNode); procedure tvFieldsExpanding(Sender: TObject; Node: TTreeNode; var AllowExpansion: Boolean); procedure FormResize(Sender: TObject); procedure Openproto1Click(Sender: TObject); procedure cbMessagesChange(Sender: TObject); private FDataFile,FProtoFile:string; FData:TStream; FProto:TProtocolBufferParser; procedure LoadFile(const FilePath:string); procedure LoadProto(const FilePath:string); procedure LoadFields(pos, max: int64; parent: TTreeNode; desc: TProtBufMessageDescriptor); protected procedure DoCreate; override; procedure DoDestroy; override; end; TNodeData=class(TObject) public procedure Node(n:TTreeNode); virtual; function Display: string; virtual; abstract; end; TMessageNodeData=class(TNodeData) private FTitle,FMessage:string; public constructor Create(const Title, Msg: string); procedure Node(n:TTreeNode); override; function Display: string; override; end; TErrorNodeData=class(TNodeData) private FMessage:string; public constructor Create(const Msg: string); procedure Node(n:TTreeNode); override; function Display: string; override; end; TNumberNodeData=class(TNodeData) private FValue:int64; public constructor Create(Value: int64); procedure Node(n:TTreeNode); override; function Display: string; override; end; TFixed64=array[0..7] of byte; TFixed32=array[0..3] of byte; TFixed64NodeData=class(TNodeData) private FValue:TFixed64; public constructor Create(const Value:TFixed64); procedure Node(n:TTreeNode); override; function Display: string; override; end; TFixed32NodeData=class(TNodeData) private FValue:TFixed32; public constructor Create(const Value:TFixed32); procedure Node(n:TTreeNode); override; function Display: string; override; end; TByLengthNodeData=class(TNodeData) private FData:TStream; FPos,FLen:int64; public constructor Create(Data:TStream;Pos,Len:int64); procedure Node(n:TTreeNode); override; function Display: string; override; property Pos: int64 read FPos; property Len: int64 read FLen; end; TStringNodeData=class(TNodeData) private FData:TStream; FPos,FLen:int64; FValue:string; public constructor Create(Data:TStream;Pos,Len:int64); procedure Node(n:TTreeNode); override; function Display: string; override; end; TEmbeddedMsgNodeData=class(TNodeData) private FName:string; FPos,FLen:int64; FDesc:TProtBufMessageDescriptor; public constructor Create(const Name: string; Pos, Len: int64; Desc: TProtBufMessageDescriptor); procedure Node(n:TTreeNode); override; function Display: string; override; property Pos: int64 read FPos; property Len: int64 read FLen; property Desc:TProtBufMessageDescriptor read FDesc; end; var frmProtBufViewMain: TfrmProtBufViewMain; implementation {$R *.dfm} { TfrmProtBufViewMain } procedure TfrmProtBufViewMain.DoCreate; var i:integer; fn:string; begin inherited; FDataFile:=''; FData:=nil; FProtoFile:=''; FProto:=TProtocolBufferParser.Create; case ParamCount of 1: begin fn:=ParamStr(1); i:=Length(fn); while (i<>0) and (fn[i]<>'.') do dec(i); if LowerCase(Copy(fn,i,Length(fn)-i+1))='.proto' then LoadProto(fn) else LoadFile(fn); end; 2: begin LoadProto(ParamStr(1)); cbMessages.ItemIndex:=0;//? LoadFile(ParamStr(2)); end; 3: begin LoadProto(ParamStr(1)); cbMessages.ItemIndex:=cbMessages.Items.IndexOf(ParamStr(2));//? LoadFile(ParamStr(3)); end; //else? end; end; procedure TfrmProtBufViewMain.DoDestroy; begin inherited; FProto.Free; FreeAndNil(FData); end; procedure TfrmProtBufViewMain.Exit1Click(Sender: TObject); begin Close; end; procedure TfrmProtBufViewMain.Open1Click(Sender: TObject); begin if odBuffer.Execute then LoadFile(odBuffer.FileName); end; procedure TfrmProtBufViewMain.tvFieldsDeletion(Sender: TObject; Node: TTreeNode); begin TTreeNode(Node.Data).Free; end; procedure TfrmProtBufViewMain.LoadFile(const FilePath: string); var f:TFileStream; m:TProtBufMessageDescriptor; begin FreeAndNil(FData); FDataFile:=FilePath; if FProtoFile='' then Caption:=FDataFile+' - Protocol Buffer Viewer' else Caption:=ExtractFileName(FDataFile)+' - '+ExtractFileName(FProtoFile)+ ' - Protocol Buffer Viewer'; Application.Title:=Caption; f:=TFileStream.Create(FilePath,fmOpenRead or fmShareDenyWrite); if f.Size>$100000 then FData:=f else begin FData:=TMemoryStream.Create; FData.CopyFrom(f,f.Size); f.Free; end; if cbMessages.ItemIndex=-1 then m:=nil else m:=cbMessages.Items.Objects[cbMessages.ItemIndex] as TProtBufMessageDescriptor; LoadFields(0,FData.Size,nil,m); end; function _ReadVarInt(Stream: TStream; var Value: cardinal): boolean; overload; var b:byte; i,l:integer; begin b:=0;//default i:=0; l:=Stream.Read(b,1); Value:=b and $7F; while (l<>0) and ((b and $80)<>0) do begin l:=Stream.Read(b,1); inc(i,7); Value:=Value or ((b and $7F) shl i); end; Result:=l<>0; end; function _ReadVarInt(Stream: TStream; var Value: int64): boolean; overload; var b:byte; i,l:integer; begin b:=0;//default i:=0; l:=Stream.Read(b,1); Value:=b and $7F; while (l<>0) and ((b and $80)<>0) do begin l:=Stream.Read(b,1); inc(i,7); Value:=Value or ((b and $7F) shl i); end; Result:=l<>0; end; function _UnZigZag(x:int64):int64; overload; begin if (x and 1)=0 then Result:=x shr 1 else Result:=-((x+1) shr 1); end; function _UnZigZag(x:integer):integer; overload; begin if (x and 1)=0 then Result:=x shr 1 else Result:=-((x+1) shr 1); end; procedure TfrmProtBufViewMain.LoadFields(pos, max: int64; parent: TTreeNode; desc: TProtBufMessageDescriptor); var n:TTreeNode; i,d:int64; d64:TFixed64 absolute d; d32:TFixed32 absolute d; dF64:double absolute d; dF32:single absolute d; FieldName,FieldType:string; Quant,TypeNr:integer; m:TProtBufMessageDescriptor; procedure Msg(const Title,Msg:string); begin TMessageNodeData.Create(Title,Msg).Node(n); end; begin FData.Position:=pos; tvFields.Items.BeginUpdate; try if parent=nil then tvFields.Items.Clear; while (FData.Position<max) and _ReadVarInt(FData,i) do begin if (desc=nil) or not(desc.MemberByKey(i shr 3, FieldName,FieldType,Quant,TypeNr)) then begin FieldName:=IntToStr(i shr 3); FieldType:=''; Quant:=0; TypeNr:=0; end; n:=tvFields.Items.AddChild(parent,FieldName+': '); //n.Data:= case i and $7 of 0://varint if _ReadVarInt(FData,d) then case TypeNr of TypeNr_int32: Msg(IntToStr(_UnZigZag(d)),'int32'#13#10+IntToStr(_UnZigZag(d))); TypeNr_int64: Msg(IntToStr(_UnZigZag(d)),'int64'#13#10+IntToStr(_UnZigZag(d))); TypeNr_uint32: Msg(IntToStr(d),'uint32'#13#10+IntToStr(d)); TypeNr_uint64: Msg(IntToStr(d),'uint64'#13#10+IntToStr(d)); TypeNr__typeByName://TypeNr_enum begin m:=FProto.MsgDescByName(desc,FieldType); if (m<>nil) and m.MemberByKey(d, FieldName,FieldType,Quant,TypeNr) then Msg(FieldName, 'enum '+FieldType+#13#10+IntToStr(d)+': '+FieldName) else TNumberNodeData.Create(d).Node(n) end; TypeNr_bool: Msg(IntToStr(d),'bool'#13#10+IntToStr(d)); else TNumberNodeData.Create(d).Node(n) end else TErrorNodeData.Create('read error').Node(n); 1://fixed64 if FData.Read(d64[0],8)=8 then case TypeNr of TypeNr_fixed64: Msg(IntToStr(d),'fixed64'#13#10+IntToStr(d)); TypeNr_sfixed64: Msg(IntToStr(d),'sfixed64'#13#10+IntToStr(d)); TypeNr_double: Msg(FloatToStr(dF64),'double'#13#10+FloatToStr(dF64)); else TFixed64NodeData.Create(d64).Node(n); end else TErrorNodeData.Create('read error').Node(n); 2://length delimited if _ReadVarInt(FData,d) then begin case TypeNr of TypeNr__typeByName://TypeNr_msg: begin m:=FProto.MsgDescByName(desc,FieldType); TEmbeddedMsgNodeData.Create(FieldType,FData.Position,d,m).Node(n); end; //TypeNr_bytes:; TypeNr_string: if d<$10000 then TStringNodeData.Create(FData,FData.Position,d).Node(n) else TByLengthNodeData.Create(FData,FData.Position,d).Node(n); else TByLengthNodeData.Create(FData,FData.Position,d).Node(n); end; FData.Seek(d,soFromCurrent); end else TErrorNodeData.Create('read error').Node(n); //3,4:raise Exception.Create('ProtBuf: groups are deprecated'); 5://fixed32 if FData.Read(d32[0],8)=8 then case TypeNr of TypeNr_fixed32: Msg(IntToStr(d),'fixed32'#13#10+IntToStr(d)); TypeNr_sfixed32: Msg(IntToStr(d),'sfixed32'#13#10+IntToStr(d)); TypeNr_float: Msg(FloatToStr(dF32),'float'#13#10+FloatToStr(dF32)); else TFixed32NodeData.Create(d32).Node(n); end else TErrorNodeData.Create('read error').Node(n); else TErrorNodeData.Create('Unknown wire type '+IntToHex(i,8)).Node(n); end; end; finally tvFields.Items.EndUpdate; end; end; procedure TfrmProtBufViewMain.tvFieldsChange(Sender: TObject; Node: TTreeNode); begin if Node.Data=nil then txtValue.Text:='' else txtValue.Text:=TNodeData(Node.Data).Display; end; procedure TfrmProtBufViewMain.tvFieldsExpanding(Sender: TObject; Node: TTreeNode; var AllowExpansion: Boolean); var d:TByLengthNodeData; e:TEmbeddedMsgNodeData; begin if Node.HasChildren and (Node.Count=0) then begin Node.HasChildren:=false; if Node.Data<>nil then begin if TNodeData(Node.Data) is TByLengthNodeData then begin d:=TNodeData(Node.Data) as TByLengthNodeData; LoadFields(d.Pos,d.Pos+d.Len,Node,nil); end; if TNodeData(Node.Data) is TEmbeddedMsgNodeData then begin e:=TNodeData(Node.Data) as TEmbeddedMsgNodeData; LoadFields(e.Pos,e.Pos+e.Len,Node,e.Desc); end; end; end; end; procedure TfrmProtBufViewMain.FormResize(Sender: TObject); begin cbMessages.Width:=Panel1.ClientWidth; end; procedure TfrmProtBufViewMain.Openproto1Click(Sender: TObject); begin if odProto.Execute then begin LoadProto(odProto.FileName); cbMessages.ItemIndex:=0; end; end; procedure TfrmProtBufViewMain.LoadProto(const FilePath: string); begin FProtoFile:=FilePath; if FDataFile='' then Caption:='('+FProtoFile+') - Protocol Buffer Viewer' else Caption:=ExtractFileName(FDataFile)+' - '+ExtractFileName(FProtoFile)+ ' - Protocol Buffer Viewer'; Application.Title:=Caption; FProto.Parse(FilePath); cbMessages.Items.BeginUpdate; try cbMessages.Items.Clear; FProto.ListDescriptors(cbMessages.Items); finally cbMessages.Items.EndUpdate; end; end; procedure TfrmProtBufViewMain.cbMessagesChange(Sender: TObject); var m:TProtBufMessageDescriptor; begin if FData<>nil then begin if cbMessages.ItemIndex=-1 then m:=nil else m:=cbMessages.Items.Objects[cbMessages.ItemIndex] as TProtBufMessageDescriptor; LoadFields(0,FData.Size,nil,m);//refresh end; end; { TNodeData } procedure TNodeData.Node(n: TTreeNode); begin n.Data:=Self; end; { TNumberNodeData } constructor TNumberNodeData.Create(Value: int64); begin inherited Create; FValue:=Value; end; function TNumberNodeData.Display: string; begin Result:=Format('varint'#13#10'unsigned: %d'#13#10'signed: %d'#13#10'%.16x', [FValue,_UnZigZag(FValue),FValue]); end; procedure TNumberNodeData.Node(n: TTreeNode); begin inherited; n.Text:=Format('%svarint %d %d',[n.Text,FValue,_UnZigZag(FValue)]); end; { TErrorNodeData } constructor TErrorNodeData.Create(const Msg: string); begin inherited Create; FMessage:=Msg; end; function TErrorNodeData.Display: string; begin Result:='!!!'#13#10+FMessage; end; procedure TErrorNodeData.Node(n: TTreeNode); begin inherited; n.Text:=n.Text+'!!! '+FMessage; end; { TFixed64NodeData } constructor TFixed64NodeData.Create(const Value: TFixed64); begin inherited Create; FValue:=Value; end; function TFixed64NodeData.Display: string; var d:TFixed64; d1:int64 absolute d; d2:double absolute d; begin d:=FValue; Result:=Format('fixed64'#13#10'unsigned: %d'#13#10'signed: %d'#13#10+ 'float: %f'#13#10'%.2x %.2x %.2x %.2x %.2x %.2x %.2x %.2x', [d1,d1,d2,d[0],d[1],d[2],d[3],d[4],d[5],d[6],d[7]]); end; procedure TFixed64NodeData.Node(n: TTreeNode); var d:TFixed64; d1:int64 absolute d; d2:double absolute d; begin inherited; d:=FValue; n.Text:=Format('%sfixed64 %d %f',[n.Text,d1,d2]); end; { TFixed32NodeData } constructor TFixed32NodeData.Create(const Value: TFixed32); begin inherited Create; FValue:=Value; end; function TFixed32NodeData.Display: string; var d:TFixed32; d1:cardinal absolute d; d2:integer absolute d; d3:single absolute d; begin d:=FValue; Result:=Format('fixed32'#13#10'unsigned: %d'#13#10'signed: %d'#13#10+ 'float: %f'#13#10'%.2x %.2x %.2x %.2x', [d1,d2,d3,d[0],d[1],d[2],d[3]]); end; procedure TFixed32NodeData.Node(n: TTreeNode); var d:TFixed32; d1:integer absolute d; d2:double absolute d; begin inherited; d:=FValue; n.Text:=Format('%sfixed32 %d %f',[n.Text,d1,d2]); end; { TByLengthNodeData } constructor TByLengthNodeData.Create(Data: TStream; Pos, Len: int64); begin inherited Create; FData:=Data; FPos:=Pos; FLen:=Len; end; function TByLengthNodeData.Display: string; var x:integer; begin Result:=Format('@%d:%d'#13#10,[FPos,FLen]); if FLen<$10000 then begin x:=Length(Result); SetLength(Result,x+FLen); FData.Position:=FPos; FData.Read(Result[x+1],FLen); end; //TODO: 'double click to...'; end; procedure TByLengthNodeData.Node(n: TTreeNode); begin inherited; n.Text:=Format('%sbyLength @%d :%d',[n.Text,FPos,FLen]); n.HasChildren:=FLen<>0; end; { TMessageNodeData } constructor TMessageNodeData.Create(const Title, Msg: string); begin inherited Create; FTitle:=Title; FMessage:=Msg; end; function TMessageNodeData.Display: string; begin Result:=FMessage; end; procedure TMessageNodeData.Node(n: TTreeNode); begin inherited; n.Text:=n.Text+FTitle; end; { TStringNodeData } constructor TStringNodeData.Create(Data: TStream; Pos, Len: int64); begin inherited Create; FData:=Data; FPos:=Pos; FLen:=Len; FValue:='';//see Node end; function TStringNodeData.Display: string; begin Result:=FValue;//more info? end; procedure TStringNodeData.Node(n: TTreeNode); var p:int64; begin inherited; SetLength(FValue,FLen); p:=FData.Position; if FData.Read(FValue[1],FLen)<>FLen then FValue:='!!! READ ERROR !!!';//raise? FData.Position:=p; n.Text:=Format('%s(%d)"%s"',[n.Text,FLen, StringReplace(FValue,'"','\"',[rfReplaceAll])]); end; { TEmbeddedMsgNodeData } constructor TEmbeddedMsgNodeData.Create(const Name: string; Pos, Len: int64; Desc: TProtBufMessageDescriptor); begin inherited Create; FName:=Name; FPos:=Pos; FLen:=Len; FDesc:=Desc; end; function TEmbeddedMsgNodeData.Display: string; begin Result:=FName; end; procedure TEmbeddedMsgNodeData.Node(n: TTreeNode); begin inherited; n.Text:=n.Text+FName; n.HasChildren:=FLen<>0; end; end.
{ Sometime mods are released for another language, or author accidently edited some records and they got saved with a different language. This script will copy FULL and DESC subrecords from master to restore original names. } unit UserScript; function Process(e: IInterface): integer; var m: IInterface; begin if not ElementExists(e, 'FULL') and not ElementExists(e, 'DESC') then Exit; // get master record m := Master(e); // no master - nothing to restore if not Assigned(m) then Exit; // if record overrides several masters, then get the last one if OverrideCount(m) > 1 then m := OverrideByIndex(m, OverrideCount(m) - 2); if not SameText(GetElementEditValues(e, 'FULL'), GetElementEditValues(m, 'FULL')) then SetElementEditValues(e, 'FULL', GetElementEditValues(m, 'FULL')); if not SameText(GetElementEditValues(e, 'DESC'), GetElementEditValues(m, 'DESC')) then SetElementEditValues(e, 'DESC', GetElementEditValues(m, 'DESC')); end; end.
unit AddHTML; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, XPButton, StdCtrls, ComCtrls, XPCheckBox, AppEvnts, ToolWin, FreeButton, XPPanel, Menus, StdActns, ActnList; type TWmMoving = record Msg: Cardinal; fwSide: Cardinal; lpRect: PRect; Result: Integer; end; type TAddHTMLFrm = class(TForm) OptionsMenu: TPopupMenu; CleanItem: TMenuItem; FullScreenItem: TMenuItem; OpenItem: TMenuItem; SaveItem: TMenuItem; CloseItem: TMenuItem; CopyItem: TMenuItem; CutItem: TMenuItem; DelItem: TMenuItem; PasteItem: TMenuItem; UndoItem: TMenuItem; sp1: TMenuItem; SelectAllItem: TMenuItem; EditItem: TMenuItem; ActionList: TActionList; EditCut: TEditCut; EditCopy: TEditCopy; EditPaste: TEditPaste; EditSelectAll: TEditSelectAll; EditUndo: TEditUndo; EditDelete: TEditDelete; sp2: TMenuItem; sp3: TMenuItem; sp5: TMenuItem; sp4: TMenuItem; PageControl: TPageControl; HTMLEditorTab: TTabSheet; HTMLPageTab: TTabSheet; HTMLEditor: TRichEdit; fr1: TXPPanel; Replace: TFreeButton; Add: TFreeButton; Options: TFreeButton; HTMLPage: TRichEdit; fr2: TXPPanel; AddToPage: TFreeButton; StatusBar: TStatusBar; procedure ReplaceClick(Sender: TObject); procedure AddClick(Sender: TObject); procedure OptionsClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure CleanItemClick(Sender: TObject); procedure FullScreenItemClick(Sender: TObject); procedure OpenItemClick(Sender: TObject); procedure SaveItemClick(Sender: TObject); procedure CloseItemClick(Sender: TObject); procedure HTMLEditorKeyPress(Sender: TObject; var Key: Char); procedure AddToPageClick(Sender: TObject); procedure FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure FormDestroy(Sender: TObject); private public procedure HTMLSyntax(RichEdit: TRichEdit; TextCol, TagCol, DopCol: TColor); procedure WMGetMinMaxInfo(var msg: TWMGetMinMaxInfo); message WM_GETMINMAXINFO; procedure WMMoving(var msg: TWMMoving); message WM_MOVING; end; var AddHTMLFrm: TAddHTMLFrm; implementation {$R *.dfm} uses MSHTML, ActiveX, SHDocVw, NP, OP; const Rect: TRect = (Left: 0; Top: 0; Right: 0; Bottom: 0); FullScreen: Boolean = False; procedure WB_LoadHTML(WebBrowser: TWebBrowser; HTMLCode: string); var sl: TStringList; ms: TMemoryStream; begin WebBrowser.Navigate('about:blank'); while WebBrowser.ReadyState < READYSTATE_INTERACTIVE do Application.ProcessMessages; if Assigned(WebBrowser.Document) then begin sl := TStringList.Create; try ms := TMemoryStream.Create; try sl.Text := HTMLCode; sl.SaveToStream(ms); ms.Seek(0, 0); (WebBrowser.Document as IPersistStreamInit).Load(TStreamAdapter.Create(ms)); finally ms.Free; end; finally sl.Free; end; end; end; procedure TAddHTMLFrm.ReplaceClick(Sender: TObject); begin try WB_LoadHTML(MainFrm.GetCurrentWB, HTMLEditor.Text); except end; end; procedure TAddHTMLFrm.AddClick(Sender: TObject); var WebDoc: HTMLDocument; WebBody: HTMLBody; begin try WebDoc := MainFrm.WebBrowser.Document as HTMLDocument; WebBody := WebDoc.body as HTMLBody; WebBody.insertAdjacentHTML('BeforeEnd', HTMLEditor.Text); except end; end; procedure TAddHTMLFrm.OptionsClick(Sender: TObject); var Pt:TPoint; begin Pt.x := Options.Width; Pt.y := 0; Pt := Options.ClientToScreen(Pt); OptionsMenu.Popup(Pt.x, Pt.y) end; procedure TAddHTMLFrm.FormShow(Sender: TObject); begin PageControl.ActivePageIndex := 0; if SetFrm.ch18.Checked then begin SetWindowLong(AddHTMLFrm.Handle, GWL_EXSTYLE, GetWindowLOng(AddHTMLFrm.Handle, GWL_EXSTYLE) or WS_EX_APPWINDOW); end; HTMLEditor.Lines.BeginUpdate; HTMLSyntax(HTMLEditor, clRed, clBlack, clBlue); HTMLEditor.Lines.EndUpdate; end; procedure TAddHTMLFrm.WMGetMinMaxInfo(var msg: TWMGetMinMaxInfo); begin inherited; with msg.MinMaxInfo^.ptMaxTrackSize do begin X := GetDeviceCaps( Canvas.handle, HORZRES ) + (Width - ClientWidth); Y := GetDeviceCaps( Canvas.handle, VERTRES ) + (Height - ClientHeight ); end; end; procedure TAddHTMLFrm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin if not FullScreenItem.Checked then begin if Key = vk_Escape then Close; end; if FullScreenItem.Checked then begin if Key = vk_Escape then FullScreenItem.Click; end; end; procedure TAddHTMLFrm.CleanItemClick(Sender: TObject); begin HTMLEditor.Lines.Clear; end; procedure TAddHTMLFrm.FullScreenItemClick(Sender: TObject); begin FullScreen := not FullScreen; if FullScreen then begin FullScreenItem.Checked := True; Rect := BoundsRect; SetBounds( Left - ClientOrigin.X, Top - ClientOrigin.Y, GetDeviceCaps( Canvas.handle, HORZRES ) + (Width - ClientWidth), GetDeviceCaps( Canvas.handle, VERTRES ) + (Height - ClientHeight )); end else begin BoundsRect := Rect; end; end; procedure TAddHTMLFrm.OpenItemClick(Sender: TObject); var TextString: String; begin try if OpenSaveFileDialog(Handle, '*.html', 'Веб-страницы (*.htm;*.html)|*.htm;*.html|Текстовые документы (*.txt)|*.txt|Все файлы (*.*)|*.*', ParamStr(1), 'Открыть', TextString, True) then begin HTMLEditor.Clear; HTMLEditor.Lines.LoadFromFile(TextString); end; except end; end; procedure TAddHTMLFrm.SaveItemClick(Sender: TObject); var TextString: String; begin try if OpenSaveFileDialog(AddHTMLFrm.Handle, '*.html', 'Веб-страницы (*.htm;*.html)|*.htm;*.html|Текстовые документы (*.txt)|*.txt|', ParamStr(1), 'Сохранить', TextString, False) then begin PostMessage(Handle, WM_USER + 1024, 0, 0); if FileExists(TextString) then if Application.MessageBox(PChar('Файл "' + TextString + '" существует.' + #13 + 'Заменить его?'), 'Подтвердите замену', MB_ICONQUESTION + mb_YesNo) <> idYes then else HTMLEditor.Lines.SaveToFile(TextString); if not FileExists(TextString) then HTMLEditor.Lines.SaveToFile(TextString); end; except end; end; procedure TAddHTMLFrm.CloseItemClick(Sender: TObject); begin AddHTMLFrm.Close; end; procedure TAddHTMLFrm.HTMLEditorKeyPress(Sender: TObject; var Key: Char); begin try HTMLSyntax(HTMLEditor, clRed, clBlack, clBlue); except end; end; procedure TAddHTMLFrm.AddToPageClick(Sender: TObject); var TextString: String; begin try if OpenSaveFileDialog(AddHTMLFrm.Handle, '*.html', 'Веб-страницы (*.htm;*.html)|*.htm;*.html|Текстовые документы (*.txt)|*.txt|', ParamStr(1), 'Сохранить', TextString, False) then begin PostMessage(Handle, WM_USER + 1024, 0, 0); if FileExists(TextString) then if Application.MessageBox(PChar('Файл "' + TextString + '" существует.' + #13 + 'Заменить его?'), 'Подтвердите замену', MB_ICONQUESTION + mb_YesNo) <> idYes then else HTMLPage.Lines.SaveToFile(TextString); if not FileExists(TextString) then HTMLPage.Lines.SaveToFile(TextString); end; except end; end; procedure TAddHTMLFrm.HTMLSyntax(RichEdit: TRichEdit; TextCol, TagCol, DopCol: TColor); var i, iDop: Integer; s: string; Col: TColor; isTag, isDop: Boolean; begin iDop := 0; isDop := False; isTag := False; Col := TextCol; RichEdit.SetFocus; for i := 0 to Length(RichEdit.Text) do begin RichEdit.SelStart := i; RichEdit.SelLength := 1; s := RichEdit.SelText; if (s = '<') or (s = '{') then isTag := True; if isTag then if (s = '"') then if not isDop then begin iDop := 1; isDop := True; end else isDop := False; if isTag then if isDop then begin if iDop <> 1 then Col := DopCol; end else Col := TagCol else Col := TextCol; RichEdit.SelAttributes.Color := Col; iDop := 0; if (s = '>') or (s = '}') then isTag := False; end; RichEdit.SelLength := 0; end; procedure TAddHTMLFrm.FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if SetFrm.ch19.Checked then begin ReleaseCapture; Perform(Wm_SysCommand, $f012, 0); end; end; procedure TAddHTMLFrm.WMMoving(var msg: TWMMoving); var r: TRect; begin if SetFrm.ch21.Checked then begin r := Screen.WorkareaRect; if msg.lprect^.left < r.left then OffsetRect(msg.lprect^, r.left - msg.lprect^.left, 0); if msg.lprect^.top < r.top then OffsetRect(msg.lprect^, 0, r.top - msg.lprect^.top); if msg.lprect^.right > r.right then OffsetRect(msg.lprect^, r.right - msg.lprect^.right, 0); if msg.lprect^.bottom > r.bottom then OffsetRect(msg.lprect^, 0, r.bottom - msg.lprect^.bottom); end; inherited; end; procedure TAddHTMLFrm.FormDestroy(Sender: TObject); begin PageControl.Free; OptionsMenu.Free; HTMLEditor.Free; ActionList.Free; StatusBar.Free; AddToPage.Free; StatusBar.Free; HTMLPage.Free; Options.Free; Replace.Free; Add.Free; fr1.Free; fr2.Free; end; end.
unit uDataStructures; interface type PsllItem = ^TsllItem; TsllItem = record next: PsllItem; data: pointer end; PdllItem = ^TdllItem; TdllItem = record next, prev: PdllItem; data: pointer end; TSingleLinkedList = class protected fCur, fRoot: PsllItem; function getBookmark: pointer; procedure setBookmark(const value: pointer); function getData: pointer; procedure setData(const value: pointer); public destructor destroy; override; function hasNext(): boolean; function isEmpty(): boolean; function next(): pointer; function first(): pointer; procedure clear(); //current element not changed procedure insertAfter(aData: pointer); procedure insertFirst(aData: pointer); procedure reverse(); //next after delete element become current function deleteFirst(): pointer; function deleteNext(): pointer; property data: pointer read getData write setData; property bookmark: pointer read getBookmark write setBookmark; end; TDualLinkedRing = class private function getBookmark: pointer; procedure setBookmark(const value: pointer); protected fCur, fRoot: PdllItem; function getData: pointer; procedure setData(const value: pointer); public destructor destroy; override; function hasNext(): boolean; function hasPrev(): boolean; function isEmpty(): boolean; function next(): pointer; function prev(): pointer; function first(): pointer; //append list A before current element. //Example: //self=(a,b,C,d) C-current a-first //A=(e,F,g) F-current d-first //result=(a,b,f,g,e,C,d) C-current a-first //List A after appending cleared and freed. procedure appendBefore(var a:TDualLinkedRing); procedure clear(); procedure insert(aData: pointer); procedure insertAfter(aData: pointer); procedure insertBefore(aData: pointer); procedure insertFirst(aData: pointer); procedure insertLast(aData: pointer); //delete root item. If cur==root, then set cur to second // (a),(root_b),(cur_c),(d) => (a),(root_cur_c),(d) // (a),(root_cur_b),(c),(d) => (a),(root_cur_c),(d) function deleteFirst(): pointer; //delete item before root // (a),(cur_b),(root_c),(d) => (a),(root_cur_c),(d) // (a),(b),(root_cur_c),(d) => (a),(root_cur_c),(d) function deleteLast(): pointer; //delete cur item & set cur pos to next after deleted. // (a),(cur_b),(c),(d) => (a),(cur_c),(d) function delete(): pointer; property data: pointer read getData write setData; property bookmark: pointer read getBookmark write setBookmark; end; type TCompareProc=function(i,j:integer):integer of object; TSwapProc=procedure(i,j:integer) of object; procedure Sort(min,max:integer; cmp:TCompareProc; swp:TSwapProc); implementation procedure Sort(min,max:integer; cmp:TCompareProc;swp:TSwapProc); procedure qSort(L,R:integer); var I, J, P: Integer; begin repeat I := L; J := R; P := (L + R)div 2; repeat while cmp(I, P) < 0 do Inc(I); while cmp(P, J) < 0 do Dec(J); if I <= J then begin swp(I,J); if(I=P)then P:=J else if(P=J)then P:=I; Inc(I); Dec(J); end; until I > J; if L < J then qSort(L, J); L := I; until I >= R; end; begin if(min<max)then qSort(min,max); end; { TSingleLinkedList } procedure TSingleLinkedList.clear; begin while assigned(fRoot) do deleteFirst(); end; function TSingleLinkedList.deleteNext: pointer; var p: PsllItem; begin result := nil; if assigned(fCur) then begin p := fCur.next; if assigned(p) then begin result := p.data; fCur.next := p.next; dispose(p); end; end; end; function TSingleLinkedList.deleteFirst: pointer; var p: PsllItem; begin p := fRoot; if fCur = p then fCur := p.next; fRoot := p.next; result := p.data; dispose(p); end; destructor TSingleLinkedList.destroy; begin clear(); inherited; end; function TSingleLinkedList.getData: pointer; begin result := fCur.data; end; function TSingleLinkedList.hasNext: boolean; begin result := assigned(fCur) and assigned(fCur.next); end; procedure TSingleLinkedList.insertAfter(aData: pointer); var p: PsllItem; begin new(p); p.data := aData; if not assigned(fRoot) then begin fRoot := p; fCur := p; p.next := nil; end else begin p.next := fCur.next; fCur.next := p; end; end; procedure TSingleLinkedList.insertFirst(aData: pointer); var p: PsllItem; begin new(p); p.next := fRoot; fRoot := p; if not assigned(fCur) then fCur := p; end; function TSingleLinkedList.next: pointer; begin fCur := fCur.next; if assigned(fCur) then result := fCur.data else result := nil; end; function TSingleLinkedList.first: pointer; begin fCur := fRoot; if assigned(fRoot) then result := fRoot.data else result := nil; end; procedure TSingleLinkedList.reverse; var p, c, n: PsllItem; begin c := fRoot; p := nil; while assigned(c) do begin n := p.next; c.next := p; p := c; c := n; end; fRoot := p; end; procedure TSingleLinkedList.setData(const value: pointer); begin fCur.data := value; end; function TSingleLinkedList.isEmpty: boolean; begin result := not assigned(fRoot); end; function TSingleLinkedList.getBookmark: pointer; begin result := fCur; end; procedure TSingleLinkedList.setBookmark(const value: pointer); begin fCur := value; end; { TDualLinkedRing } procedure TDualLinkedRing.clear; begin while assigned(fRoot) do deleteFirst(); end; function TDualLinkedRing.delete: pointer; var p: PdllItem; begin p := fCur; if p = fRoot then begin result := deleteFirst(); end else begin result := p.data; fCur := p.next; p.next.prev := p.prev; p.prev.next := p.next; dispose(p); end; end; function TDualLinkedRing.deleteFirst: pointer; var p: PdllItem; begin p := fRoot; if fCur = p then fCur := p.next; if p.next = p then begin //one-item list fRoot := nil; fCur := nil; end else begin //move to second item if fCur = p then fCur := p.next; //remove from list p.next.prev := p.prev; p.prev.next := p.next; fRoot := p.next; end; result := p.data; dispose(p); end; function TDualLinkedRing.deleteLast: pointer; begin fRoot := fRoot.prev; result := deleteFirst(); end; destructor TDualLinkedRing.destroy; begin clear(); inherited; end; function TDualLinkedRing.getBookmark: pointer; begin result := fCur; end; function TDualLinkedRing.getData: pointer; begin result := fCur.data; end; function TDualLinkedRing.hasNext: boolean; begin result := assigned(fCur) and (fCur.next <> fRoot); end; function TDualLinkedRing.hasPrev: boolean; begin result := assigned(fCur) and (fCur <> fRoot); end; procedure TDualLinkedRing.insertAfter(aData: pointer); var p: PdllItem; begin new(p); p.data := aData; if not assigned(fRoot) then begin //empty ring - new item become root fRoot := p; p.next:=p; p.prev:=p; end; if not assigned(fCur) then begin //no current item - root become current fCur := fRoot; end; //insert new between current and next. Current item not changed. p.prev := fCur; p.next := fCur.next; p.next.prev := p; p.prev.next := p; end; procedure TDualLinkedRing.insertBefore(aData: pointer); var p: PdllItem; begin new(p); p.data := aData; if not assigned(fRoot) then fRoot := p; if not assigned(fCur) then begin fCur := p; p.prev := p; end; p.next := fCur; p.prev := fCur.prev; p.next.prev := p; p.prev.next := p; end; procedure TDualLinkedRing.insertFirst(aData: pointer); var p: PdllItem; begin new(p); p.data := aData; if not assigned(fRoot) then begin fRoot := p; p.next := p; p.prev := p; end; if not assigned(fCur) then fCur := p; p.next := fRoot; p.prev := fRoot.prev; p.next.prev := p; p.prev.next := p; fRoot:=p; fCur:=p; end; procedure TDualLinkedRing.insertLast(aData: pointer); begin insertFirst(aData); fRoot := fRoot.next; end; function TDualLinkedRing.isEmpty: boolean; begin result := not assigned(fRoot); end; function TDualLinkedRing.next: pointer; begin fCur := fCur.next; result := fCur.data; end; function TDualLinkedRing.prev: pointer; begin fCur := fCur.prev; result := fCur.data; end; function TDualLinkedRing.first: pointer; begin fCur := fRoot; result := fRoot.data; end; procedure TDualLinkedRing.setBookmark(const value: pointer); begin fCur := value; end; procedure TDualLinkedRing.setData(const value: pointer); begin fCur.data := value; end; procedure TDualLinkedRing.appendBefore(var a: TDualLinkedRing); var selfPrev,aPrev:PdllItem; begin if not assigned(fCur) then fCur:=fRoot; if not assigned(fCur) then begin //empty self-list. append a-list at root fRoot:=a.fRoot; fCur:=a.fCur; a.fRoot:=nil; end else begin //self not empty if not assigned(a.fCur) then a.fCur:=a.fRoot; if assigned(a.fCur) then begin //a-list not empty. aPrev:=a.fCur.prev; selfPrev:=fCur.prev; //update forward-direction links selfPrev.next:=a.fCur; aPrev.next:=fCur; //update backward-direction links fCur.prev:=aPrev; a.fCur.prev:=selfPrev; end; a.fRoot:=nil; end; a.free; a:=nil; end; procedure TDualLinkedRing.insert(aData: pointer); begin insertAfter(aData); fCur:=fCur.next; end; end.
UNIT EVAL; (* This program acts like a calculator - You type an expression *) (* and the program calculates its value. *) (* There are five different operators (^, *) (* *, /, +, and -), and seven standard functions (ABS, SQRT, *) (* SIN, COS, ARCTAN, LN, and EXP). Parentheses within expres- *) (* sions are allowed. A special variable, called X, always *) (* holds the value FOR computation. *) INTERFACE TYPE EXPSTR = STRING;{BUT LENGTH OF INPUTTED STRING SHALL NOT EXCEED 80} {X-is the value replacement for appearing X variable} PROCEDURE EVALUATE(EXPR: EXPSTR; X:REAL; VAR VALUE: REAL; VAR EXPERR,ERR:BOOLEAN); FUNCTION PWRTEN(ET:INTEGER):REAL; IMPLEMENTATION FUNCTION VALC(NUM:REAL;VAR PWR:INTEGER):REAL; VAR STNG:STRING; CNT:BYTE; P,EL:INTEGER; DECPOINT:BOOLEAN; BEGIN STR(NUM:10:8,STNG); STNG[0]:=#10; EL:=0; P:=0; DECPOINT:=FALSE; FOR CNT:= 1 TO 10 DO BEGIN {NUM OF DIGITS CHECK} {IF CH<>'.' THEN P:=P+1} IF DECPOINT THEN EL:=EL-1; IF (STNG[CNT]='.') AND NOT DECPOINT THEN DECPOINT:=TRUE; END;{FOR} P:=10; VALC:=NUM; PWR:=P+EL; END; FUNCTION PWRTEN(ET:INTEGER):REAL; VAR PS,Y:INTEGER;XX:REAL; BEGIN PS:=ABS(ET);XX:=1; IF ET<0 THEN FOR Y:=1 TO PS DO XX:=XX/10; IF ET>0 THEN FOR Y:=1 TO PS DO XX:=XX*10; PWRTEN:=XX; END; PROCEDURE EVALUATE(EXPR: EXPSTR; X:REAL; VAR VALUE: REAL; VAR EXPERR,ERR:BOOLEAN); CONST {NOW EXPR CAN BE MODIFIED} ERRCH = '?'; EOFLINE = #13; VAR POS: INTEGER; CH: CHAR; PROCEDURE NEXTCHAR; BEGIN REPEAT POS:=POS+1; IF POS<=LENGTH(EXPR) THEN CH:=EXPR[POS] ELSE CH:=EOFLINE; UNTIL CH<>' ';{ELIMINATING SPACES IF ANY} END; FUNCTION EXPRESSION: REAL; VAR E,RR: REAL; OPR: CHAR; PR,NW:INTEGER;{PRE & NEW} FUNCTION SIMEXPR: REAL; VAR S,TT: REAL; QQ,CC:INTEGER; OPR: CHAR; FUNCTION TERM: REAL; VAR T, SGN,SFC: REAL; NN:INTEGER; FUNCTION SIGNEDFACTOR(VAR SS:INTEGER): REAL; FUNCTION FACTOR(VAR POW:INTEGER): REAL; TYPE STDF = (FABS,FSQRT,FSIN,FCOS,FARCTAN,FLN,FEXP);{ADD INT AND ROUND,FRAC} STDFLIST = ARRAY[STDF] OF STRING[6]; CONST STDFUN: STDFLIST = ('ABS','SQRT','SIN','COS','ARCTAN','LN','EXP'); VAR ST:EXPSTR; EL,EE,L,P: INTEGER; DECPOINT,NEGEXP,FOUND: BOOLEAN; F: REAL; SF: STDF; FUNCTION VALU(NUM:REAL):REAL; VAR STNG:STRING; CNT:BYTE; BEGIN STR(NUM:10:8,STNG); STNG[0]:=#10; EL:=0; P:=0; DECPOINT:=FALSE; FOR CNT:= 1 TO 10 DO BEGIN {NUM OF DIGITS CHECK} {IF CH<>'.' THEN P:=P+1} IF DECPOINT THEN EL:=EL-1; IF (STNG[CNT]='.') AND NOT DECPOINT THEN DECPOINT:=TRUE; END;{FOR} P:=10; VALU:=NUM; END; BEGIN P:=0; EL:=0; IF CH IN ['0'..'9'] THEN BEGIN F:=0.0; DECPOINT:=FALSE; REPEAT IF P<10 THEN BEGIN F:=F*10.0+(ORD(CH)-48); P:=P+1;{NUM OF DIGITS CHECK} IF DECPOINT THEN EL:=EL-1; NEXTCHAR; IF (CH='.') AND NOT DECPOINT THEN BEGIN DECPOINT:=TRUE; NEXTCHAR; END; END ELSE BEGIN ERR:=TRUE;{INFINITY ERROR} {OTHER WAY TO CHEK INF ERR CAN BE BY CHEKING POWER FROM REAL VAR BITS} CH:=ERRCH;{STOPS FURTHER PROCEEDINGS} END; UNTIL NOT(CH IN ['0'..'9']); IF CH='E' THEN BEGIN EE:=0; NEXTCHAR; IF CH IN ['+','-'] THEN BEGIN NEGEXP:=CH='-'; NEXTCHAR; END ELSE NEGEXP:=FALSE; WHILE CH IN ['0'..'9'] DO BEGIN EE:=EE*10+ORD(CH)-48; NEXTCHAR; END; IF NEGEXP THEN EL:=EL-EE ELSE EL:=EL+EE; END; IF ABS(P+EL)<11 THEN F:=F*PWRTEN(EL) ELSE BEGIN ERR:=TRUE; CH:=ERRCH; END; END ELSE{IF CH} IF CH='(' THEN BEGIN NEXTCHAR; F:=EXPRESSION; IF CH=')' THEN NEXTCHAR ELSE CH:=ERRCH; END ELSE IF CH='X' THEN BEGIN NEXTCHAR; F:=VALU(X); END ELSE BEGIN FOUND:=FALSE; FOR SF:=FABS TO FEXP DO IF NOT FOUND THEN BEGIN L:=LENGTH(STDFUN[SF]); IF COPY(EXPR,POS,L)=STDFUN[SF] THEN BEGIN POS:=POS+L-1; NEXTCHAR; F:=FACTOR(POW); CASE SF OF FABS: F:=VALU(ABS(F));{FUNCTION SGN=F/ABS(F) OR OTHER WAY} FSQRT: F:=VALU(SQRT(F)); FSIN: F:=VALU(SIN(F)); FCOS: F:=VALU(COS(F)); FARCTAN: F:=VALU(ARCTAN(F));{TAN INVERSE} FLN: IF F<=0 THEN BEGIN ERR:=TRUE; CH:=ERRCH; END ELSE F:=VALU(LN(F));{ADD LOG FUNC} FEXP: IF (F>23) OR (F<-10000) THEN BEGIN CH:=ERRCH; ERR:=TRUE; END ELSE F:=VALU(EXP(F));{CHECK RANGE, IF InRANGE THEN OK ELSE ERR} END; FOUND:=TRUE; END; END; IF NOT FOUND THEN CH:=ERRCH; END; POW:=P+EL; FACTOR:=F; END (*FACTOR*); BEGIN (*SIGNEDFACTOR*) IF CH='-' THEN BEGIN NEXTCHAR; SIGNEDFACTOR:=-FACTOR(SS); END ELSE SIGNEDFACTOR:=FACTOR(SS); END (*SIGNEDFACTOR*); BEGIN (*TERM*) T:=SIGNEDFACTOR(NN); WHILE CH='^' DO BEGIN NEXTCHAR; SFC:=SIGNEDFACTOR(NN); IF T<=0 THEN BEGIN ERR:=TRUE; CH:=ERRCH; END ELSE BEGIN T:=LN(T)*SFC; {FOR FURTHER RAISE IN POWER SIGNEDFACTOR TO BE USED FOR RECURSIVE SOLN.} IF (T>23) OR (T<-10000) THEN BEGIN ERR:=TRUE; CH:=ERRCH; END ELSE T:=EXP(T); END;{IF T<1} END;{WHILE} TERM:=T; END (*TERM*); BEGIN (*SIMEXPR*) S:=VALC(TERM,QQ); WHILE CH IN ['*','/'] DO BEGIN OPR:=CH; NEXTCHAR; TT:=VALC(TERM,CC); CASE OPR OF '*': {S:=S*TERM(CC);} {QQ & CC ARE NEVER OUT OF THE RANGE -10 TO 10} IF ABS(QQ+CC)<11 THEN S:=S*TT ELSE BEGIN ERR:=TRUE; CH:=ERRCH; END; '/': {USING VARIABLE INSTEAD OF FUNC TERM(CC) WILL REDUCE CALCS} IF ((TT<>0) AND (ABS(QQ-CC)<11)) {1st BIT SGN BIT IN REAL FOR COMMON ABS} THEN S:=S/TT ELSE BEGIN ERR:=TRUE; CH:=ERRCH; END; END; QQ:=CC; END; SIMEXPR:=S; END (*SIMEXPR*); BEGIN (*EXPRESSION*) E:=VALC(SIMEXPR,PR);{GETTING PREVIOUS POWER HERE FROM SIMEXPR()} WHILE CH IN ['+','-'] DO BEGIN OPR:=CH; NEXTCHAR; RR:=VALC(SIMEXPR,NW); CASE OPR OF '+': IF ((PR<11) AND (NW<11)) THEN E:=E+RR ELSE BEGIN ERR:=TRUE; CH:=ERRCH; END; {CHK FOR INFINITY ERR OF ADD & SUB} '-': IF ((PR<11) AND (NW<11)) THEN E:=E-RR; ELSE BEGIN ERR:=TRUE; {INFINITY ERROR BY THESE OPERATIONS GO UNDETECTED} CH:=ERRCH; END; END; PR:=NW; END; EXPRESSION:=E; END (*EXPRESSION*); BEGIN (*EVALUATE*) ERR:=FALSE; EXPERR:=ERR; POS:=0; NEXTCHAR; VALUE:=EXPRESSION; IF (CH<>EOFLINE) AND NOT(ERR) {NOW OLD LOGIC WILL WORK} THEN EXPERR:=TRUE; {ERR-INFINITY ERROR} {EXPERR-EXPRESSION ERROR} END (*EVALUATE*); BEGIN (*CALCULATOR*) { NO. OF DIGITS INPUT IS 10 CHARS MAX WITH DECIMAL &DIGITS (*FUNCTIONS LIKE FRAC,INT,ROUND ECT. SHOULD ALSO BE THERE*) (*ALSO DEFINE INFINITY*) ERROR CHECKING FOR OUT OF RANGE VALUES IS TO BE PERFORMED} END (*CALCULATOR*).
(* * Copyright (c) 2008-2009, Lucian Bentea * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *) {$I ../Library/src/DeHL.Defines.inc} unit Tests.BinaryTree; interface uses SysUtils, Tests.Utils, TestFramework, DeHL.Types, DeHL.Exceptions, DeHL.Collections.BinaryTree, DeHL.Collections.Base, DeHL.Collections.List, DeHL.Arrays; type TTestBinaryTree = class(TDeHLTestCase) published procedure TestClear(); procedure TestFind(); procedure TestContains(); procedure TestRemove(); procedure TestCreationAndDestroy(); procedure TestCopyTo(); procedure TestExceptions(); procedure TestGenArrayLists(); procedure TestEnumerator(); procedure TestObjectVariant(); procedure TestCleanup(); end; implementation { TTestBinaryTree } procedure TTestBinaryTree.TestCleanup; var ATree : TBinaryTree<Integer>; ElemCache: Integer; I: Integer; begin ElemCache := 0; { Create a new ATree } ATree := TBinaryTree<Integer>.Create( TTestType<Integer>.Create(procedure(Arg1: Integer) begin Inc(ElemCache, Arg1); end), 1 ); { Add some elements } ATree.AddLeft(ATree.Root, 2); ATree.AddRight(ATree.Root, 4); ATree.AddLeft(ATree.Root.Left, 8); ATree.AddRight(ATree.Root.Left, 16); Check(ElemCache = 0, 'Nothing should have be cleaned up yet!'); ATree.Remove(8); ATree.Remove(16); ATree.Contains(10); Check(ElemCache = 0, 'Nothing should have be cleaned up yet!'); { Simply walk the ATree } for I in ATree do if I > 0 then; Check(ElemCache = 0, 'Nothing should have be cleaned up yet!'); ATree.Clear(); Check(ElemCache = 7, 'Expected cache = 7'); ATree.Destroy; { Create a new ATree } ATree := TBinaryTree<Integer>.Create( TTestType<Integer>.Create(procedure(Arg1: Integer) begin Inc(ElemCache, Arg1); end), 1 ); ElemCache := 0; ATree.AddLeft(ATree.Root, 2); ATree.AddRight(ATree.Root, 4); ATree.AddLeft(ATree.Root.Left, 8); ATree.AddRight(ATree.Root.Left, 16); ATree.Root.Left.Left.Free; Check(ElemCache = 8, 'Expected cache = 8'); ElemCache := 0; ATree.Free; Check(ElemCache = 23, 'Expected cache = 23'); end; procedure TTestBinaryTree.TestClear; var Tree : TBinaryTree<String>; begin { Initialize the list = 'First'} Tree := TBinaryTree<String>.Create('root'); Tree.AddLeft(Tree.Root, '1'); Tree.AddRight(Tree.Root, '2'); Tree.AddLeft(Tree.Root.Left, 'a'); Tree.AddRight(Tree.Root.Left, 'b'); Check(Tree.Count = 5, 'Count is incorrect!'); Tree.Clear(); Check(Tree.Count = 0, 'Count is incorrect!'); Check(Tree.Root = nil, 'Root must be nil.'); Tree.Free(); end; procedure TTestBinaryTree.TestFind; var Tree : TBinaryTree<String>; begin { Initialize the tree} Tree := TBinaryTree<String>.Create(TStringType.Create(True), 'root'); Tree.AddLeft(Tree.Root, 'First'); Tree.AddRight(Tree.Root, 'Second'); Tree.AddLeft(Tree.Root.Right, 'Third'); Tree.AddRight(Tree.Root.Right, 'ThIrd'); { Normal find } Check(Tree.Find('FIRST') <> nil, 'Did not find "FIRST" in the list (Insensitive)'); Check(Tree.Find('FIRST').Value = 'First', 'Found node is not the one searched for ("FIRST") in the list (Insensitive)'); Check(Tree.Find('tHIRD') <> nil, 'Did not find "tHIRD" in the list (Insensitive)'); Check(Tree.Find('tHIRD').Value = 'Third', 'Found node is not the one searched for ("tHIRD") in the list (Insensitive)'); Check(Tree.Find('sEcOnD') <> nil, 'Did not find "sEcOnD" in the list (Insensitive)'); Check(Tree.Find('sEcOnD').Value = 'Second', 'Found node is not the one searched for ("sEcOnD") in the list (Insensitive)'); Check(Tree.Find('Lom') = nil, 'Found "Lom" when it''s not contained there! (Insensitive)'); Tree.Free(); end; procedure TTestBinaryTree.TestGenArrayLists; var Tree: TBinaryTree<Integer>; InOrderArr, PreOrderArr, PostOrderArr : TFixedArray<Integer>; begin Tree := TBinaryTree<Integer>.Create(5); Tree.AddLeft(Tree.Root, 2); Tree.AddRight(Tree.Root, 1); Tree.AddLeft(Tree.Root.Left, 8); { Generate lists } InOrderArr := Tree.InOrder(); PreOrderArr := Tree.PreOrder(); PostOrderArr := Tree.PostOrder(); { Test counts } Check(InOrderArr.Length = 4, 'Count of InOrderArr expected to be 4'); Check(PreOrderArr.Length = 4, 'Count of PreOrderArr expected to be 4'); Check(PostOrderArr.Length = 4, 'Count of PostOrderArr expected to be 4'); { Test elements } Check(InOrderArr[0] = 8, 'InOrderArr[0] expected to be 8'); Check(InOrderArr[1] = 2, 'InOrderArr[1] expected to be 2'); Check(InOrderArr[2] = 5, 'InOrderArr[2] expected to be 5'); Check(InOrderArr[3] = 1, 'InOrderArr[3] expected to be 1'); Check(PreOrderArr[0] = 5, 'PreOrderArr[0] expected to be 5'); Check(PreOrderArr[1] = 2, 'PreOrderArr[1] expected to be 2'); Check(PreOrderArr[2] = 8, 'PreOrderArr[2] expected to be 8'); Check(PreOrderArr[3] = 1, 'PreOrderArr[3] expected to be 1'); Check(PostOrderArr[0] = 8, 'PostOrderArr[0] expected to be 8'); Check(PostOrderArr[1] = 2, 'PostOrderArr[1] expected to be 2'); Check(PostOrderArr[2] = 1, 'PostOrderArr[2] expected to be 1'); Check(PostOrderArr[3] = 5, 'PostOrderArr[3] expected to be 5'); { Free resources } Tree.Free; end; procedure TTestBinaryTree.TestObjectVariant; var ObjTree: TObjectBinaryTree<TTestObject>; TheObject: TTestObject; ObjectDied: Boolean; begin TheObject := TTestObject.Create(@ObjectDied); ObjTree := TObjectBinaryTree<TTestObject>.Create(TheObject); Check(not ObjTree.OwnsObjects, 'OwnsObjects must be false!'); ObjTree.Free; Check(not ObjectDied, 'The object should not have been cleaned up!'); ObjTree := TObjectBinaryTree<TTestObject>.Create(TheObject); ObjTree.OwnsObjects := true; Check(ObjTree.OwnsObjects, 'OwnsObjects must be true!'); ObjTree.Clear; Check(ObjectDied, 'The object should have been cleaned up!'); ObjTree.Free; end; procedure TTestBinaryTree.TestContains; var Tree : TBinaryTree<String>; begin { Initialize the list = 'First'} Tree := TBinaryTree<String>.Create(TStringType.Create(True), 'root'); Tree.AddLeft(Tree.Root, 'First'); Tree.AddRight(Tree.Root, 'Second'); Tree.AddLeft(Tree.Root.Left, 'Third'); Check(Tree.Contains('FIRST'), 'Did not find "FIRST" in the list (Insensitive)'); Check(Tree.Contains('tHIRD'), 'Did not find "tHIRD" in the list (Insensitive)'); Check(Tree.Contains('sEcOnD'), 'Did not find "sEcOnD" in the list (Insensitive)'); Check((not Tree.Contains('Yuppy')), 'Did find "Yuppy" in the list (Insensitive)'); Tree.Free(); end; procedure TTestBinaryTree.TestRemove; var Tree : TBinaryTree<Extended>; begin { Initialize the list } Tree := TBinaryTree<Extended>.Create(0); Tree.AddLeft(Tree.Root, 3.1415); Tree.AddRight(Tree.Root, 2.71); Tree.AddLeft(Tree.Root.Right, 0.1); Tree.AddRight(Tree.Root.Right, 0.2); Tree.AddLeft(Tree.Root.Right.Right, 0.9999); Tree.Remove(2.71); Check(Tree.Count = 2, 'Tree count must be 2'); Tree.Remove(Tree.Find(0).Value); Check(Tree.Count = 0, 'Tree count must be 0'); { Free } Tree.Free(); end; procedure TTestBinaryTree.TestCreationAndDestroy; var Tree, CopyTree : TBinaryTree<Integer>; // IL : array of Integer; begin { Initialize the list } Tree := TBinaryTree<Integer>.Create(0); Tree.AddLeft(Tree.Root, 1); Tree.AddRight(Tree.Root, 2); Tree.AddLeft(Tree.Root.Left, 11); Tree.AddRight(Tree.Root.Left, 12); Check(Tree.Count = 5, 'Count must be 5 elements!'); Check(Tree.Root.Value = 0, 'Expected 0 but got another value!'); Check(Tree.Root.Left.Value = 1, 'Expected 1 but got another value!'); Check(Tree.Root.Right.Value = 2, 'Expected 2 but got another value!'); Check(Tree.Root.Left.Left.Value = 11, 'Expected 11 but got another value!'); Check(Tree.Root.Left.Right.Value = 12, 'Expected 12 but got another value!'); { Test the copy} CopyTree := TBinaryTree<Integer>.Create(Tree); Check(CopyTree.Count = 5, '(Copy) Count must be 5 elements!'); Check(CopyTree.Root.Value = 0, 'Expected 0 but got another value!'); Check(CopyTree.Root.Left.Value = 1, 'Expected 1 but got another value!'); Check(CopyTree.Root.Right.Value = 2, 'Expected 2 but got another value!'); Check(CopyTree.Root.Left.Left.Value = 11, 'Expected 11 but got another value!'); Check(CopyTree.Root.Left.Right.Value = 12, 'Expected 12 but got another value!'); { Free the list } Tree.Free; CopyTree.Free; end; procedure TTestBinaryTree.TestExceptions; var Tree1, Tree2, TreeX : TBinaryTree<Integer>; NullArg : IType<Integer>; begin NullArg := nil; Tree1 := TBinaryTree<Integer>.Create(0); Tree2 := TBinaryTree<Integer>.Create(0); Tree1.AddLeft(Tree1.Root, 1); Tree2.AddLeft(Tree2.Root, 1); Tree1.AddRight(Tree1.Root, 2); Tree2.AddRight(Tree2.Root, 2); CheckException(ENilArgumentException, procedure() begin TreeX := TBinaryTree<Integer>.Create(NullArg, 0); TreeX.Free(); end, 'ENilArgumentException not thrown in constructor (nil comparer).' ); CheckException(ENilArgumentException, procedure() begin TreeX := TBinaryTree<Integer>.Create(TType<Integer>.Default, nil); TreeX.Free(); end, 'ENilArgumentException not thrown in constructor (nil tree).' ); CheckException(ENilArgumentException, procedure() begin TreeX := TBinaryTree<Integer>.Create(NullArg, Tree1); TreeX.Free(); end, 'ENilArgumentException not thrown in constructor (nil comparer).' ); CheckException(ENilArgumentException, procedure() begin TreeX := TBinaryTree<Integer>.Create(nil); TreeX.Free(); end, 'ENilArgumentException not thrown in constructor (nil tree).' ); CheckException(EPositionOccupiedException, procedure() begin Tree1.AddLeft(Tree1.Root, 4); end, 'EPositionOccupiedException not thrown in AddLeft (occupied)!' ); CheckException(EPositionOccupiedException, procedure() begin Tree1.AddRight(Tree1.Root, 4); end, 'EPositionOccupiedException not thrown in AddRight (occupied)!' ); CheckException(ENilArgumentException, procedure() begin Tree1.AddLeft(nil, 4); end, 'ENilArgumentException not thrown in AddLeft (nil ref node)!' ); CheckException(ENilArgumentException, procedure() begin Tree1.AddRight(nil, 4); end, 'ENilArgumentException not thrown in AddRight (nil ref node)!' ); CheckException(EElementNotPartOfCollection, procedure() begin Tree1.AddLeft(Tree2.Root, 4); end, 'EElementNotPartOfCollection not thrown in AddLeft (ref node part of another)!' ); CheckException(EElementNotPartOfCollection, procedure() begin Tree2.AddRight(Tree1.Root, 4); end, 'EElementNotPartOfCollection not thrown in AddRight (ref node part of another)!' ); CheckException(ENilArgumentException, procedure() begin Tree1.AddLeft(Tree1.Root, nil); end, 'ENilArgumentException not thrown in AddLeft (nil add)!' ); CheckException(ENilArgumentException, procedure() begin Tree1.AddRight(Tree1.Root, nil); end, 'ENilArgumentException not thrown in AddRight (nil add)!' ); CheckException(EElementAlreadyInACollection, procedure() begin Tree1.AddLeft(Tree1.Root, Tree2.Root); end, 'EElementAlreadyInACollection not thrown in AddLeft (add part of 2)!' ); CheckException(EElementAlreadyInACollection, procedure() begin Tree1.AddRight(Tree1.Root, Tree2.Root); end, 'EElementAlreadyInACollection not thrown in AddRight (add part of 2)!' ); CheckException(EElementAlreadyInACollection, procedure() begin Tree1.AddLeft(Tree1.Root, Tree1.Root); end, 'EElementAlreadyInACollection not thrown in AddLeft (inter mix)!' ); CheckException(EElementAlreadyInACollection, procedure() begin Tree1.AddRight(Tree1.Root, Tree1.Root); end, 'EElementAlreadyInACollection not thrown in AddRight (inter mix)!' ); CheckException(EElementNotPartOfCollection, procedure() begin Tree1.Remove(Tree2.Root); end, 'EElementNotPartOfCollection not thrown in Remove (2nd tree node)!' ); CheckException(ENilArgumentException, procedure() begin TBinaryTreeNode<Integer>.Create(10, nil); end, 'ENilArgumentException not thrown in TBinaryTreeNode.ctor (nil tree)!' ); Tree1.Free(); Tree2.Free(); TreeX.Free(); end; procedure TTestBinaryTree.TestCopyTo; var Tree : TBinaryTree<Integer>; IL : array of Integer; begin Tree := TBinaryTree<Integer>.Create(0); { Add elements to the tree } Tree.AddLeft(Tree.Root, -1); Tree.AddRight(Tree.Root, -2); Tree.AddLeft(Tree.Root.Left, -11); Tree.AddRight(Tree.Root.Right, -12); { Test Count } Check(Tree.GetCount = 5, 'Count must be 5!'); Tree.Remove(-11); Tree.Remove(-12); Check(Tree.GetCount = 3, 'Count must be 3!'); Tree.AddLeft(Tree.Root.Right, -21); Tree.AddRight(Tree.Root.Right, -22); Tree.AddLeft(Tree.Root.Left, -17); Check(Tree.GetCount = 6, 'Count must be 6!'); { Check the copy } SetLength(IL, 6); Tree.CopyTo(IL); Check(IL[0] = -17, 'Element 0 in the new array is wrong!'); Check(IL[1] = -1, 'Element 1 in the new array is wrong!'); Check(IL[2] = -21, 'Element 2 in the new array is wrong!'); Check(IL[3] = -22, 'Element 3 in the new array is wrong!'); Check(IL[4] = -2, 'Element 4 in the new array is wrong!'); Check(IL[5] = 0, 'Element 5 in the new array is wrong!'); { Check the copy with index } SetLength(IL, 7); Tree.CopyTo(IL, 1); Check(IL[1] = -17, 'Element 0 in the new array is wrong!'); Check(IL[2] = -1, 'Element 1 in the new array is wrong!'); Check(IL[3] = -21, 'Element 2 in the new array is wrong!'); Check(IL[4] = -22, 'Element 3 in the new array is wrong!'); Check(IL[5] = -2, 'Element 4 in the new array is wrong!'); Check(IL[6] = 0, 'Element 5 in the new array is wrong!'); { Exception } SetLength(IL, 5); CheckException(EArgumentOutOfSpaceException, procedure() begin Tree.CopyTo(IL); end, 'EArgumentOutOfSpaceException not thrown in CopyTo (too small size).' ); SetLength(IL, 6); CheckException(EArgumentOutOfSpaceException, procedure() begin Tree.CopyTo(IL, 1); end, 'EArgumentOutOfSpaceException not thrown in CopyTo (too small size +1).' ); Tree.Free(); end; procedure TTestBinaryTree.TestEnumerator; var Tree : TBinaryTree<Integer>; I, X : Integer; begin Tree := TBinaryTree<Integer>.Create(0); Tree.AddLeft(Tree.Root, 10); Tree.AddRight(Tree.Root, -12); Tree.AddLeft(Tree.Root.Left, -30); X := 0; for I in Tree do begin if X = 0 then Check(I = -30, 'Enumerator failed at 0!') else if X = 1 then Check(I = 10, 'Enumerator failed at 1!') else if X = 2 then Check(I = -12, 'Enumerator failed at 2!') else if X = 3 then Check(I = 0, 'Enumerator failed at 3!') else Fail('Enumerator failed!'); Inc(X); end; { Test exceptions } CheckException(ECollectionChangedException, procedure() var I : Integer; begin for I in Tree do begin Tree.Remove(I); end; end, 'ECollectionChangedException not thrown in Enumerator!' ); Check(Tree.Count = 3, 'Enumerator failed too late'); Tree.Free; end; initialization TestFramework.RegisterTest(TTestBinaryTree.Suite); end.
unit PlayerActions; interface uses AvL, avlUtils, avlEventBus, avlMath, avlVectors, VSECore, Game, GameObjects; type TPlaceCharacterAction = class(TPlayerAction) private FChar: TCharacter; function CheckQuarter(Quarter: TQuarter): Boolean; procedure CharSelected(Sender: TObject; Char: TCharacter); procedure MouseEvent(Sender: TObject; const Args: array of const); procedure HighlightQuarter(Sender: TObject; const Args: array of const); public constructor Create(Player: TPlayer); destructor Destroy; override; end; TQuarterSelectCriteria = (qscFree, qscOneStep, qscTwoSteps); TSelectQuarterAction = class(TPlayerAction) private FCriteria: TQuarterSelectCriteria; function CheckQuarter(Quarter: TQuarter): Boolean; procedure MouseEvent(Sender: TObject; const Args: array of const); procedure HighlightQuarter(Sender: TObject; const Args: array of const); public constructor Create(Player: TPlayer; Criteria: TQuarterSelectCriteria); destructor Destroy; override; end; implementation uses GameData, GameForms, Scene {$IFDEF VSE_CONSOLE}, VSEConsole{$ENDIF}{$IFDEF VSE_LOG}, VSELog{$ENDIF}; { TPlaceCharacterAction } constructor TPlaceCharacterAction.Create(Player: TPlayer); begin inherited; FForm := TCharSelectForm.Create(Player.Objects); (FForm as TCharSelectForm).OnSelect := CharSelected; EventBus.SendEvent(SceneShowTitleMessage, Self, ['Размести персонажа', 1, Player]); {$IFDEF VSE_DEBUG} Player.Game.ActivePlayer := Player; {$ENDIF} end; destructor TPlaceCharacterAction.Destroy; begin EventBus.RemoveListeners([HighlightQuarter, MouseEvent]); FAN(FForm); inherited; end; function TPlaceCharacterAction.CheckQuarter(Quarter: TQuarter): Boolean; begin Result := (Quarter.Index > 0) and not Assigned(Quarter.Objects.ObjOfType[TCharacter, 0]); end; procedure TPlaceCharacterAction.CharSelected(Sender: TObject; Char: TCharacter); begin FForm := nil; FChar := Char; EventBus.AddListener(SceneOnQuarterHighlight, HighlightQuarter); EventBus.AddListener(GameOnMouseEvent, MouseEvent); end; procedure TPlaceCharacterAction.MouseEvent(Sender: TObject; const Args: array of const); var Obj: TGameObject; begin Assert((Length(Args) = 2) and (Args[0].VType = vtInteger) and (Args[1].VType = vtPointer)); if FPlayer.Game.ActivePlayer <> FPlayer then Exit; if TMouseEvents(Args[0].VInteger) = meDown then begin Obj := FPlayer.Game.Scene.ObjectAtMouse; if not ((Obj is TQuarter) and CheckQuarter(Obj as TQuarter)) then Exit; with TVector3D(Args[1].VPointer^) do FChar.Pos := Vector3D(X, 0, Z); FChar.Quarter := Obj as TQuarter; FPlayer.Objects.Remove(FChar); EventBus.SendEvent(SceneAddObject, Self, [FChar]); Complete; end; end; procedure TPlaceCharacterAction.HighlightQuarter(Sender: TObject; const Args: array of const); const HlColor: array[Boolean] of TColor = (clRed, clLime); begin Assert((Length(Args) = 1) and (Args[0].VType = vtObject)); if FPlayer.Game.ActivePlayer <> FPlayer then Exit; EventBus.SendEvent(SceneSetQuarterHlColor, Self, [HlColor[CheckQuarter(Args[0].VObject as TQuarter)]]) end; { TSelectQuarterAction } constructor TSelectQuarterAction.Create(Player: TPlayer; Criteria: TQuarterSelectCriteria); begin inherited Create(Player); EventBus.SendEvent(SceneShowTitleMessage, Self, ['Выбери квартал', 1, Player]); EventBus.AddListener(SceneOnQuarterHighlight, HighlightQuarter); EventBus.AddListener(GameOnMouseEvent, MouseEvent); {$IFDEF VSE_DEBUG} Player.Game.ActivePlayer := Player; {$ENDIF} end; destructor TSelectQuarterAction.Destroy; begin EventBus.RemoveListeners([HighlightQuarter, MouseEvent]); inherited; end; function TSelectQuarterAction.CheckQuarter(Quarter: TQuarter): Boolean; begin case FCriteria of qscFree: Result := (not FPlayer.Character.Profile.IsDoctor or (Quarter.Index > 0)) and not Assigned(Quarter.Objects.ObjOfType[TCharacter, 0]); else raise Exception.Create('Criteria not implemented'); end; end; procedure TSelectQuarterAction.MouseEvent(Sender: TObject; const Args: array of const); var Obj: TGameObject; begin Assert((Length(Args) = 2) and (Args[0].VType = vtInteger) and (Args[1].VType = vtPointer)); if FPlayer.Game.ActivePlayer <> FPlayer then Exit; if TMouseEvents(Args[0].VInteger) = meDown then begin Obj := FPlayer.Game.Scene.ObjectAtMouse; if not ((Obj is TQuarter) and CheckQuarter(Obj as TQuarter)) then Exit; with TVector3D(Args[1].VPointer^) do FPlayer.Character.Pos := Vector3D(X, 0, Z); FPlayer.Character.Quarter := Obj as TQuarter; Complete; end; end; procedure TSelectQuarterAction.HighlightQuarter(Sender: TObject; const Args: array of const); const HlColor: array[Boolean] of TColor = (clRed, clLime); begin Assert((Length(Args) = 1) and (Args[0].VType = vtObject)); if FPlayer.Game.ActivePlayer <> FPlayer then Exit; EventBus.SendEvent(SceneSetQuarterHlColor, Self, [HlColor[CheckQuarter(Args[0].VObject as TQuarter)]]) end; end.
unit T_ExactFloatToStr_0_Form; (* ***************************************************************************** For Testing ExactFloatToStr and ParseFloat functions. Pgm. 12/24/2002 by John Herbster. ***************************************************************************** *) interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Edit1: TEdit; Convert_b: TButton; Memo1: TMemo; ShowDebug_ck: TCheckBox; CallExVer_ck: TCheckBox; CkSmallest_b: TButton; CkDenormal2_b: TButton; CkSpecials_b: TButton; SmallestD_b: TButton; Pi_b: TButton; CkAnalyzeFloat_b: TButton; procedure Convert_bClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure Edit1KeyPress(Sender: TObject; var Key: Char); procedure CkSmallest_bClick(Sender: TObject); procedure CkDenormal2_bClick(Sender: TObject); procedure CkSpecials_bClick(Sender: TObject); procedure SmallestD_bClick(Sender: TObject); procedure Pi_bClick(Sender: TObject); procedure CvtToHex_bClick(Sender: TObject); procedure CkAnalyzeFloat_bClick(Sender: TObject); private procedure TestNumber(Value: Extended); public procedure Log(const msg: string); procedure LogFmt(const Fmt: string; const Data: array of const); end; var Form1: TForm1; implementation {$R *.DFM} uses ExactFloatToStr_JH0; function GetCpuClockCycleCount: Int64; asm dw $310F // opcode for RDTSC end; procedure TForm1.Log(const msg: string); begin Memo1.Lines.Add(msg); end; procedure TForm1.LogFmt(const Fmt: string; const Data: array of const); begin Log(Format(Fmt,Data)); end; procedure TForm1.FormCreate(Sender: TObject); begin ShowDebug_ck.Enabled := ExactFloatToStr_JH0.Debug; Edit1.Text := FloatToStr(1); end; procedure TForm1.TestNumber(Value: Extended); var ExtX: packed record Man: Int64; Exp: word end absolute Value; cc: int64; ValE4K: extended; s: string; begin if ShowDebug_ck.Checked then ExactFloatToStr_JH0.LogFmtX := LogFmt else ExactFloatToStr_JH0.LogFmtX := nil; if Abs(Value) < 1E-4000 then begin ValE4K := Value * 1E4000; LogFmt('Calling: Exp=$%4.4x, Man=$%16.16x, G=%g, Ge4K=%g', [ExtX.Exp,ExtX.Man,Value,ValE4K]); end else LogFmt('Calling: Exp=$%4.4x, Man=$%16.16x, G=%g', [ExtX.Exp,ExtX.Man,Value]); try cc := GetCpuClockCycleCount; if CallExVer_ck.Checked then s := ExactFloatToStrEx(Value) else s := ExactFloatToStrEx(Value); cc := GetCpuClockCycleCount - cc; LogFmt(' Required %s clock cycles',[ExactFloatToStr(cc)]); Log(s); except on e:Exception do LogFmt('Exception: %s',[e.Message]); end; end; procedure StrToFloatProc(const Str: string; out Value: Extended); var s: string; i,j: integer; begin s := Str; j := 0; for i := 1 to length(s) do begin if s[i] in ['-','0'..'9','.','e','E'] then begin Inc(j); s[j] := s[i] end; end; SetLength(s,j); Value := StrToFloat(s); end; procedure TForm1.Convert_bClick(Sender: TObject); var ext: extended; begin Screen.Cursor := crHourGlass; Memo1.Lines.Add(''); try StrToFloatProc(Edit1.Text, {out}ext); TestNumber(ext); finally Screen.Cursor := crDefault; end; end; procedure TForm1.Edit1KeyPress(Sender: TObject; var Key: Char); begin if Key <> ^M then Exit; Key := #0; Convert_bClick(Sender); end; procedure TForm1.CkSmallest_bClick(Sender: TObject); var ext: extended; i: integer; var ExtX: packed record Man: Int64; Exp: word end absolute ext; begin Memo1.Lines.Add(''); Screen.Cursor := crHourGlass; try ExtX.Exp := 0; ExtX.Man := $0000000000000001; for i := 1 to 2 do begin TestNumber(ext); ext := ext / 2; end; finally Screen.Cursor := crDefault; end; end; procedure TForm1.CkDenormal2_bClick(Sender: TObject); var ext: extended; i: integer; var ExtX: packed record Man: Int64; Exp: word end absolute ext; ext2: extended; begin Memo1.Lines.Add(''); Screen.Cursor := crHourGlass; try ExtX.Exp := 2; ExtX.Man := $8000000000000000; for i := 1 to 9 do begin ext2 := ext*1e4900; LogFmt('Test #%d: Exp=$%4.4x, Man=$%16.16x, G=%g, G2=%g', [i,ExtX.Exp,ExtX.Man,ext,ext2]); if (i in [2,3,4]) then TestNumber(ext); if i < 5 then ext := ext / 2 else ext := ext * 2; end; finally Screen.Cursor := crDefault; end; end; procedure TForm1.CkSpecials_bClick(Sender: TObject); var ext: extended; dbl: double; ExtX: packed record Man: Int64; Exp: word end absolute ext; DblX: int64 absolute dbl; const NanX = 0/0; DblSgnX: Int64 = $8000000000000000; {1 bit} DblExpX: Int64 = $7FF0000000000000; {11 bits} DblManX: Int64 = $000FFFFFFFFFFFFF; {52 bits (+ 1 = 53)} begin Screen.Cursor := crHourGlass; try { Test infinities: } Log(''); ExtX.Exp := $7FFF; ExtX.Man := $0000000000000000; Log('+Inf response = ' + ExactFloatToStr(ext)); ExtX.Exp := $FFFF; ExtX.Man := $0000000000000000; Log('-Inf response = ' + ExactFloatToStr(ext)); { Test indefinite: } Log(''); ext := NanX; LogFmt('Exp=$%4.4x, Man=$%16.16x',[ExtX.Exp,ExtX.Man]); Log('Indefinite response = ' + ExactFloatToStr(ext)); dbl := ext; ext := dbl; LogFmt('Dbl: Exp=$%3.3x, Man=$%13.13x', [(DblX shr (13*4)),(DblX and DblManX)]); LogFmt('Ext: Exp=$%4.4x, Man=$%16.16x',[ExtX.Exp,ExtX.Man]); Log('Indefinite dbl rsp. = ' + ExactFloatToStr(ext)); { Test QNANs: } Log(''); ExtX.Exp := $7FFF; ExtX.Man := $C100000000000000; Log('QNAN(1) response = ' + ExactFloatToStr(ext)); ExtX.Exp := $7FFF; ExtX.Man := $8100000000000000; Log('SNAN(1) response = ' + ExactFloatToStr(ext)); finally Screen.Cursor := crDefault; end; end; procedure TForm1.SmallestD_bClick(Sender: TObject); var d1, d2: double; begin Memo1.Lines.Add(''); d1 := 1; repeat d2 := d1; d1 := d1 / 2; until d1 = 0; Edit1.Text := FloatToStr(d2); TestNumber(d2); end; procedure TForm1.Pi_bClick(Sender: TObject); var ext: extended; d: double; var ExtX: packed record Man: Int64; Exp: word end absolute ext; begin Memo1.Lines.Add(''); ext := pi; Edit1.Text := FloatToStr(ext); TestNumber(ext); d := pi; Edit1.Text := FloatToStr(d); TestNumber(d); end; procedure TForm1.CvtToHex_bClick(Sender: TObject); var ext: extended; var ExtX: packed record Man: Int64; Exp: word end absolute ext; begin end; procedure TForm1.CkAnalyzeFloat_bClick(Sender: TObject); var ext, ext2: Extended; dbl: Double; sgl: Single; i: integer; { Equivalence a record to var ext: } ExtX: packed record Man: Int64; Exp: word end absolute ext; DblX: Int64 absolute dbl; SglX: LongInt absolute sgl; s: string; begin Assert(SizeOf(ExtX) = SizeOf(ext)); Assert(SizeOf(DblX) = SizeOf(dbl)); Assert(SizeOf(SglX) = SizeOf(sgl)); for i := 0 to 20 do begin case i of 0: begin Memo1.Lines.Add(''); Memo1.Lines.Add('Check simple numbers.'); ext := 15; end; 3: begin Memo1.Lines.Add(''); Memo1.Lines.Add('Check crossover into sgl denormal.'); { Set ext = 2 * <single normal minimum>: } SglX := LongInt(2) shl 23; ext := sgl; end; 7: begin Memo1.Lines.Add(''); Memo1.Lines.Add('Check crossover into dbl denormal.'); { Set ext = 2 * <double normal minimum>: } DblX := Int64(2) shl 52; s := ParseFloat(dbl); ext := dbl; end; 11: begin Memo1.Lines.Add(''); Memo1.Lines.Add('Check crossover into ext denormal.'); { Set ext = 2 * <extended normal minimum>: } ExtX.Exp := 2; ExtX.Man := $8000000000000000; end; 15: begin Memo1.Lines.Add(''); Memo1.Lines.Add('Check cross over into zero.'); { Set ext = 2 * <external denormal minimum>: } ExtX.Exp := 0; ExtX.Man := $0000000000000002; end; { Divide the number to be analyzed by 2: } else ext := ext / 2; Memo1.Lines.Add(' divide by 2 and check'); end; dbl := ext; sgl := ext; { Set ext2 to same ext value times 10^4900: } ext2 := ext*1e4900; { Save the analysis to memo box: } Memo1.Lines.Add(Format(' %2.2d: Nbr=%g ((Nbr x 1e4900)=%g)',[i, ext, ext2])); Memo1.Lines.Add(' ' + ParseFloat(ext) + ' ' + ParseFloat(dbl) + ' ' + ParseFloat(sgl)); end{i-loop}; end; end.
{ System-dependent routines for resolving tree names. } module string_treename_sys; define string_treename_local; %include 'string2.ins.pas'; %include 'file.ins.pas'; %include 'string_sys.ins.pas'; { ******************************************************************************** * * Subroutine STRING_TREENAME_LOCAL (INAM, OPTS, TNAM, TSTAT) * * Translate the input pathname INAM into a treename in TNAM. This routine * only translates names for the local file system. Links to remote machines * are never followed since this can be done in a system-independent routine. * All flags in OPTS not specifically listed as obeyed are ignored. This was * done so that OPTS can be passed between successive routines without needing * editing. The obeyed OPTS flags are: * * STRING_TNAMOPT_FLINK_K - For pathnames that resolve to symbolic links, the * link will be followed. The default is to return the name of the link * without following it. Note that links are always followed if they are * not the last component of the pathname. * * STRING_TNAMOPT_PROC_K - The pathname is to be translated from the point of * view of this process. Certain pathname elements, like "~", are * process-specific. By default, process-specific pathname elements are * not translated. * * STRING_TNAMOPT_NATIVE_K - The native file system naming conventions will * be used for TNAM. This flag is neccessary if TNAM is to be passed to * local system routines. * * TSTAT indicates the translation status of the name in TNAM. This routine * will set TSTAT to one of the following values: * * STRING_TNSTAT_NATIVE_K - The name was fully translated as requested, and * is in native system form. * * STRING_TNSTAT_COG_K - The name was fully translated as requested, and is * in Embed (formerly Cognivision) portable standard form. * * STRING_TNSTAT_REMOTE_K - The name refers to a file system object that * resides on another machine. Further translation may be required on that * machine. * * STRING_TNSTAT_PROC_K - The name starts with a pathname element that must * be translated by the process "owning" the name. * * Note that TNAM may be returned with a different node name than expected for * one of the following reasons: * * 1 - The path resolves to a file system object on this machine, but this * machine is known by more than one name. In that case, the "preferred" * name of this machine will be used. * * 2 - The path name resolved to a file system object on another machine, but * that file system object can be accesses transparently with native OS * calls on this machine. } var envvar_homedrive: string_var16_t := {HOMEDRIVE environment variable name} [str := 'HOMEDRIVE', len := 9, max := 16]; envvar_homepath: string_var16_t := {HOMEPATH environment variable name} [str := 'HOMEPATH', len := 8, max := 16]; procedure string_treename_local ( {translate pathname on local machine only} in inam: univ string_var_arg_t; {input path name} in opts: string_tnamopt_t; {set of option flags} in out tnam: univ string_var_arg_t; {output tree name} out tstat: string_tnstat_k_t); {translation result status} val_param; var ii: sys_int_machine_t; {scratch integer and loop counter} t: string_var8192_t; {current pathname within drive so far} { ******************************* * * Local subroutine IMPLICIT_CURRDIR * This routine is local to STRING_TREENAME_LOCAL. * * Set T to indicate the current working directory if there is no accumulated * pathname so far (implicitly at current directory). Since the current * directory can only be determined by the owning process, we only try to * determine the current directory if the flag STRING_TNAMOPT_PROC_K is set in * OPTS. If it's not, we set the pathname to empty and set TSTAT to * STRING_TNSTAT_PROC_K. } procedure implicit_currdir; var winlen: win_dword_t; {number of chars in string from sys call} begin if t.len > 0 then return; {we already have explicit path ?} if string_tnamopt_proc_k in opts then begin {pathname is relative to this process ?} winlen := GetCurrentDirectoryA ( {get current directory treename} t.max, {max characters allowed to write} t.str); {returned path name} if winlen = 0 then begin {system call error} sys_sys_error_bomb ('string', 'err_get_working_dir', nil, 0); end; t.len := winlen; {set number of used chars in T} if t.str[t.len] = '\' then t.len := t.len - 1; {truncate any trailing "\"} end else begin {pathname is owned by another process} tstat := string_tnstat_proc_k; {need to translate curr dir in owner process} t.len := 0; {indicate implicit current directory} end ; end; { ******************************* * * Local subroutine DO_PATHNAME (INAME, OPTS) * This routine is local to STRING_TREENAME_LOCAL. * * Add the path name elements in INAME to the resulting treename being * accumulated in T. T always ends in a component name, never the component * separator "\". } procedure do_pathname ( {translate and accumulate pathname} in iname: univ string_var_arg_t; {pathname to translate and add to T} in opts: string_tnamopt_t); {option flags to use for this translation} val_param; type comptype_k_t = ( {pathname component type} comptype_netroot_k, {name is at network root} comptype_noderoot_k, {name is at node root} comptype_rel_k); {relative to current path} var p: sys_int_machine_t; {parse index into INAME} st: sys_int_machine_t; {start index for current pathname component} iname_len: sys_int_machine_t; {length of INAME with trailing blanks removed} t_len_save: string_index_t; {saved copy of T.LEN} comptype: comptype_k_t; {type of pathname component being parsed} no_comp: boolean; {no INAME component found yet} comp: string_var8192_t; {current pathname component extracted from input string} path: string_treename_t; {scratch pathname for recursive call} lnam: string_leafname_t; {scratch leafname} ii, jj: sys_int_machine_t; {scratch integers} pick: sys_int_machine_t; {number of keyword picked from list} cmds: string_var8192_t; {full embedded command string} cp: string_index_t; {CMDS parse index} tk: string_treename_t; {token parsed from command} stat: sys_err_t; {completion status} label next_comp, retry_comp, next_in_char, got_comp, have_comp, cmd_end, done_special, abort; begin comp.max := size_char(comp.str); {init local var strings} path.max := size_char(path.str); lnam.max := size_char(lnam.str); cmds.max := size_char(cmds.str); tk.max := size_char(tk.str); iname_len := iname.len; {init unpadded INAME length} while (iname_len > 0) and (iname.str[iname_len] = ' ') {find unpadded INAME length} do iname_len := iname_len - 1; p := 1; {init INAME parse index} while (p < iname_len) and (iname.str[p] = ' ') do p := p + 1; {skip over leading blanks} no_comp := true; {init to no INAME component found yet} { * Loop back here to extract each new pathname component from INAME. P is the * index to the first character of the new component. } next_comp: {start looking for whole new component} comptype := comptype_rel_k; {init to this component is relative to existing path} retry_comp: {try again to find a component} st := p; {save index to first char of component} if p > iname_len then begin {done the whole input pathname ?} if no_comp or (t.len = 0) then begin {only have implicit pathname ?} case comptype of {where are we in naming hierarchy} comptype_netroot_k, {set return name to machine root} comptype_noderoot_k: begin sys_sys_rootdir (t); {get root directory of this machine} t.len := t.len - 1; {truncate trailing "\"} end; comptype_rel_k: begin {get current working directory} implicit_currdir; {set T to current working directory name} if tstat <> string_tnstat_native_k {need to return with special condition ?} then goto abort; end; end; end; {done handling implicit pathname} return; end; {done handling end of INAME} comp.len := 0; {init this pathname component to empty} while p <= iname_len do begin {scan remaining chars in INAME} case iname.str[p] of {check for special handling char} '/', '\': begin {separator between components} p := p + 1; {set starting index of next component} if comp.len > 0 then goto got_comp; {separator ends this component ?} if {special case of following "x:" drive name ?} (t.len >= 2) and {existing path long enough for "x:" ?} (t.str[t.len] = ':') {existing path ends in ":" ?} then begin goto next_in_char; {ignore this char as separator after drive name} end; if no_comp then begin {this char is at start of new pathname ?} case comptype of {promote the component type by one} comptype_noderoot_k: begin comptype := comptype_netroot_k; end; comptype_rel_k: begin comptype := comptype_noderoot_k; end; end; end; {end of separator before first component} goto retry_comp; {try again with new component type} end; {end of pathname separator case} end; {end of special character cases} if comp.len < comp.max then begin {this is just another component character} comp.len := comp.len + 1; comp.str[comp.len] := iname.str[p]; end; p := p + 1; {advance to next character in this component} next_in_char: {back to handle next INAME character} end; {back and process this new character} { * The next pathname component has been extracted into COMP. } got_comp: no_comp := false; {at least one component has been found now} have_comp: {pathname component to add is in COMP} if comp.len = 0 then goto next_comp; { * Check for ":", which indicates string preceeding it is a drive name. } for ii := 1 to comp.len do begin {scan characters in this component} if comp.str[ii] = ':' then begin {drive letter terminator is at I ?} string_substr (comp, 1, ii, t); {replace accumulated path with drive name} string_upcase (t); {drive names are always upper case} ii := ii + 1; {go to first char after drive name} while (ii <= comp.len) and ((comp.str[ii] = '/') or (comp.str[ii] = '\')) do ii := ii + 1; {delete leading component delimiters} for jj := ii to comp.len do begin {shift remaining component string to start} comp.str[jj-ii+1] := comp.str[jj]; end; comp.len := comp.len - ii + 1; goto have_comp; {back to process "new" pathname component} end; {done handling drive name} end; case comp.str[1] of {check for special case component syntaxes} '.': begin {could be current or parent directory} if comp.len = 1 then goto retry_comp; {current directory ?} if {parent directory ?} (comp.len = 2) and then (comp.str[2] = '.') then begin case comptype of {ignore for component types can't go up from} comptype_netroot_k, comptype_noderoot_k: begin goto retry_comp; end; end; {end of component type cases} implicit_currdir; {resolve implicit current directory if needed} if tstat <> string_tnstat_native_k {need to return with special condition ?} then goto abort; if t.str[t.len] = ':' then begin {going to machine root from drive root ?} t.len := 0; {next component starts at machine root} comptype := comptype_noderoot_k; goto retry_comp; {get next component with new COMPTYPE setting} end; while t.str[t.len] <> '\' {look for last "\" in accumulated tree name} do t.len := t.len - 1; t.len := t.len - 1; {delete trailing "\"} goto next_comp; {back for next pathname component} end; {done handling component is parent directory} end; '~': begin {could be user's home directory} if comp.len <> 1 then goto done_special; {not just "~" symbol ?} if not (string_tnamopt_proc_k in opts) then begin {we don't own pathname ?} t.len := 0; {path name so far is irrelevant} tstat := string_tnstat_proc_k; {need to be translated by owning process} goto abort; {return with special condition} end; sys_envvar_get (envvar_homedrive, t, stat); {get HOMEDRIVE value, like "C:"} if sys_error(stat) then begin sys_sys_rootdir (t); {default to machine root directory} end; if {truncate trailing "\", if present} (t.len > 0) and (t.str[t.len] = '\') then begin t.len := t.len - 1; end; sys_envvar_get (envvar_homepath, path, stat); if not sys_error(stat) then begin {successfully got home directory path name ?} do_pathname ( {resolve home directory pathname} path, {path to resolve after home drive name} [ string_tnamopt_flink_k, {follow all links} string_tnamopt_proc_k] {PATH is relative to this process} ); if tstat <> string_tnstat_native_k then goto abort; {special condition ?} end; goto next_comp; end; '(': begin {embedded command} cmds.len := 0; {init command string to empty} for ii := 2 to comp.len do begin {scan remaining characters this component} if comp.str[ii] = ')' {found end of command string character ?} then goto cmd_end; if cmds.len < cmds.max then begin {room for one more character ?} cmds.len := cmds.len + 1; {append this char to end of command name} cmds.str[cmds.len] := comp.str[ii]; end; end; {back for next cmds char in INAME} goto done_special; {")" missing, not a command ?} cmd_end: {II is COMP char of command end ")"} lnam.len := comp.len - ii; {leafname length after command} for jj := 1 to comp.len do begin {copy component remainder into COMP} lnam.str[jj] := comp.str[ii + jj]; end; { * The command string inside the parenthesis is in CMDS, and the * remaining pathname component after the command is in LNAM. } cp := 1; {init command parse index} string_token (cmds, cp, tk, stat); {get command name from command string} if sys_error(stat) then goto done_special; string_upcase (tk); {make upper case for keyword matching} string_tkpick80 (tk, {pick command name from list} 'COG EVAR VAR', pick); {number of keyword picked from list} case pick of 1: begin {(COG)pathname} if cp <= tk.len then goto done_special; {unexpected command parameter ?} string_terminate_null (lnam); {make sure LNAM.STR is null terminated} sys_cognivis_dir (lnam.str, path); {get Cognivis dir path} do_pathname (path, opts); {add on expanded Cognivis directory path} if tstat <> string_tnstat_native_k then goto abort; {special condition ?} end; 2: begin {(EVAR)envvar} if cp <= tk.len then goto done_special; {unexpected command parameter ?} if lnam.len <= 0 then goto next_comp; {ignore if no environment var name given} if not (string_tnamopt_proc_k in opts) then begin {we don't own pathname ?} tstat := string_tnstat_proc_k; {need to be translated by owning process} goto abort; {return with special condition} end; sys_envvar_get (lnam, comp, stat); {get environment variable value} if sys_error(stat) then comp.len := 0; {envvar not found same as empty string} goto have_comp; {pathname component to process is in COMP} end; 3: begin {(VAR envvar)pathname} string_token (cmds, cp, tk, stat); {get environment variable name} if sys_error(stat) then goto done_special; if cp <= tk.len then goto done_special; {unexpected additional parameter ?} if tk.len <= 0 then begin {no envvar same as empty envvar} string_copy (lnam, comp); {resolved component is path after command} goto have_comp; end; if not (string_tnamopt_proc_k in opts) then begin {we don't own pathname ?} tstat := string_tnstat_proc_k; {need to be translated by owning process} goto abort; {return with special condition} end; sys_envvar_get (tk, comp, stat); {resolved component start with envvar value} if sys_error(stat) then comp.len := 0; {not exist same as empty string} string_append (comp, lnam); {add pathname component after envvar expansion} goto have_comp; {resolved pathname component is in COMP} end; otherwise {unrecognized command} goto done_special; {don't treat as special component} end; {end of command cases} goto next_comp; {back to do next input pathname component} end; {end of imbedded command case} end; {done handling special case component names} done_special: {definately done with special handling} { * All special syntax in this pathname component, if any, have been resolved * and the result is in COMP. * * Now add this input pathname component to the end of the accumulated * treename. } case comptype of {where does component fit into hierarchy ?} comptype_netroot_k: begin {component is at network root (machine name)} string_downcase (comp); {we always list machine names in lower case} if not nodename_set then string_set_nodename; {make sure NODENAME is all set} if string_equal (comp, nodename) then begin {this is our machine name ?} sys_sys_rootdir (t); {go to machine root directory} t.len := t.len - 1; {truncate trailing "\"} goto next_comp; end; {end of node name was this machine} t.len := 1; {set T to just "/"} t.str[1] := '/'; {additional path will be set by ABORT code} tstat := string_tnstat_remote_k; {further translation must be on remmote node} goto abort; {return with special condition} end; {end of component is machine name case} comptype_noderoot_k: begin {component is at machine root} sys_sys_rootdir (t); {go to machine root directory} t.len := t.len - 1; {truncate trailing "\"} end; comptype_rel_k: begin {component is relative to existing path} implicit_currdir; {make sure we have explicit existing path} if tstat <> string_tnstat_native_k {need to return with special condition ?} then goto abort; end; end; {end of special handling component type cases} t_len_save := t.len; {save length of T before adding on component} if t.len >= t.max then return; {punt if overflowed T} t.len := t.len + 1; {append "\" separator to T} t.str[t.len] := '\'; string_append (t, comp); {append this pathname component} { * The new pathname component has been added to T. T_LEN_SAVE is the length * value for T before the pathname was added. Now check for the new treename * being a symbolic link if links are supposed to be followed at this point. } if {follow if it's a link ?} (string_tnamopt_flink_k in opts) or {link following is enabled ?} (p <= iname_len) {this is not the last pathname component ?} then begin file_link_resolve (t, path, stat); {try to read file as a symbolic link} if not sys_error(stat) then begin {actually got symbolic link value ?} t.len := t_len_save; {restore T to before link name added} do_pathname ( {append link expansion to existing path} path, {pathname to translate} opts + [string_tnamopt_flink_k]); {follow any subordinate links} if tstat <> string_tnstat_native_k {special condition occurred ?} then goto abort; {fix up pathname and leave} end; end; {done handling symbolic link} goto next_comp; {back for next input name component} { * A condition has arisen that prevents us from further processing the input * pathname. TSTAT is already set to indicate what the condition is. We now * append the unused part of INAME, starting with the current component, to the * path accumulated so far in T. } abort: if t.len >= t.max then return; {punt if overflowed T} ii := iname_len - st + 1; {number of chars in remaining path} if (t.len > 0) and (st <= iname_len) then begin {need separator ?} t.len := t.len + 1; {append "/" separator to T} t.str[t.len] := '/'; end; while ii > 0 do begin {loop until remaining path exhausted} if t.len >= t.max then return; {punt if overflowed T} t.len := t.len + 1; {apppend this component name character to T} if iname.str[st] = '\' {translate any "\" to "/"} then t.str[t.len] := '/' else t.str[t.len] := iname.str[st]; st := st + 1; {advance source char index} ii := ii - 1; {one less character to copy} end; {back for next char in remaining path} end; { ******************************* * * Start of main routine STRING_TREENAME_LOCAL. } begin t.max := size_char(t.str); {init local var string} t.len := 0; {init to no accumulated path on drive} tstat := string_tnstat_native_k; {init to returning full native pathname} do_pathname (inam, opts); {process info from input pathname} if tstat = string_tnstat_native_k then begin {we have a native pathname ?} if string_tnamopt_native_k in opts then begin {native pathname was requested ?} if t.str[t.len] = ':' then begin {pathname is raw drive name} string_append1 (t, '\'); {indicate root directory on drive} end; end else begin {translate to Embed portable pathname rules} tnam.len := 0; {init returned treename to empty} string_appendn (tnam, '//', 2); {path starts at network root} if not nodename_set then string_set_nodename; {make sure NODENAME is all set} string_append (tnam, nodename); {add machine name} string_append1 (tnam, '/'); {add separator after machine name} for ii := 1 to t.len do begin {once for each character in remaining path} if t.str[ii] = '\' then string_append1 (tnam, '/') {translate "\" to "/"} else string_append1 (tnam, t.str[ii]); end; {back for next character from T} tstat := string_tnstat_cog_k; {indicate Cognivision naming rules used} return; end {done handling Embed naming requested} ; end; {done handling T was raw native pathname} string_copy (t, tnam); {pass back final translated string} end;
unit UGerar_Lote_Aux2; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, Grids, DBGrids, SMDBGrid, UDMCadLote, NxCollection, RzPanel, SqlExpr, dbXPress; type TfrmGerar_Lote_Aux2 = class(TForm) SMDBGrid1: TSMDBGrid; Panel1: TPanel; NxSplitter1: TNxSplitter; RzGroupBox3: TRzGroupBox; SMDBGrid3: TSMDBGrid; NxSplitter2: TNxSplitter; btnConfirmar: TNxButton; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormShow(Sender: TObject); procedure btnConfirmarClick(Sender: TObject); private { Private declarations } vNumLote : Integer; vNumOrdem : Integer; vID_Material_Pri : Integer; vID_Cor_Mat_Pri : Integer; vID_Cor_Mat_Pri2 : Integer; vConsumo_Pri : Real; vID_Material_Pri2 : Integer; vConsumo_Pri2 : Real; vID_BaixaProcesso : Integer; procedure prc_Gravar_Lote; procedure prc_Le_Consumo(Tipo : String); //P= Produto Pedido S= Semi Acabado procedure prc_Le_Processo_Grupo_Item(Tipo : String); //S= Semi Acabado L=Lote P=Pedido public { Public declarations } fDMCadLote: TDMCadLote; end; var frmGerar_Lote_Aux2: TfrmGerar_Lote_Aux2; implementation uses rsDBUtils, DB, DmdDatabase; {$R *.dfm} procedure TfrmGerar_Lote_Aux2.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := Cafree; end; procedure TfrmGerar_Lote_Aux2.FormShow(Sender: TObject); begin oDBUtils.SetDataSourceProperties(Self, fDMCadLote); end; procedure TfrmGerar_Lote_Aux2.btnConfirmarClick(Sender: TObject); var ID: TTransactionDesc; sds: TSQLDataSet; begin vNumLote := 0; vNumOrdem := 0; vID_BaixaProcesso := 0; fDMCadLote.vGerado := False; sds := TSQLDataSet.Create(nil); ID.TransactionID := 1; ID.IsolationLevel := xilREADCOMMITTED; dmDatabase.scoDados.StartTransaction(ID); try sds.SQLConnection := dmDatabase.scoDados; sds.NoMetadata := True; sds.GetMetadata := False; sds.CommandText := ' UPDATE TABELALOC SET FLAG = 1 WHERE TABELA = ' + QuotedStr('LOTE'); sds.ExecSQL(); fDMCadLote.mAuxLote.First; while not fDMCadLote.mAuxLote.Eof do begin prc_Gravar_Lote; fDMCadLote.mAuxLote.Next; end; fDMCadLote.prc_Abrir_Lote_Mat(vNumOrdem); fDMCadLote.mMaterial.First; while not fDMCadLote.mMaterial.Eof do begin fDMCadLote.prc_Gravar_Lote_Mat; fDMCadLote.mMaterial.Next; end; fDMCadLote.cdsLote_Mat.ApplyUpdates(0); fDMCadLote.cdsLote.ApplyUpdates(0); fDMCadLote.cdsBaixa_Processo.ApplyUpdates(0); MessageDlg('*** Lotes/Talġes Gerados!', mtInformation, [mbok], 0); dmDatabase.scoDados.Commit(ID); fDMCadLote.vGerado := True; except dmDatabase.scoDados.Rollback(ID); raise; end; FreeAndNil(sds); if fDMCadLote.vGerado then Close; end; procedure TfrmGerar_Lote_Aux2.prc_Gravar_Lote; var vData: TDateTime; vID_CombinacaoAux: Integer; vNumPedAux: Integer; vIDProdAux : Integer; vRefAux : String; vID_Cliente : Integer; vCompleto : String; vQtdAux : Real; begin fDMCadLote.prc_Inserir; fDMCadLote.cdsLoteQTD_TALOES.AsInteger := 1; fDMCadLote.cdsLoteDTEMISSAO.AsDateTime := Date; fDMCadLote.cdsLoteHREMISSAO.AsDateTime := Now; fDMCadLote.cdsLoteID_PRODUTO.AsInteger := fDMCadLote.mAuxLoteID_Produto.AsInteger; fDMCadLote.cdsLoteREFERENCIA.AsString := fDMCadLote.mAuxLoteReferencia.AsString; fDMCadLote.cdsLoteID_COMBINACAO.AsInteger := fDMCadLote.mAuxLoteID_Combinacao.AsInteger; fDMCadLote.cdsLoteCARIMBO.AsString := ''; fDMCadLote.cdsLoteNUM_PEDIDO.AsInteger := fDMCadLote.mAuxLoteNum_Pedido.AsInteger; fDMCadLote.cdsLoteID_CLIENTE.AsInteger := fDMCadLote.mAuxLoteID_Cliente.AsInteger; fDMCadLote.cdsLoteDTENTREGA.AsDateTime := fDMCadLote.mAuxLoteDtEntrega.AsDateTime; fDMCadLote.cdsLoteFILIAL.AsInteger := fDMCadLote.cdsPendenteFILIAL.AsInteger; fDMCadLote.cdsLoteQTD.AsFloat := fDMCadLote.mAuxLoteQtd.AsFloat; fDMCadLote.cdsLoteQTD_PRODUZIDO.AsFloat := 0; fDMCadLote.cdsLoteNOME.AsString := ''; if vNumLote <= 0 then begin fDMCadLote.qProximo_Lote.Close; fDMCadLote.qProximo_Lote.Open; vNumLote := fDMCadLote.qProximo_LoteNUM_LOTE.AsInteger; end; vNumLote := vNumLote + 1; if vNumOrdem <= 0 then begin fDMCadLote.qProxima_Ordem.Close; fDMCadLote.qProxima_Ordem.Open; vNumOrdem := fDMCadLote.qProxima_OrdemNUM_ORDEM.AsInteger + 1; end; fDMCadLote.cdsLoteNUM_LOTE.AsInteger := vNumLote; fDMCadLote.cdsLoteNUM_ORDEM.AsInteger := vNumOrdem; fDMCadLote.cdsLoteQTD_ORIGINAL.AsFloat := fDMCadLote.mAuxLoteQtd_Original.AsFloat; fDMCadLote.cdsLoteQTD_PARES.AsFloat := fDMCadLote.mAuxLoteQtd_Pares.AsFloat; //fDMCadLote.cdsLoteID_PROCESSO_GRUPO.AsInteger := fDMCadLote.mAuxLoteID_Processo_Grupo.AsInteger; fDMCadLote.cdsLoteOBS_PED.AsString := fDMCadLote.mAuxLoteObs_Pedido.AsString; fDMCadLote.cdsLoteITEM_ORDEM.AsInteger := 1; fDMCadLote.cdsLoteCOMPLETO.AsString := 'S'; fDMCadLote.cdsLoteQTD.AsFloat := fDMCadLote.mAuxLoteQtd.AsFloat; fDMCadLote.cdsLoteQTD_PENDENTE.AsFloat := StrToFloat(FormatFloat('0.0000',fDMCadLote.cdsLoteQTD.AsFloat)); fDMCadLote.cdsLoteTIPO_LOTE.AsString := fDMCadLote.mAuxLoteTipo_Lote.AsString; fDMCadLote.cdsLoteUNIDADE.AsString := fDMCadLote.mAuxLoteUnidade.AsString; fDMCadLote.cdsLoteQTD_PARES.AsFloat := fDMCadLote.mAuxLoteQtd_Pares.AsFloat; fDMCadLote.cdsLoteITEM_ORDEM_TOTAL.AsInteger := 1; fDMCadLote.cdsLoteENCERADO.AsString := fDMCadLote.mAuxLoteEncerado.AsString; fDMCadLote.cdsLote.Post; fDMCadLote.mAuxLote_Ped.First; while not fDMCadLote.mAuxLote_Ped.Eof do begin fDMCadLote.cdsLote_Ped.Insert; fDMCadLote.cdsLote_PedID_PEDIDO.AsInteger := fDMCadLote.mAuxLote_PedID_Pedido.AsInteger; fDMCadLote.cdsLote_PedITEM_PEDIDO.AsInteger := fDMCadLote.mAuxLote_PedItem_Pedido.AsInteger; fDMCadLote.cdsLote_PedQTD.AsFloat := fDMCadLote.mAuxLoteQtd.AsFloat; fDMCadLote.cdsLote_PedID_CLIENTE.AsInteger := fDMCadLote.mAuxLoteID_Cliente.AsInteger; fDMCadLote.cdsLote_PedNUM_LOTE.AsInteger := fDMCadLote.cdsLoteNUM_LOTE.AsInteger; fDMCadLote.cdsLote_PedBAIXADO.AsString := 'N'; fDMCadLote.cdsLote_PedPEDIDO_CLIENTE.AsString := fDMCadLote.mAuxLote_PedPedido_Cliente.AsString; fDMCadLote.cdsLote_PedNUM_PEDIDO.AsInteger := fDMCadLote.mAuxLote_PedNum_Pedido.AsInteger; fDMCadLote.cdsLote_PedQTD_PARES.AsFloat := fDMCadLote.mAuxLote_PedQtd_Pares.AsFloat; fDMCadLote.cdsLote_Ped.Post; fDMCadLote.mAuxLote_Ped.Next; end; prc_Le_Processo_Grupo_Item(fDMCadLote.cdsLoteTIPO_LOTE.AsString); end; procedure TfrmGerar_Lote_Aux2.prc_Le_Consumo(Tipo : String); //P= Produto Pedido S= Semi Acabado var vID_Cor : Integer; vQtdAux : Real; begin vID_Material_Pri := 0; vID_Cor_Mat_Pri := 0; vID_Cor_Mat_Pri2 := 0; vConsumo_Pri := 0; vID_Material_Pri2 := 0; vConsumo_Pri2 := 0; fDMCadLote.cdsConsumo.First; while not fDMCadLote.cdsConsumo.Eof do begin if fDMCadLote.cdsConsumoTIPO_REG_MAT.AsString <> 'S' then begin if (fDMCadLote.cdsConsumoIMP_TALAO.AsString = 'S') and (Tipo <> 'P') then begin if vID_Material_Pri <= 0 then begin vID_Material_Pri := fDMCadLote.cdsConsumoID_MATERIAL.AsInteger; vConsumo_Pri := StrToFloat(FormatFloat('0.00000',fDMCadLote.cdsConsumoQTD_CONSUMO.AsFloat)); vID_Cor_Mat_Pri := fDMCadLote.cdsConsumoID_COR.AsInteger; end else if vID_Material_Pri2 <= 0 then begin vID_Material_Pri2 := fDMCadLote.cdsConsumoID_MATERIAL.AsInteger; vConsumo_Pri2 := StrToFloat(FormatFloat('0.00000',fDMCadLote.cdsConsumoQTD_CONSUMO.AsFloat)); vID_Cor_Mat_Pri2 := fDMCadLote.cdsConsumoID_COR.AsInteger; end; end; //************************* //if (fDMCadLote.cdsConsumoCONT_COR_MAT.AsInteger <= 0) or (fDMCadLote.mAuxLoteID_Combinacao.AsInteger <= 0) then // vID_Cor := 0 //else //vID_Cor := fDMCadLote.mAuxLoteID_Combinacao.AsInteger; vID_Cor := fDMCadLote.cdsConsumoID_COR.AsInteger; if fDMCadLote.cdsConsumoTIPO_REG_MAT.AsString <> 'S' then begin if fDMCadLote.mMaterial.Locate('ID_Material;ID_Cor',VarArrayOf([fDMCadLote.cdsConsumoID_MATERIAL.AsInteger,vID_Cor]),[locaseinsensitive]) then fDMCadLote.mMaterial.Edit else begin fDMCadLote.mMaterial.Insert; fDMCadLote.mMaterialID_Material.AsInteger := fDMCadLote.cdsConsumoID_MATERIAL.AsInteger; fDMCadLote.mMaterialID_Cor.AsInteger := vID_Cor; fDMCadLote.mMaterialNome_Material.AsString := fDMCadLote.cdsConsumoNOME_MATERIAL.AsString; fDMCadLote.mMaterialReferencia_Mat.AsString := fDMCadLote.cdsConsumoREFERENCIA_MAT.AsString; fDMCadLote.mMaterialUnidade.AsString := fDMCadLote.cdsConsumoUNIDADE.AsString; fDMCadLote.mMaterialID_Fornecedor.AsInteger := fDMCadLote.cdsConsumoID_FORNECEDOR.AsInteger; fDMCadLote.mMaterialTingimento.AsString := fDMCadLote.cdsConsumoTINGIMENTO.AsString; if fDMCadLote.cdsConsumoTINGIMENTO.AsString = 'S' then fDMCadLote.mMaterialID_Material_Cru.AsInteger := fDMCadLote.cdsConsumoID_MATERIAL_CRU.AsInteger else fDMCadLote.mMaterialID_Material_Cru.AsInteger := 0; end; if Tipo = 'P' then vQtdAux := StrToFloat(FormatFloat('0.00000',fDMCadLote.mAuxLote_PedQtd_Pares.AsFloat)) else vQtdAux := StrToFloat(FormatFloat('0.00000',fDMCadLote.mAuxLoteQtd.AsFloat)); fDMCadLote.mMaterialQtd_Consumo.AsFloat := fDMCadLote.mMaterialQtd_Consumo.AsFloat + StrToFloat(FormatFloat('0.0000',(fDMCadLote.cdsConsumoQTD_CONSUMO.AsFloat * vQtdAux))); if Tipo = 'P' then fDMCadLote.mMaterialQtd_Produto.AsFloat := fDMCadLote.mMaterialQtd_Produto.AsFloat + fDMCadLote.mAuxLoteQtd_Pares.AsFloat else fDMCadLote.mMaterialQtd_Produto.AsFloat := fDMCadLote.mMaterialQtd_Produto.AsFloat + fDMCadLote.mAuxLoteQtd.AsFloat; fDMCadLote.mMaterial.Post; end; end; fDMCadLote.cdsConsumo.Next; end; end; procedure TfrmGerar_Lote_Aux2.prc_Le_Processo_Grupo_Item(Tipo: String); var vTipo : String; vItemAux : Integer; begin fDMCadLote.qProcesso.Close; fDMCadLote.qProcesso.ParamByName('ID').AsInteger := fDMCadLote.cdsLoteID_PRODUTO.AsInteger; fDMCadLote.qProcesso.Open; if not fDMCadLote.cdsBaixa_Processo.Active then begin fDMCadLote.cdsBaixa_Processo.Close; fDMCadLote.sdsBaixa_Processo.ParamByName('NUM_ORDEM').AsInteger := vNumOrdem; fDMCadLote.cdsBaixa_Processo.Open; end; while not fDMCadLote.qProcesso.Eof do begin vTipo := '1'; if trim(vTipo) <> '' then begin if fDMCadLote.cdsBaixa_Processo.Locate('ID_LOTE;ID_PROCESSO',VarArrayOf([fDMCadLote.cdsLoteID.AsInteger,fDMCadLote.qProcessoID_PROCESSO.AsInteger]),[locaseinsensitive]) then begin fDMCadLote.cdsBaixa_Processo.Edit; fDMCadLote.cdsBaixa_ProcessoQTD.AsFloat := fDMCadLote.cdsLoteQTD.AsFloat; fDMCadLote.cdsBaixa_Processo.Post; vTipo := ''; end; if trim(vTipo) <> '' then begin if vID_BaixaProcesso <= 0 then vID_BaixaProcesso := dmDatabase.ProximaSequencia('BAIXA_PROCESSO',0); fDMCadLote.cdsBaixa_Processo.Last; vItemAux := fDMCadLote.cdsBaixa_ProcessoITEM.AsInteger; fDMCadLote.cdsBaixa_Processo.Insert; fDMCadLote.cdsBaixa_ProcessoID.AsInteger := vID_BaixaProcesso; fDMCadLote.cdsBaixa_ProcessoITEM.AsInteger := vItemAux + 1; fDMCadLote.cdsBaixa_ProcessoID_PROCESSO.AsInteger := fDMCadLote.qProcessoID_PROCESSO.AsInteger; fDMCadLote.cdsBaixa_ProcessoID_LOTE.AsInteger := fDMCadLote.cdsLoteID.AsInteger; fDMCadLote.cdsBaixa_ProcessoDTENTRADA.Clear; fDMCadLote.cdsBaixa_ProcessoHRENTRADA.Clear; fDMCadLote.cdsBaixa_ProcessoDTBAIXA.Clear; fDMCadLote.cdsBaixa_ProcessoHRBAIXA.Clear; fDMCadLote.cdsBaixa_ProcessoQTD.AsFloat := fDMCadLote.cdsLoteQTD.AsFloat; fDMCadLote.cdsBaixa_ProcessoQTD_PRODUZIDO.AsFloat := 0; fDMCadLote.cdsBaixa_ProcessoNUM_ORDEM.AsInteger := vNumOrdem; fDMCadLote.cdsBaixa_ProcessoTIPO.AsString := vTipo; fDMCadLote.cdsBaixa_Processo.Post; end; end; fDMCadLote.qProcesso.Next; end; end; end.
{ Copy with override "Image Space" group from your plugins to a new one, then apply this script. Makes the similar effect as those two mods: Skyrim SDR http://skyrim.nexusmods.com/mods/7081 No Tint http://skyrim.nexusmods.com/mods/648 Warning: Skyrim SDR reported to screw night vision, so you might want to leave Bloom or Adaptation unchanged if that happens. Needs confirmation. } unit UserScript; const BloomMult = 0; // Bloom multiplier AdaptSpeed = 90; // Adaptation speed AdaptStrengthMult = 1; // Adaptation strength multiplier TintMult = 0.45; // Tint multiplier TintMin = 0.1; // Min tint amount var fBloom, fAdapt, fTint: boolean; function Initialize: integer; begin Result := 0; fBloom := (MessageDlg('Tweak Bloom?', mtConfirmation, [mbYes, mbNo], 0) = mrYes); fAdapt := (MessageDlg('Tweak Eyes Adaptation?', mtConfirmation, [mbYes, mbNo], 0) = mrYes); fTint := (MessageDlg('Tweak Tint?', mtConfirmation, [mbYes, mbNo], 0) = mrYes); end; function Process(e: IInterface): integer; var v: single; begin Result := 0; if Signature(e) <> 'IMGS' then Exit; AddMessage('Processing: ' + Name(e)); if fBloom then SetElementNativeValues(e, 'HNAM - HDR\Bloom Blur Radius', GetElementNativeValues(e, 'HNAM - HDR\Bloom Blur Radius') * BloomMult); if fAdapt then begin SetElementNativeValues(e, 'HNAM - HDR\Eye Adapt Speed', AdaptSpeed); SetElementNativeValues(e, 'HNAM - HDR\Eye Adapt Strength', GetElementNativeValues(e, 'HNAM - HDR\Eye Adapt Strength') * AdaptStrengthMult); end; if fTint and ElementExists(e, 'TNAM') then begin v := GetElementNativeValues(e, 'TNAM - Tint\Amount'); // don't alter/reduce tint less than TintMin if v > TintMin then begin v := v*TintMult; if v < TintMin then v := TintMin else if v > 1 then v := 1; SetElementNativeValues(e, 'TNAM - Tint\Amount', v); end; end; end; end.
unit untEvent; {$mode objfpc}{$H+} interface uses Classes, SysUtils; {$M+} type TMyEventTakingAStringParameter = procedure(const aStrParam: string) of object; TMyDummyLoggingClass = class public EvtLogMsg: TMyEventTakingAStringParameter; // This will hold the "closure", a pointer to // the method function itself + a pointer to the // object instance it's supposed to work on. property OnLogMsg: TMyEventTakingAStringParameter read EvtLogMsg write EvtLogMsg; procedure LogMsg(const msg: string); end; implementation procedure TMyDummyLoggingClass.LogMsg(const msg: string); begin if Assigned(EvtLogMsg) then // tests if the event is assigned EvtLogMsg(msg); // calls the event. end; end.
unit PWEditInfoWell; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Well, DialogForm, ImgList, ActnList, FramesWizard, ComCtrls, ToolWin, PWInfoWellFrame; type TfrmEditInfoWell = class(TCommonDialogForm) private protected function GetEditingObjectName: string; override; procedure NextFrame(Sender: TObject); override; procedure FinishClick(Sender: TObject); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; var frmEditInfoWell: TfrmEditInfoWell; implementation uses ReasonChange, Facade; {$R *.dfm} { TCommonDialogForm1 } constructor TfrmEditInfoWell.Create(AOwner: TComponent); begin inherited; dlg.AddFrame(TfrmInfoWell); dlg.ActiveFrameIndex := 0; dlg.FinishEnableIndex := 0; Caption := 'Редактор основной инфомарции по скважине'; dlg.OnFinishClick := FinishClick; Height := 573; Width := 710; end; destructor TfrmEditInfoWell.Destroy; begin inherited; end; procedure TfrmEditInfoWell.FinishClick(Sender: TObject); var w: TWell; begin try w := EditingObject as TWell; Save; w.LastModifyDate := Date; w.Update; ShowMessage('Изменения успешно сохранены.'); except end; end; function TfrmEditInfoWell.GetEditingObjectName: string; begin Result := 'Скважина'; end; procedure TfrmEditInfoWell.NextFrame(Sender: TObject); begin inherited; end; end.
unit GradPnl; interface uses System.Classes, Vcl.Graphics, Vcl.Controls; type TDirection = (TopToBottom, BottomToTop, LeftToRight, RightToLeft, EdgesToCenter, CenterToEdges, HCenterToEdges, EdgesToHCenter, VCenterToEdges, EdgesToVCenter, TopLeft, BottomLeft, TopRight, BottomRight, EllipticIn, EllipticOut); type TCountOfColor = 1..255; type TGradientPanel = class(TGraphicControl) private { Private declarations } FColorFrom: TColor; FColorTo: TColor; FCount: TCountOfColor; FDirection: TDirection; protected procedure Paint; override; procedure SetPaintColorFrom(Value: TColor); procedure SetPaintColorTo(Value: TColor); procedure SetPaintCount(Value: TCountOfColor); procedure SetPaintDirection(Value: TDirection); public constructor Create(AOwner: TComponent); override; published property ColorFrom: TColor read FColorFrom write SetPaintColorFrom; property ColorTo: TColor read FColorTo write SetPaintColorTo; property ColorCount: TCountOfColor read FCount write SetPaintCount; property Direction: TDirection read FDirection write SetPaintDirection; property Align; property DragCursor; property DragMode; property Enabled; property Font; property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property ShowHint; property Visible; property OnClick; property OnDblClick; property OnDragDrop; property OnDragOver; property OnEndDrag; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDrag; end; procedure Register; implementation uses Windows; constructor TGradientPanel.Create(AOwner: TComponent); begin inherited Create(AOwner); FColorFrom := clBlue; FColorTo := clBlack; FCount := 64; Height := 100; Width := 100; Invalidate; end; procedure TGradientPanel.Paint; var RedFrom, GreenFrom, BlueFrom, RedTo, GreenTo, BlueTo: Byte; DiffRed, DiffGreen, DiffBlue: Integer; i, StartHeight, EndHeight, StartWidth, EndWidth: Integer; StepHeight, StepWidth: Double; begin StartHeight := 0; StartWidth := 0; EndHeight := 0; EndWidth := 0; StepHeight := 0; StepWidth := 0; case FDirection of TopToBottom, BottomToTop: begin EndHeight := Height; StepHeight := Height / (FCount + 1); end; LeftToRight, RightToLeft: begin EndWidth := Width; StepWidth := Width / (FCount + 1); end; EdgesToCenter, CenterToEdges, EllipticIn, EllipticOut: begin EndWidth := Trunc(Width / 2); StepWidth := Width / (2 * FCount + 2); EndHeight := Trunc(Height / 2); StepHeight := Height / (2 * FCount + 2); end; HCenterToEdges, EdgesToHCenter: begin EndHeight := Trunc(Height / 2); StepHeight := Height / (2 * FCount + 2); end; VCenterToEdges, EdgesToVCenter: begin EndWidth := Trunc(Width / 2); StepWidth := Width / (2 * FCount + 2); end; TopLeft, BottomLeft, TopRight, BottomRight: begin EndWidth := Width; StepWidth := Width / (FCount + 1); EndHeight := Trunc(Height / 2); StepHeight := Height / (FCount + 1); end; end; {óñòàíàâëèâàåì íà÷àëüíûé öâåò è ðàçíèöó ìåæäó íà÷àëüíûì è êîíå÷íûì} if (FDirection in [BottomToTop, RightToLeft, CenterToEdges, EllipticOut, HCenterToEdges, VCenterToEdges, TopLeft, BottomLeft, TopRight, BottomRight]) then begin RedFrom := (FColorTo and $000000FF); GreenFrom := (FColorTo and $0000FF00) shr 8; BlueFrom := (FColorTo and $00FF0000) shr 16; RedTo := (FColorFrom and $000000FF); GreenTo := (FColorFrom and $0000FF00) shr 8; BlueTo := (FColorFrom and $00FF0000) shr 16; end else begin RedFrom := (FColorFrom and $000000FF); GreenFrom := (FColorFrom and $0000FF00) shr 8; BlueFrom := (FColorFrom and $00FF0000) shr 16; RedTo := (FColorTo and $000000FF); GreenTo := (FColorTo and $0000FF00) shr 8; BlueTo := (FColorTo and $00FF0000) shr 16; end; DiffRed := RedTo - RedFrom; DiffGreen := GreenTo - GreenFrom; DiffBlue := BlueTo - BlueFrom; if (FDirection in [EllipticIn, EllipticOut]) then begin with inherited Canvas do begin Pen.Style := psClear; Brush.Color := RGB(RedFrom, GreenFrom, BlueFrom); Rectangle(0, 0, Width, Height); end; end; for i := 0 to FCount - 1 do begin with inherited Canvas do begin Pen.Style := psClear; if FCount > 1 then Brush.Color := RGB(RedFrom + MulDiv(i, DiffRed, FCount - 1), GreenFrom + MulDiv(i, DiffGreen, FCount - 1), BlueFrom + MulDiv(i, DiffBlue, FCount - 1)) else Brush.Color := RGB(RedFrom, GreenFrom, BlueFrom); case FDirection of TopToBottom, BottomToTop: Rectangle(0, StartHeight + Trunc(StepHeight * i) - 1, Width, StartHeight + Trunc(StepHeight * (i + 1))); LeftToRight, RightToLeft: Rectangle(StartWidth + Trunc(StepWidth * i) - 1, 0, StartWidth + Trunc(StepWidth * (i + 1)), Height); EdgesToCenter, CenterToEdges: Rectangle(StartWidth + Trunc(StepWidth * i) - 1, StartHeight + Trunc(StepHeight * i) - 1, Width - StartWidth - Trunc(StepWidth * i), Height - StartHeight - Trunc(StepHeight * i)); HCenterToEdges, EdgesToHCenter: begin Rectangle(0, StartHeight + Trunc(StepHeight * i) - 1, Width, StartHeight + Trunc(StepHeight * (i + 1))); Rectangle(0, Height - StartHeight - Trunc(StepHeight * i) + 1, Width, Height - StartHeight - Trunc(StepHeight * (i + 1))); end; VCenterToEdges, EdgesToVCenter: begin Rectangle(StartWidth + Trunc(StepWidth * i) - 1, 0, StartWidth + Trunc(StepWidth * (i + 1)), Height); Rectangle(Width - StartWidth - Trunc(StepWidth * i) + 1, 0, Width - StartWidth - Trunc(StepWidth * (i + 1)), Height); end; TopLeft: Rectangle(0, 0, Width - StartWidth - Trunc(StepWidth * i) + 1, Height - StartHeight - Trunc(StepHeight * i) + 1); BottomLeft: Rectangle(0, StartHeight + Trunc(StepHeight * i) - 1, Width - StartWidth - Trunc(StepWidth * i) + 1, Height); TopRight: Rectangle(StartWidth + Trunc(StepWidth * i) - 1, 0, Width, Height - StartHeight - Trunc(StepHeight * i) + 1); BottomRight: Rectangle(StartWidth + Trunc(StepWidth * i) - 1, StartHeight + Trunc(StepHeight * i) - 1, Width, Height); EllipticIn, EllipticOut: Ellipse(StartWidth + Trunc(StepWidth * i) - 1, StartHeight + Trunc(StepHeight * i) - 1, Width - StartWidth - Trunc(StepWidth * i), Height - StartHeight - Trunc(StepHeight * i)); end; end; end; with inherited Canvas do begin Pen.Style := psClear; Brush.Color := RGB(RedTo, GreenTo, BlueTo); case FDirection of TopToBottom, BottomToTop: Rectangle(0, StartHeight + Trunc(StepHeight * FCount) - 1, Width, EndHeight); LeftToRight, RightToLeft: Rectangle(StartWidth + Trunc(StepWidth * FCount) - 1, 0, EndWidth, Height); HCenterToEdges, EdgesToHCenter: begin Rectangle(0, StartHeight + Trunc(StepHeight * FCount) - 1, Width, EndHeight); Rectangle(0, EndHeight - 1, Width, Height - StartHeight - Trunc(StepHeight * (FCount - 1))); end; VCenterToEdges, EdgesToVCenter: begin Rectangle(StartWidth + Trunc(StepWidth * FCount) - 1, 0, EndWidth, Height); Rectangle(EndWidth - 1, 0, Width - StartWidth - Trunc(StepWidth * (FCount - 1)), Height); end; end; end; end; procedure TGradientPanel.SetPaintColorFrom(Value: TColor); begin if FColorFrom <> Value then begin FColorFrom := Value; Paint; end; end; procedure TGradientPanel.SetPaintColorTo(Value: TColor); begin if FColorTo <> Value then begin FColorTo := Value; Paint; end; end; procedure TGradientPanel.SetPaintCount(Value: TCountOfColor); begin if FCount <> Value then begin FCount := Value; Paint; end; end; procedure TGradientPanel.SetPaintDirection(Value: TDirection); begin if FDirection <> Value then begin FDirection := Value; Paint; end; end; procedure Register; begin RegisterComponents('cactus', [TGradientPanel]); end; end.
var x:integer; procedure TulisJawaban(x: integer); begin case x of 1..9: begin writeln('satuan'); end; 10..99: begin writeln('puluhan'); end; 100..999: begin writeln('ratusan'); end; 1000..9999: begin writeln('ribuan'); end; 10000..30000: begin writeln('puluhribuan'); end; end; end; begin while not eof do begin readln(x); TulisJawaban(x); end; end.
unit uClassProdutos; interface type TProduto = Class private FCodigo:Integer; FDescricao: String; FUnidMedida:String; procedure SetCodigo(const Value:Integer); procedure SetDescricao(const Value: String); procedure SetUnidMedida(const Value: String); public property Codigo:integer read FCodigo write SetCodigo; property Descricao:String read FDescricao write SetDescricao; property UnidMedida:String read FUnidMedida write SetUnidMedida; Procedure CarregaDados(); Procedure InsereDados(); Procedure ValidaDados(); end; implementation uses udmcadastro,Forms,SysUtils,Windows,DB; { TProduto } procedure TProduto.CarregaDados; begin //DMCadastro.cdsProdutos.Open; Codigo := DMCadastro.cdsProdutosCodigo.AsInteger; Descricao := DMCadastro.cdsProdutosDescricao.AsString; UnidMedida := DMCadastro.cdsProdutosUnidMedida.AsString; end; procedure TProduto.InsereDados; begin DMCadastro.cdsProdutosCodigo.AsInteger := Codigo; DMCadastro.cdsProdutosDescricao.AsString := Descricao; DMCadastro.cdsProdutosUnidMedida.AsString := UnidMedida; DMCadastro.cdsProdutos.Post; DMCadastro.cdsProdutos.ApplyUpdates(1); end; procedure TProduto.SetCodigo(const Value: Integer); begin if DMCadastro.cdsProdutos.State in [dsInsert] then Begin DMCadastro.sqlAux.Close; DMCadastro.sqlAux.SQL.Clear; DMCadastro.sqlAux.SQL.Add('select * from Produtos where codigo='+IntToStr(Value)); DMCadastro.sqlAux.Open; if Not DMCadastro.sqlAux.isEmpty then Begin Application.MessageBox('Codígo já Cadastrado','Erro',mb_IconError); Abort; End else FCodigo := value; End else FCodigo := value; end; procedure TProduto.SetDescricao(const Value: String); begin FDescricao := value; end; procedure TProduto.SetUnidMedida(const Value: String); begin FUnidMedida := Value; end; procedure TProduto.ValidaDados; begin If Codigo<=0 Then Begin Application.MessageBox('Campo Codígo é obrigatorio','Erro',mb_IconError); Abort; End; If trim(Descricao)='' Then Begin Application.MessageBox('Campo Descrição é obrigatorio','Erro',mb_IconError); Abort; End; If trim(UnidMedida)='' Then Begin Application.MessageBox('Campo Unidade de Medida é Obrigatorio','Erro',mb_IconError); Abort; End; end; end.
unit Cell; { ******************************************************************************** ******* XLSReadWriteII V1.14 ******* ******* ******* ******* Copyright(C) 1999,2002 Lars Arvidsson, Axolot Data ******* ******* ******* ******* email: components@axolot.com ******* ******* URL: http://www.axolot.com ******* ******************************************************************************** ** Users of the XLSReadWriteII component must accept the following ** ** disclaimer of warranty: ** ** ** ** XLSReadWriteII is supplied as is. The author disclaims all warranties, ** ** expressedor implied, including, without limitation, the warranties of ** ** merchantability and of fitness for any purpose. The author assumes no ** ** liability for damages, direct or consequential, which may result from the ** ** use of XLSReadWriteII. ** ******************************************************************************** } {$B-} interface uses SysUtils, BIFFRecsII; // ctNotUsed was erlier ctRK. type TCellType = (ctNone,ctBlank,ctNotUsed,ctInteger,ctFloat,ctString,ctBoolean,ctError,ctNumberFormula,ctStringFormula,ctBooleanFormula,ctErrorFormula,ctArrayFormula); const TNumCellType = [ctNotUsed,ctInteger,ctFloat,ctNumberFormula,ctArrayFormula]; type TCell = class(TObject) private protected FFormatIndex: integer; FRowCol: longword; public function CellType: TCellType; virtual; abstract; function MakeCopy: TCell; virtual; abstract; property RowCol: longword read FRowCol write FRowCol; property FormatIndex: integer read FFormatIndex write FFormatIndex; end; type TBlankCell = class(TCell) protected public constructor Create(RC,FI: integer); function CellType: TCellType; override; function MakeCopy: TCell; override; end; type TIntegerCell = class(TCell) private FValue: integer; protected public constructor Create(RC,FI: integer; Val: integer); function CellType: TCellType; override; function MakeCopy: TCell; override; property Value: integer read FValue write FValue; end; type TFloatCell = class(TCell) private FValue: double; protected public constructor Create(RC,FI: integer; Val: double); function CellType: TCellType; override; function MakeCopy: TCell; override; property Value: double read FValue write FValue; end; type TStringCell = class(TCell) private FValue: integer; protected public constructor Create(RC,FI: integer; Val: integer); function CellType: TCellType; override; function MakeCopy: TCell; override; property Value: integer read FValue write FValue; end; type TBooleanCell = class(TCell) private FValue: boolean; protected public constructor Create(RC,FI: integer; Val: boolean); function CellType: TCellType; override; function MakeCopy: TCell; override; property Value: boolean read FValue write FValue; end; type TErrorCell = class(TCell) private FValue: TCellError; protected public constructor Create(RC,FI: integer; Val: TCellError); function CellType: TCellType; override; function MakeCopy: TCell; override; property Value: TCellError read FValue write FValue; end; type TFormulaCell = class(TCell) private FPTGS: PByteArray; FSize: integer; protected public constructor Create(RC,FI: integer; Val: PByteArray; Size: integer); destructor Destroy; override; property PTGS: PByteArray read FPTGS; property Size: integer read FSize; end; type TNumberFormulaCell = class(TFormulaCell) private FNumberValue: double; public function CellType: TCellType; override; function MakeCopy: TCell; override; property NumberValue: double read FNumberValue write FNumberValue; end; type TStringFormulaCell = class(TFormulaCell) private FStringValue: string; public function CellType: TCellType; override; function MakeCopy: TCell; override; property StringValue: string read FStringValue write FStringValue; end; type TBooleanFormulaCell = class(TFormulaCell) private FBooleanValue: boolean; public function CellType: TCellType; override; function MakeCopy: TCell; override; property BooleanValue: boolean read FBooleanValue write FBooleanValue; end; type TErrorFormulaCell = class(TFormulaCell) private FErrorValue: TCellError; public function CellType: TCellType; override; function MakeCopy: TCell; override; property ErrorValue: TCellError read FErrorValue write FErrorValue; end; type TArrayFormulaCell = class(TFormulaCell) private FNumberValue: double; FArray: PByteArray; FArraySize: integer; public constructor Create(RC,FI: integer; Val: PByteArray; Size: integer; Arr: PByteArray; ArrSize: integer); destructor Destroy; override; function CellType: TCellType; override; function MakeCopy: TCell; override; property NumberValue: double read FNumberValue write FNumberValue; property ArrayData: PByteArray read FArray; property ArraySize: integer read FArraySize; end; implementation { TBlankCell } constructor TBlankCell.Create(RC,FI: integer); begin RowCol := RC; FFormatIndex := FI; end; function TBlankCell.CellType: TCellType; begin Result := ctBlank; end; function TBlankCell.MakeCopy: TCell; begin Result := TBlankCell.Create(FRowCol,FFormatIndex); end; { TIntegerCell } constructor TIntegerCell.Create(RC,FI: integer; Val: integer); begin RowCol := RC; FFormatIndex := FI; FValue := Val; end; function TIntegerCell.CellType: TCellType; begin Result := ctInteger; end; function TIntegerCell.MakeCopy: TCell; begin Result := TIntegerCell.Create(FRowCol,FFormatIndex,FValue); end; { TFloatCell } constructor TFloatCell.Create(RC,FI: integer; Val: double); begin RowCol := RC; FFormatIndex := FI; FValue := Val; end; function TFloatCell.CellType: TCellType; begin Result := ctFloat; end; function TFloatCell.MakeCopy: TCell; begin Result := TFloatCell.Create(FRowCol,FFormatIndex,FValue); end; { TStringCell } constructor TStringCell.Create(RC,FI: integer; Val: integer); begin RowCol := RC; FFormatIndex := FI; FValue := Val; end; function TStringCell.CellType: TCellType; begin Result := ctString; end; function TStringCell.MakeCopy: TCell; begin Result := TStringCell.Create(FRowCol,FFormatIndex,FValue); end; { TBooleanCell } constructor TBooleanCell.Create(RC,FI: integer; Val: boolean); begin RowCol := RC; FFormatIndex := FI; FValue := Val; end; function TBooleanCell.CellType: TCellType; begin Result := ctBoolean; end; function TBooleanCell.MakeCopy: TCell; begin Result := TBooleanCell.Create(FRowCol,FFormatIndex,FValue); end; { TErrorCell } constructor TErrorCell.Create(RC,FI: integer; Val: TCellError); begin RowCol := RC; FFormatIndex := FI; FValue := Val; end; function TErrorCell.CellType: TCellType; begin Result := ctError; end; function TErrorCell.MakeCopy: TCell; begin Result := TErrorCell.Create(FRowCol,FFormatIndex,FValue); end; { TFormulaCell } constructor TFormulaCell.Create(RC,FI: integer; Val: PByteArray; Size: integer); begin RowCol := RC; FFormatIndex := FI; FSize := Size; GetMem(FPTGS,FSize); Move(Val^,FPTGS^,FSize); end; destructor TFormulaCell.Destroy; begin if FPTGS <> Nil then FreeMem(FPTGS); inherited; end; function TNumberFormulaCell.CellType: TCellType; begin Result := ctNumberFormula; end; function TNumberFormulaCell.MakeCopy: TCell; begin Result := TNumberFormulaCell.Create(FRowCol,FFormatIndex,FPTGS,FSize); end; function TStringFormulaCell.CellType: TCellType; begin Result := ctStringFormula; end; function TStringFormulaCell.MakeCopy: TCell; begin Result := TStringFormulaCell.Create(FRowCol,FFormatIndex,FPTGS,FSize); end; function TBooleanFormulaCell.CellType: TCellType; begin Result := ctBooleanFormula; end; function TBooleanFormulaCell.MakeCopy: TCell; begin Result := TBooleanFormulaCell.Create(FRowCol,FFormatIndex,FPTGS,FSize); end; { TErrorFormulaCell } function TErrorFormulaCell.CellType: TCellType; begin Result := ctErrorFormula; end; function TErrorFormulaCell.MakeCopy: TCell; begin Result := TErrorFormulaCell.Create(FRowCol,FFormatIndex,FPTGS,FSize); end; { TArrayFormulaCell } constructor TArrayFormulaCell.Create(RC, FI: integer; Val: PByteArray; Size: integer; Arr: PByteArray; ArrSize: integer); begin inherited Create(RC,FI,Val,Size); FArraySize := ArrSize; GetMem(FArray,ArrSize); Move(Arr^,FArray^,ArrSize); end; destructor TArrayFormulaCell.Destroy; begin FreeMem(FArray); inherited; end; function TArrayFormulaCell.CellType: TCellType; begin Result := ctArrayFormula; end; function TArrayFormulaCell.MakeCopy: TCell; begin Result := TArrayFormulaCell.Create(FRowCol,FFormatIndex,FPTGS,FSize,FArray,FArraySize); end; end.
unit HTTPRequest; interface uses HTTPURI; type IHTTPRequest = interface ['{13CF42F3-0760-4C0F-B387-B5E7CA0C6AEB}'] function URI: IURI; function Body: String; end; THTTPRequest = class sealed(TInterfacedObject, IHTTPRequest) strict private _URI: IURI; _Body: String; public function URI: IURI; function Body: String; constructor Create(const URI: IURI; const Body: String); class function New(const URI: IURI; const Body: String): IHTTPRequest; end; implementation function THTTPRequest.URI: IURI; begin Result := _URI; end; function THTTPRequest.Body: String; begin Result := _Body; end; constructor THTTPRequest.Create(const URI: IURI; const Body: String); begin _URI := URI; _Body := Body; end; class function THTTPRequest.New(const URI: IURI; const Body: String): IHTTPRequest; begin Result := THTTPRequest.Create(URI, Body); end; end.
{ ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(ORMBr Framework.) @created(12 Out 2016) @author(Isaque Pinheiro <isaquepsp@gmail.com>) @author(Skype : ispinheiro) ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi. } unit dbcbr.ddl.interfaces; interface uses dbcbr.database.mapping; type TSupportedFeature = (Sequences, ForeignKeys, Checks, Views, Triggers); TSupportedFeatures = set of TSupportedFeature; /// <summary> /// Class unit : dbcbr.ddl.generator.pas /// Class Name : TDDLSQLGeneratorAbstract /// </summary> IDDLGeneratorCommand = interface ['{9E14DD57-94B9-4117-982A-BB9E8CBA54C6}'] function GenerateCreateTable(ATable: TTableMIK): string; function GenerateCreatePrimaryKey(APrimaryKey: TPrimaryKeyMIK): string; function GenerateCreateForeignKey(AForeignKey: TForeignKeyMIK): string; function GenerateCreateSequence(ASequence: TSequenceMIK): string; function GenerateCreateIndexe(AIndexe: TIndexeKeyMIK): string; function GenerateCreateCheck(ACheck: TCheckMIK): string; function GenerateCreateView(AView: TViewMIK): string; function GenerateCreateTrigger(ATrigger: TTriggerMIK): string; function GenerateCreateColumn(AColumn: TColumnMIK): string; function GenerateAlterColumn(AColumn: TColumnMIK): string; function GenerateAlterDefaultValue(AColumn: TColumnMIK): string; function GenerateAlterCheck(ACheck: TCheckMIK): string; function GenerateDropTable(ATable: TTableMIK): string; function GenerateDropPrimaryKey(APrimaryKey: TPrimaryKeyMIK): string; function GenerateDropForeignKey(AForeignKey: TForeignKeyMIK): string; function GenerateDropSequence(ASequence: TSequenceMIK): string; function GenerateDropIndexe(AIndexe: TIndexeKeyMIK): string; function GenerateDropCheck(ACheck: TCheckMIK): string; function GenerateDropView(AView: TViewMIK): string; function GenerateDropTrigger(ATrigger: TTriggerMIK): string; function GenerateDropColumn(AColumn: TColumnMIK): string; function GenerateDropDefaultValue(AColumn: TColumnMIK): string; function GenerateEnableForeignKeys(AEnable: Boolean): string; function GenerateEnableTriggers(AEnable: Boolean): string; /// <summary> /// Propriedade para identificar os recursos de diferentes banco de dados /// usando o mesmo modelo. /// </summary> function GetSupportedFeatures: TSupportedFeatures; property SupportedFeatures: TSupportedFeatures read GetSupportedFeatures; end; implementation end.
unit MyViews; ///////////////////////////////////////////////////////////////////// // // Hi-Files Version 2 // Copyright (c) 1997-2004 Dmitry Liman [2:461/79] // // http://hi-files.narod.ru // ///////////////////////////////////////////////////////////////////// interface uses Objects, Views, Dialogs, Drivers; type LBFlag = (lb_multisel, lb_reorder, lb_speedsearch); LBMode = set of LBFlag; type PMyListBox = ^TMyListBox; TMyListBox = object (TListBox) Reordered: Boolean; Mode : LBMode; constructor Init( var R: TRect; ANumCols: Integer; ScrollBar: PScrollBar ); procedure SetMode( AMode: LBMode ); function GetSearchStr( Item: Integer ) : String; virtual; procedure HandleEvent( var Event: TEvent ); virtual; procedure Draw; virtual; procedure FocusItem( Item: Integer ); virtual; procedure SelectItem( Item: Integer ); virtual; procedure TagItem( Item: Integer; Tag: Boolean ); virtual; function ItemTagged( Item: Integer ) : Boolean; virtual; function GetTagCount: Integer; function SelectedItem: Pointer; procedure DragItemUp; virtual; procedure DragItemDn; virtual; function DataSize: Integer; virtual; procedure GetData( var Data ); virtual; procedure SetData( var Data ); virtual; private SearchPos: Integer; Focusing : Boolean; end; { TMyListBox } PStrListEditor = ^TStrListEditor; TStrListEditor = object (TDialog) InputLine: PInputLine; ListBox : PMyListBox; procedure SetupDialog( const Caption: String; List: PCollection ); procedure HandleEvent( var Event: TEvent ); virtual; end; { TStrListEditor } PInfoPane = ^TInfoPane; TInfoPane = object (TParamText) function GetPalette: PPalette; virtual; end; { TInfoPane } type ShortStr = String[20]; LongStr = String[128]; const cmDragItemUp = 100; cmDragItemDn = 101; cmTagAll = 102; cmUntagAll = 103; cmInsItem = 104; cmDelItem = 105; cmChgItem = 106; cmAppItem = 107; cmFocusMoved = 110; cmFocusLeave = 111; cmEnter = 270; cmOptions = 271; cmImport = 272; { =================================================================== } implementation uses SysUtils, MyLib, _Res; { --------------------------------------------------------- } { TMyListBox } { --------------------------------------------------------- } { Init ---------------------------------------------------- } constructor TMyListBox.Init( var R: TRect; ANumCols: Integer; ScrollBar: PScrollBar ); begin inherited Init(R, ANumCols, ScrollBar); SetMode([lb_speedsearch]); end; { Init } { SetMode ------------------------------------------------- } procedure TMyListBox.SetMode( AMode: LBMode ); begin Mode := AMode; if lb_speedsearch in Mode then begin ShowCursor; SetCursor(1, 0); end else HideCursor; end; { SetMode } { GetSearchStr -------------------------------------------- } function TMyListBox.GetSearchStr( Item: Integer ) : String; begin Result := GetText( Item, Size.X ); end; { GetSearchStr } { HandleEvent --------------------------------------------- } procedure TMyListBox.HandleEvent( var Event: TEvent ); var j: Integer; SearchStr: String; OldFocus : Integer; procedure EventCommand( Command: Word ); begin Event.What := evCommand; Event.Command := Command; end; { EventCommand } function FirstMatch( var Index: Integer ) : Boolean; var j: Integer; S: String; begin for j := 0 to List^.Count - 1 do begin S := Copy( GetSearchStr( j ), 1, SearchPos ); if JustSameText( S, SearchStr ) then begin Index := j; Result := True; Exit; end; end; Result := False; end; { FirstMatch } procedure TagAll( Tag: Boolean ); var j: Integer; begin if lb_multisel in Mode then begin for j := 0 to Pred(Range) do TagItem( j, Tag ); DrawView; end; end; { TagAll } begin case Event.What of evKeyDown: begin if (GetShiftState and (kbLeftShift or kbRightShift)) <> 0 then begin case Event.KeyCode of kbUp : EventCommand( cmDragItemUp ); kbDown: EventCommand( cmDragItemDn ); end; end else case Event.KeyCode of kbGrayMinus: EventCommand( cmUntagAll ); kbGrayPlus : EventCommand( cmTagAll ); kbIns : EventCommand( cmInsItem ); kbDel : EventCommand( cmDelItem ); end; end; end; OldFocus := Focused; inherited HandleEvent( Event ); if OldFocus <> Focused then SearchPos := 0; if Focused >= Range then Exit; case Event.What of evCommand: begin case Event.Command of cmDragItemUp: DragItemUp; cmDragItemDn: DragItemDn; cmTagAll : TagAll( True ); cmUntagAll : TagAll( False ); else Exit; end; ClearEvent( Event ); end; evKeyDown: begin if (lb_speedsearch in Mode) and (Event.KeyCode <> kbEnter ) and (Event.KeyCode <> kbEsc) and (Event.KeyCode <> kbTab) and (Event.KeyCode <> kbShiftTab) and (Event.CharCode <> #0) then begin SearchStr := Copy( GetSearchStr(Focused), 1, SearchPos ); if (Event.KeyCode = kbBack) and (SearchPos > 0) then begin Dec( SearchPos ); Dec( SearchStr[0] ); FirstMatch( j ); FocusItem( j ); end else begin Inc( SearchPos ); SearchStr[ SearchPos ] := Event.CharCode; SearchStr[0] := Chr( SearchPos ); if FirstMatch( j ) then FocusItem( j ) else Dec( SearchPos ); end; SetCursor( SearchPos+1, Cursor.Y ); ClearEvent( Event ); end; end; end; end; { HandleEvent } { Draw ---------------------------------------------------- } procedure TMyListBox.Draw; const TAG_CHAR = ' '; // Disabled tag char var I, J, Item: Integer; NormalColor, SelectedColor, FocusedColor, Color: Word; ColWidth, CurCol, Indent: Integer; B: TDrawBuffer; Text: String; begin if State and (sfSelected + sfActive) = (sfSelected + sfActive) then begin NormalColor := GetColor(1); FocusedColor := GetColor(3); end else NormalColor := GetColor(2); SelectedColor := GetColor(4); if HScrollBar <> nil then Indent := HScrollBar^.Value else Indent := 0; ColWidth := Size.X div NumCols + 1; for I := 0 to Size.Y - 1 do begin for J := 0 to NumCols-1 do begin Item := J*Size.Y + I + TopItem; CurCol := J*ColWidth; if (State and (sfSelected + sfActive) = (sfSelected + sfActive)) and (Focused = Item) and (Range > 0) then begin Color := FocusedColor; SetCursor(CurCol+1,I); end else if Item < Range then begin if (lb_multisel in Mode) and ItemTagged(Item) or not (lb_multisel in Mode) and IsSelected(Item) then Color := SelectedColor else Color := NormalColor end else Color := NormalColor; MoveChar(B[CurCol], ' ', Color, ColWidth); if Item < Range then begin Text := GetText(Item, ColWidth + Indent); Text := Copy(Text,Indent,ColWidth); MoveStr(B[CurCol+1], Text, Color); if ItemTagged( Item ) then begin WordRec(B[CurCol]).Lo := Byte( TAG_CHAR ); WordRec(B[CurCol+ColWidth-2]).Lo := Byte( TAG_CHAR ); end; end; MoveChar(B[CurCol+ColWidth-1], #179, GetColor(5), 1); end; WriteLine(0, I, Size.X, 1, B); end; end; { Draw } { FocusItem ----------------------------------------------- } procedure TMyListBox.FocusItem( Item: Integer ); begin if not Focusing then begin Focusing := True; Message( Owner, evBroadcast, cmFocusLeave, Pointer(Focused) ); inherited FocusItem( Item ); Message( Owner, evBroadcast, cmFocusMoved, Pointer(Item) ); Focusing := False; DrawView; end; end; { FocusItem } { SelectItem ---------------------------------------------- } procedure TMyListBox.SelectItem( Item: Integer ); begin if lb_multisel in Mode then begin TagItem( Item, not ItemTagged(Item) ); if Item < Pred(Range) then FocusItem( Succ(Item) ) else DrawView; end else inherited SelectItem(Item); end; { SelectItem } { TagItem ------------------------------------------------- } procedure TMyListBox.TagItem( Item: Integer; Tag: Boolean ); begin end; { TagItem } { ItemTagged ---------------------------------------------- } function TMyListBox.ItemTagged( Item: Integer ) : Boolean; begin Result := False; end; { ItemTagged } { GetTagCount --------------------------------------------- } function TMyListBox.GetTagCount: Integer; var j: Integer; begin Result := 0; for j := Pred(List^.Count) downto 0 do if ItemTagged(j) then Inc(Result); end; { GetTagCount } { SelectedItem -------------------------------------------- } function TMyListBox.SelectedItem: Pointer; begin if Range = 0 then Result := nil else Result := List^.At(Focused); end; { SelectedItem } { DragItemUp ---------------------------------------------- } procedure TMyListBox.DragItemUp; var p: Pointer; begin if lb_reorder in Mode then begin p := SelectedItem; if (p = nil) or (Focused = 0) then Exit; List^.AtDelete( Focused ); List^.AtInsert( Pred(Focused), p ); FocusItem( Pred(Focused) ); Reordered := True; end; end; { DragItemUp } { DragItemDn ---------------------------------------------- } procedure TMyListBox.DragItemDn; var p: Pointer; begin if lb_reorder in Mode then begin p := SelectedItem; if (p = nil) or (Focused = Pred(Range)) then Exit; List^.AtDelete( Focused ); List^.AtInsert( Succ(Focused), p ); FocusItem( Succ(Focused) ); Reordered := True; end; end; { DragItemDn } { DataSize ------------------------------------------------ } function TMyListBox.DataSize: Integer; begin Result := 0; end; { DataSize } { GetData ------------------------------------------------- } procedure TMyListBox.SetData( var Data ); begin end; { SetData } { GetData ------------------------------------------------- } procedure TMyListBox.GetData( var Data ); begin end; { GetData } { --------------------------------------------------------- } { TStrListEditor } { --------------------------------------------------------- } { SetupDialog --------------------------------------------- } procedure TStrListEditor.SetupDialog( const Caption: String; List: PCollection ); var R: TRect; begin R.Assign( 0, 0, 0, 0 ); ListBox := PMyListBox( ShoeHorn( @Self, New( PMyListBox, Init(R, 1, nil) ))); ListBox^.SetMode([lb_speedsearch, lb_reorder]); InputLine := PInputLine( ShoeHorn( @Self, New( PInputLine, Init(R, Pred(SizeOf(LongStr)))))); ListBox^.NewList( List ); ReplaceStr( Title, Caption ); end; { SetupDialog } { HandleEvent --------------------------------------------- } procedure TStrListEditor.HandleEvent( var Event: TEvent ); var S: LongStr; procedure AppendItem; begin with ListBox^, List^ do begin AtInsert( Range, AllocStr(S) ); SetRange( Succ(Range) ); FocusItem( Pred(Range) ); end; end; { AppendItem } procedure ChangeItem; begin with ListBox^, List^ do begin if Range > 0 then begin AtFree( Focused ); AtInsert( Focused, AllocStr(S) ); FocusItem( Focused ); end else AppendItem; end; end; { ChangeItem } procedure InsertItem; begin with ListBox^, List^ do begin AtInsert( Focused, AllocStr('') ); SetRange( Succ(Range) ); FocusItem( Focused ); end; end; { InsertItem } procedure DeleteItem; begin with ListBox^, List^ do begin if Range = 0 then Exit; AtFree(Focused); SetRange(Pred(Range)); FocusItem(Focused); end; end; { DeleteItem } procedure FocusMoved; var p: PString; begin p := ListBox^.SelectedItem; if p <> nil then S := p^ else S := ''; InputLine^.SetData( S ); end; { FocusMoved } begin inherited HandleEvent( Event ); case Event.What of evCommand: begin InputLine^.GetData( S ); case Event.Command of cmChgItem: ChangeItem; cmInsItem: InsertItem; cmDelItem: DeleteItem; cmAppItem: AppendItem; else Exit; end; ClearEvent( Event ); end; evBroadcast: case Event.Command of cmFocusMoved: FocusMoved; end; end; end; { HandleEvent } { --------------------------------------------------------- } { TInfoPane } { --------------------------------------------------------- } { GetPalette ---------------------------------------------- } function TInfoPane.GetPalette: PPalette; const CInfoPane = #30; P: String[Length(CInfoPane)] = CInfoPane; begin Result := @P; end; { GetPalette } end.
unit CRepWellListFrame; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Well, ComCtrls, JvExComCtrls, JvListView, StdCtrls, JvExStdCtrls, JvGroupBox; type TfrmWellList = class(TFrame) gbxWells: TJvGroupBox; lvWells: TJvListView; private FSelectedWells: TSimpleWells; function GetSeletedWells: TSimpleWells; function GetSelectedWell: TSimpleWell; { Private declarations } public { Public declarations } property SelectedWells: TSimpleWells read GetSeletedWells; property SelectedWell: TSimpleWell read GetSelectedWell; procedure ReloadWells(); destructor Destroy; override; end; implementation {$R *.dfm} uses Facade, SDFacade, BaseObjects; { TfrmWellList } destructor TfrmWellList.Destroy; begin FreeAndNil(FSelectedWells); inherited; end; function TfrmWellList.GetSelectedWell: TSimpleWell; begin if Assigned(lvWells.Selected) then Result := TSimpleWell(lvWells.Selected.Data) else Result := nil; end; function TfrmWellList.GetSeletedWells: TSimpleWells; var i: integer; begin if not Assigned(FSelectedWells) then begin FSelectedWells := TSimpleWells.Create; FSelectedWells.OwnsObjects := false; FSelectedWells.Poster := nil; end else FSelectedWells.Clear; for i := 0 to lvWells.Items.Count - 1 do if lvWells.Items[i].Selected then FSelectedWells.Add(TSimpleWell(lvWells.Items[i].Data), False, True); Result := FSelectedWells; end; procedure TfrmWellList.ReloadWells; var i: integer; li: TListItem; lg: TJvListViewGroup; begin lvWells.Items.Clear; with TMainFacade.GetInstance.AllWells do for i := 0 to Count - 1 do begin li := lvWells.Items.Add; li.Caption := Items[i].Area.Name; li.SubItems.Add(Items[i].NumberWell); li.Data := Items[i]; end; end; end.
unit MsgList; interface uses Winapi.Windows, System.Classes, System.SysUtils; type TMsgItem = class; TMsgList = class; TStringArray = array of String; TMsgItem = class(TPersistent) private FOwner: TMsgList; FMsg: String; procedure SetMsg(const Value: String); public constructor Create(AOwner: TMsgList); destructor Destroy; override; published property Msg: String read FMsg write SetMsg; end; TMsgList = class(TPersistent) private FItems: TList; function GetItem(Index: Integer): TMsgItem; procedure SetItem(Index: Integer; const Value: TMsgItem); public constructor Create; destructor Destroy; override; function Add(const Msg: String = ''): TMsgItem; function Count: Integer; procedure Clear; procedure Delete(const Index: Integer); function RandomMsg(const Params: TStringArray = nil): String; property Items[Index: Integer]: TMsgItem read GetItem write SetItem; default; end; implementation { TMsgItem } constructor TMsgItem.Create(AOwner: TMsgList); begin FOwner:= AOwner; end; destructor TMsgItem.Destroy; begin inherited; end; procedure TMsgItem.SetMsg(const Value: String); begin FMsg := Value; end; { TMsgList } constructor TMsgList.Create; begin FItems:= TList.Create; end; destructor TMsgList.Destroy; begin Clear; FItems.Free; inherited; end; function TMsgList.GetItem(Index: Integer): TMsgItem; begin Result:= TMsgItem(FItems[Index]); end; function TMsgList.RandomMsg(const Params: TStringArray = nil): String; var T: TMsgItem; C, X: Integer; S, N, V: String; begin Randomize; C:= Count; X:= Random(C); T:= Items[X]; Result:= T.Msg; for X:= 0 to Length(Params)-1 do begin S:= Params[X]; N:= Copy(S, 1, Pos(':', S)-1); System.Delete(S, 1, Pos(':', S)); V:= S; Result:= StringReplace(Result, '['+N+']', V, [rfReplaceAll]); end; end; procedure TMsgList.SetItem(Index: Integer; const Value: TMsgItem); begin TMsgItem(FItems[Index]).Assign(Value); end; function TMsgList.Add(const Msg: String = ''): TMsgItem; begin Result:= TMsgItem.Create(Self); FItems.Add(Result); Result.Msg:= Msg; end; procedure TMsgList.Clear; begin while Count > 0 do Delete(0); end; function TMsgList.Count: Integer; begin Result:= FItems.Count; end; procedure TMsgList.Delete(const Index: Integer); begin TMsgItem(FItems[Index]).Free; FItems.Delete(Index); end; end.
unit PublicKey; interface type HCkByteData = Pointer; HCkPublicKey = Pointer; HCkString = Pointer; function CkPublicKey_Create: HCkPublicKey; stdcall; procedure CkPublicKey_Dispose(handle: HCkPublicKey); stdcall; procedure CkPublicKey_getDebugLogFilePath(objHandle: HCkPublicKey; outPropVal: HCkString); stdcall; procedure CkPublicKey_putDebugLogFilePath(objHandle: HCkPublicKey; newPropVal: PWideChar); stdcall; function CkPublicKey__debugLogFilePath(objHandle: HCkPublicKey): PWideChar; stdcall; function CkPublicKey_getKeySize(objHandle: HCkPublicKey): Integer; stdcall; procedure CkPublicKey_getKeyType(objHandle: HCkPublicKey; outPropVal: HCkString); stdcall; function CkPublicKey__keyType(objHandle: HCkPublicKey): PWideChar; stdcall; procedure CkPublicKey_getLastErrorHtml(objHandle: HCkPublicKey; outPropVal: HCkString); stdcall; function CkPublicKey__lastErrorHtml(objHandle: HCkPublicKey): PWideChar; stdcall; procedure CkPublicKey_getLastErrorText(objHandle: HCkPublicKey; outPropVal: HCkString); stdcall; function CkPublicKey__lastErrorText(objHandle: HCkPublicKey): PWideChar; stdcall; procedure CkPublicKey_getLastErrorXml(objHandle: HCkPublicKey; outPropVal: HCkString); stdcall; function CkPublicKey__lastErrorXml(objHandle: HCkPublicKey): PWideChar; stdcall; function CkPublicKey_getLastMethodSuccess(objHandle: HCkPublicKey): wordbool; stdcall; procedure CkPublicKey_putLastMethodSuccess(objHandle: HCkPublicKey; newPropVal: wordbool); stdcall; function CkPublicKey_getVerboseLogging(objHandle: HCkPublicKey): wordbool; stdcall; procedure CkPublicKey_putVerboseLogging(objHandle: HCkPublicKey; newPropVal: wordbool); stdcall; procedure CkPublicKey_getVersion(objHandle: HCkPublicKey; outPropVal: HCkString); stdcall; function CkPublicKey__version(objHandle: HCkPublicKey): PWideChar; stdcall; function CkPublicKey_GetDer(objHandle: HCkPublicKey; preferPkcs1: wordbool; outData: HCkByteData): wordbool; stdcall; function CkPublicKey_GetEncoded(objHandle: HCkPublicKey; preferPkcs1: wordbool; encoding: PWideChar; outStr: HCkString): wordbool; stdcall; function CkPublicKey__getEncoded(objHandle: HCkPublicKey; preferPkcs1: wordbool; encoding: PWideChar): PWideChar; stdcall; function CkPublicKey_GetJwk(objHandle: HCkPublicKey; outStr: HCkString): wordbool; stdcall; function CkPublicKey__getJwk(objHandle: HCkPublicKey): PWideChar; stdcall; function CkPublicKey_GetJwkThumbprint(objHandle: HCkPublicKey; hashAlg: PWideChar; outStr: HCkString): wordbool; stdcall; function CkPublicKey__getJwkThumbprint(objHandle: HCkPublicKey; hashAlg: PWideChar): PWideChar; stdcall; function CkPublicKey_GetOpenSslDer(objHandle: HCkPublicKey; outData: HCkByteData): wordbool; stdcall; function CkPublicKey_GetOpenSslPem(objHandle: HCkPublicKey; outStr: HCkString): wordbool; stdcall; function CkPublicKey__getOpenSslPem(objHandle: HCkPublicKey): PWideChar; stdcall; function CkPublicKey_GetPem(objHandle: HCkPublicKey; preferPkcs1: wordbool; outStr: HCkString): wordbool; stdcall; function CkPublicKey__getPem(objHandle: HCkPublicKey; preferPkcs1: wordbool): PWideChar; stdcall; function CkPublicKey_GetPkcs1ENC(objHandle: HCkPublicKey; encoding: PWideChar; outStr: HCkString): wordbool; stdcall; function CkPublicKey__getPkcs1ENC(objHandle: HCkPublicKey; encoding: PWideChar): PWideChar; stdcall; function CkPublicKey_GetPkcs8ENC(objHandle: HCkPublicKey; encoding: PWideChar; outStr: HCkString): wordbool; stdcall; function CkPublicKey__getPkcs8ENC(objHandle: HCkPublicKey; encoding: PWideChar): PWideChar; stdcall; function CkPublicKey_GetRsaDer(objHandle: HCkPublicKey; outData: HCkByteData): wordbool; stdcall; function CkPublicKey_GetXml(objHandle: HCkPublicKey; outStr: HCkString): wordbool; stdcall; function CkPublicKey__getXml(objHandle: HCkPublicKey): PWideChar; stdcall; function CkPublicKey_LoadBase64(objHandle: HCkPublicKey; keyStr: PWideChar): wordbool; stdcall; function CkPublicKey_LoadFromBinary(objHandle: HCkPublicKey; keyBytes: HCkByteData): wordbool; stdcall; function CkPublicKey_LoadFromFile(objHandle: HCkPublicKey; path: PWideChar): wordbool; stdcall; function CkPublicKey_LoadFromString(objHandle: HCkPublicKey; keyString: PWideChar): wordbool; stdcall; function CkPublicKey_LoadOpenSslDer(objHandle: HCkPublicKey; data: HCkByteData): wordbool; stdcall; function CkPublicKey_LoadOpenSslDerFile(objHandle: HCkPublicKey; path: PWideChar): wordbool; stdcall; function CkPublicKey_LoadOpenSslPem(objHandle: HCkPublicKey; str: PWideChar): wordbool; stdcall; function CkPublicKey_LoadOpenSslPemFile(objHandle: HCkPublicKey; path: PWideChar): wordbool; stdcall; function CkPublicKey_LoadPkcs1Pem(objHandle: HCkPublicKey; str: PWideChar): wordbool; stdcall; function CkPublicKey_LoadRsaDer(objHandle: HCkPublicKey; data: HCkByteData): wordbool; stdcall; function CkPublicKey_LoadRsaDerFile(objHandle: HCkPublicKey; path: PWideChar): wordbool; stdcall; function CkPublicKey_LoadXml(objHandle: HCkPublicKey; xml: PWideChar): wordbool; stdcall; function CkPublicKey_LoadXmlFile(objHandle: HCkPublicKey; path: PWideChar): wordbool; stdcall; function CkPublicKey_SaveDerFile(objHandle: HCkPublicKey; preferPkcs1: wordbool; path: PWideChar): wordbool; stdcall; function CkPublicKey_SaveLastError(objHandle: HCkPublicKey; path: PWideChar): wordbool; stdcall; function CkPublicKey_SaveOpenSslDerFile(objHandle: HCkPublicKey; path: PWideChar): wordbool; stdcall; function CkPublicKey_SaveOpenSslPemFile(objHandle: HCkPublicKey; path: PWideChar): wordbool; stdcall; function CkPublicKey_SavePemFile(objHandle: HCkPublicKey; preferPkcs1: wordbool; path: PWideChar): wordbool; stdcall; function CkPublicKey_SaveRsaDerFile(objHandle: HCkPublicKey; path: PWideChar): wordbool; stdcall; function CkPublicKey_SaveXmlFile(objHandle: HCkPublicKey; path: PWideChar): wordbool; stdcall; implementation {$Include chilkatDllPath.inc} function CkPublicKey_Create; external DLLName; procedure CkPublicKey_Dispose; external DLLName; procedure CkPublicKey_getDebugLogFilePath; external DLLName; procedure CkPublicKey_putDebugLogFilePath; external DLLName; function CkPublicKey__debugLogFilePath; external DLLName; function CkPublicKey_getKeySize; external DLLName; procedure CkPublicKey_getKeyType; external DLLName; function CkPublicKey__keyType; external DLLName; procedure CkPublicKey_getLastErrorHtml; external DLLName; function CkPublicKey__lastErrorHtml; external DLLName; procedure CkPublicKey_getLastErrorText; external DLLName; function CkPublicKey__lastErrorText; external DLLName; procedure CkPublicKey_getLastErrorXml; external DLLName; function CkPublicKey__lastErrorXml; external DLLName; function CkPublicKey_getLastMethodSuccess; external DLLName; procedure CkPublicKey_putLastMethodSuccess; external DLLName; function CkPublicKey_getVerboseLogging; external DLLName; procedure CkPublicKey_putVerboseLogging; external DLLName; procedure CkPublicKey_getVersion; external DLLName; function CkPublicKey__version; external DLLName; function CkPublicKey_GetDer; external DLLName; function CkPublicKey_GetEncoded; external DLLName; function CkPublicKey__getEncoded; external DLLName; function CkPublicKey_GetJwk; external DLLName; function CkPublicKey__getJwk; external DLLName; function CkPublicKey_GetJwkThumbprint; external DLLName; function CkPublicKey__getJwkThumbprint; external DLLName; function CkPublicKey_GetOpenSslDer; external DLLName; function CkPublicKey_GetOpenSslPem; external DLLName; function CkPublicKey__getOpenSslPem; external DLLName; function CkPublicKey_GetPem; external DLLName; function CkPublicKey__getPem; external DLLName; function CkPublicKey_GetPkcs1ENC; external DLLName; function CkPublicKey__getPkcs1ENC; external DLLName; function CkPublicKey_GetPkcs8ENC; external DLLName; function CkPublicKey__getPkcs8ENC; external DLLName; function CkPublicKey_GetRsaDer; external DLLName; function CkPublicKey_GetXml; external DLLName; function CkPublicKey__getXml; external DLLName; function CkPublicKey_LoadBase64; external DLLName; function CkPublicKey_LoadFromBinary; external DLLName; function CkPublicKey_LoadFromFile; external DLLName; function CkPublicKey_LoadFromString; external DLLName; function CkPublicKey_LoadOpenSslDer; external DLLName; function CkPublicKey_LoadOpenSslDerFile; external DLLName; function CkPublicKey_LoadOpenSslPem; external DLLName; function CkPublicKey_LoadOpenSslPemFile; external DLLName; function CkPublicKey_LoadPkcs1Pem; external DLLName; function CkPublicKey_LoadRsaDer; external DLLName; function CkPublicKey_LoadRsaDerFile; external DLLName; function CkPublicKey_LoadXml; external DLLName; function CkPublicKey_LoadXmlFile; external DLLName; function CkPublicKey_SaveDerFile; external DLLName; function CkPublicKey_SaveLastError; external DLLName; function CkPublicKey_SaveOpenSslDerFile; external DLLName; function CkPublicKey_SaveOpenSslPemFile; external DLLName; function CkPublicKey_SavePemFile; external DLLName; function CkPublicKey_SaveRsaDerFile; external DLLName; function CkPublicKey_SaveXmlFile; external DLLName; end.
{ //************************************************************// } { // Projeto MVCBr // } { // tireideletra.com.br / amarildo lacerda // } { //************************************************************// } { // Data: 03/03/2017 // } { //************************************************************// } unit MVC.oData.Base; interface uses System.Classes, System.SysUtils, MVCFramework, MVCFramework.Commons, Data.Db, oData.Interf, oData.Dialect, System.JSON; type [MVCPath('/OData')] [MVCDoc('Implements OData protocol')] TODataController = class(TMVCController) public function CreateJson(CTX: TWebContext; const AValue: string): TJsonObject; // [MVCDoc('Finalize JSON response')] procedure EndsJson(var AJson: TJsonObject); // [MVCDoc('Overload Render')] procedure RenderA(AJson: TJsonObject); procedure RenderError(CTX: TWebContext; ATexto: String); private // [MVCDoc('General parse OData URI')] procedure GetQueryBase(CTX: TWebContext); public [MVCHTTPMethod([httpGET])] [MVCPath('')] [MVCPath('/')] [MVCDoc('Get Resources list')] procedure ResourceList(CTX: TWebContext); [MVCHTTPMethod([httpGET])] [MVCPath('/$metadata')] [MVCDoc('Get config metadata file')] procedure MetadataCollection(CTX: TWebContext); [MVCHTTPMethod([httpGET])] [MVCPath('/reset')] [MVCDoc('Reset/reload metadata file')] procedure ResetCollection(CTX: TWebContext); [MVCHTTPMethod([httpGET])] [MVCPath('/OData.svc/($collection)')] [MVCDoc('Default method to query OData')] procedure QueryCollection1(CTX: TWebContext); [MVCHTTPMethod([httpGET])] [MVCPath('/OData.svc/($collection1)/($collection2)')] procedure QueryCollection2(CTX: TWebContext); [MVCHTTPMethod([httpGET])] [MVCPath('/OData.svc/($collection1)/($collection2)/($collection3)')] procedure QueryCollection3(CTX: TWebContext); [MVCHTTPMethod([httpGET])] [MVCPath('/OData.svc/($collection1)/($collection2)/($collection3)/($collection4)') ] procedure QueryCollection4(CTX: TWebContext); [MVCHTTPMethod([httpDELETE])] [MVCPath('/OData.svc/($collection)')] [MVCDoc('Default method to DELETE OData')] procedure DeleteCollection1(CTX: TWebContext); [MVCHTTPMethod([httpPOST])] [MVCPath('/OData.svc/($collection)')] [MVCDoc('Default method to INSERT OData')] procedure POSTCollection1(CTX: TWebContext); [MVCHTTPMethod([httpPATCH])] [MVCPath('/OData.svc/($collection)')] [MVCDoc('Default method to PATCH OData')] procedure PATCHCollection1(CTX: TWebContext); [MVCHTTPMethod([httpPUT])] [MVCPath('/OData.svc/($collection)')] [MVCDoc('Default method to PATCH OData')] procedure PUTCollection1(CTX: TWebContext); [MVCHTTPMethod([httpOPTIONS])] [MVCPath('/OData.svc/($collection)')] [MVCDoc('Default method to OPTIONS OData')] procedure OPTIONSCollection1(CTX: TWebContext); procedure OnBeforeAction(Context: TWebContext; const AActionName: string; var Handled: Boolean); override; procedure OnAfterAction(Context: TWebContext; const AActionName: string); override; end; TODataControllerClass = class of TODataController; implementation uses ObjectsMappers, WS.Common, {WS.Controller,} oData.ProxyBase, oData.SQL, oData.ServiceModel, oData.Engine, {$IFDEF LOGEVENTS} System.LogEvents.progress, System.LogEvents, {$ENDIF} System.DateUtils; { TODataController } function TODataController.CreateJson(CTX: TWebContext; const AValue: string) : TJsonObject; begin CTX.Response.SetCustomHeader('OData-Version', '4.0'); // CTX.Response.ContentType := 'application/json;odata.metadata=minimal'; // AL - DMVC3, nao consegue buscar conector se houver mais 1 item na lista CTX.Response.ContentType := 'application/json'; result := TJsonObject.create as TJsonObject; result.addPair('@odata.context', AValue); result.addPair('StartsAt', DateToISO8601(now)); end; procedure TODataController.DeleteCollection1(CTX: TWebContext); var FOData: IODataBase; FDataset: TDataset; JSONResponse: TJsonObject; arr: TJsonArray; n: integer; erro: TJsonObject; begin try {$IFDEF LOGEVENTS} LogEvents.DoMsg(nil, 0, CTX.Request.PathInfo); {$ENDIF} CTX.Response.StatusCode := 500; FOData := ODataBase.create(); FOData.DecodeODataURL(CTX); JSONResponse := CreateJson(CTX, CTX.Request.PathInfo); n := FOData.ExecuteDELETE(CTX.Request.Body, JSONResponse); JSONResponse.addPair('@odata.count', n.ToString); if n > 0 then CTX.Response.StatusCode := 200 else CTX.Response.StatusCode := 304; RenderA(JSONResponse); except on e: Exception do RenderError(CTX, e.message); end; end; procedure TODataController.EndsJson(var AJson: TJsonObject); begin AJson.addPair('EndsAt', DateToISO8601(now)); end; procedure TODataController.MetadataCollection(CTX: TWebContext); var js: TJsonObject; begin try js := TJsonObject.ParseJSONValue(ODataServices.LockJson.ToJSON) as TJsonObject; finally ODataServices.UnlockJson; end; render(js, true); end; procedure TODataController.ResetCollection(CTX: TWebContext); begin ODataServices.reload; CTX.Response.StatusCode := 201; render('ok'); end; procedure TODataController.ResourceList(CTX: TWebContext); var js: TJsonObject; rsp: TJsonArray; it: TJsonValue; begin render(ODataServices.ResourceList, true); end; procedure TODataController.OnAfterAction(Context: TWebContext; const AActionName: string); begin inherited; end; procedure TODataController.OnBeforeAction(Context: TWebContext; const AActionName: string; var Handled: Boolean); begin inherited; end; procedure TODataController.OPTIONSCollection1(CTX: TWebContext); var FOData: IODataBase; JSONResponse: TJsonObject; LAllow: string; begin try {$IFDEF LOGEVENTS} LogEvents.DoMsg(nil, 0, CTX.Request.PathInfo); {$ENDIF} CTX.Response.StatusCode := 200; FOData := ODataBase.create(); FOData.DecodeODataURL(CTX); JSONResponse := CreateJson(CTX, CTX.Request.PathInfo); FOData.ExecuteOPTIONS(JSONResponse); if JSONResponse.TryGetValue<string>('allow', LAllow) then begin CTX.Response.CustomHeaders.Add('Allow=' + LAllow); end; RenderA(JSONResponse); except on e: Exception do RenderError(CTX, e.message); end; end; procedure TODataController.PATCHCollection1(CTX: TWebContext); var FOData: IODataBase; FDataset: TDataset; JSONResponse: TJsonObject; arr: TJsonArray; n: integer; r: string; erro: TJsonObject; begin try {$IFDEF LOGEVENTS} LogEvents.DoMsg(nil, 0, CTX.Request.PathInfo); {$ENDIF} CTX.Response.StatusCode := 500; FOData := ODataBase.create(); FOData.DecodeODataURL(CTX); JSONResponse := CreateJson(CTX, CTX.Request.PathInfo); try r := CTX.Request.Body; n := FOData.ExecutePATCH(r, JSONResponse); JSONResponse.addPair('@odata.count', n.ToString); if n > 0 then CTX.Response.StatusCode := 201 else CTX.Response.StatusCode := 304; RenderA(JSONResponse); finally end; except on e: Exception do RenderError(CTX, e.message); end; end; procedure TODataController.POSTCollection1(CTX: TWebContext); var FOData: IODataBase; FDataset: TDataset; JSONResponse: TJsonObject; arr: TJsonArray; n: integer; r: string; erro: TJsonObject; begin try {$IFDEF LOGEVENTS} LogEvents.DoMsg(nil, 0, CTX.Request.PathInfo); {$ENDIF} CTX.Response.StatusCode := 500; FOData := ODataBase.create(); FOData.DecodeODataURL(CTX); JSONResponse := CreateJson(CTX, CTX.Request.PathInfo); n := FOData.ExecutePOST(CTX.Request.Body, JSONResponse); JSONResponse.addPair('@odata.count', n.ToString); if n > 0 then CTX.Response.StatusCode := 201 else CTX.Response.StatusCode := 304; RenderA(JSONResponse); except on e: Exception do RenderError(CTX, e.message); end; end; procedure TODataController.PUTCollection1(CTX: TWebContext); var FOData: IODataBase; FDataset: TDataset; JSONResponse: TJsonObject; arr: TJsonArray; n: integer; r: string; erro: TJsonObject; begin try {$IFDEF LOGEVENTS} LogEvents.DoMsg(nil, 0, CTX.Request.PathInfo); {$ENDIF} CTX.Response.StatusCode := 500; FOData := ODataBase.create(); FOData.DecodeODataURL(CTX); JSONResponse := CreateJson(CTX, CTX.Request.PathInfo); n := FOData.ExecutePATCH(CTX.Request.Body, JSONResponse); JSONResponse.addPair('@odata.count', n.ToString); if n > 0 then CTX.Response.StatusCode := 200 else CTX.Response.StatusCode := 304; RenderA(JSONResponse); except on e: Exception do RenderError(CTX, e.message); end; end; procedure TODataController.QueryCollection1(CTX: TWebContext); begin GetQueryBase(CTX); end; procedure TODataController.GetQueryBase(CTX: TWebContext); var FOData: IODataBase; FDataset: TDataset; JSONResponse: TJsonObject; arr: TJsonArray; n: integer; erro: TJsonObject; begin try {$IFDEF LOGEVENTS} LogEvents.DoMsg(nil, 0, CTX.Request.PathInfo); {$ENDIF} try FOData := ODataBase.create(); FOData.DecodeODataURL(CTX); JSONResponse := CreateJson(CTX, CTX.Request.PathInfo); FDataset := TDataset(FOData.ExecuteGET(nil, JSONResponse)); FDataset.first; arr := TJsonArray.create; Mapper.DataSetToJSONArray(FDataset, arr, False); if assigned(arr) then begin JSONResponse.addPair('value', arr); end; if FOData.inLineRecordCount < 0 then FOData.inLineRecordCount := FDataset.RecordCount; JSONResponse.addPair('@odata.count', FOData.inLineRecordCount.ToString); if FOData.GetParse.oData.Top > 0 then JSONResponse.addPair('@odata.top', FOData.GetParse.oData.Top.ToString); if FOData.GetParse.oData.Skip > 0 then JSONResponse.addPair('@odata.skip', FOData.GetParse.oData.Skip.ToString); RenderA(JSONResponse); finally FOData.release; FOData := nil; end; except on e: Exception do begin freeAndNil(FDataset); freeAndNil(JSONResponse); CTX.Response.StatusCode := 501; RenderError(CTX, e.message); end; end; end; procedure TODataController.QueryCollection2(CTX: TWebContext); begin GetQueryBase(CTX); end; procedure TODataController.QueryCollection3(CTX: TWebContext); begin GetQueryBase(CTX); end; procedure TODataController.QueryCollection4(CTX: TWebContext); begin GetQueryBase(CTX); end; procedure TODataController.RenderA(AJson: TJsonObject); begin EndsJson(AJson); render(AJson); end; procedure TODataController.RenderError(CTX: TWebContext; ATexto: String); var n: integer; js: TJsonObject; begin if ATexto.StartsWith('{') then begin js := TJsonObject.ParseJSONValue(ATexto) as TJsonObject; if assigned(js) then begin try js.GetValue('error').TryGetValue<integer>('code', n); if n > 0 then CTX.Response.StatusCode := n; except end; render(js); exit; end; end; js := TJsonObject.ParseJSONValue(TODataError.create(500, ATexto)) as TJsonObject; render(js); end; initialization RegisterWSController(TODataController); finalization end.
unit Model.RemessasVA; interface type TRemessasVA = class private var FId: Integer; FDistribuidor: Integer; FBanca: Integer; FProduto: String; FDataRemessa: TDate; FNumeroRemessa: String; FRemessa: Double; FDataRecobertura: TDate; FRecobertura: Double; FDataChamada: TDate; FNumeroDevolucao: String; FEncalhe: Double; FValorCobranca: Double; FValorVenda: Double; FInventario: Integer; FDivergencia: Integer; FLog: String; public property Id: Integer read FId write FId; property Distribuidor: Integer read FDistribuidor write FDistribuidor; property Banca: Integer read FBanca write FBanca; property Produto: String read FProduto write FProduto; property DataRemessa: TDate read FDataRemessa write FDataRemessa; property NumeroRemessa: String read FNumeroRemessa write FNumeroRemessa; property Remessa: Double read FRemessa write FRemessa; property DataRecobertura: TDate read FDataRecobertura write FDataRecobertura; property Recobertura: Double read FRecobertura write FRecobertura; property DataChamada: TDate read FDataChamada write FDataChamada; property NumeroDevolucao: String read FNumeroDevolucao write FNumeroDevolucao; property Encalhe: Double read FEncalhe write FEncalhe; property ValorCobranca: Double read FValorCobranca write FValorCobranca; property ValorVenda: Double read FValorVenda write FValorVenda; property Inventario: Integer read FInventario write FInventario; property Divergencia: Integer read FDivergencia write FDivergencia; property Log: String read FLog write FLog; constructor Create; overload; constructor Create(pFId: Integer; pFDistribuidor: Integer; pFBanca: Integer; pFProduto: String; pFDataRemessa: TDate; pFNumeroRemessa: String; pFRemessa: Double; pFDataRecobertura: TDate; pFRecobertura: Double; pFDataChamada: TDate; pFNumeroDevolucao: String; pFEncalhe: Double; pFValorCobranca: Double; pFValorVenda: Double; pFInventario: Integer; pFDivergencia: Integer; pFLog: String); overload; end; implementation constructor TRemessasVA.Create; begin inherited Create; end; constructor TRemessasVA.Create(pFId: Integer; pFDistribuidor: Integer; pFBanca: Integer; pFProduto: String; pFDataRemessa: TDate; pFNumeroRemessa: string; pFRemessa: Double; pFDataRecobertura: TDate; pFRecobertura: Double; pFDataChamada: TDate; pFNumeroDevolucao: string; pFEncalhe: Double; pFValorCobranca: Double; pFValorVenda: Double; pFInventario: Integer; pFDivergencia: Integer; pFLog: string); begin FId := pFId; FDistribuidor := pFDistribuidor; FBanca := pFBanca; FProduto := pFProduto; FDataRemessa := pFDataRemessa; FNumeroRemessa := pFNumeroRemessa; FRemessa := pFRemessa; FDataRecobertura := pFDataRecobertura; FRecobertura := pFRecobertura; FDataChamada := pFDataChamada; FNumeroDevolucao := pFNumeroDevolucao; FEncalhe := pFEncalhe; FValorCobranca := pFValorCobranca; FValorVenda := pFValorVenda; FDivergencia := pFDivergencia; FInventario := pFInventario; FLog := pFLog; end; end.
{ 单元名称: uJxdDataStream 单元作者: 江晓德(Terry) 邮 箱: jxd524@163.com 说 明: 基本通信能力, 使用事件模式 开始时间: 2010-09-21 修改时间: 2011-03-08 (最后修改) 类:TxdStreamBasic TxdStreamBasic: 定义基于流的相关操作,子类实现(*必须实现,-可实现) ReadStream * WriteStream * Position,Size * ReadLong - WriteLong - CheckReadSize - CheckWriteSize - 数据流类结构: TxdMemoryStream TxdFileStream / TxdStreamHandle | TxdStreamBasic < TxdOuterMemory | TxdDynamicMemory \ TxdMemoryHandle TxdStaticMemory_1K TxdStaticMemory_2K TxdStaticMemory_4K TxdStaticMemory_8K TxdMemoryFile TxdMemoryStream: 内存流,使用TMemoryStream TxdFileStream: 文件流, 使用TFileStream TxdOuterMemory: 外部数据流,使用外部提供的数据来进行读写 TxdDynamicMemory: 动态流,使用类自身动态申请的数据进行读写 TxdStaticMemory_xK: 静态流,流本身自带静态的数据进行读写 TxdMemoryFile: 内存映射文件读写 } unit uJxdDataStream; interface uses Windows, Classes, SysUtils; type {$M+} TxdStreamBasic = class public {数据读取} //读取失败则抛出异常 procedure ReadLong(var ABuffer; const ACount: Integer; const AutoIncPos: Boolean = True); virtual; function ReadByte: Byte; function ReadWord: Word; function ReadCardinal: Cardinal; function ReadInteger: Integer; function ReadInt64: Int64; function ReadString: string; //读取1位长度,再读对应长度的字符串 function ReadStringEx: string; //读取2位长度,再读取对应长度的字符串 {数据写入} //写入失败则抛出异常 procedure WriteLong(const ABuffer; const ACount: Integer; const AutoIncPos: Boolean = True); virtual; procedure WriteByte(const AValue: Byte); procedure WriteWord(const AValue: Word); procedure WriteCardinal(const AValue: Cardinal); procedure WriteInteger(const AValue: Integer); procedure WriteInt64(const AValue: Int64); procedure WriteString(const AValue: string); //写入1位长度,再写入应长度的字符串 procedure WriteStringEx(const AValue: string); //写入2位长度,再写入对应长度的字符串 {清空数据} procedure Clear; virtual; published protected {数据读与写的控制方法} function ReadStream(var ABuffer; const AByteCount: Integer): Integer; virtual; abstract; function WriteStream(const ABuffer; const AByteCount: Integer): Integer; virtual; abstract; procedure RaiseReadError; procedure RaiseWriteError; function GetPos: Int64; virtual; abstract; procedure SetPos(const Value: Int64); virtual; abstract; function GetSize: Int64; virtual; abstract; procedure SetSize(const Value: Int64); virtual; abstract; function CheckReadSize(const ACount: Integer): Boolean; virtual; function CheckWriteSize(const ACount: Integer): Boolean; virtual; published property Position: Int64 read GetPos write SetPos; property Size: Int64 read GetSize write SetSize; end; {TxdStreamHandle 以实现系统自带TStream, 不能被实例化} TxdStreamHandle = class(TxdStreamBasic) public procedure ReadLong(var ABuffer; const ACount: Integer; const AutoIncPos: Boolean = True); override; procedure WriteLong(const ABuffer; const ACount: Integer; const AutoIncPos: Boolean = True); override; destructor Destroy; override; protected FStream: TStream; function GetPos: Int64; override; procedure SetPos(const Value: Int64); override; function GetSize: Int64; override; procedure SetSize(const Value: Int64); override; function ReadStream(var ABuffer; const AByteCount: Integer): Integer; override; function WriteStream(const ABuffer; const AByteCount: Integer): Integer; override; end; {TMemoryStream 的具体化} TxdMemoryStream = class(TxdStreamHandle) public constructor Create(const AInitMemorySize: Integer); procedure Clear; override; procedure SaveToFile(const FileName: string); procedure LoadFromFile(const FileName: string); end; {TFileStream 具体化} TxdFileStream = class(TxdStreamHandle) private function GetFileName: string; public constructor Create(const AFileName: string; Mode: Word); overload; constructor Create(const AFileName: string; Mode: Word; Rights: Cardinal); overload; property FileName: string read GetFileName; protected function CheckWriteSize(const ACount: Integer): Boolean; override; end; {TxdMemoryHandle 对外部或自我申请的数据进行处理,不能被实例化} TxdMemoryHandle = class(TxdStreamBasic) public constructor Create; virtual; function CurAddress: PChar; protected FMemory: PChar; FSize: Int64; FPosition: Int64; function GetPos: Int64; override; procedure SetPos(const Value: Int64); override; function GetSize: Int64; override; procedure SetSize(const Value: Int64); override; function ReadStream(var ABuffer; const AByteCount: Integer): Integer; override; function WriteStream(const ABuffer; const AByteCount: Integer): Integer; override; public property Memory: PChar read FMemory; end; TxdMemoryFile = class(TxdMemoryHandle) public constructor Create(const AFileName: string; const AFileSize: Int64 = 0; const ACreateAlways: Boolean = False; const AOnlyRead: Boolean = False); reintroduce; destructor Destroy; override; function MapFileToMemory(const ABeginPos: Int64; const AMapSize: Cardinal): Boolean; procedure Flush; protected function WriteStream(const ABuffer; const AByteCount: Integer): Integer; override; procedure SetSize(const Value: Int64); override; //只改变当前映射大小,不改文件大小 private FFileMap: Cardinal; FFile: Cardinal; FFileName: string; FCurMapPos: Int64; FIsOnlyRead: Boolean; function GetFileSize: Int64; procedure SetFileSize(const ANewFileSize: Int64); published property IsOnlyRead: Boolean read FIsOnlyRead; property FileName: string read FFileName; property FileSize: Int64 read GetFileSize write SetFileSize; property CurMapPos: Int64 read FCurMapPos; property CurMapSize: Int64 read FSize; end; TxdMemoryMapFile = class(TxdMemoryHandle) public constructor Create(const AFileName: string; const AShareName: string = ''; const AFileShareMoe: Cardinal = FILE_SHARE_READ; const ACreateAways: Boolean = False; const AOnlyRead: Boolean = False); reintroduce; destructor Destroy; override; //AMapSize: 0表示映射所有,此时Size属性为MAXDWORD function MapFileToMemory(const ABeginPos: Int64; const AMapSize: Cardinal): Boolean; private function CreateMap: Boolean; procedure CloseMap; function GetFileSizeInfo(var AdwHigh, AdwLow: Cardinal): Boolean; private FFileHanlde, FFileMap: Cardinal; FFileName, FShareName: string; FIsOnlyRead: Boolean; FCurMapBeginPos: Int64; function GetFileSize: Int64; overload; procedure SetFileSize(const Value: Int64); published //property Size: 表示当前映射的大小,并非文件大小 //property Position: 表示当前映射对应的位置 property IsOnlyRead: Boolean read FIsOnlyRead; property FileName: string read FFileName; property ShareName: string read FShareName; property FileSize: Int64 read GetFileSize write SetFileSize; property CurMapBeginPos: Int64 read FCurMapBeginPos; end; {TxdOuterMemory 操作使用外部的内存} TxdOuterMemory = class(TxdMemoryHandle) public procedure InitMemory(const AMemory: PChar; const ASize: Int64); end; {TxdDynamicMemory 对象本身会申请内存,将是本身内存操作} TxdDynamicMemory = class(TxdMemoryHandle) public procedure InitMemory(const ASize: Int64); procedure Clear; override; end; {TxdStaticMemory 静态内存处理,分为16, 32, 64, 128, 512Byte和1, 2, 4, 8K 主要为了方便} TxdStaticMemory_16Byte = class(TxdMemoryHandle) public constructor Create; override; procedure Clear; override; private const DataSize = 16; private FData: array[ 0..DataSize - 1] of Byte; end; TxdStaticMemory_32Byte = class(TxdMemoryHandle) public constructor Create; override; procedure Clear; override; private const DataSize = 32; private FData: array[ 0..DataSize - 1] of Byte; end; TxdStaticMemory_64Byte = class(TxdMemoryHandle) public constructor Create; override; procedure Clear; override; private const DataSize = 64; private FData: array[ 0..DataSize - 1] of Byte; end; TxdStaticMemory_128Byte = class(TxdMemoryHandle) public constructor Create; override; procedure Clear; override; private const DataSize = 128; private FData: array[ 0..DataSize - 1] of Byte; end; TxdStaticMemory_256Byte = class(TxdMemoryHandle) public constructor Create; override; procedure Clear; override; private const DataSize = 256; private FData: array[ 0..DataSize - 1] of Byte; end; TxdStaticMemory_512Byte = class(TxdMemoryHandle) public constructor Create; override; procedure Clear; override; private const DataSize = 512; private FData: array[ 0..DataSize - 1] of Byte; end; TxdStaticMemory_1K = class(TxdMemoryHandle) public constructor Create; override; procedure Clear; override; private const DataSize = 1024; private FData: array[ 0..DataSize - 1] of Byte; end; TxdStaticMemory_2K = class(TxdMemoryHandle) public constructor Create; override; procedure Clear; override; private const DataSize = 1024 * 2; private FData: array[ 0..DataSize - 1] of Byte; end; TxdStaticMemory_4K = class(TxdMemoryHandle) public constructor Create; override; procedure Clear; override; private const DataSize = 1024 * 4; private FData: array[ 0..DataSize - 1] of Byte; end; TxdStaticMemory_8K = class(TxdMemoryHandle) public constructor Create; override; procedure Clear; override; private const DataSize = 1024 * 8; private FData: array[ 0..DataSize - 1] of Byte; end; TxdStaticMemory_16K = class(TxdMemoryHandle) public constructor Create; override; procedure Clear; override; private const DataSize = 1024 * 16; private FData: array[ 0..DataSize - 1] of Byte; end; TxdStaticMemory_32K = class(TxdMemoryHandle) public constructor Create; override; procedure Clear; override; private const DataSize = 1024 * 32; private FData: array[ 0..DataSize - 1] of Byte; end; {$M-} implementation { TxdStreamBasic } function TxdStreamBasic.CheckReadSize(const ACount: Integer): Boolean; begin Result := (Position + Int64(ACount) <= Size) and (ACount > 0); end; function TxdStreamBasic.CheckWriteSize(const ACount: Integer): Boolean; begin Result := (Position + Int64(ACount) <= Size) and (ACount > 0); end; procedure TxdStreamBasic.Clear; begin Position := 0; Size := 0; end; procedure TxdStreamBasic.RaiseReadError; begin raise Exception.Create( 'read data error' ); end; procedure TxdStreamBasic.RaiseWriteError; begin raise Exception.Create( 'write data error' ); end; function TxdStreamBasic.ReadByte: Byte; begin ReadLong( Result, 1 ); end; function TxdStreamBasic.ReadCardinal: Cardinal; begin ReadLong( Result, 4 ); end; function TxdStreamBasic.ReadInt64: Int64; begin ReadLong( Result, 8 ); end; function TxdStreamBasic.ReadInteger: Integer; begin ReadLong( Result, 4 ); end; procedure TxdStreamBasic.ReadLong(var ABuffer; const ACount: Integer; const AutoIncPos: Boolean); begin if not CheckReadSize(ACount) then RaiseReadError; if 0 <> ReadStream(ABuffer, ACount) then begin if AutoIncPos then Position := Position + ACount end else RaiseReadError; end; function TxdStreamBasic.ReadString: string; var btLen: Byte; begin btLen := ReadByte; if btLen > 0 then begin SetLength( Result, btLen ); ReadLong( Result[1], btLen ); end else Result := ''; end; function TxdStreamBasic.ReadStringEx: string; var dLen: Word; begin dLen := ReadWord; if dLen > 0 then begin SetLength( Result, dLen ); ReadLong( Result[1], dLen ); end else Result := ''; end; function TxdStreamBasic.ReadWord: Word; begin ReadLong( Result, 2 ); end; procedure TxdStreamBasic.WriteByte(const AValue: Byte); begin WriteLong( AValue, 1 ); end; procedure TxdStreamBasic.WriteCardinal(const AValue: Cardinal); begin WriteLong( AValue, 4 ); end; procedure TxdStreamBasic.WriteInt64(const AValue: Int64); begin WriteLong( AValue, 8 ); end; procedure TxdStreamBasic.WriteInteger(const AValue: Integer); begin WriteLong( AValue, 4 ); end; procedure TxdStreamBasic.WriteLong(const ABuffer; const ACount: Integer; const AutoIncPos: Boolean); begin if not CheckWriteSize(ACount) then RaiseReadError; if 0 <> WriteStream(ABuffer, ACount) then begin if AutoIncPos then Position := Position + ACount end else RaiseReadError; end; procedure TxdStreamBasic.WriteString(const AValue: string); var btLen: Byte; begin btLen := Byte( Length(AValue) ); WriteByte( btLen ); if btLen > 0 then WriteLong( AValue[1], btLen ); end; procedure TxdStreamBasic.WriteStringEx(const AValue: string); var dLen: Word; begin dLen := Word( Length(AValue) ); WriteWord( dLen ); if dLen > 0 then WriteLong( AValue[1], dLen ); end; procedure TxdStreamBasic.WriteWord(const AValue: Word); begin WriteLong( AValue, 2 ); end; { TxdStreamHandle } destructor TxdStreamHandle.Destroy; begin FreeAndNil( FStream ); inherited; end; function TxdStreamHandle.GetPos: Int64; begin Result := FStream.Position; end; function TxdStreamHandle.GetSize: Int64; begin Result := FStream.Size; end; procedure TxdStreamHandle.ReadLong(var ABuffer; const ACount: Integer; const AutoIncPos: Boolean); begin inherited ReadLong(ABuffer, ACount, False); if not AutoIncPos then Position := Position - ACount; end; function TxdStreamHandle.ReadStream(var ABuffer; const AByteCount: Integer): Integer; begin Result := FStream.Read( ABuffer, AByteCount ); end; procedure TxdStreamHandle.SetPos(const Value: Int64); begin FStream.Position := Value; end; procedure TxdStreamHandle.SetSize(const Value: Int64); begin if (FStream.Size <> Value) and (Value >= 0) then FStream.Size := Value; end; procedure TxdStreamHandle.WriteLong(const ABuffer; const ACount: Integer; const AutoIncPos: Boolean); begin inherited WriteLong( ABuffer, ACount, False ); if not AutoIncPos then Position := Position - ACount; end; function TxdStreamHandle.WriteStream(const ABuffer; const AByteCount: Integer): Integer; begin Result := FStream.Write( ABuffer, AByteCount ); end; { TxdMemoryStream } procedure TxdMemoryStream.Clear; begin (FStream as TMemoryStream).Clear; end; constructor TxdMemoryStream.Create(const AInitMemorySize: Integer); begin inherited Create; FStream := TMemoryStream.Create; FStream.Size := AInitMemorySize; end; procedure TxdMemoryStream.LoadFromFile(const FileName: string); begin (FStream as TMemoryStream).LoadFromFile( FileName ); end; procedure TxdMemoryStream.SaveToFile(const FileName: string); begin (FStream as TMemoryStream).SaveToFile( FileName ); end; { TxdFileStream } constructor TxdFileStream.Create(const AFileName: string; Mode: Word); begin FStream := TFileStream.Create( AFileName, Mode ); end; function TxdFileStream.CheckWriteSize(const ACount: Integer): Boolean; begin Result := True; end; constructor TxdFileStream.Create(const AFileName: string; Mode: Word; Rights: Cardinal); begin FStream := TFileStream.Create( AFileName, Mode, Rights ); end; function TxdFileStream.GetFileName: string; begin Result := (FStream as TFileStream).FileName; end; { TxdMemoryHandle } constructor TxdMemoryHandle.Create; begin FPosition := 0; FSize := 0; FMemory := nil; end; function TxdMemoryHandle.CurAddress: PChar; begin Result := FMemory + FPosition; end; function TxdMemoryHandle.GetPos: Int64; begin Result := FPosition; end; function TxdMemoryHandle.GetSize: Int64; begin Result := FSize; end; function TxdMemoryHandle.ReadStream(var ABuffer; const AByteCount: Integer): Integer; begin Move( (FMemory + FPosition)^, ABuffer, AByteCount ); Result := AByteCount; end; procedure TxdMemoryHandle.SetPos(const Value: Int64); begin if Value <= FSize then FPosition := Value; end; procedure TxdMemoryHandle.SetSize(const Value: Int64); begin FSize := Value; if FPosition > FSize then FPosition := FSize; end; function TxdMemoryHandle.WriteStream(const ABuffer; const AByteCount: Integer): Integer; begin Move( ABuffer,(FMemory + FPosition)^, AByteCount ); Result := AByteCount; end; { TxdOuterMemory } procedure TxdOuterMemory.InitMemory(const AMemory: PChar; const ASize: Int64); begin FMemory := AMemory; FPosition := 0; FSize := ASize; end; { TxdDynamicMemory } procedure TxdDynamicMemory.Clear; begin inherited; FreeMemory( FMemory ); end; procedure TxdDynamicMemory.InitMemory(const ASize: Int64); begin FreeMemory( FMemory ); FMemory := AllocMem( ASize ); FSize := ASize; FPosition := 0; end; { TxdStaticMemory_1K } procedure TxdStaticMemory_1K.Clear; begin FPosition := 0; FSize := DataSize; FillChar( FData[0], DataSize, 0 ); FMemory := @FData; end; constructor TxdStaticMemory_1K.Create; begin inherited; Clear; end; { TxdStaticMemory_2K } procedure TxdStaticMemory_2K.Clear; begin FPosition := 0; FSize := DataSize; FillChar( FData[0], DataSize, 0 ); FMemory := @FData; end; constructor TxdStaticMemory_2K.Create; begin inherited; Clear; end; { TxdStaticMemory_4K } procedure TxdStaticMemory_4K.Clear; begin FPosition := 0; FSize := DataSize; FillChar( FData[0], DataSize, 0 ); FMemory := @FData; end; constructor TxdStaticMemory_4K.Create; begin inherited; Clear; end; { TxdStaticMemory_8K } procedure TxdStaticMemory_8K.Clear; begin FPosition := 0; FSize := DataSize; FillChar( FData[0], DataSize, 0 ); FMemory := @FData; end; constructor TxdStaticMemory_8K.Create; begin inherited; Clear; end; { TxdMemoryFile } constructor TxdMemoryFile.Create(const AFileName: string; const AFileSize: Int64; const ACreateAlways: Boolean; const AOnlyRead: Boolean); var Style: Cardinal; nSize: Int64; strDir: string; begin inherited Create; if ACreateAlways or (not FileExists(AFileName)) then begin Style := CREATE_ALWAYS; strDir := ExtractFilePath( AFileName ); if not DirectoryExists(strDir) then ForceDirectories( strDir ); end else Style := OPEN_ALWAYS; if AOnlyRead then FFile := CreateFile(PAnsiChar(AFileName), GENERIC_READ, FILE_SHARE_READ, nil, Style, 0, 0) else FFile := CreateFile(PAnsiChar(AFileName), GENERIC_READ or GENERIC_WRITE, FILE_SHARE_READ or FILE_SHARE_WRITE, nil, Style, 0, 0); if FFile = INVALID_HANDLE_VALUE then raise Exception.Create(SysErrorMessage(GetLastError)); if AFileSize <> 0 then begin nSize := Windows.GetFileSize( FFile, nil ); if nSize <> AFileSize then begin FileSeek( FFile, AFileSize, FILE_BEGIN ); SetEndOfFile( FFile ); end; end; nSize := Windows.GetFileSize( FFile, nil ); FCurMapPos := -1; FSize := 0; if nSize > 0 then begin if AOnlyRead then FFileMap := CreateFileMapping( FFile, nil, PAGE_READONLY, 0, nSize, nil ) else FFileMap := CreateFileMapping( FFile, nil, PAGE_READWRITE, 0, nSize, nil ); if FFileMap = 0 then raise Exception.Create(SysErrorMessage(GetLastError)); end; FFileName := AFileName; FIsOnlyRead := AOnlyRead; end; destructor TxdMemoryFile.Destroy; begin if Assigned(FMemory) then begin FlushViewOfFile( FMemory, 0 ); UnmapViewOfFile( FMemory ); end; CloseHandle( FFileMap ); CloseHandle( FFile ); inherited; end; procedure TxdMemoryFile.Flush; begin if FMemory <> nil then FlushViewOfFile( FMemory, 0 ); end; function TxdMemoryFile.GetFileSize: Int64; begin Result := Windows.GetFileSize( FFile, nil ); end; function TxdMemoryFile.MapFileToMemory(const ABeginPos: Int64; const AMapSize: Cardinal): Boolean; var nHighOffset, nLowOffset, nMapSize: Cardinal; sf: TSystemInfo; begin Result := (FFileMap <> 0) and (ABeginPos >= 0); if not Result then Exit; nHighOffset := ABeginPos shr 32; nLowOffset := Cardinal(ABeginPos); nMapSize := AMapSize; if nMapSize <> 0 then begin GetSystemInfo(sf); if (nMapSize mod sf.dwAllocationGranularity) <> 0 then nMapSize := (nMapSize + sf.dwAllocationGranularity - 1) div sf.dwAllocationGranularity * sf.dwAllocationGranularity; end; if nMapSize >= FileSize then nMapSize := 0; if Assigned(FMemory) then UnmapViewOfFile( FMemory ); if IsOnlyRead then FMemory := MapViewOfFile( FFileMap, FILE_MAP_READ, nHighOffset, nLowOffset, nMapSize ) else FMemory := MapViewOfFile( FFileMap, FILE_MAP_ALL_ACCESS, nHighOffset, nLowOffset, nMapSize ); Result := Assigned(FMemory); if not Result then begin FSize := 0; FPosition := 0; FCurMapPos := -1; Exit; end; if AMapSize <> 0 then FSize := AMapSize else FSize := Windows.GetFileSize( FFile, nil ); FCurMapPos := ABeginPos; FPosition := 0; end; procedure TxdMemoryFile.SetFileSize(const ANewFileSize: Int64); begin if ANewFileSize <> 0 then begin FileSeek( FFile, ANewFileSize, FILE_BEGIN ); SetEndOfFile( FFile ); if FFileMap <> 0 then begin CloseHandle( FFileMap ); FFileMap := CreateFileMapping( FFile, nil, PAGE_READWRITE, 0, FSize, nil ); if FFileMap = 0 then raise Exception.Create(SysErrorMessage(GetLastError)); if FCurMapPos + FSize <= ANewFileSize then MapFileToMemory( FCurMapPos, FSize ) else begin if Assigned(FMemory) then begin UnmapViewOfFile( FMemory ); FMemory := nil; end; FCurMapPos := -1; FSize := 0; end; end; end; end; procedure TxdMemoryFile.SetSize(const Value: Int64); begin if FSize <> Value then begin if FCurMapPos >= 0 then MapFileToMemory( FCurMapPos, FSize ); end; end; function TxdMemoryFile.WriteStream(const ABuffer; const AByteCount: Integer): Integer; begin if IsOnlyRead then Result := -1 else Result := inherited WriteStream(ABuffer, AByteCount); end; { TxdStaticMemory_16Byte } procedure TxdStaticMemory_16Byte.Clear; begin FPosition := 0; FSize := DataSize; FillChar( FData[0], DataSize, 0 ); FMemory := @FData; end; constructor TxdStaticMemory_16Byte.Create; begin inherited; Clear; end; { TxdStaticMemory_32Byte } procedure TxdStaticMemory_32Byte.Clear; begin FPosition := 0; FSize := DataSize; FillChar( FData[0], DataSize, 0 ); FMemory := @FData; end; constructor TxdStaticMemory_32Byte.Create; begin inherited; Clear; end; { TxdStaticMemory_64Byte } procedure TxdStaticMemory_64Byte.Clear; begin FPosition := 0; FSize := DataSize; FillChar( FData[0], DataSize, 0 ); FMemory := @FData; end; constructor TxdStaticMemory_64Byte.Create; begin inherited; Clear; end; { TxdStaticMemory_256Byte } procedure TxdStaticMemory_256Byte.Clear; begin FPosition := 0; FSize := DataSize; FillChar( FData[0], DataSize, 0 ); FMemory := @FData; end; constructor TxdStaticMemory_256Byte.Create; begin inherited; Clear; end; { TxdStaticMemory_128Byte } procedure TxdStaticMemory_128Byte.Clear; begin FPosition := 0; FSize := DataSize; FillChar( FData[0], DataSize, 0 ); FMemory := @FData; end; constructor TxdStaticMemory_128Byte.Create; begin inherited; Clear; end; { TxdStaticMemory_512Byte } procedure TxdStaticMemory_512Byte.Clear; begin FPosition := 0; FSize := DataSize; FillChar( FData[0], DataSize, 0 ); FMemory := @FData; end; constructor TxdStaticMemory_512Byte.Create; begin inherited; Clear; end; { TxdStaticMemory_16K } procedure TxdStaticMemory_16K.Clear; begin FPosition := 0; FSize := DataSize; FillChar( FData[0], DataSize, 0 ); FMemory := @FData; end; constructor TxdStaticMemory_16K.Create; begin inherited; Clear; end; { TxdStaticMemory_32K } procedure TxdStaticMemory_32K.Clear; begin FPosition := 0; FSize := DataSize; FillChar( FData[0], DataSize, 0 ); FMemory := @FData; end; constructor TxdStaticMemory_32K.Create; begin inherited; Clear; end; { TxdMemoryMapFile } procedure TxdMemoryMapFile.CloseMap; begin if FFileMap <> 0 then begin if Assigned(FMemory) then begin UnmapViewOfFile( FMemory ); FMemory := nil; end; CloseHandle( FFileMap ); FFileMap := 0; FCurMapBeginPos := 0; end; end; constructor TxdMemoryMapFile.Create(const AFileName, AShareName: string; const AFileShareMoe: Cardinal; const ACreateAways, AOnlyRead: Boolean); var dwStyle: Cardinal; begin FFileMap := 0; FFileHanlde := INVALID_HANDLE_VALUE; if ACreateAways or not FileExists(AFileName) then begin dwStyle := CREATE_ALWAYS; if not DirectoryExists(ExtractFileDir(AFileName)) then ForceDirectories( ExtractFileDir(AFileName) ); end else begin dwStyle := OPEN_ALWAYS; end; if ACreateAways then FFileHanlde := CreateFile( PChar(AFileName), GENERIC_READ, AFileShareMoe, nil, dwStyle, 0, 0 ) else FFileHanlde := CreateFile( PChar(AFileName), GENERIC_ALL, AFileShareMoe, nil, dwStyle, 0, 0 ); if INVALID_HANDLE_VALUE = FFileHanlde then begin if AShareName = '' then raise Exception.Create( 'Can not Create File, on TxdMemoryMapFile Create!!!' ); end; FSize := GetFileSize; FFileName := AFileName; FShareName := AShareName; FCurMapBeginPos := 0 ; end; function TxdMemoryMapFile.CreateMap: Boolean; var dwHigh, dwLow, dwProtect: Cardinal; begin CloseMap; Result := GetFileSizeInfo( dwHigh, dwLow ); if Result then begin if FIsOnlyRead then dwProtect := PAGE_READONLY else dwProtect := PAGE_READWRITE; if FShareName = '' then FFileMap := CreateFileMapping( FFileHanlde, nil, dwProtect, dwHigh, dwLow, nil ) else FFileMap := CreateFileMapping( FFileHanlde, nil, dwProtect, dwHigh, dwLow, PChar(FShareName) ); end else if FShareName <> '' then begin if FIsOnlyRead then dwProtect := FILE_MAP_READ else dwProtect := FILE_MAP_ALL_ACCESS; FFileMap := OpenFileMapping( dwProtect, False, PChar(FShareName) ); end; Result := FFileMap <> 0; end; destructor TxdMemoryMapFile.Destroy; begin CloseMap; if INVALID_HANDLE_VALUE <> FFileHanlde then begin CloseHandle( FFileHanlde ); FFileHanlde := INVALID_HANDLE_VALUE; end; inherited; end; function TxdMemoryMapFile.GetFileSizeInfo(var AdwHigh, AdwLow: Cardinal): Boolean; begin if INVALID_HANDLE_VALUE = FFileHanlde then begin Result := False; Exit; end; AdwLow := Windows.GetFileSize( FFileHanlde, @AdwHigh ); Result := True; end; function TxdMemoryMapFile.MapFileToMemory(const ABeginPos: Int64; const AMapSize: Cardinal): Boolean; var SysInfo: TSystemInfo; dwSysGran, dwHighOffset, dwLowOffset, dwMapSize: Cardinal; nPos: Int64; begin if 0 = FFileMap then begin if not CreateMap then begin Result := False; Exit; end; end; GetSystemInfo( SysInfo ); dwSysGran := SysInfo.dwAllocationGranularity; nPos := (ABeginPos div dwSysGran) * dwSysGran; dwHighOffset := nPos shr 32; dwLowOffset := Cardinal(nPos); dwMapSize := (ABeginPos mod dwSysGran) + AMapSize; if Assigned(FMemory) then begin UnmapViewOfFile( FMemory ); FMemory := nil; end; if FIsOnlyRead then FMemory := MapViewOfFile( FFileMap, FILE_MAP_READ, dwHighOffset, dwLowOffset, dwMapSize ) else FMemory := MapViewOfFile( FFileMap, FILE_MAP_ALL_ACCESS, dwHighOffset, dwLowOffset, dwMapSize ); Result := Assigned( FMemory ); if Result then begin if dwMapSize <> 0 then FSize := dwMapSize else FSize := FileSize; //假设都可用 if FSize = 0 then FSize := MAXDWORD; FCurMapBeginPos := nPos; FPosition := ABeginPos mod dwSysGran; end; end; function TxdMemoryMapFile.GetFileSize: Int64; var dwHigh, dwLow: Cardinal; begin if GetFileSizeInfo(dwHigh, dwLow) then Result := dwHigh shl 32 or dwLow else Result := 0; end; procedure TxdMemoryMapFile.SetFileSize(const Value: Int64); var dwHigh, dwLow: Cardinal; begin if (INVALID_HANDLE_VALUE <> FFileHanlde) and (Value > 0) and (Value <> GetFileSize) then begin dwHigh := Value shr 32; dwLow := Cardinal( Value ); SetFilePointer( FFileHanlde, dwLow, @dwHigh, FILE_BEGIN ); SetEndOfFile( FFileHanlde ); CloseMap; end; end; end.
unit PessoaFisica; interface uses MVCFramework.Serializer.Commons, ModelBase; type [MVCNameCase(ncLowerCase)] TPessoaFisica = class(TModelBase) private FID: Integer; FID_PESSOA: Integer; FID_NIVEL_FORMACAO: Integer; FID_ESTADO_CIVIL: Integer; FCPF: string; FRG: string; FORGAO_RG: string; FDATA_EMISSAO_RG: TDateTime; FDATA_NASCIMENTO: TDateTime; FSEXO: string; FRACA: string; FNACIONALIDADE: string; FNATURALIDADE: string; FNOME_MAE: string; FNOME_PAI: string; public procedure ValidarInsercao; override; procedure ValidarAlteracao; override; procedure ValidarExclusao; override; [MVCColumnAttribute('ID', True)] [MVCNameAsAttribute('id')] property Id: Integer read FID write FID; [MVCColumnAttribute('ID_PESSOA')] [MVCNameAsAttribute('idPessoa')] property IdPessoa: Integer read FID_PESSOA write FID_PESSOA; [MVCColumnAttribute('ID_NIVEL_FORMACAO')] [MVCNameAsAttribute('idNivelFormacao')] property IdNivelFormacao: Integer read FID_NIVEL_FORMACAO write FID_NIVEL_FORMACAO; [MVCColumnAttribute('ID_ESTADO_CIVIL')] [MVCNameAsAttribute('idEstadoCivil')] property IdEstadoCivil: Integer read FID_ESTADO_CIVIL write FID_ESTADO_CIVIL; [MVCColumnAttribute('CPF')] [MVCNameAsAttribute('cpf')] property Cpf: string read FCPF write FCPF; [MVCColumnAttribute('RG')] [MVCNameAsAttribute('rg')] property Rg: string read FRG write FRG; [MVCColumnAttribute('ORGAO_RG')] [MVCNameAsAttribute('orgaoRg')] property OrgaoRg: string read FORGAO_RG write FORGAO_RG; [MVCColumnAttribute('DATA_EMISSAO_RG')] [MVCNameAsAttribute('dataEmissaoRg')] property DataEmissaoRg: TDateTime read FDATA_EMISSAO_RG write FDATA_EMISSAO_RG; [MVCColumnAttribute('DATA_NASCIMENTO')] [MVCNameAsAttribute('dataNascimento')] property DataNascimento: TDateTime read FDATA_NASCIMENTO write FDATA_NASCIMENTO; [MVCColumnAttribute('SEXO')] [MVCNameAsAttribute('sexo')] property Sexo: string read FSEXO write FSEXO; [MVCColumnAttribute('RACA')] [MVCNameAsAttribute('raca')] property Raca: string read FRACA write FRACA; [MVCColumnAttribute('NACIONALIDADE')] [MVCNameAsAttribute('nacionalidade')] property Nacionalidade: string read FNACIONALIDADE write FNACIONALIDADE; [MVCColumnAttribute('NATURALIDADE')] [MVCNameAsAttribute('naturalidade')] property Naturalidade: string read FNATURALIDADE write FNATURALIDADE; [MVCColumnAttribute('NOME_MAE')] [MVCNameAsAttribute('nomeMae')] property NomeMae: string read FNOME_MAE write FNOME_MAE; [MVCColumnAttribute('NOME_PAI')] [MVCNameAsAttribute('nomePai')] property NomePai: string read FNOME_PAI write FNOME_PAI; end; implementation { TPessoaFisica } procedure TPessoaFisica.ValidarInsercao; begin inherited; end; procedure TPessoaFisica.ValidarAlteracao; begin inherited; end; procedure TPessoaFisica.ValidarExclusao; begin inherited; end; end.
unit LUX.GPU.OpenGL.Progra; interface //#################################################################### ■ uses System.SysUtils, System.Classes, System.Generics.Collections, Winapi.OpenGL, Winapi.OpenGLext, LUX, LUX.GPU.OpenGL, LUX.GPU.OpenGL.Shader; type //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【型】 TGLProgra = class; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLPortS TGLPortS = record private public Shad :IGLShader; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLPortF TGLPortF = record private public Name :String; end; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLPorts<_TPort_> TGLPorts<_TPort_:record> = class( TDictionary<GLuint,_TPort_> ) private protected _Progra :TGLProgra; ///// メソッド procedure AddPort( const BinP_:GLuint; const Port_:_TPort_ ); virtual; abstract; procedure DelPort( const BinP_:GLuint; const Port_:_TPort_ ); virtual; abstract; public constructor Create( const Progra_:TGLProgra ); ///// プロパティ property Progra :TGLProgra read _Progra; ///// メソッド procedure Add( const BindI_:GLuint; const Port_:_TPort_ ); procedure Remove( const BindI_:GLuint ); procedure Del( const BindI_:GLuint ); procedure AddPorts; procedure DelPorts; procedure Use; virtual; procedure Unuse; virtual; end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLPortsS TGLPortsS = class( TGLPorts<TGLPortS> ) private protected ///// メソッド procedure AddPort( const BinP_:GLuint; const Port_:TGLPortS ); override; procedure DelPort( const BinP_:GLuint; const Port_:TGLPortS ); override; public ///// メソッド procedure Add( const Shad_:IGLShader ); procedure Del( const Shad_:IGLShader ); end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLPortsF TGLPortsF = class( TGLPorts<TGLPortF> ) private protected ///// メソッド procedure AddPort( const BinP_:GLuint; const Port_:TGLPortF ); override; procedure DelPort( const BinP_:GLuint; const Port_:TGLPortF ); override; public ///// メソッド procedure Add( const BinP_:GLuint; const Name_:String ); end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLProgra IGLProgra = interface( IGLObject ) ['{0B2FDEDE-30D3-439B-AC76-E61F9E028CD0}'] {protected} ///// アクセス function GetStatus :Boolean; function GetErrors :TStringList; function GetShaders :TGLPortsS; function GetFramers :TGLPortsF; ///// イベント function GetOnLinked :TProc; procedure SetOnLinked( const OnLinked_:TProc ); {public} ///// プロパティ property Status :Boolean read GetStatus ; property Errors :TStringList read GetErrors ; property Shaders :TGLPortsS read GetShaders; property Framers :TGLPortsF read GetFramers; ///// イベント property OnLinked :TProc read GetOnLinked write SetOnLinked; ///// メソッド procedure Attach( const Shader_:IGLShader ); procedure Detach( const Shader_:IGLShader ); procedure Link; procedure Use; procedure Unuse; end; //------------------------------------------------------------------------- TGLProgra = class( TGLObject, IGLProgra ) private protected _Status :Boolean; _Errors :TStringList; _Shaders :TGLPortsS; _Framers :TGLPortsF; ///// イベント _OnLinked :TProc; ///// アクセス function GetStatus :Boolean; function GetErrors :TStringList; function GetShaders :TGLPortsS; function GetFramers :TGLPortsF; ///// イベント function GetOnLinked :TProc; procedure SetOnLinked( const OnLinked_:TProc ); procedure DoOnLinked; virtual; ///// メソッド function glGetStatus :Boolean; function glGetErrors :String; public constructor Create; destructor Destroy; override; ///// プロパティ property Status :Boolean read GetStatus ; property Errors :TStringList read GetErrors ; property Shaders :TGLPortsS read GetShaders; property Framers :TGLPortsF read GetFramers; ///// イベント property OnLinked :TProc read GetOnLinked write SetOnLinked; ///// メソッド function glGetVertLoca( const Name_:String ) :GLuint; function glGetBlocLoca( const Name_:String ) :GLuint; function glGetUnifLoca( const Name_:String ) :GLuint; procedure Attach( const Shader_:IGLShader ); procedure Detach( const Shader_:IGLShader ); procedure Link; procedure Use; virtual; procedure Unuse; virtual; end; //const //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【定数】 //var //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【変数】 //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 implementation //############################################################### ■ //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【レコード】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLPortS //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLPortF //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【クラス】 //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLPorts<_TPort_> //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TGLPorts<_TPort_>.Create( const Progra_:TGLProgra ); begin inherited Create; _Progra := Progra_; end; /////////////////////////////////////////////////////////////////////// メソッド procedure TGLPorts<_TPort_>.Add( const BindI_:GLuint; const Port_:_TPort_ ); begin inherited AddOrSetValue( BindI_, Port_ ); AddPort( BindI_, Port_ ); end; procedure TGLPorts<_TPort_>.Remove( const BindI_:GLuint ); begin DelPort( BindI_, Items[ BindI_ ] ); inherited Remove( BindI_ ); end; procedure TGLPorts<_TPort_>.Del( const BindI_:GLuint ); begin Remove( BindI_ ); end; //------------------------------------------------------------------------------ procedure TGLPorts<_TPort_>.AddPorts; var P :TPair<GLuint,_TPort_>; begin for P in Self do begin with P do AddPort( Key, Value ); end; end; procedure TGLPorts<_TPort_>.DelPorts; var P :TPair<GLuint,_TPort_>; begin for P in Self do begin with P do DelPort( Key, Value ); end; end; //------------------------------------------------------------------------------ procedure TGLPorts<_TPort_>.Use; begin end; procedure TGLPorts<_TPort_>.Unuse; begin end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLPortsS //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// メソッド procedure TGLPortsS.AddPort( const BinP_:GLuint; const Port_:TGLPortS ); begin _Progra.Attach( Port_.Shad ); end; procedure TGLPortsS.DelPort( const BinP_:GLuint; const Port_:TGLPortS ); begin _Progra.Detach( Port_.Shad ); end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public /////////////////////////////////////////////////////////////////////// メソッド procedure TGLPortsS.Add( const Shad_:IGLShader ); var P :TGLPortS; begin with P do begin Shad := Shad_; end; inherited Add( Shad_.Kind, P ); end; procedure TGLPortsS.Del( const Shad_:IGLShader ); begin inherited Del( Shad_.Kind ); end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLPortsF //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// メソッド procedure TGLPortsF.AddPort( const BinP_:GLuint; const Port_:TGLPortF ); begin glBindFragDataLocation( _Progra.ID, BinP_, PGLchar( AnsiString( Port_.Name ) ) ); end; procedure TGLPortsF.DelPort( const BinP_:GLuint; const Port_:TGLPortF ); begin end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public /////////////////////////////////////////////////////////////////////// メソッド procedure TGLPortsF.Add( const BinP_:GLuint; const Name_:String ); var P :TGLPortF; begin with P do begin Name := Name_; end; inherited Add( BinP_, P ); end; //%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% TGLProgra //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& private //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& protected /////////////////////////////////////////////////////////////////////// アクセス function TGLProgra.GetStatus :Boolean; begin Result := _Status; end; function TGLProgra.GetErrors :TStringList; begin Result := _Errors; end; //------------------------------------------------------------------------------ function TGLProgra.GetShaders :TGLPortsS; begin Result := _Shaders; end; function TGLProgra.GetFramers :TGLPortsF; begin Result := _Framers; end; /////////////////////////////////////////////////////////////////////// イベント function TGLProgra.GetOnLinked :TProc; begin Result := _OnLinked; end; procedure TGLProgra.SetOnLinked( const OnLinked_:TProc ); begin _OnLinked := OnLinked_; end; procedure TGLProgra.DoOnLinked; begin _OnLinked; end; /////////////////////////////////////////////////////////////////////// メソッド function TGLProgra.glGetStatus :Boolean; var S :GLint; begin glGetProgramiv( _ID, GL_LINK_STATUS, @S ); Result := ( S = GL_TRUE ); end; function TGLProgra.glGetErrors :String; var N :GLint; Cs :TArray<GLchar>; CsN :GLsizei; begin glGetProgramiv( _ID, GL_INFO_LOG_LENGTH, @N ); SetLength( Cs, N ); glGetProgramInfoLog( _ID, N, @CsN, PGLchar( Cs ) ); SetString( Result, PGLchar( Cs ), CsN ); end; //&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& public constructor TGLProgra.Create; begin inherited Create; _Errors := TStringList.Create; _Shaders := TGLPortsS.Create( Self ); _Framers := TGLPortsF.Create( Self ); _ID := glCreateProgram; _Status := False; _OnLinked := procedure begin end; end; destructor TGLProgra.Destroy; begin glDeleteProgram( _ID ); _Shaders.DisposeOf; _Framers.DisposeOf; _Errors.DisposeOf; inherited; end; /////////////////////////////////////////////////////////////////////// メソッド function TGLProgra.glGetVertLoca( const Name_:String ) :GLuint; begin Result := glGetAttribLocation( _ID, PAnsiChar( AnsiString( Name_ ) ) ); end; function TGLProgra.glGetBlocLoca( const Name_:String ) :GLuint; begin Result := glGetUniformBlockIndex( _ID, PAnsiChar( AnsiString( Name_ ) ) ); end; function TGLProgra.glGetUnifLoca( const Name_:String ) :GLuint; begin Result := glGetUniformLocation( _ID, PAnsiChar( AnsiString( Name_ ) ) ); end; //------------------------------------------------------------------------------ procedure TGLProgra.Attach( const Shader_:IGLShader ); begin glAttachShader( _ID, Shader_.ID ); end; procedure TGLProgra.Detach( const Shader_:IGLShader ); begin glDetachShader( _ID, Shader_.ID ); end; //------------------------------------------------------------------------------ procedure TGLProgra.Link; begin glLinkProgram( _ID ); _Status := glGetStatus; _Errors.Text := glGetErrors; DoOnLinked; end; //------------------------------------------------------------------------------ procedure TGLProgra.Use; begin glUseProgram( _ID ); end; procedure TGLProgra.Unuse; begin glUseProgram( 0 ); end; //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$【ルーチン】 //############################################################################## □ initialization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 初期化 finalization //$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 最終化 end. //######################################################################### ■
unit lua.context; interface uses Generics.Collections; type TScriptContext = class private FStatus: Integer; FLoadPath: string; FLoadCPath: string; FArguments: TList<string>; FGlobals: TDictionary<string, string>; protected function GetArgCount: Integer; function GetArgArray: TArray<string>; public constructor Create; destructor Destroy; override; property Status: Integer read FStatus write FStatus; property LoadPath: string read FLoadPath write FLoadPath; property LoadCPath: string read FLoadCPath write FLoadCPath; property Arguments: TList<string> read FArguments; property ArgCount: Integer read GetArgCount; property ArgArray: TArray<string> read GetArgArray; property Globals: TDictionary<string, string> read FGlobals; end; implementation { TScriptContext } constructor TScriptContext.Create; begin inherited; FArguments := TList<string>.Create; FGlobals := TDictionary<string, string>.Create; end; destructor TScriptContext.Destroy; begin FGlobals.Free; FArguments.Free; inherited; end; function TScriptContext.GetArgArray: TArray<string>; begin Result := FArguments.ToArray; end; function TScriptContext.GetArgCount: Integer; begin Result := FArguments.Count; end; end.
unit ProcessForm; { Copyright (c) 2017+, Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls, System.ImageList, FMX.ImgList, BaseFrame; type TProcessingForm = class(TForm) lblOperation: TLabel; Button1: TButton; ImageList1: TImageList; StyleBook1: TStyleBook; Timer1: TTimer; procedure Timer1Timer(Sender: TObject); private FProc: TWorkProc; public property proc : TWorkProc read FProc write FProc; end; var ProcessingForm: TProcessingForm; implementation {$R *.fmx} procedure TProcessingForm.Timer1Timer(Sender: TObject); begin Timer1.Enabled := false; {$IFDEF MSWINDOWS} Application.ProcessMessages; {$ENDIF} try proc; finally ModalResult := mrClose; end; end; end.
unit Thread.SalvaApontamentoOperacional; interface uses System.Classes, System.Generics.Collections, System.SysUtils, Vcl.Forms, System.UITypes, Model.RHOperacionalAusencias, DAO.RHOperacionalAusencias, Model.ApontamentoOperacional, DAO.ApontamentoOperacional; type Thread_SalvaApontamentoOperacional = class(TThread) private { Private declarations } FdPos: Double; apontamento: TApontamentoOperacional; apontamentos: TObjectList<TApontamentoOperacional>; apontamentoDAO: TApontamentoOperacionalDAO; ausencia: TRHoperacionalAusencias; ausencias: TObjectList<TRHoperacionalAusencias>; ausenciaDAO: TRHoperacionalAusenciasDAO; protected procedure Execute; override; procedure IniciaProcesso; procedure AtualizaProcesso; procedure TerminaProcesso; procedure SetupApontamento; procedure SalvaApontamento; procedure SetupAusencias; procedure SalvaAusencias; 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_SalvaApontamentoOperacional.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 View.ApontamentoOperacional, View.ResultatoProcesso, uGlobais; { Thread_SalvaApontamentoOperacional } procedure Thread_SalvaApontamentoOperacional.IniciaProcesso; begin view_ApontamentoOperacional.pbApontamento.Visible := True; view_ApontamentoOperacional.dsApontamento.Enabled := False; view_ApontamentoOperacional.tbApontamento.IsLoading := True; view_ApontamentoOperacional.pbApontamento.Position := 0; view_ApontamentoOperacional.pbApontamento.Refresh; end; procedure Thread_SalvaApontamentoOperacional.Execute; begin { Place thread code here } SalvaApontamento; SalvaAusencias end; procedure Thread_SalvaApontamentoOperacional.AtualizaProcesso; begin view_ApontamentoOperacional.pbApontamento.Position := FdPos; view_ApontamentoOperacional.pbApontamento.Properties.Text := FormatFloat('0.00%',FdPos); view_ApontamentoOperacional.pbApontamento.Refresh; end; procedure Thread_SalvaApontamentoOperacional.TerminaProcesso; begin view_ApontamentoOperacional.pbApontamento.Position := 0; view_ApontamentoOperacional.pbApontamento.Properties.Text := ''; view_ApontamentoOperacional.pbApontamento.Refresh; view_ApontamentoOperacional.edtData.Text := ''; view_ApontamentoOperacional.edtTipo.ItemIndex := 0; view_ApontamentoOperacional.tbApontamento.IsLoading := False; view_ApontamentoOperacional.dsApontamento.Enabled := True; view_ApontamentoOperacional.pbApontamento.Visible := False; end; procedure Thread_SalvaApontamentoOperacional.SetupApontamento; var lLog : TStringList; begin lLog := TStringList.Create(); apontamento.ID := view_ApontamentoOperacional.tbApontamentoID_OPERACAO.AsInteger; apontamento.Entregador := view_ApontamentoOperacional.tbApontamentoCOD_ENTREGADOR.AsInteger; apontamento.RoteiroAntigo := view_ApontamentoOperacional.tbApontamentoCOD_ROTEIRO_ANTIGO.AsString; apontamento.Data := view_ApontamentoOperacional.tbApontamentoDAT_OPERACAO.AsDateTime; apontamento.StatusOperacao := view_ApontamentoOperacional.tbApontamentoCOD_STATUS_OPERACAO.AsString; apontamento.RoteiroNovo := view_ApontamentoOperacional.tbApontamentoCOD_ROTEIRO_NOVO.AsString; apontamento.Obs:= view_ApontamentoOperacional.tbApontamentoDES_OBSERVACOES.AsString; apontamento.Planilha := view_ApontamentoOperacional.tbApontamentoDOM_PLANILHA.AsString; apontamento.IDReferencia := view_ApontamentoOperacional.tbApontamentoID_REFERENCIA.AsInteger; apontamento.DataReferencia := view_ApontamentoOperacional.tbApontamentoDAT_REFERENCIA.AsDateTime; lLog.Text := view_ApontamentoOperacional.tbApontamentoDES_LOG.AsString; if apontamento.ID = 0 then begin lLog.Add('> ' + FormatDateTime('dd/mm/yyyy hh:mm:ss', Now) + ' inserido ' + uGlobais.sUsuario); end else begin lLog.Add('> ' + FormatDateTime('dd/mm/yyyy hh:mm:ss', Now) + ' alterado ' + uGlobais.sUsuario); end; apontamento.Log := lLog.Text; end; procedure Thread_SalvaApontamentoOperacional.SalvaApontamento; var apontamento : TApontamentoOperacional; iTotal : Integer; iPos : Integer; sMensagem: String; begin { Place thread code here } try Synchronize(IniciaProcesso); if not Assigned(view_ResultadoProcesso) then begin view_ResultadoProcesso := Tview_ResultadoProcesso.Create(Application); end; view_ResultadoProcesso.Show; Screen.Cursor := crHourGlass; apontamento := TApontamentoOperacional.Create(); apontamentoDAO := TApontamentoOperacionalDAO.Create(); while not view_ApontamentoOperacional.tbApontamento.Eof do begin sMensagem := ''; SetupApontamento; if apontamento.ID = 0 then begin if not apontamentoDAO.Insert(apontamento) then begin sMensagem := 'Erro ao incluir o apontamento do roteiro ' + apontamento.RoteiroAntigo + ' !'; end; end else begin if not apontamentoDAO.Update(apontamento) then begin sMensagem := 'Erro ao alterar o apontamento do roteiro ' + apontamento.RoteiroAntigo + ' !'; end; end; if not sMensagem.IsEmpty then begin view_ResultadoProcesso.edtResultado.Lines.Add(sMensagem); view_ResultadoProcesso.edtResultado.Refresh; end; view_ApontamentoOperacional.tbApontamento.Next; iPos := iPos + 1; FdPos := (iPos / iTotal) * 100; Synchronize(AtualizaProcesso); end; finally view_ApontamentoOperacional.tbApontamento.Close; view_ApontamentoOperacional.tbApontamento.Open; Synchronize(TerminaProcesso); Screen.Cursor := crDefault; apontamentoDAO.Free; end; end; procedure Thread_SalvaApontamentoOperacional.SetupAusencias; var lLog : TStringList; begin lLog := TStringList.Create(); ausencia.ID := view_ApontamentoOperacional.tbAusenciasID_AUSENCIA.AsInteger; ausencia.Data := view_ApontamentoOperacional.tbAusenciasDAT_OPERACAO.AsDateTime; ausencia.Cadastro := view_ApontamentoOperacional.tbAusenciasCOD_CADASTRO.AsInteger; ausencia.StatusOperacao := view_ApontamentoOperacional.tbAusenciasCOD_STATUS_OPERACAO.AsString; ausencia.Obs:= view_ApontamentoOperacional.tbAusenciasDES_OBSERVACOES.AsString; ausencia.IDReferencia := view_ApontamentoOperacional.tbAusenciasID_REFERENCIA.AsInteger; lLog.Text := view_ApontamentoOperacional.tbAusenciasDES_LOG.AsString; if ausencia.ID = 0 then begin lLog.Add('> ' + FormatDateTime('dd/mm/yyyy hh:mm:ss', Now) + ' inserido ' + uGlobais.sUsuario); end else begin lLog.Add('> ' + FormatDateTime('dd/mm/yyyy hh:mm:ss', Now) + ' alterado ' + uGlobais.sUsuario); end; ausencia.Log := lLog.Text; end; procedure Thread_SalvaApontamentoOperacional.SalvaAusencias; var ausencia : TRHOperacionalAusencias; iTotal : Integer; iPos : Integer; sMensagem: String; begin try Synchronize(IniciaProcesso); if not Assigned(view_ResultadoProcesso) then begin view_ResultadoProcesso := Tview_ResultadoProcesso.Create(Application); view_ResultadoProcesso.Show; end; Screen.Cursor := crHourGlass; ausencia := TRHOperacionalAusencias.Create(); ausenciaDAO := TRHOperacionalAusenciasDAO.Create(); while not view_ApontamentoOperacional.tbAusencias.Eof do begin SetupAusencias; if ausencia.ID = 0 then begin if not ausenciaDAO.Insert(ausencia) then begin sMensagem := 'Erro ao incluir a ausencia do entregador ' + view_ApontamentoOperacional.tbAusenciasCOD_CADASTRO.asString + ' !'; end; end else begin if not ausenciaDAO.Update(ausencia) then begin sMensagem := 'Erro ao alterar a ausencia do entregador ' + view_ApontamentoOperacional.tbAusenciasCOD_CADASTRO.asString + ' !'; end; end; view_ApontamentoOperacional.tbAusencias.Next; iPos := iPos + 1; FdPos := (iPos / iTotal) * 100; Synchronize(AtualizaProcesso); end; finally view_ApontamentoOperacional.tbAusencias.Close; view_ApontamentoOperacional.tbAusencias.Open; Synchronize(TerminaProcesso); Screen.Cursor := crDefault; ausenciaDAO.Free; end; end; end.
unit unWebServiceFileUtils; interface uses Types {$ifdef SERVER} ,FileCache {$ENDIF} ; procedure ByteArrayToFile(const ByteArray :TByteDynArray; const FileName :string); {$ifdef SERVER} function FileToByteArray(const FileName :string ) :TByteDynArray; {$ENDIF} implementation uses Math, System.Classes, System.SysUtils; {$ifdef SERVER} var FileCache :TFileCache; {$ENDIF} procedure ByteArrayToFile(const ByteArray :TByteDynArray; const FileName :string); var Count : integer; F : File of Byte; pTemp : Pointer; begin AssignFile( F, FileName ); Rewrite(F); try Count := Length( ByteArray ); pTemp := @ByteArray[0]; BlockWrite(F, pTemp^, Count ); finally CloseFile( F ); end; end; {$ifdef SERVER} function FileToByteArray(const FileName :string) :TByteDynArray; const BLOCK_SIZE = 1024; var BytesRead, BytesToWrite, Count : integer; F : FIle of Byte; pTemp : Pointer; nIndex :integer; begin nIndex := FileCache.IndexOf(FileName); if nIndex = -1 then begin AssignFile( F, FileName ); Reset(F); try Count := FileSize( F ); SetLength(Result, Count ); pTemp := @Result[0]; BytesRead := BLOCK_SIZE; while (BytesRead = BLOCK_SIZE ) do begin BytesToWrite := Min(Count, BLOCK_SIZE); BlockRead(F, pTemp^, BytesToWrite , BytesRead ); pTemp := Pointer(LongInt(pTemp) + BLOCK_SIZE); Count := Count-BytesRead; end; finally CloseFile( F ); end; FileCache.AddFile(FileName,Result); end else Result := FileCache.GetFileData(nIndex); end; initialization FileCache := TFileCache.Create; finalization FileCache.EmptyCache; FreeAndNil(FileCache); {$ENDIF} end.
unit ufrmAddParams; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.StdCtrls, Vcl.Buttons, uReport; Const USER_EDITLISTVIEW = WM_USER + 666; type TfrmAddParams = class(TForm) bbnOk: TBitBtn; bbnCancel: TBitBtn; lvParameters: TListView; procedure FormCreate(Sender: TObject); procedure bbnCancelClick(Sender: TObject); procedure FListViewEditorExit(Sender: TObject); procedure lvParametersClick(Sender: TObject); private { Private declarations } FParams: TCMParams; FLastReportNo: integer; FListViewEditor: TEdit; FLItem: TListitem; procedure CreateParams; procedure loadParams(aReportData: TCMMReportData); procedure UserEditListView(Var Message: TMessage); message USER_EDITLISTVIEW; public { Public declarations } function execute(aReportData: TCMMReportData): TCMParams; end; var frmAddParams: TfrmAddParams; implementation {$R *.dfm} uses commctrl, uReportController; const EDIT_COLUMN = 1; // Index of the column to Edit procedure TfrmAddParams.bbnCancelClick(Sender: TObject); begin // FreeAndNil(FParams); end; procedure TfrmAddParams.CreateParams; var i: integer; Items: TListItems; name, value: string; begin FParams.Clear; Items := lvParameters.Items; for i := 0 to Items.Count - 1 do begin name := Items[i].Caption; value := Items[i].SubItems[0]; FParams.Add(name, value); end; end; function TfrmAddParams.execute(aReportData: TCMMReportData): TCMParams; begin lvParameters.Clear; loadParams(aReportData); if (ShowModal = mrOK) then begin CreateParams; Result := FParams end else Result := nil; end; procedure TfrmAddParams.FListViewEditorExit(Sender: TObject); begin If Assigned(FLItem) Then Begin // assign the vslue of the TEdit to the Subitem FLItem.SubItems[EDIT_COLUMN - 1] := FListViewEditor.Text; FLItem := nil; FListViewEditor.Visible := False; End; end; procedure TfrmAddParams.FormCreate(Sender: TObject); begin lvParameters.Clear; FLastReportNo := -1; FParams := TCMParams.Create(); // create the TEdit and assign the OnExit event FListViewEditor := TEdit.Create(Self); FListViewEditor.Parent := lvParameters; FListViewEditor.OnExit := FListViewEditorExit; FListViewEditor.Visible := False; end; procedure TfrmAddParams.loadParams(aReportData: TCMMReportData); var params: TCMParamsInfo; listItem: TListitem; parName, keys: string; procedure reLoad; var pn: string; begin FParams.Clear; FLastReportNo := aReportData.ReportNo; FListViewEditor.Text := ''; params := aReportData.getAllParameters; for pn in params.keys do begin listItem := lvParameters.Items.Add; listItem.Caption := pn; listItem.SubItems.Add('0'); end; end; begin if FLastReportNo <> aReportData.ReportNo then begin reLoad; end else begin if FParams.Count = 0 then reLoad else for parName in FParams.keys do begin if parName = '' then begin reLoad; exit; end; listItem := lvParameters.Items.Add; listItem.Caption := parName; listItem.SubItems.Add(FParams.Items[parName]); end; end; end; procedure TfrmAddParams.lvParametersClick(Sender: TObject); var LPoint: TPoint; LVHitTestInfo: TLVHitTestInfo; begin LPoint := lvParameters.ScreenToClient(Mouse.CursorPos); ZeroMemory(@LVHitTestInfo, SizeOf(LVHitTestInfo)); LVHitTestInfo.pt := LPoint; // Check if the click was made in the column to edit If (lvParameters.perform(LVM_SUBITEMHITTEST, 0, LPARAM(@LVHitTestInfo)) <> -1) and (LVHitTestInfo.iSubItem = EDIT_COLUMN) Then PostMessage(Self.Handle, USER_EDITLISTVIEW, LVHitTestInfo.iItem, 0) else FListViewEditor.Visible := False; // hide the TEdit end; procedure TfrmAddParams.UserEditListView(var Message: TMessage); var LRect: TRect; begin LRect.Top := EDIT_COLUMN; LRect.Left := LVIR_BOUNDS; lvParameters.perform(LVM_GETSUBITEMRECT, Message.wparam, LPARAM(@LRect)); MapWindowPoints(lvParameters.Handle, FListViewEditor.Parent.Handle, LRect, 2); // get the current Item to edit FLItem := lvParameters.Items[Message.wparam]; // set the text of the Edit FListViewEditor.Text := FLItem.SubItems[EDIT_COLUMN - 1]; // set the bounds of the TEdit FListViewEditor.BoundsRect := LRect; // Show the TEdit FListViewEditor.Visible := True; FListViewEditor.SetFocus; end; end.
unit SNMP; {$WEAKPACKAGEUNIT} interface uses Windows; const /////////////////////////////////////////////////////////////////////////////// // // // ASN/BER Base Types // // // /////////////////////////////////////////////////////////////////////////////// ASN_UNIVERSAL = $00; ASN_APPLICATION = $40; ASN_CONTEXT = $80; ASN_PRIVATE = $C0; ASN_PRIMITIVE = $00; ASN_CONSTRUCTOR = $20; /////////////////////////////////////////////////////////////////////////////// // // // PDU Type Values // // // /////////////////////////////////////////////////////////////////////////////// SNMP_PDU_GET = (ASN_CONTEXT or ASN_CONSTRUCTOR or $0); SNMP_PDU_GETNEXT = (ASN_CONTEXT or ASN_CONSTRUCTOR or $1); SNMP_PDU_RESPONSE = (ASN_CONTEXT or ASN_CONSTRUCTOR or $2); SNMP_PDU_SET = (ASN_CONTEXT or ASN_CONSTRUCTOR or $3); SNMP_PDU_V1TRAP = (ASN_CONTEXT or ASN_CONSTRUCTOR or $4); SNMP_PDU_GETBULK = (ASN_CONTEXT or ASN_CONSTRUCTOR or $5); SNMP_PDU_INFORM = (ASN_CONTEXT or ASN_CONSTRUCTOR or $6); SNMP_PDU_TRAP = (ASN_CONTEXT or ASN_CONSTRUCTOR or $7); /////////////////////////////////////////////////////////////////////////////// // // // SNMP Simple Syntax Values // // // /////////////////////////////////////////////////////////////////////////////// ASN_INTEGER = (ASN_UNIVERSAL or ASN_PRIMITIVE or $02); ASN_BITS = (ASN_UNIVERSAL or ASN_PRIMITIVE or $03); ASN_OCTETSTRING = (ASN_UNIVERSAL or ASN_PRIMITIVE or $04); ASN_NULL = (ASN_UNIVERSAL or ASN_PRIMITIVE or $05); ASN_OBJECTIDENTIFIER = (ASN_UNIVERSAL or ASN_PRIMITIVE or $06); ASN_INTEGER32 = ASN_INTEGER; /////////////////////////////////////////////////////////////////////////////// // // // SNMP Constructor Syntax Values // // // /////////////////////////////////////////////////////////////////////////////// ASN_SEQUENCE = (ASN_UNIVERSAL or ASN_CONSTRUCTOR or $10); ASN_SEQUENCEOF = ASN_SEQUENCE; /////////////////////////////////////////////////////////////////////////////// // // // SNMP Application Syntax Values // // // /////////////////////////////////////////////////////////////////////////////// ASN_IPADDRESS = (ASN_APPLICATION or ASN_PRIMITIVE or $00); ASN_COUNTER32 = (ASN_APPLICATION or ASN_PRIMITIVE or $01); ASN_GAUGE32 = (ASN_APPLICATION or ASN_PRIMITIVE or $02); ASN_TIMETICKS = (ASN_APPLICATION or ASN_PRIMITIVE or $03); ASN_OPAQUE = (ASN_APPLICATION or ASN_PRIMITIVE or $04); ASN_COUNTER64 = (ASN_APPLICATION or ASN_PRIMITIVE or $06); ASN_UNSIGNED32 = (ASN_APPLICATION or ASN_PRIMITIVE or $07); /////////////////////////////////////////////////////////////////////////////// // // // SNMP Exception Conditions // // // /////////////////////////////////////////////////////////////////////////////// SNMP_EXCEPTION_NOSUCHOBJECT = (ASN_CONTEXT or ASN_PRIMITIVE or $00); SNMP_EXCEPTION_NOSUCHINSTANCE = (ASN_CONTEXT or ASN_PRIMITIVE or $01); SNMP_EXCEPTION_ENDOFMIBVIEW = (ASN_CONTEXT or ASN_PRIMITIVE or $02); /////////////////////////////////////////////////////////////////////////////// // // // SNMP Request Types (used in SnmpExtensionQueryEx) // // // /////////////////////////////////////////////////////////////////////////////// SNMP_EXTENSION_GET = SNMP_PDU_GET; SNMP_EXTENSION_GET_NEXT = SNMP_PDU_GETNEXT; SNMP_EXTENSION_GET_BULK = SNMP_PDU_GETBULK; SNMP_EXTENSION_SET_TEST = (ASN_PRIVATE or ASN_CONSTRUCTOR or $0); SNMP_EXTENSION_SET_COMMIT = SNMP_PDU_SET; SNMP_EXTENSION_SET_UNDO = (ASN_PRIVATE or ASN_CONSTRUCTOR or $1); SNMP_EXTENSION_SET_CLEANUP = (ASN_PRIVATE or ASN_CONSTRUCTOR or $2); /////////////////////////////////////////////////////////////////////////////// // // // SNMP Error Codes // // // /////////////////////////////////////////////////////////////////////////////// SNMP_ERRORSTATUS_NOERROR = 0; SNMP_ERRORSTATUS_TOOBIG = 1; SNMP_ERRORSTATUS_NOSUCHNAME = 2; SNMP_ERRORSTATUS_BADVALUE = 3; SNMP_ERRORSTATUS_READONLY = 4; SNMP_ERRORSTATUS_GENERR = 5; SNMP_ERRORSTATUS_NOACCESS = 6; SNMP_ERRORSTATUS_WRONGTYPE = 7; SNMP_ERRORSTATUS_WRONGLENGTH = 8; SNMP_ERRORSTATUS_WRONGENCODING = 9; SNMP_ERRORSTATUS_WRONGVALUE = 10; SNMP_ERRORSTATUS_NOCREATION = 11; SNMP_ERRORSTATUS_INCONSISTENTVALUE = 12; SNMP_ERRORSTATUS_RESOURCEUNAVAILABLE = 13; SNMP_ERRORSTATUS_COMMITFAILED = 14; SNMP_ERRORSTATUS_UNDOFAILED = 15; SNMP_ERRORSTATUS_AUTHORIZATIONERROR = 16; SNMP_ERRORSTATUS_NOTWRITABLE = 17; SNMP_ERRORSTATUS_INCONSISTENTNAME = 18; /////////////////////////////////////////////////////////////////////////////// // // // SNMPv1 Trap Types // // // /////////////////////////////////////////////////////////////////////////////// SNMP_GENERICTRAP_COLDSTART = 0; SNMP_GENERICTRAP_WARMSTART = 1; SNMP_GENERICTRAP_LINKDOWN = 2; SNMP_GENERICTRAP_LINKUP = 3; SNMP_GENERICTRAP_AUTHFAILURE = 4; SNMP_GENERICTRAP_EGPNEIGHLOSS = 5; SNMP_GENERICTRAP_ENTERSPECIFIC = 6; /////////////////////////////////////////////////////////////////////////////// // // // SNMP Access Types // // // /////////////////////////////////////////////////////////////////////////////// SNMP_ACCESS_NONE = 0; SNMP_ACCESS_NOTIFY = 1; SNMP_ACCESS_READ_ONLY = 2; SNMP_ACCESS_READ_WRITE = 3; SNMP_ACCESS_READ_CREATE = 4; /////////////////////////////////////////////////////////////////////////////// // // // SNMP API Return Code Definitions // // // /////////////////////////////////////////////////////////////////////////////// SNMPAPI_NOERROR = TRUE; SNMPAPI_ERROR = FALSE; /////////////////////////////////////////////////////////////////////////////// // // // SNMP Debugging Definitions // // // /////////////////////////////////////////////////////////////////////////////// SNMP_LOG_SILENT = $0; SNMP_LOG_FATAL = $1; SNMP_LOG_ERROR = $2; SNMP_LOG_WARNING = $3; SNMP_LOG_TRACE = $4; SNMP_LOG_VERBOSE = $5; SNMP_OUTPUT_TO_CONSOLE = $1; SNMP_OUTPUT_TO_LOGFILE = $2; SNMP_OUTPUT_TO_EVENTLOG = $4; // no longer supported SNMP_OUTPUT_TO_DEBUGGER = $8; type /////////////////////////////////////////////////////////////////////////////// // // // SNMP Type Definitions // // // /////////////////////////////////////////////////////////////////////////////// // #pragma pack (4) SNMPAPI = Integer; AsnOctetString = record stream : PBYTE; length : UINT; dynamic : BOOL; end; PAsnOctetString = ^AsnOctetString; AsnObjectIdentifier = record idLength : UINT; ids : PUINT; end; PAsnObjectIdentifier = ^AsnObjectIdentifier; AsnInteger32 = LongInt; AsnUnsigned32 = ULONG; AsnCounter64 = ULARGE_INTEGER; AsnCounter32 = AsnUnsigned32; AsnGauge32 = AsnUnsigned32; AsnTimeticks = AsnUnsigned32; AsnBits = AsnOctetString; AsnSequence = AsnOctetString; AsnImplicitSequence = AsnOctetString; AsnIPAddress = AsnOctetString; AsnNetworkAddress = AsnOctetString; AsnDisplayString = AsnOctetString; AsnOpaque = AsnOctetString; AsnInteger = AsnInteger32; AsnAny = record case asnType : BYTE of 0 : (number : AsnInteger32); 1 : (unsigned32 : AsnUnsigned32); 2 : (counter64 : AsnCounter64); 3 : (_string : AsnOctetString); 4 : (bits : AsnBits); 5 : (_object : AsnObjectIdentifier); 6 : (sequence : AsnSequence); 7 : (address : AsnIPAddress); 8 : (counter : AsnCounter32); 9 : (guage : AsnGauge32); 10: (ticks : AsnTimeticks); 11: (arbitrary : AsnOpaque) end; PAsnAny = ^AsnAny; AsnObjectName = AsnObjectIdentifier; AsnObjectSyntax = AsnAny; SnmpVarBind = record name : AsnObjectName; value : AsnObjectSyntax; end; PSnmpVarBind = ^SnmpVarBind; SnmpVarBindList = record list : PSnmpVarBind; len : UINT; end; PSnmpVarBindList = ^SnmpVarBindList; /////////////////////////////////////////////////////////////////////////////// // // // SNMP Extension API Type Definitions // // // /////////////////////////////////////////////////////////////////////////////// PFNSNMPEXTENSIONINIT = function ( dwUpTimeReference : DWORD; var phSubagentTrapEvent : THandle; var pFirstSupportedRegion : AsnObjectIdentifier) : BOOL; stdcall; PFNSNMPEXTENSIONINITEX = function ( var pNextSupportedRegion : AsnObjectIdentifier) : BOOL; stdcall; PFNSNMPEXTENSIONQUERY = function ( bPduType : BYTE; var pVarBindList : SnmpVarBindList; var pErrorStatus : AsnInteger32; var pErrorIndex : AsnInteger32) : BOOL; stdcall; PFNSNMPEXTENSIONQUERYEX = function ( nRequestType : UINT; nTransactionId : UINT; var pVarBindList : SnmpVarBindList; var pContextInfo : AsnOctetString; var pErrorStatus : AsnInteger32; var pErrorIndex : AsnInteger32) : BOOL; stdcall; PFNSNMPEXTENSIONTRAP = function ( var pEnterpriseOld : AsnObjectIdentifier; var pGenerticTrapId : AsnInteger32; var pSpecificTrapId : AsnInteger32; var pTimeStamp : AsnTimeticks; var pVarBindList : SnmpVarBindList) : BOOL; stdcall; PFNSNMPEXTENSIONCLOSE = procedure; stdcall; const /////////////////////////////////////////////////////////////////////////////// // // // Miscellaneous definitions // // // /////////////////////////////////////////////////////////////////////////////// DEFAULT_SNMP_PORT_UDP = 161; DEFAULT_SNMP_PORT_IPX = 36879; DEFAULT_SNMPTRAP_PORT_UDP = 162; DEFAULT_SNMPTRAP_PORT_IPX = 36880; SNMP_MAX_OID_LEN = 128; /////////////////////////////////////////////////////////////////////////////// // // // API Error Code Definitions // // // /////////////////////////////////////////////////////////////////////////////// SNMP_MEM_ALLOC_ERROR = 1; SNMP_BERAPI_INVALID_LENGTH = 10; SNMP_BERAPI_INVALID_TAG = 11; SNMP_BERAPI_OVERFLOW = 12; SNMP_BERAPI_SHORT_BUFFER = 13; SNMP_BERAPI_INVALID_OBJELEM = 14; SNMP_PDUAPI_UNRECOGNIZED_PDU = 20; SNMP_PDUAPI_INVALID_ES = 21; SNMP_PDUAPI_INVALID_GT = 22; SNMP_AUTHAPI_INVALID_VERSION = 30; SNMP_AUTHAPI_INVALID_MSG_TYPE = 31; SNMP_AUTHAPI_TRIV_AUTH_FAILED = 32; /////////////////////////////////////////////////////////////////////////////// // // // SNMP Extension API Prototypes // // // /////////////////////////////////////////////////////////////////////////////// function SnmpExtensionInit( dwUptimeReference : DWORD; var phSubagentTrapEvent : THandle; var pFirstSupportedRegion : AsnObjectIdentifier) : BOOL; stdcall; function SnmpExtensionInitEx( var pNextSupportedRegion : AsnObjectIdentifier) : BOOL; stdcall; function SnmpExtensionQuery( bPduType : BYTE; var pVarBindList : SnmpVarBindList; var pErrorStatus : AsnInteger32; var pErrorIndex : AsnInteger32) : BOOL; stdcall; function SnmpExtensionQueryEx( nRequestType : UINT; nTransactionId : UINT; var pVarBindList : SnmpVarBindList; var pContextInfo : AsnOctetString; var pErrorStatus : AsnInteger32; var pErrorIndex : AsnInteger32) : BOOL; stdcall; function SnmpExtensionTrap( var pEnterpriseOid : AsnObjectIdentifier; var pGenericTrapId : AsnInteger32; var pSpecificTrapId : AsnInteger32; var pTimestamp : AsnTimeticks; var pVarBindList : SnmpVarBindList) : BOOL; stdcall; procedure SnmpExtensionClose; stdcall; /////////////////////////////////////////////////////////////////////////////// // // // SNMP API Prototypes // // // /////////////////////////////////////////////////////////////////////////////// function SnmpUtilOidCpy( var pOidDst : AsnObjectIdentifier; var pOidSrc : AsnObjectIdentifier) : SNMPAPI; stdcall; function SnmpUtilOidAppend( var pOidDst : AsnObjectIdentifier; var pOidSrc : AsnObjectIdentifier) : SNMPAPI; stdcall; function SnmpUtilOidNCmp( var pOid1 : AsnObjectIdentifier; var pOid2 : AsnObjectIdentifier; nSubIds : UINT) : SNMPAPI; stdcall; function SnmpUtilOidCmp( var pOid1 : AsnObjectIdentifier; var pOid2 : AsnObjectIdentifier) : SNMPAPI; stdcall; procedure SnmpUtilOidFree(var pOid : AsnObjectIdentifier); stdcall; function SnmpUtilOctetsCmp( var pOctets1 : AsnOctetString; var pOctets2 : AsnOctetString) : SNMPAPI; stdcall; function SnmpUtilOctetsNCmp( var pOctets1 : AsnOctetString; var pOctets2 : AsnOctetString; nChars : UINT) : SNMPAPI; stdcall; function SnmpUtilOctetsCpy( var pOctetsDst : AsnOctetString; var pOctetsSrc : AsnOctetString) : SNMPAPI; stdcall; procedure SnmpUtilOctetsFree( var pOctets : AsnOctetString ); stdcall; function SnmpUtilAsnAnyCpy( var pAnyDst : AsnAny; var pAnySrc : AsnAny) : SNMPAPI; stdcall; procedure SnmpUtilAsnAnyFree( var pAny : AsnAny); stdcall; function SnmpUtilVarBindCpy( var pVbDst : SnmpVarBind; var pVbSrc : SnmpVarBind) : SNMPAPI; stdcall; procedure SnmpUtilVarBindFree( var pVb : SnmpVarBind ); stdcall; function SnmpUtilVarBindListCpy( var pVblDst : SnmpVarBindList; var pVblSrc : SnmpVarBindList) : SNMPAPI; stdcall; procedure SnmpUtilVarBindListFree( var pVbl : SnmpVarBindList); stdcall; procedure SnmpUtilMemFree(pMem : pointer); stdcall; function SnmpUtilMemAlloc(nBytes : UINT) : pointer; stdcall; function SnmpUtilMemReAlloc(pMem : pointer; nBytes : UINT) : pointer; stdcall; function SnmpUtilOidToA(var Oid : AsnObjectIdentifier) : PChar; stdcall; function SnmpUtilIdsToA(Ids : PUINT; idLength : UINT) : PChar; stdcall; procedure SnmpUtilPrintOid(var Oid : AsnObjectIdentifier); stdcall; procedure SnmpUtilPrintAsnAny(var pAny : AsnAny); stdcall; function SnmpSvcGetUptime : DWORD; stdcall; procedure SnmpSvcSetLogLevel (nLogLevel : Integer); stdcall; procedure SnmpSvcSetLogType (nLogType : Integer); stdcall; /////////////////////////////////////////////////////////////////////////////// // // // SNMP Debugging Prototypes // // // /////////////////////////////////////////////////////////////////////////////// procedure SnmpUtilDbgPrint( LogLevel : Integer; szFormat : PChar); stdcall; // Matches the docs, but not snmp.h implementation const snmpapidll = 'snmpapi.dll'; function SnmpExtensionInit; external snmpapidll; function SnmpExtensionInitEx; external snmpapidll; function SnmpExtensionQuery; external snmpapidll; function SnmpExtensionQueryEx; external snmpapidll; function SnmpExtensionTrap; external snmpapidll; procedure SnmpExtensionClose; external snmpapidll; function SnmpUtilOidCpy; external snmpapidll; function SnmpUtilOidAppend; external snmpapidll; function SnmpUtilOidNCmp; external snmpapidll; function SnmpUtilOidCmp; external snmpapidll; procedure SnmpUtilOidFree; external snmpapidll; function SnmpUtilOctetsCmp; external snmpapidll; function SnmpUtilOctetsNCmp; external snmpapidll; function SnmpUtilOctetsCpy; external snmpapidll; procedure SnmpUtilOctetsFree; external snmpapidll; function SnmpUtilAsnAnyCpy; external snmpapidll; procedure SnmpUtilAsnAnyFree; external snmpapidll; function SnmpUtilVarBindCpy; external snmpapidll; procedure SnmpUtilVarBindFree; external snmpapidll; function SnmpUtilVarBindListCpy; external snmpapidll; procedure SnmpUtilVarBindListFree; external snmpapidll; procedure SnmpUtilMemFree; external snmpapidll; function SnmpUtilMemAlloc; external snmpapidll; function SnmpUtilMemReAlloc; external snmpapidll; function SnmpUtilOidToA; external snmpapidll; function SnmpUtilIdsToA; external snmpapidll; procedure SnmpUtilPrintOid; external snmpapidll; procedure SnmpUtilPrintAsnAny; external snmpapidll; function SnmpSvcGetUptime; external snmpapidll; procedure SnmpSvcSetLogLevel; external snmpapidll; procedure SnmpSvcSetLogType; external snmpapidll; procedure SnmpUtilDbgPrint; external snmpapidll; end.
unit ClassInfoTests; interface uses InfraCommonIntf, TestFrameWork; type TClassInfoTests = class(TTestCase) private FPersonInfo: IClassInfo; FStudentInfo: IClassInfo; protected procedure SetUp; override; procedure TearDown; override; published procedure TestFamilyID; procedure TestFullName; procedure TestTypeID; procedure TestImplClass; procedure TestName; procedure TestOwner; procedure TestFindMembers; procedure TestConstructors; procedure TestMemberInfo; procedure TestMembers; procedure TestMethodInfo; procedure TestMethods; procedure TestProperties; procedure TestProperty; procedure TestPropertyInfo; procedure TestSuperClass; procedure TestIsSubClassOf; procedure TestSetRelation; end; implementation uses SysUtils, InfraConsts, InfraValueTypeIntf, ReflectModel, ReflectModelIntf; { TClassInfoTests } procedure TClassInfoTests.SetUp; begin inherited; TSetupModel.RegisterAddress; FPersonInfo := TSetupModel.RegisterPerson; FStudentInfo := TSetupModel.RegisterStudent; TSetupModel.RegisterPersonAddressRelation(FPersonInfo); end; procedure TClassInfoTests.TearDown; begin inherited; TSetupModel.RemoveTypeInfo(IPerson); TSetupModel.RemoveTypeInfo(IAddress); TSetupModel.RemoveTypeInfo(IStudent); end; procedure TClassInfoTests.TestConstructors; var i : integer; it : IMethodInfoIterator; begin i := 0; it := FPersonInfo.GetConstructors; CheckNotNull(It, 'Constructors''s Iterator not created'); while not it.IsDone do begin Inc(i); it.Next; end; CheckEquals(PERSON_CONSTRUCTOR_COUNT, i, 'Wrong constructors count'); end; procedure TClassInfoTests.TestFamilyID; begin CheckFalse(IsEqualGUID(FPersonInfo.FamilyID, NullGuid), 'Empty FamilyID'); Check(IsEqualGUID(FPersonInfo.FamilyID, IInfraObject), 'Wrong FamilyID, Should be IInfraObject'); end; procedure TClassInfoTests.TestFindMembers; var i: integer; It: IMemberInfoIterator; begin i := 0; It := FPersonInfo.FindMembers(mtAll); CheckNotNull(It, '(mtAll) FindMembers''s Iterator not created'); if Assigned(It) then begin while not It.IsDone do begin Inc(i); It.Next; end; CheckEquals( PERSON_PROPERTIES_COUNT+ PERSON_METHODS_COUNT+ PERSON_CONSTRUCTOR_COUNT, i, 'Wrong findmembers mtAll count'); end; i := 0; It := FPersonInfo.FindMembers([mtProperty]); CheckNotNull(It, '(mtProperty) FindMembers''s Iterator to property not created'); if Assigned(It) then begin while not It.IsDone do begin Inc(i); It.Next; end; CheckEquals(PERSON_PROPERTIES_COUNT, i, 'Wrong FindMembers(Properties) count'); end; i := 0; It := FPersonInfo.FindMembers([mtMethod]); CheckNotNull(It, '(mtMethod) FindMembers''s Iterator to Method not created'); if Assigned(It) then begin while not It.IsDone do begin Inc(i); It.Next; end; CheckEquals(PERSON_METHODS_COUNT, i, 'Wrong FindMembers(Methods) count'); end; end; procedure TClassInfoTests.TestFullName; begin CheckEquals(FPersonInfo.FullName, 'TPerson', 'ClassInfo FullName incorrect to Person'); CheckEquals(FStudentInfo.FullName, 'TStudent', 'ClassInfo FullName incorrect to Student'); // *** adicionar um CheckEquals para um objeto que tenha um fullname <> name end; procedure TClassInfoTests.TestImplClass; begin CheckEquals(FPersonInfo.ImplClass, TPerson, 'ImplClass diferent of Person'); end; procedure TClassInfoTests.TestIsSubClassOf; begin with TypeService do begin CheckTrue(FStudentInfo.IsSubClassOf(GetType(IPerson)), 'Student should be subclass of Person'); CheckTrue(FStudentInfo.IsSubClassOf(GetType(IInfraObject)), 'Student should be subclass of InfraObject'); CheckFalse(FStudentInfo.IsSubClassOf(GetType(IAddress)), 'Student shouldn''''t be subclass of Address'); end; end; procedure TClassInfoTests.TestMemberInfo; var FMember : IMemberInfo; begin FMember := FPersonInfo.GetMemberInfo('GetEmail'); CheckNotNull(FMember, 'GetMail member should be in Person'); end; procedure TClassInfoTests.TestMembers; var i : integer; it : IMemberInfoIterator; begin i := 0; it := FPersonInfo.GetMembers; CheckNotNull(It, 'Members''s Iterator not created'); while not it.IsDone do begin Inc(i); it.Next; end; CheckEquals( PERSON_METHODS_COUNT+ PERSON_PROPERTIES_COUNT+ PERSON_CONSTRUCTOR_COUNT, i, 'Wrong members count'); end; procedure TClassInfoTests.TestMethodInfo; var FMethod : IMethodInfo; begin FMethod := FPersonInfo.GetMethodInfo('SetName'); CheckNotNull(FMethod, 'SetName Method should be in Person'); FMethod := FPersonInfo.GetMethodInfo('Create'); CheckNotNull(FMethod, 'Create constructor should be in Person'); end; procedure TClassInfoTests.TestMethods; var i: integer; It: IMethodInfoIterator; begin i := 0; It := FPersonInfo.GetMethods; CheckNotNull(It, 'Methods''s Iterator not created'); while not It.IsDone do begin Inc(i); It.Next; end; CheckEquals(PERSON_METHODS_COUNT, i, 'Wrong methods count'); end; procedure TClassInfoTests.TestName; begin CheckEquals(FPersonInfo.Name, 'TPerson', 'Incorrect Personīs Class Name'); CheckEquals(FStudentInfo.Name, 'TStudent', 'Incorrect Studentīs Class Name'); end; procedure TClassInfoTests.TestOwner; begin CheckNull(FPersonInfo.Owner, 'Perssonīs Owner should be null'); CheckNull(FStudentInfo.Owner, 'Studentīs Owner should be null'); // *** ver uma classe que teria o owner <> null end; procedure TClassInfoTests.TestProperties; var i: integer; It: IPropertyInfoIterator; begin i := 0; It := FPersonInfo.GetProperties; CheckNotNull(It, 'PropertyInfo Iterator not created'); if Assigned(It) then while not It.IsDone do begin Inc(i); It.Next; end; CheckEquals(PERSON_PROPERTIES_COUNT, i, 'Wrong properties count'); end; procedure TClassInfoTests.TestProperty; var Value: IInfraString; Pessoa: IPerson; begin Pessoa := TPerson.Create; Pessoa.Name.AsString := 'Marcos'; Pessoa.Email.AsString := 'mrbar2000@gmail.com'; Value := FPersoninfo.GetProperty(Pessoa as IElement, 'Name') as IInfraString; CheckEquals(Pessoa.Name.AsString, Value.AsString, 'Wrong personīs name getting by reflection'); Value := FPersoninfo.GetProperty(Pessoa as IElement, 'Email') as IInfraString; CheckEquals(Pessoa.Email.AsString, Value.AsString, 'Wrong personīs mail getting by reflection'); Value := FPersoninfo.GetProperty(Pessoa as IElement, 'Address.Street') as IInfraString; CheckEquals(Pessoa.Address.Street.AsString, Value.AsString, 'Wrong person''''s Address.Street getting by reflection'); Value := FPersoninfo.GetProperty(Pessoa as IElement, 'Address.Quarter') as IInfraString; CheckEquals(Pessoa.Address.Quarter.AsString, Value.AsString, 'Wrong person''''s Address.Quarter getting by reflection'); end; procedure TClassInfoTests.TestPropertyInfo; var FProperty: IPropertyInfo; begin FProperty := FPersonInfo.GetPropertyInfo('Email'); CheckNotNull(FProperty, 'Email property should be in Person'); FProperty := FStudentInfo.GetPropertyInfo('Email'); CheckNotNull(FProperty, 'Email property should be in Student'); FProperty := FPersonInfo.GetPropertyInfo('Address.City'); CheckNotNull(FProperty, 'Address.City property should be in Person'); FProperty := FStudentInfo.GetPropertyInfo('Address.City'); CheckNotNull(FProperty, 'Address.City property should be in Student'); end; procedure TClassInfoTests.TestSetRelation; begin // *** Testar aqui relacoes criadas a partir de: // - TClassInfo.SetRelation(SetRelation(const pPropertyName: string;...); // - TClassInfo.SetRelation(const pPropertyInfo: IPropertyInfo;...); end; procedure TClassInfoTests.TestSuperClass; begin with TypeService do begin CheckTrue(FPersonInfo.SuperClass = GetType(IInfraObject), 'Person''''s SuperClass diferent of IInfraObject'); CheckTrue(FStudentInfo.SuperClass = GetType(IPerson), 'Student''''s SuperClass diferent of IPerson'); end; end; procedure TClassInfoTests.TestTypeID; begin CheckTrue(IsEqualGUID(FPersonInfo.TypeID, IPerson), 'TypeID diferent of Person'); end; initialization TestFramework.RegisterTest('InfraReflectTests Suite', TClassInfoTests.Suite); end.
unit Domain.Entity.Entities; interface uses System.Classes, Dialogs, SysUtils, EF.Mapping.Base, EF.Core.Types, EF.Mapping.Atributes, Domain.ValuesObject.CPF, Domain.Entity.Cliente; type [Table('Endereco')] TEndereco = class( TEntityBase ) private FLogradouro: TString; FPessoaId:TInteger; public [Column('Logradouro','varchar(50)',true)] property Logradouro: TString read FLogradouro write FLogradouro; [Column('PessoaId','integer',false)] property PessoaId: TInteger read FPessoaId write FPessoaId; end; [Table('Pessoa')] TPessoa = class( TEntityBase) private FNome: TString; FSalario: TFloat; FEndereco: TEndereco; public constructor Create; published [Column('Nome','varchar(50)',true)] property Nome: TString read FNome write FNome; [Reference('Pessoa.Id = Endereco.PessoaId')] property Endereco:TEndereco read FEndereco write FEndereco; [Column('Salario','float',true)] property Salario: TFloat read FSalario write FSalario; end; [Table('PessoaFisica')] TPessoaFisica = class( TPessoa ) private FCPFCNPJ: TCPF; FIdade: TInteger; FComissao: TFloat; FDataNascimento: TDate; published [Column('CPF','varchar(11)',true)] property CPFCNPJ: TCPF read FCPFCNPJ write FCPFCNPJ; [Column('Idade','integer',true)] property Idade: TInteger read FIdade write FIdade; [Column('Comissao','float', true)] property Comissao: TFloat read FComissao write FComissao; [Column('DataNascimento','Datetime',true)] property DataNascimento:TDate read FDataNascimento write FDataNascimento; end; [Table('PessoaJuridica')] TPessoaJuridica = class( TPessoa ) private FCNPJ: TString; published [Column('CNPJ','varchar(15)',true)] property CNPJ: TString read FCNPJ write FCNPJ; end; [Table('Produto')] TProduto = class ( TEntityBase ) private FDescricao: TString; FUNidade:TString; FPrecoVenda:TFloat; published [Column('Descricao','varchar(50)',true)] [MaxLength(20)] property Descricao: TString read FDescricao write FDescricao; [Column('Unidade','varchar(5)',true)] [Default('UN')] property Unidade: TString read FUnidade write FUnidade; [Column('PrecoVenda','float',true)] //[EntityDefault('0')] property PrecoVenda: TFloat read FPrecoVenda write FPrecoVenda; end; TItens = class(TEntityBase) private FProduto: TProduto; FDescricao: TString; public [Reference('IdProduto=Produto.Id')] property Produto: TProduto read FProduto write FProduto; [Column('Descricao','', true)] property Descricao: TString read FDescricao write FDescricao; constructor Create; end; [Table('ItensOrcamento')] TItensOrcamento = class(TItens) private FIdProduto: TInteger; FValor: TFloat; FQuantidade: TFloat; FIdOrcamento: TInteger; FDescricao:TString; public //[EntityField('IdOrcamento','integer',true,true)] property IdOrcamento :TInteger read FIdOrcamento write FIdOrcamento; published //[EntityField('Quantidade','Float', true)] property Quantidade: TFloat read FQuantidade write FQuantidade; //[EntityField('Valor','Float', true)] property Valor: TFloat read FValor write FValor; //[EntityField('IdProduto','integer', true, true )] property IdProduto: TInteger read FIdProduto write FIdProduto; end; [Table('Orcamento')] TOrcamento = class ( TEntityBase ) private FIdCliente: TInteger; FData: TDate; FCliente:TCliente; public [Reference('IdCliente=Clientes.Id')] property Cliente: TCliente read FCliente write FCliente; constructor Create; published //[EntityField('Data','date',true)] property Data:TDate read FData write FData; //[EntityField('IdCliente','integer',true)] property IdCliente: TInteger read FIdCliente write FIdCliente; end; //Classe mapeada! [Table('ClassificacaoPessoa')] TClassificacaoPessoa = class(TEntityBase) private FDescricao: TString; public [Column('Descricao','varchar(20)',false)] property Descricao:TString read FDescricao write FDescricao; end; implementation { TEntityBase } { Titens } constructor Titens.Create; begin inherited; FProduto:= TProduto.Create; end; { TPessoa } constructor TPessoa.Create; begin inherited; FEndereco:= TEndereco.Create; end; { TOrcamento } constructor TOrcamento.Create; begin inherited; FCliente:= TCliente.Create; end; end.
unit SourceComplexityCalculatorTest; interface uses Classes, SysUtils, TestFramework, SourceComplexityCalculator; type TSourceComplexityCalculatorTest = class (TTestCase) protected procedure CheckComplexity(Source: String; ProcName: String; ExpectedComplexity, ExpectedLinesOfCode, ExpectedStatementsCount: Integer); published procedure TestSimple; procedure TestComplex; procedure TestIfStatement; procedure TestIfElseStatement; procedure TestIfElseIfStatement; procedure TestIfElseIfElseStatement; procedure TestForLoop; procedure TestWhileLoop; procedure TestRepeatUntilLoop; procedure TestCaseBlock; procedure TestCaseElseBlock; procedure TestTryfinallyBlock; procedure TestTryExceptBlock; procedure TestTryExceptOnBlock; end; implementation uses PascalParser; { TSourceComplexityCalculatorTest } { Protected declarations } procedure TSourceComplexityCalculatorTest.CheckComplexity(Source: String; ProcName: String; ExpectedComplexity, ExpectedLinesOfCode, ExpectedStatementsCount: Integer); var SourceContainer: TStrings; Parser: TPascalParser; SCC: TSourceComplexityCalculator; begin SourceContainer := TStringList.Create; try SourceContainer.Text := Source; Parser := TPascalParser.Create; Parser.Parse(SourceContainer); try SCC := TSourceComplexityCalculator.Create(Parser.Root); try CheckEquals(ProcName, SCC.Functions[0]); CheckEquals(ExpectedComplexity, SCC.Complexity(ProcName)); CheckEquals(ExpectedLinesOfCode, SCC.LinesOfCode(ProcName)); CheckEquals(ExpectedStatementsCount, SCC.Complexity(ProcName)); finally SCC.Free; end; finally Parser.Free; end; finally SourceContainer.Free; end; end; { Published declarations } procedure TSourceComplexityCalculatorTest.TestSimple; const SOURCE = 'unit test; interface procedure testme; implementation procedure testme; begin end; end.'; begin CheckComplexity(SOURCE, 'testme', 1, 1, 1); end; procedure TSourceComplexityCalculatorTest.TestComplex; const SOURCE = 'unit test;'#13#10'interface'#13#10'procedure testme;'#13#10'implementation'#13#10'procedure testme;'#13#10 + 'begin'#13#10 + 'if a < b then Beep;'#13#10 + 'if a < b then Beep else Beep;'#13#10 + 'if a < b then Beep else if a > b then Beep else Beep;'#13#10 + 'for i := 0 to 100 do Beep;'#13#10 + 'case i of 1: ; end;'#13#10 + 'case i of 1: ; 2: ; end;'#13#10 + 'case i of 1: ; else Beep; end;'#13#10 + 'case i of 1: ; 2: ; else Beep; end;'#13#10 + 'try finally end;'#13#10 + 'try except end;'#13#10 + 'try except on E: Exception do end;'#13#10 + 'end; end.'; begin CheckComplexity(SOURCE, 'testme', 22, 14, 22); end; procedure TSourceComplexityCalculatorTest.TestIfStatement; const SOURCE = 'unit test; interface procedure testme; implementation procedure testme; begin if a < b then Beep; end; end.'; begin CheckComplexity(SOURCE, 'testme', 2, 1, 2); end; procedure TSourceComplexityCalculatorTest.TestIfElseStatement; const SOURCE = 'unit test; interface procedure testme; implementation procedure testme; begin if a < b then Beep else Beep; end; end.'; begin CheckComplexity(SOURCE, 'testme', 3, 1, 3); end; procedure TSourceComplexityCalculatorTest.TestIfElseIfStatement; const SOURCE = 'unit test; interface procedure testme; implementation procedure testme; begin if a < b then Beep else if a > b then Beep; end; end.'; begin CheckComplexity(SOURCE, 'testme', 3, 1, 3); end; procedure TSourceComplexityCalculatorTest.TestIfElseIfElseStatement; const SOURCE = 'unit test; interface procedure testme; implementation procedure testme; begin if a < b then Beep else if a > b then Beep else Beep; end; end.'; begin CheckComplexity(SOURCE, 'testme', 4, 1, 4); end; procedure TSourceComplexityCalculatorTest.TestForLoop; const SOURCE = 'unit test; interface procedure testme; implementation procedure testme; begin for i := 0 to 100 do Beep; end; end.'; begin CheckComplexity(SOURCE, 'testme', 2, 1, 2); end; procedure TSourceComplexityCalculatorTest.TestWhileLoop; const SOURCE = 'unit test; interface procedure testme; implementation procedure testme; begin while false do Beep; end; end.'; begin CheckComplexity(SOURCE, 'testme', 2, 1, 2); end; procedure TSourceComplexityCalculatorTest.TestRepeatUntilLoop; const SOURCE = 'unit test; interface procedure testme; implementation procedure testme; begin repeat Beep; until False; end; end.'; begin CheckComplexity(SOURCE, 'testme', 2, 1, 2); end; procedure TSourceComplexityCalculatorTest.TestCaseBlock; const SOURCE1 = 'unit test; interface procedure testme; implementation procedure testme; begin case i of 1: ; end; end; end.'; SOURCE2 = 'unit test; interface procedure testme; implementation procedure testme; begin case i of 1: ; 2: ; end; end; end.'; begin CheckComplexity(SOURCE1, 'testme', 2, 1, 2); CheckComplexity(SOURCE2, 'testme', 3, 1, 3); end; procedure TSourceComplexityCalculatorTest.TestCaseElseBlock; const SOURCE1 = 'unit test; interface procedure testme; implementation procedure testme; begin case i of 1: ; else Beep; end; end; end.'; SOURCE2 = 'unit test; interface procedure testme; implementation procedure testme; begin case i of 1: ; 2: ; else Beep; end; end; end.'; begin CheckComplexity(SOURCE1, 'testme', 3, 1, 3); CheckComplexity(SOURCE2, 'testme', 4, 1, 4); end; procedure TSourceComplexityCalculatorTest.TestTryFinallyBlock; const SOURCE = 'unit test; interface procedure testme; implementation procedure testme; begin try finally end; end; end.'; begin CheckComplexity(SOURCE, 'testme', 2, 1, 2); end; procedure TSourceComplexityCalculatorTest.TestTryExceptBlock; const SOURCE = 'unit test; interface procedure testme; implementation procedure testme; begin try except end; end; end.'; begin CheckComplexity(SOURCE, 'testme', 3, 1, 3); end; procedure TSourceComplexityCalculatorTest.TestTryExceptOnBlock; const SOURCE = 'unit test; interface procedure testme; implementation procedure testme; begin try except on E: Exception do end; end; end.'; begin CheckComplexity(SOURCE, 'testme', 4, 1, 4); end; initialization RegisterTest(TSourceComplexityCalculatorTest.Suite); end.
{ p_29_2 - полицейская база данных, версия 2 } program p_29_2; function FindNumber(var aFile: text; aNumber: integer): boolean; var n: integer; { текущий номер в БД } begin FindNumber := false; { на случай, если файл пуст } Reset(aFile); { позицию чтения устанавливаем в начало файла } n := 0; { в начале цикла задаем несуществующий номер } { читаем номера из файла, пока НЕ конец файла И номер НЕ найден } while not Eof(aFile) and (n<>aNumber) do begin Read(aFile, n); FindNumber := (n=aNumber); { true, если номер нашелся } end; end; var f: text; num: integer; {----- главная программа -----} begin Assign(f, 'police.txt'); repeat Write('Укажите номер автомобиля: '); Readln(num); if FindNumber(f, num) then Writeln('Эта машина в розыске, хватайте его!') else Writeln('Пропустите его'); until num=0; { 0 - признак завершения программы } Close(f); end.
unit Preferences; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, StdCtrls, ExtCtrls, Buttons, Menus, ToolWin, CheckLst; type TOptions = class(TForm) PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; EnableShow: TCheckBox; EnableHide: TCheckBox; btnOK: TBitBtn; btnCancel: TBitBtn; btnApply: TBitBtn; SaveHistory: TCheckBox; HistoryCount: TEdit; UpDown1: TUpDown; History: TCheckBox; AddNulles: TCheckBox; StickyWindow: TCheckBox; EnableClear: TCheckBox; HideOnInactive: TCheckBox; ClearMemoryOnExit: TCheckBox; AutoBoot: TCheckBox; AutoReplaceLayout: TCheckBox; SaveVariables: TCheckBox; StayOnTop: TCheckBox; TabSheet3: TTabSheet; memoInvFunctions: TMemo; SaveInvParamsToFile: TButton; Label1: TLabel; KeyList: TPopupMenu; Esc1: TMenuItem; Del1: TMenuItem; Pause1: TMenuItem; NumLock1: TMenuItem; CapsLock1: TMenuItem; ScrollLock1: TMenuItem; Backspace1: TMenuItem; Home1: TMenuItem; End1: TMenuItem; Insert1: TMenuItem; PageUp1: TMenuItem; PageDown1: TMenuItem; edtShow: TEdit; edtHide: TEdit; edtClearField: TEdit; Bevel1: TBevel; Label2: TLabel; TestEdit: THotKey; Label3: TLabel; DoNotTerminateOnClose: TCheckBox; ShowHintWindowOnClick: TCheckBox; EnableInsertTexts: TCheckBox; SpeedButton1: TSpeedButton; SpeedButton2: TSpeedButton; TabSheet4: TTabSheet; Label4: TLabel; clbPanelsVisible: TCheckListBox; Bevel2: TBevel; Label5: TLabel; tsUpdate: TTabSheet; CheckBox1: TCheckBox; Edit1: TEdit; Label6: TLabel; Label7: TLabel; Button1: TButton; GroupBox1: TGroupBox; CheckBox2: TCheckBox; procedure HistoryClick(Sender: TObject); procedure btnApplyClick(Sender: TObject); procedure btnOKClick(Sender: TObject); procedure FormShow(Sender: TObject); procedure SaveInvParamsToFileClick(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); procedure SpeedButton2Click(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var Options: TOptions; implementation uses KOLIniFile, InsertTextForm, Common_Utils, Main; {$R *.dfm} procedure TOptions.HistoryClick(Sender: TObject); begin btnApply.Enabled:=true; end; procedure TOptions.btnApplyClick(Sender: TObject); begin LoadSaveOptions(True); btnApply.Enabled:=false; end; procedure TOptions.btnOKClick(Sender: TObject); begin if btnApply.Enabled then btnApplyClick(Sender); end; procedure TOptions.FormShow(Sender: TObject); begin LoadSaveOptions(False); btnApply.Enabled:=false; end; procedure TOptions.SaveInvParamsToFileClick(Sender: TObject); begin SaveReplacedCaptions(@memoInvFunctions.Lines); end; procedure TOptions.SpeedButton1Click(Sender: TObject); begin frmKeyInsertText.ShowModal; end; procedure TOptions.SpeedButton2Click(Sender: TObject); begin SetClipText(Menus.ShortCutToText(TestEdit.HotKey)); end; procedure TOptions.FormCreate(Sender: TObject); begin clbPanelsVisible.ItemEnabled[0]:=false; clbPanelsVisible.Checked[0]:=true; //clbPanelsVisible.Checked[1]:= end; end.
unit PascalUnit; interface uses Classes, Types, Generics.Collections, CodeElement, Lexer, WriterIntf; type TPascalUnit = class(TCodeElement) private FFooterSource: TStringList; FInitSection: TObjectList<TCodeElement>; FLexer: TLexer; FUsedUnits: TStringList; FImplementationSection: TObjectList<TCodeElement>; function GetInterfaceSection: TObjectList<TCodeElement>; public constructor Create(AName: string); destructor Destroy(); override; procedure GetDCPUSource(AWriter: IWriter); override; function GetImplementationElement(AName: string; AType: TCodeElementClass): TCodeElement; function GetElementFromAll(AName: string; AType: TCodeElementClass): TCodeElement; property FooterSource: TStringList read FFooterSource; property InitSection: TObjectList<TCodeElement> read FInitSection; property ImplementationSection: TObjectList<TCodeElement> read FImplementationSection; property InterfaceSection: TObjectList<TCodeElement> read GetInterfaceSection; property Lexer: TLexer read FLexer; property UsedUnits: TStringList read FUsedUnits; end; implementation uses VarDeclaration, Optimizer; { TPascalUnit } constructor TPascalUnit.Create(AName: string); begin inherited; FFooterSource := TStringList.Create(); FInitSection := TObjectList<TCodeElement>.Create(); FImplementationSection := TObjectList<TCodeElement>.Create(); FLexer := TLexer.Create(); FUsedUnits := TStringList.Create(); end; destructor TPascalUnit.Destroy; begin FFooterSource.Free; FinitSection.Free; FImplementationSection.Free; FLexer.Free; FUsedUnits.Free; inherited; end; procedure TPascalUnit.GetDCPUSource; var LElement: TCodeElement; begin for LElement in FInitSection do begin LElement.GetDCPUSource(AWriter); end; for LElement in SubElements do begin if not (LElement is TVarDeclaration) then begin LElement.GetDCPUSource(AWriter); end; end; for LElement in ImplementationSection do begin LElement.GetDCPUSource(AWriter); end; for LElement in SubElements do begin if LELement is TVarDeclaration then begin LElement.GetDCPUSource(AWriter); end; end; AWriter.WriteList(FFooterSource); AWriter.Write('');//one emptyline for padding, otherwhise we screw mapping... end; function TPascalUnit.GetElementFromAll(AName: string; AType: TCodeElementClass): TCodeElement; begin Result := GetImplementationElement(AName, AType); if not Assigned(Result) then begin Result := GetElement(AName, AType); end; end; function TPascalUnit.GetImplementationElement(AName: string; AType: TCodeElementClass): TCodeElement; begin Result := GetElementInScope(AName, AType, FImplementationSection); end; function TPascalUnit.GetInterfaceSection: TObjectList<TCodeElement>; begin Result := SubElements; end; end.
{------------------------------------ 功能说明:所有窗体的主先类 修改日期:2009/05/11 作者:wzw 版权:wzw -------------------------------------} unit uBaseForm; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, _Sys, StdCtrls, AuthoritySvrIntf; type TBaseForm = class(TForm, IAuthorityCtrl) private procedure Intf_RegAuthority(aIntf: IAuthorityRegistrar); procedure DoHandleAuthority; protected class procedure RegAuthority(aIntf: IAuthorityRegistrar); virtual; {IAuthorityCtrl} procedure IAuthorityCtrl.RegAuthority = Intf_RegAuthority; procedure HandleAuthority(const Key: string; aEnable: Boolean); virtual; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; class procedure RegistryAuthority; //注册权限 end; TRegAuthorityPro = procedure(aIntf: IAuthorityRegistrar) of object; TAuthorityReg = class(TInterfacedObject, IAuthorityCtrl) private FRegAuthorityPro: TRegAuthorityPro; protected {IAuthorityCtrl} procedure RegAuthority(aIntf: IAuthorityRegistrar); procedure HandleAuthority(const Key: string; aEnable: Boolean); public constructor Create(RegAuthorityPro: TRegAuthorityPro); end; implementation uses SysSvc; {$R *.dfm} { TBaseForm } constructor TBaseForm.Create(AOwner: TComponent); begin inherited; DoHandleAuthority; end; destructor TBaseForm.Destroy; begin inherited; end; procedure TBaseForm.DoHandleAuthority; var AuthoritySvr: IAuthoritySvr; begin if SysService.QueryInterface(IAuthoritySvr, AuthoritySvr) = S_OK then AuthoritySvr.AuthorityCtrl(Self); end; procedure TBaseForm.HandleAuthority(const Key: string; aEnable: Boolean); begin end; procedure TBaseForm.Intf_RegAuthority(aIntf: IAuthorityRegistrar); begin Self.RegAuthority(aIntf); end; class procedure TBaseForm.RegAuthority(aIntf: IAuthorityRegistrar); begin end; class procedure TBaseForm.RegistryAuthority; var AuthoritySvr: IAuthoritySvr; begin if SysService.QueryInterface(IAuthoritySvr, AuthoritySvr) = S_OK then AuthoritySvr.RegAuthority(TAuthorityReg.Create(Self.RegAuthority)); end; { TAuthorityReg } constructor TAuthorityReg.Create(RegAuthorityPro: TRegAuthorityPro); begin FRegAuthorityPro := RegAuthorityPro; end; procedure TAuthorityReg.HandleAuthority(const Key: string; aEnable: Boolean); begin end; procedure TAuthorityReg.RegAuthority(aIntf: IAuthorityRegistrar); begin if Assigned(FRegAuthorityPro) then FRegAuthorityPro(aIntf); end; end.
(* *************************************************************************** This example program creates a bitmap file in memory and saves it to a file named by the user via command line. You can run it like this: ./create <width> <height> <filename> *************************************************************************** *) program create; uses SysUtils, bitmap; var mem : ^byte; bmp_size: int64; bmp_data: ^byte; bmp : TBitmap; w, h : integer; lp0, lp1: int64; begin if ParamCount() < 3 then begin WriteLn('Usage: ./create <width> <height> <output file name>'); WriteLn(' Example: ./create 800 600 /tmp/file.bmp'); exit; end; w := StrToInt(ParamStr(1)); h := StrToInt(ParamStr(2)); // get memory size required by bitmap, bitmap_get_size(width, height, bpp, header_type) bmp_size := bitmap_get_size(w, h, 24, BitmapV4); mem := GetMem(bmp_size); // create bitmap in memory bitmap_create(w, h, 24, BitmapV4, PIXEL_FORMAT_BGR24, mem); // get info bitmap_get_info(mem, bmp); bmp_data := bmp.pixels; // fill bitmap with something for lp0 := 0 to h-1 do begin for lp1 := 0 to w-1 do begin if (lp0 and $01) = 0 then begin // fill even rows, starting from down bmp_data[(bmp.row_len*lp0)+(lp1*3)+$00] := $FF; bmp_data[(bmp.row_len*lp0)+(lp1*3)+$01] := $96; bmp_data[(bmp.row_len*lp0)+(lp1*3)+$02] := $00; end else begin // fill odd rows bmp_data[(bmp.row_len*lp0)+(lp1*3)+$00] := $FF; bmp_data[(bmp.row_len*lp0)+(lp1*3)+$01] := $FF; bmp_data[(bmp.row_len*lp0)+(lp1*3)+$02] := $FF; end; end; end; // save to file if not FileExists(ParamStr(3)) then begin if bitmap_save_to_file(ParamStr(3), @bmp) then WriteLn('Bitmap file saved to: ',ParamStr(3)); end else begin WriteLn('File exists, not overwriting.'); FreeMem(mem); exit; end; FreeMem(mem); end.
unit gamepanel; {$mode objfpc}{$H+} interface uses windows, lmessages, Classes, SysUtils, controls, ExtCtrls, GL, GLext, glu, graphics, renderobject, dialogs, types; //optimizations will come later, or never. It's just a tutorial/example for CE. Not a high speed competitive first person shooter... type TMEvent = function(TGamePanel: TObject; meventtype: integer; Button: TMouseButton; Shift: TShiftState; X, Y: Integer):boolean of Object; TKEvent = function(TGamePanel: TObject; keventtype: integer; Key: Word; Shift: TShiftState):boolean of Object; TGamePanel=class(Tcustompanel) private glrc: HGLRC; ticker: TTimer; oldWndProc: TWndMethod; fOnGameTick: TNotifyEvent; fOnRender: TNotifyEvent; keyEventHandlers: array of TKEvent; mouseEventHandlers: array of TMEvent; procedure mywndproc(var TheMessage: TLMessage); procedure tick(sender: tobject); public background:record r,g,b: single; end; constructor Create(TheOwner: TComponent); override; procedure AddKeyEventHandler(keyevent: TKEvent; position: integer=-1); procedure RemoveKeyEventHandler(keyevent: TKEvent); procedure AddMouseEventHandler(mouseEvent: TMEvent; position: integer=-1); procedure RemoveMouseEventHandler(mouseEvent: TMEvent); procedure render; function PixelPosToGamePos(x,y: integer): TPointf; function GamePosToPixelPos(x,y: single): TPoint; protected 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 MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure SetParent(NewParent: TWinControl); override; published property OnGameTick: TNotifyEvent read fOnGameTick write fOnGameTick; property OnGameRender: TNotifyEvent read fOnRender write fOnRender; end; implementation var z: boolean=false; t: array [0..10] of gluint; img: tpicture; pixels: array [0..11] of single=(0,1,0,0.5,0.5,0.5,1,1,1,1,0,0); pp: pointer; r: single=0; procedure TGamePanel.KeyDown(var Key: Word; Shift: TShiftState); var i: integer; begin inherited KeyDown(Key, Shift); for i:=0 to length(KeyEventHandlers)-1 do if keyEventHandlers[i](self, 0, key, shift) then break; end; procedure TGamePanel.KeyUp(var Key: Word; Shift: TShiftState); var i: integer; begin inherited KeyUp(Key, Shift); for i:=0 to length(KeyEventHandlers)-1 do if keyEventHandlers[i](self, 1, key, shift) then break; end; function TGamePanel.GamePosToPixelPos(x,y: single): TPoint; begin result.x:=trunc((1+x)*(width/2)); result.y:=trunc((1+y)*(height/2)); end; function TGamePanel.PixelPosToGamePos(x,y: integer): TPointf; begin result.x:=(x / (width/2))-1; result.y:=(y / (height/2))-1; end; procedure TGamePanel.MouseMove(Shift: TShiftState; X, Y: Integer); var i: integer; begin inherited MouseMove(Shift, x,y); for i:=0 to length(mouseEventHandlers)-1 do if mouseEventHandlers[i](self, 2, mbLeft, Shift, x,y) then break; end; procedure TGamePanel.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var i: integer; begin inherited MouseDown(Button, Shift, x,y); for i:=0 to length(mouseEventHandlers)-1 do if mouseEventHandlers[i](self, 1, Button, Shift, x,y) then break; end; procedure TGamePanel.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var i: integer; begin inherited MouseDown(Button, Shift, x,y); for i:=0 to length(mouseEventHandlers)-1 do if mouseEventHandlers[i](self, 0, Button, Shift, x,y) then break; end; procedure TGamePanel.AddKeyEventHandler(KeyEvent: TKEvent; position: integer=-1); var i,j: integer; begin setlength(KeyEventHandlers,length(KeyEventHandlers)+1); if position=-1 then //at the end (highest order) KeyEventHandlers[length(KeyEventHandlers)-1]:=KeyEvent else begin for i:=position+1 to length(KeyEventHandlers)-2 do KeyEventHandlers[i]:=KeyEventHandlers[i+1]; KeyEventHandlers[position]:=KeyEvent; end; end; procedure TGamePanel.RemoveKeyEventHandler(KeyEvent: TKEvent); var i,j: integer; begin i:=0; while i<length(KeyEventHandlers) do begin if (tmethod(KeyEventHandlers[i]).Data=tmethod(KeyEvent).Data) and (tmethod(KeyEventHandlers[i]).Code=tmethod(KeyEvent).Code) then begin for j:=i to length(KeyEventHandlers)-2 do KeyEventhandlers[j]:=KeyEventHandlers[j+1]; setlength(KeyEventhandlers,length(KeyEventhandlers)-1) end else inc(i); end; end; procedure TGamePanel.AddMouseEventHandler(mouseEvent: TMEvent; position: integer=-1); var i,j: integer; begin setlength(mouseEventHandlers,length(mouseEventHandlers)+1); if position=-1 then //at the end (highest order) mouseEventHandlers[length(mouseEventHandlers)-1]:=mouseEvent else begin for i:=position+1 to length(mouseEventHandlers)-2 do mouseEventHandlers[i]:=mouseEventHandlers[i+1]; mouseEventHandlers[position]:=mouseEvent; end; end; procedure TGamePanel.RemoveMouseEventHandler(mouseEvent: TMEvent); var i,j: integer; begin i:=0; while i<length(mouseEventHandlers) do begin if (tmethod(mouseEventHandlers[i]).Data=tmethod(mouseEvent).Data) and (tmethod(mouseEventHandlers[i]).Code=tmethod(mouseEvent).Code) then begin for j:=i to length(mouseEventHandlers)-2 do mouseEventhandlers[j]:=mouseEventHandlers[j+1]; setlength(mouseEventhandlers,length(mouseEventhandlers)-1) end else inc(i); end; end; procedure TGamePanel.render; begin //render the 'game' wglMakeCurrent(canvas.handle, glrc); // glViewport(0, 0, Width, Height); glViewport(0, 0, Width,Height); //width, height // glMatrixMode(GL_PROJECTION); // glLoadIdentity(); // gluOrtho2D(-1,1,-1,1); //default anyhow //setup some states glClearColor(background.r, background.g, background.b, 1.0); // Set background color to black and opaque glClear(GL_COLOR_BUFFER_BIT); // Clear the color buffer (background) glMatrixMode(GL_MODELVIEW); glLoadIdentity(); if assigned(glActiveTexture)=false then pointer(glActiveTexture):=wglGetProcAddress('glActiveTexture'); glEnable(GL_TEXTURE_2D); glTexEnvf(GL_TEXTURE_2D,GL_TEXTURE_ENV_MODE,GL_MODULATE); glDepthMask(GL_FALSE); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); glColor4f(1.0,1.0,1.0,1.0);//Replace this alpha for transparency if assigned(fOnRender) then fOnRender(self); glFlush(); // Render now //present SwapBuffers(canvas.handle); end; procedure TGamePanel.mywndproc(var TheMessage: TLMessage); begin if TheMessage.msg=lm_paint then render() else oldWndProc(TheMessage); end; procedure TGamePanel.tick(sender: tobject); begin if assigned(fOnGameTick) then fOnGameTick(self); render; end; procedure TGamePanel.SetParent(NewParent: TWinControl); var pfd: TPixelFormatDescriptor; i: integer; oldparent: TWinControl; begin oldparent:=parent; inherited SetParent(NewParent); if (NewParent<>nil) and (oldparent=nil) then begin glrc:=wglCreateContext(canvas.handle); if glrc=0 then begin pfd.nSize:=sizeof(pfd); pfd.nVersion:=1; pfd.dwFlags:=PFD_DRAW_TO_WINDOW or PFD_SUPPORT_OPENGL or PFD_DOUBLEBUFFER; pfd.iPixelType:=PFD_TYPE_RGBA; pfd.cColorBits:=24; pfd.cRedBits:=0; pfd.cRedShift:=0; pfd.cGreenBits:=0; pfd.cGreenShift:=0; pfd.cBlueBits:=0; pfd.cBlueShift:=0; pfd.cAlphaBits:=0; pfd.cAlphaShift:=0; pfd.cAccumBits:=0; pfd.cAccumRedBits:=0; pfd.cAccumGreenBits:=0; pfd.cAccumBlueBits:=0; pfd.cAccumAlphaBits:=0; pfd.cDepthBits:=16; pfd.cStencilBits:=0; pfd.cAuxBuffers:=0; pfd.iLayerType:=PFD_MAIN_PLANE; pfd.bReserved:=0; pfd.dwLayerMask:=0; pfd.dwVisibleMask:=0; pfd.dwDamageMask:=0; i:=ChoosePixelFormat(canvas.handle, @pfd); SetPixelFormat(canvas.handle, i, @pfd); glrc:=wglCreateContext(canvas.handle); wglMakeCurrent(canvas.handle, glrc); if Load_GL_version_1_3()=false then begin ticker.enabled:=false; MessageDlg('OpenGL 1.3 or later is required',mtError,[mbok],0); ExitProcess(13); end; end; end; SetFocus; end; constructor TGamePanel.Create(TheOwner: TComponent); begin // if Load_GL_version_1_3=false then raise exception.create('Opengl failed to load'); inherited create(TheOwner); oldWndProc:=WindowProc; windowproc:=TWndMethod(@mywndproc); ticker:=ttimer.Create(self); ticker.OnTimer:=@tick; ticker.Interval:=16; ticker.enabled:=true; end; initialization end.
unit HS4D.Credential; interface uses HS4D.Interfaces; type THS4DCredential = class(TInterfacedObject, iHS4DCredential) private [weak] FParent : iHS4D; FBaseURL : string; FEndPoint : string; public constructor Create(Parent : iHS4D); destructor Destroy; override; class function New(aParent : iHS4D) : iHS4DCredential; function BaseURL(const aValue : string) : iHS4DCredential; overload; function BaseURL : string; overload; function &End : iHS4D; end; implementation { THS4DCredential } function THS4DCredential.BaseURL(const aValue : string) : iHS4DCredential; begin Result:= Self; FBaseURL:= aValue; end; function THS4DCredential.&End: iHS4D; begin Result:= FParent; end; function THS4DCredential.BaseURL: string; begin Result:= FBaseURL; end; constructor THS4DCredential.Create(Parent: iHS4D); begin FParent:= Parent; end; destructor THS4DCredential.Destroy; begin inherited; end; class function THS4DCredential.New(aParent: iHS4D): iHS4DCredential; begin result:= Self.Create(aParent); end; end.
{ Routines that are specific to the PICs that use 8 bit programming opcodes * and transfer programming data in 24 bit words. These include the PICs * 16F15313, 18F25Q10, and others. } module picprg_16fb; define picprg_send8mss24; define picprg_send14mss24; define picprg_send16mss24; define picprg_send22mss24; define picprg_recv8mss24; define picprg_recv14mss24; define picprg_recv16mss24; define picprg_erase_16fb; %include 'picprg2.ins.pas'; const { * Command opcodes understood by this chip. } opc_adr = 16#80; {LOAD PC ADRESS} opc_ebulk = 16#18; {BULK ERASE PROGRAM MEMORY} { ******************************************************************************** * * Subroutine PICPRG_SEND8MSS24 (PR, DAT, STAT) * * Send the 8 bit data in the low bits of DAT to the target in a 24 bit data * word. The word is sent in most to least significant bit order. } procedure picprg_send8mss24 ( {send 8 bit payload in 24 bit word, MSB first} in out pr: picprg_t; {state for this use of the library} in dat: sys_int_machine_t; {data to send in the low 8 bits} out stat: sys_err_t); {completion status} val_param; begin picprg_cmdw_send24m (pr, lshft(dat & 16#FF, 1), stat); end; { ******************************************************************************** * * Subroutine PICPRG_SEND14MSS24 (PR, DAT, STAT) * * Send the 14 bit data in the low bits of DAT to the target in a 24 bit data * word. The word is sent in most to least significant bit order. } procedure picprg_send14mss24 ( {send 14 bit payload in 24 bit word, MSB first} in out pr: picprg_t; {state for this use of the library} in dat: sys_int_machine_t; {data to send in the low 14 bits} out stat: sys_err_t); {completion status} val_param; begin picprg_cmdw_send24m (pr, lshft(dat & 16#3FFF, 1), stat); end; { ******************************************************************************** * * Subroutine PICPRG_SEND16MSS24 (PR, DAT, STAT) * * Send the 16 bit data in the low bits of DAT to the target in a 24 bit data * word. The word is sent in most to least significant bit order. } procedure picprg_send16mss24 ( {send 16 bit payload in 24 bit word, MSB first} in out pr: picprg_t; {state for this use of the library} in dat: sys_int_machine_t; {data to send in the low 16 bits} out stat: sys_err_t); {completion status} val_param; begin picprg_cmdw_send24m (pr, lshft(dat & 16#FFFF, 1), stat); end; { ******************************************************************************** * * Subroutine PICPRG_SEND22MSS24 (PR, DAT, STAT) * * Send the 22 bit data in the low bits of DAT to the target in a 24 bit data * word. The word is sent in most to least significant bit order. } procedure picprg_send22mss24 ( {send 22 bit payload in 24 bit word, MSB first} in out pr: picprg_t; {state for this use of the library} in dat: sys_int_machine_t; {data to send in the low 22 bits} out stat: sys_err_t); {completion status} val_param; begin picprg_cmdw_send24m (pr, lshft(dat & 16#3FFFFF, 1), stat); end; { ******************************************************************************** * * Subroutine PICPRG_RECV8MSS24 (PR, DAT, STAT) * * Receive a 24 bit word from the target in most to least significant bit * order. Return the 8 bit payload in DAT. } procedure picprg_recv8mss24 ( {receive 24 bit MSB-first word, get 8 bit payload} in out pr: picprg_t; {state for this use of the library} out dat: sys_int_machine_t; {returned 8 bit payload} out stat: sys_err_t); {completion status} val_param; var ii: sys_int_machine_t; begin picprg_cmdw_recv24m (pr, ii, stat); {get the 24 bit word from the target} dat := rshft(ii, 1) & 16#FF; {extract the 8 bit payload} end; { ******************************************************************************** * * Subroutine PICPRG_RECV14MSS24 (PR, DAT, STAT) * * Receive a 24 bit word from the target in most to least significant bit * order. Return the 14 bit payload in DAT. } procedure picprg_recv14mss24 ( {receive 24 bit MSB-first word, get 14 bit payload} in out pr: picprg_t; {state for this use of the library} out dat: sys_int_machine_t; {returned 14 bit payload} out stat: sys_err_t); {completion status} val_param; var ii: sys_int_machine_t; begin picprg_cmdw_recv24m (pr, ii, stat); {get the 24 bit word from the target} dat := rshft(ii, 1) & 16#3FFF; {extract the 14 bit payload} end; { ******************************************************************************** * * Subroutine PICPRG_RECV16MSS24 (PR, DAT, STAT) * * Receive a 24 bit word from the target in most to least significant bit * order. Return the 16 bit payload in DAT. } procedure picprg_recv16mss24 ( {receive 24 bit MSB-first word, get 16 bit payload} in out pr: picprg_t; {state for this use of the library} out dat: sys_int_machine_t; {returned 16 bit payload} out stat: sys_err_t); {completion status} val_param; var ii: sys_int_machine_t; begin picprg_cmdw_recv24m (pr, ii, stat); {get the 24 bit word from the target} dat := rshft(ii, 1) & 16#FFFF; {extract the 16 bit payload} end; { ******************************************************************************** * * Subroutine PICPRG_ERASE_16FB (PR, STAT) * * Erase 16F15313 and related. } procedure picprg_erase_16fb( {erase routine for 16F15313 and related} in out pr: picprg_t; {state for this use of the library} out stat: sys_err_t); {completion status} val_param; begin picprg_cmdw_send8m (pr, opc_adr, stat); {set address to 8000h} if sys_error(stat) then return; picprg_send16mss24 (pr, 16#8000, stat); if sys_error(stat) then return; picprg_cmdw_send8m (pr, opc_ebulk, stat); {do the bulk erase} if sys_error(stat) then return; picprg_cmdw_wait (pr, 0.015, stat); {wait for bulk erase to complete} if sys_error(stat) then return; picprg_cmdw_reset (pr, stat); end;
unit uClosedToModOpenToExt; interface uses Spring.Collections ; type IItemPricer = interface; TItem = record SKU: string; Price: double; Quantity: integer; Rule: IItemPricer; constructor Create(aSKU: string; aPrice: Double; aQuantity: integer; aRule: IItemPricer); end; IItemPricer = interface function CalculatePrice(aItem: TItem): Double; end; TNormalPricer = class(TInterfacedObject, IItemPricer) function CalculatePrice(aItem: TItem): Double; end; TTenPercentOffPricer = class(TInterfacedObject, IItemPricer) function CalculatePrice(aItem: TItem): Double; end; TBOGOFreePricer = class(TInterfacedObject, IItemPricer) function CalculatePrice(aItem: TItem): Double; end; TTwentyPercentOffPricer = class(TInterfacedObject, IItemPricer) function CalculatePrice(aItem: TItem): Double; end; TOrder = class private FListOfItems: IList<TItem>; function GetListOfItems: IEnumerable<TItem>; public procedure Add(aItem: TItem); function TotalAmount: Double; property Items: IEnumerable<TItem> read GetListOfItems; constructor Create; end; implementation { TOrder } procedure TOrder.Add(aItem: TItem); begin FListOfItems.Add(aItem) end; constructor TOrder.Create; begin inherited Create; FListOfItems := TCollections.CreateList<TItem>; end; function TOrder.GetListOfItems: IEnumerable<TItem>; begin Result := FListOfItems; end; function TOrder.TotalAmount: Double; var Item: TItem; begin Result := 0.0; for Item in Items do begin Result := Result + Item.Rule.CalculatePrice(Item); end; end; { TTenPercentOffPricer } function TTenPercentOffPricer.CalculatePrice(aItem: TItem): Double; begin Result := aItem.Quantity * aItem.Price * 0.90; end; { TBOGOFreePricer } function TBOGOFreePricer.CalculatePrice(aItem: TItem): Double; begin Result := aItem.Price * 0.50 * aItem.Quantity; end; { TNormalPricer } function TNormalPricer.CalculatePrice(aItem: TItem): Double; begin Result := aItem.Price * aItem.Quantity; end; { TItem } constructor TItem.Create(aSKU: string; aPrice: Double; aQuantity: integer; aRule: IItemPricer); begin SKU := aSKU; Price := aPrice; Quantity := aQuantity; Rule := aRule; end; { TTwentyPercentOffPricer } function TTwentyPercentOffPricer.CalculatePrice(aItem: TItem): Double; begin Result := aItem.Price * 0.8; end; end.
unit CommonReport; interface uses Excel97, Straton; type TCommonReport = class private FExcel: TExcelApplication; FStraton: TStraton; FReportResult: OleVariant; procedure SetStraton(Value: TStraton); procedure MakeReport; procedure MoveDataToExcel; procedure RemoveCols; public TemplateName: string; ReportName: string; Query: string; ReportID: integer; HeaderRow: variant; RemovingCols: array of byte; property Straton: TStraton read FStraton write SetStraton; constructor Create(Excel: TExcelApplication); end; implementation uses StraDictCommon, ClientCommon, SysUtils; procedure TCommonReport.RemoveCols; var i: integer; begin for i:=High(RemovingCols) downto 0 do FExcel.Run('DeleteColumn',RemovingCols[i]); end; procedure TCommonReport.MoveDataToExcel; var sPath: string; i, j: integer; vbc: OleVariant; wb: _WorkBook; begin // соединяемся FExcel.Connect; sPath := ExtractFilePath(ParamStr(0))+TemplateName; wb := FExcel.Workbooks.Add(sPath,0); // добавляем макросы vbc:=wb.VBProject.VBComponents.Add(1); vbc.Name := 'macros'; vbc.Codemodule.AddFromString('Sub DeleteColumn(Index as integer)'+#13+#10+ 'Columns(Index).Delete'+#13+#10+ 'End Sub'); // шапка FExcel.Cells.Item[11,3].Value := ReportName; FExcel.Cells.Item[12,1].Value := '№'; for i := 0 to varArrayHighBound(HeaderRow, 1) do FExcel.Cells.Item[12,i+2].Value := varAsType(HeaderRow[i],varOleStr); // результаты запроса for j:=0 to varArrayHighBound(FReportResult,2) do begin // порядковый номер FExcel.Cells.Item[j+13,1].Value := j+1; // непосредственно данные for i:=0 to varArrayHighBound(FReportResult,1) do //if varType(FReportResult[i,j]) <> varCurrency then FExcel.Cells.Item[j+13,i+2].Value := FReportResult[i,j] {else FExcel.Cells.Item[j+13,i+2].Value := varAsType(FReportResult[i,j], varSingle);} end; // автоподбор FExcel.Columns.AutoFit; // если задано - удаляем пустые столбцы RemoveCols; // отсоединяемся wb.VBProject.VBComponents.Remove(wb.VBProject.VBComponents.Item('macros')); FExcel.Visible[0] := true; FExcel.Disconnect; end; procedure TCommonReport.MakeReport; var sFilter: string; begin sFilter := ''; if Assigned(FStraton) then sFilter := FStraton.MakeFilter(true, nil); if (sFilter<>'') then if pos('WHERE', UpperCase(Query)) > 0 then Query := Query + ' and Straton_ID in ' + sFilter else Query := Query + ' where Straton_ID in ' + sFilter; if IServer.ExecuteQuery(Query) > 0 then begin FReportResult := IServer.QueryResult; // соединяемся с Excel // выбрасываем данные в соответствующие столбцы // если задано - удаляем пустые столбцы MoveDataToExcel; end; end; procedure TCommonReport.SetStraton(Value: TStraton); begin FStraton := Value; MakeReport; end; constructor TCommonReport.Create(Excel: TExcelApplication); begin inherited Create; FStraton := nil; FExcel := Excel; end; end.
{ ID: a_zaky01 PROG: lamps LANG: PASCAL } type lamps=array[1..100] of boolean; var n,c,count,kon,koff,i,i1,i2,i3,i4,j:integer; lampon,lampoff:array[1..100] of integer; lamp:lamps; hasil:array[1..16] of lamps; fin,fout:text; function check(lamp:lamps):boolean; var i:integer; begin check:=true; if kon>0 then for i:=1 to kon do if not lamp[lampon[i]] then begin check:=false; break; end; if koff>0 then for i:=1 to koff do if lamp[lampoff[i]] then begin check:=false; break; end; end; procedure sort(count:integer); var i,j,k:integer; g:boolean; temp:lamps; begin for i:=count downto 1 do for j:=1 to i-1 do begin g:=true; k:=1; while k<=count do begin if (hasil[j][k]) and not(hasil[j+1][k]) then break else if not(hasil[j][k]) and (hasil[j+1][k]) then begin g:=false; break; end else inc(k); end; if g then begin temp:=hasil[j]; hasil[j]:=hasil[j+1]; hasil[j+1]:=temp; end; end; end; begin assign(fin,'lamps.in'); assign(fout,'lamps.out'); reset(fin); rewrite(fout); readln(fin,n); readln(fin,c); kon:=0; koff:=0; while true do begin read(fin,i); if i=-1 then break; inc(kon); lampon[kon]:=i; end; while true do begin read(fin,i); if i=-1 then break; inc(koff); lampoff[koff]:=i; end; count:=0; for i1:=0 to 1 do for i2:=0 to 1 do for i3:=0 to 1 do for i4:=0 to 1 do if (i1+i2+i3+i4<=c) and ((c-(i1+i2+i3+i4)) mod 2=0) then begin if i1=1 then for i:=1 to n do lamp[i]:=false else for i:=1 to n do lamp[i]:=true; if i2=1 then for i:=1 to (n+1) div 2 do lamp[2*i-1]:=not lamp[2*i-1]; if i3=1 then for i:=1 to n div 2 do lamp[2*i]:=not lamp[2*i]; if i4=1 then for i:=1 to (n+2) div 3 do lamp[3*i-2]:=not lamp[3*i-2]; if check(lamp) then begin inc(count); hasil[count]:=lamp; end; end; if count=0 then writeln(fout,'IMPOSSIBLE') else begin sort(count); for i:=1 to count do begin for j:=1 to n do if hasil[i][j] then write(fout,1) else write(fout,0); writeln(fout); end; end; close(fin); close(fout); end.
{ --- START LICENSE BLOCK --- *********************************************************** testjcr6.pas This particular file has been released in the public domain and is therefore free of any restriction. You are allowed to credit me as the original author, but this is not required. This file was setup/modified in: 2019 If the law of your country does not support the concept of a product being released in the public domain, while the original author is still alive, or if his death was not longer than 70 years ago, you can deem this file "(c) Jeroen Broks - licensed under the CC0 License", with basically comes down to the same lack of restriction the public domain offers. (YAY!) *********************************************************** Version 19.03.01 --- END LICENSE BLOCK --- } Program TestJCR6; Uses jcr6; var jt:tJCRFile; Begin Writeln('JCR6 test utility'); writeln('=== Test.txt ==='); JCR_Open(jt,'Test.JCR','Test.txt'); while not JCR_Eof(jt) do write(JCR_GetChar(jt)); writeln; JCR_Close(jt); writeln('=== Readme.md ==='); JCR_Open(jt,'Test.JCR','ReAdMe.Md'); while not JCR_Eof(jt) do write(JCR_GetChar(jt)); writeln; JCR_Close(jt); writeln('All done!'); End.
unit VN.Types.ViewNavigatorInfo; interface uses VN.Types; type TvnViewInfo = class(TInterfacedObject) private FName: string; FCreateDestroyTime: TvnCreateDestroyTime; FNavigationClass: TvnControlClass; FControl: TvnControl; FIsCreated: Boolean; FIsHaveParent: Boolean; FParent: TvnControl; procedure SetParent(const Value: TvnControl); private procedure NotifySelfShow; procedure NotifySelfHide; procedure NotifySelfDestroy; function CanBeFree(ADestroyTime: TvnCreateDestroyTime): Boolean; function CanBeCreate(ACreationTime: TvnCreateDestroyTime): Boolean; function IsCreated: Boolean; function IsHaveParent: Boolean; procedure ViewCreate; procedure ViewDestroy; public procedure NotifySelfCreate; // must be private procedure ShowView(AParent: TvnControl); procedure HideView(); constructor Create(const AName: string; ANavClass: TvnControlClass; ACreateDestroyTime: TvnCreateDestroyTime = TvnCreateDestroyTime.OnShowHide); destructor Destroy; override; property Name: string read FName write FName; property NavigationClass: TvnControlClass read FNavigationClass write FNavigationClass; property CreateDestroyTime: TvnCreateDestroyTime read FCreateDestroyTime write FCreateDestroyTime; property Control: TvnControl read FControl write FControl; property Parent: TvnControl read FParent write SetParent; end; implementation { TvnViewInfo } function TvnViewInfo.CanBeCreate(ACreationTime: TvnCreateDestroyTime): Boolean; begin Result := (FCreateDestroyTime = ACreationTime) and (not IsCreated); end; function TvnViewInfo.CanBeFree(ADestroyTime: TvnCreateDestroyTime): Boolean; begin Result := IsCreated and (FCreateDestroyTime = ADestroyTime) and (not IsHaveParent); end; constructor TvnViewInfo.Create(const AName: string; ANavClass: TvnControlClass; ACreateDestroyTime: TvnCreateDestroyTime = TvnCreateDestroyTime.OnShowHide); begin FName := AName; FNavigationClass := ANavClass; FCreateDestroyTime := ACreateDestroyTime; HideView; NotifySelfCreate; end; destructor TvnViewInfo.Destroy; begin NotifySelfDestroy; inherited; end; procedure TvnViewInfo.HideView; begin Parent := nil; NotifySelfHide; end; procedure TvnViewInfo.ViewCreate; begin FControl := TvnControl(FNavigationClass.Create(nil)); FIsCreated := True; end; procedure TvnViewInfo.ViewDestroy; begin FControl.DisposeOf; // or Free? FControl := nil; FIsCreated := False; end; function TvnViewInfo.IsCreated: Boolean; begin Result := FIsCreated and Assigned(FControl); end; function TvnViewInfo.IsHaveParent: Boolean; begin Result := FIsHaveParent; end; procedure TvnViewInfo.NotifySelfCreate; begin if CanBeCreate(TvnCreateDestroyTime.OnCreateDestroy) then ViewCreate; end; procedure TvnViewInfo.NotifySelfDestroy; begin if CanBeFree(TvnCreateDestroyTime.OnCreateDestroy) then ViewDestroy; end; procedure TvnViewInfo.NotifySelfHide; begin if CanBeFree(TvnCreateDestroyTime.OnShowHide) then ViewDestroy; end; procedure TvnViewInfo.NotifySelfShow; begin if CanBeCreate(TvnCreateDestroyTime.OnShowHide) then ViewCreate; end; procedure TvnViewInfo.SetParent(const Value: TvnControl); begin FParent := Value; if IsCreated then FControl.Parent := Value; FIsHaveParent := Assigned(Value); end; procedure TvnViewInfo.ShowView(AParent: TvnControl); begin NotifySelfShow; Parent := AParent; FControl.Visible := True; end; end.
unit Options; interface uses Classes, SysUtils, PxCommandLine, PxSettings; type TOptions = class (TPxCommandLineParser) private function GetHelp: Boolean; function GetQuiet: Boolean; function GetDataFolder: String; function GetOutputFile: String; protected class procedure Initialize; class procedure Shutdown; procedure CreateOptions; override; procedure AfterParseOptions; override; public class function Instance: TOptions; property Help: Boolean read GetHelp; property Quiet: Boolean read GetQuiet; property DataFolder: String read GetDataFolder; property OutputFile: String read GetOutputFile; end; implementation { TOptions } { Private declarations } function TOptions.GetHelp: Boolean; begin Result := ByName['help'].Value; end; function TOptions.GetQuiet: Boolean; begin Result := ByName['quiet'].Value; end; function TOptions.GetDataFolder: String; begin Result := ByName['data-folder'].Value; if Result <> '' then Result := IncludeTrailingPathDelimiter(Result); end; function TOptions.GetOutputFile: String; begin Result := ByName['output-file'].Value; end; { Protected declarations } var _Instance: TOptions = nil; class procedure TOptions.Initialize; begin _Instance := TOptions.Create; _Instance.Parse; end; class procedure TOptions.Shutdown; begin FreeAndNil(_Instance); end; procedure TOptions.CreateOptions; begin with AddOption(TPxBoolOption.Create('h', 'help')) do Explanation := 'Show help'; with AddOption(TPxBoolOption.Create('q', 'quiet')) do Explanation := 'Be quiet'; with AddOption(TPxStringOption.Create('i', 'data-folder')) do begin Explanation := 'Data folder to read data from'; Value := IniFile.ReadString('settings', LongForm, 'data'); end; with AddOption(TPxStringOption.Create('o', 'output-file')) do begin Explanation := 'Output file to store produced SQL statements'; Value := IniFile.ReadString('settings', LongForm, 'rtmgr.sql'); end; end; procedure TOptions.AfterParseOptions; begin if not Quiet then begin Writeln(Format('%s - binary data from version 3.x to SQL converter', [ ExtractFileName(ParamStr(0)) ])); Writeln; end; if DataFolder = '' then begin Writeln('Error: no data folder specified!'); Writeln; Halt(1); end; if OutputFile = '' then begin Writeln('Error: no output file specified!'); Writeln; Halt(2); end; end; { Public declarations } class function TOptions.Instance: TOptions; begin Result := _Instance; end; initialization TOptions.Initialize; finalization TOptions.Shutdown; end.
unit Tests.Grijjy.MongoDB.Samples; interface uses System.Generics.Collections, DUnitX.TestFramework, Grijjy.Bson, Grijjy.MongoDB, Grijjy.MongoDB.Queries; type TTestDocumentationSamples = class private FClient: IgoMongoClient; FDatabase: IgoMongoDatabase; FCollection: IgoMongoCollection; private procedure RemoveIds(const ADocuments: TArray<TgoBsonDocument>); function ParseMultiple(const AJsons: array of String): TArray<TgoBsonDocument>; procedure CheckEquals(const AExpected, AActual: TArray<TgoBsonDocument>); overload; public [Setup] procedure Setup; [TearDown] procedure Teardown; public [Test] procedure Example01; [Test] procedure Example03; end; type TPrimerFixture = class private class var FClient: IgoMongoClient; FDatabase: IgoMongoDatabase; FDataset: TList<TgoBsonDocument>; FReloadCollection: Boolean; private procedure LoadDataSetFromResource; procedure LoadCollection; protected procedure AltersCollection; procedure RemoveId(const ADocument: TgoBsonDocument); procedure CheckEquals(const AExpected, AActual: TgoBsonValue); overload; class property Database: IgoMongoDatabase read FDatabase; public class constructor Create; class destructor Destroy; public [Setup] procedure Setup; [SetupFixture] procedure SetupFixture; public end; type TTestQueryPrimer = class(TPrimerFixture) public [Test] procedure QueryAll; [Test] procedure LogicalAnd; [Test] procedure LogicalOr; [Test] procedure QueryTopLevelField; [Test] procedure QueryEmbeddedDocument; [Test] procedure QueryFieldInArray; [Test] procedure GreaterThan; [Test] procedure LessThan; [Test] procedure Sort; end; type TTestInsertPrimer = class(TPrimerFixture) public [Test] procedure InsertADocument; end; type TTestRemovePrimer = class(TPrimerFixture) public [Test] procedure RemoveMatchingDocuments; [Test] procedure RemoveAllDocuments; [Test] procedure DropCollection; end; type TTestUpdatePrimer = class(TPrimerFixture) public [Test] procedure UpdateTopLevelFields; [Test] procedure UpdateEmbeddedField; [Test] procedure UpdateMultipleDocuments; end; implementation uses System.Types, System.Classes, System.SysUtils, System.DateUtils, System.Zip, Tests.Grijjy.MongoDB.Settings; {$R Resources.res} { TTestDocumentationSamples } procedure TTestDocumentationSamples.CheckEquals(const AExpected, AActual: TArray<TgoBsonDocument>); var I: Integer; Exp, Act: TArray<String>; begin Assert.AreEqual(Length(AExpected), Length(AActual)); SetLength(Exp, Length(AExpected)); SetLength(Act, Length(AActual)); for I := 0 to Length(AExpected) - 1 do begin Exp[I] := AExpected[I].ToJson; Act[I] := AActual[I].ToJson; end; TArray.Sort<String>(Exp); TArray.Sort<String>(Act); for I := 0 to Length(Exp) - 1 do Assert.AreEqual(Exp[I], Act[I]); end; procedure TTestDocumentationSamples.Example01; var Doc: TgoBsonDocument; Result: TArray<TgoBsonDocument>; begin Doc := TgoBsonDocument.Create() .Add('item', 'canvas') .Add('qty', 100) .Add('tags', TgoBsonArray.Create(['cotton'])) .Add('size', TgoBsonDocument.Create() .Add('h', 28) .Add('w', 35.5) .Add('uom', 'cm')); Assert.IsTrue(FCollection.InsertOne(Doc)); Result := FCollection.Find.ToArray; RemoveIds(Result); CheckEquals(ParseMultiple( ['{ item: "canvas", qty: 100, tags: ["cotton"], size: { h: 28, w: 35.5, uom: "cm" } }']), Result); end; procedure TTestDocumentationSamples.Example03; var Docs, Result: TArray<TgoBsonDocument>; begin Docs := TArray<TgoBsonDocument>.Create( TgoBsonDocument.Create() .Add('item', 'journal') .Add('qty', 25) .Add('tags', TgoBsonArray.Create(['blank', 'red'])) .Add('size', TgoBsonDocument.Create() .Add('h', 14) .Add('w', 21) .Add('uom', 'cm')), TgoBsonDocument.Create() .Add('item', 'mat') .Add('qty', 85) .Add('tags', TgoBsonArray.Create(['gray'])) .Add('size', TgoBsonDocument.Create() .Add('h', 27.9) .Add('w', 35.5) .Add('uom', 'cm')), TgoBsonDocument.Create() .Add('item', 'mousepad') .Add('qty', 25) .Add('tags', TgoBsonArray.Create(['gel', 'blue'])) .Add('size', TgoBsonDocument.Create() .Add('h', 19) .Add('w', 22.85) .Add('uom', 'cm'))); Assert.AreEqual(3, FCollection.InsertMany(Docs)); Result := FCollection.Find.ToArray; RemoveIds(Result); CheckEquals(ParseMultiple( ['{ item: "journal", qty: 25, tags: ["blank", "red"], size: { h: 14, w: 21, uom: "cm" } }', '{ item: "mat", qty: 85, tags: ["gray"], size: { h: 27.9, w: 35.5, uom: "cm" } }', '{ item: "mousepad", qty: 25, tags: ["gel", "blue"], size: { h: 19, w: 22.85, uom: "cm" } }']), Result); end; function TTestDocumentationSamples.ParseMultiple( const AJsons: array of String): TArray<TgoBsonDocument>; var I: Integer; begin SetLength(Result, Length(AJsons)); for I := 0 to Length(AJsons) - 1 do Result[I] := TgoBsonDocument.Parse(AJsons[I]); end; procedure TTestDocumentationSamples.RemoveIds( const ADocuments: TArray<TgoBsonDocument>); var Doc: TgoBsonDocument; begin for Doc in ADocuments do Doc.Remove('_id'); end; procedure TTestDocumentationSamples.Setup; begin FClient := TgoMongoClient.Create(TEST_SERVER_HOST, TEST_SERVER_PORT); FDatabase := FClient.GetDatabase('test'); FCollection := FDatabase.GetCollection('inventory'); FDatabase.DropCollection('inventory'); end; procedure TTestDocumentationSamples.Teardown; begin FCollection := nil; FDatabase := nil; FClient := nil; end; { TPrimerFixture } procedure TPrimerFixture.AltersCollection; begin FReloadCollection := True; end; procedure TPrimerFixture.CheckEquals(const AExpected, AActual: TgoBsonValue); begin Assert.AreEqual(AExpected.IsNil, AActual.IsNil); if (AExpected.IsNil) then Exit; Assert.AreEqual(AExpected.ToJson, AActual.ToJson); end; class constructor TPrimerFixture.Create; begin FDataset := TList<TgoBsonDocument>.Create; FReloadCollection := True; end; class destructor TPrimerFixture.Destroy; begin FreeAndNil(FDataset); end; procedure TPrimerFixture.LoadCollection; var Collection: IgoMongoCollection; begin FDatabase.DropCollection('restaurants'); Collection := FDatabase.GetCollection('restaurants'); Assert.AreEqual(25359, Collection.InsertMany(FDataset)); end; procedure TPrimerFixture.LoadDataSetFromResource; var Stream: TStream; ZipFile: TZipFile; Bytes: TBytes; Reader: TStreamReader; Line: String; Doc: TgoBsonDocument; begin ZipFile := nil; Stream := TResourceStream.Create(HInstance, 'DATASET', RT_RCDATA); try ZipFile := TZipFile.Create; ZipFile.Open(Stream, zmRead); ZipFile.Read('dataset.json', Bytes); finally ZipFile.Free; Stream.Free; end; Reader := nil; Stream := TBytesStream.Create(Bytes); try Reader := TStreamReader.Create(Stream, TEncoding.UTF8); while (not Reader.EndOfStream) do begin Line := Reader.ReadLine; Doc := TgoBsonDocument.Parse(Line); FDataset.Add(Doc); end; finally Reader.Free; Stream.Free; end; end; procedure TPrimerFixture.RemoveId(const ADocument: TgoBsonDocument); begin ADocument.Remove('_id'); end; procedure TPrimerFixture.Setup; begin if (FReloadCollection) then begin LoadCollection; FReloadCollection := False; end; end; procedure TPrimerFixture.SetupFixture; begin if (FClient = nil) then begin FClient := TgoMongoClient.Create(TEST_SERVER_HOST, TEST_SERVER_PORT); FDatabase := FClient.GetDatabase('test'); LoadDataSetFromResource; FReloadCollection := True; end; end; { TTestQueryPrimer } procedure TTestQueryPrimer.GreaterThan; var Collection: IgoMongoCollection; Count: Integer; Doc: TgoBsonDocument; begin Collection := Database.GetCollection('restaurants'); Count := 0; for Doc in Collection.Find(TgoMongoFilter.Gt('grades.score', 30)) do Inc(Count); Assert.AreEqual(1959, Count); end; procedure TTestQueryPrimer.LessThan; var Collection: IgoMongoCollection; Count: Integer; Doc: TgoBsonDocument; begin Collection := Database.GetCollection('restaurants'); Count := 0; for Doc in Collection.Find(TgoMongoFilter.Lt('grades.score', 10)) do Inc(Count); Assert.AreEqual(19065, Count); end; procedure TTestQueryPrimer.LogicalAnd; var Collection: IgoMongoCollection; Count: Integer; Doc: TgoBsonDocument; begin Collection := Database.GetCollection('restaurants'); Count := 0; for Doc in Collection.Find( TgoMongoFilter.Eq('cuisine', 'Italian') and TgoMongoFilter.Eq('address.zipcode', '10075') ) do Inc(Count); Assert.AreEqual(15, Count); end; procedure TTestQueryPrimer.LogicalOr; var Collection: IgoMongoCollection; Count: Integer; Doc: TgoBsonDocument; begin Collection := Database.GetCollection('restaurants'); Count := 0; for Doc in Collection.Find( TgoMongoFilter.Eq('cuisine', 'Italian') or TgoMongoFilter.Eq('address.zipcode', '10075') ) do Inc(Count); Assert.AreEqual(1153, Count); end; procedure TTestQueryPrimer.QueryAll; var Collection: IgoMongoCollection; Count: Integer; Doc: TgoBsonDocument; begin Collection := Database.GetCollection('restaurants'); Count := 0; for Doc in Collection.Find() do Inc(Count); Assert.AreEqual(25359, Count); end; procedure TTestQueryPrimer.QueryEmbeddedDocument; var Collection: IgoMongoCollection; Count: Integer; Doc: TgoBsonDocument; begin Collection := Database.GetCollection('restaurants'); Count := 0; for Doc in Collection.Find(TgoMongoFilter.Eq('address.zipcode', '10075')) do Inc(Count); Assert.AreEqual(99, Count); end; procedure TTestQueryPrimer.QueryFieldInArray; var Collection: IgoMongoCollection; Count: Integer; Doc: TgoBsonDocument; begin Collection := Database.GetCollection('restaurants'); Count := 0; for Doc in Collection.Find(TgoMongoFilter.Eq('grades.grade', 'B')) do Inc(Count); Assert.AreEqual(8280, Count); end; procedure TTestQueryPrimer.QueryTopLevelField; var Collection: IgoMongoCollection; Count: Integer; Doc: TgoBsonDocument; begin Collection := Database.GetCollection('restaurants'); Count := 0; for Doc in Collection.Find(TgoMongoFilter.Eq('borough', 'Manhattan')) do Inc(Count); Assert.AreEqual(10259, Count); end; procedure TTestQueryPrimer.Sort; var Collection: IgoMongoCollection; Doc, Address: TgoBsonDocument; Count: Integer; Borough, ZipCode, PrevBorough, PrevZipCode: String; begin Collection := Database.GetCollection('restaurants'); PrevBorough := ''; PrevZipCode := ''; Count := 0; for Doc in Collection.Find(TgoMongoFilter.Empty, TgoMongoSort.Ascending('borough') + TgoMongoSort.Ascending('address.zipcode')) do begin Borough := Doc['borough']; Assert.IsTrue(Borough >= PrevBorough); if (Borough = PrevBorough) then begin Address := Doc['address'].AsBsonDocument; ZipCode := Address['zipcode']; Assert.IsTrue(ZipCode >= PrevZipCode); PrevZipCode := ZipCode; end else PrevZipCode := ''; PrevBorough := Borough; Inc(Count); end; Assert.IsTrue(PrevBorough <> ''); Assert.AreEqual(25359, Count); end; { TTestInsertPrimer } procedure TTestInsertPrimer.InsertADocument; var Doc, Result: TgoBsonDocument; Collection: IgoMongoCollection; begin AltersCollection; Doc := TgoBsonDocument.Create() .Add('address', TgoBsonDocument.Create() .Add('street', '2 Avenue') .Add('zipcode', '10075') .Add('building', '1480') .Add('coord', TgoBsonArray.Create([73.9557413, 40.7720266]))) .Add('borough', 'Manhattan') .Add('cuisine', 'Italian') .Add('grades', TgoBsonArray.Create([ TgoBsonDocument.Create() .Add('date', EncodeDateTime(2014, 10, 1, 0, 0, 0, 0)) .Add('grade', 'A') .Add('score', 11), TgoBsonDocument.Create() .Add('date', EncodeDateTime(2014, 1, 6, 0, 0, 0, 0)) .Add('grade', 'B') .Add('score', 17)])) .Add('name', 'Vella') .Add('restaurant_id', '941704620'); Collection := Database.GetCollection('restaurants'); Assert.IsTrue(Collection.InsertOne(Doc)); Result := Collection.FindOne(TgoMongoFilter.Eq('restaurant_id', '941704620')); RemoveId(Result); CheckEquals(Doc, Result); end; { TTestRemovePrimer } procedure TTestRemovePrimer.DropCollection; var Collections: TArray<String>; Index: Integer; begin AltersCollection; Collections := Database.ListCollectionNames; TArray.Sort<String>(Collections); Assert.IsTrue(TArray.BinarySearch(Collections, 'restaurants', Index)); Database.DropCollection('restaurants'); Collections := Database.ListCollectionNames; TArray.Sort<String>(Collections); Assert.IsFalse(TArray.BinarySearch(Collections, 'restaurants', Index)); end; procedure TTestRemovePrimer.RemoveAllDocuments; var Collection: IgoMongoCollection; Count: Integer; begin AltersCollection; Collection := Database.GetCollection('restaurants'); Count := Collection.DeleteMany(TgoMongoFilter.Empty); Assert.AreEqual(25359, Count); end; procedure TTestRemovePrimer.RemoveMatchingDocuments; var Collection: IgoMongoCollection; Count: Integer; begin AltersCollection; Collection := Database.GetCollection('restaurants'); Count := Collection.DeleteMany(TgoMongoFilter.Eq('borough', 'Manhattan')); Assert.AreEqual(10259, Count); end; { TTestUpdatePrimer } procedure TTestUpdatePrimer.UpdateEmbeddedField; var Collection: IgoMongoCollection; Filter: TgoMongoFilter; Doc, Address: TgoBsonDocument; begin AltersCollection; Collection := Database.GetCollection('restaurants'); Filter := TgoMongoFilter.Eq('restaurant_id', '41156888'); Doc := Collection.FindOne(Filter); Address := Doc['address'].AsBsonDocument; Assert.AreEqual(Address['street'].AsString, 'East 31 Street'); Assert.IsTrue(Collection.UpdateOne(Filter, TgoMongoUpdate.Init.&Set('address.street', 'East 31st Street'))); Doc := Collection.FindOne(Filter); Address := Doc['address'].AsBsonDocument; Assert.AreEqual(Address['street'].AsString, 'East 31st Street'); end; procedure TTestUpdatePrimer.UpdateMultipleDocuments; var Collection: IgoMongoCollection; FilterOld, FilterNew: TgoMongoFilter; begin AltersCollection; Collection := Database.GetCollection('restaurants'); FilterOld := TgoMongoFilter.Eq('address.zipcode', '10016') and TgoMongoFilter.Eq('cuisine', 'Other'); FilterNew := TgoMongoFilter.Eq('address.zipcode', '10016') and TgoMongoFilter.Eq('cuisine', 'Category To Be Determined'); Assert.AreEqual(20, Collection.Count(FilterOld)); Assert.AreEqual(0, Collection.Count(FilterNew)); Assert.AreEqual(20, Collection.UpdateMany(FilterOld, TgoMongoUpdate.Init .&Set('cuisine', 'Category To Be Determined') .CurrentDate('lastModified'))); Assert.AreEqual(0, Collection.Count(FilterOld)); Assert.AreEqual(20, Collection.Count(FilterNew)); end; procedure TTestUpdatePrimer.UpdateTopLevelFields; var Collection: IgoMongoCollection; Doc: TgoBsonDocument; begin AltersCollection; Collection := Database.GetCollection('restaurants'); Doc := Collection.FindOne(TgoMongoFilter.Eq('name', 'Juni')); Assert.AreEqual(Doc['cuisine'].AsString, 'American '); Assert.IsTrue(Collection.UpdateOne( TgoMongoFilter.Eq('name', 'Juni'), TgoMongoUpdate.Init .&Set('cuisine', 'American (New)') .CurrentDate('lastModified'))); Doc := Collection.FindOne(TgoMongoFilter.Eq('name', 'Juni')); Assert.AreEqual(Doc['cuisine'].AsString, 'American (New)'); end; initialization TDUnitX.RegisterTestFixture(TTestDocumentationSamples); TDUnitX.RegisterTestFixture(TTestQueryPrimer); TDUnitX.RegisterTestFixture(TTestInsertPrimer); TDUnitX.RegisterTestFixture(TTestRemovePrimer); TDUnitX.RegisterTestFixture(TTestUpdatePrimer); end.
unit UnitCreateProject; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TFormCreateProject = class(TForm) EditProjectName: TEdit; Label1: TLabel; Edit1: TEdit; Label2: TLabel; ButtonFinish: TButton; ButtonCancel: TButton; Label4: TLabel; Label3: TLabel; procedure ButtonCancelClick(Sender: TObject); procedure EditProjectNameChange(Sender: TObject); procedure ButtonFinishClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var FormCreateProject: TFormCreateProject; implementation uses UnitCodeGenerator, UnitCreateModule, System.UITypes; {$R *.dfm} procedure TFormCreateProject.ButtonCancelClick(Sender: TObject); begin Self.Close; end; procedure TFormCreateProject.ButtonFinishClick(Sender: TObject); begin if Not DirectoryExists(Edit1.Text) then begin if CreateDir(Edit1.Text) then begin EZCodeGenerator.TreeViewProjectExplorer.SelectedFolder := Edit1.Text; Self.Close; FormCreateModule.ShowModal; end else MessageDlg('Project create failed!', mtError, [mbOK], 0); end else MessageDlg('This project already exited!', mtError, [mbOK], 0); end; procedure TFormCreateProject.EditProjectNameChange(Sender: TObject); begin Edit1.Text := EZCodeGenerator.TreeViewProjectExplorer.RootedAtFileSystemFolder + '\' + EditProjectName.Text; end; end.
program HelloUser; procedure Main(); var name: String; age, year, yearBorn: Integer; begin // Read the user's name WriteLn('Please user you name: '); ReadLn(name); // Read the user's age WriteLn('How old are you this year? '); ReadLn(age); // Read the current year WriteLn('What year is it? '); ReadLn(year); // Calculate the year the user was born yearBorn := year - age; // Output the year the user was born in WriteLn('Hello, ', name, '. You were born in ', yearBorn, '.'); // Exit WriteLn('Press Enter to continue.'); ReadLn(); end; begin Main(); end.
{$include kode.inc} unit kode_filter_onepole; { brief one pole filters leaky integrator with various routings to get shelving and high pass 0: no filter 1: lp 2: hp 3: ls 4: hs } //---------------------------------------------------------------------- interface //---------------------------------------------------------------------- type KFilter_OnePole = class private FType : longword; FInterpolate : Boolean; a0, b1, y : Single; _gain, _gain2 : Single; i_a0, i_b1 : Single; d_a0, d_b1 : Single; s_a0, s_b1 : Single; private procedure reset_p; public constructor create; procedure setup(AType:LongWord=0; ASRate:Single=44100; AFreq:Single=11000; AGain:Single=1; AInterp:Boolean=False); procedure interpolate(AFrames:LongInt); function process(AInput:Single) : Single; end; //---------------------------------------------------------------------- implementation //---------------------------------------------------------------------- uses kode_const; constructor KFilter_OnePole.create; begin inherited; reset_p; FInterpolate := False; FType := 0; setup; end; //---------- // reset parameters (private) procedure KFilter_OnePole.reset_p; begin i_a0 := 0; i_b1 := 0; d_a0 := 0; d_b1 := 0; s_a0 := 0; s_b1 := 0; end; //---------- { setup filter filter types: 0 - no filter 1 - low pass 2 - high pass 3 - low shelf 4 - high shelf type unsigned int - filter type (0 - 4) srate float - sample rate (Hz) freq float - frequency (Hz) gain float - gain (dB) intrp bool - parameter interpolation (on / off) } procedure KFilter_OnePole.setup(AType:LongWord=0; ASRate:Single=44100; AFreq:Single=11000; AGain:Single=1; AInterp:Boolean=False); begin //gain _gain := 1; //axDB2Lin(gain); _gain2 := _gain - 1; // reset params if filter has changed if AType <> FType then reset_p; // if type out of range set to 0 FType := AType; if (FType < 0) or (FType > 4) then FType := 0; // coeff b1 := {axExpf}exp(-KODE_PI2*AFreq / ASRate); a0 := 1 - b1; // has interpolation FInterpolate := True; if not AInterp then begin i_a0 := a0; i_b1 := b1; FInterpolate := false; end; end; //---------- { interpolate filter coeff call this from axFormat::doProcessBlock(..) or each N samples: myfilter.interpolate(N) } procedure KFilter_OnePole.interpolate(AFrames:LongInt); var inv_sb : Single; begin if FInterpolate and (FType <> 0) then begin inv_sb := 1 / AFrames; // --- d_a0 := (a0 - s_a0)*inv_sb; i_a0 := s_a0; s_a0 := a0; // --- d_b1 := (b1 - s_b1)*inv_sb; i_b1 := s_b1; s_b1 := b1; end; end; //---------- function KFilter_OnePole.process(AInput:Single) : Single; begin if FInterpolate then begin i_a0 += d_a0; i_b1 += d_b1; end; case FType of 0: // no filter result := AInput * _gain; 1: // lp begin y := (i_a0 * AInput) + (i_b1*y) + KODE_DENORM; result := (y - KODE_DENORM) * _gain; end; 2: // hp begin y := (i_a0 * AInput) + (i_b1*y) + KODE_DENORM; result := (AInput - y - KODE_DENORM) * _gain; end; 3: // ls begin y := (i_a0*AInput) + (i_b1*y) + KODE_DENORM; result := AInput + ((y - KODE_DENORM) * _gain2); end; 4: // hs begin y := (i_a0*AInput) + (i_b1*y) + KODE_DENORM; result := AInput + ((AInput - y - KODE_DENORM) * _gain2); end; end; end; //---------------------------------------------------------------------- end.
{ Remove master references from overriding cell that have the same scale, position and rotation as references in the master cell. Usefull when plugin was merged into the master file, but modified later and now there is a need to find refs that have already been merged. Since references usually don't have Editor ID and their FormIDs have also changed in master file after the merging process, the only way to find them is by using base record or model, position, rotation and scale. When bDetectByModel = False, base record will be used for detection, in case when duplicated references put the same record in the same spot. When bDetectByModel = True, base record model file name will be used, in case when duplicated references put different records in the same spot, however the put model is the same. } unit RemoveSameReferencesAgainstMaster; const bDetectByModel = False; bReportOnly = True; // True - only report found refs, False - report and remove them var slRefs: TStringList; function Initialize: integer; begin slRefs := TwbFastStringList.Create; end; function IsRef(e: IInterface): Boolean; begin Result := Pos(Signature(e), 'REFR ACHR ACRE PMIS PHZD PGRE PARW PBAR PBEA PCON PFLA') <> 0; end; function GetToken(e: IInterface): string; var id: string; begin if bDetectByModel then // detect by base record model name id := LowerCase(GetElementEditValues(BaseRecord(e), 'Model\MODL')) else // detect by base record id := Name(BaseRecord(e)); Result := Format('%s %s %d %d %d %d %d %d', [ id, GetElementEditValues(e, 'XSCL'), Round(GetElementNativeValues(e, 'DATA\Position\X')), Round(GetElementNativeValues(e, 'DATA\Position\Y')), Round(GetElementNativeValues(e, 'DATA\Position\Z')), Round(GetElementNativeValues(e, 'DATA\Rotation\X')), Round(GetElementNativeValues(e, 'DATA\Rotation\Y')), Round(GetElementNativeValues(e, 'DATA\Rotation\Z')) ]); end; procedure CompareReferences(cell1, cell2: IInterface; GroupType: integer); var refs, ref: IInterface; i: integer; token: string; begin slRefs.Clear; // gather master refs from the first (master) cell refs := FindChildGroup(ChildGroup(cell1), GroupType, cell1); for i := 0 to Pred(ElementCount(refs)) do begin ref := ElementByIndex(refs, i); if IsMaster(ref) and IsRef(ref) then slRefs.Add(GetToken(ref)); end; // compare against master refs from the second (overriding) cell refs := FindChildGroup(ChildGroup(cell2), GroupType, cell2); for i := 0 to Pred(ElementCount(refs)) do begin ref := ElementByIndex(refs, i); if IsMaster(ref) and IsRef(ref) then begin token := GetToken(ref); if slRefs.IndexOf(token) <> -1 then begin AddMessage('Removing: ' + Name(ref)); if not bReportOnly then RemoveNode(ref); end; end; end; end; function Process(e: IInterface): integer; begin // check per cell if Signature(e) <> 'CELL' then Exit; // only for overriding cell (we need a master cell to compare) if IsMaster(e) then Exit; // persistent refs CompareReferences(Master(e), e, 8); // temporary refs CompareReferences(Master(e), e, 9); end; function Finalize: integer; begin slRefs.Free; end; end.
{******************************************************************************} {* DCPcrypt v2.0 written by David Barton (crypto@cityinthesky.co.uk) **********} {******************************************************************************} {* A binary compatible implementation of RipeMD-160 ***************************} {******************************************************************************} {* Copyright (c) 1999-2002 David Barton *} {* Permission is hereby granted, free of charge, to any person obtaining a *} {* copy of this software and associated documentation files (the "Software"), *} {* to deal in the Software without restriction, including without limitation *} {* the rights to use, copy, modify, merge, publish, distribute, sublicense, *} {* and/or sell copies of the Software, and to permit persons to whom the *} {* Software is furnished to do so, subject to the following conditions: *} {* *} {* The above copyright notice and this permission notice shall be included in *} {* all copies or substantial portions of the Software. *} {* *} {* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *} {* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *} {* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL *} {* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *} {* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *} {* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER *} {* DEALINGS IN THE SOFTWARE. *} {******************************************************************************} unit DCPripemd160; interface uses Classes, Sysutils, DCPcrypt2, DCPconst; type TDCP_ripemd160= class(TDCP_hash) protected LenHi, LenLo: longword; Index: DWord; CurrentHash: array[0..4] of DWord; HashBuffer: array[0..63] of byte; procedure Compress; public class function GetId: integer; override; class function GetAlgorithm: string; override; class function GetHashSize: integer; override; class function SelfTest: boolean; override; procedure Init; override; procedure Burn; override; procedure Update(const Buffer; Size: longword); override; procedure Final(var Digest); override; end; {******************************************************************************} {******************************************************************************} implementation {$R-}{$Q-} procedure TDCP_ripemd160.Compress; var aa, bb, cc, dd, ee, aaa, bbb, ccc, ddd, eee: DWord; X: array[0..15] of DWord; begin Move(HashBuffer,X,Sizeof(X)); aa:= CurrentHash[0]; aaa:= CurrentHash[0]; bb:= CurrentHash[1]; bbb:= CurrentHash[1]; cc:= CurrentHash[2]; ccc:= CurrentHash[2]; dd:= CurrentHash[3]; ddd:= CurrentHash[3]; ee:= CurrentHash[4]; eee:= CurrentHash[4]; aa:= aa + (bb xor cc xor dd) + X[ 0]; aa:= ((aa shl 11) or (aa shr (32-11))) + ee; cc:= ((cc shl 10) or (cc shr (32-10))); ee:= ee + (aa xor bb xor cc) + X[ 1]; ee:= ((ee shl 14) or (ee shr (32-14))) + dd; bb:= ((bb shl 10) or (bb shr (32-10))); dd:= dd + (ee xor aa xor bb) + X[ 2]; dd:= ((dd shl 15) or (dd shr (32-15))) + cc; aa:= ((aa shl 10) or (aa shr (32-10))); cc:= cc + (dd xor ee xor aa) + X[ 3]; cc:= ((cc shl 12) or (cc shr (32-12))) + bb; ee:= ((ee shl 10) or (ee shr (32-10))); bb:= bb + (cc xor dd xor ee) + X[ 4]; bb:= ((bb shl 5) or (bb shr (32-5))) + aa; dd:= ((dd shl 10) or (dd shr (32-10))); aa:= aa + (bb xor cc xor dd) + X[ 5]; aa:= ((aa shl 8) or (aa shr (32-8))) + ee; cc:= ((cc shl 10) or (cc shr (32-10))); ee:= ee + (aa xor bb xor cc) + X[ 6]; ee:= ((ee shl 7) or (ee shr (32-7))) + dd; bb:= ((bb shl 10) or (bb shr (32-10))); dd:= dd + (ee xor aa xor bb) + X[ 7]; dd:= ((dd shl 9) or (dd shr (32-9))) + cc; aa:= ((aa shl 10) or (aa shr (32-10))); cc:= cc + (dd xor ee xor aa) + X[ 8]; cc:= ((cc shl 11) or (cc shr (32-11))) + bb; ee:= ((ee shl 10) or (ee shr (32-10))); bb:= bb + (cc xor dd xor ee) + X[ 9]; bb:= ((bb shl 13) or (bb shr (32-13))) + aa; dd:= ((dd shl 10) or (dd shr (32-10))); aa:= aa + (bb xor cc xor dd) + X[10]; aa:= ((aa shl 14) or (aa shr (32-14))) + ee; cc:= ((cc shl 10) or (cc shr (32-10))); ee:= ee + (aa xor bb xor cc) + X[11]; ee:= ((ee shl 15) or (ee shr (32-15))) + dd; bb:= ((bb shl 10) or (bb shr (32-10))); dd:= dd + (ee xor aa xor bb) + X[12]; dd:= ((dd shl 6) or (dd shr (32-6))) + cc; aa:= ((aa shl 10) or (aa shr (32-10))); cc:= cc + (dd xor ee xor aa) + X[13]; cc:= ((cc shl 7) or (cc shr (32-7))) + bb; ee:= ((ee shl 10) or (ee shr (32-10))); bb:= bb + (cc xor dd xor ee) + X[14]; bb:= ((bb shl 9) or (bb shr (32-9))) + aa; dd:= ((dd shl 10) or (dd shr (32-10))); aa:= aa + (bb xor cc xor dd) + X[15]; aa:= ((aa shl 8) or (aa shr (32-8))) + ee; cc:= ((cc shl 10) or (cc shr (32-10))); ee:= ee + ((aa and bb) or ((not aa) and cc)) + X[ 7] + $5a827999; ee:= ((ee shl 7) or (ee shr (32-7))) + dd; bb:= ((bb shl 10) or (bb shr (32-10))); dd:= dd + ((ee and aa) or ((not ee) and bb)) + X[ 4] + $5a827999; dd:= ((dd shl 6) or (dd shr (32-6))) + cc; aa:= ((aa shl 10) or (aa shr (32-10))); cc:= cc + ((dd and ee) or ((not dd) and aa)) + X[13] + $5a827999; cc:= ((cc shl 8) or (cc shr (32-8))) + bb; ee:= ((ee shl 10) or (ee shr (32-10))); bb:= bb + ((cc and dd) or ((not cc) and ee)) + X[ 1] + $5a827999; bb:= ((bb shl 13) or (bb shr (32-13))) + aa; dd:= ((dd shl 10) or (dd shr (32-10))); aa:= aa + ((bb and cc) or ((not bb) and dd)) + X[10] + $5a827999; aa:= ((aa shl 11) or (aa shr (32-11))) + ee; cc:= ((cc shl 10) or (cc shr (32-10))); ee:= ee + ((aa and bb) or ((not aa) and cc)) + X[ 6] + $5a827999; ee:= ((ee shl 9) or (ee shr (32-9))) + dd; bb:= ((bb shl 10) or (bb shr (32-10))); dd:= dd + ((ee and aa) or ((not ee) and bb)) + X[15] + $5a827999; dd:= ((dd shl 7) or (dd shr (32-7))) + cc; aa:= ((aa shl 10) or (aa shr (32-10))); cc:= cc + ((dd and ee) or ((not dd) and aa)) + X[ 3] + $5a827999; cc:= ((cc shl 15) or (cc shr (32-15))) + bb; ee:= ((ee shl 10) or (ee shr (32-10))); bb:= bb + ((cc and dd) or ((not cc) and ee)) + X[12] + $5a827999; bb:= ((bb shl 7) or (bb shr (32-7))) + aa; dd:= ((dd shl 10) or (dd shr (32-10))); aa:= aa + ((bb and cc) or ((not bb) and dd)) + X[ 0] + $5a827999; aa:= ((aa shl 12) or (aa shr (32-12))) + ee; cc:= ((cc shl 10) or (cc shr (32-10))); ee:= ee + ((aa and bb) or ((not aa) and cc)) + X[ 9] + $5a827999; ee:= ((ee shl 15) or (ee shr (32-15))) + dd; bb:= ((bb shl 10) or (bb shr (32-10))); dd:= dd + ((ee and aa) or ((not ee) and bb)) + X[ 5] + $5a827999; dd:= ((dd shl 9) or (dd shr (32-9))) + cc; aa:= ((aa shl 10) or (aa shr (32-10))); cc:= cc + ((dd and ee) or ((not dd) and aa)) + X[ 2] + $5a827999; cc:= ((cc shl 11) or (cc shr (32-11))) + bb; ee:= ((ee shl 10) or (ee shr (32-10))); bb:= bb + ((cc and dd) or ((not cc) and ee)) + X[14] + $5a827999; bb:= ((bb shl 7) or (bb shr (32-7))) + aa; dd:= ((dd shl 10) or (dd shr (32-10))); aa:= aa + ((bb and cc) or ((not bb) and dd)) + X[11] + $5a827999; aa:= ((aa shl 13) or (aa shr (32-13))) + ee; cc:= ((cc shl 10) or (cc shr (32-10))); ee:= ee + ((aa and bb) or ((not aa) and cc)) + X[ 8] + $5a827999; ee:= ((ee shl 12) or (ee shr (32-12))) + dd; bb:= ((bb shl 10) or (bb shr (32-10))); dd:= dd + ((ee or (not aa)) xor bb) + X[ 3] + $6ed9eba1; dd:= ((dd shl 11) or (dd shr (32-11))) + cc; aa:= ((aa shl 10) or (aa shr (32-10))); cc:= cc + ((dd or (not ee)) xor aa) + X[10] + $6ed9eba1; cc:= ((cc shl 13) or (cc shr (32-13))) + bb; ee:= ((ee shl 10) or (ee shr (32-10))); bb:= bb + ((cc or (not dd)) xor ee) + X[14] + $6ed9eba1; bb:= ((bb shl 6) or (bb shr (32-6))) + aa; dd:= ((dd shl 10) or (dd shr (32-10))); aa:= aa + ((bb or (not cc)) xor dd) + X[ 4] + $6ed9eba1; aa:= ((aa shl 7) or (aa shr (32-7))) + ee; cc:= ((cc shl 10) or (cc shr (32-10))); ee:= ee + ((aa or (not bb)) xor cc) + X[ 9] + $6ed9eba1; ee:= ((ee shl 14) or (ee shr (32-14))) + dd; bb:= ((bb shl 10) or (bb shr (32-10))); dd:= dd + ((ee or (not aa)) xor bb) + X[15] + $6ed9eba1; dd:= ((dd shl 9) or (dd shr (32-9))) + cc; aa:= ((aa shl 10) or (aa shr (32-10))); cc:= cc + ((dd or (not ee)) xor aa) + X[ 8] + $6ed9eba1; cc:= ((cc shl 13) or (cc shr (32-13))) + bb; ee:= ((ee shl 10) or (ee shr (32-10))); bb:= bb + ((cc or (not dd)) xor ee) + X[ 1] + $6ed9eba1; bb:= ((bb shl 15) or (bb shr (32-15))) + aa; dd:= ((dd shl 10) or (dd shr (32-10))); aa:= aa + ((bb or (not cc)) xor dd) + X[ 2] + $6ed9eba1; aa:= ((aa shl 14) or (aa shr (32-14))) + ee; cc:= ((cc shl 10) or (cc shr (32-10))); ee:= ee + ((aa or (not bb)) xor cc) + X[ 7] + $6ed9eba1; ee:= ((ee shl 8) or (ee shr (32-8))) + dd; bb:= ((bb shl 10) or (bb shr (32-10))); dd:= dd + ((ee or (not aa)) xor bb) + X[ 0] + $6ed9eba1; dd:= ((dd shl 13) or (dd shr (32-13))) + cc; aa:= ((aa shl 10) or (aa shr (32-10))); cc:= cc + ((dd or (not ee)) xor aa) + X[ 6] + $6ed9eba1; cc:= ((cc shl 6) or (cc shr (32-6))) + bb; ee:= ((ee shl 10) or (ee shr (32-10))); bb:= bb + ((cc or (not dd)) xor ee) + X[13] + $6ed9eba1; bb:= ((bb shl 5) or (bb shr (32-5))) + aa; dd:= ((dd shl 10) or (dd shr (32-10))); aa:= aa + ((bb or (not cc)) xor dd) + X[11] + $6ed9eba1; aa:= ((aa shl 12) or (aa shr (32-12))) + ee; cc:= ((cc shl 10) or (cc shr (32-10))); ee:= ee + ((aa or (not bb)) xor cc) + X[ 5] + $6ed9eba1; ee:= ((ee shl 7) or (ee shr (32-7))) + dd; bb:= ((bb shl 10) or (bb shr (32-10))); dd:= dd + ((ee or (not aa)) xor bb) + X[12] + $6ed9eba1; dd:= ((dd shl 5) or (dd shr (32-5))) + cc; aa:= ((aa shl 10) or (aa shr (32-10))); cc:= cc + ((dd and aa) or (ee and (not aa))) + X[ 1] + $8f1bbcdc; cc:= ((cc shl 11) or (cc shr (32-11))) + bb; ee:= ((ee shl 10) or (ee shr (32-10))); bb:= bb + ((cc and ee) or (dd and (not ee))) + X[ 9] + $8f1bbcdc; bb:= ((bb shl 12) or (bb shr (32-12))) + aa; dd:= ((dd shl 10) or (dd shr (32-10))); aa:= aa + ((bb and dd) or (cc and (not dd))) + X[11] + $8f1bbcdc; aa:= ((aa shl 14) or (aa shr (32-14))) + ee; cc:= ((cc shl 10) or (cc shr (32-10))); ee:= ee + ((aa and cc) or (bb and (not cc))) + X[10] + $8f1bbcdc; ee:= ((ee shl 15) or (ee shr (32-15))) + dd; bb:= ((bb shl 10) or (bb shr (32-10))); dd:= dd + ((ee and bb) or (aa and (not bb))) + X[ 0] + $8f1bbcdc; dd:= ((dd shl 14) or (dd shr (32-14))) + cc; aa:= ((aa shl 10) or (aa shr (32-10))); cc:= cc + ((dd and aa) or (ee and (not aa))) + X[ 8] + $8f1bbcdc; cc:= ((cc shl 15) or (cc shr (32-15))) + bb; ee:= ((ee shl 10) or (ee shr (32-10))); bb:= bb + ((cc and ee) or (dd and (not ee))) + X[12] + $8f1bbcdc; bb:= ((bb shl 9) or (bb shr (32-9))) + aa; dd:= ((dd shl 10) or (dd shr (32-10))); aa:= aa + ((bb and dd) or (cc and (not dd))) + X[ 4] + $8f1bbcdc; aa:= ((aa shl 8) or (aa shr (32-8))) + ee; cc:= ((cc shl 10) or (cc shr (32-10))); ee:= ee + ((aa and cc) or (bb and (not cc))) + X[13] + $8f1bbcdc; ee:= ((ee shl 9) or (ee shr (32-9))) + dd; bb:= ((bb shl 10) or (bb shr (32-10))); dd:= dd + ((ee and bb) or (aa and (not bb))) + X[ 3] + $8f1bbcdc; dd:= ((dd shl 14) or (dd shr (32-14))) + cc; aa:= ((aa shl 10) or (aa shr (32-10))); cc:= cc + ((dd and aa) or (ee and (not aa))) + X[ 7] + $8f1bbcdc; cc:= ((cc shl 5) or (cc shr (32-5))) + bb; ee:= ((ee shl 10) or (ee shr (32-10))); bb:= bb + ((cc and ee) or (dd and (not ee))) + X[15] + $8f1bbcdc; bb:= ((bb shl 6) or (bb shr (32-6))) + aa; dd:= ((dd shl 10) or (dd shr (32-10))); aa:= aa + ((bb and dd) or (cc and (not dd))) + X[14] + $8f1bbcdc; aa:= ((aa shl 8) or (aa shr (32-8))) + ee; cc:= ((cc shl 10) or (cc shr (32-10))); ee:= ee + ((aa and cc) or (bb and (not cc))) + X[ 5] + $8f1bbcdc; ee:= ((ee shl 6) or (ee shr (32-6))) + dd; bb:= ((bb shl 10) or (bb shr (32-10))); dd:= dd + ((ee and bb) or (aa and (not bb))) + X[ 6] + $8f1bbcdc; dd:= ((dd shl 5) or (dd shr (32-5))) + cc; aa:= ((aa shl 10) or (aa shr (32-10))); cc:= cc + ((dd and aa) or (ee and (not aa))) + X[ 2] + $8f1bbcdc; cc:= ((cc shl 12) or (cc shr (32-12))) + bb; ee:= ((ee shl 10) or (ee shr (32-10))); bb:= bb + (cc xor (dd or (not ee))) + X[ 4] + $a953fd4e; bb:= ((bb shl 9) or (bb shr (32-9))) + aa; dd:= ((dd shl 10) or (dd shr (32-10))); aa:= aa + (bb xor (cc or (not dd))) + X[ 0] + $a953fd4e; aa:= ((aa shl 15) or (aa shr (32-15))) + ee; cc:= ((cc shl 10) or (cc shr (32-10))); ee:= ee + (aa xor (bb or (not cc))) + X[ 5] + $a953fd4e; ee:= ((ee shl 5) or (ee shr (32-5))) + dd; bb:= ((bb shl 10) or (bb shr (32-10))); dd:= dd + (ee xor (aa or (not bb))) + X[ 9] + $a953fd4e; dd:= ((dd shl 11) or (dd shr (32-11))) + cc; aa:= ((aa shl 10) or (aa shr (32-10))); cc:= cc + (dd xor (ee or (not aa))) + X[ 7] + $a953fd4e; cc:= ((cc shl 6) or (cc shr (32-6))) + bb; ee:= ((ee shl 10) or (ee shr (32-10))); bb:= bb + (cc xor (dd or (not ee))) + X[12] + $a953fd4e; bb:= ((bb shl 8) or (bb shr (32-8))) + aa; dd:= ((dd shl 10) or (dd shr (32-10))); aa:= aa + (bb xor (cc or (not dd))) + X[ 2] + $a953fd4e; aa:= ((aa shl 13) or (aa shr (32-13))) + ee; cc:= ((cc shl 10) or (cc shr (32-10))); ee:= ee + (aa xor (bb or (not cc))) + X[10] + $a953fd4e; ee:= ((ee shl 12) or (ee shr (32-12))) + dd; bb:= ((bb shl 10) or (bb shr (32-10))); dd:= dd + (ee xor (aa or (not bb))) + X[14] + $a953fd4e; dd:= ((dd shl 5) or (dd shr (32-5))) + cc; aa:= ((aa shl 10) or (aa shr (32-10))); cc:= cc + (dd xor (ee or (not aa))) + X[ 1] + $a953fd4e; cc:= ((cc shl 12) or (cc shr (32-12))) + bb; ee:= ((ee shl 10) or (ee shr (32-10))); bb:= bb + (cc xor (dd or (not ee))) + X[ 3] + $a953fd4e; bb:= ((bb shl 13) or (bb shr (32-13))) + aa; dd:= ((dd shl 10) or (dd shr (32-10))); aa:= aa + (bb xor (cc or (not dd))) + X[ 8] + $a953fd4e; aa:= ((aa shl 14) or (aa shr (32-14))) + ee; cc:= ((cc shl 10) or (cc shr (32-10))); ee:= ee + (aa xor (bb or (not cc))) + X[11] + $a953fd4e; ee:= ((ee shl 11) or (ee shr (32-11))) + dd; bb:= ((bb shl 10) or (bb shr (32-10))); dd:= dd + (ee xor (aa or (not bb))) + X[ 6] + $a953fd4e; dd:= ((dd shl 8) or (dd shr (32-8))) + cc; aa:= ((aa shl 10) or (aa shr (32-10))); cc:= cc + (dd xor (ee or (not aa))) + X[15] + $a953fd4e; cc:= ((cc shl 5) or (cc shr (32-5))) + bb; ee:= ((ee shl 10) or (ee shr (32-10))); bb:= bb + (cc xor (dd or (not ee))) + X[13] + $a953fd4e; bb:= ((bb shl 6) or (bb shr (32-6))) + aa; dd:= ((dd shl 10) or (dd shr (32-10))); aaa:= aaa + (bbb xor (ccc or (not ddd))) + X[ 5] + $50a28be6; aaa:= ((aaa shl 8) or (aaa shr (32-8))) + eee; ccc:= ((ccc shl 10) or (ccc shr (32-10))); eee:= eee + (aaa xor (bbb or (not ccc))) + X[14] + $50a28be6; eee:= ((eee shl 9) or (eee shr (32-9))) + ddd; bbb:= ((bbb shl 10) or (bbb shr (32-10))); ddd:= ddd + (eee xor (aaa or (not bbb))) + X[ 7] + $50a28be6; ddd:= ((ddd shl 9) or (ddd shr (32-9))) + ccc; aaa:= ((aaa shl 10) or (aaa shr (32-10))); ccc:= ccc + (ddd xor (eee or (not aaa))) + X[ 0] + $50a28be6; ccc:= ((ccc shl 11) or (ccc shr (32-11))) + bbb; eee:= ((eee shl 10) or (eee shr (32-10))); bbb:= bbb + (ccc xor (ddd or (not eee))) + X[ 9] + $50a28be6; bbb:= ((bbb shl 13) or (bbb shr (32-13))) + aaa; ddd:= ((ddd shl 10) or (ddd shr (32-10))); aaa:= aaa + (bbb xor (ccc or (not ddd))) + X[ 2] + $50a28be6; aaa:= ((aaa shl 15) or (aaa shr (32-15))) + eee; ccc:= ((ccc shl 10) or (ccc shr (32-10))); eee:= eee + (aaa xor (bbb or (not ccc))) + X[11] + $50a28be6; eee:= ((eee shl 15) or (eee shr (32-15))) + ddd; bbb:= ((bbb shl 10) or (bbb shr (32-10))); ddd:= ddd + (eee xor (aaa or (not bbb))) + X[ 4] + $50a28be6; ddd:= ((ddd shl 5) or (ddd shr (32-5))) + ccc; aaa:= ((aaa shl 10) or (aaa shr (32-10))); ccc:= ccc + (ddd xor (eee or (not aaa))) + X[13] + $50a28be6; ccc:= ((ccc shl 7) or (ccc shr (32-7))) + bbb; eee:= ((eee shl 10) or (eee shr (32-10))); bbb:= bbb + (ccc xor (ddd or (not eee))) + X[ 6] + $50a28be6; bbb:= ((bbb shl 7) or (bbb shr (32-7))) + aaa; ddd:= ((ddd shl 10) or (ddd shr (32-10))); aaa:= aaa + (bbb xor (ccc or (not ddd))) + X[15] + $50a28be6; aaa:= ((aaa shl 8) or (aaa shr (32-8))) + eee; ccc:= ((ccc shl 10) or (ccc shr (32-10))); eee:= eee + (aaa xor (bbb or (not ccc))) + X[ 8] + $50a28be6; eee:= ((eee shl 11) or (eee shr (32-11))) + ddd; bbb:= ((bbb shl 10) or (bbb shr (32-10))); ddd:= ddd + (eee xor (aaa or (not bbb))) + X[ 1] + $50a28be6; ddd:= ((ddd shl 14) or (ddd shr (32-14))) + ccc; aaa:= ((aaa shl 10) or (aaa shr (32-10))); ccc:= ccc + (ddd xor (eee or (not aaa))) + X[10] + $50a28be6; ccc:= ((ccc shl 14) or (ccc shr (32-14))) + bbb; eee:= ((eee shl 10) or (eee shr (32-10))); bbb:= bbb + (ccc xor (ddd or (not eee))) + X[ 3] + $50a28be6; bbb:= ((bbb shl 12) or (bbb shr (32-12))) + aaa; ddd:= ((ddd shl 10) or (ddd shr (32-10))); aaa:= aaa + (bbb xor (ccc or (not ddd))) + X[12] + $50a28be6; aaa:= ((aaa shl 6) or (aaa shr (32-6))) + eee; ccc:= ((ccc shl 10) or (ccc shr (32-10))); eee:= eee + ((aaa and ccc) or (bbb and (not ccc))) + X[ 6] + $5c4dd124; eee:= ((eee shl 9) or (eee shr (32-9))) + ddd; bbb:= ((bbb shl 10) or (bbb shr (32-10))); ddd:= ddd + ((eee and bbb) or (aaa and (not bbb))) + X[11] + $5c4dd124; ddd:= ((ddd shl 13) or (ddd shr (32-13))) + ccc; aaa:= ((aaa shl 10) or (aaa shr (32-10))); ccc:= ccc + ((ddd and aaa) or (eee and (not aaa))) + X[ 3] + $5c4dd124; ccc:= ((ccc shl 15) or (ccc shr (32-15))) + bbb; eee:= ((eee shl 10) or (eee shr (32-10))); bbb:= bbb + ((ccc and eee) or (ddd and (not eee))) + X[ 7] + $5c4dd124; bbb:= ((bbb shl 7) or (bbb shr (32-7))) + aaa; ddd:= ((ddd shl 10) or (ddd shr (32-10))); aaa:= aaa + ((bbb and ddd) or (ccc and (not ddd))) + X[ 0] + $5c4dd124; aaa:= ((aaa shl 12) or (aaa shr (32-12))) + eee; ccc:= ((ccc shl 10) or (ccc shr (32-10))); eee:= eee + ((aaa and ccc) or (bbb and (not ccc))) + X[13] + $5c4dd124; eee:= ((eee shl 8) or (eee shr (32-8))) + ddd; bbb:= ((bbb shl 10) or (bbb shr (32-10))); ddd:= ddd + ((eee and bbb) or (aaa and (not bbb))) + X[ 5] + $5c4dd124; ddd:= ((ddd shl 9) or (ddd shr (32-9))) + ccc; aaa:= ((aaa shl 10) or (aaa shr (32-10))); ccc:= ccc + ((ddd and aaa) or (eee and (not aaa))) + X[10] + $5c4dd124; ccc:= ((ccc shl 11) or (ccc shr (32-11))) + bbb; eee:= ((eee shl 10) or (eee shr (32-10))); bbb:= bbb + ((ccc and eee) or (ddd and (not eee))) + X[14] + $5c4dd124; bbb:= ((bbb shl 7) or (bbb shr (32-7))) + aaa; ddd:= ((ddd shl 10) or (ddd shr (32-10))); aaa:= aaa + ((bbb and ddd) or (ccc and (not ddd))) + X[15] + $5c4dd124; aaa:= ((aaa shl 7) or (aaa shr (32-7))) + eee; ccc:= ((ccc shl 10) or (ccc shr (32-10))); eee:= eee + ((aaa and ccc) or (bbb and (not ccc))) + X[ 8] + $5c4dd124; eee:= ((eee shl 12) or (eee shr (32-12))) + ddd; bbb:= ((bbb shl 10) or (bbb shr (32-10))); ddd:= ddd + ((eee and bbb) or (aaa and (not bbb))) + X[12] + $5c4dd124; ddd:= ((ddd shl 7) or (ddd shr (32-7))) + ccc; aaa:= ((aaa shl 10) or (aaa shr (32-10))); ccc:= ccc + ((ddd and aaa) or (eee and (not aaa))) + X[ 4] + $5c4dd124; ccc:= ((ccc shl 6) or (ccc shr (32-6))) + bbb; eee:= ((eee shl 10) or (eee shr (32-10))); bbb:= bbb + ((ccc and eee) or (ddd and (not eee))) + X[ 9] + $5c4dd124; bbb:= ((bbb shl 15) or (bbb shr (32-15))) + aaa; ddd:= ((ddd shl 10) or (ddd shr (32-10))); aaa:= aaa + ((bbb and ddd) or (ccc and (not ddd))) + X[ 1] + $5c4dd124; aaa:= ((aaa shl 13) or (aaa shr (32-13))) + eee; ccc:= ((ccc shl 10) or (ccc shr (32-10))); eee:= eee + ((aaa and ccc) or (bbb and (not ccc))) + X[ 2] + $5c4dd124; eee:= ((eee shl 11) or (eee shr (32-11))) + ddd; bbb:= ((bbb shl 10) or (bbb shr (32-10))); ddd:= ddd + ((eee or (not aaa)) xor bbb) + X[15] + $6d703ef3; ddd:= ((ddd shl 9) or (ddd shr (32-9))) + ccc; aaa:= ((aaa shl 10) or (aaa shr (32-10))); ccc:= ccc + ((ddd or (not eee)) xor aaa) + X[ 5] + $6d703ef3; ccc:= ((ccc shl 7) or (ccc shr (32-7))) + bbb; eee:= ((eee shl 10) or (eee shr (32-10))); bbb:= bbb + ((ccc or (not ddd)) xor eee) + X[ 1] + $6d703ef3; bbb:= ((bbb shl 15) or (bbb shr (32-15))) + aaa; ddd:= ((ddd shl 10) or (ddd shr (32-10))); aaa:= aaa + ((bbb or (not ccc)) xor ddd) + X[ 3] + $6d703ef3; aaa:= ((aaa shl 11) or (aaa shr (32-11))) + eee; ccc:= ((ccc shl 10) or (ccc shr (32-10))); eee:= eee + ((aaa or (not bbb)) xor ccc) + X[ 7] + $6d703ef3; eee:= ((eee shl 8) or (eee shr (32-8))) + ddd; bbb:= ((bbb shl 10) or (bbb shr (32-10))); ddd:= ddd + ((eee or (not aaa)) xor bbb) + X[14] + $6d703ef3; ddd:= ((ddd shl 6) or (ddd shr (32-6))) + ccc; aaa:= ((aaa shl 10) or (aaa shr (32-10))); ccc:= ccc + ((ddd or (not eee)) xor aaa) + X[ 6] + $6d703ef3; ccc:= ((ccc shl 6) or (ccc shr (32-6))) + bbb; eee:= ((eee shl 10) or (eee shr (32-10))); bbb:= bbb + ((ccc or (not ddd)) xor eee) + X[ 9] + $6d703ef3; bbb:= ((bbb shl 14) or (bbb shr (32-14))) + aaa; ddd:= ((ddd shl 10) or (ddd shr (32-10))); aaa:= aaa + ((bbb or (not ccc)) xor ddd) + X[11] + $6d703ef3; aaa:= ((aaa shl 12) or (aaa shr (32-12))) + eee; ccc:= ((ccc shl 10) or (ccc shr (32-10))); eee:= eee + ((aaa or (not bbb)) xor ccc) + X[ 8] + $6d703ef3; eee:= ((eee shl 13) or (eee shr (32-13))) + ddd; bbb:= ((bbb shl 10) or (bbb shr (32-10))); ddd:= ddd + ((eee or (not aaa)) xor bbb) + X[12] + $6d703ef3; ddd:= ((ddd shl 5) or (ddd shr (32-5))) + ccc; aaa:= ((aaa shl 10) or (aaa shr (32-10))); ccc:= ccc + ((ddd or (not eee)) xor aaa) + X[ 2] + $6d703ef3; ccc:= ((ccc shl 14) or (ccc shr (32-14))) + bbb; eee:= ((eee shl 10) or (eee shr (32-10))); bbb:= bbb + ((ccc or (not ddd)) xor eee) + X[10] + $6d703ef3; bbb:= ((bbb shl 13) or (bbb shr (32-13))) + aaa; ddd:= ((ddd shl 10) or (ddd shr (32-10))); aaa:= aaa + ((bbb or (not ccc)) xor ddd) + X[ 0] + $6d703ef3; aaa:= ((aaa shl 13) or (aaa shr (32-13))) + eee; ccc:= ((ccc shl 10) or (ccc shr (32-10))); eee:= eee + ((aaa or (not bbb)) xor ccc) + X[ 4] + $6d703ef3; eee:= ((eee shl 7) or (eee shr (32-7))) + ddd; bbb:= ((bbb shl 10) or (bbb shr (32-10))); ddd:= ddd + ((eee or (not aaa)) xor bbb) + X[13] + $6d703ef3; ddd:= ((ddd shl 5) or (ddd shr (32-5))) + ccc; aaa:= ((aaa shl 10) or (aaa shr (32-10))); ccc:= ccc + ((ddd and eee) or ((not ddd) and aaa)) + X[ 8] + $7a6d76e9; ccc:= ((ccc shl 15) or (ccc shr (32-15))) + bbb; eee:= ((eee shl 10) or (eee shr (32-10))); bbb:= bbb + ((ccc and ddd) or ((not ccc) and eee)) + X[ 6] + $7a6d76e9; bbb:= ((bbb shl 5) or (bbb shr (32-5))) + aaa; ddd:= ((ddd shl 10) or (ddd shr (32-10))); aaa:= aaa + ((bbb and ccc) or ((not bbb) and ddd)) + X[ 4] + $7a6d76e9; aaa:= ((aaa shl 8) or (aaa shr (32-8))) + eee; ccc:= ((ccc shl 10) or (ccc shr (32-10))); eee:= eee + ((aaa and bbb) or ((not aaa) and ccc)) + X[ 1] + $7a6d76e9; eee:= ((eee shl 11) or (eee shr (32-11))) + ddd; bbb:= ((bbb shl 10) or (bbb shr (32-10))); ddd:= ddd + ((eee and aaa) or ((not eee) and bbb)) + X[ 3] + $7a6d76e9; ddd:= ((ddd shl 14) or (ddd shr (32-14))) + ccc; aaa:= ((aaa shl 10) or (aaa shr (32-10))); ccc:= ccc + ((ddd and eee) or ((not ddd) and aaa)) + X[11] + $7a6d76e9; ccc:= ((ccc shl 14) or (ccc shr (32-14))) + bbb; eee:= ((eee shl 10) or (eee shr (32-10))); bbb:= bbb + ((ccc and ddd) or ((not ccc) and eee)) + X[15] + $7a6d76e9; bbb:= ((bbb shl 6) or (bbb shr (32-6))) + aaa; ddd:= ((ddd shl 10) or (ddd shr (32-10))); aaa:= aaa + ((bbb and ccc) or ((not bbb) and ddd)) + X[ 0] + $7a6d76e9; aaa:= ((aaa shl 14) or (aaa shr (32-14))) + eee; ccc:= ((ccc shl 10) or (ccc shr (32-10))); eee:= eee + ((aaa and bbb) or ((not aaa) and ccc)) + X[ 5] + $7a6d76e9; eee:= ((eee shl 6) or (eee shr (32-6))) + ddd; bbb:= ((bbb shl 10) or (bbb shr (32-10))); ddd:= ddd + ((eee and aaa) or ((not eee) and bbb)) + X[12] + $7a6d76e9; ddd:= ((ddd shl 9) or (ddd shr (32-9))) + ccc; aaa:= ((aaa shl 10) or (aaa shr (32-10))); ccc:= ccc + ((ddd and eee) or ((not ddd) and aaa)) + X[ 2] + $7a6d76e9; ccc:= ((ccc shl 12) or (ccc shr (32-12))) + bbb; eee:= ((eee shl 10) or (eee shr (32-10))); bbb:= bbb + ((ccc and ddd) or ((not ccc) and eee)) + X[13] + $7a6d76e9; bbb:= ((bbb shl 9) or (bbb shr (32-9))) + aaa; ddd:= ((ddd shl 10) or (ddd shr (32-10))); aaa:= aaa + ((bbb and ccc) or ((not bbb) and ddd)) + X[ 9] + $7a6d76e9; aaa:= ((aaa shl 12) or (aaa shr (32-12))) + eee; ccc:= ((ccc shl 10) or (ccc shr (32-10))); eee:= eee + ((aaa and bbb) or ((not aaa) and ccc)) + X[ 7] + $7a6d76e9; eee:= ((eee shl 5) or (eee shr (32-5))) + ddd; bbb:= ((bbb shl 10) or (bbb shr (32-10))); ddd:= ddd + ((eee and aaa) or ((not eee) and bbb)) + X[10] + $7a6d76e9; ddd:= ((ddd shl 15) or (ddd shr (32-15))) + ccc; aaa:= ((aaa shl 10) or (aaa shr (32-10))); ccc:= ccc + ((ddd and eee) or ((not ddd) and aaa)) + X[14] + $7a6d76e9; ccc:= ((ccc shl 8) or (ccc shr (32-8))) + bbb; eee:= ((eee shl 10) or (eee shr (32-10))); bbb:= bbb + (ccc xor ddd xor eee) + X[12]; bbb:= ((bbb shl 8) or (bbb shr (32-8))) + aaa; ddd:= ((ddd shl 10) or (ddd shr (32-10))); aaa:= aaa + (bbb xor ccc xor ddd) + X[15]; aaa:= ((aaa shl 5) or (aaa shr (32-5))) + eee; ccc:= ((ccc shl 10) or (ccc shr (32-10))); eee:= eee + (aaa xor bbb xor ccc) + X[10]; eee:= ((eee shl 12) or (eee shr (32-12))) + ddd; bbb:= ((bbb shl 10) or (bbb shr (32-10))); ddd:= ddd + (eee xor aaa xor bbb) + X[ 4]; ddd:= ((ddd shl 9) or (ddd shr (32-9))) + ccc; aaa:= ((aaa shl 10) or (aaa shr (32-10))); ccc:= ccc + (ddd xor eee xor aaa) + X[ 1]; ccc:= ((ccc shl 12) or (ccc shr (32-12))) + bbb; eee:= ((eee shl 10) or (eee shr (32-10))); bbb:= bbb + (ccc xor ddd xor eee) + X[ 5]; bbb:= ((bbb shl 5) or (bbb shr (32-5))) + aaa; ddd:= ((ddd shl 10) or (ddd shr (32-10))); aaa:= aaa + (bbb xor ccc xor ddd) + X[ 8]; aaa:= ((aaa shl 14) or (aaa shr (32-14))) + eee; ccc:= ((ccc shl 10) or (ccc shr (32-10))); eee:= eee + (aaa xor bbb xor ccc) + X[ 7]; eee:= ((eee shl 6) or (eee shr (32-6))) + ddd; bbb:= ((bbb shl 10) or (bbb shr (32-10))); ddd:= ddd + (eee xor aaa xor bbb) + X[ 6]; ddd:= ((ddd shl 8) or (ddd shr (32-8))) + ccc; aaa:= ((aaa shl 10) or (aaa shr (32-10))); ccc:= ccc + (ddd xor eee xor aaa) + X[ 2]; ccc:= ((ccc shl 13) or (ccc shr (32-13))) + bbb; eee:= ((eee shl 10) or (eee shr (32-10))); bbb:= bbb + (ccc xor ddd xor eee) + X[13]; bbb:= ((bbb shl 6) or (bbb shr (32-6))) + aaa; ddd:= ((ddd shl 10) or (ddd shr (32-10))); aaa:= aaa + (bbb xor ccc xor ddd) + X[14]; aaa:= ((aaa shl 5) or (aaa shr (32-5))) + eee; ccc:= ((ccc shl 10) or (ccc shr (32-10))); eee:= eee + (aaa xor bbb xor ccc) + X[ 0]; eee:= ((eee shl 15) or (eee shr (32-15))) + ddd; bbb:= ((bbb shl 10) or (bbb shr (32-10))); ddd:= ddd + (eee xor aaa xor bbb) + X[ 3]; ddd:= ((ddd shl 13) or (ddd shr (32-13))) + ccc; aaa:= ((aaa shl 10) or (aaa shr (32-10))); ccc:= ccc + (ddd xor eee xor aaa) + X[ 9]; ccc:= ((ccc shl 11) or (ccc shr (32-11))) + bbb; eee:= ((eee shl 10) or (eee shr (32-10))); bbb:= bbb + (ccc xor ddd xor eee) + X[11]; bbb:= ((bbb shl 11) or (bbb shr (32-11))) + aaa; ddd:= ((ddd shl 10) or (ddd shr (32-10))); ddd:= ddd + cc + CurrentHash[1]; CurrentHash[1]:= CurrentHash[2] + dd + eee; CurrentHash[2]:= CurrentHash[3] + ee + aaa; CurrentHash[3]:= CurrentHash[4] + aa + bbb; CurrentHash[4]:= CurrentHash[0] + bb + ccc; CurrentHash[0]:= ddd; FillChar(X,Sizeof(X),0); Index:= 0; FillChar(HashBuffer,Sizeof(HashBuffer),0); end; class function TDCP_ripemd160.GetHashSize: integer; begin Result:= 160; end; class function TDCP_ripemd160.GetId: integer; begin Result:= DCP_ripemd160; end; class function TDCP_ripemd160.GetAlgorithm: string; begin Result:= 'RipeMD-160'; end; class function TDCP_ripemd160.SelfTest: boolean; const Test1Out: array[0..19] of byte= ($0B,$DC,$9D,$2D,$25,$6B,$3E,$E9,$DA,$AE,$34,$7B,$E6,$F4,$DC,$83,$5A,$46,$7F,$FE); Test2Out: array[0..19] of byte= ($F7,$1C,$27,$10,$9C,$69,$2C,$1B,$56,$BB,$DC,$EB,$5B,$9D,$28,$65,$B3,$70,$8D,$BC); var TestHash: TDCP_ripemd160; TestOut: array[0..19] of byte; begin TestHash:= TDCP_ripemd160.Create(nil); TestHash.Init; TestHash.UpdateStr('a'); TestHash.Final(TestOut); Result:= CompareMem(@TestOut,@Test1Out,Sizeof(Test1Out)); TestHash.Init; TestHash.UpdateStr('abcdefghijklmnopqrstuvwxyz'); TestHash.Final(TestOut); Result:= CompareMem(@TestOut,@Test2Out,Sizeof(Test2Out)) and Result; TestHash.Free; end; procedure TDCP_ripemd160.Init; begin Burn; CurrentHash[0]:= $67452301; CurrentHash[1]:= $efcdab89; CurrentHash[2]:= $98badcfe; CurrentHash[3]:= $10325476; CurrentHash[4]:= $c3d2e1f0; fInitialized:= true; end; procedure TDCP_ripemd160.Burn; begin LenHi:= 0; LenLo:= 0; Index:= 0; FillChar(HashBuffer,Sizeof(HashBuffer),0); FillChar(CurrentHash,Sizeof(CurrentHash),0); fInitialized:= false; end; procedure TDCP_ripemd160.Update(const Buffer; Size: longword); var PBuf: ^byte; begin if not fInitialized then raise EDCP_hash.Create('Hash not initialized'); Inc(LenHi,Size shr 29); Inc(LenLo,Size*8); if LenLo< (Size*8) then Inc(LenHi); PBuf:= @Buffer; while Size> 0 do begin if (Sizeof(HashBuffer)-Index)<= DWord(Size) then begin Move(PBuf^,HashBuffer[Index],Sizeof(HashBuffer)-Index); Dec(Size,Sizeof(HashBuffer)-Index); Inc(PBuf,Sizeof(HashBuffer)-Index); Compress; end else begin Move(PBuf^,HashBuffer[Index],Size); Inc(Index,Size); Size:= 0; end; end; end; procedure TDCP_ripemd160.Final(var Digest); begin if not fInitialized then raise EDCP_hash.Create('Hash not initialized'); HashBuffer[Index]:= $80; if Index>= 56 then Compress; PDWord(@HashBuffer[56])^:= LenLo; PDWord(@HashBuffer[60])^:= LenHi; Compress; Move(CurrentHash,Digest,Sizeof(CurrentHash)); Burn; end; end.
unit Unit15; { Delphi System Enumerator ------------------------ Enumerates all processes running on a system. For each process: - all modules (DLL's etc..) it uses, - all windows it uses ( including invisible windows), are listed Author : D. Claessens <dirk.claessens16@yucom.be> FREEWARE ( BUT USE AT YOUR OWN RISK ) ====================================================================== Tested on : Delphi 4 update pack 2+3, P3/550/128/W98se, P1/100/24/W95 NOTE: will NOT, repeat _NOT_ work on NT, due to security constraints ====================================================================== } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, TlHelp32, ComCtrls; const Version = 'v1.2'; type TForm13 = class(TForm) Button1: TButton; ListWin: TRichEdit; PrBar: TProgressBar; procedure Button1Click(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } WindowList, ProcessList : TStringList; procedure GetModules ( ProcessID: DWORD; Buf: TStrings ); procedure GetProcesses( Buf: TStrings); procedure ListAll; public { Public declarations } end; var Form13: TForm13; implementation uses Unit1, Main; {$R *.DFM} //========================================== procedure TForm13.FormCreate(Sender: TObject); begin Caption := Caption + ' ' + Version; WindowList := TStringList.Create; ProcessList := TStringList.Create; end; //=========================================== procedure TForm13.FormDestroy(Sender: TObject); begin WindowList.Free; ProcessList.Free; end; {----------------------------------------} { Window enumeration Callback procedure } { NOTE: this proc _must_ be global, } { and _cannot_ be a method. } {----------------------------------------} function WinEnumProc( hWnd: THandle; Val: integer ): boolean; stdcall; const FmtStr = '%-8.8x %-8.8x %-35s %s'; var ClassName, WinText : array[0..255] of Char; WinInfo : string; LpdwProcessID : DWORD; begin // get classname from handle GetClassName( hWnd, ClassName, 255 ); // get window title from handle (if any) if GetWindowText( hWnd, WinText, 255) = 0 then Wintext := 'no title'; // get some window info WinInfo := ''; case boolean(IsWindowVisible( hWnd )) of true : WinInfo := ' [visible'; false: WinInfo := ' [invisible'; end; // if boolean(IsIconic( hWnd )) then WinInfo := WinInfo + ',iconic]' else WinInfo := WinInfo + ']'; // get ProcessID that owns this window lpdwProcessID := 1; GetWindowThreadProcessID( hWnd, @lpdwProcessID ); // ProcessID is stored separately, to facilitate searching later //Form1.WindowList.AddObject( Format( FmtStr, [lpdwProcessID, hWnd, // string(ClassName), // string(WinText)]) + WinInfo, // TObject( lpdwProcessID)); // Tell Windows to continue Result := true; end; {-------------------------------------------------------------} { Enumerates modules in use, given a ProcessID } {-------------------------------------------------------------} procedure TForm13.GetModules( ProcessID: DWORD; Buf: TStrings ); const FmtMod = ' %8.8x %6.1f %4.4d %15s %-s'; var hSnap : THandle; ModuleEntry : TModuleEntry32; // <<==see TLHelp32.pas for details Proceed : Boolean; begin Buf.Clear; hSnap := CreateToolhelp32Snapshot( TH32CS_SNAPMODULE , ProcessID ); if HSnap <> -1 then begin // //Buf.Add(' '); //Buf.Add(' Modules used:'); //Buf.Add(' ModuleID Size(kb) Usage Module Path'); //Buf.Add(' -------- -------- ------ ------ ----'); // ModuleEntry.dwSize := SizeOf(TModuleEntry32); Proceed := Module32First(hSnap, ModuleEntry); while Proceed do begin with ModuleEntry do (* Buf.add( Format( FmtMod, [Th32ModuleID, ModBaseSize/1024, GlblCntUsage, szModule, ExtractFilePath(szEXEPath)]) ); *) Proceed := Module32Next( hSnap, ModuleEntry); end; // CloseHandle( hSnap ); end else ShowMessage( 'Oops...' + SysErrorMessage(GetLastError)); end; {--------------------------------------------------------------------} { Enumerates running tasks } { } {--------------------------------------------------------------------} procedure TForm13.GetProcesses( Buf: TStrings); const FmtProc = ' * %s'; var hSnap : THandle; ProcessEntry : TProcessEntry32; // <<==see TLHelp32.pas for details Proceed : Boolean; begin Buf.Clear; Buf.Add(' Elenco Processi Attivi'); //Form1.Memo1.Clear; Form1.Memo1.Lines.Add(' '); Form1.Memo1.Lines.Add(' '); Form1.Memo1.Lines.Add(' Elenco Processi Attivi'); Form1.Memo1.Lines.Add(' ------'); // get a snapshot handle hSnap := CreateToolhelp32Snapshot( TH32CS_SNAPALL , 0 ); if HSnap <> -1 then begin ProcessEntry.dwSize := SizeOf(TProcessEntry32); Proceed := Process32First(hSnap, ProcessEntry); while Proceed do begin with ProcessEntry do begin Form1.Memo1.Lines.AddObject( Format( FmtProc, [szEXEFile]), TObject(TH32ProcessID)); Buf.AddObject( Format( FmtProc, [szEXEFile]), TObject(TH32ProcessID)); end; // Keep calling until Windows returns false Proceed := Process32Next( hSnap, ProcessEntry); end; CloseHandle( hSnap ); end else ShowMessage( 'Oops...' + SysErrorMessage(GetLastError)); end; //============================================ procedure TForm13.Button1Click(Sender: TObject); begin WindowList.Clear; ProcessList.Clear; EnumWindows( @WinEnumProc, 0); GetProcesses( ProcessList); ListAll; end; //======================= procedure TForm13.ListAll; var i,j : integer; ProcessID : DWORD; ModuleList : TStringList; WindowLess : boolean; begin PrBar.Max := ProcessList.Count; PrBar.Position := 0; ListWin.Clear; ModuleList := TStringList.Create; if ProcessList.Count > 0 then for i := 0 to pred(ProcessList.Count) do begin PrBar.Position := i; //ListWin.Lines.Add(' '); //ListWin.Lines.Add(''); with ListWin.SelAttributes do begin Color := clNAVY; Style := [fsUNDERLINE]; end; //ListWin.Lines.Add('ProcessID ParentID ModuleID Usage Threads Prio Path'); with ListWin.SelAttributes do begin Style := []; Color := clNAVY; end; ListWin.Lines.Add( ProcessList[i] ); //ListWin.Lines.Add( ' '); with ListWin.SelAttributes do begin Color := clGREEN; Style := []; end; //ListWin.Lines.Add( ' Owned Windows:'); // with ListWin.SelAttributes do begin Color := clGREEN; Style := [fsUNDERLINE]; end; // WindowLess := true; if WindowList.Count > 0 then begin ListWin.Lines.Add( ' ProcessID HWND Classname Window Title'); with ListWin.SelAttributes do begin Style := []; Color := clGREEN; end; // look for matching ProcessID's // these were stored in the pointer space of the stringlists for j := 0 to pred(WindowList.Count) do if DWORD( WindowList.Objects[j] ) = DWORD( ProcessList.Objects[i]) then begin // add windows owned by this processID ListWin.Lines.Add( ' ' + WindowList[j] ); WindowLess := false; end; end; if WindowLess then //ListWin.Lines.Add(' none.'); // with ListWin.SelAttributes do begin Style := []; Color := clPURPLE; end; GetModules( DWORD(ProcessList.Objects[i]), ModuleList ); ListWin.Lines.AddStrings( ModuleList ); end; ModuleList.Free; PrBar.Position := 0; end; end.
{ wakaru Copyright (c) 2019 mr-highball Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. } unit wakaru.types; {$mode delphi}{$H+} interface uses Classes, SysUtils, wakaru.consts, wakaru.collection; type { IIdentifiable } (* a means of identifying uniquely, and optionally with a user defined tag *) IIdentifiable = interface ['{22B4C03D-52C8-4578-AD9C-D2A9A054F70C}'] //property methods function GetID: String; function GetTag: String; procedure SetTag(const AValue: String); //properties (* unique generated identifier *) property ID : String read GetID; (* "friendly" identifier that can be modified by caller *) property Tag : String read GetTag write SetTag; end; //forward INode = interface; { INodes } (* a collection of nodes *) INodes = IInterfaceCollection<INode>; { INodeConnection } (* a node connection binds node(s) together but always has only one source node *) INodeConnection = interface ['{1187154A-EF72-4BF5-A975-D28FA418726D}'] //-------------------------------------------------------------------------- //property methods //-------------------------------------------------------------------------- function GetSource: INode; procedure SetSource(AValue: INode); function GetConnected: INodes; //-------------------------------------------------------------------------- //properties //-------------------------------------------------------------------------- property Source : INode read GetSource write SetSource; property Connected : INodes read GetConnected; //-------------------------------------------------------------------------- //methods //-------------------------------------------------------------------------- end; { INodeConnections } (* a collection of node connections *) INodeConnections = IInterfaceCollection<INodeConnection>; (* nodes are interconnected constructs that accept signals and express a value. additionally, nodes transmit signals through node connections when thresholds are met *) INode = interface ['{0B7F6660-5A94-4F70-8434-E9865A2C7004}'] //-------------------------------------------------------------------------- //property methods //-------------------------------------------------------------------------- function GetConnections: INodeConnections; function GetID: IIdentifiable; function GetRawValue: TSignalRange; function GetValue: TSignal; procedure SetRawValue(AValue: TSignalRange); procedure SetValue(AValue: TSignal); //-------------------------------------------------------------------------- //properties //-------------------------------------------------------------------------- (* collection of outgoing connections *) property Connections : INodeConnections read GetConnections; (* signal representation of the "RawValue" *) property Value : TSignal read GetValue write SetValue; (* the current value this node is at *) property RawValue : TSignalRange read GetRawValue write SetRawValue; (* unique identifier for this node *) property ID : IIdentifiable read GetID; //-------------------------------------------------------------------------- //methods //-------------------------------------------------------------------------- (* resets the node's value to the default resting state *) procedure Reset(); (* passes a signal value to this node which may or may not affect this node's value, and connected downstream nodes *) procedure Signal(const AValue : TSignalRange); end; { INodeCluster } (* a node cluster is a collection of connected nodes and has the roles of taking the signal measurement of all nodes, as well as distributing incoming external signal information *) INodeCluster = interface ['{53CF34C9-D26E-475A-B412-34239499824F}'] //-------------------------------------------------------------------------- //property methods //-------------------------------------------------------------------------- function GetID: IIdentifiable; function GetNodes: INodes; function GetValue: TSignal; //-------------------------------------------------------------------------- //properties //-------------------------------------------------------------------------- (* children nodes inside this cluster *) property Nodes : INodes read GetNodes; (* unique identifier for the cluster *) property ID : IIdentifiable read GetID; (* calculates the signal value of all contained nodes *) property Value : TSignal read GetValue; //-------------------------------------------------------------------------- //methods //-------------------------------------------------------------------------- (* passes a signal down to child node(s) *) procedure Signal(const AValue : TSignalRange); end; { IClusters } (* a collection of node clusters *) INodeClusters = IInterfaceCollection<INodeCluster>; { INodeNetwork } (* the network is a collection of at least one node cluster. primary responsibilities include distributing external signals to clusters, maintaining the "pulse", and recording finalized signals for the clusters for a given pulse. this can also be seen as the top level interface when working with nodes *) INodeNetwork = interface ['{821D75CF-455A-434B-9406-29B3CA0CA224}'] //-------------------------------------------------------------------------- //property methods //-------------------------------------------------------------------------- function GetClusters: INodeClusters; function GetID: IIdentifiable; //-------------------------------------------------------------------------- //properties //-------------------------------------------------------------------------- (* unique identifier for this network *) property ID : IIdentifiable read GetID; (* child node clusters *) property Clusters : INodeClusters read GetClusters; //Committed : collection //Uncommitted : collection //-------------------------------------------------------------------------- //methods //-------------------------------------------------------------------------- (* stores current signals to the "working" (uncommitted) pulse collection for all clusters *) procedure Pulse(); (* stores entire tree to "memory" (committed) with an optional session identifier *) procedure Commit(); overload; procedure Commit(const AIdentifier : String); overload; (* clears the "working" collection and resets all nodes inside of all clusters to their default state *) procedure Clear(); (* passes a signal down to child cluster(s) *) procedure Signal(const AValue : TSignalRange); end; implementation end.
unit PascalCoin.RPC.Consts; interface const //All Approximate Values RECOVERY_WAIT_BLOCKS = 420480; //Approx 4 Years BLOCKS_PER_YEAR = 105120; //Approx BLOCKS_PER_MONTH = BLOCKS_PER_YEAR div 12; BLOCKS_PER_DAY = BLOCKS_PER_YEAR div 365; RPC_ERRNUM_INTERNALERROR = 100; RPC_ERRNUM_NOTIMPLEMENTED = 101; RPC_ERRNUM_METHODNOTFOUND = 1001; RPC_ERRNUM_INVALIDACCOUNT = 1002; RPC_ERRNUM_INVALIDBLOCK = 1003; RPC_ERRNUM_INVALIDOPERATION = 1004; RPC_ERRNUM_INVALIDPUBKEY = 1005; RPC_ERRNUM_INVALIDACCOUNTNAME = 1006; RPC_ERRNUM_NOTFOUND = 1010; RPC_ERRNUM_WALLETPASSWORDPROTECTED = 1015; RPC_ERRNUM_INVALIDDATA = 1016; RPC_ERRNUM_INVALIDSIGNATURE = 1020; RPC_ERRNUM_NOTALLOWEDCALL = 1021; RPC_MULTIPLE_ERRORS = 999999; DEEP_SEARCH = -1; PASCALCOIN_ENCODING = ['a' .. 'z', '0' .. '9', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '+', '{', '}', '[', ']', '_', ':', '`', '|', '<', '>', ',', '.', '?', '/', '~']; PASCALCOIN_ENCODING_START = ['a' .. 'z', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '+', '{', '}', '[', ']', '_', ':', '`', '|', '<', '>', ',', '.', '?', '/', '~']; PASCALCOIN_BASE_58 = ['1' .. '9', 'A' .. 'H', 'J' .. 'N', 'P' .. 'Z', 'a' .. 'k', 'm' .. 'z']; PASCALCOIN_HEXA = ['0'..'9', 'a'..'f', 'A'..'F']; implementation end.
(****************************************************************************** * PasVulkan * ****************************************************************************** * Version see PasVulkan.Framework.pas * ****************************************************************************** * zlib license * *============================================================================* * * * Copyright (C) 2016-2020, Benjamin Rosseaux (benjamin@rosseaux.de) * * * * This software is provided 'as-is', without any express or implied * * warranty. In no event will the authors be held liable for any damages * * arising from the use of this software. * * * * Permission is granted to anyone to use this software for any purpose, * * including commercial applications, and to alter it and redistribute it * * freely, subject to the following restrictions: * * * * 1. The origin of this software must not be misrepresented; you must not * * claim that you wrote the original software. If you use this software * * in a product, an acknowledgement in the product documentation would be * * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. * * * ****************************************************************************** * General guidelines for code contributors * *============================================================================* * * * 1. Make sure you are legally allowed to make a contribution under the zlib * * license. * * 2. The zlib license header goes at the top of each source file, with * * appropriate copyright notice. * * 3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan * * Pascal header. * * 4. After a pull request, check the status of your pull request on * http://github.com/BeRo1985/pasvulkan * * 5. Write code which's compatible with Delphi >= 2009 and FreePascal >= * * 3.1.1 * * 6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, * * but if needed, make it out-ifdef-able. * * 7. No use of third-party libraries/units as possible, but if needed, make * * it out-ifdef-able. * * 8. Try to use const when possible. * * 9. Make sure to comment out writeln, used while debugging. * * 10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, * * x86-64, ARM, ARM64, etc.). * * 11. Make sure the code runs on all platforms with Vulkan support * * * ******************************************************************************) unit PasVulkan.Scene3D.Renderer.ImageBasedLighting.EnvMapCubeMaps; {$i PasVulkan.inc} {$ifndef fpc} {$ifdef conditionalexpressions} {$if CompilerVersion>=24.0} {$legacyifend on} {$ifend} {$endif} {$endif} {$m+} interface uses SysUtils, Classes, Math, PasMP, Vulkan, PasVulkan.Types, PasVulkan.Math, PasVulkan.Framework, PasVulkan.Application, PasVulkan.Scene3D.Renderer.Globals; type { TpvScene3DRendererImageBasedLightingEnvMapCubeMaps } TpvScene3DRendererImageBasedLightingEnvMapCubeMaps=class public const Width=512; Height=512; Samples=1024; private fComputeShaderModule:TpvVulkanShaderModule; fVulkanPipelineShaderStageCompute:TpvVulkanPipelineShaderStage; fVulkanGGXImage:TpvVulkanImage; fVulkanCharlieImage:TpvVulkanImage; fVulkanLambertianImage:TpvVulkanImage; fVulkanSampler:TpvVulkanSampler; fVulkanGGXImageView:TpvVulkanImageView; fVulkanCharlieImageView:TpvVulkanImageView; fVulkanLambertianImageView:TpvVulkanImageView; fGGXMemoryBlock:TpvVulkanDeviceMemoryBlock; fCharlieMemoryBlock:TpvVulkanDeviceMemoryBlock; fLambertianMemoryBlock:TpvVulkanDeviceMemoryBlock; fGGXDescriptorImageInfo:TVkDescriptorImageInfo; fCharlieDescriptorImageInfo:TVkDescriptorImageInfo; fLambertianDescriptorImageInfo:TVkDescriptorImageInfo; public constructor Create(const aVulkanDevice:TpvVulkanDevice;const aVulkanPipelineCache:TpvVulkanPipelineCache;const aDescriptorImageInfo:TVkDescriptorImageInfo;const aImageFormat:TVkFormat=TVkFormat(VK_FORMAT_R16G16B16A16_SFLOAT)); destructor Destroy; override; published property VulkanGGXImage:TpvVulkanImage read fVulkanGGXImage; property VulkanCharlieImage:TpvVulkanImage read fVulkanCharlieImage; property VulkanLambertianImage:TpvVulkanImage read fVulkanLambertianImage; property VulkanSampler:TpvVulkanSampler read fVulkanSampler; property VulkanGGXImageView:TpvVulkanImageView read fVulkanGGXImageView; property VulkanCharlieImageView:TpvVulkanImageView read fVulkanCharlieImageView; property VulkanLambertianImageView:TpvVulkanImageView read fVulkanLambertianImageView; public property GGXDescriptorImageInfo:TVkDescriptorImageInfo read fGGXDescriptorImageInfo; property CharlieDescriptorImageInfo:TVkDescriptorImageInfo read fCharlieDescriptorImageInfo; property LambertianDescriptorImageInfo:TVkDescriptorImageInfo read fLambertianDescriptorImageInfo; end; implementation function Hammersley(Index,NumSamples:TpvInt32):TpvVector2; const OneOver32Bit=1.0/4294967296.0; var ReversedIndex:TpvUInt32; begin ReversedIndex:=TpvUInt32(Index); ReversedIndex:=(ReversedIndex shl 16) or (ReversedIndex shr 16); ReversedIndex:=((ReversedIndex and $00ff00ff) shl 8) or ((ReversedIndex and $ff00ff00) shr 8); ReversedIndex:=((ReversedIndex and $0f0f0f0f) shl 4) or ((ReversedIndex and $f0f0f0f0) shr 4); ReversedIndex:=((ReversedIndex and $33333333) shl 2) or ((ReversedIndex and $cccccccc) shr 2); ReversedIndex:=((ReversedIndex and $55555555) shl 1) or ((ReversedIndex and $aaaaaaaa) shr 1); result.x:=frac(TpvFloat(Index)/TpvFloat(NumSamples)); result.y:=ReversedIndex*OneOver32Bit; end; function GenerateTBN(const Normal:TpvVector3):TpvMatrix3x3; var Bitangent,Tangent:TpvVector3; begin if (1.0-abs(Normal.y))<=1e-6 then begin if Normal.y>0.0 then begin Bitangent:=TpvVector3.InlineableCreate(0.0,0.0,1.0); end else begin Bitangent:=TpvVector3.InlineableCreate(0.0,0.0,-1.0); end; end else begin Bitangent:=TpvVector3.InlineableCreate(0.0,1.0,0.0); end; Tangent:=Bitangent.Cross(Normal).Normalize; result:=TpvMatrix3x3.Create(Tangent,Normal.Cross(Tangent).Normalize,Normal); end; function D_GGX(const NdotH,Roughness:TpvScalar):TpvScalar; begin result:=sqr(Roughness/((1.0-sqr(NdotH))+sqr(NdotH*Roughness)))*OneOverPI; end; function GGX(const xi:TpvVector2;const Roughness:TpvScalar):TpvVector4; var Alpha:TpvScalar; begin Alpha:=sqr(Roughness); result.x:=Clamp(sqrt((1.0-xi.y)/(1.0+((sqr(Alpha)-1.0)*xi.y))),0.0,1.0); result.y:=sqrt(1.0-sqr(result.x)); result.z:=TwoPI*xi.x; result.w:=D_GGX(result.x,Alpha)*0.25; end; function D_Charlie(const SheenRoughness,NdotH:TpvScalar):TpvScalar; var InvR,Cos2H,Sin2H:TpvScalar; begin InvR:=1.0/Clamp(SheenRoughness,1e-6,1.0); Cos2H:=sqr(NdotH); Sin2H:=1.0-Cos2H; result:=(2.0+InvR)*power(Sin2H,InvR*0.5)*OneOverTwoPI; end; function Charlie(const xi:TpvVector2;const Roughness:TpvScalar):TpvVector4; var Alpha:TpvScalar; begin Alpha:=sqr(Roughness); result.y:=Power(xi.y,Alpha/((2.0*Alpha)+1.0)); result.x:=sqrt(1.0-sqr(result.y)); result.z:=TwoPI*xi.x; result.w:=D_Charlie(Alpha,result.x)*0.25; end; function Lambertian(const xi:TpvVector2;const Roughness:TpvScalar):TpvVector4; begin result.x:=sqrt(1.0-xi.y); result.y:=sqrt(xi.y); result.z:=TwoPI*xi.x; result.w:=result.x*OneOverPI; end; type TImportanceSampleFunction=function(const xi:TpvVector2;const Roughness:TpvScalar):TpvVector4; TImportanceSamples=array of TpvVector4; procedure GetImportanceSamples(out aSamples:TImportanceSamples;const aCount:TpvSizeInt;const aRoughness:TpvScalar;const aImportanceSampleFunction:TImportanceSampleFunction;const aLambertian:boolean); var SampleIndex,TryIteration:TpvSizeInt; t:TpvVector4; x32,v:TpvUInt32; begin aSamples:=nil; SetLength(aSamples,aCount); if aLambertian then begin for SampleIndex:=0 to aCount-1 do begin t:=aImportanceSampleFunction(Hammersley(SampleIndex,aCount),aRoughness); aSamples[SampleIndex]:=TpvVector4.InlineableCreate(TpvVector3.InlineableCreate(TpvVector2.InlineableCreate(cos(t.z),sin(t.z))*t.y,t.x).Normalize,t.w); end; end else begin x32:=$3c7a92e1; for SampleIndex:=0 to aCount-1 do begin t.xy:=Hammersley(SampleIndex,aCount); for TryIteration:=1 to 256 do begin t:=aImportanceSampleFunction(t.xy,aRoughness); t.xyz:=TpvVector3.InlineableCreate(TpvVector2.InlineableCreate(cos(t.z),sin(t.z))*t.y,t.x).Normalize; if t.z<1e-4 then begin x32:=x32 xor (x32 shl 13); x32:=x32 xor (x32 shr 17); x32:=x32 xor (x32 shl 5); v:=x32; v:=(((v shr 10) and $3fffff)+((v shr 9) and 1)) or $40000000; t.x:=TpvFloat(pointer(@v)^)-2.0; x32:=x32 xor (x32 shl 13); x32:=x32 xor (x32 shr 17); x32:=x32 xor (x32 shl 5); v:=x32; v:=(((v shr 10) and $3fffff)+((v shr 9) and 1)) or $40000000; t.y:=TpvFloat(pointer(@v)^)-2.0; end else begin break; end; end; aSamples[SampleIndex]:=t; end; end; end; { TpvScene3DRendererImageBasedLightingEnvMapCubeMaps } constructor TpvScene3DRendererImageBasedLightingEnvMapCubeMaps.Create(const aVulkanDevice:TpvVulkanDevice;const aVulkanPipelineCache:TpvVulkanPipelineCache;const aDescriptorImageInfo:TVkDescriptorImageInfo;const aImageFormat:TVkFormat); type TPushConstants=record MipMapLevel:TpvInt32; MaxMipMapLevel:TpvInt32; NumSamples:TpvInt32; Which:TpvInt32; end; PpvVulkanImage=^TpvVulkanImage; PpvVulkanDeviceMemoryBlock=^TpvVulkanDeviceMemoryBlock; var ImageIndex,Index,MipMaps:TpvSizeInt; Stream:TStream; MemoryRequirements:TVkMemoryRequirements; RequiresDedicatedAllocation, PrefersDedicatedAllocation:boolean; MemoryBlockFlags:TpvVulkanDeviceMemoryBlockFlags; ImageSubresourceRange:TVkImageSubresourceRange; GraphicsQueue:TpvVulkanQueue; GraphicsCommandPool:TpvVulkanCommandPool; GraphicsCommandBuffer:TpvVulkanCommandBuffer; GraphicsFence:TpvVulkanFence; ComputeQueue:TpvVulkanQueue; ComputeCommandPool:TpvVulkanCommandPool; ComputeCommandBuffer:TpvVulkanCommandBuffer; ComputeFence:TpvVulkanFence; ImageViews:array[0..2] of array of TpvVulkanImageView; VulkanDescriptorSetLayout:TpvVulkanDescriptorSetLayout; VulkanDescriptorPool:TpvVulkanDescriptorPool; VulkanDescriptorSets:array[0..2] of array of TpvVulkanDescriptorSet; DescriptorImageInfos:array[0..2] of array of TVkDescriptorImageInfo; PipelineLayout:TpvVulkanPipelineLayout; Pipeline:TpvVulkanComputePipeline; PushConstants:TPushConstants; //ImageMemoryBarrier:TVkImageMemoryBarrier; Images:array[0..2] of PpvVulkanImage; MemoryBlocks:array[0..2] of PpvVulkanDeviceMemoryBlock; // ImportanceSamples:TImportanceSamples; begin inherited Create; //GetImportanceSamples(ImportanceSamples,1024,0.1,Charlie); Stream:=pvScene3DShaderVirtualFileSystem.GetFile('cubemap_filter_comp.spv'); try fComputeShaderModule:=TpvVulkanShaderModule.Create(aVulkanDevice,Stream); finally Stream.Free; end; MipMaps:=IntLog2(Max(Width,Height))+1; fVulkanPipelineShaderStageCompute:=TpvVulkanPipelineShaderStage.Create(VK_SHADER_STAGE_COMPUTE_BIT,fComputeShaderModule,'main'); Images[0]:=@fVulkanGGXImage; Images[1]:=@fVulkanCharlieImage; Images[2]:=@fVulkanLambertianImage; MemoryBlocks[0]:=@fGGXMemoryBlock; MemoryBlocks[1]:=@fCharlieMemoryBlock; MemoryBlocks[2]:=@fLambertianMemoryBlock; for ImageIndex:=0 to 2 do begin Images[ImageIndex]^:=TpvVulkanImage.Create(aVulkanDevice, TVkImageCreateFlags(VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT), VK_IMAGE_TYPE_2D, aImageFormat, Width, Height, 1, MipMaps, 6, VK_SAMPLE_COUNT_1_BIT, VK_IMAGE_TILING_OPTIMAL, TVkImageUsageFlags(VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_STORAGE_BIT) or TVkImageUsageFlags(VK_IMAGE_USAGE_SAMPLED_BIT), VK_SHARING_MODE_EXCLUSIVE, 0, nil, VK_IMAGE_LAYOUT_UNDEFINED ); MemoryRequirements:=aVulkanDevice.MemoryManager.GetImageMemoryRequirements(Images[ImageIndex]^.Handle, RequiresDedicatedAllocation, PrefersDedicatedAllocation); MemoryBlockFlags:=[]; if RequiresDedicatedAllocation or PrefersDedicatedAllocation then begin Include(MemoryBlockFlags,TpvVulkanDeviceMemoryBlockFlag.DedicatedAllocation); end; MemoryBlocks[ImageIndex]^:=aVulkanDevice.MemoryManager.AllocateMemoryBlock(MemoryBlockFlags, MemoryRequirements.size, MemoryRequirements.alignment, MemoryRequirements.memoryTypeBits, TVkMemoryPropertyFlags(VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT), 0, 0, 0, 0, 0, 0, 0, TpvVulkanDeviceMemoryAllocationType.ImageOptimal, @Images[ImageIndex]^.Handle); if not assigned(MemoryBlocks[ImageIndex]^) then begin raise EpvVulkanMemoryAllocationException.Create('Memory for texture couldn''t be allocated!'); end; MemoryBlocks[ImageIndex]^.AssociatedObject:=self; VulkanCheckResult(aVulkanDevice.Commands.BindImageMemory(aVulkanDevice.Handle, Images[ImageIndex]^.Handle, MemoryBlocks[ImageIndex]^.MemoryChunk.Handle, MemoryBlocks[ImageIndex]^.Offset)); end; GraphicsQueue:=aVulkanDevice.GraphicsQueue; ComputeQueue:=aVulkanDevice.ComputeQueue; GraphicsCommandPool:=TpvVulkanCommandPool.Create(aVulkanDevice, aVulkanDevice.GraphicsQueueFamilyIndex, TVkCommandPoolCreateFlags(VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT)); try GraphicsCommandBuffer:=TpvVulkanCommandBuffer.Create(GraphicsCommandPool,VK_COMMAND_BUFFER_LEVEL_PRIMARY); try GraphicsFence:=TpvVulkanFence.Create(aVulkanDevice); try ComputeCommandPool:=TpvVulkanCommandPool.Create(aVulkanDevice, aVulkanDevice.ComputeQueueFamilyIndex, TVkCommandPoolCreateFlags(VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT)); try ComputeCommandBuffer:=TpvVulkanCommandBuffer.Create(ComputeCommandPool,VK_COMMAND_BUFFER_LEVEL_PRIMARY); try ComputeFence:=TpvVulkanFence.Create(aVulkanDevice); try FillChar(ImageSubresourceRange,SizeOf(TVkImageSubresourceRange),#0); ImageSubresourceRange.aspectMask:=TVkImageAspectFlags(VK_IMAGE_ASPECT_COLOR_BIT); ImageSubresourceRange.baseMipLevel:=0; ImageSubresourceRange.levelCount:=MipMaps; ImageSubresourceRange.baseArrayLayer:=0; ImageSubresourceRange.layerCount:=6; for ImageIndex:=0 to 2 do begin Images[ImageIndex]^.SetLayout(TVkImageAspectFlags(VK_IMAGE_ASPECT_COLOR_BIT), TVkImageLayout(VK_IMAGE_LAYOUT_UNDEFINED), TVkImageLayout(VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL), @ImageSubresourceRange, GraphicsCommandBuffer, GraphicsQueue, GraphicsFence, true); end; fVulkanSampler:=TpvVulkanSampler.Create(aVulkanDevice, TVkFilter(VK_FILTER_LINEAR), TVkFilter(VK_FILTER_LINEAR), TVkSamplerMipmapMode(VK_SAMPLER_MIPMAP_MODE_LINEAR), TVkSamplerAddressMode(VK_SAMPLER_ADDRESS_MODE_REPEAT), TVkSamplerAddressMode(VK_SAMPLER_ADDRESS_MODE_REPEAT), TVkSamplerAddressMode(VK_SAMPLER_ADDRESS_MODE_REPEAT), 0.0, false, 1.0, false, TVkCompareOp(VK_COMPARE_OP_NEVER), 0.0, MipMaps, TVkBorderColor(VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK), false); fVulkanGGXImageView:=TpvVulkanImageView.Create(aVulkanDevice, fVulkanGGXImage, TVkImageViewType(VK_IMAGE_VIEW_TYPE_CUBE), aImageFormat, TVkComponentSwizzle(VK_COMPONENT_SWIZZLE_IDENTITY), TVkComponentSwizzle(VK_COMPONENT_SWIZZLE_IDENTITY), TVkComponentSwizzle(VK_COMPONENT_SWIZZLE_IDENTITY), TVkComponentSwizzle(VK_COMPONENT_SWIZZLE_IDENTITY), TVkImageAspectFlags(VK_IMAGE_ASPECT_COLOR_BIT), 0, MipMaps, 0, 6); fVulkanCharlieImageView:=TpvVulkanImageView.Create(aVulkanDevice, fVulkanCharlieImage, TVkImageViewType(VK_IMAGE_VIEW_TYPE_CUBE), aImageFormat, TVkComponentSwizzle(VK_COMPONENT_SWIZZLE_IDENTITY), TVkComponentSwizzle(VK_COMPONENT_SWIZZLE_IDENTITY), TVkComponentSwizzle(VK_COMPONENT_SWIZZLE_IDENTITY), TVkComponentSwizzle(VK_COMPONENT_SWIZZLE_IDENTITY), TVkImageAspectFlags(VK_IMAGE_ASPECT_COLOR_BIT), 0, MipMaps, 0, 6); fVulkanLambertianImageView:=TpvVulkanImageView.Create(aVulkanDevice, fVulkanLambertianImage, TVkImageViewType(VK_IMAGE_VIEW_TYPE_CUBE), aImageFormat, TVkComponentSwizzle(VK_COMPONENT_SWIZZLE_IDENTITY), TVkComponentSwizzle(VK_COMPONENT_SWIZZLE_IDENTITY), TVkComponentSwizzle(VK_COMPONENT_SWIZZLE_IDENTITY), TVkComponentSwizzle(VK_COMPONENT_SWIZZLE_IDENTITY), TVkImageAspectFlags(VK_IMAGE_ASPECT_COLOR_BIT), 0, MipMaps, 0, 6); fGGXDescriptorImageInfo:=TVkDescriptorImageInfo.Create(fVulkanSampler.Handle, fVulkanGGXImageView.Handle, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); fCharlieDescriptorImageInfo:=TVkDescriptorImageInfo.Create(fVulkanSampler.Handle, fVulkanCharlieImageView.Handle, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); fLambertianDescriptorImageInfo:=TVkDescriptorImageInfo.Create(fVulkanSampler.Handle, fVulkanLambertianImageView.Handle, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL); for ImageIndex:=0 to 2 do begin ImageViews[ImageIndex]:=nil; DescriptorImageInfos[ImageIndex]:=nil; end; try for ImageIndex:=0 to 2 do begin SetLength(ImageViews[ImageIndex],MipMaps); SetLength(DescriptorImageInfos[ImageIndex],MipMaps); end; for ImageIndex:=0 to 2 do begin for Index:=0 to MipMaps-1 do begin ImageViews[ImageIndex,Index]:=TpvVulkanImageView.Create(aVulkanDevice, Images[ImageIndex]^, TVkImageViewType(VK_IMAGE_VIEW_TYPE_CUBE), aImageFormat, TVkComponentSwizzle(VK_COMPONENT_SWIZZLE_IDENTITY), TVkComponentSwizzle(VK_COMPONENT_SWIZZLE_IDENTITY), TVkComponentSwizzle(VK_COMPONENT_SWIZZLE_IDENTITY), TVkComponentSwizzle(VK_COMPONENT_SWIZZLE_IDENTITY), TVkImageAspectFlags(VK_IMAGE_ASPECT_COLOR_BIT), Index, 1, 0, 6); DescriptorImageInfos[ImageIndex,Index]:=TVkDescriptorImageInfo.Create(fVulkanSampler.Handle, ImageViews[ImageIndex,Index].Handle, VK_IMAGE_LAYOUT_GENERAL); end; end; try VulkanDescriptorSetLayout:=TpvVulkanDescriptorSetLayout.Create(aVulkanDevice); try VulkanDescriptorSetLayout.AddBinding(0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, TVkShaderStageFlags(VK_SHADER_STAGE_COMPUTE_BIT), []); VulkanDescriptorSetLayout.AddBinding(1, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, TVkShaderStageFlags(VK_SHADER_STAGE_COMPUTE_BIT), []); VulkanDescriptorSetLayout.Initialize; VulkanDescriptorPool:=TpvVulkanDescriptorPool.Create(aVulkanDevice, TVkDescriptorPoolCreateFlags(VK_DESCRIPTOR_POOL_CREATE_FREE_DESCRIPTOR_SET_BIT), 3*MipMaps); try VulkanDescriptorPool.AddDescriptorPoolSize(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER,3*MipMaps); VulkanDescriptorPool.AddDescriptorPoolSize(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE,3*MipMaps); VulkanDescriptorPool.Initialize; for ImageIndex:=0 to 2 do begin VulkanDescriptorSets[ImageIndex]:=nil; end; try for ImageIndex:=0 to 2 do begin SetLength(VulkanDescriptorSets[ImageIndex],MipMaps); for Index:=0 to MipMaps-1 do begin VulkanDescriptorSets[ImageIndex,Index]:=TpvVulkanDescriptorSet.Create(VulkanDescriptorPool, VulkanDescriptorSetLayout); VulkanDescriptorSets[ImageIndex,Index].WriteToDescriptorSet(0, 0, 1, TVkDescriptorType(VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER), [aDescriptorImageInfo], [], [], false); VulkanDescriptorSets[ImageIndex,Index].WriteToDescriptorSet(1, 0, 1, TVkDescriptorType(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE), [DescriptorImageInfos[ImageIndex,Index]], [], [], false); VulkanDescriptorSets[ImageIndex,Index].Flush; end; end; try PipelineLayout:=TpvVulkanPipelineLayout.Create(aVulkanDevice); try PipelineLayout.AddPushConstantRange(TVkShaderStageFlags(VK_SHADER_STAGE_COMPUTE_BIT),0,SizeOf(TPushConstants)); PipelineLayout.AddDescriptorSetLayout(VulkanDescriptorSetLayout); PipelineLayout.Initialize; Pipeline:=TpvVulkanComputePipeline.Create(aVulkanDevice, aVulkanPipelineCache, 0, fVulkanPipelineShaderStageCompute, PipelineLayout, nil, 0); try for ImageIndex:=0 to 2 do begin Images[ImageIndex]^.SetLayout(TVkImageAspectFlags(VK_IMAGE_ASPECT_COLOR_BIT), TVkImageLayout(VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL), TVkImageLayout(VK_IMAGE_LAYOUT_GENERAL), @ImageSubresourceRange, GraphicsCommandBuffer, GraphicsQueue, GraphicsFence, true); end; ComputeCommandBuffer.Reset(TVkCommandBufferResetFlags(VK_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT)); ComputeCommandBuffer.BeginRecording(TVkCommandBufferUsageFlags(VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT)); { FillChar(ImageMemoryBarrier,SizeOf(TVkImageMemoryBarrier),#0); ImageMemoryBarrier.sType:=VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; ImageMemoryBarrier.pNext:=nil; ImageMemoryBarrier.srcAccessMask:=TVkAccessFlags(VK_ACCESS_SHADER_READ_BIT); ImageMemoryBarrier.dstAccessMask:=TVkAccessFlags(VK_ACCESS_SHADER_WRITE_BIT); ImageMemoryBarrier.oldLayout:=VK_IMAGE_LAYOUT_GENERAL; ImageMemoryBarrier.newLayout:=VK_IMAGE_LAYOUT_GENERAL; ImageMemoryBarrier.srcQueueFamilyIndex:=VK_QUEUE_FAMILY_IGNORED; ImageMemoryBarrier.dstQueueFamilyIndex:=VK_QUEUE_FAMILY_IGNORED; ImageMemoryBarrier.image:=fVulkanImage.Handle; ImageMemoryBarrier.subresourceRange.aspectMask:=TVkImageAspectFlags(VK_IMAGE_ASPECT_COLOR_BIT); ImageMemoryBarrier.subresourceRange.baseMipLevel:=0; ImageMemoryBarrier.subresourceRange.levelCount:=MipMaps; ImageMemoryBarrier.subresourceRange.baseArrayLayer:=0; ImageMemoryBarrier.subresourceRange.layerCount:=1; ComputeCommandBuffer.CmdPipelineBarrier(TVkPipelineStageFlags(VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT), TVkPipelineStageFlags(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT), 0, 0,nil, 0,nil, 1,@ImageMemoryBarrier); } ComputeCommandBuffer.CmdBindPipeline(VK_PIPELINE_BIND_POINT_COMPUTE,Pipeline.Handle); for ImageIndex:=0 to 2 do begin for Index:=0 to MipMaps-1 do begin ComputeCommandBuffer.CmdBindDescriptorSets(VK_PIPELINE_BIND_POINT_COMPUTE, PipelineLayout.Handle, 0, 1, @VulkanDescriptorSets[ImageIndex,Index].Handle, 0, nil); PushConstants.MipMapLevel:=Index; PushConstants.MaxMipMapLevel:=MipMaps-1; if (ImageIndex=0) and (Index=0) then begin PushConstants.NumSamples:=1; end else begin PushConstants.NumSamples:=Min(128 shl Index,Samples); end; PushConstants.Which:=ImageIndex; ComputeCommandBuffer.CmdPushConstants(PipelineLayout.Handle, TVkShaderStageFlags(TVkShaderStageFlagBits.VK_SHADER_STAGE_COMPUTE_BIT), 0, SizeOf(TPushConstants), @PushConstants); ComputeCommandBuffer.CmdDispatch(Max(1,(Width+((1 shl (4+Index))-1)) shr (4+Index)), Max(1,(Height+((1 shl (4+Index))-1)) shr (4+Index)), 6); end; end; { FillChar(ImageMemoryBarrier,SizeOf(TVkImageMemoryBarrier),#0); ImageMemoryBarrier.sType:=VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; ImageMemoryBarrier.pNext:=nil; ImageMemoryBarrier.srcAccessMask:=TVkAccessFlags(VK_ACCESS_SHADER_WRITE_BIT); ImageMemoryBarrier.dstAccessMask:=TVkAccessFlags(VK_ACCESS_MEMORY_READ_BIT); ImageMemoryBarrier.oldLayout:=VK_IMAGE_LAYOUT_GENERAL; ImageMemoryBarrier.newLayout:=VK_IMAGE_LAYOUT_GENERAL; ImageMemoryBarrier.srcQueueFamilyIndex:=VK_QUEUE_FAMILY_IGNORED; ImageMemoryBarrier.dstQueueFamilyIndex:=VK_QUEUE_FAMILY_IGNORED; ImageMemoryBarrier.image:=fVulkanImage.Handle; ImageMemoryBarrier.subresourceRange.aspectMask:=TVkImageAspectFlags(VK_IMAGE_ASPECT_COLOR_BIT); ImageMemoryBarrier.subresourceRange.baseMipLevel:=0; ImageMemoryBarrier.subresourceRange.levelCount:=MipMaps; ImageMemoryBarrier.subresourceRange.baseArrayLayer:=0; ImageMemoryBarrier.subresourceRange.layerCount:=1; ComputeCommandBuffer.CmdPipelineBarrier(TVkPipelineStageFlags(VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT), TVkPipelineStageFlags(VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT), 0, 0,nil, 0,nil, 1,@ImageMemoryBarrier); } ComputeCommandBuffer.EndRecording; ComputeCommandBuffer.Execute(ComputeQueue,TVkPipelineStageFlags(VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT),nil,nil,ComputeFence,true); for ImageIndex:=0 to 2 do begin Images[ImageIndex]^.SetLayout(TVkImageAspectFlags(VK_IMAGE_ASPECT_COLOR_BIT), TVkImageLayout(VK_IMAGE_LAYOUT_GENERAL), TVkImageLayout(VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL), @ImageSubresourceRange, GraphicsCommandBuffer, GraphicsQueue, GraphicsFence, true); end; finally FreeAndNil(Pipeline); end; finally FreeAndNil(PipelineLayout); end; finally for ImageIndex:=0 to 2 do begin for Index:=0 to MipMaps-1 do begin FreeAndNil(VulkanDescriptorSets[ImageIndex,Index]); end; end; end; finally for ImageIndex:=0 to 2 do begin VulkanDescriptorSets[ImageIndex]:=nil; end; end; finally FreeAndNil(VulkanDescriptorPool); end; finally FreeAndNil(VulkanDescriptorSetLayout); end; finally for ImageIndex:=0 to 2 do begin for Index:=0 to MipMaps-1 do begin FreeAndNil(ImageViews[ImageIndex,Index]); end; end; end; finally for ImageIndex:=0 to 2 do begin ImageViews[ImageIndex]:=nil; DescriptorImageInfos[ImageIndex]:=nil; end; end; finally FreeAndNil(ComputeFence); end; finally FreeAndNil(ComputeCommandBuffer); end; finally FreeAndNil(ComputeCommandPool); end; finally FreeAndNil(GraphicsFence); end; finally FreeAndNil(GraphicsCommandBuffer); end; finally FreeAndNil(GraphicsCommandPool); end; end; destructor TpvScene3DRendererImageBasedLightingEnvMapCubeMaps.Destroy; begin FreeAndNil(fGGXMemoryBlock); FreeAndNil(fCharlieMemoryBlock); FreeAndNil(fLambertianMemoryBlock); FreeAndNil(fVulkanGGXImageView); FreeAndNil(fVulkanCharlieImageView); FreeAndNil(fVulkanLambertianImageView); FreeAndNil(fVulkanSampler); FreeAndNil(fVulkanGGXImage); FreeAndNil(fVulkanCharlieImage); FreeAndNil(fVulkanLambertianImage); FreeAndNil(fVulkanPipelineShaderStageCompute); FreeAndNil(fComputeShaderModule); inherited Destroy; end; end.
unit SmartPointer; interface type TSmartPtr<T: class> = record private FRef: T; function GetRefCountPtr: PInteger; inline; procedure Retain; inline; procedure Release; inline; public constructor Create(const ARef: T); class operator Initialize(out ADest: TSmartPtr<T>); class operator Finalize(var ADest: TSmartPtr<T>); class operator Assign(var ADest: TSmartPtr<T>; const [ref] ASrc: TSmartPtr<T>); { For testing only } function GetRefCount: Integer; property Ref: T read FRef; end; implementation { TSmartPtr<T> } constructor TSmartPtr<T>.Create(const ARef: T); begin FRef := ARef; Assert((FRef = nil) or (GetRefCountPtr^ = 0)); Retain; end; class operator TSmartPtr<T>.Initialize(out ADest: TSmartPtr<T>); begin ADest.FRef := nil; end; class operator TSmartPtr<T>.Finalize(var ADest: TSmartPtr<T>); begin ADest.Release; end; class operator TSmartPtr<T>.Assign(var ADest: TSmartPtr<T>; const [ref] ASrc: TSmartPtr<T>); begin if (ADest.FRef <> ASrc.FRef) then begin ADest.Release; ADest.FRef := ASrc.FRef; ADest.Retain; end; end; function TSmartPtr<T>.GetRefCountPtr: PInteger; begin if (FRef = nil) then Result := nil else Result := PInteger(IntPtr(FRef) + FRef.InstanceSize - hfFieldSize + hfMonitorOffset); end; procedure TSmartPtr<T>.Retain; begin var RefCountPtr := GetRefCountPtr; if (RefCountPtr <> nil) then AtomicIncrement(RefCountPtr^); end; procedure TSmartPtr<T>.Release; begin var RefCountPtr := GetRefCountPtr; if (RefCountPtr <> nil) then begin if (AtomicDecrement(RefCountPtr^) = 0) then begin { Before destroying the object, we must make sure that the hidden monitor is set to nil or 0. Otherwise, the destructor will try to free the monitor, which isn't actually a monitor but a reference count. This would most likely result in an access violation. Fortunately, this line of code only gets executed when reference count has dropped to 0, which has the same effect as setting the monitor to nil. } FRef.Free; end; FRef := nil; end; end; function TSmartPtr<T>.GetRefCount: Integer; begin var RefCountPtr := GetRefCountPtr; if (RefCountPtr = nil) then Result := 0 else Result := RefCountPtr^; end; end.
unit uMCListener; {$mode objfpc}{$H+} interface uses Classes, SysUtils, synsock, uLog, uNetwork, blcksock, umcconnection; type TThreadMCListener = class(TThread) private { Private declarations } trLocalIp:string; trPort:integer; trLogMsg:string; S:TTCPBlockSocket; procedure ReadParams; //procedure toLog; procedure trWriteLog(msg_str:string); //procedure UpdateCurrSocketID; protected { Protected declarations } procedure Execute; override; public constructor Create(local_ip: string); end; implementation uses uMain; { TThreadMCListener } constructor TThreadMCListener.Create(local_ip: string); begin inherited create(false); FreeOnTerminate := true; trLocalIp := local_ip; end; procedure TThreadMCListener.Execute; var S_res:TSocketResult; ss:tSocket; le:integer; begin FreeOnTerminate:=true; //Synchronize(@ReadParams); ReadParams; S_res:=PrepereSocketToListen(trLocalIp,trPort); While S_res.res<>1 do begin if Terminated then begin exit; end; trWriteLog('Error: cannot bind socket to local ip '+trLocalIp+' port '+inttostr(trPort)+'; err '+inttostr(-1*S_res.res)); trWriteLog('Waiting 5 seconds and try again..'); Sleep(5000); S_res:=PrepereSocketToListen(trLocalIp,trPort); end; S:=S_res.S; while not Terminated do begin if s.CanRead(500) then begin S.ResetLastError; ss:=S.Accept; le:=s.LastError; if le<>0 Then begin trWriteLog('Error while accepting connection. Err '+inttostr(-1*le)); Continue; end; // start new thread to proceed connection umcconnection.TThreadMCConnection.Create(ss); end; end; s.CloseSocket; end; procedure TThreadMCListener.ReadParams; begin //trPort:=uMain.sManagerConsoleListeningPort; cs1.Enter; trPort:=uMain.sManagerConsoleListeningPort; cs1.Leave; end; //procedure TThreadMCListener.toLog; //begin // uLog.WriteLogMsg(trLogMsg); //end; procedure TThreadMCListener.trWriteLog(msg_str:string); begin //trLogMsg:=msg_str; //Synchronize(@toLog); uLog.WriteLogMsg(msg_str); end; end.
unit SqlServerProvider; interface uses Windows, Forms, ComObj, ActiveX,Variants,DataAccessProvider; type TSQLServerProvider = class(TAbstractConnectProvider) private FLastError: string; protected function Get_MaxFieldCount: Integer; override; function Get_MaxTableCount: Integer; override; function Get_LastError: WideString; override; function GetFieldDefSQL(const FieldName: WideString; FieldType: Integer; FieldSize: Integer; DotLen: Integer; CanNull: WordBool; Data: OleVariant; IsPrimaryKey: WordBool): WideString; overload; override; function GetCreateIndexSQL(const TableName: WideString; Fields: OleVariant; const IndexName: WideString; IndexType: Integer; Data: OleVariant;Unique: WordBool): WideString; override; function GetRenameTableSQL(const OldTableName: WideString; const NewTableName: WideString): WideString; override; function GetDropFieldSQL(const TableName: WideString; const FieldNames: WideString): WideString; override; function GetCreateTableName(const TableName: WideString): WideString; override; function GetTopSelectSQL(const Fields: WideString; const TableName: WideString; const WhereCondition: WideString; const OrderCondition: WideString): WideString; override; function GetDate: WideString; override; function GetTableName(const TableName: WideString): WideString;override; function GetIndexName(const IndexName: WideString): WideString; override; function GetDataBaseSQL: WideString; override; function TableExists(const ATableName,ASchema: WideString): WideString; override; function ProcedureExists(const AProcedureName:WideString; const ASchema: WideString): WideString; override; function ReNameTable(const AOldName: WideString; const ANewName: WideString): WideString; override; function GetDropTableSQL(const ATableName: WideString): WideString; override; function GetFieldName(const AFieldName: WideString): WideString; override; function GetFieldValue(FieldType: Integer; Data: OleVariant): OleVariant; override; function GetFieldStringValue(FieldType: Integer;Data: OleVariant): WideString; override; function GetDropIndexSQL(const AIndexName: WideString; const ATableName: WideString): WideString; override; function GetAddFieldSQL(const AFieldName: WideString; AFieldType: Integer; AFieldSize: Integer; AFieldPrecision: Integer): WideString; override; function GetResetFiledSizeSQL(const AFieldName: WideString; AFieldSize: SYSINT): WideString; override; function Get_NeedReStructTable: WordBool; override; function GetAddFieldConnSQL(const ATableName: WideString;const ASQL: WideString): WideString; override; function GetIndexExistsSQL(const AIndexName: WideString): WideString; override; function GetUpdateFieldLengthSQL(const ATableName: WideString; const AFieldName: WideString; AOldLength: Integer; ANewLength: Integer): WideString; override; function FieldExists(const ATableName,AField: WideString): WideString; override; function GetAlterFieldSQL(const ATableName: WideString; const AFieldName: WideString; AOleType: Integer; ANewType: Integer; AFieldLength: Integer; AIsNull: WordBool): WideString; override; function GetUpdateVarcharToDate(const ATableName: WideString; const AFieldName: WideString): WideString; override; function GetUpdateDateToVarcharSQL(const ATableName: WideString; const AFieldName: WideString; AFieldSize: Integer): WideString; override; function GetUpdateVarCharToNumSQL(const ATableName: WideString; const AFieldName: WideString): WideString; override; function GetSetFieldNullSQL(const ATableName: WideString; const AFieldName: WideString): WideString; override; public destructor Destroy; override; end; implementation uses ComServ, SysUtils, DB, Controls,ProviderConst; const SQL_TopSelectFormatStr = 'SELECT TOP 1 %s FROM %s %s %s'; SQL_GetCurrentDateTime = 'SELECT GETDATE() AS CURRENTDATETIME'; SQL_GetDBList = 'SELECT NAME FROM MASTER..SYSDATABASES'; SQL_TABLEEXISTS = 'SELECT NAME AS TABLENAME FROM DBO.SYSOBJECTS WHERE ID=OBJECT_ID(N''[DBO].[%s]'')'+ ' AND OBJECTPROPERTY(ID, N''ISUSERTABLE'') = 1'; SQL_PROCEDUREEXISTS = 'SELECT NAME AS TABLENAME FROM DBO.SYSOBJECTS WHERE ID=OBJECT_ID(N''[DBO].[%s]'')'+ ' AND OBJECTPROPERTY(ID, N''ISPROCEDURE'') = 1'; SQL_FIELDEXISTS ='SELECT NAME FROM DBO.SYSCOLUMNS WHERE ID = OBJECT_ID(N''[dbo].[%s]'') '+ ' AND OBJECTPROPERTY(ID, N''ISUSERTABLE'') = 1 AND NAME =''%s''' ; SQL_RENAMETABLE = 'EXEC SP_RENAME %s,%s'; SQL_DROPTABLE = 'DROP TABLE %s'; SQL_DROPINDEX = 'DROP INDEX %s.%s'; SQL_DROPFIELD = 'ALTER TABLE %s DROP COLUMN %s'; SQL_ADDFIELD = '%s,'; SQL_ADDFIELDCONNSTR = 'ALTER TABLE %s ADD %s'; SQL_UPDATEFIELDLENGTH = 'UPDATE %s SET %1:s=SUBSTRING(%1:s, %d, %d)'; SQL_UPDATEVARCHARTODATE = 'UPDATE %s SET %1:s=NULL WHERUPDATE %s SET %1:s=CONVERT(VARCHAR(%d), '+ 'CAST(%1:s AS DATETIME), 126) WHERE ISDATE(%1:s)=1E ISDATE(%1:s)=0 '; SQL_UPDATEDATETOVARCHAR = ''; SQL_UPDATEVARCHARTONUM = 'UPDATE %s SET %1:s=NULL WHERE ISNUMERIC(%1:s)=0'; SQL_ALTERFIELDSQL = 'ALTER TABLE %s ALTER COLUMN %s'; SQL_SETFIELDNULL = 'UPDATE %s SET %s=null'; SQL_WHERECONDITIONSIGN = ' WHERE '; SQL_ORDERCONDITIONSIGN = ' ORDER BY'; function TSQLServerProvider.Get_MaxFieldCount: Integer; begin Result := Int_Max_Field_Count; end; function TSQLServerProvider.Get_MaxTableCount: Integer; begin Result := Int_Max_Table_Count; end; function TSQLServerProvider.Get_LastError: WideString; begin Result := FLastError; end; function TSQLServerProvider.GetFieldDefSQL(const FieldName: WideString; FieldType, FieldSize, DotLen: Integer; CanNull: WordBool; Data: OleVariant;IsPrimaryKey: WordBool): WideString; const NS: array[False..True] of string = ('NOT NULL', 'NULL'); var KeyStr : string; //add by lijun 2004-3-26 begin //得到创建表时字段的SQL描述 Result := ''; case TFieldType(FieldType) of ftString,ftwidestring: Result := Format('VARCHAR(%d)', [FieldSize]); ftFixedChar : Result := Format('CHAR(%d)',[FieldSize]); ftSmallint, ftInteger, ftWord: Result := 'INT'; ftBoolean: Result := 'BIT'; ftFloat, ftBCD: Result := Format('FLOAT', [DotLen]); ftCurrency: Result := 'MONEY'; ftDate, ftTime, ftDateTime: Result := 'DATETIME'; ftAutoInc: Result := 'INT IDENTITY(1,1)'; ftBlob, ftGraphic: Result := 'IMAGE'; ftMemo: Result := 'TEXT'; end; KeyStr := ''; //add by lijun 2004-3-26 增加判断是否主键 if IsPrimaryKey then KeyStr := PrimaryKeyStr; Result := Format('[%s] %s %s %s', [FieldName, Result,KeyStr, NS[CanNull]]); //add by lijun end; end; function TSQLServerProvider.GetCreateIndexSQL(const TableName: WideString; Fields: OleVariant; const IndexName: WideString; IndexType: Integer; Data: OleVariant;Unique: WordBool): WideString; var S: string; I: Integer; SUnique:string; begin S := ''; for I := VarArrayLowBound(Fields, 1) to VarArrayHighBound(Fields, 1) do S := S+'['+Fields[I]+'],'; if Length(S) > 0 then Delete(S, Length(S), 1); SUnique := ''; //add by lijun 2004-3-29 索引增加唯一标识 if Unique then SUnique := UNIQUESQLTAG; case IndexType of {1:主键;0:索引} 1 : Result := 'ALTER TABLE '+TableName+' WITH NOCHECK ADD '+ 'CONSTRAINT ['+IndexName+'] PRIMARY KEY CLUSTERED '+ '('+S+') ON [PRIMARY]'; 0 : Result := 'CREATE '+SUnique+' INDEX '+IndexName+ ' ON '+TableName+'('+S+')'; end; //add by lijun end; end; function TSQLServerProvider.GetRenameTableSQL(const OldTableName, NewTableName: WideString): WideString; begin Result := Format('EXEC SP_RENAME %s,%s', [OldTableName, NewTableName]); { case ConnType of ctSQLServer: begin Result := Format('EXEC SP_RENAME %s,%s', [OldName, NewName]); end; ctDB2 : begin Result := Format('RENAME TABLE %s TO %s', [OldName, NewName]); end;   end; } end; function TSQLServerProvider.GetDropFieldSql( const TableName: WideString; const FieldNames: WideString): WideString; begin Result := Format(SQL_DROPFIELD,[TableName,FieldNames]); end; function TSQLServerProvider.GetCreateTableName( const TableName: WideString): WideString; begin if Pos('DBO.', UpperCase(Trim(TableName)))<> 1 then Result := '[dbo].['+Trim(TableName)+']' else Result := TableName; end; destructor TSQLServerProvider.Destroy; begin inherited; end; function TSQLServerProvider.GetTopSelectSQL(const Fields, TableName: WideString;const WhereCondition: WideString; const OrderCondition: WideString): WideString; var sWhere,sOrder:WideString; begin if Trim(WhereCondition)='' then sWhere := '' Else sWhere := SQL_WHERECONDITIONSIGN + WhereCondition; if Trim(OrderCondition)='' then sOrder := '' Else sOrder := SQL_ORDERCONDITIONSIGN + OrderCondition; result := format(SQL_TopSelectFormatStr,[Fields,TableName,sWhere,sOrder]); end; function TSQLServerProvider.GetDate: WideString; begin result := SQL_GetCurrentDateTime; end; function TSQLServerProvider.GetTableName( const TableName: WideString): WideString; begin Result := TableName; end; function TSQLServerProvider.GetIndexName( const IndexName: WideString): WideString; begin Result := IndexName; end; function TSQLServerProvider.GetDataBaseSQL: WideString; begin Result := SQL_GetDBList; end; function TSQLServerProvider.TableExists( const ATableName,ASchema: WideString): WideString; begin Result := format(SQL_TABLEEXISTS,[ATableName]); end; function TSQLServerProvider.ReNameTable(const AOldName, ANewName: WideString): WideString; begin Result := format(SQL_RENAMETABLE,[UpperCase(AOldName),UpperCase(ANewName)]); end; function TSQLServerProvider.GetDropTableSQL( const ATableName: WideString): WideString; begin Result := Format(SQL_DROPTABLE,[ATableName]); end; function TSQLServerProvider.GetFieldName( const AFieldName: WideString): WideString; begin Result := AFieldName; end; function TSQLServerProvider.GetFieldValue(FieldType: Integer; Data: OleVariant): OleVariant; begin Result := Data; case TFieldType(FieldType) of ftBoolean: if Data then Result := '1' else Result := '0'; else Result := Data; end; end; function TSQLServerProvider.GetFieldStringValue(FieldType: Integer; Data: OleVariant): WideString; begin Result := Data; end; function TSQLServerProvider.GetAddFieldSQL(const AFieldName: WideString; AFieldType: Integer; AFieldSize: Integer; AFieldPrecision: Integer): WideString; begin Result := Format(SQL_ADDFIELD,[GetFieldDefSQL(AFieldName,AFieldType, AFieldSize,AFieldPrecision,True,Null,False)]); end; function TSQLServerProvider.GetDropIndexSQL( const AIndexName: WideString; const ATableName: WideString): WideString; begin Result := Format(SQL_DROPINDEX,[ATableName,AIndexName]); end; function TSQLServerProvider.GetResetFiledSizeSQL(const AFieldName: WideString; AFieldSize: SYSINT): WideString; begin end; function TSQLServerProvider.Get_NeedReStructTable: WordBool; begin Result := False; end; function TSQLServerProvider.GetAddFieldConnSQL( const ATableName: WideString;const ASQL: WideString): WideString; begin Result := Format(SQL_ADDFIELDCONNSTR,[ATableName,ASQL]); end; function TSQLServerProvider.GetIndexExistsSQL( const AIndexName: WideString): WideString; begin // Result := Format(); end; function TSQLServerProvider.GetUpdateFieldLengthSQL(const ATableName, AFieldName: WideString; AOldLength, ANewLength: Integer): WideString; begin Result := Format(SQL_UPDATEFIELDLENGTH,[ATableName,AFieldName,AOldLength,ANewLength]); end; function TSQLServerProvider.GetAlterFieldSQL(const ATableName, AFieldName: WideString; AOleType, ANewType: Integer; AFieldLength: Integer; AIsNull: WordBool): WideString; begin Result := Format(SQL_ALTERFIELDSQL,[ATableName, GetFieldDefSQL(AFieldName,ANewType,AFieldLength,0,AIsNull,null,False)]); end; function TSQLServerProvider.GetUpdateVarcharToDate(const ATableName, AFieldName: WideString): WideString; begin Result := Format(SQL_UPDATEVARCHARTODATE,[ATableName,AFieldName]); end; function TSQLServerProvider.GetUpdateDateToVarcharSQL(const ATableName, AFieldName: WideString;AFieldSize: Integer): WideString; begin Result := Format(SQL_UPDATEDATETOVARCHAR,[ATableName,AFieldName,AFieldSize]); end; function TSQLServerProvider.GetUpdateVarCharToNumSQL(const ATableName, AFieldName: WideString): WideString; begin Result := Format(SQL_UPDATEVARCHARTONUM,[ATableName,AFieldName]); end; function TSQLServerProvider.GetSetFieldNullSQL(const ATableName, AFieldName: WideString): WideString; begin Result := Format( SQL_SETFIELDNULL,[ATableName,AFieldName]); end; function TSQLServerProvider.FieldExists(const ATableName, AField: WideString): WideString; begin Result := format(SQL_FIELDEXISTS,[ATableName,AField]); end; function TSQLServerProvider.ProcedureExists(const AProcedureName:WideString;const ASchema: WideString): WideString; begin Result := format(SQL_PROCEDUREEXISTS,[AProcedureName]); end; end.
unit Mht; interface type HCkMht = Pointer; HCkTask = Pointer; HCkString = Pointer; function CkMht_Create: HCkMht; stdcall; procedure CkMht_Dispose(handle: HCkMht); stdcall; function CkMht_getAbortCurrent(objHandle: HCkMht): wordbool; stdcall; procedure CkMht_putAbortCurrent(objHandle: HCkMht; newPropVal: wordbool); stdcall; procedure CkMht_getBaseUrl(objHandle: HCkMht; outPropVal: HCkString); stdcall; procedure CkMht_putBaseUrl(objHandle: HCkMht; newPropVal: PWideChar); stdcall; function CkMht__baseUrl(objHandle: HCkMht): PWideChar; stdcall; function CkMht_getConnectTimeout(objHandle: HCkMht): Integer; stdcall; procedure CkMht_putConnectTimeout(objHandle: HCkMht; newPropVal: Integer); stdcall; procedure CkMht_getDebugHtmlAfter(objHandle: HCkMht; outPropVal: HCkString); stdcall; procedure CkMht_putDebugHtmlAfter(objHandle: HCkMht; newPropVal: PWideChar); stdcall; function CkMht__debugHtmlAfter(objHandle: HCkMht): PWideChar; stdcall; procedure CkMht_getDebugHtmlBefore(objHandle: HCkMht; outPropVal: HCkString); stdcall; procedure CkMht_putDebugHtmlBefore(objHandle: HCkMht; newPropVal: PWideChar); stdcall; function CkMht__debugHtmlBefore(objHandle: HCkMht): PWideChar; stdcall; procedure CkMht_getDebugLogFilePath(objHandle: HCkMht; outPropVal: HCkString); stdcall; procedure CkMht_putDebugLogFilePath(objHandle: HCkMht; newPropVal: PWideChar); stdcall; function CkMht__debugLogFilePath(objHandle: HCkMht): PWideChar; stdcall; function CkMht_getDebugTagCleaning(objHandle: HCkMht): wordbool; stdcall; procedure CkMht_putDebugTagCleaning(objHandle: HCkMht; newPropVal: wordbool); stdcall; function CkMht_getEmbedImages(objHandle: HCkMht): wordbool; stdcall; procedure CkMht_putEmbedImages(objHandle: HCkMht; newPropVal: wordbool); stdcall; function CkMht_getEmbedLocalOnly(objHandle: HCkMht): wordbool; stdcall; procedure CkMht_putEmbedLocalOnly(objHandle: HCkMht; newPropVal: wordbool); stdcall; function CkMht_getFetchFromCache(objHandle: HCkMht): wordbool; stdcall; procedure CkMht_putFetchFromCache(objHandle: HCkMht; newPropVal: wordbool); stdcall; function CkMht_getHeartbeatMs(objHandle: HCkMht): Integer; stdcall; procedure CkMht_putHeartbeatMs(objHandle: HCkMht; newPropVal: Integer); stdcall; function CkMht_getIgnoreMustRevalidate(objHandle: HCkMht): wordbool; stdcall; procedure CkMht_putIgnoreMustRevalidate(objHandle: HCkMht; newPropVal: wordbool); stdcall; function CkMht_getIgnoreNoCache(objHandle: HCkMht): wordbool; stdcall; procedure CkMht_putIgnoreNoCache(objHandle: HCkMht; newPropVal: wordbool); stdcall; procedure CkMht_getLastErrorHtml(objHandle: HCkMht; outPropVal: HCkString); stdcall; function CkMht__lastErrorHtml(objHandle: HCkMht): PWideChar; stdcall; procedure CkMht_getLastErrorText(objHandle: HCkMht; outPropVal: HCkString); stdcall; function CkMht__lastErrorText(objHandle: HCkMht): PWideChar; stdcall; procedure CkMht_getLastErrorXml(objHandle: HCkMht; outPropVal: HCkString); stdcall; function CkMht__lastErrorXml(objHandle: HCkMht): PWideChar; stdcall; function CkMht_getLastMethodSuccess(objHandle: HCkMht): wordbool; stdcall; procedure CkMht_putLastMethodSuccess(objHandle: HCkMht; newPropVal: wordbool); stdcall; function CkMht_getNoScripts(objHandle: HCkMht): wordbool; stdcall; procedure CkMht_putNoScripts(objHandle: HCkMht; newPropVal: wordbool); stdcall; function CkMht_getNtlmAuth(objHandle: HCkMht): wordbool; stdcall; procedure CkMht_putNtlmAuth(objHandle: HCkMht; newPropVal: wordbool); stdcall; function CkMht_getNumCacheLevels(objHandle: HCkMht): Integer; stdcall; procedure CkMht_putNumCacheLevels(objHandle: HCkMht; newPropVal: Integer); stdcall; function CkMht_getNumCacheRoots(objHandle: HCkMht): Integer; stdcall; function CkMht_getPreferIpv6(objHandle: HCkMht): wordbool; stdcall; procedure CkMht_putPreferIpv6(objHandle: HCkMht; newPropVal: wordbool); stdcall; function CkMht_getPreferMHTScripts(objHandle: HCkMht): wordbool; stdcall; procedure CkMht_putPreferMHTScripts(objHandle: HCkMht; newPropVal: wordbool); stdcall; procedure CkMht_getProxy(objHandle: HCkMht; outPropVal: HCkString); stdcall; procedure CkMht_putProxy(objHandle: HCkMht; newPropVal: PWideChar); stdcall; function CkMht__proxy(objHandle: HCkMht): PWideChar; stdcall; procedure CkMht_getProxyLogin(objHandle: HCkMht; outPropVal: HCkString); stdcall; procedure CkMht_putProxyLogin(objHandle: HCkMht; newPropVal: PWideChar); stdcall; function CkMht__proxyLogin(objHandle: HCkMht): PWideChar; stdcall; procedure CkMht_getProxyPassword(objHandle: HCkMht; outPropVal: HCkString); stdcall; procedure CkMht_putProxyPassword(objHandle: HCkMht; newPropVal: PWideChar); stdcall; function CkMht__proxyPassword(objHandle: HCkMht): PWideChar; stdcall; function CkMht_getReadTimeout(objHandle: HCkMht): Integer; stdcall; procedure CkMht_putReadTimeout(objHandle: HCkMht; newPropVal: Integer); stdcall; function CkMht_getRequireSslCertVerify(objHandle: HCkMht): wordbool; stdcall; procedure CkMht_putRequireSslCertVerify(objHandle: HCkMht; newPropVal: wordbool); stdcall; procedure CkMht_getSocksHostname(objHandle: HCkMht; outPropVal: HCkString); stdcall; procedure CkMht_putSocksHostname(objHandle: HCkMht; newPropVal: PWideChar); stdcall; function CkMht__socksHostname(objHandle: HCkMht): PWideChar; stdcall; procedure CkMht_getSocksPassword(objHandle: HCkMht; outPropVal: HCkString); stdcall; procedure CkMht_putSocksPassword(objHandle: HCkMht; newPropVal: PWideChar); stdcall; function CkMht__socksPassword(objHandle: HCkMht): PWideChar; stdcall; function CkMht_getSocksPort(objHandle: HCkMht): Integer; stdcall; procedure CkMht_putSocksPort(objHandle: HCkMht; newPropVal: Integer); stdcall; procedure CkMht_getSocksUsername(objHandle: HCkMht; outPropVal: HCkString); stdcall; procedure CkMht_putSocksUsername(objHandle: HCkMht; newPropVal: PWideChar); stdcall; function CkMht__socksUsername(objHandle: HCkMht): PWideChar; stdcall; function CkMht_getSocksVersion(objHandle: HCkMht): Integer; stdcall; procedure CkMht_putSocksVersion(objHandle: HCkMht; newPropVal: Integer); stdcall; function CkMht_getUnpackDirect(objHandle: HCkMht): wordbool; stdcall; procedure CkMht_putUnpackDirect(objHandle: HCkMht; newPropVal: wordbool); stdcall; function CkMht_getUnpackUseRelPaths(objHandle: HCkMht): wordbool; stdcall; procedure CkMht_putUnpackUseRelPaths(objHandle: HCkMht; newPropVal: wordbool); stdcall; function CkMht_getUpdateCache(objHandle: HCkMht): wordbool; stdcall; procedure CkMht_putUpdateCache(objHandle: HCkMht; newPropVal: wordbool); stdcall; function CkMht_getUseCids(objHandle: HCkMht): wordbool; stdcall; procedure CkMht_putUseCids(objHandle: HCkMht; newPropVal: wordbool); stdcall; function CkMht_getUseFilename(objHandle: HCkMht): wordbool; stdcall; procedure CkMht_putUseFilename(objHandle: HCkMht; newPropVal: wordbool); stdcall; function CkMht_getUseIEProxy(objHandle: HCkMht): wordbool; stdcall; procedure CkMht_putUseIEProxy(objHandle: HCkMht; newPropVal: wordbool); stdcall; function CkMht_getUseInline(objHandle: HCkMht): wordbool; stdcall; procedure CkMht_putUseInline(objHandle: HCkMht; newPropVal: wordbool); stdcall; function CkMht_getVerboseLogging(objHandle: HCkMht): wordbool; stdcall; procedure CkMht_putVerboseLogging(objHandle: HCkMht; newPropVal: wordbool); stdcall; procedure CkMht_getVersion(objHandle: HCkMht; outPropVal: HCkString); stdcall; function CkMht__version(objHandle: HCkMht): PWideChar; stdcall; procedure CkMht_getWebSiteLogin(objHandle: HCkMht; outPropVal: HCkString); stdcall; procedure CkMht_putWebSiteLogin(objHandle: HCkMht; newPropVal: PWideChar); stdcall; function CkMht__webSiteLogin(objHandle: HCkMht): PWideChar; stdcall; procedure CkMht_getWebSiteLoginDomain(objHandle: HCkMht; outPropVal: HCkString); stdcall; procedure CkMht_putWebSiteLoginDomain(objHandle: HCkMht; newPropVal: PWideChar); stdcall; function CkMht__webSiteLoginDomain(objHandle: HCkMht): PWideChar; stdcall; procedure CkMht_getWebSitePassword(objHandle: HCkMht; outPropVal: HCkString); stdcall; procedure CkMht_putWebSitePassword(objHandle: HCkMht; newPropVal: PWideChar); stdcall; function CkMht__webSitePassword(objHandle: HCkMht): PWideChar; stdcall; procedure CkMht_AddCacheRoot(objHandle: HCkMht; dir: PWideChar); stdcall; procedure CkMht_AddCustomHeader(objHandle: HCkMht; name: PWideChar; value: PWideChar); stdcall; procedure CkMht_AddExternalStyleSheet(objHandle: HCkMht; url: PWideChar); stdcall; procedure CkMht_ClearCustomHeaders(objHandle: HCkMht); stdcall; procedure CkMht_ExcludeImagesMatching(objHandle: HCkMht; pattern: PWideChar); stdcall; function CkMht_GetAndSaveEML(objHandle: HCkMht; url_or_htmlFilepath: PWideChar; emlPath: PWideChar): wordbool; stdcall; function CkMht_GetAndSaveEMLAsync(objHandle: HCkMht; url_or_htmlFilepath: PWideChar; emlPath: PWideChar): HCkTask; stdcall; function CkMht_GetAndSaveMHT(objHandle: HCkMht; url_or_htmlFilepath: PWideChar; mhtPath: PWideChar): wordbool; stdcall; function CkMht_GetAndSaveMHTAsync(objHandle: HCkMht; url_or_htmlFilepath: PWideChar; mhtPath: PWideChar): HCkTask; stdcall; function CkMht_GetAndZipEML(objHandle: HCkMht; url_or_htmlFilepath: PWideChar; zipEntryFilename: PWideChar; zipFilename: PWideChar): wordbool; stdcall; function CkMht_GetAndZipEMLAsync(objHandle: HCkMht; url_or_htmlFilepath: PWideChar; zipEntryFilename: PWideChar; zipFilename: PWideChar): HCkTask; stdcall; function CkMht_GetAndZipMHT(objHandle: HCkMht; url_or_htmlFilepath: PWideChar; zipEntryFilename: PWideChar; zipFilename: PWideChar): wordbool; stdcall; function CkMht_GetAndZipMHTAsync(objHandle: HCkMht; url_or_htmlFilepath: PWideChar; zipEntryFilename: PWideChar; zipFilename: PWideChar): HCkTask; stdcall; function CkMht_GetCacheRoot(objHandle: HCkMht; index: Integer; outStr: HCkString): wordbool; stdcall; function CkMht__getCacheRoot(objHandle: HCkMht; index: Integer): PWideChar; stdcall; function CkMht_GetEML(objHandle: HCkMht; url_or_htmlFilepath: PWideChar; outStr: HCkString): wordbool; stdcall; function CkMht__getEML(objHandle: HCkMht; url_or_htmlFilepath: PWideChar): PWideChar; stdcall; function CkMht_GetEMLAsync(objHandle: HCkMht; url_or_htmlFilepath: PWideChar): HCkTask; stdcall; function CkMht_GetMHT(objHandle: HCkMht; url_or_htmlFilepath: PWideChar; outStr: HCkString): wordbool; stdcall; function CkMht__getMHT(objHandle: HCkMht; url_or_htmlFilepath: PWideChar): PWideChar; stdcall; function CkMht_GetMHTAsync(objHandle: HCkMht; url_or_htmlFilepath: PWideChar): HCkTask; stdcall; function CkMht_HtmlToEML(objHandle: HCkMht; htmlText: PWideChar; outStr: HCkString): wordbool; stdcall; function CkMht__htmlToEML(objHandle: HCkMht; htmlText: PWideChar): PWideChar; stdcall; function CkMht_HtmlToEMLAsync(objHandle: HCkMht; htmlText: PWideChar): HCkTask; stdcall; function CkMht_HtmlToEMLFile(objHandle: HCkMht; html: PWideChar; emlFilename: PWideChar): wordbool; stdcall; function CkMht_HtmlToEMLFileAsync(objHandle: HCkMht; html: PWideChar; emlFilename: PWideChar): HCkTask; stdcall; function CkMht_HtmlToMHT(objHandle: HCkMht; htmlText: PWideChar; outStr: HCkString): wordbool; stdcall; function CkMht__htmlToMHT(objHandle: HCkMht; htmlText: PWideChar): PWideChar; stdcall; function CkMht_HtmlToMHTAsync(objHandle: HCkMht; htmlText: PWideChar): HCkTask; stdcall; function CkMht_HtmlToMHTFile(objHandle: HCkMht; html: PWideChar; mhtFilename: PWideChar): wordbool; stdcall; function CkMht_HtmlToMHTFileAsync(objHandle: HCkMht; html: PWideChar; mhtFilename: PWideChar): HCkTask; stdcall; function CkMht_IsUnlocked(objHandle: HCkMht): wordbool; stdcall; procedure CkMht_RemoveCustomHeader(objHandle: HCkMht; name: PWideChar); stdcall; procedure CkMht_RestoreDefaults(objHandle: HCkMht); stdcall; function CkMht_SaveLastError(objHandle: HCkMht; path: PWideChar): wordbool; stdcall; function CkMht_UnlockComponent(objHandle: HCkMht; unlockCode: PWideChar): wordbool; stdcall; function CkMht_UnpackMHT(objHandle: HCkMht; mhtFilename: PWideChar; unpackDir: PWideChar; htmlFilename: PWideChar; partsSubDir: PWideChar): wordbool; stdcall; function CkMht_UnpackMHTString(objHandle: HCkMht; mhtString: PWideChar; unpackDir: PWideChar; htmlFilename: PWideChar; partsSubDir: PWideChar): wordbool; stdcall; implementation {$Include chilkatDllPath.inc} function CkMht_Create; external DLLName; procedure CkMht_Dispose; external DLLName; function CkMht_getAbortCurrent; external DLLName; procedure CkMht_putAbortCurrent; external DLLName; procedure CkMht_getBaseUrl; external DLLName; procedure CkMht_putBaseUrl; external DLLName; function CkMht__baseUrl; external DLLName; function CkMht_getConnectTimeout; external DLLName; procedure CkMht_putConnectTimeout; external DLLName; procedure CkMht_getDebugHtmlAfter; external DLLName; procedure CkMht_putDebugHtmlAfter; external DLLName; function CkMht__debugHtmlAfter; external DLLName; procedure CkMht_getDebugHtmlBefore; external DLLName; procedure CkMht_putDebugHtmlBefore; external DLLName; function CkMht__debugHtmlBefore; external DLLName; procedure CkMht_getDebugLogFilePath; external DLLName; procedure CkMht_putDebugLogFilePath; external DLLName; function CkMht__debugLogFilePath; external DLLName; function CkMht_getDebugTagCleaning; external DLLName; procedure CkMht_putDebugTagCleaning; external DLLName; function CkMht_getEmbedImages; external DLLName; procedure CkMht_putEmbedImages; external DLLName; function CkMht_getEmbedLocalOnly; external DLLName; procedure CkMht_putEmbedLocalOnly; external DLLName; function CkMht_getFetchFromCache; external DLLName; procedure CkMht_putFetchFromCache; external DLLName; function CkMht_getHeartbeatMs; external DLLName; procedure CkMht_putHeartbeatMs; external DLLName; function CkMht_getIgnoreMustRevalidate; external DLLName; procedure CkMht_putIgnoreMustRevalidate; external DLLName; function CkMht_getIgnoreNoCache; external DLLName; procedure CkMht_putIgnoreNoCache; external DLLName; procedure CkMht_getLastErrorHtml; external DLLName; function CkMht__lastErrorHtml; external DLLName; procedure CkMht_getLastErrorText; external DLLName; function CkMht__lastErrorText; external DLLName; procedure CkMht_getLastErrorXml; external DLLName; function CkMht__lastErrorXml; external DLLName; function CkMht_getLastMethodSuccess; external DLLName; procedure CkMht_putLastMethodSuccess; external DLLName; function CkMht_getNoScripts; external DLLName; procedure CkMht_putNoScripts; external DLLName; function CkMht_getNtlmAuth; external DLLName; procedure CkMht_putNtlmAuth; external DLLName; function CkMht_getNumCacheLevels; external DLLName; procedure CkMht_putNumCacheLevels; external DLLName; function CkMht_getNumCacheRoots; external DLLName; function CkMht_getPreferIpv6; external DLLName; procedure CkMht_putPreferIpv6; external DLLName; function CkMht_getPreferMHTScripts; external DLLName; procedure CkMht_putPreferMHTScripts; external DLLName; procedure CkMht_getProxy; external DLLName; procedure CkMht_putProxy; external DLLName; function CkMht__proxy; external DLLName; procedure CkMht_getProxyLogin; external DLLName; procedure CkMht_putProxyLogin; external DLLName; function CkMht__proxyLogin; external DLLName; procedure CkMht_getProxyPassword; external DLLName; procedure CkMht_putProxyPassword; external DLLName; function CkMht__proxyPassword; external DLLName; function CkMht_getReadTimeout; external DLLName; procedure CkMht_putReadTimeout; external DLLName; function CkMht_getRequireSslCertVerify; external DLLName; procedure CkMht_putRequireSslCertVerify; external DLLName; procedure CkMht_getSocksHostname; external DLLName; procedure CkMht_putSocksHostname; external DLLName; function CkMht__socksHostname; external DLLName; procedure CkMht_getSocksPassword; external DLLName; procedure CkMht_putSocksPassword; external DLLName; function CkMht__socksPassword; external DLLName; function CkMht_getSocksPort; external DLLName; procedure CkMht_putSocksPort; external DLLName; procedure CkMht_getSocksUsername; external DLLName; procedure CkMht_putSocksUsername; external DLLName; function CkMht__socksUsername; external DLLName; function CkMht_getSocksVersion; external DLLName; procedure CkMht_putSocksVersion; external DLLName; function CkMht_getUnpackDirect; external DLLName; procedure CkMht_putUnpackDirect; external DLLName; function CkMht_getUnpackUseRelPaths; external DLLName; procedure CkMht_putUnpackUseRelPaths; external DLLName; function CkMht_getUpdateCache; external DLLName; procedure CkMht_putUpdateCache; external DLLName; function CkMht_getUseCids; external DLLName; procedure CkMht_putUseCids; external DLLName; function CkMht_getUseFilename; external DLLName; procedure CkMht_putUseFilename; external DLLName; function CkMht_getUseIEProxy; external DLLName; procedure CkMht_putUseIEProxy; external DLLName; function CkMht_getUseInline; external DLLName; procedure CkMht_putUseInline; external DLLName; function CkMht_getVerboseLogging; external DLLName; procedure CkMht_putVerboseLogging; external DLLName; procedure CkMht_getVersion; external DLLName; function CkMht__version; external DLLName; procedure CkMht_getWebSiteLogin; external DLLName; procedure CkMht_putWebSiteLogin; external DLLName; function CkMht__webSiteLogin; external DLLName; procedure CkMht_getWebSiteLoginDomain; external DLLName; procedure CkMht_putWebSiteLoginDomain; external DLLName; function CkMht__webSiteLoginDomain; external DLLName; procedure CkMht_getWebSitePassword; external DLLName; procedure CkMht_putWebSitePassword; external DLLName; function CkMht__webSitePassword; external DLLName; procedure CkMht_AddCacheRoot; external DLLName; procedure CkMht_AddCustomHeader; external DLLName; procedure CkMht_AddExternalStyleSheet; external DLLName; procedure CkMht_ClearCustomHeaders; external DLLName; procedure CkMht_ExcludeImagesMatching; external DLLName; function CkMht_GetAndSaveEML; external DLLName; function CkMht_GetAndSaveEMLAsync; external DLLName; function CkMht_GetAndSaveMHT; external DLLName; function CkMht_GetAndSaveMHTAsync; external DLLName; function CkMht_GetAndZipEML; external DLLName; function CkMht_GetAndZipEMLAsync; external DLLName; function CkMht_GetAndZipMHT; external DLLName; function CkMht_GetAndZipMHTAsync; external DLLName; function CkMht_GetCacheRoot; external DLLName; function CkMht__getCacheRoot; external DLLName; function CkMht_GetEML; external DLLName; function CkMht__getEML; external DLLName; function CkMht_GetEMLAsync; external DLLName; function CkMht_GetMHT; external DLLName; function CkMht__getMHT; external DLLName; function CkMht_GetMHTAsync; external DLLName; function CkMht_HtmlToEML; external DLLName; function CkMht__htmlToEML; external DLLName; function CkMht_HtmlToEMLAsync; external DLLName; function CkMht_HtmlToEMLFile; external DLLName; function CkMht_HtmlToEMLFileAsync; external DLLName; function CkMht_HtmlToMHT; external DLLName; function CkMht__htmlToMHT; external DLLName; function CkMht_HtmlToMHTAsync; external DLLName; function CkMht_HtmlToMHTFile; external DLLName; function CkMht_HtmlToMHTFileAsync; external DLLName; function CkMht_IsUnlocked; external DLLName; procedure CkMht_RemoveCustomHeader; external DLLName; procedure CkMht_RestoreDefaults; external DLLName; function CkMht_SaveLastError; external DLLName; function CkMht_UnlockComponent; external DLLName; function CkMht_UnpackMHT; external DLLName; function CkMht_UnpackMHTString; external DLLName; end.
{Ä Fido Pascal Conference ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ PASCAL Ä Msg : 588 of 702 From : Bill Buchanan 1:2410/225.0 19 Apr 93 11:48 To : Robert Macdonald Subj : Music ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ -=> Quoting Robert Macdonald to All <=- RM> I'm just learning Pascal, and I was 1dering if it's possible 2 play RM> music in Pascal? If so... how? RM> C U L8r! Here's a little program that allows you to play the "PIANO" on your keyboard. No soundcard needed or anything like that. This may give you a small idea on how to create your own sounds ... Program Music; {by Judy Birmingham, 9/18/92} Uses Crt; Const {-------------------------------------------------------------------} {These values will vary by the song you choose} {I wish I could have made these variables instead of constants, but I seemed to be locked into using const, because they define array sizes in the types declared below.} TotalLinesInSong = 4; {Number of lines in song} MaxNotesInPhrase = 9; {Max number of notes in any line} BeatNote = 4; {Bottom number in Time Signature} {Handles cut time (2/2), 6/8 etc.} Tempo = 160; {Number of beats per minute} {-------------------------------------------------------------------} {Note frequencies} R = 0; {Rest = frequency of 0 : silence} C = 260; {Frequency of middle c } CC = 277; {Double letter indicates a sharp} D = 294; DD = 311; E = 330; F = 349; FF = 370; G = 392; GG = 415; A = 440; AA = 466; B = 494; {Note durations} Q = 1 * (BeatNote/4); {Quarter note} I = 0.5 * (BeatNote/4); {Eighth note} H = 2 * (BeatNote/4); {Half note} W = 4 * (BeatNote/4); {Whole note} S = 0.25 * (BeatNote/4); {Sixteenth note} DQ = 1.5 * (BeatNote/4); {Dotted quarter} DI = 0.75 * (BeatNote/4); {Dotted eighth} DH = 3 * (BeatNote/4); {Dotted half} DS = 0.375 * (BeatNote/4); {Dotted sixteenth} Beat = 60000/Tempo; {Duration of 1 beat in millisecs} Type IValues = Array [1..MaxNotesInPhrase] of Integer; RValues = Array [1..MaxNotesInPhrase] of Real; Phrase = Record Lyric : String; Notes : IValues; {array of note frequencies} Octave : IValues; {array of note octaves} Rhythm : RValues; {array of note durations} end; Song = Array [1..TotalLinesInSong] of Phrase; {Sample song} CONST RowRow : Song = ( (Lyric : 'Row Row Row Your Boat'; NOTES : (C,C,C,D,E,R,0,0,0); OCTAVE : (1,1,1,1,1,1,0,0,0); RHYTHM : (DQ,DQ,Q,I,Q,I,R,0,0) ), (Lyric : 'Gently down the stream'; NOTES : (E,D,E,F,G,R,0,0,0); OCTAVE : (1,1,1,1,1,1,0,0,0); RHYTHM : (Q,I,Q,I,DQ,DQ,0,0,0) ), (Lyric : 'Merrily merrily merrily merrily'; NOTES : (C,C,G,G,E,E,C,C,0 ); OCTAVE : (2,2,1,1,1,1,1,1,0 ); RHYTHM : (Q,I,Q,I,Q,I,Q,I,0 ) ), (Lyric : 'Life is but a dream.'; NOTES : (G,F,E,D,C,R,0,0,0 ); OCTAVE : (1,1,1,1,1,1,0,0,0 ); RHYTHM : (Q,I,Q,I,H,Q,0,0,0 ) )); Procedure LYRICS (THE_WORDS : string); begin Writeln (THE_WORDS); end; Procedure PLAYNOTE (NOTE, OCT: integer; DURATION : real); begin Sound (NOTE * OCT); Delay (Round(BEAT * DURATION)); NoSound; End; Procedure PLAYPHRASE (N : integer; NOTES, OCTAVE : IValues; RHYTHM : RValues) ; Var INDEX : Integer; Begin For INDEX := 1 to N do PLAYNOTE (NOTES[INDEX], OCTAVE[INDEX], RHYTHM[INDEX]); End; Procedure PLAYSONG (Title : String; Tune : Song); Var Counter : Integer; begin ClrScr; GotoXY(11,3); Writeln (Title); Window (10,5,70,19); ClrScr; For counter := 1 to TotalLinesInSong do begin LYRICS(Tune[counter].Lyric); PLAYPHRASE(MaxNotesInPhrase,Tune[counter].Notes, Tune[counter].Octave, Tune[counter].Rhythm); end; end; BEGIN ClrScr; PlaySong ('"Row Row Row Your Boat "', RowRow); END. ... Dyslexic atheists don't believe in Dog. --- Blue Wave/QBBS v2.12 [NR] * Origin: Screen Magic -Rockwood, MI- (1:2410/225.0)
{ WORK IN PROGRESS! DO NOT USE ON REAL PLUGINS! Only for Fallout 3 and New Vegas. Script tries to undelete and disable navmeshes since they can't be handled like other UDR references. We need a very clever modder to finish it. } unit UserScript; var UndeletedCount: integer; function Process(e: IInterface): integer; var vertices, v, f, entry: IInterface; navi, nvmis, nvmi: IInterface; i: integer; begin Result := 0; if not (GetIsEditable(e) and GetIsDeleted(e)) then Exit; if Signature(e) <> 'NAVM' then Exit; AddMessage('Undeleting: ' + Name(e)); // Find NVMI entry in NAVI for undeleted mesh f := GetFile(e); if not Assigned(f) then Exit; navi := GroupBySignature(f, 'NAVI'); if not Assigned(navi) then begin AddMessage('No NAVI group found'); Exit; end; // NAVI group always has only 1 record if ElementCount(navi) = 1 then begin navi := ElementByIndex(navi, 0); // get master NAVI record because NAVI record in plugin doesn't have NVMI for deleted navmesh navi := Master(navi); end else begin AddMessage('NAVI group must have 1 record'); Exit; end; if not Assigned(navi) then begin AddMessage('No master NAVI record found'); Exit; end; nvmis := ElementByName(navi, 'Navigation Map Infos'); if not Assigned(nvmis) then Exit; for i := 0 to ElementCount(nvmis) - 1 do begin entry := ElementByIndex(nvmis, i); if GetElementNativeValues(entry, 'Navigation Mesh') = FormID(e) then begin nvmi := entry; Break; end; end; if Assigned(nvmi) then begin AddMessage('Found NVMI subrecord in NAVI'); end; // now we need to do something here with NAVI... // and probably NVPP for Skyrim etc. // uncomment if you don't want to undelete navmesh Exit; // Navmesh undelete and disable SetIsDeleted(e, True); SetIsDeleted(e, False); SetIsInitiallyDisabled(e, True); // place navmesh below the ground (change Z on all vertices) // currently only for Skyrim if wbGameMode = gmTES5 then begin vertices := ElementByPath(e, 'NVNM - Geometry\Vertices'); for i := 0 to ElementCount(vertices) - 1 do SetElementNativeValues(ElementByIndex(vertices, v), 'Z', -30000); end; Inc(UndeletedCount); end; function Finalize: integer; begin AddMessage('Undeleted navmeshes: ' + IntToStr(UndeletedCount)); end; end.
{ WARNING: This code is old, and some data structures have changed out from * under it. The source code is here to preserve it, but it is currently not * being built. } { Type 1 OCTREE_DATA aggregate object. * * This object shows the octree voxel structure, not the data in the octree. * The octree must be a previously created TYPE1_OCTREE object. } module type1_octree_data; define type1_octree_data_class_make; %include 'ray_type1_2.ins.pas'; %include 'type1_octree.ins.pas'; octdat_data_p_t = ^octdat_data_t; octdat_data_t = record {data record pointed to by object block} shader: ray_shader_t; {pointer to shader entry point} liparm_p: type1_liparm_p_t; {pointer to light source parameters block} visprop_p: type1_visprop_p_t; {pointer to visual properties block} oct_data_p: oct_data_p_t; {pointer to OCTREE object's data} box_size: real; {0 to 1 relative displayed voxel size} box_gap: real; {gap from displayed box to voxel edge} show_objects: boolean; {objects in octree also displayed if TRUE} end; priv_hit_info_p_t = ^priv_hit_info_t; priv_hit_info_t = record {our expanded hit info data} base: type1_hit_info_t; {standard hit into data} point: vect_3d_t; {intersection point} unorm: vect_3d_t; {unit normal at intersect point} end; { ******************************************************************************** * * Local subroutine TYPE1_OCTREE_VERSION (VERSION) * * Return version information obout this class of objects. } procedure type1_octree_data_version ( {return version information about object} out version: ray_object_version_t); {returned version information} val_param; begin version.year := 1987; version.month := 12; version.day := 27; version.hour := 14; version.minute := 45; version.second := 0; version.version := 0; version.name := string_v('OCTREE_DATA'); version.aggregate := false; end; { ******************************************************************************** * * Local subroutine TYPE1_OCTREE_CREATE (OBJECT, CREA, STAT) * * Fill in the new object in OBJECT. CREA is the user data parameters for this * object. STAT is the standard system error return code. } procedure type1_octree_data_create ( {create new primitive with custom data} in out object: ray_object_t; {object to be filled in} in var crea: univ ray_crea_data_t; {specific build-time data for this object} out stat: sys_err_t); {completion status code} val_param; var crea_p: type1_octree_data_crea_data_p_t; {pointer to creation data, our format} data_p: octdat_data_p_t; {pointer to internal object data} begin sys_error_none (stat); {init to no error} crea_p := univ_ptr(addr(crea)); {get pointer to creation data, our format} util_mem_grab ( {create new data block for this object} sizeof(data_p^), ray_mem_p^, false, data_p); data_p^.shader := crea_p^.shader; {copy pointer to shader to use} data_p^.liparm_p := crea_p^.liparm_p; {copy pointer to light source block} data_p^.visprop_p := crea_p^.visprop_p; {copy pointer to visual properties block} data_p^.oct_data_p := {get pointer to OCTREE object's data block} oct_data_p_t(crea_p^.oct_obj_p^.data_p); data_p^.box_size := crea_p^.box_size; {copy relative size of displayed voxel} data_p^.box_gap := (1.0-crea_p^.box_size)/2.0; {make voxel edge to box size gap} data_p^.show_objects := crea_p^.show_objects; {copy show objects in octree flag} object.data_p := data_p; {set data pointer in object block} end; { ******************************************************************************** * * Local function TYPE1_OCTREE_INTERSECT_CHECK ( * GRAY, OBJECT, GPARMS, HIT_INFO, SHADER) * * Check ray and object for an intersection. If so, return TRUE, and save any * partial results in HIT_INFO. These partial results may be used later to get * detailed information about the intersection geometry. } function type1_octree_data_intersect_check ( {check for ray/object intersection} in out gray: univ ray_desc_t; {input ray descriptor} in object: ray_object_t; {input object to intersect ray with} in gparms: univ ray_object_parms_t; {run time obj-specific parameters} out hit_info: ray_hit_info_t; {handle to routines and data to get hit color} out shader: ray_shader_t) {pointer to shader to resolve color here} :boolean; {TRUE if ray does hit object} val_param; const min_voxel_size = 4.768372E-7; {dimension of minimum LSB sized voxel} mic = 4.76837E-7; {min representable coor in 0.0 to 1.0 space} mac = 1.0 - mic; {max representable coor in 0.0 to 1.0 space} cached_checks = 4; {previously checked objects list max size} type icoor_t = record case integer of {integer XYZ coordinate with array overlay} 1:( {individually named fields} x, y, z: sys_int_machine_t); 2:( {overlay array of algorithmic indexing} coor: array[1..3] of sys_int_machine_t); end; var ray_p: type1_ray_p_t; {pointer to ray, our format} parms_p: type1_object_parms_p_t; {pointer to runtime parameters, our format} data_p: octdat_data_p_t; {pointer to object's specific data area} p: vect3_t; {ray point in 0 to 1 space} v: vect3_t; {non-uint ray vector in 0 to 1 space} rv: vect3_t; {reciprocal of V, =1E20 if V=0} maj, min1, min2: integer32; {1-3 subscripts for major and minor axies} slope: vect3_t; {slope of each axis with respect to major axis} rslope: vect3_t; {reciprocal of SLOPE, above} max_odist: real; {max octree space ray distance to hit point} dist_m, dist_b: real; {for equation RAY_DIST = OCT_DIST*DIST_M+DIST_B} dmaj: real; {major axis delta} dmin: real; {minor axis delta} p1, p2: vect3_t; {scratch points} level: integer32; {nesting level of current node, top = 0} bit_mask: integer32; {mask for picking off decision bit at this lev} coor_mask: integer32; {masks in relevant adr bits for this level} icoor: icoor_t; {32 bit integer XYZ coordinate} vp: node_p_t; {pointer to current voxel} i, j: integer32; {loop counters and scratch integers} box: ray_box_t; {paralellpiped for voxel intersection checks} box_coor: array[0..1] of vect_3d_t; {possible box corner points} newp: node_p_t; {pointer to new subdivided voxel} obj_pp: ^ray_object_p_t; {adr of next obj pnt in scanning voxel list} vlnp: node_p_t; {pointer to curr node in scanning voxel list} nleft: integer32; {obj pointers left this node in scanning list} new_left: integer32; {num obj pointers left in node being built} n_new: integer32; {total number of objects in voxel being built} new_pp: ^ray_object_p_t; {adr of next obj pointer in node being built} nnewp: node_p_t; {pointer to node being built} here: boolean; {flag indicating ray can hit object in box} enclosed: boolean; {flag indicating object completely encloses box} hit: boolean; {the ray hit an object} parms: type1_object_parms_t; {parameters to pass to subordinate objects} old_mem: integer32; {MEM index before any object hits} new_mem: integer32; {MEM index after last object hit} sz: real; {used for size of current voxel} last_checks: {cached object pointers of recent misses} array[1..cached_checks] of ray_object_p_t; n_cached: integer32; {number of object pointers in LAST_CHECKS array} next_cache: integer32; {LAST_checks index of where to put next obj pnt} visprop_p: type1_visprop_p_t; {pointer to local customized visprop block} dist: real; {scratch distance} d1, d2, d3, d4: real; {ray distances to intersect points} hit_axis: integer32; {axis perpendicular to box plane that got hit} hit_geom_p: priv_hit_info_p_t; {pointer to hit geom block in MEM array} label got_p, new_coor, new_voxel, leaf_node, subdivide_voxel, trace_voxel, next_obj, next_coor, no_hit, not_hit_box, skip_objects, leave; begin ray_p := univ_ptr(addr(gray)); {make pointer to ray, our format} data_p := octdat_data_p_t(object.data_p); {make pointer to object's data area} parms_p := univ_ptr(addr(gparms)); {make pointer to runtime parameters, our format} with {set up abbreviations} data_p^:dd, data_p^.oct_data_p^:d do begin { * Abbreviations: * * DD - Specific data block for this object * D - Specidic data block for OCTREE object * * Now transform the ray into the (0,0,0) to (1,1,1) octree space. } p.x := (ray_p^.point.x + ray_p^.vect.x*ray_p^.min_dist - d.origin.x)*d.recip_size.x; p.y := (ray_p^.point.y + ray_p^.vect.y*ray_p^.min_dist - d.origin.y)*d.recip_size.y; p.z := (ray_p^.point.z + ray_p^.vect.z*ray_p^.min_dist - d.origin.z)*d.recip_size.z; v.x := ray_p^.vect.x*d.recip_size.x; {transform ray vector to our space (not unity)} v.y := ray_p^.vect.y*d.recip_size.y; v.z := ray_p^.vect.z*d.recip_size.z; dist_m := 1.0/sqrt( {make octree to ray space ray length factor} sqr(v.x) + sqr(v.y) + sqr(v.z)); v.x := v.x*dist_m; {make V a unit vector} v.y := v.y*dist_m; v.z := v.z*dist_m; if abs(v.x) > 1.0E-10 {make reciprocal of V used for voxel stepping} then rv.x := 1.0/v.x else rv.x := 1.0E20; if abs(v.y) > 1.0E-10 then rv.y := 1.0/v.y else rv.y := 1.0E20; if abs(v.z) > 1.0E-10 then rv.z := 1.0/v.z else rv.z := 1.0E20; { * The ray point and ray vector have been transformed into a space in which the * octree occupies (0,0,0) to (1,1,1). The transformed ray point is in P, and the * transformed ray vector is in V. V is a unit vector. This transformed space * is only used to decide which voxels the ray hits. The original ray is passed * directly to the subordinate object intersection routines. * * Start by determining which is the major axis and the two minor axies. } if abs(v.x) > abs(v.y) {sort based on X and Y alone} then begin maj := 1; min2 := 2; end else begin maj := 2; min2 := 1; end ; if abs(v.z) > abs(v.coor[maj]) {sort biggest against Z} then maj := 3; if abs(v.z) < abs(v.coor[min2]) {sort smallest against Z} then min2 := 3; min1 := 6 - maj - min2; {middle size must be the one left over} { * MAJ, MIN1, MIN2 are indicies for the most major to the most minor axies. } slope.coor[maj] := 1.0; {find slopes with respect to major axis} slope.coor[min1] := v.coor[min1]/v.coor[maj]; slope.coor[min2] := v.coor[min2]/v.coor[maj]; if (p.x >= mic) and (p.x <= mac) {is ray point inside octree ?} and (p.y >= mic) and (p.y <= mac) and (p.z >= mic) and (p.z <= mac) then begin {start point is just the ray point} dist_b := 0.0; {ray space distance from ray point to point P} goto got_p; {point P is all set} end; { * The ray start point is not inside the octree. Make points P1 and P2 which are * the intersection points between the ray and the front and back planes perpendicular * to the major axis. P1 and P2 are clipped to the ray starting point. } if (p.coor[maj] < mic) and (v.coor[maj] < 0.0) {start behind and heading away ?} then goto no_hit; if (p.coor[maj] > mac) and (v.coor[maj] > 0.0) {start in front and heading more so ?} then goto no_hit; if ((p.coor[maj] < mic) and (v.coor[maj] > 0.0)) {intersecting MAJ=MIC plane ?} or ((p.coor[maj] > mic) and (v.coor[maj] < 0.0)) then begin {the ray hits the MAJ=MIC plane} dmaj := mic - p.coor[maj]; {major axis distance to plane} p1.coor[maj] := mic; {find intersect point with MAJ=MIC plane} p1.coor[min1] := p.coor[min1] + dmaj*slope.coor[min1]; p1.coor[min2] := p.coor[min2] + dmaj*slope.coor[min2]; end else begin {ray does not hit the MAJ=MIC plane} p1 := p; {ray start is the MAJ minimum point} end ; {P1 set to major axis minimum point} if ((p.coor[maj] > mac) and (v.coor[maj] < 0.0)) {intersecting MAJ=MAC plane ?} or ((p.coor[maj] < mac) and (v.coor[maj] > 0.0)) then begin {ray hits the MAJ=MAC plane} dmaj := mac - p.coor[maj]; {major axis distance to plane} p2.coor[maj] := mac; {find intersect point with MAJ=MAC plane} p2.coor[min1] := p.coor[min1] + dmaj*slope.coor[min1]; p2.coor[min2] := p.coor[min2] + dmaj*slope.coor[min2]; end else begin {ray does not hit the MAJ=MAC plane} p2 := p; {ray start is the MAJ maximum point} end ; {P2 set to major axis maximum point} { * The line segment P1 to P2 is the segment of the ray passing thru the major axis * MIC to MAC slice. P1 to P2 are in order of increasing major axis. Now clip the * line segment against the MIN1 and MIN2 MIC to MAC slices. The resulting line * segment is the intersection of the ray and the outside of the octree. } if slope.coor[min1] >= 0.0 {check P1-->P2 direction relative to MIN1 axis} then begin {P1 --> P2 goes along increasing MIN1} if p1.coor[min1] > mac then goto no_hit; {ray starts past MIN1 slice ?} if p2.coor[min1] < mic then goto no_hit; {ray ends before MIN1 slice ?} if p1.coor[min1] < mic then begin {ray starts before hitting MIN1 slice ?} dmaj := {major axis delta from P1 to MIN1=MIC} (mic - p.coor[min1])/slope.coor[min1]; p1.coor[maj] := p.coor[maj] + dmaj; {P1-->P2 intersect point with MIN1=MIC} p1.coor[min1] := mic; p1.coor[min2] := p.coor[min2] + dmaj*slope.coor[min2]; end; {done adjusting P1 to MIN1 slice} if p2.coor[min1] > mac then begin {need to adjust P2 coordinate ?} dmaj := {major axis delta from P1 to MIN1=MAC} (mac - p.coor[min1])/slope.coor[min1]; p2.coor[maj] := p.coor[maj] + dmaj; {P1-->P2 intersect point with MIN1=MAC} p2.coor[min1] := mac; p2.coor[min2] := p.coor[min2] + dmaj*slope.coor[min2]; end; {done adjusting P2 to MIN1 slice} end else begin {P2 --> P1 goes along decreasing MIN1} if p2.coor[min1] > mac then goto no_hit; {ray starts past MIN1 slice ?} if p1.coor[min1] < mic then goto no_hit; {ray ends before MIN1 slice ?} if p2.coor[min1] < mic then begin {ray starts before hitting MIN1 slice ?} dmaj := {major axis delta from P2 to MIN1=MIC} (mic - p.coor[min1])/slope.coor[min1]; p2.coor[maj] := p.coor[maj] + dmaj; {P2-->P1 intersect point with MIN1=MIC} p2.coor[min1] := mic; p2.coor[min2] := p.coor[min2] + dmaj*slope.coor[min2]; end; {done adjusting P2 to MIN1 slice} if p1.coor[min1] > mac then begin {need to adjust P1 coordinate ?} dmaj := {major axis delta from P2 to MIN1=MAC} (mac - p.coor[min1])/slope.coor[min1]; p1.coor[maj] := p.coor[maj] + dmaj; {P2-->P1 intersect point with MIN1=MAC} p1.coor[min1] := mac; p1.coor[min2] := p.coor[min2] + dmaj*slope.coor[min2]; end; {done adjusting P1 to MIN1 slice} end ; {done clipping segment to MIN1 slice} if slope.coor[min2] >= 0.0 {check P1-->P2 direction relative to MIN2 axis} then begin {P1 --> P2 goes along increasing MIN2} if p1.coor[min2] > mac then goto no_hit; {ray starts past MIN2 slice ?} if p2.coor[min2] < mic then goto no_hit; {ray ends before MIN2 slice ?} if p1.coor[min2] < mic then begin {ray starts before hitting MIN2 slice ?} dmaj := {major axis delta from P1 to MIN2=MIC} (mic - p.coor[min2])/slope.coor[min2]; p1.coor[maj] := p.coor[maj] + dmaj; {P1-->P2 intersect point with MIN2=MIC} p1.coor[min2] := mic; p1.coor[min1] := p.coor[min1] + dmaj*slope.coor[min1]; end; {done adjusting P1 to MIN2 slice} if p2.coor[min2] > mac then begin {need to adjust P2 coordinate ?} dmaj := {major axis delta from P1 to MIN2=MAC} (mac - p.coor[min2])/slope.coor[min2]; p2.coor[maj] := p.coor[maj] + dmaj; {P1-->P2 intersect point with MIN2=MAC} p2.coor[min2] := mac; p2.coor[min1] := p.coor[min1] + dmaj*slope.coor[min1]; end; {done adjusting P2 to MIN2 slice} end else begin {P2 --> P1 goes along decreasing MIN2} if p2.coor[min2] > mac then goto no_hit; {ray starts past MIN2 slice ?} if p1.coor[min2] < mic then goto no_hit; {ray ends before MIN2 slice ?} if p2.coor[min2] < mic then begin {ray starts before hitting MIN2 slice ?} dmaj := {major axis delta from P2 to MIN2=MIC} (mic - p.coor[min2])/slope.coor[min2]; p2.coor[maj] := p.coor[maj] + dmaj; {P2-->P1 intersect point with MIN2=MIC} p2.coor[min2] := mic; p2.coor[min1] := p.coor[min1] + dmaj*slope.coor[min1]; end; {done adjusting P2 to MIN2 slice} if p1.coor[min2] > mac then begin {need to adjust P1 coordinate ?} dmaj := {major axis delta from P2 to MIN2=MAC} (mac - p.coor[min2])/slope.coor[min2]; p1.coor[maj] := p.coor[maj] + dmaj; {P2-->P1 intersect point with MIN2=MAC} p1.coor[min2] := mac; p1.coor[min1] := p.coor[min1] + dmaj*slope.coor[min1]; end; {done adjusting P1 to MIN2 slice} end ; {done clipping segment to MIN2 slice} { * The line segment P1 to P2 is the part of the ray that intersects the outer box * of the octree. P1 to P2 is in order of increasing major axis. Now set P to the * ray start point inside the octree. } if v.coor[maj] >= 0.0 {check MAJ direction with respect to ray dir} then begin {ray is in increasing MAJ direction} p := p1; end else begin {ray is in decreasing MAJ direction} p := p2; end ; dist_b := sqrt( {ray space distance from ray point to point P} sqr(p.x*d.size.x + d.origin.x - ray_p^.point.x) + sqr(p.y*d.size.y + d.origin.y - ray_p^.point.y) + sqr(p.z*d.size.z + d.origin.z - ray_p^.point.z) ); { * P is the first point along the ray that is also inside the octree. P is in the * octree (0,0,0) to (1,1,1) space. } got_p: {jump here if P started out inside octree} if abs(slope.coor[min1]) > mic {check for slope useable or not} then begin {slope is big enough to be useable} rslope.coor[min1] := 1.0/slope.coor[min1]; end else begin {slope is too small to use inverse} slope.coor[min1] := 0.0; {make it zero so it doesn't cause trouble} end ; {done making MIN1 reciprocal slope} if abs(slope.coor[min2]) > mic {check for slope useable or not} then begin {slope is big enough to be useable} rslope.coor[min2] := 1.0/slope.coor[min2]; end else begin {slope is too small to use inverse} slope.coor[min2] := 0.0; {make it zero so it doesn't cause trouble} end ; {done making MIN2 reciprocal slope} p1 := p; {save ray starting point inside octree} if dd.shader = nil {resolve shader pointer inheritance} then parms.shader := parms_p^.shader else parms.shader := dd.shader; if dd.liparm_p = nil {resolve LIPARM pointer inheritance} then parms.liparm_p := parms_p^.liparm_p else parms.liparm_p := dd.liparm_p; if dd.visprop_p = nil {resolve VISPROP pointer inheritance} then parms.visprop_p := parms_p^.visprop_p else parms.visprop_p := dd.visprop_p; n_cached := 0; {init checked objects cache to empty} next_cache := 1; {init where to cache next checked obj pointer} hit := false; {init to ray not hit anything in octree} old_mem := next_mem; {save MEM index before any obj save blocks} { * Point P1 has been set to the first point along the ray inside the octree. This * will be used later to recompute subsequent points along the ray_p^. * * Point P contains the floating point coordinates at which to check for objects * to intersect the ray with. First convert these to integer coordinates that can * be used to index down the octree to the specific leaf node voxel that contains * this point. P will be converted to 32 bit integer coordinates, where the octree * 0 to 1 space will map to 0 to 32767. Therefore, if the high 16 bits of the * 32 bit coordinate are non-zero, then this coordinate is outside the octree. * If the coordinate is outside the octree, then all possible voxels have already * been checked, and the ray has hit nothing. } icoor.x := trunc(p.x*32768.0); {make integer X coor} icoor.y := trunc(p.y*32768.0); {make integer Y coor} icoor.z := trunc(p.z*32768.0); {make integer Z coor} new_coor: {jump back here to check voxel at each new coor} vp := d.top_node_p; {init current node to top level node} bit_mask := 16#8000; {init bit mask to highest address bit} coor_mask := 16#FFFF8000; {init mask to no significant address bits} level := 0; {init to at top level node} new_voxel: {jump here to process the voxel at adr VP} if vp^.n_obj >= 0 then goto leaf_node; {this voxel is a leaf node ?} bit_mask := rshft(bit_mask, 1); {position mask to pick off proper decision bits} if bit_mask & icoor.x <> 0 {set I to index for proper child voxel} then i := 1 else i := 0; if bit_mask & icoor.y <> 0 then i := i+2; if bit_mask & icoor.z <> 0 then i := i+4; vp := vp^.node_p[i]; {get pointer to child voxel containing coor} coor_mask := rshft(coor_mask, 1); {update mask of significant coordinate bits} level := level+1; {indicate we are one more level down the tree} if vp = nil then goto next_coor; {new nested node does not exist ?} goto new_voxel; {back and process this new voxel} { * VP is pointing to the leaf node containing the coordinate in ICOOR. Check whether * the voxel needs to be subdivided. If so, subdivide it and then jump back to * NEW_VOXEL to find the voxel at the next level down. } leaf_node: if level >= d.max_gen then goto trace_voxel; {already divided max allowed levels ?} if level < d.min_gen then goto subdivide_voxel; {not deeper than min level ?} if vp^.misses < d.min_miss then goto trace_voxel; {not enough rays missed here ?} if vp^.hits > vp^.misses then goto trace_voxel; {more than half the rays hit here ?} { * This voxel needs to be subdivided. } subdivide_voxel: { * VP is pointing at a the leaf node voxel that the ray is supposed to be traced * thru. } trace_voxel: {jump here to trace ray thru voxel at VP} sz := bit_mask*3.051758E-5; {make full width of this voxel in octree space} box.edge[1].width := dd.box_size*sz*d.size.x; {make length of box sides} box.edge[2].width := dd.box_size*sz*d.size.y; box.edge[3].width := dd.box_size*sz*d.size.z; box.point.x := ((coor_mask & icoor.x)*3.051758E-5 + sz*dd.box_gap)*d.size.x + d.origin.x; box.point.y := ((coor_mask & icoor.y)*3.051758E-5 + sz*dd.box_gap)*d.size.y + d.origin.y; box.point.z := ((coor_mask & icoor.z)*3.051758E-5 + sz*dd.box_gap)*d.size.z + d.origin.z; p2.x := box.point.x - ray_p^.point.x; {make vector from box corner to ray} p2.y := box.point.y - ray_p^.point.y; p2.z := box.point.z - ray_p^.point.z; dist := p2.coor[maj]/ray_p^.vect.coor[maj]; {MAJ ray distance to box corner MAJ plane} if ray_p^.vect.coor[maj] >= 0.0 {check ray direction along MAJ axis} then begin {ray is heading towards positive MAJ} d1 := dist; {ray distance to first MAJ plane} d2 := dist + box.edge[maj].width/ray_p^.vect.coor[maj]; {ray dist to 2nd MAJ plane} end else begin {ray is heading towards negative MAJ} d1 := dist + box.edge[maj].width/ray_p^.vect.coor[maj]; {ray dist to 1st MAJ plane} d2 := dist; {ray distance to second MAJ plane} end ; hit_axis := maj; {D1 currenlty represents hit with MAJ axis} { * D1 and D2 are now the distance along the ray to the two planes at the box faces * perpendicular to the MAJ axis. Now succesively clip this line segment to the * MIN1 and MIN2 slices. If anything is left over, then the hit point is at ray * distance D1. HIT_AXIS is kept current to indicate which axis plane clip D1 * represents. } if abs(ray_p^.vect.coor[min1]) > 1.0e-6 then begin {ray not paralell to this axis ?} if ray_p^.vect.coor[min1] >= 0.0 {check ray direction along MIN1 axis} then begin {ray is heading in positive MIN1 direction} d3 := p2.coor[min1]/ray_p^.vect.coor[min1]; d4 := d3 + box.edge[min1].width/ray_p^.vect.coor[min1]; end else begin {ray is heading in negative MIN1 direction} d4 := p2.coor[min1]/ray_p^.vect.coor[min1]; d3 := d4 + box.edge[min1].width/ray_p^.vect.coor[min1]; end ; if d3 > d1 then begin d1 := d3; hit_axis := min1; end; if d4 < d2 then d2 := d4; end; {done with ray not paralell to MIN1 plane} if abs(ray_p^.vect.coor[min2]) > 1.0e-6 then begin {ray not paralell to this axis ?} if ray_p^.vect.coor[min2] >= 0.0 {check ray direction along MIN2 axis} then begin {ray is heading in positive MIN2 direction} d3 := p2.coor[min2]/ray_p^.vect.coor[min2]; d4 := d3 + box.edge[min2].width/ray_p^.vect.coor[min2]; end else begin {ray is heading in negative MIN2 direction} d4 := p2.coor[min2]/ray_p^.vect.coor[min2]; d3 := d4 + box.edge[min2].width/ray_p^.vect.coor[min2]; end ; if d3 > d1 then begin d1 := d3; hit_axis := min2; end; if d4 < d2 then d2 := d4; end; {done with ray not paralell to MIN2 plane} if d1 > d2 then goto not_hit_box; {ray does not hit the voxel box at all ?} if (d1 < ray_p^.min_dist) or (d1 > ray_p^.max_dist) then goto not_hit_box; {hit point not inside legal interval} { * The ray has hit the box. } hit := true; {indicate that this ray hit something} ray_p^.max_dist := d1; {only closer hits are allowed from now on} hit_info.object_p := addr(object); {return handle to object that got hit} hit_info.distance := d1; {fill in ray distance to hit point} hit_info.enter := true; hit_geom_p := univ_ptr(addr(mem[next_mem])); {get pointer to hit geom block} next_mem := ((sizeof(priv_hit_info_t)+3) & 16#0FFFFFFFC) + next_mem; {allocate 4 byte chunks for HIT_GEOM block} visprop_p := univ_ptr(addr(mem[next_mem])); {allocate space for customized visprop block} next_mem := ((sizeof(type1_visprop_t)+3) & 16#0FFFFFFFC) + next_mem; {allocate 4 byte chunks for HIT_GEOM block} if next_mem > mem_block_size then begin {not enough room for HIT_GEOM block ?} writeln ('Insufficient space in array MEM (RAY_TYPE1_2.INS.PAS).'); sys_bomb; {save traceback info and abort} end; new_mem := next_mem; {save NEXT_MEM after this hit allocation} next_mem := old_mem; {restore MEM allocation to before this hit data} hit_info.shader_parms_p := {fill in pointer to hit geometry save area} ray_shader_parms_p_t(hit_geom_p); hit_geom_p^.base.liparm_p := parms.liparm_p; hit_geom_p^.base.visprop_p := visprop_p; hit_geom_p^.point.x := ray_p^.point.x + ray_p^.vect.x*d1; hit_geom_p^.point.y := ray_p^.point.y + ray_p^.vect.y*d1; hit_geom_p^.point.z := ray_p^.point.z + ray_p^.vect.z*d1; hit_geom_p^.unorm.x := 0.0; {init hit point normal vector} hit_geom_p^.unorm.y := 0.0; hit_geom_p^.unorm.z := 0.0; if ray_p^.vect.coor[hit_axis] > 0.0 then hit_geom_p^.unorm.coor[hit_axis] := -1.0 else hit_geom_p^.unorm.coor[hit_axis] := 1.0; shader := parms.shader; { * Fudge the visprop block to color code parameters at this voxel. } visprop_p^ := parms.visprop_p^; {make local copy of visprop block} sz := vp^.hits + vp^.misses; {total number of rays thru here} if sz > 0.0 {check for enough rays to form ratio} then begin {there was at least one ray thru this voxel} if vp^.hits = 0 {check for any hits at all} then begin {none of the rays thru here hit anything} visprop_p^.diff_col.red := 1.0; visprop_p^.diff_col.grn := 1.0; visprop_p^.diff_col.blu := 0.0; end else begin visprop_p^.diff_col.red := vp^.misses / sz; visprop_p^.diff_col.grn := vp^.hits / sz; visprop_p^.diff_col.blu := 0.5; end ; end else begin {there were no rays thru here} visprop_p^.diff_col.red := 0.2; visprop_p^.diff_col.grn := 0.2; visprop_p^.diff_col.blu := 1.0; end ; { * HIT is set to true if the ray hit the displayable voxel box. } not_hit_box: {jump here if ray not hit this voxel box} if not dd.show_objects then goto skip_objects; obj_pp := addr(vp^.obj_p[1]); {init address of next object pointer} vlnp := vp; {init current node pointer} nleft := obj_per_leaf_node; {init number of obj pointers left this node} for i := 1 to vp^.n_obj do begin {once for each object in this voxel} if nleft <= 0 then begin {no more object pointers in this node ?} vlnp := vlnp^.next_p; {make pointer to next node in chain} obj_pp := addr(vlnp^.ch_p[1]); {make adr of first object pointer in new node} nleft := obj_per_data_node; {init number of object pointers left this node} end; for j := 1 to n_cached do begin {check the cache of previous object checks} if obj_pp^ = last_checks[j] then goto next_obj; {already checked this object ?} end; {back and check next cached miss} checks := checks+1; {log one more ray/object intersect check} if obj_pp^^.routines_p^.intersect_check^ ( {run object's intersect check routine} ray, {the ray to intersect object with} obj_pp^^, {the object to intersect ray with} parms, {run time specific parameters} hit_info, {partial results returned} shader) {returned shader} then begin {the ray did hit the object} hit := true; {remember that the ray hit something} new_mem := next_mem; {save MEM index after this hit data} next_mem := old_mem; {restore mem index to before hit data} hits := hits+1; {log one more ray/object hit} end else begin {the ray did not hit the object} end ; last_checks[next_cache] := obj_pp^; {save pointer to object we just checked} next_cache := next_cache+1; {advance where to put next checked obj pointer} if next_cache > cached_checks {wrap NEXT_CACHE back to 1} then next_cache := 1; if n_cached < cached_checks {LAST_CHECKS not full yet ?} then n_cached := n_cached+1; {one more object in checked objects cache} next_obj: {skip to here to test next object in voxel} obj_pp := {make adr of next obj pointer in this node} univ_ptr(integer32(obj_pp)+sizeof(obj_pp^)); nleft := nleft-1; {one less object pointer left in this node} end; {back and process next object in this voxel} skip_objects: {jump to here to skip checking objects in voxel} { * We are done with the current voxel pointed to by VP. Update point P to a * coordinate inside the next voxel, and then jump back to NEW_COOR. P1 is the first * ray point inside the octree. } next_coor: {jump here to step to the next voxel} if v.coor[maj] >= 0.0 then begin {major axis is heading in positive direction} max_odist := {make octree ray dist to voxel MAJ limit} ( ((icoor.coor[maj] & coor_mask)+bit_mask)*3.051758E-5 - p1.coor[maj] + mic)*rv.coor[maj]; end else begin {major axis is heading in negative direction} max_odist := {make octree ray dist to voxel MAJ limit} ( (icoor.coor[maj] & coor_mask)*3.051758E-5 - p1.coor[maj] - mic)*rv.coor[maj]; end ; if v.coor[min1] >= 0.0 then begin {ray is heading in postive MIN1 direction} dmin := {make octree ray dist to voxel MIN1 limit} ( ((icoor.coor[min1] & coor_mask)+bit_mask)*3.051758E-5 - p1.coor[min1] + mic)*rv.coor[min1]; end else begin {ray is heading in negative MIN1 direction} dmin := {make octree ray dist to voxel MIN1 limit} ( (icoor.coor[min1] & coor_mask)*3.051758E-5 - p1.coor[min1] - mic)*rv.coor[min1]; end ; if dmin < max_odist then max_odist := dmin; {clip max dist in voxel to shortest} if v.coor[min2] >= 0.0 then begin {ray is heading in postive MIN2 direction} dmin := {make octree ray dist to voxel MIN2 limit} ( ((icoor.coor[min2] & coor_mask)+bit_mask)*3.051758E-5 - p1.coor[min2] + mic)*rv.coor[min2]; end else begin {ray is heading in negative MIN2 direction} dmin := {make octree ray dist to voxel MIN2 limit} ( (icoor.coor[min2] & coor_mask)*3.051758E-5 - p1.coor[min2] - mic)*rv.coor[min2]; end ; if dmin < max_odist then max_odist := dmin; {clip max dist in voxel to shortest} if (max_odist*dist_m+dist_b) >= ray_p^.max_dist then begin {ray ends in this voxel ?} goto leave; end; {done with ray ending in this voxel} icoor.x := round((p1.x + v.x*max_odist)*32768.0-0.5); icoor.y := round((p1.y + v.y*max_odist)*32768.0-0.5); icoor.z := round((p1.z + v.z*max_odist)*32768.0-0.5); if (icoor.x ! icoor.y ! icoor.z) & 16#FFFF8000 <> 0 then begin {outside octree ?} goto leave; end; goto new_coor; {point P is new coordinate to find voxel at} { * The ray has ended, or we checked all the voxels in its path. Now return to the * caller. } leave: if hit {all done with ray, did we hit anything ?} then begin {the ray hit something} next_mem := new_mem; {set next mem after hit data for this hit} type1_octree_data_intersect_check := true; {indicate we hit something} return; {return with hit} end else begin {the ray hit nothing} type1_octree_data_intersect_check := false; {indicate no hit for this ray} return; {return with no hit} end ; { * Jump here if the ray never intersected the outside box of the octree in the first * place. } no_hit: type1_octree_data_intersect_check := false; {indicate no hit} end; {done with abbreviations} end; { ******************************************************************************** * * Local subroutine TYPE1_OCTREE_INTERSECT_GEOM (HIT_INFO, FLAGS, GEOM_INFO) * * Return specific geometric information about a ray/object intersection in * GEOM_INFO. In HIT_INFO are any useful results left by the ray/object * intersection check calculation. FLAGS identifies what specific geometric * information is being requested. } procedure type1_octree_data_intersect_geom ( {return detailed geometry of intersection} in hit_info: ray_hit_info_t; {data saved by INTERSECT_CHECK} in flags: ray_geom_flags_t; {bit mask octree of what is being requested} out geom_info: ray_geom_info_t); {filled in geometric info} val_param; var hit_geom_p: priv_hit_info_p_t; {pointer to hit geometry block} begin geom_info.flags := []; {init what info we returned indicator} hit_geom_p := {pointer to HIT_GEOM block} priv_hit_info_p_t(hit_info.shader_parms_p); with {define abbreviations} hit_geom_p^:hit_geom {object specific hit geometry block} do begin { * Abbreviations: * HIT_GEOM - Our hit geometry block in the MEM array. * * Return intersection point coordinates. } if ray_geom_point in flags then begin geom_info.flags := {inidicate intersect point returned} geom_info.flags + [ray_geom_point]; geom_info.point := hit_geom.point; end; { * Return unit normal vector of surface at intersection point. } if ray_geom_unorm in flags then begin geom_info.flags := {indicate unit normal returned} geom_info.flags + [ray_geom_unorm]; geom_info.unorm := hit_geom.unorm; end; {done returning unit surface normal} end; {done using abbreviations} end; { ******************************************************************************** * * Subroutine TYPE1_OCTREE_DATA_CLASS_MAKE (POINTERS, SIZE) * * Fill in the routines block for this class of objects. } procedure type1_octree_data_class_make ( {fill in object class descriptor} out pointers: ray_object_routines_t); {block to fill in} val_param; begin pointers.create := addr(type1_octree_data_create); pointers.version := addr(type1_octree_data_version); pointers.intersect_check := addr(type1_octree_data_intersect_check); pointers.intersect_geom := addr(type1_octree_data_intersect_geom); pointers.intersect_box := addr(type1_octree_data_intersect_box); pointers.add_child := addr(type1_octree_data_add_child); end;
{******************************************************************************* * * * PentireFMX * * * * https://github.com/gmurt/PentireFMX * * * * Copyright 2020 Graham Murt * * * * email: graham@kernow-software.co.uk * * * * 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 forthe specific language governing permissions and * * limitations under the License. * * * *******************************************************************************} unit ksChatList; interface uses Classes, FMX.Controls, FMX.Objects, FMX.StdCtrls, FMX.Types, System.UITypes, ksInputList, FMX.Edit; type TksChatList = class; TksChatInsertPosition = (cipTop, cipBottom); TksChatToolbar = class(TToolBar) private FChatList: TksChatList; FEdit: TEdit; FButton: TButton; procedure DoClickSend(Sender: TObject); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; [ComponentPlatformsAttribute(pidAllPlatforms)] TksChatList = class(TControl) private FToolbar: TksChatToolbar; FInputList: TksInputList; FSenderName: string; FInsertPosition: TksChatInsertPosition; FTimeFormat: string; FDateFormat: string; procedure SetSenderName(const Value: string); procedure SetInsertPosition(const Value: TksChatInsertPosition); procedure SetDateFormat(const Value: string); procedure SetTimeFormat(const Value: string); protected public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure BeginUpdate; override; procedure EndUpdate; override; procedure AddDateSeperator(ADate: TDateTime); function AddChatItem(AID, ASender, AText: string; ADateTime: TDateTime; AAlign: TTextAlign; AColor, ATextColor: TAlphaColor; const AUse24HourTime: Boolean = True): TksInputListChatItem; published property Position; property Width; property Height; property SenderName: string read FSenderName write SetSenderName; property InsertPosition: TksChatInsertPosition read FInsertPosition write SetInsertPosition default cipBottom; property TimeFormat: string read FTimeFormat write SetTimeFormat; property DateFormat: string read FDateFormat write SetDateFormat; end; procedure Register; implementation uses System.UIConsts, Sysutils; procedure Register; begin RegisterComponents('Pentire FMX', [TksChatList]); end; { TksChatList } function TksChatList.AddChatItem(AID, ASender, AText: string; ADateTime: TDateTime; AAlign: TTextAlign; AColor, ATextColor: TAlphaColor; const AUse24HourTime: Boolean): TksInputListChatItem; begin Result := FInputList.Items.AddChatItem(AID, ASender, AText, ADateTime, AAlign, AColor, ATextColor); end; procedure TksChatList.AddDateSeperator(ADate: TDateTime); begin FInputList.Items.AddSeperator(FormatDateTime(FDateFormat, ADate)) end; procedure TksChatList.BeginUpdate; begin inherited; FInputList.BeginUpdate; end; constructor TksChatList.Create(AOwner: TComponent); begin inherited; FInputList := TksInputList.Create(Self); FToolbar := TksChatToolbar.Create(Self); Height := 400; Width := 300; FInputList.Stored := False; FToolbar.Stored := False; FInputList.BackgroundColor := claWhite; FInputList.ShowDividers := False; FToolbar.Align := TAlignLayout.Bottom; FInputList.Align := TAlignLayout.Client; AddObject(FToolbar); AddObject(FInputList); end; destructor TksChatList.Destroy; begin FInputList.DisposeOf; FToolbar.DisposeOf; inherited; end; procedure TksChatList.EndUpdate; begin FInputList.EndUpdate; inherited; end; procedure TksChatList.SetDateFormat(const Value: string); begin FDateFormat := Value; end; procedure TksChatList.SetInsertPosition(const Value: TksChatInsertPosition); begin FInsertPosition := Value; end; procedure TksChatList.SetSenderName(const Value: string); begin FSenderName := Value; end; procedure TksChatList.SetTimeFormat(const Value: string); begin FTimeFormat := Value; end; { TksChatToolbar } constructor TksChatToolbar.Create(AOwner: TComponent); begin inherited; FChatList := (AOwner as TksChatList); FEdit := TEdit.Create(Self); FButton := TButton.Create(Self); FEdit.Stored := False; FEdit.Align := TAlignLayout.Client; FButton.Stored := False; FButton.Align := TAlignLayout.Right; FButton.Text := 'SEND'; FButton.OnClick := DoClickSend; AddObject(FEdit); AddObject(FButton); end; destructor TksChatToolbar.Destroy; begin FEdit.DisposeOf; inherited; end; procedure TksChatToolbar.DoClickSend(Sender: TObject); begin FChatList.AddChatItem('', FChatList.SenderName, FEdit.Text, Now, TTextAlign.Trailing, claDodgerblue, claWhite, True); end; end.
unit sMemo; {$I sDefs.inc} {.$DEFINE LOGGED} interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, sConst, sCommonData {$IFDEF TNTUNICODE}, TntStdCtrls, TntClasses, TntSysUtils, TntActnList, TntControls{$ENDIF}, sDefaults, acSBUtils{$IFDEF LOGGED}, sDebugMsgs{$ENDIF}; type {$IFDEF TNTUNICODE} TsMemo = class(TTntMemo) {$ELSE} TsMemo = class(TMemo) {$ENDIF} {$IFNDEF NOTFORHELP} private FCommonData: TsCtrlSkinData; FDisabledKind: TsDisabledKind; FOnVScroll: TNotifyEvent; FOnScrollCaret: TNotifyEvent; FBoundLabel: TsBoundLabel; procedure SetDisabledKind(const Value: TsDisabledKind); public ListSW : TacScrollWnd; procedure AfterConstruction; override; constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Loaded; override; procedure WndProc (var Message: TMessage); override; published property Text; property CharCase; Property OnScrollCaret : TNotifyEvent read FOnScrollCaret write FOnScrollCaret; Property OnVScroll : TNotifyEvent read FOnVScroll write FOnVScroll; {$ENDIF} // NOTFORHELP property BoundLabel : TsBoundLabel read FBoundLabel write FBoundLabel; property SkinData : TsCtrlSkinData read FCommonData write FCommonData; property DisabledKind : TsDisabledKind read FDisabledKind write SetDisabledKind default DefDisabledKind; {$IFDEF TNTUNICODE} property SelText; property SelStart; property SelLength; {$ENDIF} end; implementation uses sVCLUtils, sMessages, sGraphUtils, sAlphaGraph, sSkinProps; { TsMemo } procedure TsMemo.AfterConstruction; begin inherited AfterConstruction; FCommonData.Loaded; end; constructor TsMemo.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := ControlStyle - [csOpaque]; FCommonData := TsCtrlSkinData.Create(Self, {$IFDEF DYNAMICCACHE} False {$ELSE} True {$ENDIF}); FCommonData.COC := COC_TsMemo; if FCommonData.SkinSection = '' then FCommonData.SkinSection := s_Edit; FDisabledKind := DefDisabledKind; FBoundLabel := TsBoundLabel.Create(Self, FCommonData); end; destructor TsMemo.Destroy; begin if ListSW <> nil then FreeAndNil(ListSW); FreeAndNil(FBoundLabel); if Assigned(FCommonData) then FreeAndNil(FCommonData); inherited Destroy; end; procedure TsMemo.Loaded; begin inherited Loaded; FCommonData.Loaded; RefreshEditScrolls(SkinData, ListSW); end; procedure TsMemo.SetDisabledKind(const Value: TsDisabledKind); begin if FDisabledKind <> Value then begin FDisabledKind := Value; FCommonData.Invalidate; end; end; procedure TsMemo.WndProc(var Message: TMessage); var PS : TPaintStruct; begin {$IFDEF LOGGED} AddToLog(Message); {$ENDIF} if (Message.Msg = CM_FONTCHANGED) and Showing and HandleAllocated then RedrawWindow(Handle, nil, 0, RDW_ERASE or RDW_INVALIDATE or RDW_FRAME); if Message.Msg = SM_ALPHACMD then case Message.WParamHi of AC_CTRLHANDLED : begin Message.Result := 1; Exit end; // AlphaSkins supported AC_GETAPPLICATION : begin Message.Result := longint(Application); Exit end; AC_SETNEWSKIN : if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) then begin CommonWndProc(Message, FCommonData); exit end; AC_REMOVESKIN : if LongWord(Message.LParam) = LongWord(SkinData.SkinManager) then begin if ListSW <> nil then FreeAndNil(ListSW); CommonWndProc(Message, FCommonData); RecreateWnd; exit end; AC_REFRESH : if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) then begin CommonWndProc(Message, FCommonData); RefreshEditScrolls(SkinData, ListSW); if HandleAllocated and Visible then RedrawWindow(Handle, nil, 0, RDW_INVALIDATE or RDW_ERASE or RDW_FRAME); exit end end; if not ControlIsReady(Self) or not FCommonData.Skinned then inherited else begin case Message.Msg of WM_PAINT : begin FCommonData.Updating := FCommonData.Updating; if FCommonData.Updating then begin // Exit if parent is not ready yet BeginPaint(Handle, PS); EndPaint(Handle, PS); Exit; end; inherited; exit; end; WM_SETFOCUS, WM_KILLFOCUS : begin inherited; Exit; end; end; CommonWndProc(Message, FCommonData); inherited; case Message.Msg of CM_SHOWINGCHANGED : RefreshEditScrolls(SkinData, ListSW); CM_VISIBLECHANGED, CM_ENABLEDCHANGED, WM_SETFONT : begin FCommonData.Invalidate; end; CM_TEXTCHANGED, CM_CHANGED : if Assigned(ListSW) then UpdateScrolls(ListSW, True); EM_SETSEL : if Assigned(FOnScrollCaret) then FOnScrollCaret(Self); WM_HSCROLL, WM_VSCROLL : begin if (Message.Msg = WM_VSCROLL) and Assigned(FOnVScroll) then begin FOnVScroll(Self); end; end; end; end; // Aligning of the bound label if Assigned(BoundLabel) and Assigned(BoundLabel.FtheLabel) then case Message.Msg of WM_SIZE, WM_WINDOWPOSCHANGED : begin BoundLabel.AlignLabel end; CM_VISIBLECHANGED : begin BoundLabel.FtheLabel.Visible := Visible; BoundLabel.AlignLabel end; CM_ENABLEDCHANGED : begin BoundLabel.FtheLabel.Enabled := Enabled or not (dkBlended in DisabledKind); BoundLabel.AlignLabel end; CM_BIDIMODECHANGED : begin BoundLabel.FtheLabel.BiDiMode := BiDiMode; BoundLabel.AlignLabel end; end; end; end.
unit UdmMakePartial; interface uses System.SysUtils, System.Classes, FireDAC.Comp.BatchMove, FireDAC.Comp.BatchMove.Text, FireDAC.Comp.BatchMove.DataSet, FireDAC.Comp.Client, Data.DB, System.DateUtils; type TDM_MakePartialFile = class(TDataModule) private { Private declarations } BMFileToMem: TFDBatchMove; BMTextReader: TFDBatchMoveTextReader; BMDataSetWriter: TFDBatchMoveDataSetWriter; MTToday: TFDMemTable; MTYesterday: TFDMemTable; BMDataSetReader: TFDBatchMoveDataSetReader; BMTextWriter: TFDBatchMoveTextWriter; Procedure CreateInfoForPartialLoad; Procedure LoadFilesYesterdayAndToday; Function CreateFormatFiles: Boolean; procedure SortInsumoPartial; public { Public declarations } NameFFormat : String; NameFYesterday : String; NameFToday : String; NameFPartial : String; FPartial : Text; FilesSeparator : Char; SortFieldsFull : String; SortFieldsPartial : String; ArrTime : Array[1..17] Of Integer; KontTime : Integer; StartTime : TDateTime; MsgError : String; Function initProcess(Out MsgProcess : String; GetFnombre_archivo_full_ayer, GetFnombre_archivo_full_hoy, GetFnombre_archivo_partial : String) : Boolean; Procedure MakePartialFile; Procedure InitTime; Procedure TakeTimeInSeconds; end; var DM_MakePartialFile: TDM_MakePartialFile; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} { TDM_MakePartialFile } Function TDM_MakePartialFile.CreateFormatFiles : Boolean; Var Path : String; FFmt : Text; Begin Result := True; Try Path := ExtractFilePath(NameFYesterday); System.Assign(FFmt,Path+NameFFormat); System.Rewrite(FFmt); WriteLn(FFmt,'TARJETA|ESTADO|CLASE|TIPO_DCTO|DOCUMENTO|NOMBRE|FECHA_VCTO|PINOFFSET|TIPO_CTA|CUENTA|INDPIN'); WriteLn(FFmt,'TARJETADE16POSIC|E|CC|TI|DOCUMENTODE16POS|NOMBREDE32POSICIONESNOMBREDE32PO|FECV|PINO|TC|CUENTADE10|P'); System.Close(FFmt); Path := ExtractFilePath(NameFToday); System.Assign(FFmt,Path+NameFFormat); System.Rewrite(FFmt); WriteLn(FFmt,'TARJETA|ESTADO|CLASE|TIPO_DCTO|DOCUMENTO|NOMBRE|FECHA_VCTO|PINOFFSET|TIPO_CTA|CUENTA|INDPIN'); WriteLn(FFmt,'TARJETADE16POSIC|E|CC|TI|DOCUMENTODE16POS|NOMBREDE32POSICIONESNOMBREDE32PO|FECV|PINO|TC|CUENTADE10|P'); System.Close(FFmt); Path := ExtractFilePath(NameFPartial); System.Assign(FFmt,Path+NameFFormat); System.Rewrite(FFmt); WriteLn(FFmt,'OPERACION|TARJETA|ESTADO|CLASE|TIPO_DCTO|DOCUMENTO|NOMBRE|FECHA_VCTO|PINOFFSET|TIPO_CTA|CUENTA|INDPIN'); WriteLn(FFmt,'O|TARJETADE16POSIC|E|CC|TI|DOCUMENTODE16POS|NOMBREDE32POSICIONESNOMBREDE32PO|FECV|PINO|TC|CUENTADE10|P'); System.Close(FFmt); Except On E : Exception do Begin MsgError := e.Message; Result := False; End End; End; function TDM_MakePartialFile.initProcess(Out MsgProcess : String; GetFnombre_archivo_full_ayer, GetFnombre_archivo_full_hoy, GetFnombre_archivo_partial : String) : Boolean; Var I : Integer; begin NameFFormat := 'Format.txt'; NameFYesterday := GetFnombre_archivo_full_ayer; NameFToday := GetFnombre_archivo_full_hoy; NameFPartial := GetFnombre_archivo_partial; FilesSeparator := '|'; SortFieldsFull := 'TARJETA;TIPO_CTA;CUENTA'; SortFieldsPartial := 'OPERACION;TARJETA;TIPO_CTA;CUENTA'; KontTime := 0; for I := 1 To Length(ArrTime) Do ArrTime[I] := -1; if CreateFormatFiles then Begin Result := True; End Else Begin MsgProcess := 'Error al crear archivos de Formato: '+MsgError; Result := False; End; end; procedure TDM_MakePartialFile.LoadFilesYesterdayAndToday; Var F : File; begin // Hace load archivo de ayer InitTime; if Not FileExists(NameFYesterday) then Begin System.Assign(F,NameFYesterday); System.ReWrite(F); System.Close(F); End; BMTextReader.FileName := ExtractFilePath(NameFYesterday) + NameFFormat; BMTextReader.DataDef.Separator := FilesSeparator; BMTextReader.DataDef.WithFieldNames := True; BMFileToMem.Reader := BMTextReader; BMDataSetWriter.DataSet := MTYesterday; BMDataSetWriter.Optimise := False; BMFileToMem.Writer := BMDataSetWriter; BMFileToMem.GuessFormat; BMFileToMem.Execute; BMTextReader.FileName := NameFYesterday; BMTextReader.DataDef.WithFieldNames := False; BMFileToMem.Execute; MTYesterday.First; MTYesterday.Delete; MTYesterday.First; while Not MTYesterday.Eof And (MTYesterday.Fields.Fields[0].AsString = '') do Begin // Porque cuando un archivo no tiene registros (tamaño 0) incluye un registro en nulo MTYesterday.Delete; MTYesterday.Next; End; TakeTimeInSeconds; InitTime; MTYesterday.IndexFieldNames := SortFieldsFull; TakeTimeInSeconds; // Hace load archivo de hoy InitTime; BMTextReader.FileName := ExtractFilePath(NameFToday) + NameFFormat; BMTextReader.DataDef.Separator := FilesSeparator; BMTextReader.DataDef.WithFieldNames := True; BMFileToMem.Reader := BMTextReader; BMDataSetWriter.DataSet := MTToday; BMDataSetWriter.Optimise := False; BMFileToMem.Writer := BMDataSetWriter; BMFileToMem.GuessFormat; BMFileToMem.Execute; BMTextReader.FileName := NameFToday; BMTextReader.DataDef.WithFieldNames := False; BMFileToMem.Execute; MTToday.First; MTToday.Delete; MTToday.First; while Not MTToday.Eof And (MTToday.Fields.Fields[0].AsString = '') do Begin // Porque cuando un archivo no tiene registros (tamaño 0) incluye un registro en nulo MTToday.Delete; MTToday.Next; End; TakeTimeInSeconds; InitTime; MTToday.IndexFieldNames := SortFieldsFull; TakeTimeInSeconds; end; procedure TDM_MakePartialFile.CreateInfoForPartialLoad; Var K1 : String; K2 : String; Function CompKeyField : ShortInt; Begin // 0 1 2 3 4 5 6 7 8 9 // TARJETA |ESTADO | CLASE | TIPO_DCTO | DOCUMENTO | NOMBRE | FECHA_VCTO | PINOFFSET | TIPO_CTA | CUENTA K1 := MTYesterday.Fields.Fields[0].AsString + // Tarjeta MTYesterday.Fields.Fields[8].AsString + // Tipo_Cta MTYesterday.Fields.Fields[9].AsString; // Cuenta K2 := MTToday.Fields.Fields[0].AsString + // Tarjeta MTToday.Fields.Fields[8].AsString + // Tipo_Cta MTToday.Fields.Fields[9].AsString; // Cuenta if K1 = K2 then Result := 0 Else if K1 < K2 then Result := -1 Else Result := 1; End; // 0 1 2 3 4 5 6 7 8 9 // TARJETA |ESTADO | CLASE | TIPO_DCTO | DOCUMENTO | NOMBRE | FECHA_VCTO | PINOFFSET | TIPO_CTA | CUENTA Var S1 : String; S2 : String; Function CompRecsOK : Boolean; Var I : Integer; Begin S1 := ''; for I := 0 to MTYesterday.FieldCount - 3 do S1 := S1 + MTYesterday.Fields.Fields[I].AsString; S1 := S1 + MTYesterday.Fields.Fields[MTYesterday.FieldCount-1].AsString; S2 := ''; for I := 0 to MTToday.FieldCount - 3 do S2 := S2 + MTToday.Fields.Fields[I].AsString; S2 := S2 + MTToday.Fields.Fields[MTToday.FieldCount-1].AsString; Result := S1 = S2; End; Var S : String; Procedure AppendRec(Today: Boolean;GetOpera : Char); Var I : Integer; Begin S := GetOpera + '|'; if Today then Begin for I := 0 to MTToday.FieldCount - 1 do S := S + MTToday.Fields.Fields[I].AsString + '|'; End Else Begin for I := 0 to MTYesterday.FieldCount - 1 do S := S + MTYesterday.Fields.Fields[I].AsString + '|'; End; WriteLn(FPartial,Copy(S,1,Length(S)-1)); End; begin // '1' es 'D' Delete // '2' es 'A' Adition // '3' es 'U' Update System.Assign(FPartial,NameFPartial+'.tmp'); System.ReWrite(FPartial); MTYesterday.First; MTToday.First; while Not MTYesterday.Eof And Not MTToday.EOF do Begin case CompKeyField of -1 : Begin AppendRec(False,'1');// Delete al Partial "D" Yesterday MTYesterday.Next; End; 0 : Begin if Not CompRecsOK then Begin AppendRec(True,'3');// Update al Partial "U" Today End; MTYesterday.Next; MTToday.Next; End; 1 : Begin AppendRec(True,'2');// Insert al Partial "A" Today MTToday.Next; End; end; End; if Not MTYesterday.Eof then Begin while Not MTYesterday.Eof do Begin AppendRec(False,'1');// Delete al Partial "D" Yesterday MTYesterday.Next; End; End; if Not MTToday.Eof then Begin while Not MTToday.Eof do Begin AppendRec(True,'2');// Insert al Partial "A" Today MTToday.Next; End; End; System.Close(FPartial); end; Procedure TDM_MakePartialFile.SortInsumoPartial; Procedure MakePartialFileSinceTMP; Var FDef : Text; S : String; I : Integer; Frst : Boolean; Begin System.Assign(FDef,NameFPartial); System.ReWrite(FDef); MTToday.First; while Not MTToday.Eof do Begin S := ''; case MTToday.Fields.Fields[0].AsString[1] of '1' : S := 'D' + '|'; '2' : S := 'A' + '|'; '3' : S := 'U' + '|'; end; for I := 1 to MTToday.FieldCount - 1 do S := S + MTToday.Fields.Fields[I].AsString + '|'; WriteLn(FDef,Copy(S,1,Length(S)-1)); MTToday.Next; End; System.Close(FDef); End; Begin InitTime; BMTextReader.FileName := ExtractFilePath(NameFPartial) + NameFFormat; BMTextReader.DataDef.Separator := FilesSeparator; BMTextReader.DataDef.WithFieldNames := True; BMFileToMem.Reader := BMTextReader; MTToday.Close; FreeAndNil(MTToday); MTToday := TFDMemTable.Create(Nil); BMDataSetWriter.DataSet := MTToday; BMDataSetWriter.Optimise := False; BMFileToMem.Writer := BMDataSetWriter; BMFileToMem.GuessFormat; BMFileToMem.Execute; BMTextReader.FileName := NameFPartial+'.tmp'; BMTextReader.DataDef.WithFieldNames := False; BMFileToMem.Execute; MTToday.First; MTToday.Delete; MTToday.First; while Not MTToday.Eof And (MTToday.Fields.Fields[0].AsString = '') do Begin // Porque cuando un archivo no tiene registros (tamaño 0) incluye un registro en nulo MTToday.Delete; MTToday.Next; End; //MTToday.IndexFieldNames := SortFieldsPartial; with MTToday.Indexes.Add do begin // Crea Índice Name := 'by_operation'; Fields := SortFieldsPartial; Active := True; end; MTToday.IndexName := 'by_operation'; // Activa el índice} MTToday.IndexesActive := True; MakePartialFileSinceTMP; DeleteFile(NameFPartial+'.tmp'); { BMDataSetReader.DataSet := MTToday; BMDataSetReader.Optimise := False; BMDataSetReader.Rewind := False; Pendiente averiguar cómo obtener la salida ordenada en un batchmove desde un MemTable con index y cómo modificar la salida de un campo en el archivo de texto. DeleteFile(NameFPartial); BMTextWriter.FileName := NameFPartial; BMTextWriter.DataDef.Separator := FilesSeparator; BMTextWriter.DataDef.Delimiter := #0; BMTextWriter.DataDef.WithFieldNames := False; BMFileToMem.Writer := BMTextWriter; BMFileToMem.Execute;} TakeTimeInSeconds; End; procedure TDM_MakePartialFile.MakePartialFile; begin // Crea componentes para utilización BMFileToMem := TFDBatchMove.Create(Nil); BMTextReader := TFDBatchMoveTextReader.Create(Nil); BMDataSetWriter := TFDBatchMoveDataSetWriter.Create(Nil); BMDataSetReader := TFDBatchMoveDataSetReader.Create(Nil); BMTextWriter := TFDBatchMoveTextWriter.Create(Nil); MTToday := TFDMemTable.Create(Nil); MTYesterday := TFDMemTable.Create(Nil); LoadFilesYesterdayAndToday; InitTime; CreateInfoForPartialLoad; TakeTimeInSeconds; SortInsumoPartial; // Libera componentes utilizados FreeAndNil(BMFileToMem ); FreeAndNil(BMTextReader ); FreeAndNil(BMDataSetWriter); FreeAndNil(BMDataSetReader); FreeAndNil(BMTextWriter); FreeAndNil(MTToday); FreeAndNil(MTYesterday); end; procedure TDM_MakePartialFile.InitTime; begin StartTime := Now; end; procedure TDM_MakePartialFile.TakeTimeInSeconds; begin If KontTime < Length(ArrTime) Then Begin Inc(KontTime); ArrTime[KontTime] := SecondsBetween(StartTime,Now); End; end; end.
{ ******************************************************************************* Title: T2Ti ERP Description: Controller para geração do arquivo Sped Contribuições The MIT License Copyright: Copyright (C) 2014 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 2.0 ******************************************************************************* } unit SpedContribuicoesController; interface uses Forms, Classes, SQLExpr, SysUtils, Generics.Collections, Controller, DBXJSON, DBXCommon, Biblioteca, ACBrEFDBlocos, Constantes, ACBrEPCBlocos; type TSpedContribuicoesController = class(TController) private class procedure GerarBloco0; class procedure GerarBlocoA; class procedure GerarBlocoC; class procedure GerarBlocoD; class procedure GerarBlocoF; class procedure GerarBlocoI; class procedure GerarBlocoM; class procedure GerarBloco1; class function GerarArquivoSpedContribuicoes: Boolean; protected public // consultar class function GerarSpedContribuicoes(pFiltro: String): String; end; implementation uses T2TiORM, UDataModule, EmpresaController, // VOs EmpresaVO, ContadorVO, UnidadeProdutoVO, ProdutoVO, EcfImpressoraVO, EcfNotaFiscalCabecalhoVO, NfeCupomFiscalReferenciadoVO, ViewSpedC321VO, ViewSpedC370VO, ViewSpedC390VO, ViewSpedC425VO, ViewSpedC490VO, EcfR02VO, EcfR03VO, EcfVendaCabecalhoVO, EcfVendaDetalheVO, FiscalApuracaoIcmsVO, ProdutoAlteracaoItemVO, ViewSpedNfeEmitenteVO, ViewSpedNfeDestinatarioVO, ViewSpedNfeItemVO, UnidadeConversaoVO, TributOperacaoFiscalVO, NfeTransporteVO, ViewSpedNfeDetalheVO, ViewSpedC190VO, ViewSpedC300VO, NfeCabecalhoVO; { TSpedContribuicoesController } var Empresa: TEmpresaVO; VersaoLeiaute, TipoEscrituracao, IdEmpresa, IdContador: Integer; DataInicial, DataFinal, Arquivo, FiltroLocal: String; {$REGION 'Infra'} class function TSpedContribuicoesController.GerarSpedContribuicoes(pFiltro: String): String; var ConteudoFiltro: TStringList; begin try ConteudoFiltro := TStringList.Create; Split('|', pFiltro, ConteudoFiltro); { 0 - Periodo Inicial 1 - Periodo Final 2 - Versao Leiaute 3 - Tipo Escrituracao 4 - IdEmpresa 5 - IdContador } DataInicial := ConteudoFiltro[0]; DataFinal := ConteudoFiltro[1]; VersaoLeiaute := StrToInt(ConteudoFiltro[2]); TipoEscrituracao := StrToInt(ConteudoFiltro[3]); IdEmpresa := StrToInt(ConteudoFiltro[4]); IdContador := StrToInt(ConteudoFiltro[5]); // FormatSettings.DecimalSeparator := ','; GerarArquivoSpedContribuicoes; Result := Arquivo; finally FreeAndNil(ConteudoFiltro); end; end; {$ENDREGION} {$REGION 'Geração Arquivo'} {$REGION 'BLOCO 0: ABERTURA, IDENTIFICAÇÃO E REFERÊNCIAS'} class procedure TSpedContribuicoesController.GerarBloco0; var Contador: TContadorVO; ListaProduto: TObjectList<TViewSpedNfeItemVO>; ListaEmitente: TObjectList<TViewSpedNfeEmitenteVO>; ListaDestinatario: TObjectList<TViewSpedNfeDestinatarioVO>; ListaUnidade: TObjectList<TUnidadeProdutoVO>; ListaProdutoAlterado: TObjectList<TProdutoAlteracaoItemVO>; ListaOperacaoFiscal: TObjectList<TTributOperacaoFiscalVO>; UnidadeConversao: TUnidadeConversaoVO; UnidadeProduto: TUnidadeProdutoVO; ListaParticipante: TStringList; ListaSiglaUnidade: TStringList; i: Integer; begin try Empresa := TEmpresaController.ConsultaObjeto('ID=' + IntToStr(IdEmpresa)); Contador := TT2TiORM.ConsultarUmObjeto<TContadorVO>('ID=' + IntToStr(IdContador), True); ListaEmitente := TT2TiORM.Consultar<TViewSpedNfeEmitenteVO>('ID in (select ID_FORNECEDOR from NFE_CABECALHO where DATA_HORA_EMISSAO BETWEEN ' + QuotedStr(DataInicial) + ' and ' + QuotedStr(DataFinal) + ')', '-1', False); ListaDestinatario := TT2TiORM.Consultar<TViewSpedNfeDestinatarioVO>('ID in (select ID_CLIENTE from NFE_CABECALHO where DATA_HORA_EMISSAO BETWEEN ' + QuotedStr(DataInicial) + ' and ' + QuotedStr(DataFinal) + ')', '-1', False); ListaProduto := TT2TiORM.Consultar<TViewSpedNfeItemVO>('ID in (select ID_PRODUTO from NFE_DETALHE JOIN NFE_CABECALHO ON NFE_DETALHE.ID_NFE_CABECALHO = NFE_CABECALHO.ID' + ' where NFE_CABECALHO.DATA_HORA_EMISSAO BETWEEN ' + QuotedStr(DataInicial) + ' and ' + QuotedStr(DataFinal) + ')', '-1', False); ListaProdutoAlterado := TT2TiORM.Consultar<TProdutoAlteracaoItemVO>('DATA_INICIAL BETWEEN ' + QuotedStr(DataInicial) + ' and ' + QuotedStr(DataFinal), '-1', False); ListaOperacaoFiscal := TT2TiORM.Consultar<TTributOperacaoFiscalVO>('ID>0', '-1', False); with FDataModule.ACBrSpedContribuicoes.Bloco_0 do begin // REGISTRO 0000: ABERTURA DO ARQUIVO DIGITAL E IDENTIFICAÇÃO DA PESSOA JURÍDICA with Registro0000New do begin COD_VER := TACBrVersaoLeiaute(VersaoLeiaute); TIPO_ESCRIT := TACBrTipoEscrit(TipoEscrituracao); //IND_SIT_ESP := indSitAbertura; NUM_REC_ANTERIOR := ''; //Número do Recibo da Escrituração anterior a ser retificada, utilizado quando TIPO_ESCRIT for igual a 1 NOME := Empresa.RazaoSocial; CNPJ := Empresa.CNPJ; UF := Empresa.EnderecoPrincipal.UF; COD_MUN := Empresa.CodigoIbgeCidade; //SUFRAMA := Empresa.SUFRAMA; IND_NAT_PJ := indNatPJSocEmpresariaGeral; IND_ATIV := indAtivComercio; end; // REGISTRO 0001: ABERTURA DO BLOCO 0 with Registro0001New do begin IND_MOV := imComDados; // REGISTRO 0035: IDENTIFICAÇÃO DE SOCIEDADE EM CONTA DE PARTICIPAÇÃO – SCP { Não Implementado } // REGISTRO 0100: DADOS DO CONTABILISTA with Registro0100New do begin NOME := Contador.NOME; CPF := Contador.CPF; CRC := Contador.InscricaoCrc; CNPJ := Contador.CNPJ; CEP := Contador.CEP; ENDERECO := Contador.Logradouro; NUM := Contador.Numero; COMPL := Contador.Complemento; BAIRRO := Contador.BAIRRO; FONE := Contador.FONE; FAX := Contador.FAX; EMAIL := Contador.EMAIL; COD_MUN := Contador.MunicipioIbge; end; // with Registro0100New do // REGISTRO 0110: REGIMES DE APURAÇÃO DA CONTRIBUIÇÃO SOCIAL E DE APROPRIAÇÃO DE CRÉDITO with Registro0110New do begin COD_INC_TRIB := codEscrOpIncNaoCumulativo; IND_APRO_CRED := indMetodoApropriacaoDireta; COD_TIPO_CONT := codIndTipoConExclAliqBasica; end; // REGISTRO 0111: TABELA DE RECEITA BRUTA MENSAL PARA FINS DE RATEIO DE CRÉDITOS COMUNS // REGISTRO 0120: IDENTIFICAÇÃO DE PERÍODOS DISPENSADOS DA ESCRITURAÇÃO FISCAL DIGITAL DAS CONTRIBUIÇÕES – EFD-CONTRIBUIÇÕES { Não Implementados } // REGISTRO 0140: TABELA DE CADASTRO DE ESTABELECIMENTO with Registro0140New do begin COD_EST := 'MATRIZ'; NOME := Empresa.RazaoSocial;; CNPJ := Empresa.CNPJ; UF := Empresa.EnderecoPrincipal.UF; IE := Empresa.InscricaoEstadual; COD_MUN := Empresa.CodigoIbgeCidade; IM := Empresa.InscricaoMunicipal; //SUFRAMA := Empresa.SUFRAMA; // REGISTRO 0145: REGIME DE APURAÇÃO DA CONTRIBUIÇÃO PREVIDENCIÁRIA SOBRE A RECEITA BRUTA { Não Implementado } // REGISTRO 0150: TABELA DE CADASTRO DO PARTICIPANTE ListaParticipante := TStringList.Create; if assigned(ListaEmitente) then begin for i := 0 to ListaEmitente.Count - 1 do begin with Registro0150New do begin COD_PART := 'F' + IntToStr(TViewSpedNfeEmitenteVO(ListaEmitente.Items[i]).Id); NOME := TViewSpedNfeEmitenteVO(ListaEmitente.Items[i]).NOME; COD_PAIS := '01058'; if Length(TViewSpedNfeEmitenteVO(ListaEmitente.Items[i]).CpfCnpj) = 11 then CPF := TViewSpedNfeEmitenteVO(ListaEmitente.Items[i]).CpfCnpj else CNPJ := TViewSpedNfeEmitenteVO(ListaEmitente.Items[i]).CpfCnpj; IE := TViewSpedNfeEmitenteVO(ListaEmitente.Items[i]).InscricaoEstadual; COD_MUN := TViewSpedNfeEmitenteVO(ListaEmitente.Items[i]).CodigoMunicipio; //SUFRAMA := TViewSpedNfeEmitenteVO(ListaEmitente.Items[i]).SUFRAMA.ToString; ENDERECO := TViewSpedNfeEmitenteVO(ListaEmitente.Items[i]).Logradouro; NUM := TViewSpedNfeEmitenteVO(ListaEmitente.Items[i]).Numero; COMPL := TViewSpedNfeEmitenteVO(ListaEmitente.Items[i]).Complemento; BAIRRO := TViewSpedNfeEmitenteVO(ListaEmitente.Items[i]).BAIRRO; // ListaParticipante.Add(COD_PART); end; // with Registro0150New do end; // for I := 0 to ListaEmitente.Count - 1 do end; // if assigned(ListaEmitente) then if assigned(ListaDestinatario) then begin for i := 0 to ListaDestinatario.Count - 1 do begin if ListaParticipante.IndexOf(TViewSpedNfeEmitenteVO(ListaDestinatario.Items[i]).CpfCnpj) = -1 then begin with Registro0150New do begin COD_PART := 'C' + IntToStr(TViewSpedNfeEmitenteVO(ListaDestinatario.Items[i]).Id); NOME := TViewSpedNfeDestinatarioVO(ListaDestinatario.Items[i]).NOME; COD_PAIS := '01058'; if Length(TViewSpedNfeDestinatarioVO(ListaDestinatario.Items[i]).CpfCnpj) = 11 then CPF := TViewSpedNfeDestinatarioVO(ListaDestinatario.Items[i]).CpfCnpj else CNPJ := TViewSpedNfeDestinatarioVO(ListaDestinatario.Items[i]).CpfCnpj; IE := TViewSpedNfeDestinatarioVO(ListaDestinatario.Items[i]).InscricaoEstadual; COD_MUN := TViewSpedNfeDestinatarioVO(ListaDestinatario.Items[i]).CodigoMunicipio; //SUFRAMA := TViewSpedNfeDestinatarioVO(ListaDestinatario.Items[i]).SUFRAMA.ToString; ENDERECO := TViewSpedNfeDestinatarioVO(ListaDestinatario.Items[i]).Logradouro; NUM := TViewSpedNfeDestinatarioVO(ListaDestinatario.Items[i]).Numero; COMPL := TViewSpedNfeDestinatarioVO(ListaDestinatario.Items[i]).Complemento; BAIRRO := TViewSpedNfeDestinatarioVO(ListaDestinatario.Items[i]).BAIRRO; end; // with Registro0150New do end; end; // for I := 0 to ListaDestinatario.Count - 1 do end; // if assigned(ListaDestinatario) then // REGISTRO 0200: TABELA DE IDENTIFICAÇÃO DO ITEM (PRODUTO E SERVIÇOS) ListaSiglaUnidade := TStringList.Create; ListaUnidade := TObjectList<TUnidadeProdutoVO>.Create; for i := 0 to ListaProduto.Count - 1 do begin with Registro0200New do begin COD_ITEM := IntToStr(TViewSpedNfeItemVO(ListaProduto.Items[i]).Id); DESCR_ITEM := TViewSpedNfeItemVO(ListaProduto.Items[i]).NOME; COD_BARRA := TViewSpedNfeItemVO(ListaProduto.Items[i]).GTIN; (* TEM QUE PREENCHER PARA INFORMAR NO 0205 *) COD_ANT_ITEM := ''; UNID_INV := IntToStr(TViewSpedNfeItemVO(ListaProduto.Items[i]).IdUnidadeProduto); TIPO_ITEM := TACBrTipoItem(StrToInt(TViewSpedNfeItemVO(ListaProduto.Items[i]).TipoItemSped)); COD_NCM := TViewSpedNfeItemVO(ListaProduto.Items[i]).NCM; EX_IPI := TViewSpedNfeItemVO(ListaProduto.Items[i]).ExTipi; COD_GEN := Copy(TViewSpedNfeItemVO(ListaProduto.Items[i]).NCM, 1, 2); COD_LST := TViewSpedNfeItemVO(ListaProduto.Items[i]).CodigoLst; ALIQ_ICMS := TViewSpedNfeItemVO(ListaProduto.Items[i]).AliquotaIcmsPaf; if ListaSiglaUnidade.IndexOf(IntToStr(TViewSpedNfeItemVO(ListaProduto.Items[i]).IdUnidadeProduto)) = -1 then begin ListaSiglaUnidade.Add(IntToStr(TViewSpedNfeItemVO(ListaProduto.Items[i]).IdUnidadeProduto)); UnidadeProduto := TUnidadeProdutoVO.Create; UnidadeProduto.Id := TViewSpedNfeItemVO(ListaProduto.Items[i]).IdUnidadeProduto; UnidadeProduto.Sigla := TViewSpedNfeItemVO(ListaProduto.Items[i]).Sigla; ListaUnidade.Add(UnidadeProduto); end; // if ListaSiglaUnidade.IndexOf(IntToStr(TViewSpedNfeItemVO(ListaProduto.Items[i]).IdUnidadeProduto)) = -1 then end; // with Registro0200New do end; // for i := 0 to ListaProduto.Count - 1 do // REGISTRO 0190: IDENTIFICAÇÃO DAS UNIDADES DE MEDIDA for i := 0 to ListaUnidade.Count - 1 do begin with Registro0190New do begin UNID := IntToStr(TUnidadeProdutoVO(ListaUnidade.Items[i]).Id); DESCR := TUnidadeProdutoVO(ListaUnidade.Items[i]).Sigla; end; end; // REGISTRO 0205: ALTERAÇÃO DO ITEM for i := 0 to ListaProdutoAlterado.Count - 1 do begin with Registro0205New do begin DESCR_ANT_ITEM := TProdutoAlteracaoItemVO(ListaProdutoAlterado.Items[i]).NOME; DT_INI := TProdutoAlteracaoItemVO(ListaProdutoAlterado.Items[i]).DataInicial; DT_FIN := TProdutoAlteracaoItemVO(ListaProdutoAlterado.Items[i]).DataFinal; COD_ANT_ITEM := TProdutoAlteracaoItemVO(ListaProdutoAlterado.Items[i]).Codigo; end; // with Registro0205New do end; // for i := 0 to ListaProdutoAlterado.Count - 1 do // REGISTRO 0206: CÓDIGO DE PRODUTO CONFORME TABELA PUBLICADA PELA ANP (COMBUSTÍVEIS) { Não Implementado } // REGISTRO 0208: CÓDIGO DE GRUPOS POR MARCA COMERCIAL– REFRI (BEBIDAS FRIAS). { Não Implementado } end; // REGISTRO 0400: TABELA DE NATUREZA DA OPERAÇÃO/PRESTAÇÃO for i := 0 to ListaOperacaoFiscal.Count - 1 do begin with Registro0400New do begin COD_NAT := IntToStr(TTributOperacaoFiscalVO(ListaOperacaoFiscal.Items[i]).Id); DESCR_NAT := TTributOperacaoFiscalVO(ListaOperacaoFiscal.Items[i]).DescricaoNaNf; end; // with Registro0400New do end; // for i := 0 to ListaOperacaoFiscal.Count - 1 do // REGISTRO 0450: TABELA DE INFORMAÇÃO COMPLEMENTAR DO DOCUMENTO FISCAL { Não Implementado } // REGISTRO 0500: PLANO DE CONTAS CONTÁBEIS { Não Implementado } // REGISTRO 0600: CENTRO DE CUSTOS { Não Implementado } end; // with Registro0001New do end; finally FreeAndNil(Contador); FreeAndNil(ListaProduto); FreeAndNil(ListaEmitente); FreeAndNil(ListaDestinatario); FreeAndNil(ListaUnidade); FreeAndNil(ListaProdutoAlterado); FreeAndNil(ListaOperacaoFiscal); FreeAndNil(ListaParticipante); FreeAndNil(ListaSiglaUnidade); end; end; {$ENDREGION} {$REGION 'BLOCO A: DOCUMENTOS FISCAIS - SERVIÇOS (NÃO SUJEITOS AO ICMS)'} class procedure TSpedContribuicoesController.GerarBlocoA; begin try with FDataModule.ACBrSpedContribuicoes.Bloco_A do begin // REGISTRO A001: ABERTURA DO BLOCO A with RegistroA001New do begin IND_MOV := imSemDados; end; // with RegistroA100New do end; finally end; end; {$ENDREGION 'BLOCO A: DOCUMENTOS FISCAIS - SERVIÇOS (NÃO SUJEITOS AO ICMS)'} {$REGION 'BLOCO C: DOCUMENTOS FISCAIS I - MERCADORIAS (ICMS/IPI)'} class procedure TSpedContribuicoesController.GerarBlocoC; var ListaImpressora: TObjectList<TEcfImpressoraVO>; ListaNF2Cabecalho: TObjectList<TEcfNotaFiscalCabecalhoVO>; ListaNF2CabecalhoCanceladas: TObjectList<TEcfNotaFiscalCabecalhoVO>; ListaNFeCabecalho: TObjectList<TNfeCabecalhoVO>; ListaNFeDetalhe: TObjectList<TViewSpedNfeDetalheVO>; ListaNFeAnalitico: TObjectList<TViewSpedC190VO>; ListaCupomNFe: TObjectList<TNfeCupomFiscalReferenciadoVO>; ListaC300: TObjectList<TViewSpedC300VO>; ListaC321: TObjectList<TViewSpedC321VO>; ListaC370: TObjectList<TViewSpedC370VO>; ListaC390: TObjectList<TViewSpedC390VO>; ListaC425: TObjectList<TViewSpedC425VO>; ListaC490: TObjectList<TViewSpedC490VO>; ListaR02: TObjectList<TEcfR02VO>; ListaR03: TObjectList<TEcfR03VO>; ListaR04: TObjectList<TEcfVendaCabecalhoVO>; ListaR05: TObjectList<TEcfVendaDetalheVO>; i, j, k, l, m, g: Integer; // NfeTransporte: TNfeTransporteVO; EcfNotaFiscalCabecalho: TEcfNotaFiscalCabecalhoVO; Produto: TProdutoVO; begin try with FDataModule.ACBrSpedContribuicoes.Bloco_C do begin // REGISTRO C001: ABERTURA DO BLOCO C with RegistroC001New do begin IND_MOV := imComDados; ListaNF2Cabecalho := TT2TiORM.Consultar<TEcfNotaFiscalCabecalhoVO>('DATA_EMISSAO BETWEEN ' + QuotedStr(DataInicial) + ' and ' + QuotedStr(DataFinal), '-1', False); ListaNF2CabecalhoCanceladas := TT2TiORM.Consultar<TEcfNotaFiscalCabecalhoVO>('CANCELADA = ' + QuotedStr('S') + ' and DATA_EMISSAO BETWEEN ' + QuotedStr(DataInicial) + ' and ' + QuotedStr(DataFinal), '-1', False); ListaNFeCabecalho := TT2TiORM.Consultar<TNfeCabecalhoVO>('DATA_HORA_EMISSAO BETWEEN ' + QuotedStr(DataInicial) + ' and ' + QuotedStr(DataFinal), '-1', False); // REGISTRO C010: IDENTIFICAÇÃO DO ESTABELECIMENTO with RegistroC010New do begin CNPJ := Empresa.Cnpj; IND_ESCRI := IndEscriIndividualizado; // 1 – Apuração com base nos registros de consolidaçãodas operações por NF-e (C180 e C190) e por ECF (C490); // 2 – Apuração com base no registro individualizado de NF-e (C100 e C170) e de ECF (C400) if assigned(ListaNFeCabecalho) then begin for i := 0 to ListaNFeCabecalho.Count - 1 do begin // REGISTRO C100: NOTA FISCAL (CÓDIGO 01), NOTA FISCAL AVULSA (CÓDIGO 1B), NOTA FISCAL DE PRODUTOR (CÓDIGO 04), NF-e (CÓDIGO 55) e NFC-e (CÓDIGO 65) with RegistroC100New do begin IND_OPER := TACBrTipoOperacao(TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).TipoOperacao); IND_EMIT := edEmissaoPropria; if TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).IdCliente > 0 then COD_PART := 'C' + IntToStr(TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).IdCliente) else COD_PART := 'F' + IntToStr(TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).IdFornecedor); COD_MOD := TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).CodigoModelo; (* 4.1.2- Tabela Situação do Documento Código Descrição 00 Documento regular 01 Documento regular extemporâneo 02 Documento cancelado 03 Documento cancelado extemporâneo 04 NFe denegada 05 Nfe – Numeração inutilizada 06 Documento Fiscal Complementar 07 Documento Fiscal Complementar extemporâneo. 08 Documento Fiscal emitido com base em Regime Especial ou Norma Específica *) if TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).StatusNota = 0 then COD_SIT := sdRegular else COD_SIT := sdCancelado; SER := TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).Serie; NUM_DOC := TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).Numero; CHV_NFE := TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).ChaveAcesso; DT_DOC := TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).DataHoraEmissao; DT_E_S := TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).DataHoraEntradaSaida; VL_DOC := TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).ValorTotal; IND_PGTO := TACBrTipoPagamento(TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).IndicadorFormaPagamento); VL_DESC := TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).ValorDesconto; VL_ABAT_NT := 0; VL_MERC := TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).ValorTotalProdutos; // NfeTransporte := TT2TiORM.ConsultarUmObjeto<TNfeTransporteVO>('ID_NFE_CABECALHO=' + IntToStr(TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).Id), False); if assigned(NfeTransporte) then begin IND_FRT := TACBrTipoFrete(NfeTransporte.ModalidadeFrete); FreeAndNil(NfeTransporte); end; VL_FRT := TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).ValorFrete; VL_SEG := TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).ValorSeguro; VL_OUT_DA := TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).ValorDespesasAcessorias; VL_BC_ICMS := TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).BaseCalculoIcms; VL_ICMS := TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).ValorIcms; VL_BC_ICMS_ST := TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).BaseCalculoIcmsSt; VL_ICMS_ST := TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).ValorIcmsSt; VL_IPI := TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).ValorIpi; VL_PIS := TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).ValorPis; VL_COFINS := TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).ValorCofins; VL_PIS_ST := 0; VL_COFINS_ST := 0; // REGISTRO C110: COMPLEMENTO DO DOCUMENTO - INFORMAÇÃO COMPLEMENTAR DA NOTA FISCAL (CÓDIGOS 01, 1B, 04 e 55) { Não Implementado } // REGISTRO C111: PROCESSO REFERENCIADO { Não Implementado } // REGISTRO C120: COMPLEMENTO DO DOCUMENTO - OPERAÇÕES DE IMPORTAÇÃO (CÓDIGO 01) { Não Implementado } try // REGISTRO C170: COMPLEMENTO DO DOCUMENTO - ITENS DO DOCUMENTO (CÓDIGOS 01, 1B, 04 e 55) ListaNFeDetalhe := TT2TiORM.Consultar<TViewSpedNfeDetalheVO>('ID_NFE_CABECALHO=' + IntToStr(TNfeCabecalhoVO(ListaNFeCabecalho.Items[i]).Id), '-1', False); if assigned(ListaNFeDetalhe) then begin for j := 0 to ListaNFeDetalhe.Count - 1 do begin with RegistroC170New do begin NUM_ITEM := IntToStr(TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).NumeroItem); COD_ITEM := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).GTIN; DESCR_COMPL := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).NomeProduto; QTD := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).QuantidadeComercial; UNID := IntToStr(TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).IdUnidadeProduto); VL_ITEM := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).ValorTotal; VL_DESC := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).ValorDesconto; IND_MOV := mfSim; //CST_ICMS := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).CstIcms; CFOP := IntToStr(TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).CFOP); COD_NAT := IntToStr(TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).IdTributOperacaoFiscal); VL_BC_ICMS := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).BaseCalculoIcms; ALIQ_ICMS := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).AliquotaIcms; VL_ICMS := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).ValorIcms; VL_BC_ICMS_ST := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).ValorBaseCalculoIcmsSt; ALIQ_ST := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).AliquotaIcmsSt; VL_ICMS_ST := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).ValorIcmsSt; IND_APUR := iaMensal; //CST_IPI := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).CstIpi; COD_ENQ := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).EnquadramentoIpi; VL_BC_IPI := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).ValorBaseCalculoIpi; ALIQ_IPI := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).AliquotaIpi; VL_IPI := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).ValorIpi; //CST_PIS := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).CstPis; VL_BC_PIS := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).ValorBaseCalculoPis; ALIQ_PIS_PERC := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).AliquotaPisPercentual; QUANT_BC_PIS := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).QuantidadeVendidaPis; ALIQ_PIS_R := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).AliquotaPisReais; VL_PIS := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).ValorPis; //CST_COFINS := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).CstCofins; VL_BC_COFINS := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).BaseCalculoCofins; ALIQ_COFINS_PERC := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).AliquotaCofinsPercentual; QUANT_BC_COFINS := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).QuantidadeVendidaCofins; ALIQ_COFINS_R := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).AliquotaCofinsReais; VL_COFINS := TViewSpedNfeDetalheVO(ListaNFeDetalhe.Items[j]).ValorCofins; COD_CTA := ''; end; // with RegistroC170New do end; // for j := 0 to ListaNFeDetalhe.Count - 1 do end; // if Assigned(ListaNFeDetalhe) then finally FreeAndNil(ListaNFeDetalhe); end; // REGISTRO C175: REGISTRO ANALÍTICO DO DOCUMENTO (CÓDIGO 65) { Será analisado após a implementação da NFC-e } // REGISTRO C180: CONSOLIDAÇÃO DE NOTAS FISCAIS ELETRÔNICAS EMITIDAS PELA PESSOA JURÍDICA (CÓDIGOS 55 e 65) – OPERAÇÕES DE VENDAS // REGISTRO C181: DETALHAMENTO DA CONSOLIDAÇÃO – OPERAÇÕES DE VENDAS – PIS/PASEP // REGISTRO C185: DETALHAMENTO DA CONSOLIDAÇÃO – OPERAÇÕES DE VENDAS – COFINS // REGISTRO C188: PROCESSO REFERENCIADO { Não Implementados } // REGISTRO C190: CONSOLIDAÇÃO DE NOTAS FISCAIS ELETRÔNICAS (CÓDIGO 55) – OPERAÇÕES DE AQUISIÇÃO COM DIREITO A CRÉDITO, E OPERAÇÕES DE DEVOLUÇÃO DE COMPRAS E VENDAS. // REGISTRO C191: DETALHAMENTO DA CONSOLIDAÇÃO – OPERAÇÕES DE AQUISIÇÃO COM DIREITO A CRÉDITO, E OPERAÇÕES DE DEVOLUÇÃO DE COMPRAS E VENDAS – PIS/PASEP // REGISTRO C195: DETALHAMENTO DA CONSOLIDAÇÃO - OPERAÇÕES DE AQUISIÇÃO COM DIREITO A CRÉDITO, E OPERAÇÕES DE DEVOLUÇÃO DE COMPRAS E VENDAS – COFINS // REGISTRO C198: PROCESSO REFERENCIADO // REGISTRO C199: COMPLEMENTO DO DOCUMENTO - OPERAÇÕESDE IMPORTAÇÃO (CÓDIGO 55) { Não Implementados } end; // with RegistroC100New do end; // for i := 0 to ListaNFeCabecalho.Count - 1 do end; // if Assigned(ListaNFeCabecalho) then // REGISTRO C380: NOTA FISCAL DE VENDA A CONSUMIDOR (CÓDIGO 02) - CONSOLIDAÇÃO DE DOCUMENTOS EMITIDOS. ListaC300 := TT2TiORM.Consultar<TViewSpedC300VO>('DATA_EMISSAO BETWEEN ' + QuotedStr(DataInicial) + ' and ' + QuotedStr(DataFinal), '-1', False); if assigned(ListaC300) then begin for i := 0 to ListaC300.Count - 1 do begin with RegistroC380New do begin COD_MOD := '2'; FiltroLocal := '(DATA_EMISSAO BETWEEN ' + QuotedStr(DataInicial) + ' and ' + QuotedStr(DataFinal) + ')'; EcfNotaFiscalCabecalho := TT2TiORM.ConsultarUmObjeto<TEcfNotaFiscalCabecalhoVO>('ID=' + IntToStr(TT2TiORM.SelectMin('ECF_NOTA_FISCAL_CABECALHO', FiltroLocal)), False); if assigned(EcfNotaFiscalCabecalho) then begin NUM_DOC_INI := StrToInt(EcfNotaFiscalCabecalho.Numero); DT_DOC_INI := EcfNotaFiscalCabecalho.DataEmissao; FreeAndNil(EcfNotaFiscalCabecalho); end; EcfNotaFiscalCabecalho := TT2TiORM.ConsultarUmObjeto<TEcfNotaFiscalCabecalhoVO>('ID=' + IntToStr(TT2TiORM.SelectMax('ECF_NOTA_FISCAL_CABECALHO', FiltroLocal)), False); if assigned(EcfNotaFiscalCabecalho) then begin NUM_DOC_FIN := StrToInt(EcfNotaFiscalCabecalho.Numero); DT_DOC_FIN := EcfNotaFiscalCabecalho.DataEmissao; FreeAndNil(EcfNotaFiscalCabecalho); end; VL_DOC := TViewSpedC300VO(ListaC300.Items[i]).SomaTotalNf; VL_DOC_CANC := 0; // Como pegar os valores cancelados? // REGISTRO C381: DETALHAMENTO DA CONSOLIDAÇÃO – PIS/P ASEP // REGISTRO C385: DETALHAMENTO DA CONSOLIDAÇÃO – COFINS { Exercício: implementar } // REGISTRO C395: NOTAS FISCAIS DE VENDA A CONSUMIDOR(CÓDIGOS 02, 2D, 2E e 59) – AQUISIÇÕES/ENTRADAS COM CRÉDITO. // REGISTRO C396: ITENS DO DOCUMENTO (CÓDIGOS 02, 2D, 2E e 59) – AQUISIÇÕES/ENTRADAS COM CRÉDITO { Não Implementados } end; // with RegistroC380New do end; // for i := 0 to ListaC380.Count - 1 do end; // if assigned(ListaC380) then ListaImpressora := TT2TiORM.Consultar<TEcfImpressoraVO>('ID>0', '-1', False); if assigned(ListaImpressora) then begin for i := 0 to ListaImpressora.Count - 1 do begin // REGISTRO C400: EQUIPAMENTO ECF (CÓDIGOS 02 e 2D) with RegistroC400New do begin COD_MOD := TEcfImpressoraVO(ListaImpressora.Items[i]).ModeloDocumentoFiscal; ECF_MOD := TEcfImpressoraVO(ListaImpressora.Items[i]).Modelo; ECF_FAB := TEcfImpressoraVO(ListaImpressora.Items[i]).Serie; ECF_CX := TEcfImpressoraVO(ListaImpressora.Items[i]).Numero; try // verifica se existe movimento no periodo para aquele ECF FiltroLocal := 'ID_IMPRESSORA=' + IntToStr(TEcfImpressoraVO(ListaImpressora.Items[i]).Id) + ' and (DATA_EMISSAO BETWEEN ' + QuotedStr(DataInicial) + ' and ' + QuotedStr(DataFinal) + ')'; ListaR02 := TT2TiORM.Consultar<TEcfR02VO>(FiltroLocal, '-1', False); if assigned(ListaR02) then begin for j := 0 to ListaR02.Count - 1 do begin // REGISTRO C405: REDUÇÃO Z (CÓDIGOS 02 e 2D) with RegistroC405New do begin DT_DOC := TEcfR02VO(ListaR02.Items[j]).DataMovimento; CRO := TEcfR02VO(ListaR02.Items[j]).CRO; CRZ := TEcfR02VO(ListaR02.Items[j]).CRZ; NUM_COO_FIN := TEcfR02VO(ListaR02.Items[j]).Coo; GT_FIN := TEcfR02VO(ListaR02.Items[j]).GrandeTotal; VL_BRT := TEcfR02VO(ListaR02.Items[j]).VendaBruta; try // REGISTRO C481: RESUMO DIÁRIO DE DOCUMENTOS EMITIDOSPOR ECF – PIS/PASEP (CÓDIGOS 02 e 2D). // REGISTRO C485: RESUMO DIÁRIO DE DOCUMENTOS EMITIDOSPOR ECF – COFINS (CÓDIGOS 02 e 2D) FiltroLocal := 'TOTALIZADOR_PARCIAL not like ' + QuotedStr('%CAN%') + 'and TOTALIZADOR_PARCIAL not like ' + QuotedStr('%S%') + ' and (DATA_VENDA BETWEEN ' + QuotedStr(DataInicial) + ' and ' + QuotedStr(DataFinal) + ')'; ListaC425 := TT2TiORM.Consultar<TViewSpedC425VO>(FiltroLocal, '-1', False); if assigned(ListaC425) then begin for l := 0 to ListaC425.Count - 1 do begin with RegistroC481New do begin //CST_PIS := ''; // De onde pegar? VL_ITEM := TViewSpedC425VO(ListaC425.Items[l]).SomaItem; VL_BC_PIS := 0; // De onde pegar? ALIQ_PIS := 0; // De onde pegar? QUANT_BC_PIS := 0; // De onde pegar? ALIQ_PIS_QUANT := 0; // De onde pegar? VL_PIS := TViewSpedC425VO(ListaC425.Items[l]).SomaPis; COD_ITEM := IntToStr(TViewSpedC425VO(ListaC425.Items[l]).IdEcfProduto); end; // with RegistroC481New do with RegistroC485New do begin //CST_COFINS := ''; // De onde pegar? VL_ITEM := TViewSpedC425VO(ListaC425.Items[l]).SomaItem; VL_BC_COFINS := 0; // De onde pegar? ALIQ_COFINS := 0; // De onde pegar? QUANT_BC_COFINS := 0; // De onde pegar? ALIQ_COFINS_QUANT := 0; // De onde pegar? VL_COFINS := TViewSpedC425VO(ListaC425.Items[l]).SomaPis; COD_ITEM := IntToStr(TViewSpedC425VO(ListaC425.Items[l]).IdEcfProduto); end; // with RegistroC485New do end; // for l := 0 to ListaC425.Count - 1 do end; // if Assigned(ListaC425) then finally FreeAndNil(ListaC425); end; // REGISTRO C489: PROCESSO REFERENCIADO { Não Implementado } // REGISTRO C490: CONSOLIDAÇÃO DE DOCUMENTOS EMITIDOS POR ECF (CÓDIGOS 02, 2D, 59 e 60) // REGISTRO C491: DETALHAMENTO DA CONSOLIDAÇÃO DE DOCUMENTOS EMITIDOS POR ECF (CÓDIGOS 02, 2D e 59) – PIS/PASEP // REGISTRO C495: DETALHAMENTO DA CONSOLIDAÇÃO DE DOCUMENTOS EMITIDOS POR ECF (CÓDIGOS 02, 2D e 59) – COFINS // REGISTRO C499: PROCESSO REFERENCIADO { Não Implementados } end; // with RegistroC405New do end; // for j := 0 to ListaR02.Count - 1 do end; // if Assigned(ListaR02) then finally FreeAndNil(ListaR02); end; end; // with RegistroC400New do end; // for i := 0 to ListaImpressora.Count - 1 do end; // if Assigned(ListaImpressora) then // REGISTRO C500: NOTA FISCAL/CONTA DE ENERGIA ELÉTRICA (CÓDIGO 06), NOTA FISCAL/CONTA DE FORNECIMENTO D'ÁGUA CANALIZADA (CÓDIGO 29) E NOTA FISCAL CONSUMO FORNECIMENTO DE GÁS (CÓDIGO 28) E NF-e (CÓDIGO 55)– DOCUMENTOS DE ENTRADA/AQUISIÇÃO COM CRÉDITO // REGISTRO C501: COMPLEMENTO DA OPERAÇÃO (CÓDIGOS 06,28 e 29) – PIS/PASEP // REGISTRO C505: COMPLEMENTO DA OPERAÇÃO (CÓDIGOS 06,28 e 29) – COFINS // REGISTRO C509: PROCESSO REFERENCIADO // REGISTRO C600: CONSOLIDAÇÃO DIÁRIA DE NOTAS FISCAIS/CONTAS EMITIDAS DE ENERGIA ELÉTRICA (CÓDIGO 06), NOTA FISCAL/CONTA DE FORNECIMENTO D'ÁGUA CANALIZADA (CÓDIGO 29) E NOTA FISCAL/CONTA DE FORNECIMENTO DE GÁS (CÓDIGO 28) (EMPRESAS OBRIGADAS OU NÃO OBRIGADAS AO CONVENIO ICMS 115/03) – DOCUMENTOS DE SAÍDA // REGISTRO C601: COMPLEMENTO DA CONSOLIDAÇÃO DIÁRIA (CÓDIGOS 06, 28 e 29) – DOCUMENTOS DE SAÍDAS - PIS/PASEP // REGISTRO C605: COMPLEMENTO DA CONSOLIDAÇÃO DIÁRIA (CÓDIGOS 06, 28 e 29) – DOCUMENTOS DE SAÍDAS – COFINS // REGISTRO C609: PROCESSO REFERENCIADO { Não Implementados } // REGISTRO C800: CUPOM FISCAL ELETRÔNICO (CÓDIGO 59) // REGISTRO C810: DETALHAMENTO DO CUPOM FISCAL ELETRÔNICO (CÓDIGO 59) – PIS/PASEP E COFINS // REGISTRO C820: DETALHAMENTO DO CUPOM FISCAL ELETRÔNICO (CÓDIGO 59) – PIS/PASEP E COFINS APURADO POR UNIDADE DE MEDIDA DEPRODUTO // REGISTRO C830: PROCESSO RERENCIADO // REGISTRO C860: IDENTIFICAÇÃO DO EQUIPAMENTO SAT-CF-E // REGISTRO C870: RESUMO DIÁRIO DE DOCUMENTOS EMITIDOS POR EQUIPAMENTO SAT-CF-E (CÓDIGO 59) – PIS/PASEP E COFINS // REGISTRO C880: RESUMO DIÁRIO DE DOCUMENTOS EMITIDOS POR EQUIPAMENTO SAT-CF-E (CÓDIGO 59) – PIS/PASEP E COFINS APURADO POR UNIDADE DE MEDIDA DE PRODUTO // REGISTRO C890: PROCESSO REFERENCIADO (* Serão analisados após implementação do SAT *) end; end; // with RegistroC001New do end; // with FDataModule.ACBrSpedContribuicoes.Bloco_C do finally FreeAndNil(ListaImpressora); FreeAndNil(ListaNF2Cabecalho); FreeAndNil(ListaNF2CabecalhoCanceladas); FreeAndNil(ListaNFeCabecalho); FreeAndNil(ListaC300); FreeAndNil(ListaC321); FreeAndNil(ListaC390); end; end; {$ENDREGION} {$REGION 'BLOCO D: DOCUMENTOS FISCAIS II - SERVIÇOS (ICMS)'} class procedure TSpedContribuicoesController.GerarBlocoD; begin try with FDataModule.ACBrSpedContribuicoes.Bloco_D do begin // REGISTRO D001: ABERTURA DO BLOCO F with RegistroD001New do begin IND_MOV := imSemDados end; // with RegistroD001New do end; finally end; end; {$ENDREGION} {$REGION 'BLOCO F: DEMAIS DOCUMENTOS E OPERAÇÕES'} class procedure TSpedContribuicoesController.GerarBlocoF; begin try with FDataModule.ACBrSpedContribuicoes.Bloco_F do begin // REGISTRO F001: ABERTURA DO BLOCO F with RegistroF001New do begin IND_MOV := imSemDados end; // with RegistroF001New do end; finally end; end; {$ENDREGION} {$REGION 'BLOCO I: OPERAÇÕES DAS INSTITUIÇÕES FINANCEIRAS, SEGURADORAS, ENTIDADES DE PREVIDENCIA PRIVADA, OPERADORAS DE PLANOS DE ASSISTÊNCIA À SAÚDE E DEMAIS PESSOAS JURÍDICAS REFERIDAS NOS §§ 6º, 8ºE 9ºDO ART. 3ºDA LEI nº9.718/98'} class procedure TSpedContribuicoesController.GerarBlocoI; begin try with FDataModule.ACBrSpedContribuicoes.Bloco_I do begin // REGISTRO I001: ABERTURA DO BLOCO I with RegistroI001New do begin IND_MOV := imSemDados end; // with RegistroI001New do end; finally end; end; {$ENDREGION} {$REGION 'BLOCO M: APURAÇÃO DA CONTRIBUIÇÃO E CRÉDITO DO PIS/PASEP E DA COFINS'} class procedure TSpedContribuicoesController.GerarBlocoM; begin try with FDataModule.ACBrSpedContribuicoes.Bloco_M do begin // REGISTRO M001: ABERTURA DO BLOCO M with RegistroM001New do begin IND_MOV := imSemDados end; // with RegistroM001New do end; finally end; end; {$ENDREGION} {$REGION 'BLOCO 1: COMPLEMENTO DA ESCRITURAÇÃO – CONTROLE DE SALDOS DE CRÉDITOS E DE RETENÇÕES, OPERAÇÕES EXTEMPORÂNEAS E OUTRAS INFORMAÇÕES'} class procedure TSpedContribuicoesController.GerarBloco1; var i: Integer; begin try with FDataModule.ACBrSpedContribuicoes.Bloco_1 do begin // REGISTRO 1001: ABERTURA DO BLOCO 1 with Registro1001New do begin IND_MOV := imSemDados; end; // with Registro1001New do end; finally end; end; {$ENDREGION} {$REGION 'Gerar Arquivo'} class function TSpedContribuicoesController.GerarArquivoSpedContribuicoes: Boolean; begin Result := False; try try with FDataModule.ACBrSpedContribuicoes do begin DT_INI := TextoParaData(DataInicial); DT_FIN := TextoParaData(DataFinal); end; // BLOCO 0: ABERTURA, IDENTIFICAÇÃO E REFERÊNCIAS GerarBloco0; // BLOCO A: DOCUMENTOS FISCAIS - SERVIÇOS (NÃO SUJEITOS AO ICMS) { Será analisado após a implementação da NFS-e Exercício: Analisar como implementar com dados de um NF-e de serviço. } GerarBlocoA; // BLOCO C: DOCUMENTOS FISCAIS I - MERCADORIAS (ICMS/IPI GerarBlocoC; // BLOCO D: DOCUMENTOS FISCAIS II - SERVIÇOS (ICMS). // Estabelecimentos que efetivamente tenham realizado as operações especificadas no Bloco D (prestação ou contratação), relativas a serviços de transporte de cargas e/ou de passageiros, serviços de comunicação e de telecomunicação, mediante emissão de documento fiscal definido pela legislação do ICMS e do IPI, que devam ser escrituradas no Bloco D. { Não Implementado } GerarBlocoD; // BLOCO F: DEMAIS DOCUMENTOS E OPERAÇÕES // Neste bloco serão informadas pela pessoa jurídica, as demais operações geradoras de contribuição ou de crédito, não informadas nos Blocos A, C e D { Não Implementado } GerarBlocoF; // BLOCO I: OPERAÇÕES DAS INSTITUIÇÕES FINANCEIRAS, SEGURADORAS, ENTIDADES DE PREVIDENCIA PRIVADA, OPERADORAS DE PLANOS DE ASSISTÊNCIA À SAÚDE E DEMAIS PESSOAS JURÍDICAS REFERIDAS NOS §§ 6º, 8ºE 9ºDO ART. 3ºDA LEI nº9.718/98. { Não Implementado } GerarBlocoI; // BLOCO M: APURAÇÃO DA CONTRIBUIÇÃO E CRÉDITO DO PIS/PASEP E DA COFINS { Gerado pelo PVA } GerarBlocoM; // BLOCO P: APURAÇÃO DA CONTRIBUIÇÃO PREVIDENCIÁRIA SOBRE A RECEITA BRUTA (CPRB) { Não Implementado } // BLOCO 1: COMPLEMENTO DA ESCRITURAÇÃO – CONTROLE DE SALDOS DE CRÉDITOS E DE RETENÇÕES, OPERAÇÕES EXTEMPORÂNEAS E OUTRAS INFORMAÇÕES { Não Implementado } GerarBloco1; Arquivo := ExtractFilePath(Application.ExeName) + '\Arquivos\Sped\SpedContribuicoes' + FormatDateTime('DDMMYYYYhhmmss', Now) + '.txt'; if not DirectoryExists(ExtractFilePath(Application.ExeName) + '\Arquivos\Sped\') then ForceDirectories(ExtractFilePath(Application.ExeName) + '\Arquivos\Sped\'); FDataModule.ACBrSpedContribuicoes.Arquivo := Arquivo; FDataModule.ACBrSpedContribuicoes.SaveFileTXT; Result := True; except Result := False; end; finally FreeAndNil(Empresa); end; end; {$ENDREGION} {$ENDREGION} initialization Classes.RegisterClass(TSpedContribuicoesController); finalization Classes.UnRegisterClass(TSpedContribuicoesController); end.
unit EventUnit; interface uses SysUtils, Classes, IBDatabase; type TDBEvent = (deInsert, deUpdate, deDelete, deReference); TDBNotifyEvent = procedure (const TableName: string; Event: TDBEvent; ID: Integer; LocalEvent: Boolean) of object; procedure RegisterEventHandler(Handler: TDBNotifyEvent; const TableName: string; ID: Integer); procedure UnregisterEventHandler(Handler: TDBNotifyEvent; const TableName: string; ID: Integer); overload; procedure UnregisterEventHandler(Handler: TDBNotifyEvent); overload; procedure PostLocalEvent(const TableName: string; Event: TDBEvent; ID: Integer; Handler: TDBNotifyEvent = nil); procedure ShutdownEvents; var AlertDataBase: TIBDataBase; LocalOnly: Boolean; implementation uses Contnrs, IBEvents; type { TEventList } TEventList = class private FEvents: TIBEvents; FID: Integer; FSignaled: Boolean; Handlers: array of TDBNotifyEvent; procedure EventAlert(Sender: TObject; EventName: string; EventCount: LongInt; var CancelAlerts: Boolean); public constructor Create(const TableName: string; AID: Integer); destructor Destroy; override; procedure RegisterEventHandler(Handler: TDBNotifyEvent); procedure UnregisterEventHandler(Handler: TDBNotifyEvent); procedure PostEvent(const TableName: string; Event: TDBEvent; LocalEvent: Boolean; Handler: TDBNotifyEvent = nil); procedure Shutdown; property ID: Integer read FID; end; { TTableEventMan } TTableEventMan = class private FItems: TObjectList; FName: string; function FindID(ID: Integer): TEventList; public constructor Create; destructor Destroy; override; procedure RegisterEventHandler(Handler: TDBNotifyEvent; ID: Integer); procedure UnregisterEventHandler(Handler: TDBNotifyEvent; ID: Integer); overload; procedure UnregisterEventHandler(Handler: TDBNotifyEvent); overload; procedure PostEvent(Event: TDBEvent; ID: Integer; LocalEvent: Boolean; Handler: TDBNotifyEvent); procedure Shutdown; property Name: string read FNAme write FName; end; { TEventMan } TEventMan = class private FTableMans: TStrings; public constructor Create; destructor Destroy; override; procedure RegisterEventHandler(Handler: TDBNotifyEvent; const TableName: string; ID: Integer); procedure UnregisterEventHandler(Handler: TDBNotifyEvent; const TableName: string; ID: Integer); overload; procedure UnregisterEventHandler(Handler: TDBNotifyEvent); overload; procedure PostEvent(const TableName: string; Event: TDBEvent; ID: Integer; LocalEvent: Boolean; Handler: TDBNotifyEvent); procedure Shutdown; end; { TEventList } constructor TEventList.Create(const TableName: string; AID: Integer); begin inherited Create; FID := AID; if (AlertDataBase <> nil) and not LocalOnly then begin FEvents := TIBEvents.Create(nil); FEvents.AutoRegister := False; FEvents.Database := AlertDataBase; FEvents.Events.Text := Format('%0:sI%1:.8x'#13#10'%0:sU%1:.8x'#13#10'%0:sD%1:.8x'#13#10'%0:sR%1:.8x'#13#10, [TableName, ID]); FEvents.OnEventAlert := EventAlert; FEvents.RegisterEvents; end; end; destructor TEventList.Destroy; begin Shutdown; inherited Destroy; end; procedure TEventList.EventAlert(Sender: TObject; EventName: string; EventCount: LongInt; var CancelAlerts: Boolean); var TableName: string; Event: TDBEvent; ID: Integer; begin CancelAlerts := False; if Length(EventName) = 15 then begin TableName := Copy(EventName, 1, 6); case EventName[7] of 'I': Event := deInsert; 'U': Event := deUpdate; 'D': Event := deDelete; 'R': Event := deReference; else Exit; end; ID := StrToIntDef('$' + Copy(EventName, 8, 8), 0); if ID = Self.ID then PostEvent(TableName, Event, False); end; end; procedure TEventList.RegisterEventHandler(Handler: TDBNotifyEvent); var L: Integer; begin L := Length(Handlers); SetLength(Handlers, L + 1); Handlers[L] := Handler; end; procedure TEventList.UnregisterEventHandler(Handler: TDBNotifyEvent); var L, I: Integer; M1, M2: TMethod; begin M1 := TMethod(Handler); L := Length(Handlers); for I := L - 1 downto 0 do begin M2 := TMethod(Handlers[I]); if (M1.Code = M2.Code) and (M1.Data = M2.Data) then begin Move(@Handlers[I + 1], @Handlers[I], (L - I) * SizeOf(TDBNotifyEvent)); Dec(L); end; end; SetLength(Handlers, L); end; procedure TEventList.PostEvent(const TableName: string; Event: TDBEvent; LocalEvent: Boolean; Handler: TDBNotifyEvent); var I: Integer; M1, M2: TMethod; CurrentHandler: TDBNotifyEvent; begin if LocalEvent then begin FSignaled := True; end else begin if FSignaled then begin FSignaled := False; Exit; end; end; M1 := TMethod(Handler); for I := 0 to Length(Handlers) - 1 do begin CurrentHandler := Handlers[I]; M2 := TMethod(CurrentHandler); if (M1.Code <> M2.Code) or (M1.Data <> M2.Data) then begin CurrentHandler(TableName, Event, ID, LocalEvent); end; end; end; procedure TEventList.Shutdown; begin if FEvents <> nil then begin FEvents.UnRegisterEvents; FEvents.Free; FEvents := nil; end; end; { TTableEventMan } constructor TTableEventMan.Create; begin inherited Create; FItems := TObjectList.Create; end; destructor TTableEventMan.Destroy; begin FItems.Free; inherited Destroy; end; function TTableEventMan.FindID(ID: Integer): TEventList; var I: Integer; begin for I := 0 to FItems.Count - 1 do begin Result := TEventList(FItems[I]); if Result.ID = ID then Exit; end; Result := nil; end; procedure TTableEventMan.RegisterEventHandler(Handler: TDBNotifyEvent; ID: Integer); var Item: TEventList; begin Item := FindID(ID); if Item = nil then begin Item := TEventList.Create(Name, ID); FItems.Add(Item); end; Item.RegisterEventHandler(Handler); end; procedure TTableEventMan.UnregisterEventHandler(Handler: TDBNotifyEvent; ID: Integer); var Item: TEventList; begin Item := FindID(ID); if Item <> nil then Item.UnregisterEventHandler(Handler); end; procedure TTableEventMan.UnregisterEventHandler(Handler: TDBNotifyEvent); var I: Integer; begin for I := 0 to FItems.Count - 1 do TEventList(FItems[I]).UnregisterEventHandler(Handler); end; procedure TTableEventMan.PostEvent(Event: TDBEvent; ID: Integer; LocalEvent: Boolean; Handler: TDBNotifyEvent); var Item: TEventList; begin Item := FindID(ID); if Item <> nil then Item.PostEvent(Name, Event, LocalEvent, Handler); end; procedure TTableEventMan.Shutdown; var I: Integer; begin for I := 0 to FItems.Count - 1 do TEventList(FItems[I]).Shutdown; end; { TEventMan } constructor TEventMan.Create; begin inherited Create; FTableMans := TStringList.Create; end; destructor TEventMan.Destroy; var I: Integer; begin if FTableMans <> nil then begin for I := 0 to FTableMans.Count - 1 do FTableMans.Objects[I].Free; FTableMans.Free; end; inherited Destroy; end; procedure TEventMan.RegisterEventHandler(Handler: TDBNotifyEvent; const TableName: string; ID: Integer); var Index: Integer; FTableMan: TTableEventMan; begin Index := FTableMans.IndexOf(TableName); if Index = -1 then begin FTableMan := TTableEventMan.Create; FTableMan.Name := TableName; FTableMans.AddObject(TableName, FTableMan); end else FTableMan := TTableEventMan(FTableMans.Objects[Index]); FTableMan.RegisterEventHandler(Handler, ID); end; procedure TEventMan.UnregisterEventHandler(Handler: TDBNotifyEvent; const TableName: string; ID: Integer); var Index: Integer; begin Index := FTableMans.IndexOf(TableName); if Index <> -1 then begin TTableEventMan(FTableMans.Objects[Index]).UnregisterEventHandler(Handler, ID); end; end; procedure TEventMan.UnregisterEventHandler(Handler: TDBNotifyEvent); var I: Integer; begin for I := 0 to FTableMans.Count - 1 do begin TTableEventMan(FTableMans.Objects[I]).UnregisterEventHandler(Handler); end; end; procedure TEventMan.PostEvent(const TableName: string; Event: TDBEvent; ID: Integer; LocalEvent: Boolean; Handler: TDBNotifyEvent); var Index: Integer; begin Index := FTableMans.IndexOf(TableName); if Index <> -1 then begin TTableEventMan(FTableMans.Objects[Index]).PostEvent(Event, ID, LocalEvent, Handler); end; end; procedure TEventMan.Shutdown; var I: Integer; begin for I := 0 to FTableMans.Count - 1 do begin TTableEventMan(FTableMans.Objects[I]).Shutdown; end; end; var FEventMan: TEventMan; procedure RegisterEventHandler(Handler: TDBNotifyEvent; const TableName: string; ID: Integer); begin if FEventMan = nil then FEventMan := TEventMan.Create; FEventMan.RegisterEventHandler(Handler, TableName, ID); end; procedure UnregisterEventHandler(Handler: TDBNotifyEvent; const TableName: string; ID: Integer); begin if FEventMan <> nil then FEventMan.UnregisterEventHandler(Handler, TableName, ID); end; procedure UnregisterEventHandler(Handler: TDBNotifyEvent); begin if FEventMan <> nil then FEventMan.UnregisterEventHandler(Handler); end; procedure PostEvent(const TableName: string; Event: TDBEvent; ID: Integer; LocalEvent: Boolean; Handler: TDBNotifyEvent); begin if FEventMan <> nil then FEventMan.PostEvent(TableName, Event, ID, LocalEvent, Handler); end; procedure PostLocalEvent(const TableName: string; Event: TDBEvent; ID: Integer; Handler: TDBNotifyEvent); begin PostEvent(TableName, Event, ID, True, Handler); if ID <> 0 then PostEvent(TableName, Event, 0, True, Handler); end; procedure ShutdownEvents; begin if FEventMan <> nil then FEventMan.Shutdown; end; initialization finalization if FEventMan <> nil then begin FEventMan.Free; FEventMan := nil; end; end.
unit OptionsEditorTabs; interface uses System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, BCControls.CheckBox, BCCommon.OptionsContainer, BCFrames.OptionsFrame, JvExStdCtrls, JvCheckBox; type TOptionsEditorTabsFrame = class(TOptionsFrame) Panel: TPanel; CloseTabByDblClickCheckBox: TBCCheckBox; CloseTabByMiddleClickCheckBox: TBCCheckBox; DoubleBufferedCheckBox: TBCCheckBox; MultilineCheckBox: TBCCheckBox; ShowCloseButtonCheckBox: TBCCheckBox; ShowImageCheckBox: TBCCheckBox; RightClickSelectCheckBox: TBCCheckBox; private { Private declarations } public { Public declarations } destructor Destroy; override; procedure GetData; override; procedure PutData; override; end; function OptionsEditorTabsFrame(AOwner: TComponent): TOptionsEditorTabsFrame; implementation {$R *.dfm} var FOptionsEditorTabsFrame: TOptionsEditorTabsFrame; function OptionsEditorTabsFrame(AOwner: TComponent): TOptionsEditorTabsFrame; begin if not Assigned(FOptionsEditorTabsFrame) then FOptionsEditorTabsFrame := TOptionsEditorTabsFrame.Create(AOwner); Result := FOptionsEditorTabsFrame; end; destructor TOptionsEditorTabsFrame.Destroy; begin inherited; FOptionsEditorTabsFrame := nil; end; procedure TOptionsEditorTabsFrame.PutData; begin OptionsContainer.EditorCloseTabByDblClick := CloseTabByDblClickCheckBox.Checked; OptionsContainer.EditorCloseTabByMiddleClick := CloseTabByMiddleClickCheckBox.Checked; OptionsContainer.EditorMultiLine := MultiLineCheckBox.Checked; OptionsContainer.EditorDoubleBuffered := DoubleBufferedCheckBox.Checked; OptionsContainer.EditorShowCloseButton := ShowCloseButtonCheckBox.Checked; OptionsContainer.EditorShowImage := ShowImageCheckBox.Checked; OptionsContainer.EditorRightClickSelect := RightClickSelectCheckBox.Checked; end; procedure TOptionsEditorTabsFrame.GetData; begin CloseTabByDblClickCheckBox.Checked := OptionsContainer.EditorCloseTabByDblClick; CloseTabByMiddleClickCheckBox.Checked := OptionsContainer.EditorCloseTabByMiddleClick; MultiLineCheckBox.Checked := OptionsContainer.EditorMultiLine; DoubleBufferedCheckBox.Checked := OptionsContainer.EditorDoubleBuffered; ShowCloseButtonCheckBox.Checked := OptionsContainer.EditorShowCloseButton; ShowImageCheckBox.Checked := OptionsContainer.EditorShowImage; RightClickSelectCheckBox.Checked := OptionsContainer.EditorRightClickSelect; end; end.
(*Напишите процедуру для очистки экрана, она может пригодиться вам в будущем. Подсказка: можно напечатать несколько десятков пустых строк (не менее 25, что зависит от настройки размера консольного окна).*) const CScreen = 25; { количество строк в консольном окне } procedure ClearScreen; var i : integer; begin for i:=1 to CScreen do Writeln; end; begin ClearScreen; end.
unit UMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, ShellApi; type TFMain = class(TForm) Timer1: TTimer; procedure Timer1Timer(Sender: TObject); private FOutFolder: string; FInFolder: string; FViewerPath: string; procedure SetInFolder(const Value: string); procedure SetOutFolder(const Value: string); procedure SetViewerPath(const Value: string); public procedure ScanAndClean; function PrepareFolderPath(pFolder :string) :string; published // папка с исходными файлами property InFolder :string read FInFolder write SetInFolder; // папка с файлами результатов property OutFolder :string read FOutFolder write SetOutFolder; // путь запуска FRViewer.exe property ReportViewerPath :string read FViewerPath write SetViewerPath; end; var FMain: TFMain; implementation {$R *.dfm} { TFMain } function TFMain.PrepareFolderPath(pFolder: string): string; begin if (pFolder[length(pFolder)]<>'\') then Result:=pFolder; end; procedure TFMain.ScanAndClean; var inFile, outFile :TextFile; i :integer; sr: TSearchRec; s, s_part, line, parFr :string; begin try if FindFirst(InFolder+'\*.*', faAnyFile, sr) = 0 then begin repeat if (AnsiLowerCase(ExtractFileExt(sr.Name))='.prn') then begin AssignFile(inFile,InFolder+'\'+sr.Name); Reset(inFile); s:=''; i:=0; s_part:=''; while not EOF(inFile) do begin Readln(inFile, line); if (Trim(line)<>'') then begin if i=0 then s:=s+line+#13#10 else begin if (i>3) and (s<>'') then s:=s+#12+line+#13#10 else s:=s+line+#13#10; i:=0; s_part:=''; end end else begin s_part:=s_part+line+#13#10; Inc(i); end; end; CloseFile(InFile); AssignFile(outFile,OutFolder+'\'+sr.Name); Rewrite(outFile); Write(OutFile,s); CloseFile(OutFile); DeleteFile(InFolder+'\'+sr.Name); end else if (AnsiLowerCase(ExtractFileExt(sr.Name))='.frp') then begin AssignFile(outFile,OutFolder+'\'+sr.Name); if CopyFile( PChar(InFolder+'\'+sr.Name),PChar(OutFolder+'\'+sr.Name),true ) then begin DeleteFile(InFolder+'\'+sr.Name); if Pos('[1]',sr.Name)>0 then ParFr:='\p' // печать отчета сразу после открытия, без просмотра else ParFr:=''; ShellExecute( Application.Handle,'Open', PChar('"'+ReportViewerPath+'"'), PChar('"'+OutFolder+'\'+sr.Name+'" '+ParFr), nil,SW_SHOWNORMAL ); end; end; until FindNext(sr) <> 0; FindClose(sr); end; except ShowMessage('Ошибка при обработке файлов!'); end; end; procedure TFMain.SetInFolder(const Value: string); begin FInFolder:=PrepareFolderPath(Value); end; procedure TFMain.SetOutFolder(const Value: string); begin FOutFolder:=PrepareFolderPath(Value); end; procedure TFMain.SetViewerPath(const Value: string); begin FViewerPath:=Value; end; procedure TFMain.Timer1Timer(Sender: TObject); begin Timer1.Enabled:=false; ScanAndClean; Timer1.Enabled:=true; end; end.
{ Routines that deal with environment file descriptors. } module picprg_env; define picprg_env_read; %include 'picprg2.ins.pas'; const env_name = 'picprg.env'; {environment file set name} type adradd_k_t = ( {how to add address to list} adradd_asc_k, {insert by ascending address order} adradd_end_k); {add to end of list} { ******************************************************************************* * * Subroutine PICPRG_ENV_READ (PR, STAT) * * Read the PICPRG.ENV environment file set and save the information in * PR.ENV. PR.ENV is assumed to be completely uninitialized before this * call. } procedure picprg_env_read ( {read env file, save info in PR} in out pr: picprg_t; {state for this use of the library} out stat: sys_err_t); {completion status} val_param; var conn: file_conn_t; {connection to the environment file set} buf: string_var8192_t; {one line input buffer} lnam: string_leafname_t; {scratch file leafname} p: string_index_t; {BUF parse index} i: sys_int_machine_t; {scratch integer} r: real; {scratch floating point value} adr: picprg_adr_t; {scratch target address} dat: picprg_dat_t; {scratch target address word} i8: int8u_t; {scratch 8 bit unsigned integer} idspace: picprg_idspace_k_t; {chip ID name space} org: picprg_org_k_t; {software/firmware creating organization ID} idblock_p: picprg_idblock_p_t; {pointer to currently open ID block} cmd: string_var32_t; {command name, upper case} tk: string_var80_t; {scratch token} pick: sys_int_machine_t; {number of keyword picked from list} name_p: picprg_idname_p_t; {pointer to current chip name descriptor} name_pp: ^picprg_idname_p_t; {points to where to link next name descr} vdd: picprg_vddvals_t; {scratch Vdd voltage levels descriptor} cmds: string_var8192_t; {list of all the command keywords} famnames: string_var1024_t; {list of family names for TYPE command} adrres_set: boolean; {ADRRES explicitly set this block} label loop_line, loop_name, done_names, loop_vdd, done_vdd, done_cmd, eof, err_parm, err_noid, err_missing, err_atline, abort; { ********** * * Subroutine INSERT_ADR (LIST_P, ADRADD, ADR, MASK, STAT) * This routine is internal to PICPRG_ENV_READ. * * Insert the address ADR into the list of address specifications. ADRADD * specifies how the address is to be added to the list. LIST_P is the start * of list pointer, which may be updated. } procedure insert_adr ( {insert new address into list} in out list_p: picprg_adrent_p_t; {pointer to first list entry, may be updated} in adradd: adradd_k_t; {where to add new entry to list} in adr: picprg_adr_t; {address to insert} in mask: picprg_dat_t; {mask of valid bits at this address} out stat: sys_err_t); {completion status} val_param; var ent_p: picprg_adrent_p_t; {pointer to the new list entry} ent_pp: ^picprg_adrent_p_t; {pointer to chain link to the new entry} e_p: picprg_adrent_p_t; {pointer to current list entry} begin sys_error_none (stat); {init to no error encountered} util_mem_grab ( {allocate memory for the new list entry} sizeof(ent_p^), pr.mem_p^, false, ent_p); ent_p^.adr := adr; {save address in list entry} ent_p^.mask := mask; {save valid bits mask in list entry} ent_p^.val := 0; {init to value in target of this word is unknown} ent_p^.kval := false; ent_pp := addr(list_p); {init pointer to where to link in new entry} e_p := list_p; {init the next list entry pointer} while e_p <> nil do begin {scan the existing list} if e_p^.adr = adr then begin {entry with this address already exists ?} sys_stat_set (picprg_subsys_k, picprg_stat_dupadr_k, stat); return; end; case adradd of {what is strategy for adding new address to list ?} adradd_asc_k: begin {add in ascending address order} if e_p^.adr < adr then begin {new entry goes after this one} ent_pp := addr(e_p^.next_p); {update pointer to link new entry to} end; end; adradd_end_k: begin {add to end of list} ent_pp := addr(e_p^.next_p); end; end; e_p := e_p^.next_p; {advance to next list entry} end; { * ENT_PP is pointing to the chain link where the new entry is to be * inserted. } ent_p^.next_p := ent_pp^; {insert the new entry into the chain} ent_pp^ := ent_p; end; { *************************************************************************** * * Start of main routine. } begin buf.max := size_char(buf.str); {init local var strings} lnam.max := size_char(lnam.str); cmd.max := size_char(cmd.str); tk.max := size_char(tk.str); cmds.max := size_char(cmds.str); famnames.max := size_char(famnames.str); string_vstring (lnam, env_name, size_char(env_name)); {make var string env name} file_open_read_env ( {open the environment file set for reading} lnam, {environment file set name} '', {file name suffix} true, {read file set in global to local order} conn, {returned connection to the file set} stat); if sys_error(stat) then return; { * Initialize ENV in the library state. } for org := picprg_org_min_k to picprg_org_max_k do begin {once each possible ORG} pr.env.org[org].name.max := size_char(pr.env.org[org].name.str); pr.env.org[org].name.len := 0; {init to no organization with this ID} pr.env.org[org].webpage.max := size_char(pr.env.org[org].webpage.str); pr.env.org[org].webpage.len := 0; end; pr.env.idblock_p := nil; {init device ID blocks chain to empty} { * Initialize local state before reading all the commands. } idblock_p := nil; {init to not currently within an ID block} cmds.len := 0; {set list of command name keywords} string_appends (cmds, 'ORG'(0)); {1} string_appends (cmds, ' ID'(0)); {2} string_appends (cmds, ' NAMES'(0)); {3} string_appends (cmds, ' VDD'(0)); {4} string_appends (cmds, ' REV'(0)); {5} string_appends (cmds, ' TYPE'(0)); {6} string_appends (cmds, ' ENDID'(0)); {7} string_appends (cmds, ' PINS'(0)); {8} string_appends (cmds, ' NPROG'(0)); {9} string_appends (cmds, ' NDAT'(0)); {10} string_appends (cmds, ' MASKPRG'(0)); {11} string_appends (cmds, ' MASKDAT'(0)); {12} string_appends (cmds, ' TPROG'(0)); {13} string_appends (cmds, ' DATMAP'(0)); {14} string_appends (cmds, ' CONFIG'(0)); {15} string_appends (cmds, ' OTHER'(0)); {16} string_appends (cmds, ' TPROGD'(0)); {17} string_appends (cmds, ' MASKPRGE'(0)); {18} string_appends (cmds, ' MASKPRGO'(0)); {19} string_appends (cmds, ' WRITEBUF'(0)); {20} string_appends (cmds, ' WBUFRANGE'(0)); {21} string_appends (cmds, ' VPP'(0)); {22} string_appends (cmds, ' RESADR'(0)); {23} string_appends (cmds, ' EECON1'(0)); {24} string_appends (cmds, ' EEADR'(0)); {25} string_appends (cmds, ' EEADRH'(0)); {26} string_appends (cmds, ' EEDATA'(0)); {27} string_appends (cmds, ' VISI'(0)); {28} string_appends (cmds, ' TBLPAG'(0)); {29} string_appends (cmds, ' NVMCON'(0)); {30} string_appends (cmds, ' NVMKEY'(0)); {31} string_appends (cmds, ' NVMADR'(0)); {32} string_appends (cmds, ' NVMADRU'(0)); {33} famnames.len := 0; {set list of family names for TYPE command} string_appends (famnames, '10F'(0)); {1} string_appends (famnames, ' 16F'(0)); {2} string_appends (famnames, ' 12F6XX'(0)); {3} string_appends (famnames, ' 16F62X'(0)); {4} string_appends (famnames, ' 16F62XA'(0)); {5} string_appends (famnames, ' 16F716'(0)); {6} string_appends (famnames, ' 16F87XA'(0)); {7} string_appends (famnames, ' 18F'(0)); {8} string_appends (famnames, ' 30F'(0)); {9} string_appends (famnames, ' 18F2520'(0)); {10} string_appends (famnames, ' 16F688'(0)); {11} string_appends (famnames, ' 16F88'(0)); {12} string_appends (famnames, ' 16F77'(0)); {13} string_appends (famnames, ' 16F84'(0)); {14} string_appends (famnames, ' 18F6680'(0)); {15} string_appends (famnames, ' 18F6310'(0)); {16} string_appends (famnames, ' 18F2523'(0)); {17} string_appends (famnames, ' 16F7X7'(0)); {18} string_appends (famnames, ' 16F88X'(0)); {19} string_appends (famnames, ' 16F61X'(0)); {20} string_appends (famnames, ' 18J'(0)); {21} string_appends (famnames, ' 24H'(0)); {22} string_appends (famnames, ' 12F'(0)); {23} string_appends (famnames, ' 16F72X'(0)); {24} string_appends (famnames, ' 24F'(0)); {25} string_appends (famnames, ' 18F14K22'(0)); {26} string_appends (famnames, ' 16F182X'(0)); {27} string_appends (famnames, ' 16F720'(0)); {28} string_appends (famnames, ' 18F14K50'(0)); {29} string_appends (famnames, ' 24FJ'(0)); {30} string_appends (famnames, ' 12F1501'(0)); {31} string_appends (famnames, ' 18K80'(0)); {32} string_appends (famnames, ' 33EP'(0)); {33} string_appends (famnames, ' 16F15313'(0)); {34} string_appends (famnames, ' 16F183XX'(0)); {35} string_appends (famnames, ' 18F25Q10'(0)); {36} { * Loop back here to read each new line from the environment file set. } loop_line: file_read_env (conn, buf, stat); {read next env file set line into BUF} if file_eof(stat) then goto eof; {hit end of file set ?} p := 1; {init parse index for the new line} string_token (buf, p, cmd, stat); {get the command name} string_upcase (cmd); string_tkpick (cmd, cmds, pick); {pick the command name from keywords list} case pick of { ********************* * * ORG id name webpage } 1: begin string_token_int (buf, p, i, stat); {get ID number into I} if sys_error(stat) then goto err_parm; i8 := i; {convert to 8 bit unsigned integer} org := picprg_org_k_t(i8); {make ID for the selected organization} string_token (buf, p, pr.env.org[org].name, stat); {get organization name string} if sys_error(stat) then goto err_parm; string_token (buf, p, pr.env.org[org].webpage, stat); {get web page address} if sys_error(stat) then goto err_parm; string_downcase (pr.env.org[org].webpage); {save web address in lower case} end; { ********************* * * ID namespace binid } 2: begin if idblock_p <> nil then begin {already within an ID block ?} sys_stat_set (picprg_subsys_k, picprg_stat_idid_k, stat); goto err_atline; end; string_token (buf, p, tk, stat); {get ID namespace name string} string_upcase (tk); {make upper case for keyword matching} string_tkpick80 (tk, {pick namespace name from list} '16 16B 18 12 30 18B', pick); {number of name picked from the list} case pick of 1: idspace := picprg_idspace_16_k; 2: idspace := picprg_idspace_16b_k; 3: idspace := picprg_idspace_18_k; 4: idspace := picprg_idspace_12_k; 5: idspace := picprg_idspace_30_k; 6: idspace := picprg_idspace_18b_k; otherwise goto err_parm; {invalid ID namespace name, parameter error} end; string_token (buf, p, tk, stat); {get binary ID pattern token} if sys_error(stat) then goto err_parm; util_mem_grab ( {allocate memory for the new ID block} sizeof(idblock_p^), pr.mem_p^, false, idblock_p); idblock_p^.next_p := pr.env.idblock_p; {insert new block at the start of the chain} pr.env.idblock_p := idblock_p; idblock_p^.idspace := idspace; {initialize the new ID block descriptor} idblock_p^.mask := 0; idblock_p^.id := 0; idblock_p^.vdd.low := 4.5; idblock_p^.vdd.norm := 5.0; idblock_p^.vdd.high := 5.5; idblock_p^.vdd.twover := abs(idblock_p^.vdd.high - idblock_p^.vdd.low) > 0.010; idblock_p^.vppmin := 12.5; idblock_p^.vppmax := 13.5; idblock_p^.name_p := nil; idblock_p^.rev_mask := 2#11111; idblock_p^.rev_shft := 0; idblock_p^.wbufsz := 1; idblock_p^.wbstrt := 0; idblock_p^.wblen := 0; idblock_p^.pins := 0; idblock_p^.nprog := 0; idblock_p^.ndat := 0; idblock_p^.adrres := 0; idblock_p^.adrreskn := true; idblock_p^.maskprg.maske := 0; idblock_p^.maskprg.masko := 0; idblock_p^.maskdat.maske := 0; idblock_p^.maskdat.masko := 0; idblock_p^.datmap := lastof(idblock_p^.datmap); idblock_p^.tprogp := 0.0; idblock_p^.tprogd := 0.0; idblock_p^.config_p := nil; idblock_p^.other_p := nil; idblock_p^.fam := picprg_picfam_unknown_k; idblock_p^.eecon1 := 16#FA6; idblock_p^.eeadr := 16#FA9; idblock_p^.eeadrh := 16#FAA; idblock_p^.eedata := 16#FA8; idblock_p^.visi := 16#0784; idblock_p^.tblpag := 16#0032; idblock_p^.nvmcon := 16#0760; idblock_p^.nvmkey := 16#0766; idblock_p^.nvmadr := 16#0762; idblock_p^.nvmadru := 16#0764; idblock_p^.hdouble := false; idblock_p^.eedouble := false; adrres_set := false; {init to ADRRES not explicitly set from command} string_upcase (tk); {make upper case for pattern matching} if string_equal (tk, string_v('NONE'(0))) then begin {this chip has no ID ?} idblock_p^.mask := ~0; {set all bits to significant} goto done_cmd; {done with this command} end; for i := 1 to tk.len do begin {once for each character in binary pattern} idblock_p^.mask := lshft(idblock_p^.mask, 1); {make room for this new bit} idblock_p^.id := lshft(idblock_p^.id, 1); case tk.str[i] of {what is specified for this bit ?} '0': begin {bit must be 0} idblock_p^.mask := idblock_p^.mask ! 1; end; '1': begin {bit must be 1} idblock_p^.mask := idblock_p^.mask ! 1; idblock_p^.id := idblock_p^.id ! 1; end; 'X': begin {bit is "don't care"} end; otherwise goto err_parm; {this parameter is invalid} end; end; {back to process next binary pattern char} end; { ********************* * * NAMES name ... name } 3: begin if idblock_p = nil then goto err_noid; {no ID block currently open ?} if idblock_p^.name_p <> nil then begin {list of names already exists ?} sys_stat_set (picprg_subsys_k, picprg_stat_names2_k, stat); goto err_atline; end; name_pp := addr(idblock_p^.name_p); {init where to link next name descriptor} loop_name: {back here each new name token} string_token (buf, p, tk, stat); {get this name token into TK} if string_eos(stat) then goto done_names; {exhausted the name tokens ?} if sys_error(stat) then goto err_parm; util_mem_grab ( {allocate memory for this new name descriptor} sizeof(name_p^), pr.mem_p^, false, name_p); name_pp^ := name_p; {link new descriptor to end of chain} name_pp := addr(name_p^.next_p); {update end of chain pointer} name_p^.next_p := nil; {init to no chain entry after this one} name_p^.name.max := size_char(name_p^.name.str); {set name string for this entry} string_copy (tk, name_p^.name); string_upcase (name_p^.name); {names are stored in upper case} name_p^.vdd := idblock_p^.vdd; {set Vdd levels for this name to defaults} goto loop_name; {back to get and process next name token} done_names: {hit end of command line} end; { ********************* * * VDD low normal high [name ... name] } 4: begin if idblock_p = nil then goto err_noid; {no ID block currently open ?} string_token_fpm (buf, p, vdd.low, stat); if sys_error(stat) then goto err_parm; string_token_fpm (buf, p, vdd.norm, stat); if sys_error(stat) then goto err_parm; string_token_fpm (buf, p, vdd.high, stat); if sys_error(stat) then goto err_parm; vdd.twover := abs(vdd.high - vdd.low) > 0.010; i := 0; {init number of names processed} loop_vdd: {back here to get each new name token} string_token (buf, p, tk, stat); {get this name token into TK} if string_eos(stat) then goto done_vdd; {exhausted the name tokens ?} if sys_error(stat) then goto err_parm; i := i + 1; {count one more name processed} string_upcase (tk); {all names are stored upper case} name_p := idblock_p^.name_p; {init pointer to start of names chain} while name_p <> nil do begin {once for each name in the list} if string_equal (tk, name_p^.name) then begin {this name matches the token ?} name_p^.vdd := vdd; {set the Vdd levels for this name} goto loop_vdd; {back to get next name token} end; name_p := name_p^.next_p; {advance to next name in the list} end; {back and test this new name for a match} sys_stat_set (picprg_subsys_k, picprg_stat_badvddname_k, stat); sys_stat_parm_vstr (tk, stat); goto err_atline; done_vdd: {done with all name tokens} if i = 0 then begin {no names supplied at all ?} name_p := idblock_p^.name_p; {init pointer to start of names chain} while name_p <> nil do begin {once for each name in the list} name_p^.vdd := vdd; {set the Vdd levels for this name} name_p := name_p^.next_p; {advance to next name in the list} end; {back and test this new name for a match} end; end; { ********************* * * REV mask shift } 5: begin if idblock_p = nil then goto err_noid; {no ID block currently open ?} string_token_int (buf, p, i, stat); {get mask} if sys_error(stat) then goto err_parm; idblock_p^.rev_mask := i; string_token_int (buf, p, idblock_p^.rev_shft, stat); {get shift count} if sys_error(stat) then goto err_parm; end; { ********************* * * TYPE family } 6: begin if idblock_p = nil then goto err_noid; {no ID block currently open ?} idblock_p^.wbstrt := 0; {init to write buffer not apply to this fam} idblock_p^.wblen := 0; string_token (buf, p, tk, stat); {get family name token} if sys_error(stat) then goto err_parm; string_upcase (tk); {make upper case for keyword matching} string_tkpick (tk, famnames, pick); {pick family name from the list} case pick of 1: begin idblock_p^.fam := picprg_picfam_10f_k; end; 2: begin idblock_p^.fam := picprg_picfam_16f_k; idblock_p^.wblen := 8192; end; 3: begin idblock_p^.fam := picprg_picfam_12f6xx_k; idblock_p^.wblen := 8192; end; 4: begin idblock_p^.fam := picprg_picfam_16f62x_k; idblock_p^.wblen := 8192; end; 5: begin idblock_p^.fam := picprg_picfam_16f62xa_k; idblock_p^.wblen := 8192; end; 6: begin idblock_p^.fam := picprg_picfam_16f716_k; idblock_p^.wblen := 8192; end; 7: begin idblock_p^.fam := picprg_picfam_16f87xa_k; idblock_p^.wblen := 8192; end; 8: begin idblock_p^.fam := picprg_picfam_18f_k; idblock_p^.wblen := 16#200000; end; 9: begin idblock_p^.fam := picprg_picfam_30f_k; idblock_p^.wbufsz := 64; idblock_p^.wblen := 16#F80000; end; 10: begin idblock_p^.fam := picprg_picfam_18f2520_k; idblock_p^.wblen := 16#200000; end; 11: begin idblock_p^.fam := picprg_picfam_16f688_k; idblock_p^.wblen := 8192; end; 12: begin idblock_p^.fam := picprg_picfam_16f88_k; idblock_p^.wblen := 8192 + 4; {user ID locations also use write buffer} end; 13: begin idblock_p^.fam := picprg_picfam_16f77_k; idblock_p^.wblen := 8192 + 4; {user ID locations also use write buffer} end; 14: begin idblock_p^.fam := picprg_picfam_16f84_k; idblock_p^.wblen := 8192; end; 15: begin idblock_p^.fam := picprg_picfam_18f6680_k; idblock_p^.wblen := 16#200000; end; 16: begin idblock_p^.fam := picprg_picfam_18f6310_k; idblock_p^.wblen := 16#200000; end; 17: begin idblock_p^.fam := picprg_picfam_18f2523_k; idblock_p^.wblen := 16#200000; end; 18: begin idblock_p^.fam := picprg_picfam_16f7x7_k; idblock_p^.wblen := 8192; end; 19: begin idblock_p^.fam := picprg_picfam_16f88x_k; idblock_p^.wblen := 8192; end; 20: begin idblock_p^.fam := picprg_picfam_16f61x_k; idblock_p^.wblen := 8192; end; 21: begin idblock_p^.fam := picprg_picfam_18j_k; idblock_p^.wblen := 16#200000; end; 22: begin idblock_p^.fam := picprg_picfam_24h_k; idblock_p^.wbufsz := 128; idblock_p^.wblen := 16#F80000; end; 23: begin idblock_p^.fam := picprg_picfam_12f_k; end; 24: begin idblock_p^.fam := picprg_picfam_16f72x_k; idblock_p^.wblen := 8192; end; 25: begin idblock_p^.fam := picprg_picfam_24f_k; idblock_p^.wbufsz := 64; idblock_p^.wblen := 16#F80000; end; 26: begin idblock_p^.fam := picprg_picfam_18f14k22_k; idblock_p^.wblen := 16#200000; end; 27: begin idblock_p^.fam := picprg_picfam_16f182x_k; idblock_p^.wblen := 16#8000; end; 28: begin idblock_p^.fam := picprg_picfam_16f720_k; idblock_p^.wblen := 8192; end; 29: begin idblock_p^.fam := picprg_picfam_18f14k50_k; idblock_p^.wblen := 16#200000; end; 30: begin idblock_p^.fam := picprg_picfam_24fj_k; idblock_p^.wbufsz := 64; idblock_p^.wblen := 16#F80000; end; 31: begin idblock_p^.fam := picprg_picfam_12f1501_k; idblock_p^.wblen := 16#8000; end; 32: begin idblock_p^.fam := picprg_picfam_18k80_k; idblock_p^.wblen := 16#200000; end; 33: begin idblock_p^.fam := picprg_picfam_33ep_k; idblock_p^.wblen := 16#F80000; end; 34: begin idblock_p^.fam := picprg_picfam_16f15313_k; idblock_p^.wblen := 16#8000; idblock_p^.adrres := 0; {reset sets address to 0} idblock_p^.adrreskn := true; end; 35: begin idblock_p^.fam := picprg_picfam_16f183xx_k; idblock_p^.wblen := 16#8000; idblock_p^.adrres := 0; {reset sets address to 0} idblock_p^.adrreskn := true; end; 36: begin idblock_p^.fam := picprg_picfam_18f25q10_k; idblock_p^.wblen := 0; idblock_p^.adrreskn := false; end; otherwise sys_stat_set (picprg_subsys_k, picprg_stat_badfam_k, stat); sys_stat_parm_vstr (tk, stat); goto err_atline; end; end; { ********************* * * ENDID } 7: begin if idblock_p = nil then goto err_noid; {no ID block currently open ?} if idblock_p^.name_p = nil then begin {no name specified ?} string_vstring (tk, 'NAME'(0), -1); goto err_missing; end; if idblock_p^.fam = picprg_picfam_unknown_k then begin {no family type specified ?} string_vstring (tk, 'TYPE'(0), -1); goto err_missing; end; if idblock_p^.pins = 0 then begin {number of pins not specified ?} string_vstring (tk, 'PINS'(0), -1); goto err_missing; end; if idblock_p^.nprog = 0 then begin string_vstring (tk, 'NPROG'(0), -1); goto err_missing; end; if (idblock_p^.maskprg.maske = 0) and (idblock_p^.maskprg.masko = 0) then begin string_vstring (tk, 'MASKPRG'(0), -1); goto err_missing; end; if (idblock_p^.ndat > 0) and {this chip has data memory ?} (idblock_p^.datmap = lastof(idblock_p^.datmap)) {no mapping specified ?} then begin string_vstring (tk, 'DATMAP'(0), -1); goto err_missing; end; if not adrres_set then begin {ADRRES not explicitly set from a command ?} case idblock_p^.fam of picprg_picfam_10f_k, picprg_picfam_12f_k: begin {12 bit core} idblock_p^.adrres := (idblock_p^.nprog * 2) - 1; end; end; {end of PIC family type cases} end; idblock_p^.hdouble := {determine whether HEX file addresses doubled} (idblock_p^.maskprg.maske > 255) or (idblock_p^.maskprg.masko > 255); idblock_p^.eedouble := {determine EEPROM adr doubled beyond HDOUBLE} ( (not idblock_p^.hdouble) and (idblock_p^.maskdat.maske > 255) or (idblock_p^.maskdat.masko > 255) ) or (idblock_p^.maskprg.maske <> idblock_p^.maskprg.masko); idblock_p := nil; {indicate not currently in an ID block} end; { ********************* * * PINS n } 8: begin if idblock_p = nil then goto err_noid; {no ID block currently open ?} string_token_int (buf, p, idblock_p^.pins, stat); end; { ********************* * * NPROG n } 9: begin if idblock_p = nil then goto err_noid; {no ID block currently open ?} string_token_int (buf, p, i, stat); idblock_p^.nprog := i; end; { ********************* * * NDAT n } 10: begin if idblock_p = nil then goto err_noid; {no ID block currently open ?} string_token_int (buf, p, i, stat); idblock_p^.ndat := i; end; { ********************* * * MASKPROG mask } 11: begin if idblock_p = nil then goto err_noid; {no ID block currently open ?} string_token_int (buf, p, i, stat); idblock_p^.maskprg.maske := i; idblock_p^.maskprg.masko := i; end; { ********************* * * MASKDAT mask } 12: begin if idblock_p = nil then goto err_noid; {no ID block currently open ?} string_token_int (buf, p, i, stat); idblock_p^.maskdat.maske := i; idblock_p^.maskdat.masko := i; end; { ********************* * * TPROG ms } 13: begin if idblock_p = nil then goto err_noid; {no ID block currently open ?} string_token_fpm (buf, p, r, stat); r := r / 1000.0; {convert to seconds} idblock_p^.tprogp := r; {set program memory write delay time} idblock_p^.tprogd := r; {set data memory write delay time} end; { ********************* * * DATMAP adr } 14: begin if idblock_p = nil then goto err_noid; {no ID block currently open ?} string_token_int (buf, p, i, stat); idblock_p^.datmap := i; end; { ********************* * * CONFIG adr mask } 15: begin if idblock_p = nil then goto err_noid; {no ID block currently open ?} string_token_int (buf, p, i, stat); {get address} if sys_error(stat) then goto err_parm; adr := i; string_token_int (buf, p, i, stat); {get mask} if sys_error(stat) then goto err_parm; dat := i; insert_adr (idblock_p^.config_p, adradd_end_k, adr, dat, stat); if sys_error(stat) then goto err_atline; end; { ********************* * * OTHER adr mask } 16: begin if idblock_p = nil then goto err_noid; {no ID block currently open ?} string_token_int (buf, p, i, stat); {get address} if sys_error(stat) then goto err_parm; adr := i; string_token_int (buf, p, i, stat); {get mask} if sys_error(stat) then goto err_parm; dat := i; insert_adr (idblock_p^.other_p, adradd_asc_k, adr, dat, stat); if sys_error(stat) then goto err_atline; end; { ********************* * * TPROGD ms } 17: begin if idblock_p = nil then goto err_noid; {no ID block currently open ?} string_token_fpm (buf, p, r, stat); r := r / 1000.0; {convert to seconds} idblock_p^.tprogd := r; {set data memory write delay time} end; { ********************* * * MASKPROGE mask } 18: begin if idblock_p = nil then goto err_noid; {no ID block currently open ?} string_token_int (buf, p, i, stat); idblock_p^.maskprg.maske := i; end; { ********************* * * MASKPROGO mask } 19: begin if idblock_p = nil then goto err_noid; {no ID block currently open ?} string_token_int (buf, p, i, stat); idblock_p^.maskprg.masko := i; end; { ********************* * * WRITEBUF n } 20: begin if idblock_p = nil then goto err_noid; {no ID block currently open ?} string_token_int (buf, p, i, stat); idblock_p^.wbufsz := i; end; { ********************* * * WBUFRANGE start len } 21: begin if idblock_p = nil then goto err_noid; {no ID block currently open ?} string_token_int (buf, p, i, stat); if sys_error(stat) then goto err_parm; idblock_p^.wbstrt := i; string_token_int (buf, p, i, stat); idblock_p^.wblen := i; end; { ********************* * * VPP min max } 22: begin if idblock_p = nil then goto err_noid; {no ID block currently open ?} string_token_fpm (buf, p, r, stat); if sys_error(stat) then goto err_parm; idblock_p^.vppmin := r; string_token_fpm (buf, p, r, stat); if sys_error(stat) then goto err_parm; idblock_p^.vppmax := r; end; { ********************* * * RESADR (adr | NONE) } 23: begin if idblock_p = nil then goto err_noid; {no ID block currently open ?} string_token (buf, p, tk, stat); if sys_error(stat) then goto err_parm; string_upcase (tk); if string_equal (tk, string_v('NONE'(0))) then begin {NONE} idblock_p^.adrres := 0; idblock_p^.adrreskn := false; end else begin {address} string_t_int (tk, i, stat); if sys_error(stat) then goto err_parm; idblock_p^.adrres := i; end ; adrres_set := true; end; { ********************* * * EECON1 adr } 24: begin if idblock_p = nil then goto err_noid; {no ID block currently open ?} string_token_int (buf, p, i, stat); if sys_error(stat) then goto err_parm; idblock_p^.eecon1 := i; end; { ********************* * * EEADR adr } 25: begin if idblock_p = nil then goto err_noid; {no ID block currently open ?} string_token_int (buf, p, i, stat); if sys_error(stat) then goto err_parm; idblock_p^.eeadr := i; end; { ********************* * * EEADRH adr } 26: begin if idblock_p = nil then goto err_noid; {no ID block currently open ?} string_token_int (buf, p, i, stat); if sys_error(stat) then goto err_parm; idblock_p^.eeadrh := i; end; { ********************* * * EEDATA adr } 27: begin if idblock_p = nil then goto err_noid; {no ID block currently open ?} string_token_int (buf, p, i, stat); if sys_error(stat) then goto err_parm; idblock_p^.eedata := i; end; { ********************* * * VISI adr } 28: begin if idblock_p = nil then goto err_noid; {no ID block currently open ?} string_token_int (buf, p, i, stat); if sys_error(stat) then goto err_parm; idblock_p^.visi := i; end; { ********************* * * TBLPAG adr } 29: begin if idblock_p = nil then goto err_noid; {no ID block currently open ?} string_token_int (buf, p, i, stat); if sys_error(stat) then goto err_parm; idblock_p^.tblpag := i; end; { ********************* * * NVMCON adr } 30: begin if idblock_p = nil then goto err_noid; {no ID block currently open ?} string_token_int (buf, p, i, stat); if sys_error(stat) then goto err_parm; idblock_p^.nvmcon := i; end; { ********************* * * NVMKEY adr } 31: begin if idblock_p = nil then goto err_noid; {no ID block currently open ?} string_token_int (buf, p, i, stat); if sys_error(stat) then goto err_parm; idblock_p^.nvmkey := i; end; { ********************* * * NVMADR adr } 32: begin if idblock_p = nil then goto err_noid; {no ID block currently open ?} string_token_int (buf, p, i, stat); if sys_error(stat) then goto err_parm; idblock_p^.nvmadr := i; end; { ********************* * * NVMADRU adr } 33: begin if idblock_p = nil then goto err_noid; {no ID block currently open ?} string_token_int (buf, p, i, stat); if sys_error(stat) then goto err_parm; idblock_p^.nvmadru := i; end; { ********************* * * Unrecognized command. } otherwise sys_stat_set (picprg_subsys_k, picprg_stat_badcmd_k, stat); sys_stat_parm_vstr (cmd, stat); goto err_atline; end; { * Done processing this command. Check for error status. } done_cmd: {command may jump here when done} if sys_error(stat) then goto err_parm; string_token (buf, p, tk, stat); {try go get another token from cmd line} if string_eos(stat) then goto loop_line; {hit end of line, back for next line} sys_stat_set (picprg_subsys_k, picprg_stat_tkextra_k, stat); goto err_atline; { * The end of the environment file set has been reached. } eof: file_close (conn); {close the environment file set} if idblock_p <> nil then begin {an ID block is currently open ?} sys_stat_set (picprg_subsys_k, picprg_stat_ideof_k, stat); return; end; return; {normal return with no error} { * Jump here on error with a parameter. STAT will be overwritten with * a generic parameter error message giving the file and line number. } err_parm: sys_stat_set (picprg_subsys_k, picprg_stat_barg_atline_k, stat); goto err_atline; { * Jump here if the command is only allowed within an ID block and no * ID block is currently open. } err_noid: {not within an ID block} sys_stat_set (picprg_subsys_k, picprg_stat_nidblock_k, stat); sys_stat_parm_vstr (cmd, stat); {add command name} goto err_atline; { * A required value was not supplied in an ID block. TK is set to the * name of the command that sets the parameter. } err_missing: sys_stat_set (picprg_subsys_k, picprg_stat_idmissing_k, stat); sys_stat_parm_vstr (tk, stat); {name of missing command} goto err_atline; { * An error has occurred on this line. STAT must already be set to the * appropriate status. The line number and file name of the error will * be added as two STAT parameters, in that order. } err_atline: sys_stat_parm_int (conn.lnum, stat); {add line number within file} sys_stat_parm_vstr (conn.tnam, stat); {add file pathname} { * Common error abort point. STAT is already fully set. The connection to * the environment file set is closed. } abort: file_close (conn); {close connection to the environment file set} end; {return with error status}
{ ********************** Descrição das Atividades ******************************* OS Programador Data Descrição 003 Marcos Luiz 06/04/16 Criação da Variavel Global Codigo do Regime Tributario da Filial } unit Global ; interface Uses Graphics, Forms, dbTables, IniFiles, BDE, CCambio, CParFinanc, SysUtils, Classes, FMTBcd, Aguardando, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, FireDAC.Comp.DataSet, FireDAC.Comp.Client; Var G_DBHnd : hDbiDb ; // Database Handle GCorDeFundo : TColor ; GFormHeight, GFormWidth, GFormLeft, // Posição e tamanho GFormTop : Integer ; // dos forms de cadastro GLastForm : TForm ; // Último formulário aberto GPerOperacao: Array Of String ; // Vetor com as operacoes permitidas para o usuario GPerManut: Array of String ; // Vetor com as opcoes de manutencao das operacoes GPerNumOpe : Integer ; // Operacoes disponiveis para um usuario GClienteNovo : String; GDatabase : String ; // Nome da base de dados GEmpresa : String ; // Codigo da empresa padrão GEmpRazao: String ; // Razao social da empresa padrao GFone : String ; // Telefone GCGC : String ; // CGC GLogo : String ; // Arquivo com o logotipo da empresa GMascContab : String ; // Máscara contábil GUsuario : String ; // Usuario que esta utilizando o sistema GNome : String ; GSenha : String ; // Senha descriptografada GPerfil : String ; // Perfil de usuario que esta utilizando o sistema GCCusto : String ; // C.Custo de usuario que esta utilizando o sistema GOpeId : String ; // Ope Id que esta utilizando a planilha GUsuFil : String ; // Lista de Filiais que o usurio tem permissao GPathIMG : String; GImagemFTP : Boolean; // Sistema salva imagem em ftp ou rede. (* Variáveis do arquivo ini *) GGerarAviso : String[1] ; GGerarCheque : String[1] ; GFilial : String[15] ; GVendedor : String[15] ; GFilCod : Integer ; GUsuarioAtivo : String[1]; (* Cambio *) GCambio : TCambio ; (* Parâmetros Financeiros *) GParFin : TParFinanc ; GMoedaUs : String[15] ; GMoedaBR : String[15] ; GMoedaCB : String[15] ; GCaixaUS : String[15] ; GVersao : String[4] ; GFatorComInvoice : Double; GFatorVenInvoice : Double; GFatorVen : Double; GFatorCom : Double; (* Uso do Banco Generico *) GBanGen : Boolean ; GValBanGen : Double; GBanGenFim : Boolean; {* Parametros Fiscais *} GRegimeTrib : Integer; //003 GFilialUF : String[2]; Listtemp2: TStringList; Function Glob_FillPerfil ( CodUsu : String ) : Boolean ; Export ; Function Glob_GetAccess ( CodOpe : String ; CodManut : String = '' ) : Boolean ; Export ; Procedure Glob_ReadIni() ; Export ; Function Glob_Cript ( Value : String ) : String ; Export ; Function Glob_Decript ( Value : String ) : String ; Export ; Function Glob_GetDigito ( CodRes : Integer ) : String ; Overload ; Export ; Function Glob_GetDigito ( CodRes : String ) : String ; Overload ; Export ; Function Glob_GetParFin : Boolean ; procedure AguardandoProcesso(Formulario: TForm; Visivel: Boolean; Titulo : String= ''); function ContaChar(Palavra, BuscaCaracter: string): integer; procedure ListarArquivos(diretorioInicial, mascara: string; listtotaldir: boolean = false; recursive: boolean = true); Function Glob_FillPerfilPG ( CodUsu : Integer ) : Boolean ; Export ; implementation Uses StrFun, SQLTableFun, NumFun, DBConect ; Function Glob_FillPerfilPG ( CodUsu : Integer ) : Boolean ; Var Tab : TSQLTableClass ; CodPer : String ; QPerOpe, QUsuario : TFDQuery ; i : Integer ; Begin Result := False ; QUsuario := TFDQuery.Create(Nil); Try QUsuario.Connection := DB_Conect.SQLConnection; QUsuario.Close; QUsuario.SQL.Clear; QUsuario.SQL.Add('Select codusuario, nome, senha, codfilial, codperfil From usuario '); QUsuario.SQL.Add(' Where codusuario = :codusuario'); QUsuario.Params.ParamByName('codusuario').AsInteger := CodUsu; QUsuario.Open; CodPer := IntToStr(QUsuario.FieldByName('codperfil').AsInteger); GPerfil := IntToStr(QUsuario.FieldByName('codfilial').AsInteger); Finally FreeAndNil(QUsuario); End; QPerOpe := TFDQuery.Create(Nil); Try QPerOpe.Connection := DB_Conect.SQLConnection; QPerOpe.Close; QPerOpe.SQL.Clear; QPerOpe.SQL.Add('Select codoperacao, manut from perfil_operacao '); QPerOpe.SQL.Add(' where codperfil = :codperfil'); QPerOpe.Params.ParamByName('codperfil').AsInteger := StrToInt(CodPer); QPerOpe.Open; If ( QPerOpe.Eof ) Then Begin GPerNumOpe := 1 ; SetLength(GPerOperacao,1) ; SetLength(GPerManut,1) ; GPerOperacao[0] := 'CAD-ESTADO' ; GPerManut[0] :='T' ; Exit ; End; GPerNumOpe := QPerOpe.RecordCount ; SetLength(GPerOperacao,GPerNumOpe) ; SetLength(GPerManut,GPerNumOpe) ; i := 0 ; While ( Not QPerOpe.Eof ) Do Begin GPerOperacao[i] := QPerOpe.FieldByName('codoperacao').AsString ; GPerManut[i] := QPerOpe.FieldByName('manut').AsString ; i := i + 1 ; QPerOpe.Next ; End; GUsuario := IntToStr(CodUsu); Result := True ; Finally FreeAndNil(QPerOpe); End; End ; function ContaChar(Palavra, BuscaCaracter: string): integer; var i: Integer; begin result := 0; for i := 1 to length(Palavra) do if AnsiUpperCase(copy(Palavra, i, 1)) = AnsiUpperCase(BuscaCaracter) then inc(result); end; procedure ListarArquivos(diretorioInicial, mascara: string; listtotaldir: boolean = false; recursive: boolean = true); var i, x: integer; listatemp: TStrings; ItemMask: ShortString; c: Integer; procedure ListarDiretorios(Folder: string; lista: Tstrings); var Rec: TSearchRec; begin lista.Clear; if SysUtils.FindFirst(Folder + '*', faDirectory, Rec) = 0 then try repeat lista.Add(rec.Name); until SysUtils.FindNext(Rec) <> 0; finally if lista.count <> 0 then begin // deleta o diretorio .. lista.Delete(1); // deleta o diretorio . lista.Delete(0); end; end; end; procedure ListarAtahos(Folder, mask: string; Lista: Tstrings); var Rec: TSearchRec; begin lista.Clear; if SysUtils.FindFirst(Folder + mask, faAnyFile, Rec) = 0 then try repeat lista.Add(rec.Name); until SysUtils.FindNext(Rec) <> 0; finally SysUtils.FindClose(Rec); end; end; procedure AddLIstInOther(ListSource, ListDestino: TStrings); var f: integer; begin for f := 0 to ListSource.Count - 1 do begin ListDestino.Add(ListSource.Strings[f]); end; end; begin listatemp := TStringList.Create; c := ContaChar(Mascara, ';') + 1; for x := 1 to c do begin ItemMask := Str_Pal(mascara, x, ';'); ListarAtahos(diretorioInicial, ItemMask, listatemp); if listtotaldir = true then begin for i := 0 to listatemp.Count - 1 do begin listatemp.Strings[i] := diretorioInicial + listatemp.Strings[i]; end; end; AddLIstInOther(listatemp, listtemp2); if recursive = true then begin ListarDiretorios(diretorioInicial, listatemp); for i := 0 to listatemp.Count - 1 do begin ListarArquivos(diretorioInicial + listatemp.Strings[i] + '\', ItemMask, listtotaldir, recursive); end; end; end; listatemp.Free; end; procedure AguardandoProcesso(Formulario: TForm; Visivel: Boolean; Titulo : String=''); var i: integer; begin if FrmAguardando <> nil then begin FreeAndNil(FrmAguardando); end; if Visivel then begin FrmAguardando := TFrmAguardando.Create(application); FrmAguardando.Position := poScreenCenter; FrmAguardando.Show; Application.ProcessMessages; // if Assigned(CDSBase) then // begin // i := -1; // while i <> CDSBase.RecordCount do // begin // i := CDSBase.RecordCount; // CDSBase.GetNextPacket; FrmAguardando.LbInfo.Caption := UpperCase(Titulo); FrmAguardando.Refresh; // end; // end; end; end; (* ---------------------------------------------------------------------- *) (* Glob_FillPerfil => Enche os vetores com as caracteristicas do perfil *) (* do usuario *) (* ---------------------------------------------------------------------- *) Function Glob_FillPerfil ( CodUsu : String ) : Boolean ; Var Tab : TSQLTableClass ; CodPer : String ; QPerOpe : TFDQuery ; i : Integer ; Begin Result := False ; Tab := TSQLTableClass.Create ; If ( Not Tab.OpenTable('usuario') ) Then Begin Tab.SetError('[Glob_SetPerfil] - Não foi possível abrir a tabela USUARIO') ; Exit ; End ; If ( Not Tab.SetFieldKey('CodUsuario') ) Then Begin Tab.SetError('[Glob_SetPerfil] - Não foi possível definir a chave primária da tabela USUARIO') ; Exit ; End ; Tab.SetKey([CodUsu]) ; If ( Not Tab.Find(True) ) Then Begin Tab.SetError('[Glob_SetPerfil] - Usuário não encontrado') ; Exit ; End ; //CodPer := Tab.GetFieldValue('CodPerfil') ; CodPer := Tab.GetFieldValue('Filial') ; // if Pos('T10', Tab.GetFieldValue('CodPerfil')) > 0 then // GPerfil := Copy(Tab.GetFieldValue('CodPerfil'), 5, 6) // else GPerfil := Copy(Tab.GetFieldValue('Filial'), 1, 10) ; GCCusto := Tab.GetFieldValue('filial') ; QPerOpe := Tab.ExecSqlSel('Select CodOperacao, Manut From Perfil_Operacao ' + // 'Where CodPerfil = ''' + CodPer + '''') ; 'Where CodPerfil = ''' + Tab.GetFieldValue('CodPerfil') + '''') ; If ( QPerOpe.Eof ) Then Begin Tab.SetError('[Glob_SetPerfil] - Este usuário não apresenta perfil cadastrado') ; GPerNumOpe := 1 ; SetLength(GPerOperacao,1) ; SetLength(GPerManut,1) ; GPerOperacao[0] := 'CAD-ESTADO' ; GPerManut[0] :='T' ; Exit ; End; GPerNumOpe := QPerOpe.RecordCount ; SetLength(GPerOperacao,GPerNumOpe) ; SetLength(GPerManut,GPerNumOpe) ; i := 0 ; While ( Not QPerOpe.Eof ) Do Begin GPerOperacao[i] := QPerOpe.FieldByName('CodOperacao').AsString ; GPerManut[i] := QPerOpe.FieldByName('Manut').AsString ; i := i + 1 ; QPerOpe.Next ; End; GUsuario := CodUsu ; Tab.SetError ; Tab.Destroy ; Result := True ; End ; (* ---------------------------------------------------------------------- *) (* Glob_GetAccess => Devolve se um usuario tem ou nao acesso a uma *) (* operacao / manutencao *) (* ---------------------------------------------------------------------- *) Function Glob_GetAccess ( CodOpe : String ; CodManut : String = '' ) : Boolean ; Var i : Integer ; Begin If ( CodOpe = '' ) Then Begin Result := True ; Exit ; End ; Result := False ; For i:=0 To GPerNumOpe-1 Do Begin If ( GPerOperacao[i] = CodOpe ) Then Begin If ( Pos('T',GPerManut[i]) <> 0 ) Then Begin Result := True ; Break ; End ; If ( (CodManut = '') Or (Pos(CodManut,GPerManut[i]) <> 0) ) Then Begin Result := True ; Break ; End ; End ; End ; End ; (* ---------------------------------------------------------------------- *) (* Glob_ReadIni => Le o arquivo MESTRE.INI *) (* ---------------------------------------------------------------------- *) Procedure Glob_ReadIni() ; Var Ini : TIniFile ; Tab : TSQLTableClass ; Begin Ini := TIniFile.Create('.\mestre.ini') ; GFilial := Ini.ReadString('Empresa','Filial','') ; GLogo := Ini.ReadString('Empresa','Logo','') ; GGerarCheque := Ini.ReadString('MovCorrente','GerarCheque','N') ; GGerarAviso := Ini.ReadString('MovCorrente','GerarAviso','N') ; Ini.Free ; Tab := TSQLTableClass.Create ; // GEmpresa := Tab.SeekGet('Filial','CodFilial',[GFilial],'Empresa') ; // GEmpRazao := Tab.SeekGet('Filial','CodFilial',[GFilial],'Razao') ; // GFone := Tab.SeekGet('Filial','CodFilial',[GFilial],'Telefone') ; // GCGC := Tab.SeekGet('Filial','CodFilial',[GFilial],'CGC') ; Tab.Destroy ; End ; (* ---------------------------------------------------------------------- *) (* Glob_Cript => Recebe um string e o criptografa *) (* ---------------------------------------------------------------------- *) Function Glob_Cript ( Value : String ) : String ; var p : Array [0..256] of Char ; begin { StrPCopy(p,Value) ; RC4Crypt(p,Length(Value)) ; Result := String(p) ; } End ; (* ---------------------------------------------------------------------- *) (* Glob_Decript => Recebe um string criptografado e o descriptografa *) (* ---------------------------------------------------------------------- *) Function Glob_Decript ( Value : String ) : String ; //var // p : Array [0..256] of Char ; Begin { StrPCopy(p,Value) ; RC4Crypt(p,Length(Value)) ; Result := String(p) ; } End ; (* ---------------------------------------------------------------------- *) (* Glob_GetDigito => Devolve o digito verificador *) (* ---------------------------------------------------------------------- *) Function Glob_GetDigito ( CodRes : Integer ) : String ; Var Fxa : String ; Fclc, Fmul, Fdig : Integer ; Fdiv : Integer ; Begin Fxa := Num_IntToStrZ(CodRes,4) ; Fclc := Str_StrToInt( Copy(Fxa,4,1) ) * 4 ; Fmul := Str_StrToInt(Copy(Num_IntToStrZ(Fclc,2),1,1)) + Str_StrToInt(Copy(Num_IntToStrZ(Fclc,2),2,1)) ; Fclc := Str_StrToInt( Copy(Fxa,3,1) ) * 3 ; Fmul := Fmul + Str_StrToInt(Copy(Num_IntToStrZ(Fclc,2),1,1)) + Str_StrToInt(Copy(Num_IntToStrZ(Fclc,2),2,1)) ; Fclc := Str_StrToInt( Copy(Fxa,2,1) ) * 2 ; Fmul := Fmul + Str_StrToInt(Copy(Num_IntToStrZ(Fclc,2),1,1)) + Str_StrToInt(Copy(Num_IntToStrZ(Fclc,2),2,1)) ; Fdiv := Trunc(Fmul/10) * 10 ; Fdig := Abs(10 - Str_StrToInt(Copy(Num_IntToStrZ((Fmul - Fdiv),2),2,1))) ; Result := Copy(Num_IntToStrZ(Fdig,2),2,1) ; End ; (* ---------------------------------------------------------------------- *) (* Glob_GetDigito => Devolve o digito verificador *) (* ---------------------------------------------------------------------- *) Function Glob_GetDigito ( CodRes : String ) : String ; Var Cod : Integer ; Fxa : String ; Fclc, Fmul, Fdig : Integer ; Fdiv : Integer ; Begin Cod := Str_StrToInt(CodRes) ; Fxa := Num_IntToStrZ(Cod,4) ; Fclc := Str_StrToInt( Copy(Fxa,4,1) ) * 4 ; Fmul := Str_StrToInt(Copy(Num_IntToStrZ(Fclc,2),1,1)) + Str_StrToInt(Copy(Num_IntToStrZ(Fclc,2),2,1)) ; Fclc := Str_StrToInt( Copy(Fxa,3,1) ) * 3 ; Fmul := Fmul + Str_StrToInt(Copy(Num_IntToStrZ(Fclc,2),1,1)) + Str_StrToInt(Copy(Num_IntToStrZ(Fclc,2),2,1)) ; Fclc := Str_StrToInt( Copy(Fxa,2,1) ) * 2 ; Fmul := Fmul + Str_StrToInt(Copy(Num_IntToStrZ(Fclc,2),1,1)) + Str_StrToInt(Copy(Num_IntToStrZ(Fclc,2),2,1)) ; Fdiv := Trunc(Fmul/10) * 10 ; Fdig := Abs(10 - Str_StrToInt(Copy(Num_IntToStrZ((Fmul - Fdiv),2),2,1))) ; Result := Copy(Num_IntToStrZ(Fdig,2),2,1) ; End ; (* ---------------------------------------------------------------------- *) (* Glob_GetParFin ==> Lê os parâmetros financeiros *) (* ---------------------------------------------------------------------- *) Function Glob_GetParFin : Boolean ; Begin Result := False ; GParFin := TParFinanc.Create() ; If ( Not GParFin.Select() ) Then Exit ; GMoedaUS := GParFin.CodMoedaUS ; GMoedaBR := GParFin.CodMoedaBR ; GMoedaCB := GParFin.CodMoedaCB ; GVersao := GParFin.Versao ; GCaixaUS := 'CXUS' ; GFatorComInvoice := GParFin.FatorComInvoice; GFatorVenInvoice := GParFin.FatorVenInvoice; GFatorVen := GParFin.FatorVen; GFatorCom := GParFin.FatorCom; GCambio := TCambio.Create() ; Result := True ; End ; Initialization GDatabase := 'ESCGESTAO' ; GCorDeFundo := $007CA6BD ; GFormHeight := 512 ; GFormWidth := 746 ; end.
PROGRAM PaulRevere(INPUT, OUTPUT); {Печать соответствующего сообщения ,зависящего от величины на входе: '...by land' для 1; '...by sea' для 2; иначе печать ссобщения об ошибке} VAR Lanterns: CHAR; BEGIN {PaulRevere} READ(Lanterns); IF Lanterns = 'L' THEN BEGIN READ(Lanterns); IF lanterns = 'L' THEN WRITELN('The British are coming by sea.') ELSE WRITELN('The British are coming by land.') END ELSE WRITELN('The North Church shows only ''', Lanterns, '''.') END. {PaulRevere}
{ this file is part of Ares Aresgalaxy ( http://aresgalaxy.sourceforge.net ) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ########### original code taken from SlavaNap source code. ########### Copyright 2001,2002 by SlavaNap development team Released under GNU General Public License Latest version is available at http://www.slavanap.org ********************************************************** Unit: Classes2 Rip of original Classes.pas - replaced classes TList, TStrings, TStringList *********************************************************} unit Classes2; interface uses SysUtils, Windows, Classes; //const // MaxListSize = Maxint div 16; type { TMyList class } PPointerList = ^TPointerList; TPointerList = array[0..MaxListSize - 1] of Pointer; TListSortCompare = function (Item1, Item2: Pointer): Integer; // TmyList=Tlist; // TMyStringList=Tstringlist; //implementation TMyList = class(TObject) private FList: PPointerList; FCount: Integer; FCapacity: Integer; protected function Get(Index: Integer): Pointer; procedure Grow; virtual; procedure Put(Index: Integer; Item: Pointer); procedure SetCapacity(NewCapacity: Integer); procedure SetCount(NewCount: Integer); public // GrowDelta: Integer; constructor Create; destructor Destroy; override; function Add(Item: Pointer): Integer; procedure Clear; dynamic; procedure Delete(Index: Integer); class procedure Error(const Msg: string; Data: Integer); virtual; procedure Exchange(Index1, Index2: Integer); function Expand: TMyList; function First: Pointer; function IndexOf(Item: Pointer): Integer; procedure Insert(Index: Integer; Item: Pointer); function Last: Pointer; procedure Move(CurIndex, NewIndex: Integer); function Remove(Item: Pointer): Integer; procedure Pack; procedure Sort(Compare: TListSortCompare); property Capacity: Integer read FCapacity write SetCapacity; property Count: Integer read FCount write SetCount; property Items[Index: Integer]: Pointer read Get write Put; default; property List: PPointerList read FList; end; // TMyStrings class TMyStrings = class(TPersistent) private FUpdateCount: Integer; FAdapter: IStringsAdapter; function GetCommaText: string; function GetName(Index: Integer): string; function GetValue(const Name: string): string; procedure ReadData(Reader: TReader); procedure SetCommaText(const Value: string); procedure SetStringsAdapter(const Value: IStringsAdapter); procedure SetValue(const Name, Value: string); procedure WriteData(Writer: TWriter); protected procedure DefineProperties(Filer: TFiler); override; procedure Error(const Msg: string; Data: Integer); function Get(Index: Integer): string; virtual; abstract; function GetCapacity: Integer; virtual; function GetCount: Integer; virtual; abstract; function GetObject(Index: Integer): TObject; virtual; function GetTextStr: string; virtual; procedure Put(Index: Integer; const S: string); virtual; procedure PutObject(Index: Integer; AObject: TObject); virtual; procedure SetCapacity(NewCapacity: Integer); virtual; procedure SetTextStr(const Value: string); virtual; procedure SetUpdateState(Updating: Boolean); virtual; public destructor Destroy; override; function Add(const S: string): Integer; virtual; function AddObject(const S: string; AObject: TObject): Integer; virtual; procedure Append(const S: string); procedure AddStrings(Strings: TMyStrings); virtual; procedure Assign(Source: TPersistent); override; procedure BeginUpdate; procedure Clear; virtual; abstract; procedure Delete(Index: Integer); virtual; abstract; procedure EndUpdate; function Equals(Strings: TMyStrings): Boolean; procedure Exchange(Index1, Index2: Integer); virtual; function GetText: PChar; virtual; function IndexOf(const S: string): Integer; virtual; function IndexOfName(const Name: string): Integer; function IndexOfObject(AObject: TObject): Integer; procedure Insert(Index: Integer; const S: string); virtual; abstract; procedure InsertObject(Index: Integer; const S: string; AObject: TObject); procedure LoadFromFile(const FileName: string); virtual; procedure LoadFromStream(Stream: TStream); virtual; procedure Move(CurIndex, NewIndex: Integer); virtual; procedure SaveToFile(const FileName: string); virtual; procedure SaveToStream(Stream: TStream); virtual; procedure SetText(Text: PChar); virtual; property Capacity: Integer read GetCapacity write SetCapacity; property CommaText: string read GetCommaText write SetCommaText; property Count: Integer read GetCount; property Names[Index: Integer]: string read GetName; property Objects[Index: Integer]: TObject read GetObject write PutObject; property Values[const Name: string]: string read GetValue write SetValue; property Strings[Index: Integer]: string read Get write Put; default; property Text: string read GetTextStr write SetTextStr; property StringsAdapter: IStringsAdapter read FAdapter write SetStringsAdapter; end; // TMyStringList class TDuplicates = (dupIgnore, dupAccept, dupError); PStringItem = ^TStringItem; TStringItem = record FString: string; FObject: TObject; end; PStringItemList = ^TStringItemList; TStringItemList = array[0..MaxListSize] of TStringItem; TMyStringList = class(TMyStrings) private FList: PStringItemList; FCount: Integer; FCapacity: Integer; FSorted: Boolean; FDuplicates: TDuplicates; FOnChange: TNotifyEvent; FOnChanging: TNotifyEvent; procedure ExchangeItems(Index1, Index2: Integer); procedure Grow; procedure QuickSort(L, R: Integer); procedure InsertItem(Index: Integer; const S: string); procedure SetSorted(Value: Boolean); protected procedure Changed; virtual; procedure Changing; virtual; function Get(Index: Integer): string; override; function GetCapacity: Integer; override; function GetCount: Integer; override; function GetObject(Index: Integer): TObject; override; procedure Put(Index: Integer; const S: string); override; procedure PutObject(Index: Integer; AObject: TObject); override; procedure SetCapacity(NewCapacity: Integer); override; procedure SetUpdateState(Updating: Boolean); override; public // GrowDelta: Integer; constructor Create; destructor Destroy; override; function Add(const S: string): Integer; override; procedure Clear; override; procedure Delete(Index: Integer); override; procedure Exchange(Index1, Index2: Integer); override; function Find(const S: string; var Index: Integer): Boolean; virtual; function IndexOf(const S: string): Integer; override; procedure Insert(Index: Integer; const S: string); override; procedure Sort; virtual; property Duplicates: TDuplicates read FDuplicates write FDuplicates; property Sorted: Boolean read FSorted write SetSorted; property OnChange: TNotifyEvent read FOnChange write FOnChange; property OnChanging: TNotifyEvent read FOnChanging write FOnChanging; end; implementation // TMyList constructor TMyList.Create; begin inherited; // GrowDelta:=DefaultGrowDelta; FCapacity:=0; FCount:=0; end; destructor TMyList.Destroy; begin Clear; inherited; end; function TMyList.Add(Item: Pointer): Integer; begin Result := FCount; if Result = FCapacity then Grow; FList^[Result] := Item; Inc(FCount); end; procedure TMyList.Clear; begin SetCount(0); SetCapacity(0); end; procedure TMyList.Delete(Index: Integer); begin if (Index < 0) or (Index >= FCount) then Error('', Index); Dec(FCount); if Index < FCount then System.Move(FList^[Index + 1], FList^[Index], (FCount - Index) * SizeOf(Pointer)); end; class procedure TMyList.Error(const Msg: string; Data: Integer); function ReturnAddr: Pointer; asm MOV EAX,[EBP+4] end; begin raise EListError.CreateFmt(Msg, [Data]) at ReturnAddr; end; procedure TMyList.Exchange(Index1, Index2: Integer); var Item: Pointer; begin if (Index1 < 0) or (Index1 >= FCount) then Error('', Index1); if (Index2 < 0) or (Index2 >= FCount) then Error('', Index2); Item := FList^[Index1]; FList^[Index1] := FList^[Index2]; FList^[Index2] := Item; end; function TMyList.Expand: TMyList; begin if FCount = FCapacity then Grow; Result := Self; end; function TMyList.First: Pointer; begin Result := Get(0); end; function TMyList.Get(Index: Integer): Pointer; begin if (Index < 0) or (Index >= FCount) then Error('', Index); Result := FList^[Index]; end; procedure TMyList.Grow; begin if FCapacity<64 then SetCapacity(FCapacity+8) else if FCapacity<256 then SetCapacity(FCapacity+32) else if FCapacity<1024 then SetCapacity(FCapacity+64) else SetCapacity(FCapacity+128); end; function TMyList.IndexOf(Item: Pointer): Integer; begin Result := 0; while (Result < FCount) and (FList^[Result] <> Item) do Inc(Result); if Result = FCount then Result := -1; end; procedure TMyList.Insert(Index: Integer; Item: Pointer); begin if (Index < 0) or (Index > FCount) then Error('', Index); if FCount = FCapacity then Grow; if Index < FCount then System.Move(FList^[Index], FList^[Index + 1], (FCount - Index) * SizeOf(Pointer)); FList^[Index] := Item; Inc(FCount); end; function TMyList.Last: Pointer; begin Result := Get(FCount - 1); end; procedure TMyList.Move(CurIndex, NewIndex: Integer); var Item: Pointer; begin if CurIndex <> NewIndex then begin if (NewIndex < 0) or (NewIndex >= FCount) then Error('', NewIndex); Item := Get(CurIndex); Delete(CurIndex); Insert(NewIndex, Item); end; end; procedure TMyList.Put(Index: Integer; Item: Pointer); begin if (Index < 0) or (Index >= FCount) then Error('', Index); FList^[Index] := Item; end; function TMyList.Remove(Item: Pointer): Integer; begin Result := IndexOf(Item); if Result <> -1 then Delete(Result); end; procedure TMyList.Pack; var I: Integer; begin for I := FCount - 1 downto 0 do if Items[I] = nil then Delete(I); end; procedure TMyList.SetCapacity(NewCapacity: Integer); begin if (NewCapacity < FCount) or (NewCapacity > MaxListSize) then Error('', NewCapacity); if NewCapacity <> FCapacity then begin ReallocMem(FList, NewCapacity * SizeOf(Pointer)); FCapacity := NewCapacity; end; end; procedure TMyList.SetCount(NewCount: Integer); begin if (NewCount < 0) or (NewCount > MaxListSize) then Error('', NewCount); if NewCount > FCapacity then SetCapacity(NewCount); if NewCount > FCount then FillChar(FList^[FCount], (NewCount - FCount) * SizeOf(Pointer), 0); FCount := NewCount; end; procedure QuickSort(SortList: PPointerList; L, R: Integer; SCompare: TListSortCompare); var I, J: Integer; P, T: Pointer; begin repeat I := L; J := R; P := SortList^[(L + R) shr 1]; repeat while SCompare(SortList^[I], P) < 0 do Inc(I); while SCompare(SortList^[J], P) > 0 do Dec(J); if I <= J then begin T := SortList^[I]; SortList^[I] := SortList^[J]; SortList^[J] := T; Inc(I); Dec(J); end; until I > J; if L < J then QuickSort(SortList, L, J, SCompare); L := I; until I >= R; end; procedure TMyList.Sort(Compare: TListSortCompare); begin if (FList <> nil) and (Count > 1) then QuickSort(FList, 0, Count - 1, Compare); end; /// TMyStrings destructor TMyStrings.Destroy; begin StringsAdapter := nil; inherited Destroy; end; function TMyStrings.Add(const S: string): Integer; begin Result := GetCount; Insert(Result, S); end; function TMyStrings.AddObject(const S: string; AObject: TObject): Integer; begin Result := Add(S); PutObject(Result, AObject); end; procedure TMyStrings.Append(const S: string); begin Add(S); end; procedure TMyStrings.AddStrings(Strings: TMyStrings); var I: Integer; begin BeginUpdate; try for I := 0 to Strings.Count - 1 do AddObject(Strings[I], Strings.Objects[I]); finally EndUpdate; end; end; procedure TMyStrings.Assign(Source: TPersistent); begin if Source is TMyStrings then begin BeginUpdate; try Clear; AddStrings(TMyStrings(Source)); finally EndUpdate; end; Exit; end; inherited Assign(Source); end; procedure TMyStrings.BeginUpdate; begin if FUpdateCount = 0 then SetUpdateState(True); Inc(FUpdateCount); end; procedure TMyStrings.DefineProperties(Filer: TFiler); function DoWrite: Boolean; begin if Filer.Ancestor <> nil then begin Result := True; if Filer.Ancestor is TMyStrings then Result := not Equals(TMyStrings(Filer.Ancestor)) end else Result := Count > 0; end; begin Filer.DefineProperty('Strings', ReadData, WriteData, DoWrite); end; procedure TMyStrings.EndUpdate; begin Dec(FUpdateCount); if FUpdateCount = 0 then SetUpdateState(False); end; function TMyStrings.Equals(Strings: TMyStrings): Boolean; var I, Count: Integer; begin Result := False; Count := GetCount; if Count <> Strings.GetCount then Exit; for I := 0 to Count - 1 do if Get(I) <> Strings.Get(I) then Exit; Result := True; end; procedure TMyStrings.Error(const Msg: string; Data: Integer); function ReturnAddr: Pointer; asm MOV EAX,[EBP+4] end; begin raise EStringListError.CreateFmt(Msg, [Data]) at ReturnAddr; end; procedure TMyStrings.Exchange(Index1, Index2: Integer); var TempObject: TObject; TempString: string; begin BeginUpdate; try TempString := Strings[Index1]; TempObject := Objects[Index1]; Strings[Index1] := Strings[Index2]; Objects[Index1] := Objects[Index2]; Strings[Index2] := TempString; Objects[Index2] := TempObject; finally EndUpdate; end; end; function TMyStrings.GetCapacity: Integer; begin // descendants may optionally override/replace this default implementation Result := Count; end; function TMyStrings.GetCommaText: string; var S: string; P: PChar; I, Count: Integer; begin Count := GetCount; if (Count = 1) and (Get(0) = '') then Result := '""' else begin Result := ''; for I := 0 to Count - 1 do begin S := Get(I); P := PChar(S); while not (P^ in [#0..' ','"',',']) do P := CharNext(P); if (P^ <> #0) then S := AnsiQuotedStr(S, '"'); Result := Result + S + ','; end; System.Delete(Result, Length(Result), 1); end; end; function TMyStrings.GetName(Index: Integer): string; var P: Integer; begin Result := Get(Index); P := AnsiPos('=', Result); if P <> 0 then SetLength(Result, P-1) else SetLength(Result, 0); end; function TMyStrings.GetObject(Index: Integer): TObject; begin Result := nil; end; function TMyStrings.GetText: PChar; begin Result := StrNew(PChar(GetTextStr)); end; function TMyStrings.GetTextStr: string; var I, L, Size, Count: Integer; P: PChar; S: string; begin Count := GetCount; Size := 0; for I := 0 to Count - 1 do Inc(Size, Length(Get(I)) + 2); SetString(Result, nil, Size); P := Pointer(Result); for I := 0 to Count - 1 do begin S := Get(I); L := Length(S); if L <> 0 then begin System.Move(Pointer(S)^, P^, L); Inc(P, L); end; P^ := #13; Inc(P); P^ := #10; Inc(P); end; end; function TMyStrings.GetValue(const Name: string): string; var I: Integer; begin I := IndexOfName(Name); if I >= 0 then Result := Copy(Get(I), Length(Name) + 2, MaxInt) else Result := ''; end; function TMyStrings.IndexOf(const S: string): Integer; begin for Result := 0 to GetCount - 1 do if AnsiCompareText(Get(Result), S) = 0 then Exit; Result := -1; end; function TMyStrings.IndexOfName(const Name: string): Integer; var P: Integer; S: string; begin for Result := 0 to GetCount - 1 do begin S := Get(Result); P := AnsiPos('=', S); if (P <> 0) and (AnsiCompareText(Copy(S, 1, P - 1), Name) = 0) then Exit; end; Result := -1; end; function TMyStrings.IndexOfObject(AObject: TObject): Integer; begin for Result := 0 to GetCount - 1 do if GetObject(Result) = AObject then Exit; Result := -1; end; procedure TMyStrings.InsertObject(Index: Integer; const S: string; AObject: TObject); begin Insert(Index, S); PutObject(Index, AObject); end; procedure TMyStrings.LoadFromFile(const FileName: string); var Stream: TStream; begin Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite); try LoadFromStream(Stream); finally Stream.Free; end; end; procedure TMyStrings.LoadFromStream(Stream: TStream); var Size: Integer; S: string; begin BeginUpdate; try Size := Stream.Size - Stream.Position; SetString(S, nil, Size); Stream.Read(Pointer(S)^, Size); SetTextStr(S); finally EndUpdate; end; end; procedure TMyStrings.Move(CurIndex, NewIndex: Integer); var TempObject: TObject; TempString: string; begin if CurIndex <> NewIndex then begin BeginUpdate; try TempString := Get(CurIndex); TempObject := GetObject(CurIndex); Delete(CurIndex); InsertObject(NewIndex, TempString, TempObject); finally EndUpdate; end; end; end; procedure TMyStrings.Put(Index: Integer; const S: string); var TempObject: TObject; begin TempObject := GetObject(Index); Delete(Index); InsertObject(Index, S, TempObject); end; procedure TMyStrings.PutObject(Index: Integer; AObject: TObject); begin end; procedure TMyStrings.ReadData(Reader: TReader); begin Reader.ReadListBegin; BeginUpdate; try Clear; while not Reader.EndOfList do Add(Reader.ReadString); finally EndUpdate; end; Reader.ReadListEnd; end; procedure TMyStrings.SaveToFile(const FileName: string); var Stream: TStream; begin Stream := TFileStream.Create(FileName, fmCreate); try SaveToStream(Stream); finally Stream.Free; end; end; procedure TMyStrings.SaveToStream(Stream: TStream); var S: string; begin S := GetTextStr; Stream.WriteBuffer(Pointer(S)^, Length(S)); end; procedure TMyStrings.SetCapacity(NewCapacity: Integer); begin // do nothing - descendants may optionally implement this method end; procedure TMyStrings.SetCommaText(const Value: string); var P, P1: PChar; S: string; begin BeginUpdate; try Clear; P := PChar(Value); while P^ in [#1..' '] do P := CharNext(P); while P^ <> #0 do begin if P^ = '"' then S := AnsiExtractQuotedStr(P, '"') else begin P1 := P; while (P^ > ' ') and (P^ <> ',') do P := CharNext(P); SetString(S, P1, P - P1); end; Add(S); while P^ in [#1..' '] do P := CharNext(P); if P^ = ',' then repeat P := CharNext(P); until not (P^ in [#1..' ']); end; finally EndUpdate; end; end; procedure TMyStrings.SetStringsAdapter(const Value: IStringsAdapter); begin if FAdapter <> nil then FAdapter.ReleaseStrings; FAdapter := Value; if FAdapter <> nil then FAdapter.ReferenceStrings(TStrings(Self)); end; procedure TMyStrings.SetText(Text: PChar); begin SetTextStr(Text); end; procedure TMyStrings.SetTextStr(const Value: string); var P, Start: PChar; S: string; begin BeginUpdate; try Clear; P := Pointer(Value); if P <> nil then while P^ <> #0 do begin Start := P; while not (P^ in [#0, #10, #13]) do Inc(P); SetString(S, Start, P - Start); Add(S); if P^ = #13 then Inc(P); if P^ = #10 then Inc(P); end; finally EndUpdate; end; end; procedure TMyStrings.SetUpdateState(Updating: Boolean); begin end; procedure TMyStrings.SetValue(const Name, Value: string); var I: Integer; begin I := IndexOfName(Name); if Value <> '' then begin if I < 0 then I := Add(''); Put(I, Name + '=' + Value); end else begin if I >= 0 then Delete(I); end; end; procedure TMyStrings.WriteData(Writer: TWriter); var I: Integer; begin Writer.WriteListBegin; for I := 0 to Count - 1 do Writer.WriteString(Get(I)); Writer.WriteListEnd; end; /////////////////////////7 TMyStringli constructor TMyStringList.Create; begin inherited; // GrowDelta:=DefaultGrowDelta; end; destructor TMyStringList.Destroy; begin FOnChange := nil; FOnChanging := nil; inherited Destroy; if FCount <> 0 then Finalize(FList^[0], FCount); FCount := 0; SetCapacity(0); end; function TMyStringList.Add(const S: string): Integer; begin if not Sorted then Result := FCount else if Find(S, Result) then case Duplicates of dupIgnore: Exit; dupError: Error('', 0); end; InsertItem(Result, S); end; procedure TMyStringList.Changed; begin if (FUpdateCount = 0) and Assigned(FOnChange) then FOnChange(Self); end; procedure TMyStringList.Changing; begin if (FUpdateCount = 0) and Assigned(FOnChanging) then FOnChanging(Self); end; procedure TMyStringList.Clear; begin if FCount <> 0 then begin Changing; Finalize(FList^[0], FCount); FCount := 0; SetCapacity(0); Changed; end; end; procedure TMyStringList.Delete(Index: Integer); begin if (Index < 0) or (Index >= FCount) then Error('', Index); Changing; Finalize(FList^[Index]); Dec(FCount); if Index < FCount then System.Move(FList^[Index + 1], FList^[Index], (FCount - Index) * SizeOf(TStringItem)); Changed; end; procedure TMyStringList.Exchange(Index1, Index2: Integer); begin if (Index1 < 0) or (Index1 >= FCount) then Error('', Index1); if (Index2 < 0) or (Index2 >= FCount) then Error('', Index2); Changing; ExchangeItems(Index1, Index2); Changed; end; procedure TMyStringList.ExchangeItems(Index1, Index2: Integer); var Temp: Integer; Item1, Item2: PStringItem; begin Item1 := @FList^[Index1]; Item2 := @FList^[Index2]; Temp := Integer(Item1^.FString); Integer(Item1^.FString) := Integer(Item2^.FString); Integer(Item2^.FString) := Temp; Temp := Integer(Item1^.FObject); Integer(Item1^.FObject) := Integer(Item2^.FObject); Integer(Item2^.FObject) := Temp; end; function TMyStringList.Find(const S: string; var Index: Integer): Boolean; var L, H, I, C: Integer; begin Result := False; L := 0; H := FCount - 1; while L <= H do begin I := (L + H) shr 1; C := AnsiCompareText(FList^[I].FString, S); if C < 0 then L := I + 1 else begin H := I - 1; if C = 0 then begin Result := True; if Duplicates <> dupAccept then L := I; end; end; end; Index := L; end; function TMyStringList.Get(Index: Integer): string; begin if (Index < 0) or (Index >= FCount) then Error('', Index); Result := FList^[Index].FString; end; function TMyStringList.GetCapacity: Integer; begin Result := FCapacity; end; function TMyStringList.GetCount: Integer; begin Result := FCount; end; function TMyStringList.GetObject(Index: Integer): TObject; begin if (Index < 0) or (Index >= FCount) then Error('', Index); Result := FList^[Index].FObject; end; procedure TMyStringList.Grow; begin if FCapacity<64 then SetCapacity(FCapacity+8) else if FCapacity<256 then SetCapacity(FCapacity+32) else if FCapacity<1024 then SetCapacity(FCapacity+64) else SetCapacity(FCapacity+128); end; function TMyStringList.IndexOf(const S: string): Integer; begin if not Sorted then Result := inherited IndexOf(S) else if not Find(S, Result) then Result := -1; end; procedure TMyStringList.Insert(Index: Integer; const S: string); begin if Sorted then Error('', 0); if (Index < 0) or (Index > FCount) then Error('', Index); InsertItem(Index, S); end; procedure TMyStringList.InsertItem(Index: Integer; const S: string); begin Changing; if FCount = FCapacity then Grow; if Index < FCount then System.Move(FList^[Index], FList^[Index + 1], (FCount - Index) * SizeOf(TStringItem)); with FList^[Index] do begin Pointer(FString) := nil; FObject := nil; FString := S; end; Inc(FCount); Changed; end; procedure TMyStringList.Put(Index: Integer; const S: string); begin if Sorted then Error('', 0); if (Index < 0) or (Index >= FCount) then Error('', Index); Changing; FList^[Index].FString := S; Changed; end; procedure TMyStringList.PutObject(Index: Integer; AObject: TObject); begin if (Index < 0) or (Index >= FCount) then Error('', Index); Changing; FList^[Index].FObject := AObject; Changed; end; procedure TMyStringList.QuickSort(L, R: Integer); var I, J: Integer; P: string; begin repeat I := L; J := R; P := FList^[(L + R) shr 1].FString; repeat while AnsiCompareText(FList^[I].FString, P) < 0 do Inc(I); while AnsiCompareText(FList^[J].FString, P) > 0 do Dec(J); if I <= J then begin ExchangeItems(I, J); Inc(I); Dec(J); end; until I > J; if L < J then QuickSort(L, J); L := I; until I >= R; end; procedure TMyStringList.SetCapacity(NewCapacity: Integer); begin ReallocMem(FList, NewCapacity * SizeOf(TStringItem)); FCapacity := NewCapacity; end; procedure TMyStringList.SetSorted(Value: Boolean); begin if FSorted <> Value then begin if Value then Sort; FSorted := Value; end; end; procedure TMyStringList.SetUpdateState(Updating: Boolean); begin if Updating then Changing else Changed; end; procedure TMyStringList.Sort; begin if not Sorted and (FCount > 1) then begin Changing; QuickSort(0, FCount - 1); Changed; end; end; end.
{******************************************************************************} { Ruler } { ----- } { } { Copyright © 2003-2005 Pieter Zijlstra } { } { A horizontal ruler component simular like the one used in Word(Pad). } { - Adjustable left and right margins. } { - Adjustable first, hanging, left and right indent markers. } { - Tabs can be added/removed at runtime and designtime. } { - Tabs support left, center, right, decimal and wordbar alignment when } { toAdvancedTabs is set in TabsSettings.Options. } { } { E-mail: p.zylstra@hccnet.nl } { Website: http://home.hccnet.nl/p.zylstra/ } {==============================================================================} { This software is FREEWARE } { ------------------------- } { } { You may freely use it in any software, including commercial software, but } { be-aware that the code is provided as-is, with no implied warranty. } {==============================================================================} { } { Notes: } { - This component uses different names for the same indentations: } { Indent-Left is for the visible part (eg Hint) called "hanging indent" and } { to make it more confusing, Indent-Both is called "left indent" (ala Word). } { } { - XP themes. } { - for D4-6 when using Mike Lischkes ThemeManager the ruler will paint its } { background using the parent when ParentColor := True. } { - for D7 set ParentBackGround to True so that the ruler use the parent's } { theme background to draw its own background. } { } { } { Version history: } { 0.9.9.0 11 feb 2003 - First public release (BETA) } { 0.9.9.1 27 may 2003 - Added property UnitsDisplay. } { - Based on comments of Andrew Fiddian-Green: } { - Removed RulerAdj (4/3) 'kludge' . } { - Property Pixels of TTab is now actual returning the } { number of pixels instead of points it was doing before } { whith the above mentioned (removed) RulerAdj 'kludge'. } { - Added new property TTab.Points. } { - Improved 3D look of the outline of the ruler. } { 1.0.0.0 14 jun 2003 - Draw default tab stops as little dot markers at the } { bottom of the ruler. } { - SnapToRuler for Tabs, Indents and Margins. } { - Adjustable margins (by dragging them). } { - Indent and Tab hints can be modified from the OI. } { 1.0.1.0 31 jul 2003 - Based on bug report by John Bennett: } { - SetFirstIndent sets the LeftIndent back to the } { original position when the FirstIndent is moved } { outside the margins and kept within margins by code. } { 1.0.2.0 29 oct 2003 - BugFix: } { - Left and RightMargin were not stored when they were } { set to zero in the OI. This default action (for some } { of the types) of Delphi is now overruled by using } { DefineProperties and separate readers and writers. } { 1.1.0.0 1 nov 2003 - New IndentOption, ioKeepWithinMargins. This one is } { set to True by default because this was (roughly) the } { default behaviour of the previous versions. BTW setting} { this option to False is not very usefull when using a } { standard TRichEdit. } { - Indents and Margins can no longer be dragged outside } { the paper-area. } { - The First/Left/Both idents can no longer be dragged } { closer then a 1/8 inch towards the RightIndent (and } { vice versa). } { - The LeftMargin can no longer be dragged closer then } { a 1/8 inch towards the RightMargin (and vice versa). } { - Added following procedures for use with TRVRuler } { DoRulerItemSelect(...); } { DoRulerItemMove(...) } { DoRulerItemRelease; } { - Made it compatible with D2 and D3 (and hopefully D4). } { 1.2.0.0 5 nov 2003 - Added new ruler units ruMillimeters, ruPicas, ruPixels } { and ruPoints. } { - Removed previous added DefineProperties (see v1.0.2.0) } { LeftMargin and RightMargin are now only set in the } { constructor when the Ruler is dropped on a component } { from within the IDE. } { - Improved ioKeepWithinMargins so that you can't drag the} { indents beyond the margins when this is option is set. } { - Improved handling of indents when dragging. The } { First/Left/Both indents are now kept separated from the} { Right indent. } { - Added MarginSettings.GripColor. It will only be painted} { when the color is not the same as the MarginColor or the} { RulerColor. } { - Added "DoubleBuffered" for Delphi versions below D4. } { - BugFix: Arrggh, forgot to set the Font of the Canvas. } { 1.2.1.0 6 nov 2003 - Changed compiler directives and the file-order of some } { record definitions for C++ Builder compatibility. } { 1.3.0.0 19 feb 2004 - BugFix: in SetUnitsProgram the conversion for ruPicas } { to other ruler units was missing. } { - New options to enable displaying of the last position } { of an item (only Indents) while it's being dragged. } { - When SnapToRuler is True and a tab is placed on the } { ruler by clicking on the empty ruler it will also be } { directly 'snapped' into the right place. } { - Register moved to RulersReg.pas } { ~ New TableEditor for TRichView (under construction). } { - RTL (beta) } { 1.3.0.1 20 feb 2004 - Left and RightMargin handling changed for RTL. } { Tabs are changed from LeftAligned to RightAligned when } { the BiDiMode has changed. } { 1.3.1.0 21 feb 2004 - Corrected RTL drawing of OutLine. } { - Corrected handling of Tabs in RTL mode. } { - Implemented ItemSeparation for RTL mode. } { - Also Tabs can display their last position while it's } { being dragged (set roItemsShowLastPos of Ruler.Options).} { - Added property BiDiModeRuler that can be used to force } { the ruler to use LTR or RTL independent of Delphi's } { build-in BiDiMode handling. } { 1.4.0.0 22 feb 2004 - Ruler goes vertical: } { - Added property RulerType } { - Added property TopMargin } { - Added property BottomMargin } { - Added 'specialised' component TVRuler which just sets} { the defaults for using the Ruler in vertical mode. } { - New property Flat } { - Property LeftInset is replaced by property Inset. } { 1.4.1.0 28 feb 2004 - Cleaning up (double) code. } { - Added property Zoom (in percentage, default is 100%). } { 1.4.2.0 29 feb 2004 - Scale will be drawn relative to the margin when } { roScaleRelativeToMargin is set. } { 1.5.0.0 23 mar 2004 - TableEditor for TRichView. } { - Made property ScreenRes writable (for TRichView) } { - Improved handling of the default printer/paper } { dimensions. In case the printer is not available } { (network disconnected) paper dimensions will use } { default "Letter" settings. } { 1.5.0.1 02 apr 2004 - Added property DefaultTabWidth. } { 1.5.0.2 04 apr 2004 - BugFix: Forgot to update DefaultTabWidth } { when UnitsProgram is changed. } { - Drawing of Tabs (and DefaultTabs) within table cells. } { - Limitted drag of columns/borders to neighbouring } { columns/borders. } { 1.6.0.0 12 apr 2004 - Added TableEditor.DraggedDelta. } { - Changed drawing of the margins a little when Flat is } { True. Also the Table graphics will be drawn flat now. } { - Table: Drag/Shift when VK_SHIFT is pressed. } { - BugFix: KeepDragWithinPageArea did not function } { correctly in RTL mode. } { - BugFix: KeepColumnsSeparated did not function } { correctly in RTL mode. } { 1.6.1.0 13 apr 2004 - BugFix: When DefaultTabWidth did not have a valid } { value (it should be >0) it would cause the } { drawing routines to go into an endless loop. } { 1.7.0.0 19 dec 2004 - Added the basics for Bullets & Numbering for TRichView.} { 1.7.1.0 21 apr 2005 - Improved drawing for themed applications, background } { did not show correctly on for instance PageControls. } { (thanks to Alexander Halser for fixing this). } { 1.7.2.0 01 may 2005 - BugFix: The first time the position was calculated for } { a tab when adding tabs did not take the margin } { into account. } { - Default tabs are no longer drawn by default before the } { LeftIndent. If you want them back you can turn off } { toDontShowDefaultTabsBeforeLeftIndent of } { TabSettings.Options. } { 1.7.3.0 14 may 2005 - BugFix: The Font could be modified by themed drawing } { The Canvas is now forced to (re)create its } { drawing objects (Brush, Font, Pen). } {******************************************************************************} unit Ruler; {$B-} interface {$I CompVers.inc} uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, ExtCtrls, Menus; type TRulerType = ( rtHorizontal, rtVertical ); TTabAlign = ( taLeftAlign, taCenterAlign, taRightAlign, taDecimalAlign, taWordBarAlign ); TIndentGraphic = ( igNone, igUp, igDown, igRectangle, igLevelDec1, igLevelDec2, igLevelInc1, igLevelInc2 ); TIndentType = ( itBoth, // just to move both first and left indent sliders. itFirst, // relative to left margin itLeft, // relative to first indent itRight ); TLevelType = ( ltLevelDec, ltLevelInc ); TMarginType = ( mtTop, mtBottom, mtLeft, mtRight ); TBiDiModeRuler = ( bmUseBiDiMode, bmLeftToRight, bmRightToLeft ); TRulerUnits = ( ruInches, ruCentimeters, ruMillimeters, ruPicas, ruPixels, ruPoints ); THitItem = ( hiNone, hiOnTab, hiOnBothIndent, hiOnFirstIndent, hiOnLeftIndent, hiOnRightIndent, hiOnTopMargin, hiOnBottomMargin, hiOnLeftMargin, hiOnRightMargin, hiOnColumn, hiOnLeftBorder, hiOnRightBorder, hiOnLevelDec, hiOnLevelInc ); THitItems = set of THitItem; TDragItem = ( diNone, diBorder, diColumn, diIndent, diMargin, diTab ); TTableGraphic = ( tgNone, tgBorder, tgColumn ); TBorderType = ( btLeft, btRight ); TTablePosition = ( tpAbsolute, tpFromFirstIndent, tpFromLeftIndent, tpFromMargin ); TIndentOption = ( ioExtraShadow, ioKeepWithinMargins, ioShowFirstIndent, ioShowHangingIndent, ioShowLeftIndent, ioShowRightIndent, ioSnapToRuler ); TIndentOptions = set of TIndentOption; TLevelGraphic = ( lgType1, lgType2 ); TListEditorOption = ( leoAdjustable, leoLevelAdjustable ); TListEditorOptions = set of TListEditorOption; TMarginOption = ( moAdjustable, moSnapToRuler ); TMarginOptions = set of TMarginOption; TRulerOption = ( roAutoUpdatePrinterWidth, roItemsShowLastPos, roUseDefaultPrinterWidth, roScaleRelativeToMargin ); TRulerOptions = set of TRulerOption; TTabOption = ( toAdvancedTabs, toShowDefaultTabs, toSnapToRuler, toDontShowDefaultTabsBeforeLeftIndent ); TTabOptions = set of TTabOption; TTableEditorOption = ( teoAdjustable, teoSnapToRuler ); TTableEditorOptions = set of TTableEditorOption; TTableEditorVisible = ( tevNever, tevOnlyWhenActive ); TZoomRange = 1..10000; // 1% - 10000% const AllBorders: THitItems = [hiOnLeftBorder..hiOnRightBorder]; AllIndents: THitItems = [hiOnBothIndent..hiOnRightIndent]; AllLevels: THitItems = [hiOnLevelDec..hiOnLevelInc]; AllMargins: THitItems = [hiOnTopMargin..hiOnRightMargin]; AllTable: THitItems = [hiOnColumn, hiOnLeftBorder..hiOnRightBorder]; AllTabs: THitItems = [hiOnTab]; DefaultIndentOptions = [ioKeepWithinMargins, ioShowFirstIndent, ioShowHangingIndent, ioShowLeftIndent, ioShowRightIndent]; DefaultListOptions = [leoAdjustable, leoLevelAdjustable]; DefaultMarginOptions = [moAdjustable]; DefaultRulerOptions = [roUseDefaultPrinterWidth]; DefaultTableOptions = [teoAdjustable]; DefaultTabOptions = [toShowDefaultTabs, toDontShowDefaultTabsBeforeLeftIndent]; type TDragInfo = record Item: TDragItem; Index: Integer; Offset: Integer; end; THitInfo = record Index: Integer; HitItems: THitItems; end; TIndent = record Graphic: TIndentGraphic; Left: Integer; Position: Extended; Top: Integer; end; TMargin = record Grip: Integer; Position: Extended; end; TTableBorder = record Left: Integer; Position: Extended; end; TIndentArray = array[TIndentType] of TIndent; TCustomRuler = class; TTab = class(TCollectionItem) private FAlign: TTabAlign; FColor: TColor; FDeleting: Boolean; FLeft: Integer; FPosition: Extended; FTop: Integer; function GetPixels: Extended; function GetPoints: Extended; function GetRTLAlign: TTabAlign; procedure SetAlign(const Value: TTabAlign); procedure SetColor(const Value: TColor); procedure SetPosition(const Value: Extended); procedure SetPixels(const Value: Extended); procedure SetPoints(const Value: Extended); protected property Pixels: Extended read GetPixels write SetPixels; property RTLAlign: TTabAlign read GetRTLAlign; public constructor Create(Collection: TCollection); override; procedure AssignTo(Dest: TPersistent); override; property Left: Integer read FLeft write FLeft; property Points: Extended read GetPoints write SetPoints; property Top: Integer read FTop write FTop; published property Align: TTabAlign read FAlign write SetAlign; property Color: TColor read FColor write SetColor; property Position: Extended read FPosition write SetPosition; end; TTabs = class(TCollection) private FBlockDoTabChanged: Boolean; FRuler: TCustomRuler; function GetTab(Index: Integer): TTab; procedure SetTab(Index: Integer; const Value: TTab); protected {$IFDEF COMPILER35_UP} function GetOwner: TPersistent; override; {$ELSE} function GetOwner: TPersistent; {$ENDIF} procedure SortTabs; procedure Update(Item: TCollectionItem); override; public constructor Create(Ruler: TCustomRuler); function Add: TTab; property Items[Index: Integer]: TTab read GetTab write SetTab; default; property Ruler: TCustomRuler read FRuler; end; TRulerCell = class(TCollectionItem) private FCellWidth: Extended; FDragBoundary: Extended; FFirstIndent: Extended; FLeft: Integer; FLeftIndent: Extended; FRightIndent: Extended; function GetDragLimit: Integer; function GetPosition: Extended; procedure SetCellWidth(const Value: Extended); procedure SetDragBoundary(const Value: Extended); procedure SetLeft(const Value: Integer); procedure SetPosition(const Value: Extended); protected property DragLimit: Integer read GetDragLimit; property FirstIndent: Extended read FFirstIndent write FFirstIndent; property Left: Integer read FLeft write SetLeft; property LeftIndent: Extended read FLeftIndent write FLeftIndent; property Position: Extended read GetPosition write SetPosition; property RightIndent: Extended read FRightIndent write FRightIndent; public constructor Create(Collection: TCollection); override; property DragBoundary: Extended read FDragBoundary write SetDragBoundary; published property CellWidth: Extended read FCellWidth write SetCellWidth; end; TRulerCells = class(TCollection) private FRuler: TCustomRuler; function GetCell(Index: Integer): TRulerCell; procedure SetCell(Index: Integer; const Value: TRulerCell); protected {$IFDEF COMPILER35_UP} function GetOwner: TPersistent; override; {$ELSE} function GetOwner: TPersistent; {$ENDIF} procedure Update(Item: TCollectionItem); override; public constructor Create(AOwner: TCustomRuler); function Add: TRulerCell; property Items[Index: Integer]: TRulerCell read GetCell write SetCell; default; property Ruler: TCustomRuler read FRuler; end; TRulerListEditor = class(TPersistent) private FActive: Boolean; FLevelGraphic: TLevelGraphic; FListLevel: Integer; FOptions: TListEditorOptions; FOwner: TCustomRuler; procedure SetOptions(const Value: TListEditorOptions); procedure SetActive(const Value: Boolean); procedure SetLevelGraphic(const Value: TLevelGraphic); protected {$IFDEF COMPILER35_UP} function GetOwner: TPersistent; override; {$ELSE} function GetOwner: TPersistent; {$ENDIF} procedure Invalidate; public constructor Create(AOwner: TCustomRuler); virtual; property Active: Boolean read FActive write SetActive; property ListLevel: Integer read FListLevel write FListLevel; property Ruler: TCustomRuler read FOwner; published property LevelGraphic: TLevelGraphic read FLevelGraphic write SetLevelGraphic default lgType1; property Options: TListEditorOptions read FOptions write SetOptions default DefaultListOptions; end; TRulerTableEditor = class(TPersistent) private FActive: Boolean; FBackGroundColor: TColor; FBorders: array[TBorderType] of TTableBorder; FBorderHSpacing: Extended; FBorderWidth: Extended; FCellPadding: Extended; FCellBorderWidth: Extended; FCellHSpacing: Extended; FCellIndex: Integer; FDragCursor: TCursor; FDraggedColumn: Integer; FDraggedDelta: Extended; FDraggedWithShift: Boolean; FDragLast: Integer; FDragStart: Integer; FFirstIndent: Extended; FForeGroundColor: TColor; FLeftIndent: Extended; FOptions: TTableEditorOptions; FOwner: TCustomRuler; FRightIndent: Extended; FRulerCells: TRulerCells; FRulerIndents: TIndentArray; // Used to store a temporary copy. FTablePosition: TTablePosition; FUseDragBoundaries: Boolean; FVisible: TTableEditorVisible; function GetBorderRect(const BorderType: TBorderType): TRect; function GetCellRect(const Index: Integer): TRect; function GetColumnIndexAt(const X, Y: Integer): Integer; function GetNextValidCell(const Index: Integer): Integer; function GetOffset: Integer; function GetPrevValidCell(const Index: Integer): Integer; function GetTableLeft: Extended; function GetTableWidth: Extended; function GetTotalCellSpacing(const FromBorder, FromLeft: Boolean): Integer; function KeepColumnsSeparated(const Index, Left: Integer): Integer; function KeepWithinCurrentCell(const IT: TIndentType; const X: Integer): Integer; function LastValidCellIndex: Integer; function RTLAdjust(X, Offset: Integer): Integer; procedure SetActive(const Value: Boolean); procedure SetBackGroundColor(const Value: TColor); procedure SetBorderHSpacing(const Value: Extended); procedure SetBorderWidth(const Value: Extended); procedure SetCellBorderWidth(const Value: Extended); procedure SetCellHSpacing(const Value: Extended); procedure SetCellIndex(const Value: Integer); procedure SetCellPading(const Value: Extended); procedure SetDragCursor(const Value: TCursor); procedure SetFirstIndent(const Value: Extended); procedure SetForeGroundColor(const Value: TColor); procedure SetLeftIndent(const Value: Extended); procedure SetOptions(const Value: TTableEditorOptions); procedure SetRightIndent(const Value: Extended); procedure SetRulerCells(const Value: TRulerCells); procedure SetTableLeft(const Value: Extended); procedure SetTableWidth(const Value: Extended); procedure SetTablePosition(const Value: TTablePosition); procedure SetVisible(const Value: TTableEditorVisible); procedure UpdateIndentPosition(const IT: TIndentType; const XPos: Integer); protected function CalculateCurrentIndentPosition(const IT: TIndentType): Integer; {$IFDEF COMPILER35_UP} function GetOwner: TPersistent; override; {$ELSE} function GetOwner: TPersistent; {$ENDIF} procedure Invalidate; property Offset: Integer read GetOffset; public constructor Create(AOwner: TCustomRuler); virtual; destructor Destroy; override; property DraggedColumn: Integer read FDraggedColumn; property DraggedDelta: Extended read FDraggedDelta; property DraggedWithShift: Boolean read FDraggedWithShift; property Ruler: TCustomRuler read FOwner; property UseDragBoundaries: Boolean read FUseDragBoundaries write FUseDragBoundaries; published property Active: Boolean read FActive write SetActive; property BackGroundColor: TColor read FBackGroundColor write SetBackGroundColor default clBtnFace; property BorderHSpacing: Extended read FBorderHSpacing write SetBorderHSpacing; property BorderWidth: Extended read FBorderWidth write SetBorderWidth; property CellBorderWidth: Extended read FCellBorderWidth write SetCellBorderWidth; property CellHSpacing: Extended read FCellHSpacing write SetCellHSpacing; property CellIndex: Integer read FCellIndex write SetCellIndex; property CellPadding: Extended read FCellPadding write SetCellPading; property Cells: TRulerCells read FRulerCells write SetRulerCells; property DragCursor: TCursor read FDragCursor write SetDragCursor default crHSplit; property FirstIndent: Extended read FFirstIndent write SetFirstIndent; property ForeGroundColor: TColor read FForeGroundColor write SetForeGroundColor default clBtnShadow; property LeftIndent: Extended read FLeftIndent write SetLeftIndent; property Options: TTableEditorOptions read FOptions write SetOptions default DefaultTableOptions; property RightIndent: Extended read FRightIndent write SetRightIndent; property TableLeft: Extended read GetTableLeft write SetTableLeft; property TablePosition: TTablePosition read FTablePosition write SetTablePosition default tpFromMargin; property TableWidth: Extended read GetTableWidth write SetTableWidth; property Visible: TTableEditorVisible read FVisible write SetVisible default tevOnlyWhenActive; end; TIndentSettings = class(TPersistent) private FDragCursor: TCursor; FOptions: TIndentOptions; FOwner: TCustomRuler; procedure SetDragCursor(const Value: TCursor); procedure SetOptions(const Value: TIndentOptions); public constructor Create(AOwner: TCustomRuler); virtual; procedure AssignTo(Dest: TPersistent); override; property Owner: TCustomRuler read FOwner; published property DragCursor: TCursor read FDragCursor write SetDragCursor default crDrag; property Options: TIndentOptions read FOptions write SetOptions default DefaultIndentOptions; end; TMarginSettings = class(TPersistent) private FDragCursor: TCursor; FGripColor: TColor; FOptions: TMarginOptions; FOwner: TCustomRuler; procedure SetDragCursor(const Value: TCursor); procedure SetOptions(const Value: TMarginOptions); procedure SetGripColor(const Value: TColor); public constructor Create(AOwner: TCustomRuler); virtual; procedure AssignTo(Dest: TPersistent); override; property Owner: TCustomRuler read FOwner; published property DragCursor: TCursor read FDragCursor write SetDragCursor default crSizeWE; property GripColor: TColor read FGripColor write SetGripColor default clBtnShadow; property Options: TMarginOptions read FOptions write SetOptions default DefaultMarginOptions; end; TTabSettings = class(TPersistent) private FDeleteCursor: TCursor; FDragCursor: TCursor; FOptions: TTabOptions; FOwner: TCustomRuler; procedure SetDeleteCursor(const Value: TCursor); procedure SetDragCursor(const Value: TCursor); procedure SetOptions(const Value: TTabOptions); public constructor Create(AOwner: TCustomRuler); virtual; procedure AssignTo(Dest: TPersistent); override; property Owner: TCustomRuler read FOwner; published property DeleteCursor: TCursor read FDeleteCursor write SetDeleteCursor default crNone; property DragCursor: TCursor read FDragCursor write SetDragCursor default crDrag; property Options: TTabOptions read FOptions write SetOptions default DefaultTabOptions; end; TRulerTexts = class(TPersistent) private FHintColumnMove: string; FHintIndentFirst: string; FHintIndentLeft: string; FHintIndentHanging: string; FHintIndentRight: string; FHintLevelDec: string; FHintLevelInc: string; FHintTabCenter: string; FHintTabDecimal: string; FHintTabLeft: string; FHintTabRight: string; FHintTabWordBar: string; FMenuTabCenter: string; FMenuTabDecimal: string; FMenuTabLeft: string; FMenuTabRight: string; FMenuTabWordBar: string; FRuler: TCustomRuler; procedure SetHintColumnMove(const Value: string); procedure SetHintIndentFirst(const Value: string); procedure SetHintIndentHanging(const Value: string); procedure SetHintIndentLeft(const Value: string); procedure SetHintIndentRight(const Value: string); procedure SetHintLevelDec(const Value: string); procedure SetHintLevelInc(const Value: string); procedure SetHintTabCenter(const Value: string); procedure SetHintTabDecimal(const Value: string); procedure SetHintTabLeft(const Value: string); procedure SetHintTabRight(const Value: string); procedure SetHintTabWordBar(const Value: string); procedure SetMenuTabCenter(const Value: string); procedure SetMenuTabDecimal(const Value: string); procedure SetMenuTabLeft(const Value: string); procedure SetMenuTabRight(const Value: string); procedure SetMenuTabWordBar(const Value: string); public constructor Create(AOwner: TCustomRuler); virtual; published property HintColumnMove: string read FHintColumnMove write SetHintColumnMove; property HintIndentFirst: string read FHintIndentFirst write SetHintIndentFirst; property HintIndentLeft: string read FHintIndentLeft write SetHintIndentLeft; property HintIndentHanging: string read FHintIndentHanging write SetHintIndentHanging; property HintIndentRight: string read FHintIndentRight write SetHintIndentRight; property HintLevelDec: string read FHintLevelDec write SetHintLevelDec; property HintLevelInc: string read FHintLevelInc write SetHintLevelInc; property HintTabCenter: string read FHintTabCenter write SetHintTabCenter; property HintTabDecimal: string read FHintTabDecimal write SetHintTabDecimal; property HintTabLeft: string read FHintTabLeft write SetHintTabLeft; property HintTabRight: string read FHintTabRight write SetHintTabRight; property HintTabWordBar: string read FHintTabWordBar write SetHintTabWordBar; property MenuTabCenter: string read FMenuTabCenter write SetMenuTabCenter; property MenuTabDecimal: string read FMenuTabDecimal write SetMenuTabDecimal; property MenuTabLeft: string read FMenuTabLeft write SetMenuTabLeft; property MenuTabRight: string read FMenuTabRight write SetMenuTabRight; property MenuTabWordBar: string read FMenuTabWordBar write SetMenuTabWordBar; end; TRulerItemClickEvent = procedure(Sender: TObject; X: Integer) of object; TRulerItemMoveEvent = procedure(Sender: TObject; X: Integer; Removing: Boolean) of object; TCustomRuler = class(TCustomControl) private FBiDiModeRuler: TBiDiModeRuler; FDefaultTabWidth: Extended; FDiff: Integer; FDragInfo: TDragInfo; FFlat: Boolean; FIndents: TIndentArray; FIndentSettings: TIndentSettings; FIndentTraces: TIndentArray; FInset: Integer; FItemSeparation: Integer; FListEditor: TRulerListEditor; FMargins: array[TMarginType] of TMargin; FMarginSettings: TMarginSettings; FMarginColor: TColor; FMaxTabs: Integer; FMultiPixels: Extended; FMultiPoints: Extended; {$IFDEF COMPILER7_UP} FOldParentBackground: Boolean; {$ENDIF} FOldShowHint: Boolean; FOnBiDiModeChanged: TNotifyEvent; FOnIndentChanged: TNotifyEvent; FOnMarginChanged: TNotifyEvent; FOnRulerItemMove: TRulerItemMoveEvent; FOnRulerItemRelease: TNotifyEvent; FOnRulerItemSelect: TRulerItemClickEvent; FOnTabChanged: TNotifyEvent; FOnTableColumnChanged: TNotifyEvent; FOrgHint: string; FOvrHint: Boolean; FPageHeight: Extended; FPageWidth: Extended; FPopupMenu: TPopupMenu; FPrinterHeight: Extended; FPrinterWidth: Extended; FRulerColor: TColor; FRulerOptions: TRulerOptions; FRulerTexts: TRulerTexts; FRulerType: TRulerType; FScreenRes: Integer; FTableEditor: TRulerTableEditor; FTabs: TTabs; FTabSettings: TTabSettings; FTabTrace: TTab; FTimer: TTimer; FUnitsDisplay: TRulerUnits; FUnitsProgram: TRulerUnits; FZoom: TZoomRange; procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED; function GetBottomMargin: Extended; function GetDefaultTabWidth: Extended; function GetEndMargin: Extended; function GetEndMarginGrip: Integer; function GetFirstIndent: Extended; function GetIndentRect(IndentType: TIndentType): TRect; function GetLeftIndent: Extended; function GetLeftMargin: Extended; function GetLevelRect(LevelType: TLevelType): TRect; function GetMarginGripRect(MarginType: TMarginType): TRect; function GetMarginRect(MarginType: TMarginType): TRect; function GetRightIndent: Extended; function GetRightMargin: Extended; function GetStartMargin: Extended; function GetStartMarginGrip: Integer; function GetTabIndexAt(X, Y: Integer): Integer; function GetTopMargin: Extended; function HitItemsToIndex(HitItems: THitItems): Integer; procedure PaintHDefaultTabs(Canvas: TCanvas; R: TRect); procedure PaintHIndent(Canvas: TCanvas; Graphic: TIndentGraphic; X, Y: Integer; HighLight, ExtraShadow, Dimmed: Boolean); procedure PaintHIndents(Canvas: TCanvas; R: TRect); procedure PaintHMargins(Canvas: TCanvas; R: TRect); procedure PaintHMarkers(Canvas: TCanvas; R: TRect); procedure PaintHOutline(Canvas: TCanvas; R: TRect); procedure PaintHTab(Canvas: TCanvas; Graphic: TTabAlign; X, Y: Integer); procedure PaintHTableGraphic(Canvas: TCanvas; Graphic: TTableGraphic; R: TRect); procedure PaintHTableGraphics(Canvas: TCanvas; R: TRect); procedure PaintHTabs(Canvas: TCanvas; R: TRect); procedure PaintVMargins(Canvas: TCanvas; R: TRect); procedure PaintVMarkers(Canvas: TCanvas; R: TRect); procedure PaintVOutline(Canvas: TCanvas; R: TRect); procedure ProcessParentBackground(B: Boolean); function RTLAdjust(X, Offset: Integer): Integer; function RTLAdjustRect(const R: TRect): TRect; procedure SetBiDiModeRuler(const Value: TBiDiModeRuler); procedure SetBottomMargin(Value: Extended); procedure SetDefaultTabWidth(const Value: Extended); procedure SetFirstIndent(Value: Extended); procedure SetFlat(const Value: Boolean); procedure SetIndentSettings(const Value: TIndentSettings); procedure SetInset(const Value: Integer); procedure SetItemSeparation(const Value: Integer); procedure SetLeftIndent(Value: Extended); procedure SetLeftMargin(Value: Extended); procedure SetListEditor(const Value: TRulerListEditor); procedure SetMarginColor(const Value: TColor); procedure SetMarginSettings(const Value: TMarginSettings); procedure SetMaxTabs(const Value: Integer); procedure SetPageHeight(const Value: Extended); procedure SetPageWidth(const Value: Extended); procedure SetRightIndent(Value: Extended); procedure SetRightMargin(Value: Extended); procedure SetRulerColor(const Value: TColor); procedure SetRulerOptions(const Value: TRulerOptions); procedure SetRulerTexts(const Value: TRulerTexts); procedure SetRulerType(const Value: TRulerType); procedure SetScreenRes(const Value: Integer); procedure SetTableEditor(const Value: TRulerTableEditor); procedure SetTabs(const Value: TTabs); procedure SetTabSettings(const Value: TTabSettings); procedure SetTopMargin(Value: Extended); procedure SetUnitsDisplay(const Value: TRulerUnits); procedure SetUnitsProgram(const Value: TRulerUnits); procedure SetZoom(const Value: TZoomRange); procedure TimerProc(Sender: TObject); protected procedure DoBiDiModeChanged; dynamic; procedure DoIndentChanged; dynamic; procedure DoLevelButtonDown(Direction: Integer); dynamic; procedure DoLevelButtonUp(Direction: Integer); dynamic; procedure DoMarginChanged; dynamic; procedure DoRulerItemMove(X: Integer; Removing: Boolean); dynamic; procedure DoRulerItemRelease; dynamic; procedure DoRulerItemSelect(X: Integer); dynamic; procedure DoTabChanged; dynamic; procedure DoTableColumnChanged; dynamic; function GetClosestOnRuler(X: Integer; FromMargin: Boolean): Integer; procedure Loaded; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseMove(Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure OverrideHint(NewHint: string); procedure Paint; override; procedure PaintHorizontalRuler(Canvas: TCanvas); procedure PaintVerticalRuler(Canvas: TCanvas); function PointsToUnits(const Value: Extended): Extended; procedure PopupClick(Sender: TObject); procedure RestoreHint; function UnitsPerInch(Units: TRulerUnits): Extended; function UnitsToPoints(const Value: Extended): Extended; procedure UpdatePageDimensions; virtual; function UseRTL: Boolean; virtual; function ZoomAndRound(const Value: Extended): Integer; function ZPixsToUnits(const Value: Extended): Extended; function ZUnitsToPixs(const Value: Extended): Extended; property BiDiModeRuler: TBiDiModeRuler read FBiDiModeRuler write SetBiDiModeRuler default bmUseBiDiMode; property BottomMargin: Extended read GetBottomMargin write SetBottomMargin; property DefaultTabWidth: Extended read GetDefaultTabWidth write SetDefaultTabWidth; property EndMargin: Extended read GetEndMargin; property EndMarginGrip: Integer read GetEndMarginGrip; property FirstIndent: Extended read GetFirstIndent write SetFirstIndent; property Flat: Boolean read FFlat write SetFlat; property IndentSettings: TIndentSettings read FIndentSettings write SetIndentSettings; property Inset: Integer read FInset write SetInset default 10; property ItemSeparation: Integer read FItemSeparation write SetItemSeparation; property LeftIndent: Extended read GetLeftIndent write SetLeftIndent; property LeftMargin: Extended read GetLeftMargin write SetLeftMargin; property ListEditor: TRulerListEditor read FListEditor write SetListEditor; property MarginColor: TColor read FMarginColor write SetMarginColor default clInfoBk; property MarginSettings: TMarginSettings read FMarginSettings write SetMarginSettings; property MaxTabs: Integer read FMaxTabs write SetMaxTabs default 32; property OnBiDiModeChanged: TNotifyEvent read FOnBiDiModeChanged write FOnBiDiModeChanged; property OnIndentChanged: TNotifyEvent read FOnIndentChanged write FOnIndentChanged; property OnMarginChanged: TNotifyEvent read FOnMarginChanged write FOnMarginChanged; property OnRulerItemMove: TRulerItemMoveEvent read FOnRulerItemMove write FOnRulerItemMove; property OnRulerItemRelease: TNotifyEvent read FOnRulerItemRelease write FOnRulerItemRelease; property OnRulerItemSelect: TRulerItemClickEvent read FOnRulerItemSelect write FOnRulerItemSelect; property OnTabChanged: TNotifyEvent read FOnTabChanged write FOnTabChanged; property OnTableColumnChanged: TNotifyEvent read FOnTableColumnChanged write FOnTableColumnChanged; property Options: TRulerOptions read FRulerOptions write SetRulerOptions default DefaultRulerOptions; property RightIndent: Extended read GetRightIndent write SetRightIndent; property RightMargin: Extended read GetRightMargin write SetRightMargin; property RulerColor: TColor read FRulerColor write SetRulerColor default clWindow; property RulerTexts: TRulerTexts read FRulerTexts write SetRulerTexts; property RulerType: TRulerType read FRulerType write SetRulerType default rtHorizontal; property StartMargin: Extended read GetStartMargin; property StartMarginGrip: Integer read GetStartMarginGrip; property TableEditor: TRulerTableEditor read FTableEditor write SetTableEditor; property Tabs: TTabs read FTabs write SetTabs; property TabSettings: TTabSettings read FTabSettings write SetTabSettings; property TopMargin: Extended read GetTopMargin write SetTopMargin; property UnitsDisplay: TRulerUnits read FUnitsDisplay write SetUnitsDisplay default ruCentimeters; property UnitsProgram: TRulerUnits read FUnitsProgram write SetUnitsProgram default ruCentimeters; property Zoom: TZoomRange read FZoom write SetZoom default 100; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure AddRichEdit98Tab(const Value: Extended; Alignment: TTabAlign); function GetHitTestInfoAt(X, Y: Integer): THitInfo; property MultiPixels: Extended read FMultiPixels; property MultiPoints: Extended read FMultiPoints; property PageHeight: Extended read FPageHeight write SetPageHeight; property PageWidth: Extended read FPageWidth write SetPageWidth; function PixsToUnits(const Value: Extended): Extended; function UnitsToPixs(const Value: Extended): Extended; property ScreenRes: Integer read FScreenRes write SetScreenRes; end; TRuler = class(TCustomRuler) published property Align; {$IFDEF COMPILER4_UP} property Anchors; property BiDiMode; property Constraints; property DragKind; {$ENDIF} property BiDiModeRuler; property BottomMargin; property Color; property DefaultTabWidth; property DragCursor; property DragMode; property Enabled; property FirstIndent; property Flat; property Font; property Hint; property IndentSettings; property Inset; property LeftIndent; property LeftMargin; property MarginColor; property MarginSettings; property MaxTabs; property OnBiDiModeChanged; property OnClick; {$IFDEF COMPILER5_UP} property OnContextPopup; {$ENDIF} property OnDblClick; property OnDragDrop; property OnDragOver; {$IFDEF COMPILER4_UP} property OnEndDock; {$ENDIF} property OnEndDrag; property OnIndentChanged; property OnMarginChanged; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnRulerItemMove; property OnRulerItemRelease; property OnRulerItemSelect; {$IFDEF COMPILER4_UP} property OnStartDock; {$ENDIF} property OnStartDrag; property OnTabChanged; property OnTableColumnChanged; property Options; {$IFDEF COMPILER7_UP} property ParentBackground; {$ENDIF} {$IFDEF COMPILER4_UP} property ParentBiDiMode; {$ENDIF} property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property RightIndent; property RightMargin; property RulerColor; property RulerTexts; property RulerType; property ShowHint; property Tabs; property TabSettings; property TopMargin; property Visible; property UnitsDisplay; property UnitsProgram; property Zoom; end; TVRuler = class(TCustomRuler) public constructor Create(AOwner: TComponent); override; property MaxTabs default 0; property RulerType default rtVertical; published property Align; {$IFDEF COMPILER4_UP} property Anchors; property Constraints; property DragKind; {$ENDIF} property BottomMargin; property Color; property DragCursor; property DragMode; property Enabled; property Flat; property Font; property Hint; property Inset; property MarginColor; property MarginSettings; property OnBiDiModeChanged; property OnClick; {$IFDEF COMPILER5_UP} property OnContextPopup; {$ENDIF} property OnDblClick; property OnDragDrop; property OnDragOver; {$IFDEF COMPILER4_UP} property OnEndDock; {$ENDIF} property OnEndDrag; property OnMarginChanged; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnRulerItemMove; property OnRulerItemRelease; property OnRulerItemSelect; {$IFDEF COMPILER4_UP} property OnStartDock; {$ENDIF} property OnStartDrag; property Options; {$IFDEF COMPILER7_UP} property ParentBackground; {$ENDIF} property ParentColor; property ParentFont; property ParentShowHint; property PopupMenu; property RulerColor; property ShowHint; property TopMargin; property Visible; property UnitsDisplay; property UnitsProgram; property Zoom; end; implementation uses Printers; const cmPerInch = 2.54; mmPerInch = 25.4; PicasPerInch = 6; PointsPerInch = 72; // Determines the increments in which the numbers should be displayed. NumberIncrements: array[TRulerUnits] of Integer = (1, 1, 20, 6, 100, 36); // Determines the increments in which the markers should be displayed. MarkerIncrements: array[TRulerUnits] of Extended = (1/8, 0.25, 2.5, 1, 10, 6); // Determines the number of dot markers between Numbers and Markers. DotMarkers: array[TRulerUnits] of Integer = (3, 1, 3, 2, 4, 2); // Used for "SnapToRuler" GridSteps: array[TRulerUnits] of Extended = (1/16, 0.25, 2.5, 0.5, 5, 6); BorderOffset: Integer = 4; ColumnOffset: Integer = 4; IndentOffset: Integer = 4; TabOffset: array[TTabAlign] of Integer = (0, 3, 4, 3, 3); function IMax(A, B: Integer): Integer; begin if A > B then Result := A else Result := B; end; function IMin(A, B: Integer): Integer; begin if A < B then Result := A else Result := B; end; { TTab } procedure TTab.AssignTo(Dest: TPersistent); begin if Dest is TTab then begin with Dest as TTab do begin FAlign := Self.Align; FLeft := Self.Left; FTop := Self.Top; end; end else inherited; end; constructor TTab.Create(Collection: TCollection); begin inherited Create(Collection); FAlign := taLeftAlign; FColor := clBlack; end; function TTab.GetPixels: Extended; begin with TTabs(Collection).Ruler do Result := UnitsToPixs(Position); end; function TTab.GetPoints: Extended; begin with TTabs(Collection).Ruler do Result := UnitsToPoints(Position); end; function TTab.GetRTLAlign: TTabAlign; begin Result := FAlign; if Assigned(Collection) then if TTabs(Collection).Ruler.UseRTL then if FAlign = taLeftAlign then Result := taRightAlign else if FAlign = taRightAlign then Result := taLeftAlign; end; procedure TTab.SetAlign(const Value: TTabAlign); var HotSpot: Integer; begin if Value <> FAlign then begin case FAlign of taLeftAlign: HotSpot := Left; taRightAlign: HotSpot := Left + 5; else HotSpot := Left + 3; end; // Setup new alignment and the rest of the stuff. FAlign := Value; case FAlign of taLeftAlign: Left := HotSpot; taCenterAlign: Left := HotSpot - 3; taRightAlign: Left := HotSpot - 5; taDecimalAlign: Left := HotSpot - 3; taWordBarAlign: Left := HotSpot - 3; end; Changed(False); end; end; procedure TTab.SetColor(const Value: TColor); begin if Value <> FColor then begin FColor := Value; TCustomRuler(TTabs(Collection).GetOwner).Invalidate; end; end; procedure TTab.SetPixels(const Value: Extended); begin with TTabs(Collection).Ruler do Position := PixsToUnits(Value); end; procedure TTab.SetPoints(const Value: Extended); begin with TTabs(Collection).Ruler do Position := PointsToUnits(Value); end; procedure TTab.SetPosition(const Value: Extended); begin FPosition := Value; with TTabs(Collection) do begin BeginUpdate; try SortTabs; finally EndUpdate; end; end; end; { TTabs } function CompareTabs(Item1, Item2: Pointer): Integer; begin if TTab(Item1).Position > TTab(Item2).Position then Result := +1 else if TTab(Item1).Position < TTab(Item2).Position then Result := -1 else Result := 0; end; function TTabs.Add: TTab; begin Result := TTab(inherited Add); end; constructor TTabs.Create(Ruler: TCustomRuler); begin inherited Create(TTab); FRuler := Ruler; end; function TTabs.GetOwner: TPersistent; begin Result := FRuler; end; function TTabs.GetTab(Index: Integer): TTab; begin Result := TTab(inherited Items[Index]); end; procedure TTabs.SetTab(Index: Integer; const Value: TTab); begin inherited SetItem(Index, Value); FRuler.Invalidate; end; procedure TTabs.SortTabs; var I: Integer; List: TList; begin List := TList.Create; try for I := 0 to Count - 1 do List.Add(Items[I]); List.Sort(CompareTabs); for I := 0 to List.Count - 1 do TTab(List.Items[I]).Index := I finally List.Free; end; end; procedure TTabs.Update(Item: TCollectionItem); begin inherited; with FRuler do begin if csLoading in ComponentState then Exit; if not FBlockDoTabChanged then DoTabChanged; Invalidate; end; end; { TIndentSettings } procedure TIndentSettings.AssignTo(Dest: TPersistent); begin if Dest is TIndentSettings then begin with Dest as TIndentSettings do begin DragCursor := Self.DragCursor; Options := Self.Options; end; end else inherited; end; constructor TIndentSettings.Create(AOwner: TCustomRuler); begin FOwner := AOwner; FDragCursor := crDrag; FOptions := DefaultIndentOptions; end; procedure TIndentSettings.SetDragCursor(const Value: TCursor); begin if FDragCursor <> Value then begin FDragCursor := Value; FOwner.Invalidate; end; end; procedure TIndentSettings.SetOptions(const Value: TIndentOptions); begin if FOptions <> Value then begin FOptions := Value; if ioShowLeftIndent in FOptions then Include(FOptions, ioShowHangingIndent); if not (ioShowHangingIndent in FOptions) then Exclude(FOptions, ioShowLeftIndent); FOwner.Invalidate; end; end; { TMarginSettings } procedure TMarginSettings.AssignTo(Dest: TPersistent); begin if Dest is TMarginSettings then begin with Dest as TMarginSettings do begin DragCursor := Self.DragCursor; GripColor := Self.GripColor; Options := Self.Options; end; end else inherited; end; constructor TMarginSettings.Create(AOwner: TCustomRuler); begin FOwner := AOwner; FDragCursor := crSizeWE; FGripColor := clBtnShadow; FOptions := DefaultMarginOptions; end; procedure TMarginSettings.SetDragCursor(const Value: TCursor); begin if FDragCursor <> Value then begin FDragCursor := Value; FOwner.Invalidate; end; end; procedure TMarginSettings.SetGripColor(const Value: TColor); begin if FGripColor <> Value then begin FGripColor := Value; FOwner.Invalidate; end; end; procedure TMarginSettings.SetOptions(const Value: TMarginOptions); begin if FOptions <> Value then begin FOptions := Value; FOwner.Invalidate; end; end; { TTabSettings } procedure TTabSettings.AssignTo(Dest: TPersistent); begin if Dest is TTabSettings then begin with Dest as TTabSettings do begin DeleteCursor := Self.DeleteCursor; DragCursor := Self.DragCursor; Options := Self.Options; end; end else inherited; end; constructor TTabSettings.Create(AOwner: TCustomRuler); begin FOwner := AOwner; FDeleteCursor := crDrag; FDragCursor := crDrag; FOptions := DefaultTabOptions; end; procedure TTabSettings.SetDeleteCursor(const Value: TCursor); begin if FDeleteCursor <> Value then begin FDeleteCursor := Value; FOwner.Invalidate; end; end; procedure TTabSettings.SetDragCursor(const Value: TCursor); begin if FDragCursor <> Value then begin FDragCursor := Value; FOwner.Invalidate; end; end; procedure TTabSettings.SetOptions(const Value: TTabOptions); var I: Integer; begin if FOptions <> Value then begin FOptions := Value; if not (toAdvancedTabs in Value) then for I := 0 to FOwner.Tabs.Count - 1 do FOwner.Tabs[I].Align := taLeftAlign; FOwner.Invalidate; end; end; { TRulerTexts } constructor TRulerTexts.Create(AOwner: TCustomRuler); begin FRuler := AOwner; FHintColumnMove := 'Move Table Column'; FHintIndentFirst := 'First Indent'; FHintIndentLeft := 'Left Indent'; FHintIndentHanging := 'Hanging Indent'; FHintIndentRight := 'Right Indent'; FHintLevelDec := 'Decrease level'; FHintLevelInc := 'Increase level'; FHintTabCenter := 'Center aligned tab'; FHintTabDecimal := 'Decimal aligned tab'; FHintTabLeft := 'Left aligned tab'; FHintTabRight := 'Right aligned tab'; FHintTabWordBar := 'Word Bar aligned tab'; FMenuTabCenter := 'Center align'; FMenuTabDecimal := 'Decimal align'; FMenuTabLeft := 'Left align'; FMenuTabRight := 'Right align'; FMenuTabWordBar := 'Word Bar align'; end; procedure TRulerTexts.SetHintColumnMove(const Value: string); begin FHintColumnMove := Value; end; procedure TRulerTexts.SetHintIndentFirst(const Value: string); begin FHintIndentFirst := Value; end; procedure TRulerTexts.SetHintIndentHanging(const Value: string); begin FHintIndentHanging := Value; end; procedure TRulerTexts.SetHintIndentLeft(const Value: string); begin FHintIndentLeft := Value; end; procedure TRulerTexts.SetHintIndentRight(const Value: string); begin FHintIndentRight := Value; end; procedure TRulerTexts.SetHintLevelDec(const Value: string); begin FHintLevelDec := Value; end; procedure TRulerTexts.SetHintLevelInc(const Value: string); begin FHintLevelInc := Value; end; procedure TRulerTexts.SetHintTabCenter(const Value: string); begin FHintTabCenter := Value; end; procedure TRulerTexts.SetHintTabDecimal(const Value: string); begin FHintTabDecimal := Value; end; procedure TRulerTexts.SetHintTabLeft(const Value: string); begin FHintTabLeft := Value; end; procedure TRulerTexts.SetHintTabRight(const Value: string); begin FHintTabRight := Value; end; procedure TRulerTexts.SetHintTabWordBar(const Value: string); begin FHintTabWordBar := Value; end; procedure TRulerTexts.SetMenuTabCenter(const Value: string); begin FMenuTabCenter := Value; end; procedure TRulerTexts.SetMenuTabDecimal(const Value: string); begin FMenuTabDecimal := Value; end; procedure TRulerTexts.SetMenuTabLeft(const Value: string); begin FMenuTabLeft := Value; end; procedure TRulerTexts.SetMenuTabRight(const Value: string); begin FMenuTabRight := Value; end; procedure TRulerTexts.SetMenuTabWordBar(const Value: string); begin FMenuTabWordBar := Value; end; { TCustomRuler } // --- Specialised procedure to directly add tabs from a TRichEdit98 control procedure TCustomRuler.AddRichEdit98Tab(const Value: Extended; Alignment: TTabAlign); begin with Tabs do begin BeginUpdate; try with Add do begin Points := Value; Align := Alignment; end; finally EndUpdate; end; end; end; procedure TCustomRuler.CMFontChanged(var Message: TMessage); begin inherited; Invalidate; end; constructor TCustomRuler.Create(AOwner: TComponent); var DC: HDC; begin inherited Create(AOwner); ControlStyle := ControlStyle + [csReplicatable]; {$IFDEF COMPILER4_UP} DoubleBuffered := True; {$ELSE} ControlStyle := ControlStyle + [csOpaque]; {$ENDIF} Height := 25; Width := 600; FIndentSettings:= TIndentSettings.Create(Self); FInset := 10; FListEditor := TRulerListEditor.Create(Self); FMarginColor := clInfoBk; FMarginSettings:= TMarginSettings.Create(Self); FMaxTabs := 32; FRulerColor := clWindow; FRulerOptions := DefaultRulerOptions; FRulerTexts := TRulerTexts.Create(Self); FTableEditor := TRulerTableEditor.Create(Self); FTabs := TTabs.Create(Self); FTabSettings := TTabSettings.Create(Self); FUnitsDisplay := ruCentimeters; FUnitsProgram := ruCentimeters; PageHeight := cmPerInch * 11; // Standard Letter PageWidth := cmPerInch * 8.5; // Standard Letter FRulerType := rtHorizontal; FZoom := 100; if (Owner = nil) or (([csReading, csDesigning] * Owner.ComponentState) = [csDesigning]) then begin // Component is being dropped on a form, give it some nice defaults. TopMargin := 2.54; BottomMargin := 2.54; LeftMargin := 2.54; RightMargin := 2.54; end; DC := GetDC(0); try FScreenRes := GetDeviceCaps(DC, LOGPIXELSX); // Pixels per inch FMultiPixels := FScreenRes / cmPerInch; finally ReleaseDC(0, DC); end; FMultiPoints := PointsPerInch / cmPerInch; FItemSeparation := Round(UnitsToPixs(2.54 / 8)); FIndents[itBoth].Graphic := igRectangle; FIndents[itFirst].Graphic := igDown; FIndents[itLeft].Graphic := igUp; FIndents[itRight].Graphic := igUp; FTimer := TTimer.Create(Self); with FTimer do begin Interval := 500; OnTimer := TimerProc; Enabled := False; end; end; destructor TCustomRuler.Destroy; begin FIndentSettings.Free; FListEditor.Free; FMarginSettings.Free; FPopupMenu.Free; FRulerTexts.Free; FTableEditor.Free; FTabs.Free; FTabSettings.Free; inherited Destroy; end; procedure TCustomRuler.DoBiDiModeChanged; begin if Assigned(FOnBiDiModeChanged) then FOnBiDiModeChanged(Self); end; procedure TCustomRuler.DoIndentChanged; begin if Assigned(FOnIndentChanged) then FOnIndentChanged(Self); end; procedure TCustomRuler.DoLevelButtonDown(Direction: Integer); begin end; procedure TCustomRuler.DoLevelButtonUp(Direction: Integer); begin end; procedure TCustomRuler.DoMarginChanged; begin if Assigned(FOnMarginChanged) then FOnMarginChanged(Self); end; procedure TCustomRuler.DoRulerItemMove(X: Integer; Removing: Boolean); begin if Assigned(FOnRulerItemMove) then FOnRulerItemMove(Self, X, Removing); end; procedure TCustomRuler.DoRulerItemRelease; begin if Assigned(FOnRulerItemRelease) then FOnRulerItemRelease(Self); end; procedure TCustomRuler.DoRulerItemSelect(X: Integer); begin if Assigned(FOnRulerItemSelect) then FOnRulerItemSelect(Self, X); end; procedure TCustomRuler.DoTabChanged; begin if Assigned(FOnTabChanged) then FOnTabChanged(Self); end; procedure TCustomRuler.DoTableColumnChanged; begin if Assigned(FOnTableColumnChanged) then FOnTableColumnChanged(Self); end; function TCustomRuler.GetBottomMargin: Extended; begin Result := FMargins[mtBottom].Position; end; function TCustomRuler.GetClosestOnRuler(X: Integer; FromMargin: Boolean): Integer; var Grid: Extended; XPos: Extended; begin // Setup display grid steps. Grid := GridSteps[UnitsDisplay]; // Convert to UnitsProgram since this is what the rest is based on. Grid := Grid * UnitsPerInch(UnitsProgram) / UnitsPerInch(UnitsDisplay); if FromMargin then begin XPos := ZPixsToUnits(RTLAdjust(X, Inset)) - StartMargin; Result := RTLAdjust(Inset + Round(ZUnitsToPixs(StartMargin + Grid * Round(XPos / Grid))), 0); end else begin XPos := ZPixsToUnits(RTLAdjust(X, Inset)); Result := RTLAdjust(Inset + Round(ZUnitsToPixs(Grid * Round(XPos / Grid))), 0); end; end; function TCustomRuler.GetDefaultTabWidth: Extended; begin if FDefaultTabWidth <= 0 then FDefaultTabWidth := 0.5 * UnitsPerInch(UnitsProgram); Result := FDefaultTabWidth; end; function TCustomRuler.GetEndMargin: Extended; begin if UseRTL then Result := LeftMargin else Result := RightMargin; end; function TCustomRuler.GetEndMarginGrip: Integer; begin if UseRTL then Result := FMargins[mtLeft].Grip else Result := FMargins[mtRight].Grip; end; function TCustomRuler.GetFirstIndent: Extended; begin Result := FIndents[itFirst].Position; end; function TCustomRuler.GetHitTestInfoAt(X, Y: Integer): THitInfo; var BT: TBorderType; IT: TIndentType; MT: TMarginType; P: TPoint; begin Result.HitItems := []; P := Point(X, Y); if RulerType = rtHorizontal then begin // First check if it is on one of the indent sliders for IT := Low(TIndentType) to High(TIndentType) do if PtInRect(GetIndentRect(IT), P) then case IT of itBoth: Include(Result.HitItems, hiOnBothIndent); itFirst: Include(Result.HitItems, hiOnFirstIndent); itLeft: Include(Result.HitItems, hiOnLeftIndent); itRight: Include(Result.HitItems, hiOnRightIndent); end; if ListEditor.Active and (leoLevelAdjustable in ListEditor.Options) then begin if PtInRect(GetLevelRect(ltLevelDec), P) then if UseRTL then Include(Result.HitItems, hiOnLevelInc) else Include(Result.HitItems, hiOnLevelDec); if PtInRect(GetLevelRect(ltLevelInc), P) then if UseRTL then Include(Result.HitItems, hiOnLevelDec) else Include(Result.HitItems, hiOnLevelInc); end; if Result.HitItems <> [] then Exit; // Second, check if it is on one of the tabs. Result.Index := GetTabIndexAt(X, Y); if Result.Index <> -1 then begin Result.HitItems := Result.HitItems + [hiOnTab]; Exit; end; if TableEditor.Active and (teoAdjustable in TableEditor.Options) then begin // Third, check if it is on a Table Column. Result.Index := TableEditor.GetColumnIndexAt(X, Y); if Result.Index <> -1 then begin Result.HitItems := Result.HitItems + [hiOnColumn]; Exit; end; // Fourth, check if it is on a Table Border. for BT := Low(TBorderType) to High(TBorderType) do if PtInRect(TableEditor.GetBorderRect(BT), P) then case BT of // !!! btLeft: Include(Result.HitItems, hiOnLeftBorder); btRight: Include(Result.HitItems, hiOnRightBorder); end; if Result.HitItems <> [] then Exit; end; // Fifth, check if it is on a margin for MT := mtLeft to mtRight do if PtInRect(GetMarginGripRect(MT), P) then case MT of mtLeft: Include(Result.HitItems, hiOnLeftMargin); mtRight: Include(Result.HitItems, hiOnRightMargin); end; end else begin // For vertical ruler only check Top and BottomMargin for MT := mtTop to mtBottom do if PtInRect(GetMarginGripRect(MT), P) then case MT of mtTop: Include(Result.HitItems, hiOnTopMargin); mtBottom: Include(Result.HitItems, hiOnBottomMargin); end; end; end; function TCustomRuler.GetIndentRect(IndentType: TIndentType): TRect; var H: Integer; begin with FIndents[IndentType] do begin if Graphic = igRectangle then H := 7 else H := 8; Result := Rect(Left, Top, Left + 9, Top + H); end; end; function TCustomRuler.GetLeftIndent: Extended; begin Result := FIndents[itLeft].Position; end; function TCustomRuler.GetLeftMargin: Extended; begin Result := FMargins[mtLeft].Position; end; function TCustomRuler.GetLevelRect(LevelType: TLevelType): TRect; begin Result := GetIndentRect(itBoth); case LevelType of ltLevelDec: begin Result.Left := Result.Left - 8; Result.Right := Result.Right - 8; end; ltLevelInc: begin Result.Left := Result.Left + 8; Result.Right := Result.Right + 8; end; end; end; function TCustomRuler.GetMarginGripRect(MarginType: TMarginType): TRect; var R: TRect; begin R := GetMarginRect(MarginType); case MarginType of mtTop: Result := Rect(R.Left, R.Bottom - 2, R.Right, R.Bottom + 2); mtBottom: Result := Rect(R.Left, R.Top - 2, R.Right, R.Top + 2); mtLeft: Result := Rect(R.Right - 2, R.Top, R.Right + 2, R.Bottom); mtRight: Result := Rect(R.Left - 2, R.Top, R.Left + 2, R.Bottom); end; end; function TCustomRuler.GetMarginRect(MarginType: TMarginType): TRect; var B, L, R, T: Integer; begin if RulerType = rtHorizontal then begin T := 4; B := Height - 10; if (MarginType = mtLeft) xor UseRTL then begin L := Inset + 1; R := Inset + Round(ZUnitsToPixs(StartMargin)); if UseRTL then Dec(L); Result := RTLAdjustRect(Rect(L, T, R, B)); end else begin L := Inset + Round(ZUnitsToPixs(PageWidth - EndMargin)); R := Inset + Round(ZUnitsToPixs(PageWidth)); if UseRTL then Dec(R); Result := RTLAdjustRect(Rect(L, T, R, B)); end; end else begin L := 4; R := Width - 3; if MarginType = mtTop then begin T := Inset + 1; B := Inset + Round(ZUnitsToPixs(TopMargin)); Result := Rect(L, T, R, B); end else begin T := Inset + Round(ZUnitsToPixs(PageHeight - BottomMargin)); B := Inset + Round(ZUnitsToPixs(PageHeight)); Result := Rect(L, T, R, B); end; end; end; function TCustomRuler.GetRightIndent: Extended; begin Result := FIndents[itRight].Position; end; function TCustomRuler.GetRightMargin: Extended; begin Result := FMargins[mtRight].Position; end; function TCustomRuler.GetStartMargin: Extended; begin if UseRTL then Result := RightMargin else Result := LeftMargin; end; function TCustomRuler.GetStartMarginGrip: Integer; begin if UseRTL then Result := FMargins[mtRight].Grip else Result := FMargins[mtLeft].Grip; end; function TCustomRuler.GetTabIndexAt(X, Y: Integer): Integer; var I: Integer; W: Integer; begin Result := -1; for I := 0 to Tabs.Count - 1 do with Tabs[I] do begin case Align of taLeftAlign, taRightAlign: W := 6; else W := 8; end; if (X >= Left) and (X < Left + W) and (Y >= Top) and (Y < Top + 6) then Result := I; end; end; function TCustomRuler.GetTopMargin: Extended; begin Result := FMargins[mtTop].Position; end; function TCustomRuler.HitItemsToIndex(HitItems: THitItems): Integer; begin Result := -1; if hiOnBothIndent in HitItems then Result := Integer(itBoth) else if hiOnFirstIndent in HitItems then Result := Integer(itFirst) else if hiOnLeftIndent in HitItems then Result := Integer(itLeft) else if hiOnRightIndent in HitItems then Result := Integer(itRight) else if hiOnLeftBorder in HitItems then Result := Integer(btLeft) else if hiOnRightBorder in HitItems then Result := Integer(btRight) else if hiOnTopMargin in HitItems then Result := Integer(mtTop) else if hiOnBottomMargin in HitItems then Result := Integer(mtBottom) else if hiOnLeftMargin in HitItems then Result := Integer(mtLeft) else if hiOnRightMargin in HitItems then Result := Integer(mtRight); end; procedure TCustomRuler.Loaded; begin inherited; UpdatePageDimensions; end; procedure TCustomRuler.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var BT: TBorderType; HitInfo: THitInfo; IT: TIndentType; NewTab: TTab; P: TPoint; begin // Turn off hints while dragging. It can obscure the RichEdit when // the user uses vertical marker lines within the RichEdit. FOldShowHint := ShowHint; ShowHint := False; HitInfo := GetHitTestInfoAt(X, Y); if not (moAdjustable in MarginSettings.Options) then HitInfo.HitItems := HitInfo.HitItems - AllMargins; if Button = mbLeft then begin if (RulerType = rtHorizontal) and (HitInfo.HitItems = []) then begin // Add a new tab when the user clicked on a 'blank' part of the ruler. if Tabs.Count < MaxTabs then with Tabs do begin BeginUpdate; try NewTab := Add; with NewTab do if toSnapToRuler in TabSettings.Options then X := GetClosestOnRuler(X, True) + TabOffset[RTLAlign]; if TableEditor.Active then NewTab.Position := ZPixsToUnits(TableEditor.RTLAdjust(X, 0) - TableEditor.GetCellRect(TableEditor.CellIndex).Left) else NewTab.Position := ZPixsToUnits(RTLAdjust(X, Inset)) - StartMargin; finally FBlockDoTabChanged := True; try EndUpdate; finally FBlockDoTabChanged := False; end; end; FDragInfo.Item := diTab; FDragInfo.Index := NewTab.Index; FDragInfo.Offset := TabOffset[NewTab.RTLAlign]; ProcessParentBackGround(True); Tabs[FDragInfo.Index].Left := X - TabOffset[NewTab.RTLAlign]; DoRulerItemSelect(X); end; end else begin if (AllIndents * HitInfo.HitItems) <> [] then begin Screen.Cursor := IndentSettings.DragCursor; FDragInfo.Item := diIndent; FDragInfo.Index := HitItemsToIndex(HitInfo.HitItems); IT := TIndentType(FDragInfo.Index); if roItemsShowLastPos in Options then FIndentTraces := FIndents; if hiOnBothIndent in HitInfo.HitItems then FDiff := FIndents[itFirst].Left - FIndents[itLeft].Left else FDiff := 0; if Screen.Cursor = crHSplit then FDragInfo.Offset := IndentOffset else FDragInfo.Offset := X - FIndents[IT].Left; X := FIndents[IT].Left + IndentOffset; if IndentSettings.DragCursor = crHSplit then begin P := ClientToScreen(Point(X, Y)); Windows.SetCursorPos(P.X, P.Y) end; ProcessParentBackGround(True); DoRulerItemSelect(X); end else if (AllLevels * HitInfo.HitItems) <> [] then begin if hiOnLevelDec in HitInfo.HitItems then DoLevelButtonDown(-1); if hiOnLevelInc in HitInfo.HitItems then DoLevelButtonDown(+1); end else if hiOnTab in HitInfo.HitItems then begin Screen.Cursor := TabSettings.DragCursor; FDragInfo.Item := diTab; FDragInfo.Index := HitInfo.Index; FDragInfo.Offset := X - Tabs[FDragInfo.Index].Left; if roItemsShowLastPos in Options then begin FTabTrace := TTab.Create(nil); FTabTrace.Assign(Tabs[FDragInfo.Index]); FTabTrace.FAlign := Tabs[FDragInfo.Index].RTLAlign; end; ProcessParentBackGround(True); with Tabs[FDragInfo.Index] do X := Left + TabOffset[RTLAlign]; DoRulerItemSelect(X); end else if hiOnColumn in HitInfo.HitItems then begin TableEditor.FDraggedWithShift := ssShift in Shift; TableEditor.FDragStart := X; Screen.Cursor := TableEditor.DragCursor; FDragInfo.Item := diColumn; FDragInfo.Index := HitInfo.Index; if Screen.Cursor = crHSplit then FDragInfo.Offset := ColumnOffset else FDragInfo.Offset := X - TableEditor.Cells[FDragInfo.Index].Left; ProcessParentBackGround(True); with TableEditor.Cells[FDragInfo.Index] do X := Left + ColumnOffset; DoRulerItemSelect(X); end else if (AllBorders * HitInfo.HitItems) <> [] then begin TableEditor.FDraggedWithShift := False; Screen.Cursor := TableEditor.DragCursor; FDragInfo.Item := diBorder; FDragInfo.Index := HitItemsToIndex(HitInfo.HitItems); BT := TBorderType(FDragInfo.Index); if Screen.Cursor = crHSplit then FDragInfo.Offset := BorderOffset else FDragInfo.Offset := X - TableEditor.FBorders[BT].Left; ProcessParentBackGround(True); with TableEditor.FBorders[BT] do X := Left + BorderOffset; DoRulerItemSelect(X); end else if (AllMargins * HitInfo.HitItems) <> [] then begin if RulerType = rtHorizontal then begin Screen.Cursor := MarginSettings.DragCursor; FDragInfo.Item := diMargin; FDragInfo.Index := HitItemsToIndex(HitInfo.HitItems); FDragInfo.Offset := X - FMargins[TMarginType(FDragInfo.Index)].Grip; ProcessParentBackGround(True); X := FMargins[TMarginType(FDragInfo.Index)].Grip; DoRulerItemSelect(X); end else begin Screen.Cursor := MarginSettings.DragCursor; FDragInfo.Item := diMargin; FDragInfo.Index := HitItemsToIndex(HitInfo.HitItems); FDragInfo.Offset := Y - FMargins[TMarginType(FDragInfo.Index)].Grip; ProcessParentBackGround(True); Y := FMargins[TMarginType(FDragInfo.Index)].Grip; DoRulerItemSelect(Y); end; end; end; end; inherited; end; procedure TCustomRuler.MouseMove(Shift: TShiftState; X, Y: Integer); var BT: TBorderType; HitInfo: THitInfo; I: Integer; IT: TIndentType; MT: TMarginType; PageWidthInPixels: Integer; function GetTabHint(TA: TTabAlign): string; begin case TA of taCenterAlign: Result := RulerTexts.HintTabCenter; taDecimalAlign: Result := RulerTexts.HintTabDecimal; taRightAlign: Result := RulerTexts.HintTabRight; taWordBarAlign: Result := RulerTexts.HintTabWordBar; else Result := RulerTexts.HintTabLeft; end; end; function KeepDragWithinPageArea(X, Offset: Integer): Integer; begin Result := X; if UseRTL then begin Result := IMin(Result, RTLAdjust(Inset, Offset)); Result := IMax(Result, RTLAdjust(Inset + PageWidthInPixels, Offset)); end else begin Result := IMax(Result, Inset - Offset); Result := IMin(Result, Inset - Offset + PageWidthInPixels); end; end; begin if FDragInfo.Item = diNone then begin HitInfo := GetHitTestInfoAt(X, Y); if (TableEditor.Active and ((hiOnColumn in HitInfo.HitItems) or (hiOnRightBorder in HitInfo.HitItems)) and (teoAdjustable in TableEditor.Options)) or ((moAdjustable in MarginSettings.Options) and ((HitInfo.HitItems - AllMargins) = []) and ((HitInfo.HitItems * AllMargins) <> [])) then Windows.SetCursor(Screen.Cursors[MarginSettings.DragCursor]) else Windows.SetCursor(Screen.Cursors[Cursor]); if hiOnTab in HitInfo.HitItems then OverrideHint(GetTabHint(Tabs[HitInfo.Index].Align)) else if hiOnBothIndent in HitInfo.HitItems then OverrideHint(RulerTexts.HintIndentLeft) else if hiOnFirstIndent in HitInfo.HitItems then OverrideHint(RulerTexts.HintIndentFirst) else if hiOnLeftIndent in HitInfo.HitItems then OverrideHint(RulerTexts.HintIndentHanging) else if hiOnRightIndent in HitInfo.HitItems then OverrideHint(RulerTexts.HintIndentRight) else if hiOnLevelDec in HitInfo.HitItems then OverrideHint(RulerTexts.HintLevelDec) else if hiOnLevelInc in HitInfo.HitItems then OverrideHint(RulerTexts.HintLevelInc) else if hiOnColumn in HitInfo.HitItems then OverrideHint(RulerTexts.HintColumnMove) else if hiOnLeftBorder in HitInfo.HitItems then OverrideHint(RulerTexts.HintColumnMove) else if hiOnRightBorder in HitInfo.HitItems then OverrideHint(RulerTexts.HintColumnMove) else RestoreHint; end; PageWidthInPixels := Round(ZUnitsToPixs(PageWidth)); if FDragInfo.Item = diIndent then begin IT := TIndentType(FDragInfo.Index); with FIndents[IT] do begin if ioSnapToRuler in IndentSettings.Options then Left := GetClosestOnRuler(X, True) - IndentOffset else Left := X - FDragInfo.Offset; // Keep the First/Left/Both indents separated from the right indent if not UseRTL then begin // Keep the indent within the page-area if FDiff < 0 then Left := Left + FDiff; Left := KeepDragWithinPageArea(Left, IndentOffset); if FDiff < 0 then Left := Left - FDiff; if IT in [itFirst, itLeft] then begin Left := IMin(Left, FIndents[itRight].Left - ItemSeparation); if ioKeepWithinMargins in IndentSettings.Options then Left := IMax(Left, StartMarginGrip - IndentOffset); if TableEditor.Active then Left := TableEditor.KeepWithinCurrentCell(IT, Left); end; if IT = itBoth then begin if FDiff > 0 then Left := Left + FDiff; Left := IMin(Left, FIndents[itRight].Left - ItemSeparation); if FDiff > 0 then Left := Left - FDiff; if ioKeepWithinMargins in IndentSettings.Options then begin if FDiff < 0 then Left := Left + FDiff; Left := IMax(Left, StartMarginGrip - IndentOffset); if FDiff < 0 then Left := Left - FDiff; end; if TableEditor.Active then begin if FDiff < 0 then Left := Left + FDiff; Left := TableEditor.KeepWithinCurrentCell(IT, Left); if FDiff < 0 then Left := Left - FDiff; end; end; if IT = itRight then begin Left := IMax(Left, FIndents[itFirst].Left + ItemSeparation); Left := IMax(Left, FIndents[itLeft].Left + ItemSeparation); if ioKeepWithinMargins in IndentSettings.Options then Left := IMin(Left, EndMarginGrip - IndentOffset); if TableEditor.Active then Left := TableEditor.KeepWithinCurrentCell(IT, Left); end; end else begin // Keep the indent within the page-area if FDiff > 0 then Left := Left + FDiff; Left := KeepDragWithinPageArea(Left, IndentOffset); if FDiff > 0 then Left := Left - FDiff; if IT in [itFirst, itLeft] then begin Left := IMax(Left, FIndents[itRight].Left + ItemSeparation); if ioKeepWithinMargins in IndentSettings.Options then Left := IMin(Left, StartMarginGrip - IndentOffset); if TableEditor.Active then Left := TableEditor.KeepWithinCurrentCell(IT, Left); end; if IT = itBoth then begin if FDiff < 0 then Left := Left + FDiff; Left := IMax(Left, FIndents[itRight].Left + ItemSeparation); if FDiff < 0 then Left := Left - FDiff; if ioKeepWithinMargins in IndentSettings.Options then begin if FDiff > 0 then Left := Left + FDiff; Left := IMin(Left, StartMarginGrip - IndentOffset); if FDiff > 0 then Left := Left - FDiff; end; if TableEditor.Active then begin if FDiff > 0 then Left := Left + FDiff; Left := TableEditor.KeepWithinCurrentCell(IT, Left); if FDiff > 0 then Left := Left - FDiff; end; end; if IT = itRight then begin Left := IMin(Left, FIndents[itFirst].Left - ItemSeparation); Left := IMin(Left, FIndents[itLeft].Left - ItemSeparation); if ioKeepWithinMargins in IndentSettings.Options then Left := IMax(Left, EndMarginGrip - IndentOffset); if TableEditor.Active then Left := TableEditor.KeepWithinCurrentCell(IT, Left); end; end; end; // Keep Idents 'synchronized' when needed. if IT = itLeft then begin FIndents[itBoth].Left := FIndents[itLeft].Left; end; if IT = itBoth then begin FIndents[itFirst].Left := FIndents[itBoth].Left + FDiff; FIndents[itLeft].Left := FIndents[itBoth].Left; end; X := FIndents[IT].Left + IndentOffset; DoRulerItemMove(X, False); Invalidate; end; if FDragInfo.Item = diTab then begin with Tabs[FDragInfo.Index] do begin FDeleting := (Y < 0) or (Y > Self.Height); if toSnapToRuler in TabSettings.Options then Left := GetClosestOnRuler(X, True) - TabOffset[RTLAlign] else Left := X - FDragInfo.Offset; // Keep the tabs within the page-area Left := KeepDragWithinPageArea(Left, TabOffset[RTLAlign]); if FDeleting then Screen.Cursor := TabSettings.DeleteCursor else Screen.Cursor := TabSettings.DragCursor; X := Left + TabOffset[RTLAlign]; end; DoRulerItemMove(X, False); Invalidate; end; if FDragInfo.Item = diColumn then begin with TableEditor.Cells[FDragInfo.Index] do begin if teoSnapToRuler in TableEditor.Options then Left := GetClosestOnRuler(X, True) - ColumnOffset else Left := X - FDragInfo.Offset; Left := KeepDragWithinPageArea(Left, ColumnOffset); Left := TableEditor.KeepColumnsSeparated(FDragInfo.Index, Left); X := Left + ColumnOffset; TableEditor.FDragLast := X; end; DoRulerItemMove(X, False); Invalidate; end; if FDragInfo.Item = diBorder then begin BT := TBorderType(FDragInfo.Index); with TableEditor.FBorders[BT] do begin if teoSnapToRuler in TableEditor.Options then Left := GetClosestOnRuler(X, True) - BorderOffset else Left := X - FDragInfo.Offset; Left := KeepDragWithinPageArea(Left, BorderOffset); if BT = btLeft then Left := TableEditor.KeepColumnsSeparated(-1, Left) else Left := TableEditor.KeepColumnsSeparated(TableEditor.Cells.Count-1, Left); X := Left + BorderOffset; end; DoRulerItemMove(X, False); Invalidate; end; if FDragInfo.Item = diMargin then begin MT := TMarginType(FDragInfo.Index); if RulerType = rtHorizontal then begin with FMargins[MT] do begin if moSnapToRuler in MarginSettings.Options then Grip := GetClosestOnRuler(X, False) else Grip := X - FDragInfo.Offset; // Keep the margins within the page-area Grip := KeepDragWithinPageArea(Grip, 0); // Keep the Left and Right margins separated. if MT = mtLeft then Grip := IMin(Grip, FMargins[mtRight].Grip - ItemSeparation) else Grip := IMax(Grip, FMargins[mtLeft].Grip + ItemSeparation); // Keep the indents separated if not UseRTL then begin if MT = mtLeft then begin I := Round(ZUnitsToPixs(FirstIndent)); if FIndents[itLeft].Left > FIndents[itFirst].Left then I := I + FIndents[itLeft].Left - FIndents[itFirst].Left; Grip := IMin(Grip, FIndents[itRight].Left + IndentOffset - I - ItemSeparation); end else begin I := Round(ZUnitsToPixs(RightIndent)); Grip := IMax(Grip, FIndents[itFirst].Left + IndentOffset + I + ItemSeparation); Grip := IMax(Grip, FIndents[itLeft].Left + IndentOffset + I + ItemSeparation); end; end else begin if MT = mtLeft then begin I := Round(ZUnitsToPixs(RightIndent)); Grip := IMin(Grip, FIndents[itFirst].Left + IndentOffset - I - ItemSeparation); Grip := IMin(Grip, FIndents[itLeft].Left + IndentOffset - I - ItemSeparation); end else begin I := Round(ZUnitsToPixs(FirstIndent)); if FIndents[itLeft].Left < FIndents[itFirst].Left then I := I - FIndents[itLeft].Left + FIndents[itFirst].Left; Grip := IMax(Grip, FIndents[itRight].Left + IndentOffset + I + ItemSeparation); end; end; end; X := FMargins[MT].Grip; DoRulerItemMove(X, False); Invalidate; end else begin with FMargins[MT] do begin if moSnapToRuler in MarginSettings.Options then Grip := GetClosestOnRuler(Y, False) else Grip := Y - FDragInfo.Offset; // Keep the margins within the page-area Grip := IMax(Grip, Inset); Grip := IMin(Grip, Inset + Round(ZUnitsToPixs(PageHeight))); // Keep the Top and Bottom margins separated. if MT = mtTop then Grip := IMin(Grip, FMargins[mtBottom].Grip - ItemSeparation) else Grip := IMax(Grip, FMargins[mtTop].Grip + ItemSeparation); end; Y := FMargins[MT].Grip; DoRulerItemMove(Y, False); Invalidate; end; end; inherited; end; procedure TCustomRuler.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var BT: TBorderType; Delta: Extended; HitInfo: THitInfo; IT: TIndentType; MT: TMarginType; NewWidth: Extended; P: TPoint; XPos: Integer; YPos: Integer; function NewMenuItem(ACaption: string; AOnClick: TNotifyEvent; ATag: TTabAlign): TMenuItem; begin Result := TMenuItem.Create(Self); Result.Caption := ACaption; Result.OnClick := AOnClick; Result.Tag := Integer(ATag); end; begin if FDragInfo.Item = diIndent then begin try for IT := Low(TIndentType) to High(TIndentType) do FIndentTraces[IT].Graphic := igNone; IT := TIndentType(FDragInfo.Index); XPos := FIndents[IT].Left + IndentOffset; if TableEditor.Active then begin XPos := TableEditor.RTLAdjust(XPos, 0); TableEditor.UpdateIndentPosition(IT, XPos) end else begin XPos := RTLAdjust(XPos, Inset); if IT = itFirst then begin FIndents[itLeft].Position := StartMargin + FirstIndent + LeftIndent - ZPixsToUnits(XPos); FirstIndent := ZPixsToUnits(XPos) - StartMargin; end else if IT = itLeft then LeftIndent := ZPixsToUnits(XPos) - FirstIndent - StartMargin else if IT = itBoth then FirstIndent := ZPixsToUnits(XPos) - LeftIndent - StartMargin else RightIndent := PageWidth - EndMargin - ZPixsToUnits(XPos); end; DoRulerItemRelease; ProcessParentBackGround(False); finally FDragInfo.Item := diNone; Screen.Cursor := crDefault; end; end; if FDragInfo.Item = diTab then begin FTabTrace.Free; FTabTrace := nil; // When finished dragging a Tab, calculate the new Position // or remove the Tab when it was dragged outside the ruler. try with Tabs[FDragInfo.Index] do if FDeleting then Tabs.Items[FDragInfo.Index].Free else begin XPos := Left + TabOffset[RTLAlign]; if TableEditor.Active then begin XPos := TableEditor.RTLAdjust(XPos, 0); Position := ZPixsToUnits(XPos - TableEditor.GetCellRect(TableEditor.CellIndex).Left); end else begin XPos := RTLAdjust(XPos, Inset); Position := ZPixsToUnits(XPos) - StartMargin; end; end; DoRulerItemRelease; ProcessParentBackGround(False); finally FDragInfo.Item := diNone; Screen.Cursor := crDefault; end; end; if FDragInfo.Item = diColumn then begin try TableEditor.FDragLast := TableEditor.FDragStart; if TableEditor.DraggedWithShift then TableEditor.TableWidth := ZPixsToUnits(TableEditor.FBorders[btRight].Left - TableEditor.FBorders[btLeft].Left); with TableEditor.Cells[FDragInfo.Index] do Position := ZPixsToUnits(Left + ColumnOffset - TableEditor.GetOffset) - TableEditor.TableLeft; DoRulerItemRelease; ProcessParentBackGround(False); finally FDragInfo.Item := diNone; Screen.Cursor := crDefault; end; end; if FDragInfo.Item = diBorder then begin try BT := TBorderType(FDragInfo.Index); XPos := TableEditor.FBorders[BT].Left + BorderOffset; if BT = btLeft then TableEditor.TableLeft := ZPixsToUnits(XPos - TableEditor.GetOffset) else begin NewWidth := ZPixsToUnits(XPos - TableEditor.GetOffset) - TableEditor.TableLeft; Delta := NewWidth - TableEditor.TableWidth; TableEditor.TableWidth := NewWidth; with TableEditor do if Cells.Count > 0 then with Cells[Cells.Count-1] do Position := Position + Delta; end; DoRulerItemRelease; ProcessParentBackGround(False); finally FDragInfo.Item := diNone; Screen.Cursor := crDefault; end; end; if FDragInfo.Item = diMargin then begin try MT := TMarginType(FDragInfo.Index); if RulerType = rtHorizontal then begin XPos := FMargins[MT].Grip; XPos := RTLAdjust(XPos, Inset); if MT = mtLeft then begin if UseRTL then LeftMargin := PageWidth - ZPixsToUnits(XPos) else LeftMargin := ZPixsToUnits(XPos) end else begin if UseRTL then RightMargin := ZPixsToUnits(XPos) else RightMargin := PageWidth - ZPixsToUnits(XPos); end; end else begin YPos := FMargins[MT].Grip - Inset; if MT = mtTop then TopMargin := ZPixsToUnits(YPos) else BottomMargin := PageHeight - ZPixsToUnits(YPos); end; DoRulerItemRelease; ProcessParentBackGround(False); finally FDragInfo.Item := diNone; Screen.Cursor := crDefault; end; end; HitInfo := GetHitTestInfoAt(X, Y); if (AllLevels * HitInfo.HitItems) <> [] then begin if hiOnLevelDec in HitInfo.HitItems then DoLevelButtonUp(-1); if hiOnLevelInc in HitInfo.HitItems then DoLevelButtonUp(+1); end; // Create and show a popupmenu when right-clicked on a Tab. if (toAdvancedTabs in TabSettings.Options) and (Button = mbRight) then begin HitInfo := GetHitTestInfoAt(X, Y); if (hiOnTab in HitInfo.HitItems) and (HitInfo.Index >= 0) then begin if not Assigned(FPopupMenu) then begin FPopupmenu := TPopupMenu.Create(Self); with FPopupMenu, RulerTexts do begin Items.Add(NewMenuItem(MenuTabLeft, PopupClick, taLeftAlign)); Items.Add(NewMenuItem(MenuTabCenter, PopupClick, taCenterAlign)); Items.Add(NewMenuItem(MenuTabRight, PopupClick, taRightAlign)); Items.Add(NewMenuItem(MenuTabDecimal, PopupClick, taDecimalAlign)); Items.Add(NewMenuItem(MenuTabWordBar, PopupClick, taWordBarAlign)); end; end; with FPopupMenu do begin Tag := HitInfo.Index; P := Self.ClientToScreen(Point(X, Y)); Popup(P.X, P.Y); end; end; end; ShowHint := FOldShowHint; inherited; end; procedure TCustomRuler.OverrideHint(NewHint: string); var P: TPoint; {$IFNDEF COMPILER5_UP} M: TWMMouse; {$ENDIF} begin if not FOvrHint then FOrgHint := Hint; Hint := NewHint; if not FOvrHint then begin GetCursorPos(P); {$IFDEF COMPILER5_UP} Application.ActivateHint(P); {$ELSE} M.Pos.X := -1; M.Pos.Y := -1; Application.HintMouseMessage(Self, TMessage(M)); M.Pos.X := P.X; M.Pos.Y := P.Y; Application.HintMouseMessage(Self, TMessage(M)); {$ENDIF} end; FOvrHint := True; end; procedure TCustomRuler.Paint; var ACanvas: TCanvas; {$IFNDEF COMPILER4_UP} ABitmap: TBitmap; R: TRect; {$ELSE} DC: THandle; LastOrigin: TPoint; {$ENDIF} begin {$IFNDEF COMPILER4_UP} ABitmap := TBitmap.Create; try // Buffer data in local bitmap ABitmap.Width := Width; ABitmap.Height := Height; ACanvas := ABitmap.Canvas; ACanvas.Brush.Color := Self.Color; ACanvas.Brush.Style := bsSolid; ACanvas.FillRect(ClientRect); {$ELSE} // Use original canvas ACanvas := Canvas; {$IFDEF COMPILER7_UP} if FOldParentBackground then begin {$ELSE} if ParentColor or ((Parent <> nil) and (Parent.Brush.Color = Color)) then begin {$ENDIF} DC := ACanvas.Handle; GetWindowOrgEx(DC, LastOrigin); SetWindowOrgEx(DC, LastOrigin.X + Left, LastOrigin.Y + Top, nil); Self.Parent.Perform(WM_ERASEBKGND, Integer(DC), Integer(DC)); SetWindowOrgEx(DC, LastOrigin.X, LastOrigin.Y, nil); // Above code might change font settings for DC without TCanvas knowing // about it. Next lines are there to force TCanvas to reset its internal // State and to (re)create the drawing objects when needed. ACanvas.Handle := 0; ACanvas.Handle := DC; end; {$ENDIF} if RulerType = rtHorizontal then PaintHorizontalRuler(ACanvas) else PaintVerticalRuler(ACanvas); {$IFNDEF COMPILER4_UP} R := ClientRect; Canvas.CopyMode := cmSrcCopy; Canvas.Draw(R.Left, R.Top, ABitmap); finally ABitmap.Free end; {$ENDIF} end; procedure TCustomRuler.PaintHorizontalRuler(Canvas: TCanvas); var R: TRect; begin R := Rect(0, 0, Width, Height - 7); PaintHOutline(Canvas, R); PaintHMargins(Canvas, R); PaintHMarkers(Canvas, R); PaintHTableGraphics(Canvas, R); PaintHDefaultTabs(Canvas, R); PaintHTabs(Canvas, R); PaintHIndents(Canvas, R); end; procedure TCustomRuler.PaintHDefaultTabs(Canvas: TCanvas; R: TRect); var N: Integer; X: Integer; XAdj: Integer; XInd: Integer; XMax: Integer; XMin: Integer; XTab: Integer; begin if toShowDefaultTabs in TabSettings.Options then begin if TableEditor.Active then with TableEditor do begin XMin := GetCellRect(CellIndex).Left; XMax := GetCellRect(CellIndex).Right; end else begin XMin := RTLAdjust(StartMarginGrip, 0); XMax := RTLAdjust(EndMarginGrip, 0); end; // Don't display default tabs before the first actual tab. if Tabs.Count > 0 then XTab := XMin + Round(ZUnitsToPixs(Tabs[Tabs.Count-1].Position)) else XTab := XMin; if toDontShowDefaultTabsBeforeLeftIndent in TabSettings.Options then begin if TableEditor.Active then XInd := TableEditor.CalculateCurrentIndentPosition(itLeft) else XInd := XMin + Round(ZUnitsToPixs(FirstIndent + LeftIndent)); if XInd > XTab then XTab := XInd; end; N := 0; with Canvas do begin Pen.Color := clBtnShadow; repeat Inc(N); X := XMin + ZoomAndRound(N * UnitsToPixs(DefaultTabWidth)); if (X > XTab) and (X < XMax) then begin if TableEditor.Active then XAdj := TableEditor.RTLAdjust(X, 0) else XAdj := RTLAdjust(X, 0); if Flat then begin MoveTo(XAdj, R.Bottom); LineTo(XAdj, R.Bottom + 2); end else begin MoveTo(XAdj, R.Bottom - 2); LineTo(XAdj, R.Bottom); end; end; until X >= XMax; end; end; end; procedure TCustomRuler.PaintHIndent(Canvas: TCanvas; Graphic: TIndentGraphic; X, Y: Integer; HighLight, ExtraShadow, Dimmed: Boolean); var Points: array[0..5] of TPoint; begin if Dimmed then begin Canvas.Brush.Color := clBtnFace; Canvas.Pen.Color := clBtnShadow; HighLight := False; ExtraShadow := False; end else begin Canvas.Brush.Color := clBtnFace; Canvas.Pen.Color := clBlack; end; // Using polygons instead of normal line drawing and floodfill. // Floodfill does not always fill the entire area. This especially // happens when scrolling the stuff in and out of a view area. with Canvas do case Graphic of igUp: begin Points[0] := Point(X+4, Y+0); Points[1] := Point(X+8, Y+4); Points[2] := Point(X+8, Y+7); Points[3] := Point(X+0, Y+7); Points[4] := Point(X+0, Y+4); Points[5] := Point(X+0, Y+4); Polygon(Points); if HighLight then begin Pen.Color := clWhite; MoveTo(X+4, Y+1); LineTo(X+1, Y+4); LineTo(X+1, Y+6); end; if ExtraShadow then begin Pen.Color := clBtnShadow; LineTo(X+7, Y+6); LineTo(X+7, Y+4); LineTo(X+3, Y); end; end; igDown: begin Points[0] := Point(X+0, Y+0); Points[1] := Point(X+8, Y+0); Points[2] := Point(X+8, Y+3); Points[3] := Point(X+4, Y+7); Points[4] := Point(X+0, Y+3); Points[5] := Point(X+0, Y+3); Polygon(Points); if HighLight then begin Pen.Color := clWhite; MoveTo(X+4, Y+6); LineTo(X+1, Y+3); LineTo(X+1, Y+1); LineTo(X+7, Y+1); end; if ExtraShadow then begin Pen.Color := clBtnShadow; LineTo(X+7, Y+3); LineTo(X+3, Y+7); end; end; igRectangle, igLevelDec2, igLevelInc2: begin Points[0] := Point(X+0, Y+0); Points[1] := Point(X+8, Y+0); Points[2] := Point(X+8, Y+6); Points[3] := Point(X+0, Y+6); Points[4] := Point(X+0, Y+0); Points[5] := Point(X+0, Y+0); Polygon(Points); if HighLight then begin Pen.Color := clWhite; MoveTo(X+1, Y+4); LineTo(X+1, Y+1); LineTo(X+7, Y+1); end; if ExtraShadow then begin Pen.Color := clBtnShadow; LineTo(X+7, Y+5); LineTo(X+0, Y+5); end; case Graphic of igLevelDec2: begin Pen.Color := clBlack; MoveTo(X+6, Y+3); LineTo(X+1, Y+3); MoveTo(X+4, Y+1); LineTo(X+4, Y+6); MoveTo(X+3, Y+2); LineTo(X+3, Y+5); end; igLevelInc2: begin Pen.Color := clBlack; MoveTo(X+2, Y+3); LineTo(X+7, Y+3); MoveTo(X+4, Y+1); LineTo(X+4, Y+6); MoveTo(X+5, Y+2); LineTo(X+5, Y+5); end; end; end; igLevelDec1: begin Points[0] := Point(X+8, Y+0); Points[1] := Point(X+5, Y+0); Points[2] := Point(X+2, Y+3); Points[3] := Point(X+5, Y+6); Points[4] := Point(X+8, Y+6); Points[5] := Point(X+8, Y+0); Polygon(Points); if HighLight then begin Pen.Color := clWhite; MoveTo(X+3, Y+3); LineTo(X+5, Y+1); LineTo(X+7, Y+1); end; if ExtraShadow then begin Pen.Color := clBtnShadow; LineTo(X+7, Y+5); LineTo(X+5, Y+5); LineTo(X+2, Y+2); end; end; igLevelInc1: begin Points[0] := Point(X+0, Y+0); Points[1] := Point(X+3, Y+0); Points[2] := Point(X+6, Y+3); Points[3] := Point(X+3, Y+6); Points[4] := Point(X+0, Y+6); Points[5] := Point(X+0, Y+0); Polygon(Points); if HighLight then begin Pen.Color := clWhite; MoveTo(X+1, Y+4); LineTo(X+1, Y+1); LineTo(X+3, Y+1); end; if ExtraShadow then begin Pen.Color := clBtnShadow; LineTo(X+5, Y+3); LineTo(X+3, Y+5); LineTo(X+0, Y+5); end; end; end; end; procedure TCustomRuler.PaintHIndents(Canvas: TCanvas; R: TRect); var I: TIndentType; begin if roItemsShowLastPos in Options then begin for I := High(TIndentType) downto Low(TIndentType) do with FIndentTraces[I] do begin PaintHIndent(Canvas, Graphic, Left, Top, False, False, True); if (I = itBoth) and (Graphic <> igNone) and ListEditor.Active and (leoLevelAdjustable in ListEditor.Options) then begin if ListEditor.LevelGraphic = lgType1 then begin PaintHIndent(Canvas, igLevelDec1, Left - 8, Top, False, False, True); PaintHIndent(Canvas, igLevelInc1, Left + 8, Top, False, False, True); end else begin PaintHIndent(Canvas, igLevelDec2, Left - 8, Top, False, False, True); PaintHIndent(Canvas, igLevelInc2, Left + 8, Top, False, False, True); end; end; end; end; for I := High(TIndentType) downto Low(TIndentType) do with FIndents[I] do begin case I of itBoth: begin Top := R.Bottom; if FDragInfo.Item <> diIndent then begin if TableEditor.Active then begin Left := TableEditor.CalculateCurrentIndentPosition(I); Left := TableEditor.RTLAdjust(Left, IndentOffset); end else begin Left := RTLAdjust(StartMarginGrip, 0) + Round(ZUnitsToPixs(FirstIndent + LeftIndent)); Left := RTLAdjust(Left, IndentOffset) end; end; if not (ioShowLeftIndent in IndentSettings.Options) then Continue; end; itFirst: begin Top := 0; if FDragInfo.Item <> diIndent then begin if TableEditor.Active then begin Left := TableEditor.CalculateCurrentIndentPosition(I); Left := TableEditor.RTLAdjust(Left, IndentOffset); end else begin Left := RTLAdjust(StartMarginGrip, 0) + Round(ZUnitsToPixs(FirstIndent)); Left := RTLAdjust(Left, IndentOffset) end; end; if not (ioShowFirstIndent in IndentSettings.Options) then Continue; end; itLeft: begin Top := R.Bottom - 7; if FDragInfo.Item <> diIndent then begin if TableEditor.Active then begin Left := TableEditor.CalculateCurrentIndentPosition(I); Left := TableEditor.RTLAdjust(Left, IndentOffset); end else begin Left := RTLAdjust(StartMarginGrip, 0) + Round(ZUnitsToPixs(FirstIndent + LeftIndent)); Left := RTLAdjust(Left, IndentOffset) end; end; if not (ioShowHangingIndent in IndentSettings.Options) then Continue; end; itRight: begin Top := R.Bottom - 7; if FDragInfo.Item <> diIndent then begin if TableEditor.Active then begin Left := TableEditor.CalculateCurrentIndentPosition(I); Left := TableEditor.RTLAdjust(Left, IndentOffset); end else begin Left := RTLAdjust(EndMarginGrip, 0) - Round(ZUnitsToPixs(RightIndent)); Left := RTLAdjust(Left, IndentOffset) end; end; if not (ioShowRightIndent in IndentSettings.Options) then Continue; end; end; PaintHIndent(Canvas, Graphic, Left, Top, True, ioExtraShadow in IndentSettings.Options, False); if (I = itBoth) and (Graphic <> igNone) and ListEditor.Active and (leoLevelAdjustable in ListEditor.Options) then begin if ListEditor.LevelGraphic = lgType1 then begin PaintHIndent(Canvas, igLevelDec1, Left - 8, Top, True, ioExtraShadow in IndentSettings.Options, False); PaintHIndent(Canvas, igLevelInc1, Left + 8, Top, True, ioExtraShadow in IndentSettings.Options, False); end else begin PaintHIndent(Canvas, igLevelDec2, Left - 8, Top, True, ioExtraShadow in IndentSettings.Options, False); PaintHIndent(Canvas, igLevelInc2, Left + 8, Top, True, ioExtraShadow in IndentSettings.Options, False); end; end; end; end; procedure TCustomRuler.PaintHMargins(Canvas: TCanvas; R: TRect); var MT: TMarginType; MR: TRect; begin for MT := mtLeft to mtRight do with FMargins[MT], Canvas do begin MR := GetMarginRect(MT); if MT = mtLeft then begin if FDragInfo.Item <> diMargin then Grip := MR.Right; MR.Right := Grip; end else begin if FDragInfo.Item <> diMargin then Grip := MR.Left; MR.Left := Grip + 1; end; if MR.Left < 2 then MR.Left := 2; if MR.Right > (Width - 2) then MR.Right := (Width - 2); if MR.Left > MR.Right then Continue; if Flat then begin Dec(MR.Top, 2); Inc(MR.Bottom, 2); if MT = mtLeft then Dec(MR.Left) else Inc(MR.Right); end; Brush.Color := MarginColor; FillRect(MR); if (MarginSettings.GripColor <> MarginColor) and (MarginSettings.GripColor <> RulerColor) then begin if MT = mtLeft then begin MR.Left := IMax(MR.Left, MR.Right - 2); MR.Right := MR.Right + 3; end else begin MR.Right := IMin(MR.Right, MR.Left + 2); MR.Left := MR.Left - 3; end; if MR.Left > MR.Right then Continue; Brush.Color := MarginSettings.GripColor; FillRect(MR); end; end; end; procedure TCustomRuler.PaintHMarkers(Canvas: TCanvas; R: TRect); var ClipR: HRGN; D: Integer; DotH: Integer; DotX: Integer; DotY: Integer; I: Integer; MarkH: Integer; MarkX: Integer; MarkY: Integer; N: Integer; M: Extended; MG: Integer; Number: Integer; NumbX: Integer; NumbY: Integer; S: string; TH: Integer; TW: Integer; TR: TRect; Z: Integer; begin Canvas.Font := Self.Font; TH := Canvas.TextHeight('0123456789'); DotH := TH div 5; // Height of the dot markers DotY := ((R.Bottom - 2 - DotH) div 2) + 2; MarkH := TH div 3; // Height of the halfway markers MarkY := ((R.Bottom - 2 - MarkH) div 2) + 2; N := NumberIncrements[UnitsDisplay]; M := MarkerIncrements[UnitsDisplay]; D := DotMarkers[UnitsDisplay]; Z := IMax(1, Round(100 / Zoom)); N := Z * N; M := Z * M; if roScaleRelativeToMargin in Options then begin MG := RTLAdjust(StartMarginGrip, Inset); Number := Pred(Trunc(ZPixsToUnits(-MG) * UnitsPerInch(UnitsDisplay) / UnitsPerInch(UnitsProgram))); end else begin MG := 0; Number := 0; end; with Canvas do begin TR := ClientRect; TR.Left := TR.Left + Inset; TR := RTLAdjustRect(TR); InflateRect(TR, -3, -3); // Prevent the markers to paint over the right edge. ClipR := CreateRectRgn(TR.Left, TR.Top, TR.Right, TR.Bottom); SelectClipRgn(Handle, ClipR); DeleteObject(ClipR); Pen.Color := clBlack; Brush.Style := bsClear; repeat Inc(Number); NumbX := Number * ScreenRes; // X offset of center of number markers (inch based) MarkX := NumbX - ScreenRes div 2; // X offset of center of halfway markers NumbX := ZoomAndRound(N * NumbX / UnitsPerInch(UnitsDisplay)); MarkX := ZoomAndRound(N * MarkX / UnitsPerInch(UnitsDisplay)); NumbX := Inset + NumbX; // X position of number markers MarkX := Inset + MarkX; // X position of halfway markers NumbX := MG + NumbX; // Adjust for possible relative display MarkX := MG + MarkX; MarkX := RTLAdjust(MarkX, 0); NumbX := RTLAdjust(NumbX, 0); S := IntToStr(Abs(N * Number)); TW := TextWidth(S); NumbX := NumbX - (TW div 2); // Center number markers NumbY := ((R.Bottom - 2 - TH) div 2) + 2; TextRect(TR, NumbX, NumbY, S); // Draw halfway markers if UnitsDisplay in [ruPicas, ruPoints] then begin MoveTo(MarkX, DotY); LineTo(MarkX, DotY + DotH); end else begin MoveTo(MarkX, MarkY); LineTo(MarkX, MarkY + MarkH); end; // Draw dot markers for I := 1 to D do begin Z := ZoomAndRound(I * M * ScreenRes / UnitsPerInch(UnitsDisplay)); DotX := MarkX + Z; MoveTo(DotX, DotY); LineTo(DotX, DotY + DotH); DotX := MarkX - Z; MoveTo(DotX, DotY); LineTo(DotX, DotY + DotH); end; NumbX := RTLAdjust(NumbX, 0); until NumbX > Width; SelectClipRgn(Canvas.Handle, 0); end; end; procedure TCustomRuler.PaintHOutline(Canvas: TCanvas; R: TRect); var R2: TRect; function LocalRTLAdjustRect(const R: TRect): TRect; begin if UseRTL then Result := Rect(Width - R.Right, R.Top, Width - R.Left, R.Bottom) else Result := R; end; begin with Canvas do begin Brush.Color := RulerColor; Brush.Style := bsSolid; R2 := Rect(Inset, 2, R.Right, R.Bottom - 1); R2 := LocalRTLAdjustRect(R2); if R2.Left < 1 then R2.Left := 0; if R2.Right > Width then R2.Right := Width; if R2.Left < R2.Right then begin FillRect(R2); if UseRTL then begin Dec(R2.Left); Inc(R2.Right); end else begin Dec(R2.Left); Inc(R2.Right); end; if R2.Left < 1 then R2.Left := 0; if R2.Right > Width then R2.Right := Width; if not Flat then Windows.DrawEdge(Canvas.Handle, R2, EDGE_SUNKEN, BF_RECT); end; // Area to the right of the paper Brush.Color := clBtnFace; R2.Left := Inset + Round(ZUnitsToPixs(PageWidth)) + 1; R2 := Rect(R2.Left, 2, R.Right, R.Bottom - 1); R2 := LocalRTLAdjustRect(R2); if R2.Left < R2.Right then begin FillRect(R2); if UseRTL then Inc(R2.Right, 2) else Dec(R2.Left); if not Flat then Windows.DrawEdge(Canvas.Handle, R2, EDGE_ETCHED, BF_RECT); end; end; end; procedure TCustomRuler.PaintHTableGraphic(Canvas: TCanvas; Graphic: TTableGraphic; R: TRect); var I: Integer; X, Y, B: Integer; begin X := R.Left; Y := R.Top; B := R.Bottom; with Canvas do begin if Flat then begin Pen.Color := TableEditor.BackGroundColor; Brush.Color := TableEditor.BackGroundColor; Rectangle(R.Left, R.Top+2, R.Right, R.Bottom-2); end else begin Pen.Color := clBlack; Brush.Color := TableEditor.BackGroundColor; Rectangle(R.Left, R.Top, R.Right, R.Bottom); Pen.Color := clWhite; MoveTo(X+7, Y+1); LineTo(X+1, Y+1); LineTo(X+1, B-2); end; case Graphic of tgBorder: begin Pen.Color := TableEditor.ForeGroundColor; I := Y + 3; while I < B - 3 do begin MoveTo(X+2, I); LineTo(X+3, I); MoveTo(X+4, I); LineTo(X+5, I); MoveTo(X+6, I); LineTo(X+7, I); I := I + 2; end; end; tgColumn: begin Pen.Color := TableEditor.ForeGroundColor; MoveTo(X+2, Y+5); LineTo(X+3, Y+5); LineTo(X+3, B-6); LineTo(X+1, B-6); MoveTo(X+6, Y+5); LineTo(X+5, Y+5); LineTo(X+5, B-6); LineTo(X+7, B-6); end; end; end; end; procedure TCustomRuler.PaintHTableGraphics(Canvas: TCanvas; R: TRect); var BT: TBorderType; I: Integer; RG: TRect; begin if not TableEditor.Active or (TableEditor.Cells.Count < 1) then Exit; for BT := Low(TBorderType) to High(TBorderType) do with TableEditor, TableEditor.FBorders[BT] do begin if FDragInfo.Item <> diBorder then begin Left := TableEditor.Offset + Round(ZUnitsToPixs(Position)) - BorderOffset; if DraggedWithShift and (BT = btRight) then Left := Left + FDragLast - FDragStart; end else if (Integer(btLeft) = FDragInfo.Index) and (BT = btRight) then Left := TableEditor.FBorders[btLeft].Left + Round(ZUnitsToPixs(TableEditor.TableWidth)); RG := Rect(Left, 0, Left + 9, R.Bottom + 1); PaintHTableGraphic(Canvas, tgBorder, RG) end; // Never paint the last ColumnGraphic. for I := 0 to TableEditor.LastValidCellIndex - 1 do with TableEditor, TableEditor.Cells[I] do if CellWidth >= 0 then begin if (FDragInfo.Item <> diColumn) then Left := FBorders[btLeft].Left + Trunc(ZUnitsToPixs(Position)) else if (DraggedWithShift and (I > FDragInfo.Index)) then Left := FBorders[btLeft].Left + FDragLast - FDragStart + Trunc(ZUnitsToPixs(Position)); RG := Rect(Left, 0, Left + 9, R.Bottom + 1); PaintHTableGraphic(Canvas, tgColumn, RG); end; end; procedure TCustomRuler.PaintHTab(Canvas: TCanvas; Graphic: TTabAlign; X, Y: Integer); begin if UseRTL then X := Pred(X); with Canvas do case Graphic of taLeftAlign: begin MoveTo(X+0, Y+0); LineTo(X+0, Y+5); LineTo(X+6, Y+5); MoveTo(X+1, Y+0); LineTo(X+1, Y+4); LineTo(X+6, Y+4); end; taCenterAlign: begin MoveTo(X+0, Y+5); LineTo(X+8, Y+5); MoveTo(X+0, Y+4); LineTo(X+8, Y+4); MoveTo(X+3, Y+0); LineTo(X+3, Y+4); MoveTo(X+4, Y+0); LineTo(X+4, Y+4); end; taRightAlign: begin MoveTo(X+5, Y+0); LineTo(X+5, Y+5); LineTo(X-1, Y+5); MoveTo(X+4, Y+0); LineTo(X+4, Y+4); LineTo(X-1, Y+4); end; taDecimalAlign: begin MoveTo(X+0, Y+5); LineTo(X+8, Y+5); MoveTo(X+0, Y+4); LineTo(X+8, Y+4); MoveTo(X+3, Y+0); LineTo(X+3, Y+4); MoveTo(X+4, Y+0); LineTo(X+4, Y+4); MoveTo(X+6, Y+1); LineTo(X+8, Y+1); MoveTo(X+6, Y+2); LineTo(X+8, Y+2); end; taWordBarAlign: begin MoveTo(X+3, Y+0); LineTo(X+3, Y+6); MoveTo(X+4, Y+0); LineTo(X+4, Y+6); end; end; end; procedure TCustomRuler.PaintHTabs(Canvas: TCanvas; R: TRect); var I: Integer; begin if roItemsShowLastPos in Options then if Assigned(FTabTrace) then begin Canvas.Pen.Color := clBtnShadow; with FTabTrace do PaintHTab(Canvas, RTLAlign, Left, Top); end; for I := 0 to Tabs.Count - 1 do begin with Tabs[I] do begin if FDeleting then Canvas.Pen.Color := clBtnFace else Canvas.Pen.Color := Color; if FDragInfo.Item <> diTab then if TableEditor.Active then begin Left := TableEditor.GetCellRect(TableEditor.CellIndex).Left; Left := Left + Round(ZUnitsToPixs(Position)); Left := TableEditor.RTLAdjust(Left, TabOffset[RTLAlign]); end else begin Left := RTLAdjust(StartMarginGrip, 0); Left := Left + Round(ZUnitsToPixs(Position)); Left := RTLAdjust(Left, TabOffset[RTLAlign]); end; Top := R.Bottom - 8; PaintHTab(Canvas, RTLAlign, Left, Top); end; end; end; procedure TCustomRuler.PaintVerticalRuler(Canvas: TCanvas); var R: TRect; begin R := Rect(0, 0, Width, Height); PaintVOutline(Canvas, R); PaintVMargins(Canvas, R); PaintVMarkers(Canvas, R); end; procedure TCustomRuler.PaintVMargins(Canvas: TCanvas; R: TRect); var MT: TMarginType; MR: TRect; begin for MT := mtTop to mtBottom do with FMargins[MT], Canvas do begin MR := GetMarginRect(MT); if MT = mtTop then begin if FDragInfo.Item <> diMargin then Grip := MR.Bottom; MR.Bottom := Grip; end else begin if FDragInfo.Item <> diMargin then Grip := MR.Top; MR.Top := Grip + 1; end; if MR.Top < 2 then MR.Top := 2; if MR.Bottom > (Height - 2) then MR.Bottom := (Height - 2); if MR.Top > MR.Bottom then Continue; if Flat then begin Dec(MR.Left, 2); Inc(MR.Right, 2); if MT = mtTop then Dec(MR.Top) else Inc(MR.Bottom); end; Brush.Color := MarginColor; FillRect(MR); if (MarginSettings.GripColor <> MarginColor) and (MarginSettings.GripColor <> RulerColor) then begin if MT = mtTop then begin MR.Top := IMax(MR.Top, MR.Bottom - 2); MR.Bottom := MR.Bottom + 3; end else begin MR.Bottom := IMin(MR.Bottom, MR.Top + 2); MR.Top := MR.Top - 3; end; if MR.Top > MR.Bottom then Continue; Brush.Color := MarginSettings.GripColor; FillRect(MR); end; end; end; procedure TCustomRuler.PaintVMarkers(Canvas: TCanvas; R: TRect); var ClipR: HRGN; D: Integer; DotX: Integer; DotY: Integer; DotW: Integer; I: Integer; MarkX: Integer; MarkY: Integer; MarkW: Integer; N: Integer; M: Extended; MG: Integer; Number: Integer; NumbX: Integer; NumbY: Integer; S: string; TH: Integer; TW: Integer; TR: TRect; Z: Integer; lf: TLogFont; tf: TFont; begin // Get 90 degrees rotated font Canvas.Font := Self.Font; with Canvas do begin tf := TFont.Create; tf.Assign(Font); GetObject(tf.Handle, sizeof(lf), @lf); lf.lfEscapement := 900; // angle * 10 lf.lfOrientation := 900; tf.Handle := CreateFontIndirect(lf); Font.Assign(tf); tf.Free; end; TH := Canvas.TextHeight('0123456789'); DotW := TH div 5; // Width of the dot markers DotX := ((R.Right - 2 - DotW) div 2) + 2; MarkW := TH div 3; // Width of the halfway markers MarkX := ((R.Right - 2 - MarkW) div 2) + 2; N := NumberIncrements[UnitsDisplay]; M := MarkerIncrements[UnitsDisplay]; D := DotMarkers[UnitsDisplay]; Z := IMax(1, Round(100 / Zoom)); N := Z * N; M := Z * M; if roScaleRelativeToMargin in Options then begin MG := FMargins[mtTop].Grip - Inset; Number := Pred(Trunc(ZPixsToUnits(-MG) * UnitsPerInch(UnitsDisplay) / UnitsPerInch(UnitsProgram))); end else begin MG := 0; Number := 0; end; with Canvas do begin TR := ClientRect; TR.Top := TR.Top + Inset; InflateRect(TR, -3, -3); // Prevent the markers to paint over the right edge. ClipR := CreateRectRgn(TR.Left, TR.Top, TR.Right, TR.Bottom); SelectClipRgn(Handle, ClipR); DeleteObject(ClipR); Pen.Color := clBlack; Brush.Style := bsClear; repeat Inc(Number); NumbY := Number * ScreenRes; // Y offset of center of number markers (inch based) MarkY := NumbY - ScreenRes div 2; // Y offset of center of half-inch markers NumbY := ZoomAndRound(N * NumbY / UnitsPerInch(UnitsDisplay)); MarkY := ZoomAndRound(N * MarkY / UnitsPerInch(UnitsDisplay)); NumbY := Inset + NumbY; // Y position of number markers MarkY := Inset + MarkY; // Y position of halfway markers NumbY := MG + NumbY; // Adjust for possible relative display MarkY := MG + MarkY; S := IntToStr(Abs(N * Number)); TW := TextWidth(S); NumbY := NumbY + (TW div 2); // Center number markers NumbX := ((R.Right - 2 - TH) div 2) + 2; TextRect(TR, NumbX, NumbY, S); // Draw halfway markers if UnitsDisplay in [ruPicas, ruPoints] then begin MoveTo(DotX, MarkY); LineTo(DotX + DotW, MarkY); end else begin MoveTo(MarkX, MarkY); LineTo(MarkX + MarkW, MarkY); end; // Draw dot markers for I := 1 to D do begin Z := ZoomAndRound(I * M * ScreenRes / UnitsPerInch(UnitsDisplay)); DotY := MarkY + Z; MoveTo(DotX, DotY); LineTo(DotX + DotW, DotY); DotY := MarkY - Z; MoveTo(DotX, DotY); LineTo(DotX + DotW, DotY); end; until NumbY > Height; SelectClipRgn(Canvas.Handle, 0); end; end; procedure TCustomRuler.PaintVOutline(Canvas: TCanvas; R: TRect); var R2: TRect; begin with Canvas do begin Brush.Color := RulerColor; Brush.Style := bsSolid; R2 := Rect(2, Inset, R.Right - 1, R.Bottom - 1); if R2.Top < 1 then R2.Top := 0; if R2.Top < R2.Bottom then begin FillRect(R2); Dec(R2.Top); Inc(R2.Bottom); if R2.Top < 1 then R2.Top := 0; if not Flat then Windows.DrawEdge(Canvas.Handle, R2, EDGE_SUNKEN, BF_RECT); end; // Area at the bottom of the paper Brush.Color := clBtnFace; R2.Top := Inset + Round(ZUnitsToPixs(PageHeight)) + 1; R2 := Rect(2, R2.Top, R.Right - 1, R.Bottom - 1); if R2.Top < R2.Bottom then begin FillRect(R2); Dec(R2.Top); Inc(R2.Bottom); if not Flat then Windows.DrawEdge(Canvas.Handle, R2, EDGE_ETCHED, BF_RECT); end; end; end; function TCustomRuler.PixsToUnits(const Value: Extended): Extended; begin Result := Value / MultiPixels; end; function TCustomRuler.PointsToUnits(const Value: Extended): Extended; begin Result := Value / MultiPoints; end; procedure TCustomRuler.PopupClick(Sender: TObject); var I: Integer; begin // The Popupmenu itself holds the TabIndex in its Tag property I := (Sender as TMenuItem).GetParentComponent.Tag; Tabs[I].Align := TTabAlign(TMenuItem(Sender).Tag); end; procedure TCustomRuler.ProcessParentBackground(B: Boolean); begin {$IFDEF COMPILER7_UP} if B then begin FOldParentBackground := ParentBackground; if FOldParentBackground then ParentBackground := False; end else if FOldParentBackground then ParentBackground := True; {$ENDIF} end; procedure TCustomRuler.RestoreHint; var P: TPoint; {$IFNDEF COMPILER5_UP} M: TWMMouse; {$ENDIF} begin if FOvrHint then begin FOvrHint := False; Hint := FOrgHint; GetCursorPos(P); {$IFDEF COMPILER5_UP} Application.ActivateHint(P); {$ELSE} M.Pos.X := -1; M.Pos.Y := -1; Application.HintMouseMessage(Self, TMessage(M)); M.Pos.X := P.X; M.Pos.Y := P.Y; Application.HintMouseMessage(Self, TMessage(M)); {$ENDIF} end; end; function TCustomRuler.RTLAdjust(X, Offset: Integer): Integer; begin if UseRTL then Result := Pred(Width - (X + Offset)) else Result := X - Offset; end; function TCustomRuler.RTLAdjustRect(const R: TRect): TRect; begin if UseRTL then Result := Rect(Pred(Width - R.Right), R.Top, Pred(Width - R.Left), R.Bottom) else Result := R; end; procedure TCustomRuler.SetBiDiModeRuler(const Value: TBiDiModeRuler); begin if FBiDiModeRuler <> Value then begin FBiDiModeRuler := Value; DoBiDiModeChanged; Invalidate; end; end; procedure TCustomRuler.SetBottomMargin(Value: Extended); begin if Value <> BottomMargin then begin if not (csLoading in ComponentState) then if Value < 0 then Value := 0 else if TopMargin + Value > PageHeight then Value := PageHeight - TopMargin; FMargins[mtBottom].Position := Value; DoMarginChanged; Invalidate; end; end; procedure TCustomRuler.SetDefaultTabWidth(const Value: Extended); begin if FDefaultTabWidth <> Value then begin if Value > 0 then FDefaultTabWidth := Value; Invalidate; end; end; procedure TCustomRuler.SetFirstIndent(Value: Extended); var MinValue: Extended; WorkWidth: Extended; begin if Value <> FirstIndent then begin if not (csLoading in ComponentState) then begin if ioKeepWithinMargins in IndentSettings.Options then MinValue := 0 else MinValue := -StartMargin; if Value < MinValue then begin FIndents[itLeft].Position := FIndents[itLeft].Position + Value; Value := MinValue end else begin WorkWidth := PageWidth - RightMargin - LeftMargin; if Value > WorkWidth then begin FIndents[itLeft].Position := FIndents[itLeft].Position + Value - WorkWidth; Value := WorkWidth; end; end; end; FIndents[itFirst].Position := Value; DoIndentChanged; Invalidate; end; end; procedure TCustomRuler.SetFlat(const Value: Boolean); begin if FFlat <> Value then begin FFlat := Value; Invalidate; end; end; procedure TCustomRuler.SetIndentSettings(const Value: TIndentSettings); begin FIndentSettings.Assign(Value); end; procedure TCustomRuler.SetInset(const Value: Integer); begin if Value <> FInset then begin FInset := Value; Invalidate; end; end; procedure TCustomRuler.SetItemSeparation(const Value: Integer); begin FItemSeparation := Value; end; procedure TCustomRuler.SetLeftIndent(Value: Extended); var MinValue: Extended; WorkWidth: Extended; begin if Value <> LeftIndent then begin if not (csLoading in ComponentState) then begin if ioKeepWithinMargins in IndentSettings.Options then MinValue := 0 else MinValue := -StartMargin; if FirstIndent + Value < MinValue then Value := -FirstIndent else begin WorkWidth := PageWidth - RightMargin - LeftMargin; if FirstIndent + Value >= WorkWidth - RightIndent then Value := WorkWidth - RightIndent - FirstIndent end; end; FIndents[itLeft].Position := Value; DoIndentChanged; Invalidate; end; end; procedure TCustomRuler.SetLeftMargin(Value: Extended); begin if Value <> LeftMargin then begin if not (csLoading in ComponentState) then if Value < 0 then Value := 0 else if RightMargin + Value > PageWidth then Value := PageWidth - RightMargin; FMargins[mtLeft].Position := Value; DoMarginChanged; Invalidate; end; end; procedure TCustomRuler.SetListEditor(const Value: TRulerListEditor); begin FListEditor := Value; end; procedure TCustomRuler.SetMarginColor(const Value: TColor); begin if Value <> FMarginColor then begin FMarginColor := Value; Invalidate; end; end; procedure TCustomRuler.SetMarginSettings(const Value: TMarginSettings); begin FMarginSettings.Assign(Value); end; procedure TCustomRuler.SetMaxTabs(const Value: Integer); begin if Value <> FMaxTabs then begin FMaxTabs := Value; while Tabs.Count > FMaxTabs do Tabs.Items[Tabs.Count-1].Free; end; end; procedure TCustomRuler.SetPageHeight(const Value: Extended); begin if FPageHeight <> Value then begin FPageHeight := Value; Invalidate; end; end; procedure TCustomRuler.SetPageWidth(const Value: Extended); begin if FPageWidth <> Value then begin FPageWidth := Value; Invalidate; end; end; procedure TCustomRuler.SetRightIndent(Value: Extended); var MinValue: Extended; begin if Value <> RightIndent then begin if not (csLoading in ComponentState) then begin if ioKeepWithinMargins in IndentSettings.Options then MinValue := 0 else MinValue := -EndMargin; if Value < MinValue then Value := MinValue else if PageWidth - EndMargin - Value <= StartMargin + FirstIndent then Value := StartMargin + FirstIndent - PageWidth + EndMargin; end; FIndents[itRight].Position := Value; DoIndentChanged; Invalidate; end; end; procedure TCustomRuler.SetRightMargin(Value: Extended); begin if Value <> RightMargin then begin if not (csLoading in ComponentState) then if Value < 0 then Value := 0 else if LeftMargin + Value > PageWidth then Value := PageWidth - LeftMargin; FMargins[mtRight].Position := Value; DoMarginChanged; Invalidate; end; end; procedure TCustomRuler.SetRulerColor(const Value: TColor); begin if Value <> FRulerColor then begin FRulerColor := Value; Invalidate; end; end; procedure TCustomRuler.SetRulerOptions(const Value: TRulerOptions); begin if FRulerOptions <> Value then begin FRulerOptions := Value; FTimer.Enabled := roAutoUpdatePrinterWidth in FRulerOptions; Invalidate; end; end; procedure TCustomRuler.SetRulerTexts(const Value: TRulerTexts); begin FRulerTexts := Value; end; procedure TCustomRuler.SetRulerType(const Value: TRulerType); var DC: HDC; begin if FRulerType <> Value then begin FRulerType := Value; DC := GetDC(0); try if FRulerType = rtHorizontal then ScreenRes := GetDeviceCaps(DC, LOGPIXELSX) // Pixels per inch else ScreenRes := GetDeviceCaps(DC, LOGPIXELSY); finally ReleaseDC(0, DC); end; Invalidate; // Rotate ruler if not (csReading in ComponentState) then SetBounds(Left, Top, Height, Width); end; end; procedure TCustomRuler.SetScreenRes(const Value: Integer); begin if FScreenRes <> Value then begin FScreenRes := Value; SetUnitsProgram(UnitsProgram); Invalidate; end; end; procedure TCustomRuler.SetTableEditor(const Value: TRulerTableEditor); begin FTableEditor := Value; end; procedure TCustomRuler.SetTabs(const Value: TTabs); begin FTabs := Value; end; procedure TCustomRuler.SetTabSettings(const Value: TTabSettings); begin FTabSettings.Assign(Value); end; procedure TCustomRuler.SetTopMargin(Value: Extended); begin if Value <> TopMargin then begin if not (csLoading in ComponentState) then if Value < 0 then Value := 0 else if BottomMargin + Value > PageHeight then Value := PageHeight - BottomMargin; FMargins[mtTop].Position := Value; DoMarginChanged; Invalidate; end; end; procedure TCustomRuler.SetUnitsDisplay(const Value: TRulerUnits); begin if FUnitsDisplay <> Value then begin FUnitsDisplay := Value; Invalidate; end; end; procedure TCustomRuler.SetUnitsProgram(const Value: TRulerUnits); var M: Extended; I: Integer; begin if Value <> FUnitsProgram then begin M := UnitsPerInch(Value) / UnitsPerInch(FUnitsProgram); FUnitsProgram := Value; PageHeight := M * PageHeight; PageWidth := M * PageWidth; if not (csLoading in ComponentState) then begin FDefaultTabWidth := M * DefaultTabWidth; FIndents[itFirst].Position := M * FirstIndent; FIndents[itLeft].Position := M * LeftIndent; FIndents[itRight].Position := M * RightIndent; FMargins[mtTop].Position := M * TopMargin; FMargins[mtBottom].Position:= M * BottomMargin; FMargins[mtLeft].Position := M * LeftMargin; FMargins[mtRight].Position := M * RightMargin; for I := 0 to FTabs.Count - 1 do FTabs[I].Position := M * FTabs[I].Position; with TableEditor do begin FBorderHSpacing := M * BorderHSpacing; FBorderWidth := M * BorderWidth; FCellBorderWidth:= M * CellBorderWidth; FCellHSpacing := M * CellHSpacing; FCellPadding := M * CellPadding; FFirstIndent := M * FirstIndent; FLeftIndent := M * LeftIndent; FRightIndent := M * RightIndent; FBorders[btLeft].Position := M * FBorders[btLeft].Position; FBorders[btRight].Position := M * FBorders[btRight].Position; for I := 0 to Cells.Count - 1 do if Cells[I].CellWidth >= 0 then Cells[I].CellWidth := M * Cells[I].CellWidth; end; Invalidate; end; end; // FMultiPixels can be used to convert Units to pixels. // 1 / FMultiPixels can of course be used for the reversed effect. FMultiPixels := UnitsPerInch(ruPixels) / UnitsPerInch(FUnitsProgram); // FMultiPoints can be used to convert Units to Points // 1 / FMultiPoints can of course be used for the reversed effect. FMultiPoints := UnitsPerInch(ruPoints) / UnitsPerInch(FUnitsProgram); end; procedure TCustomRuler.SetZoom(const Value: TZoomRange); begin if FZoom <> Value then begin FZoom := Value; Invalidate; end; end; procedure TCustomRuler.TimerProc(Sender: TObject); begin UpdatePageDimensions; end; function TCustomRuler.UnitsPerInch(Units: TRulerUnits): Extended; begin case Units of ruCentimeters: Result := cmPerInch; ruMillimeters: Result := mmPerInch; ruPicas: Result := PicasPerInch; ruPixels: Result := ScreenRes; ruPoints: Result := PointsPerInch; else Result := 1; end; end; function TCustomRuler.UnitsToPixs(const Value: Extended): Extended; begin Result := Value * MultiPixels; end; function TCustomRuler.UnitsToPoints(const Value: Extended): Extended; begin Result := Value * MultiPoints; end; procedure TCustomRuler.UpdatePageDimensions; var InchHeight: Extended; InchWidth: Extended; PixsInchX: Integer; PixsInchY: Integer; PhysHeight: Integer; PhysWidth: Integer; PrinterHandle: HDC; begin PrinterHandle := 0; {$IFNDEF FPC} try if ((roUseDefaultPrinterWidth in FRulerOptions) or (roAutoUpdatePrinterWidth in FRulerOptions)) and (Printer.Printers.Count > 0) then PrinterHandle := Printer.Handle; except // Eat errors in case the default printer is not available. end; {$ENDIF} if PrinterHandle <> 0 then begin PixsInchX := GetDeviceCaps(PrinterHandle, LOGPIXELSX); PixsInchY := GetDeviceCaps(PrinterHandle, LOGPIXELSY); PhysWidth := GetDeviceCaps(PrinterHandle, PHYSICALWIDTH); InchWidth := PhysWidth / PixsInchX; PhysHeight := GetDeviceCaps(PrinterHandle, PHYSICALHEIGHT); InchHeight := PhysHeight / PixsInchY; end else begin InchWidth := 8.5; InchHeight := 11; end; if InchWidth <> FPrinterWidth then begin FPrinterWidth := InchWidth; PageWidth := InchWidth * UnitsPerInch(UnitsProgram); end; if InchHeight <> FPrinterHeight then begin FPrinterHeight := InchHeight; PageHeight := InchHeight * UnitsPerInch(UnitsProgram); end; end; function TCustomRuler.UseRTL: Boolean; begin Result := False; case BiDiModeRuler of bmRightToLeft: Result := True; bmUseBiDiMode: {$IFDEF COMPILER4_UP} Result := UseRightToLeftReading; {$ELSE} Result := False; {$ENDIF} end; end; function TCustomRuler.ZoomAndRound(const Value: Extended): Integer; begin Result := Round(Value * Zoom / 100); end; function TCustomRuler.ZPixsToUnits(const Value: Extended): Extended; begin Result := PixsToUnits(Value) * 100 / Zoom; end; function TCustomRuler.ZUnitsToPixs(const Value: Extended): Extended; begin Result := UnitsToPixs(Value) * Zoom / 100; end; { TVRuler } constructor TVRuler.Create(AOwner: TComponent); begin inherited Create(AOwner); Height := 600; Width := 21; Font.Name := 'Arial'; FIndentSettings.Options := []; FMarginSettings.DragCursor := crSizeNS; FMaxTabs := 0; FTabSettings.Options := []; FRulerType := rtVertical; end; { TRulerCell } constructor TRulerCell.Create(Collection: TCollection); begin inherited Create(Collection); FDragBoundary := -1; end; function TRulerCell.GetDragLimit: Integer; var I: Integer; X: Extended; begin with TCustomRuler(TRulerCells(Collection).GetOwner).TableEditor do begin X := BorderHSpacing; if Index < Collection.Count then begin for I := 0 to Index do if Cells[I].DragBoundary >= 0 then begin X := X + CellBorderWidth; X := X + Cells[I].DragBoundary; X := X + CellBorderWidth; X := X + CellHSpacing; end; X := X - 0.5 * CellHSpacing; end; Result := FBorders[btLeft].Left + Trunc(Ruler.ZUnitsToPixs(X)); end; end; function TRulerCell.GetPosition: Extended; var I: Integer; begin with TCustomRuler(TRulerCells(Collection).GetOwner).TableEditor do begin Result := BorderHSpacing; if Index < Collection.Count then begin for I := 0 to Index do if Cells[I].CellWidth >= 0 then begin Result := Result + CellBorderWidth; Result := Result + Cells[I].CellWidth; Result := Result + CellBorderWidth; Result := Result + CellHSpacing; end; Result := Result - 0.5 * CellHSpacing; end; end; end; procedure TRulerCell.SetCellWidth(const Value: Extended); begin if FCellWidth <> Value then begin FCellWidth := Value; TCustomRuler(TRulerCells(Collection).GetOwner).Invalidate; end; end; procedure TRulerCell.SetDragBoundary(const Value: Extended); begin FDragBoundary := Value; end; procedure TRulerCell.SetLeft(const Value: Integer); begin FLeft := Value; end; procedure TRulerCell.SetPosition(const Value: Extended); var I: Integer; begin with TCustomRuler(TRulerCells(Collection).GetOwner).TableEditor do begin FDraggedDelta := Value - Position; Collection.BeginUpdate; try CellWidth := CellWidth + FDraggedDelta; I := GetNextValidCell(Index); if I <= Collection.Count - 1 then Cells[I].CellWidth := Cells[I].CellWidth - FDraggedDelta; FDraggedColumn := Index; for I := Index + 1 to Cells.Count - 1 do if Cells[I].CellWidth < 0 then Inc(FDraggedColumn) else Break; finally Collection.EndUpdate; end; end; end; { TRulerCells } function TRulerCells.Add: TRulerCell; begin Result := TRulerCell(inherited Add); end; constructor TRulerCells.Create(AOwner: TCustomRuler); begin inherited Create(TRulerCell); FRuler := AOwner; end; function TRulerCells.GetCell(Index: Integer): TRulerCell; begin Result := TRulerCell(inherited Items[Index]); end; function TRulerCells.GetOwner: TPersistent; begin Result := FRuler; end; procedure TRulerCells.SetCell(Index: Integer; const Value: TRulerCell); begin inherited SetItem(Index, Value); FRuler.Invalidate; end; procedure TRulerCells.Update(Item: TCollectionItem); begin inherited; with FRuler do begin if csLoading in ComponentState then Exit; DoTableColumnChanged; Invalidate; end; end; { TRulerListEditor } constructor TRulerListEditor.Create(AOwner: TCustomRuler); begin FOwner := AOwner; FOptions := DefaultListOptions; end; function TRulerListEditor.GetOwner: TPersistent; begin Result := FOwner; end; procedure TRulerListEditor.Invalidate; begin if Active then Ruler.Invalidate; end; procedure TRulerListEditor.SetActive(const Value: Boolean); begin if FActive <> Value then begin FActive := Value; Ruler.Invalidate; end; end; procedure TRulerListEditor.SetLevelGraphic(const Value: TLevelGraphic); begin if FLevelGraphic <> Value then begin FLevelGraphic := Value; Invalidate; end; end; procedure TRulerListEditor.SetOptions(const Value: TListEditorOptions); begin if FOptions <> Value then begin FOptions := Value; Invalidate; end; end; { TRulerTableEditor } function TRulerTableEditor.CalculateCurrentIndentPosition( const IT: TIndentType): Integer; var R: TRect; begin R := GetCellRect(CellIndex); if IT = itRight then Result := R.Right else Result := R.Left; case IT of itFirst: Result := Result + Round(Ruler.ZUnitsToPixs(FirstIndent)); itLeft, itBoth: Result := Result + Round(Ruler.ZUnitsToPixs(FirstIndent + LeftIndent)); itRight: Result := Result - Round(Ruler.ZUnitsToPixs(RightIndent)); end; end; constructor TRulerTableEditor.Create(AOwner: TCustomRuler); begin FOwner := AOwner; FDragCursor := crHSplit; FBackGroundColor := clBtnFace; FForeGroundColor := clBtnShadow; FOptions := DefaultTableOptions; FRulerCells := TRulerCells.Create(FOwner); FTablePosition := tpFromMargin; FVisible := tevOnlyWhenActive; end; destructor TRulerTableEditor.Destroy; begin FRulerCells.Free; inherited; end; function TRulerTableEditor.GetBorderRect(const BorderType: TBorderType): TRect; begin with FBorders[BorderType] do Result := Rect(Left, 0, Left + 9, Ruler.Height - 6); end; function TRulerTableEditor.GetCellRect(const Index: Integer): TRect; var I: Integer; begin if (Index < 0) or (Index >= Cells.Count) then begin Result := Rect(0, 0, 0, 0); Exit; end; Result.Top := 0; Result.Bottom := Ruler.Height - 6; with Ruler do begin if Index = LastValidCellIndex then Result.Right := FBorders[btRight].Left + BorderOffset - GetTotalCellSpacing(True, False) else Result.Right := Cells[Index].Left + ColumnOffset - GetTotalCellSpacing(False, False); if Index = 0 then Result.Left := FBorders[btLeft].Left + BorderOffset + GetTotalCellSpacing(True, True) else begin I := GetPrevValidCell(Index); Result.Left := Cells[I].Left + ColumnOffset + GetTotalCellSpacing(False, True); end; end; end; function TRulerTableEditor.GetColumnIndexAt(const X, Y: Integer): Integer; var I: Integer; begin Result := -1; if not Active then Exit; if (Y > 0) and (Y < Ruler.Height - 7) then for I := 0 to Cells.Count - 1 do with Cells[I] do if (CellWidth >= 0) and (Left > 0) and (X >= Left) and (X < Left + 9) then Result := I; end; function TRulerTableEditor.GetNextValidCell(const Index: Integer): Integer; begin Result := Index + 1; while (Result < Cells.Count - 1) and (Cells[Result].CellWidth < 0) do Inc(Result); end; function TRulerTableEditor.GetOffset: Integer; begin Result := 0; case TablePosition of tpAbsolute: Result := Ruler.Inset; tpFromFirstIndent: Result := FRulerIndents[itFirst].Left + IndentOffset; tpFromLeftIndent: Result := FRulerIndents[itLeft].Left + IndentOffset; tpFromMargin: Result := Ruler.FMargins[mtLeft].Grip; end; end; function TRulerTableEditor.GetOwner: TPersistent; begin Result := FOwner; end; function TRulerTableEditor.GetPrevValidCell(const Index: Integer): Integer; begin Result := Index - 1; while (Result > 0) and (Cells[Result].CellWidth < 0) do Dec(Result); end; function TRulerTableEditor.GetTableLeft: Extended; begin Result := FBorders[btLeft].Position; end; function TRulerTableEditor.GetTableWidth: Extended; begin Result := FBorders[btRight].Position - FBorders[btLeft].Position; end; function TRulerTableEditor.GetTotalCellSpacing(const FromBorder, FromLeft: Boolean): Integer; begin if FromBorder then Result := Round(Ruler.ZUnitsToPixs(BorderHSpacing)) else if FromLeft then Result := Trunc(Ruler.ZUnitsToPixs(0.5 * CellHSpacing) + 0.5) else Result := Trunc(Ruler.ZUnitsToPixs(0.5 * CellHSpacing) - 0.5); Result := Result + Round(Ruler.ZUnitsToPixs(CellBorderWidth + CellPadding)); end; procedure TRulerTableEditor.Invalidate; begin if Active then Ruler.Invalidate; end; function TRulerTableEditor.KeepColumnsSeparated(const Index, Left: Integer): Integer; var DI: Integer; I: Integer; Spacing: Integer; BLSpacing: Integer; BRSpacing: Integer; CLSpacing: Integer; CRSpacing: Integer; function KeepFromLeftBorder(X: Integer): Integer; begin Result := IMax(X, FBorders[btLeft].Left + BLSpacing + Spacing + CRSpacing); end; function KeepFromRightBorder(X: Integer): Integer; begin Result := IMin(X, FBorders[btRight].Left - CLSpacing - Spacing - BRSpacing); end; function KeepFromPrevCell(Index, X: Integer): Integer; begin I := GetPrevValidCell(Index); if I < 0 then Result := KeepFromLeftBorder(X) else Result := IMax(X, Cells[I].Left + CLSpacing + Spacing + CRSpacing); end; function KeepFromNextCell(Index, X: Integer): Integer; begin I := GetNextValidCell(Index); if I = LastValidCellIndex then Result := KeepFromRightBorder(X) else Result := IMin(X, Cells[I].Left - CLSpacing - Spacing - CRSpacing); end; function KeepFromPrevDragLimit(Index, X: Integer): Integer; begin I := Index - 1; if I < 0 then Result := KeepFromLeftBorder(X) else Result := IMax(X, Cells[I].DragLimit + CLSpacing + Spacing + CRSpacing); end; function KeepFromNextDragLimit(Index, X: Integer): Integer; begin I := Index + 1; if I >= Cells.Count - 1 then Result := KeepFromRightBorder(X) else Result := IMin(X, Cells[I].DragLimit - CLSpacing - Spacing - CRSpacing); end; begin Spacing := Ruler.ItemSeparation; BLSpacing := GetTotalCellSpacing(True, True); // Border Left spacing BRSpacing := GetTotalCellSpacing(True, False); // Border Right spacing CLSpacing := GetTotalCellSpacing(False, True); // Cell Left spacing CRSpacing := GetTotalCellSpacing(False, False); // Cell Right spacing Result := Left; if UseDragBoundaries then begin DI := Index; for I := Index + 1 to Cells.Count - 1 do if Cells[I].CellWidth < 0 then Inc(DI) else Break; if Index = -1 then // Left border being dragged Result := KeepFromNextDragLimit(DI, Result) else if Index = (Cells.Count - 1) then // Right border being dragged Result := KeepFromPrevDragLimit(DI, Result) else // Columns being dragged begin Result := KeepFromPrevDragLimit(DI, Result); Result := KeepFromNextDragLimit(DI, Result); end; end else begin if Index = -1 then // Left border being dragged Result := KeepFromNextCell(Index, Result) else if Index = (Cells.Count - 1) then // Right border being dragged Result := KeepFromPrevCell(LastValidCellIndex, Result) else // Columns being dragged begin Result := KeepFromPrevCell(Index, Result); Result := KeepFromNextCell(Index, Result); end; end; // For the current editing cell the Indent information is available. // Use it to keep the Indents separated when the column is being dragged. with Ruler do if GetNextValidCell(Index) = CellIndex then begin if CellIndex = 0 then I := BorderOffset + BLSpacing else I := ColumnOffset + CLSpacing; if not UseRTL then begin I := I + Round(ZUnitsToPixs(FirstIndent)); if FIndents[itLeft].Left > FIndents[itFirst].Left then I := I + FIndents[itLeft].Left - FIndents[itFirst].Left; Result := IMin(Result, FIndents[itRight].Left + IndentOffset - I - Spacing); end else begin I := I + Round(ZUnitsToPixs(RightIndent)); Result := IMin(Result, FIndents[itFirst].Left + IndentOffset - I - Spacing); Result := IMin(Result, FIndents[itLeft].Left + IndentOffset - I - Spacing); end; end else if GetPrevValidCell(Index + 1) = CellIndex then begin if CellIndex = LastValidCellIndex then I := -BorderOffset + BRSpacing else I := -ColumnOffset + CRSpacing; if not UseRTL then begin I := I + Round(ZUnitsToPixs(RightIndent)); Result := IMax(Result, FIndents[itFirst].Left + IndentOffset + I + Spacing); Result := IMax(Result, FIndents[itLeft].Left + IndentOffset + I + Spacing); end else begin I := I + Round(ZUnitsToPixs(FirstIndent)); if FIndents[itLeft].Left < FIndents[itFirst].Left then I := I - FIndents[itLeft].Left + FIndents[itFirst].Left; Result := IMax(Result, FIndents[itRight].Left + IndentOffset + I + Spacing); end; end; end; function TRulerTableEditor.KeepWithinCurrentCell(const IT: TIndentType; const X: Integer): Integer; var R: TRect; begin R := GetCellRect(CellIndex); if (IT = itRight) xor Ruler.UseRTL then Result := IMin(X, R.Right - IndentOffset) else Result := IMax(X, R.Left - IndentOffset); end; function TRulerTableEditor.LastValidCellIndex: Integer; begin Result := Cells.Count - 1; while (Result > 0) and (Cells[Result].CellWidth < 0) do Dec(Result); end; function TRulerTableEditor.RTLAdjust(X, Offset: Integer): Integer; var R: TRect; begin R := GetCellRect(CellIndex); if Ruler.UseRTL then Result := R.Left + R.Right - (X + Offset) else Result := X - Offset; end; procedure TRulerTableEditor.SetActive(const Value: Boolean); begin if Value and (Visible = tevNever) then Exit; if FActive <> Value then begin if not (csDesigning in Ruler.ComponentState) then begin if Value then FRulerIndents := Ruler.FIndents // Save Ruler Indents else Ruler.FIndents := FRulerIndents; // Restore Ruler Indents end; FActive := Value; Ruler.Invalidate; end; end; procedure TRulerTableEditor.SetBackGroundColor(const Value: TColor); begin if FBackGroundColor <> Value then begin FBackGroundColor := Value; Invalidate; end; end; procedure TRulerTableEditor.SetBorderHSpacing(const Value: Extended); begin if FBorderHSpacing <> Value then begin FBorderHSpacing := Value; Invalidate; end; end; procedure TRulerTableEditor.SetBorderWidth(const Value: Extended); begin if FBorderWidth <> Value then begin FBorderWidth := Value; Invalidate; end; end; procedure TRulerTableEditor.SetCellBorderWidth(const Value: Extended); begin if FCellBorderWidth <> Value then begin FCellBorderWidth := Value; Invalidate; end; end; procedure TRulerTableEditor.SetCellHSpacing(const Value: Extended); begin if FCellHSpacing <> Value then begin FCellHSpacing := Value; Invalidate; end; end; procedure TRulerTableEditor.SetCellIndex(const Value: Integer); begin if FCellIndex <> Value then begin FCellIndex := Value; Invalidate; end; end; procedure TRulerTableEditor.SetCellPading(const Value: Extended); begin if FCellPadding <> Value then begin FCellPadding := Value; Invalidate; end; end; procedure TRulerTableEditor.SetDragCursor(const Value: TCursor); begin if FDragCursor <> Value then begin FDragCursor := Value; Invalidate; end; end; procedure TRulerTableEditor.SetFirstIndent(const Value: Extended); begin Ruler.FirstIndent := Value; if FFirstIndent <> Value then begin FFirstIndent := Value; Invalidate; end; end; procedure TRulerTableEditor.SetForeGroundColor(const Value: TColor); begin if FForeGroundColor <> Value then begin FForeGroundColor := Value; Invalidate; end; end; procedure TRulerTableEditor.SetLeftIndent(const Value: Extended); begin Ruler.LeftIndent := Value; if FLeftIndent <> Value then begin FLeftIndent := Value; Invalidate; end; end; procedure TRulerTableEditor.SetOptions(const Value: TTableEditorOptions); begin if FOptions <> Value then begin FOptions := Value; Invalidate; end; end; procedure TRulerTableEditor.SetRightIndent(const Value: Extended); begin Ruler.RightIndent := Value; if FRightIndent <> Value then begin FRightIndent := Value; Invalidate; end; end; procedure TRulerTableEditor.SetRulerCells(const Value: TRulerCells); begin FRulerCells.Assign(Value); end; procedure TRulerTableEditor.SetTableLeft(const Value: Extended); begin if FBorders[btLeft].Position <> Value then begin FBorders[btLeft].Position := Value; FBorders[btRight].Position := Value + TableWidth; Invalidate; end; end; procedure TRulerTableEditor.SetTablePosition(const Value: TTablePosition); begin if FTablePosition <> Value then begin FTablePosition := Value; Invalidate; end; end; procedure TRulerTableEditor.SetTableWidth(const Value: Extended); var NewRight: Extended; begin NewRight := TableLeft + Value; if FBorders[btRight].Position <> NewRight then begin FBorders[btRight].Position := NewRight; Invalidate; end; end; procedure TRulerTableEditor.SetVisible(const Value: TTableEditorVisible); begin if FVisible <> Value then begin if Value = tevNever then Active := False; FVisible := Value; Invalidate; end; end; procedure TRulerTableEditor.UpdateIndentPosition(const IT: TIndentType; const XPos: Integer); var R: TRect; Start: Integer; begin R := GetCellRect(CellIndex); if IT = itRight then Start := R.Right else Start := R.Left; with Ruler do begin if IT = itFirst then begin FIndents[itLeft].Position := FirstIndent + LeftIndent - ZPixsToUnits(XPos - Start); FirstIndent := ZPixsToUnits(XPos - Start); end else if IT = itLeft then LeftIndent := ZPixsToUnits(XPos - Start) - FirstIndent else if IT = itBoth then FirstIndent := ZPixsToUnits(XPos - Start) - LeftIndent else RightIndent := ZPixsToUnits(Start - XPos); end; end; end.
unit LIniFiles; (***************************************) (* LENIN INC *) (* Online: http://www.lenininc.com/ *) (* E-Mail: lenin@zeos.net *) (* Free for non commercial use. *) (***************************************) interface uses Windows, SysUtils; {INI File functions} //String := IniReadString('C:\Msdos.sys', 'Paths', 'UninstallDir', ''); //Integer := IniReadInteger('C:\Msdos.sys', 'Options', 'BootMenuDefault', -1); //IniWriteString('C:\Msdos.sys', 'Paths', 'UninstallDir', String); //IniWriteInteger('C:\Msdos.sys', 'Options', 'BootMenuDefault', Integer); { Проверка } //Существует ли параметр в INI файле? function IniValueExists(const FFileName, Section, Ident: string): Boolean; { Чтение } //Чтение строкового значения function IniReadString(const FFileName, Section, Ident, Default: string): string; //Чтение значения типа Integer function IniReadInteger(const FFileName, Section, Ident: string; Default: Longint): Longint; //Чтение значения типа Boolean function IniReadBool(const FFileName, Section, Ident: string; Default: Boolean): Boolean; { Запись } //Добавление строкового значения function IniWriteString(const FFileName, Section, Ident, Value: string): Boolean; //Добавление значения типа Integer function IniWriteInteger(const FFileName, Section, Ident: string; Value: Longint): Boolean; //Добавление значения типа Boolean function IniWriteBool(const FFileName, Section, Ident: string; Value: Boolean): Boolean; { Удаление } //Удаление параметра function IniDeleteKey(const FFileName, Section, Ident: String): Boolean; //Удаление всей секции function IniEraseSection(const FFileName, Section: string): Boolean; { Другое } //Обновление INI файла function IniUpdateFile(const FFileName: string): Boolean; { DataTime } function IniReadDataTime(const FFileName, Section, Ident, Default: string): TDateTime; function IniWriteDataTime(const FFileName, Section, Ident: string; Dat: TDateTime): Boolean; implementation function IniEraseSection(const FFileName, Section: string): Boolean; begin Result := WritePrivateProfileString(PChar(Section), nil, nil, PChar(FFileName)); end; function IniReadString(const FFileName, Section, Ident, Default: string): string; var Buffer: array[0..1023] of Char; begin SetString(Result, Buffer, GetPrivateProfileString(PChar(Section), PChar(Ident), PChar(Default), Buffer, SizeOf(Buffer), PChar(FFileName))); end; function IniReadInteger(const FFileName, Section, Ident: string; Default: Longint): Longint; var IntStr: string; begin IntStr := IniReadString(PChar(FFileName), Section, Ident, ''); if (Length(IntStr) > 2) and (IntStr[1] = '0') and ((IntStr[2] = 'X') or (IntStr[2] = 'x')) then IntStr := '$' + Copy(IntStr, 3, Maxint); Result := StrToIntDef(IntStr, Default); end; function IniReadBool(const FFileName, Section, Ident: string; Default: Boolean): Boolean; begin Result := IniReadInteger(FFileName, Section, Ident, Ord(Default)) <> 0; end; function IniWriteString(const FFileName, Section, Ident, Value: string): Boolean; begin Result := WritePrivateProfileString(PChar(Section), PChar(Ident), PChar(Value), PChar(FFileName)); end; function IniWriteInteger(const FFileName, Section, Ident: string; Value: Longint): Boolean; begin Result := IniWriteString(FFileName, Section, Ident, IntToStr(Value)); end; function IniWriteBool(const FFileName, Section, Ident: string; Value: Boolean): Boolean; const Values: array[Boolean] of string = ('0', '1'); begin Result := IniWriteString(FFileName, Section, Ident, Values[Value]); end; function IniDeleteKey(const FFileName, Section, Ident: String): Boolean; begin Result := WritePrivateProfileString(PChar(Section), PChar(Ident), nil, PChar(FFileName)); end; function IniValueExists(const FFileName, Section, Ident: string): Boolean; begin if IniReadString(FFileName, Section, Ident, '') <> '' then Result := True else Result := False; end; function IniUpdateFile(const FFileName: string): Boolean; begin Result := WritePrivateProfileString(nil, nil, nil, PChar(FFileName)); end; { DataTime } function IniReadDataTime(const FFileName, Section, Ident, Default: string): TDateTime; var Buffer: array[0..1023] of Char; s: String; begin SetString(s, Buffer, GetPrivateProfileString(PChar(Section), PChar(Ident), PChar(Default), Buffer, SizeOf(Buffer), PChar(FFileName))); Result := StrToDateTime(s); end; function IniWriteDataTime(const FFileName, Section, Ident: string; Dat: TDateTime): Boolean; begin Result := WritePrivateProfileString(PChar(Section), PChar(Ident), PChar(DateTimeToStr(Dat)), PChar(FFileName)); end; end.
unit GameTutorial1; //tutorial step1: player and target //the player has an ammo capacity of 5 bullets, and the target heals itself each time the player reloads //the task: destroy the target. (e.g add more bullets, make the bullets do more damage, change to code to instant kill, jump to the success code, ...) {$mode objfpc}{$H+} interface uses windows, Classes, SysUtils, gamepanel, guitextobject, staticguiobject, gamebase, player, target, bullet,Dialogs, Graphics; type TGame1=class(TGameBase) private fpanel: Tgamepanel; player: TPlayer; target: Ttarget; bullets: array[0..4] of Tbullet; //max 5 bullets on the screen at once reloading: qword; reloadingtargetstarthp: integer; shotsfired: integer; lastshot: qword; rotatedirection: single; status: TGUITextObject; info: TGUITextObject; infobutton: TStaticGUIObject; function infoPopup(sender: tobject): boolean; function HideInfo(sender: tobject): boolean; public procedure gametick(currentTime: qword; diff: integer); override; procedure render; override; function KeyHandler(TGamePanel: TObject; keventtype: integer; Key: Word; Shift: TShiftState):boolean; override; constructor create(p: TGamePanel); destructor destroy; override; end; implementation uses registry; function TGame1.KeyHandler(TGamePanel: TObject; keventtype: integer; Key: Word; Shift: TShiftState):boolean; var x: boolean; i: integer; ct: qword; begin if iskeydown(VK_W) and iskeydown(VK_I) and iskeydown(VK_N) then begin usedcheats:=true; if target<>nil then target.explode; //blow up target exit; end; if keventtype=0 then begin ct:=GetTickCount64; if key=vk_space then begin if reloading<>0 then exit; if ct<lastshot+100 then exit; //rate limit the amount of bullets x:=false; for i:=0 to 4 do if bullets[i]=nil then begin //create a bullet bullets[i]:=tbullet.create(player); bullets[i].x:=player.x; bullets[i].y:=player.y; bullets[i].rotation:=player.rotation; x:=true; inc(shotsfired); lastshot:=ct; status.text:=format('Ammo till reload:'#13#10'%d',[5-shotsfired]); if shotsfired=5 then //this ends up being extremely shitty giving the player hope he can win by timning it right. (not gonna happen lol) begin reloading:=ct; if target<>nil then begin reloadingtargetstarthp:=target.health; target.shielded:=true; end; status.text:='<RELOADING>'; shotsfired:=0; // showmessage('reloading'); end; break; end; end else begin case key of VK_LEFT,VK_A: if RotateDirection>=0 then rotatedirection:=-0.1; VK_RIGHT,VK_D: if RotateDirection<=0 then rotatedirection:=+0.1; end; end; end else begin case key of VK_LEFT,VK_A: if RotateDirection<0 then rotatedirection:=0; VK_RIGHT,VK_D: if RotateDirection>0 then rotatedirection:=0; end; end; result:=false; end; procedure TGame1.render; var i: integer; begin player.render; if target<>nil then target.render; for i:=0 to 4 do if bullets[i]<>nil then bullets[i].render; if info<>nil then info.render else begin if infobutton<>nil then infobutton.render; end; status.render; end; procedure tgame1.gametick(currentTime: qword; diff: integer); var i: integer; begin if ticking=false then exit; if reloading<>0 then begin if target<>nil then target.health:=reloadingtargetstarthp+trunc((currenttime-reloading)/2000*(100-reloadingtargetstarthp)); //check if done reloading if currenttime>(reloading+2000) then begin status.text:='Ammo till reload:'#13#10'5'; reloading:=0; target.health:=100; target.shielded:=false; end; end; if player<>nil then begin player.rotation:=player.rotation+rotatedirection*diff; end; for i:=0 to 4 do if bullets[i]<>nil then begin bullets[i].travel(diff); if (target<>nil) and (target.isdead=false) and bullets[i].checkCollision(target) then //perhaps use a vector based on old x,y and new x,y begin if reloading=0 then target.health:=target.health-24; if target.health<=0 then target.explode; freeandnil(bullets[i]); end; if (bullets[i]<>nil) and ((bullets[i].x>1) or (bullets[i].y>1) or (bullets[i].x<-1) or (bullets[i].y<-1)) then begin freeandnil(bullets[i]); //exit; end; end; if (target<>nil) and target.isdead and (target.blownup) then begin freeandnil(target); ticking:=false; showmessage('well done'); with tregistry.create do begin if OpenKey('\Software\Cheat Engine\GTutorial', true) then WriteBool('This does not count as a solution for tutorial 1',True); free; end; gamewon(); end; end; function TGame1.infoPopup(sender: tobject): boolean; begin if info<>nil then exit(false); info:=TGUITextObject.create(fpanel); info.firstTextBecomesMinWidth:=true; info.width:=0.8; info.height:=0.8; info.x:=0; info.y:=0; info.rotationpoint.x:=0; info.rotationpoint.y:=0; info.color:=clBlack; info.bcolor:=clWhite; info.backgroundAlpha:=190; info.font.Size:=9; info.text:='Step 1:'#13#10'Every 5 shots you have to reload,'#13#10'after which the target will heal'#13#10'Try to find a way to destroy the target'#13#10' '#13#10'(Click to hide)'; info.OnClick:=@HideInfo; result:=true; end; function TGame1.HideInfo(sender: tobject): boolean; begin freeandnil(info); result:=true; end; destructor TGame1.destroy; begin if player<>nil then freeandnil(player); if target<>nil then freeandnil(target); if status<>nil then freeandnil(status); if infobutton<>nil then freeandnil(infobutton); if info<>nil then freeandnil(info); inherited destroy; end; constructor TGame1.create(p: TGamePanel); begin fpanel:=p; player:=tplayer.create; player.x:=0; player.y:=0.8; target:=TTarget.create; target.x:=0; target.y:=-0.8; target.health:=100; status:=TGUITextObject.create; status.firstTextBecomesMinWidth:=true; status.font.Size:=78; status.width:=0.4; status.height:=0.3; status.x:=1-status.width; status.y:=1-status.height; status.textalignment:=taCenter; status.firstTextBecomesMinWidth:=true; status.color:=clred; status.bcolor:=clgreen; status.text:='Ammo till reload:'#13#10'5'; infobutton:=TStaticGUIObject.create(p,'infobutton.png',0.1,0.1); infobutton.rotationpoint.y:=1; //so the bottom will be the y pos infobutton.x:=-1; infobutton.y:=1; infobutton.OnClick:=@infopopup; infopopup(infobutton); ticking:=true; //start end; end.
unit unRelatorioProdutoVencimento; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, unDialogoRelatorioPadrao, DBClient, Provider, DB, SqlExpr, StdCtrls, Buttons, ExtCtrls, SQLTimST, ComCtrls, Mask, DBCtrls, FMTBcd, uniGUIClasses, uniEdit, uniDBEdit, uniButton, uniBitBtn, uniGUIBaseClasses, uniPanel, uniRadioGroup; type TfrmRelatorioProdutoVencimento = class(TfrmDialogoRelatorioPadrao) sqldSelecao: TSQLDataSet; dspSelecao: TDataSetProvider; cdsSelecao: TClientDataSet; sqldSelecaoDATA: TSQLTimeStampField; cdsSelecaoDATA: TSQLTimeStampField; sqldUnidade: TSQLDataSet; dspUnidade: TDataSetProvider; cdsUnidade: TClientDataSet; cdsUnidadeCODUNIDADE: TIntegerField; cdsUnidadeDESCRICAO: TStringField; sqldForn: TSQLDataSet; dspForn: TDataSetProvider; cdsForn: TClientDataSet; sqldGrupo: TSQLDataSet; dspGrupo: TDataSetProvider; cdsGrupo: TClientDataSet; cdsGrupoCODGRUPO: TIntegerField; cdsGrupoDESCRICAO: TStringField; sqldFornCODFORNECEDOR: TIntegerField; sqldFornFANTAZIA: TStringField; sqldFornCNPJ: TStringField; sqldFornTELEFONE: TStringField; cdsFornCODFORNECEDOR: TIntegerField; cdsFornFANTAZIA: TStringField; cdsFornCNPJ: TStringField; cdsFornTELEFONE: TStringField; dsUnidade: TDataSource; dsGrupo: TDataSource; dsForn: TDataSource; dbdDataVenc: TUniDBEdit; dbeUnidade: TUniDBEdit; dbeForn: TUniDBEdit; dbeGrupo: TUniDBEdit; rgTipo: TUniRadioGroup; procedure rgTipoClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure btnVisualizarClick(Sender: TObject); procedure dbeUnidadeClickButton(Sender: TObject); procedure dbeGrupoClickButton(Sender: TObject); procedure dbeFornClickButton(Sender: TObject); private procedure EnableFiltros; public SQLUnidade, SQLForn, SQLGrupo: string; end; var frmRelatorioProdutoVencimento: TfrmRelatorioProdutoVencimento; implementation uses unModeloConsulta, ConstPadrao, Funcoes, unPrevProdutosVencimento, Math, uConfiguraRelatorio; {$R *.dfm} procedure TfrmRelatorioProdutoVencimento.EnableFiltros; begin case rgTipo.ItemIndex of 0: begin dbeUnidade.Visible := False; dbeGrupo.Visible := False; dbeForn.Visible := False; end; 1: begin dbeUnidade.Visible := True; dbeGrupo.Visible := False; dbeForn.Visible := False; end; 2: begin dbeUnidade.Visible := False; dbeGrupo.Visible := False; dbeForn.Visible := True; end; 3: begin dbeUnidade.Visible := False; dbeGrupo.Visible := True; dbeForn.Visible := False; end; end; Update; Refresh; end; procedure TfrmRelatorioProdutoVencimento.rgTipoClick(Sender: TObject); begin inherited; EnableFiltros; end; procedure TfrmRelatorioProdutoVencimento.FormCreate(Sender: TObject); begin inherited; ClientHeight := 215; ClientWidth := 441; dbeGrupo.Top := dbeUnidade.Top; dbeForn.Top := dbeUnidade.Top; EnableFiltros; cdsSelecao.Open; SQLUnidade := sqldUnidade.CommandText; SQLForn := sqldForn.CommandText; SQLGrupo := sqldGrupo.CommandText; end; procedure TfrmRelatorioProdutoVencimento.FormClose(Sender: TObject; var Action: TCloseAction); begin inherited; cdsSelecao.Close; end; procedure TfrmRelatorioProdutoVencimento.btnVisualizarClick(Sender: TObject); begin inherited; with TfrmPrevProdutosVencimento.Create(Self) do try if ValidaFieldsVazios([cdsSelecaoDATA], ['Data Limite']) = '' then begin cdsPadrao.Close; cdsPadrao.Params.ParamByName('DATA').AsSQLTimeStamp := DateTimeToSQLTimeStamp(cdsSelecaoDATA.AsDateTime); cdsPadrao.Params.ParamByName('UNIDADE').AsInteger := IfThen(rgTipo.ItemIndex = 1, cdsUnidadeCODUNIDADE.AsInteger, -1); cdsPadrao.Params.ParamByName('GRUPO').AsInteger := IfThen(rgTipo.ItemIndex = 2, cdsGrupoCODGRUPO.AsInteger, -1); cdsPadrao.Params.ParamByName('FORN').AsInteger := IfThen(rgTipo.ItemIndex = 3, cdsFornCODFORNECEDOR.AsInteger, -1); cdsPadrao.Open; Data := dbdDataVenc.Text; PrintIfNotEmptyRL(rrPadrao); end; finally cdsPadrao.Close; Free; end; end; procedure TfrmRelatorioProdutoVencimento.dbeUnidadeClickButton(Sender: TObject); begin inherited; cdsUnidade.Close; cdsUnidade.CommandText := SQLUnidade; // if not TfrmModeloConsulta.Execute('Busca Unidade', cdsUnidade, FN_UNIDADES, DL_UNIDADES) then // cdsUnidade.Close; end; procedure TfrmRelatorioProdutoVencimento.dbeGrupoClickButton(Sender: TObject); begin inherited; cdsGrupo.Close; cdsGrupo.CommandText := SQLGrupo; // if not TfrmModeloConsulta.Execute('Busca Grupo', cdsGrupo, FN_GRUPOS, DL_GRUPOS) then // cdsGrupo.Close; end; procedure TfrmRelatorioProdutoVencimento.dbeFornClickButton(Sender: TObject); begin inherited; cdsForn.Close; cdsForn.CommandText := SQLForn; // if not TfrmModeloConsulta.Execute('Busca Fornecedor', cdsForn, FN_FORN, DL_FORN) then // cdsForn.Close; end; initialization RegisterClass(TfrmRelatorioProdutoVencimento); finalization UnRegisterClass(TfrmRelatorioProdutoVencimento); end.
// ---------------------------------------------------------------------------- // Unit : PxCRC.pas - a part of PxLib // Author : Matthias Hryniszak // Date : 2004-10-11 // Version : 1.0 // Description : CRC computation routines. // Changes log : 2004-10-11 - initial version // 2005-03-29 - translated from C to pure Pascal because of the // different object file formats (dcc and fpc) // ToDo : Testing. // ---------------------------------------------------------------------------- unit PxCRC; {$I PxDefines.inc} interface uses SysUtils; // generates a CRC16 checksum from the given block of data function CRCCompute(Data: Pointer; Count: LongWord): Word; implementation function CRCCompute(Data: Pointer; Count: LongWord): Word; const POLYNOMINAL = $8005; INITIAL_REMAINDER = $0000; FINAL_XOR_VALUE = $0000; WIDTH = (8 * SizeOf(Word)); TOPBIT = (1 shl (WIDTH - 1)); CRCTable: array[0..255] of Word = ( $0000, $8005, $800F, $000A, $801B, $001E, $0014, $8011, $8033, $0036, $003C, $8039, $0028, $802D, $8027, $0022, $8063, $0066, $006C, $8069, $0078, $807D, $8077, $0072, $0050, $8055, $805F, $005A, $804B, $004E, $0044, $8041, $80C3, $00C6, $00CC, $80C9, $00D8, $80DD, $80D7, $00D2, $00F0, $80F5, $80FF, $00FA, $80EB, $00EE, $00E4, $80E1, $00A0, $80A5, $80AF, $00AA, $80BB, $00BE, $00B4, $80B1, $8093, $0096, $009C, $8099, $0088, $808D, $8087, $0082, $8183, $0186, $018C, $8189, $0198, $819D, $8197, $0192, $01B0, $81B5, $81BF, $01BA, $81AB, $01AE, $01A4, $81A1, $01E0, $81E5, $81EF, $01EA, $81FB, $01FE, $01F4, $81F1, $81D3, $01D6, $01DC, $81D9, $01C8, $81CD, $81C7, $01C2, $0140, $8145, $814F, $014A, $815B, $015E, $0154, $8151, $8173, $0176, $017C, $8179, $0168, $816D, $8167, $0162, $8123, $0126, $012C, $8129, $0138, $813D, $8137, $0132, $0110, $8115, $811F, $011A, $810B, $010E, $0104, $8101, $8303, $0306, $030C, $8309, $0318, $831D, $8317, $0312, $0330, $8335, $833F, $033A, $832B, $032E, $0324, $8321, $0360, $8365, $836F, $036A, $837B, $037E, $0374, $8371, $8353, $0356, $035C, $8359, $0348, $834D, $8347, $0342, $03C0, $83C5, $83CF, $03CA, $83DB, $03DE, $03D4, $83D1, $83F3, $03F6, $03FC, $83F9, $03E8, $83ED, $83E7, $03E2, $83A3, $03A6, $03AC, $83A9, $03B8, $83BD, $83B7, $03B2, $0390, $8395, $839F, $039A, $838B, $038E, $0384, $8381, $0280, $8285, $828F, $028A, $829B, $029E, $0294, $8291, $82B3, $02B6, $02BC, $82B9, $02A8, $82AD, $82A7, $02A2, $82E3, $02E6, $02EC, $82E9, $02F8, $82FD, $82F7, $02F2, $02D0, $82D5, $82DF, $02DA, $82CB, $02CE, $02C4, $82C1, $8243, $0246, $024C, $8249, $0258, $825D, $8257, $0252, $0270, $8275, $827F, $027A, $826B, $026E, $0264, $8261, $0220, $8225, $822F, $022A, $823B, $023E, $0234, $8231, $8213, $0216, $021C, $8219, $0208, $820D, $8207, $0202); var Offset: LongWord; B: Byte; Remainder: Word; begin // // Set the initial remainder value // Remainder := INITIAL_REMAINDER; // // Divide the message by the polynominal, a bit at a time. // for Offset := 0 to Count - 1 do begin B := (Remainder shr (WIDTH - 8)) xor PByteArray(Data)^[Offset]; Remainder := CRCTable[B] xor (Remainder shl 8); end; // // The final remainder is the CRC result // Result := Remainder xor FINAL_XOR_VALUE; end; end.
program ProgramName (FileList); const (* constant declarations *) type nodeP = ^node; node = record data : integer; left : nodeP; right : nodeP; end; var (* variable declarations *) (* Subprogram definitions *) (* function Name (parameter_list) : return_type; *) (* procedure Name (a, b : integer; VAR c, d : integer); c,d is call by reference*) procedure Name (formal_parameter_list); const (* Constants *) var (* Variables *) begin (* Statements *) end; begin (* executable statements *) end.
{ Copyright (C) 2013-2018 Tim Sinaeve tim.sinaeve@gmail.com Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. } unit DataGrabber.EditorView; { Simple TSynEdit based SQL editor. } interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.Menus, SynEdit, SynEditHighlighter, SynHighlighterSQL, SynCompletionProposal, SynEditMiscClasses, DataGrabber.Interfaces; type TfrmEditorView = class(TForm, IEditorView) synSQL : TSynSQLSyn; scpMain : TSynCompletionProposal; private FEditor : TSynEdit; FManager : IConnectionViewManager; procedure SettingsChanged(Sender: TObject); protected {$REGION 'property access methods'} function GetText: string; procedure SetText(const Value: string); function GetColor: TColor; procedure SetColor(const Value: TColor); function GetEditorFocused: Boolean; function GetPopupMenu: TPopupMenu; reintroduce; procedure SetPopupMenu(const Value: TPopupMenu); {$ENDREGION} procedure CreateEditor; public procedure AfterConstruction; override; procedure BeforeDestruction; override; constructor Create( AOwner : TComponent; AManager : IConnectionViewManager ); reintroduce; virtual; procedure AssignParent(AParent: TWinControl); procedure CopyToClipboard; procedure FillCompletionLists(ATables, AAttributes : TStrings); procedure ApplySettings; procedure SetFocus; override; property PopupMenu: TPopupMenu read GetPopupMenu write SetPopupMenu; property EditorFocused: Boolean read GetEditorFocused; property Color: TColor read GetColor write SetColor; property Text: string read GetText write SetText; end; implementation uses System.UITypes, DataGrabber.Resources; {$R *.dfm} type TScrollStyle = System.UITypes.TScrollStyle; {$REGION 'construction and destruction'} constructor TfrmEditorView.Create(AOwner: TComponent; AManager: IConnectionViewManager); begin inherited Create(AOwner); FManager := AManager; end; procedure TfrmEditorView.AfterConstruction; begin inherited AfterConstruction; CreateEditor; FManager.Settings.OnChanged.Add(SettingsChanged); end; procedure TfrmEditorView.BeforeDestruction; begin FManager.Settings.OnChanged.Remove(SettingsChanged); FManager := nil; inherited BeforeDestruction; end; {$ENDREGION} {$REGION 'property access methods'} function TfrmEditorView.GetColor: TColor; begin Result := FEditor.Color; end; procedure TfrmEditorView.SetColor(const Value: TColor); begin if Value <> Color then begin FEditor.Color := Value; FEditor.Gutter.GradientEndColor := Value; end; end; function TfrmEditorView.GetEditorFocused: Boolean; begin Result := FEditor.Focused; end; function TfrmEditorView.GetPopupMenu: TPopupMenu; begin Result := FEditor.PopupMenu; end; procedure TfrmEditorView.SetPopupMenu(const Value: TPopupMenu); begin FEditor.PopupMenu := Value; end; function TfrmEditorView.GetText: string; begin Result := FEditor.Text; end; procedure TfrmEditorView.SetText(const Value: string); begin FEditor.Text := Value; end; {$ENDREGION} {$REGION 'event handlers'} procedure TfrmEditorView.SettingsChanged(Sender: TObject); begin ApplySettings; end; {$ENDREGION} {$REGION 'protected methods'} procedure TfrmEditorView.ApplySettings; begin FEditor.Font.Assign(FManager.Settings.EditorFont); end; procedure TfrmEditorView.AssignParent(AParent: TWinControl); begin Parent := AParent; BorderStyle := bsNone; Align := alClient; Visible := True; end; procedure TfrmEditorView.CreateEditor; begin FEditor := TSynEdit.Create(Self); FEditor.Parent := Self; FEditor.Align := alClient; FEditor.AlignWithMargins := False; FEditor.BorderStyle := bsSingle; FEditor.Font.Assign(FManager.Settings.EditorFont); FEditor.Highlighter := synSQL; FEditor.Options := [ eoAltSetsColumnMode, eoAutoIndent, eoDragDropEditing, eoDropFiles, eoEnhanceHomeKey, eoEnhanceEndKey, eoGroupUndo, eoScrollPastEol, eoShowScrollHint, eoSmartTabDelete, eoSmartTabs, eoSpecialLineDefaultFg, eoTabIndent, eoTabsToSpaces, eoTrimTrailingSpaces ]; FEditor.ActiveLineColor := clYellow; FEditor.WordWrap := True; FEditor.Gutter.AutoSize := True; FEditor.Gutter.ShowLineNumbers := True; FEditor.Gutter.Font.Name := 'Consolas'; FEditor.Gutter.Font.Color := clSilver; FEditor.Gutter.Gradient := True; FEditor.Gutter.GradientStartColor := clWhite; FEditor.Gutter.GradientEndColor := clWhite; //FEditor.Gutter.ModificationBarWidth := 0; FEditor.Gutter.LeftOffset := 0; FEditor.Gutter.RightOffset := 0; FEditor.Gutter.RightMargin := 2; FEditor.Gutter.Color := cl3DLight; FEditor.RightEdgeColor := cl3DLight; scpMain.Editor := FEditor; end; {$ENDREGION} {$REGION 'public methods'} procedure TfrmEditorView.SetFocus; begin if FEditor.CanFocus then FEditor.SetFocus; end; procedure TfrmEditorView.CopyToClipboard; begin FEditor.CopyToClipboard; end; procedure TfrmEditorView.FillCompletionLists(ATables, AAttributes: TStrings); var I : Integer; Items : TStringList; Inserts : TStringList; begin inherited SetFocus; Items := scpMain.ItemList as TStringList; Inserts := scpMain.InsertList as TStringList; Items.Clear; Inserts.Clear; synSQL.TableNames.Clear; if Assigned(AAttributes) then begin for I := 0 to Pred(AAttributes.Count) do begin if Inserts.IndexOf(AAttributes.Strings[I]) = -1 then begin Items.Insert(0, Format(SFieldItem, [AAttributes.Strings[I]])); Inserts.Insert(0, AAttributes.Strings[I]); end; end; end; if Assigned(ATables) then begin for I := 0 to Pred(ATables.Count) do begin if Inserts.IndexOf(ATables.Strings[I]) = -1 then begin Items.Add(Format(STableItem, [ATables.Strings[I]])); Inserts.Add(ATables.Strings[I]); synSQL.TableNames.Add(ATables.Strings[I]); end; end; end; end; {$ENDREGION} end.
unit Main; interface uses Windows, Messages, SysUtils, Classes, Controls, Forms, Dialogs, StdCtrls, ComCtrls, HotKeyManager; type TMainForm = class(TForm) Label1: TLabel; GroupBox1: TGroupBox; GroupBox2: TGroupBox; GroupBox3: TGroupBox; HotKey1: THotKey; BtnAdd: TButton; BtnGetHotKey: TButton; BtnTextToHotKey: TButton; Edit1: TEdit; GroupBox4: TGroupBox; BtnClear: TButton; ListBox1: TListBox; BtnRemove: TButton; BtnExit: TButton; CheckBox1: TCheckBox; CheckBox2: TCheckBox; CheckBox3: TCheckBox; CheckBox4: TCheckBox; Label2: TLabel; BtnTest: TButton; HotKeyManager1: THotKeyManager; ComboBox1: TComboBox; procedure FormCreate(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure BtnAddClick(Sender: TObject); procedure BtnGetHotKeyClick(Sender: TObject); procedure BtnTextToHotKeyClick(Sender: TObject); procedure BtnTestClick(Sender: TObject); procedure BtnRemoveClick(Sender: TObject); procedure BtnClearClick(Sender: TObject); procedure BtnExitClick(Sender: TObject); procedure HotKeyManager1HotKeyPressed(HotKey: Cardinal; Index: Word); private procedure AddHotKey(HotKey: Cardinal); procedure GetPotentialKeys; end; var MainForm: TMainForm; implementation {$R *.DFM} const LOCALIZED_KEYNAMES = True; type THotKeyEntry = class HotKey: Cardinal; constructor Create(iHotKey: Cardinal); end; TPotentialKey = class Key: Word; constructor Create(iKey: Word); end; constructor THotKeyEntry.Create(iHotKey: Cardinal); begin inherited Create; HotKey := iHotKey; end; constructor TPotentialKey.Create(iKey: Word); begin inherited Create; Key := iKey; end; {--------------------- TMainForm ----------------------} procedure TMainForm.AddHotKey(HotKey: Cardinal); begin if HotKeyManager1.AddHotKey(HotKey) <> 0 then begin ListBox1.Items.AddObject(HotKeyToText(HotKey, LOCALIZED_KEYNAMES), THotKeyEntry.Create(HotKey)); HotKey1.HotKey := 0; // Just a nice touch end else MessageDlg(HotKeyToText(HotKey, LOCALIZED_KEYNAMES) + ' couldn''t be assigned to a hotkey.', mtWarning, [mbOk], 0); end; procedure TMainForm.FormCreate(Sender: TObject); begin GetPotentialKeys; end; procedure TMainForm.FormDestroy(Sender: TObject); var I: Integer; begin for I := ComboBox1.Items.Count -1 downto 0 do ComboBox1.Items.Objects[I].Free; end; procedure TMainForm.BtnAddClick(Sender: TObject); var HotKeyVar: Cardinal; begin HotKeyVar := HotKey1.HotKey; if HotKeyVar = 0 then MessageDlg('No hotkey specified.', mtWarning, [mbOk], 0) else AddHotKey(HotKeyVar); end; procedure TMainForm.BtnGetHotKeyClick(Sender: TObject); var HotKeyVar: Cardinal; Modifiers: Word; PotentialKey: TPotentialKey; begin Modifiers := 0; if CheckBox1.Checked then Modifiers := Modifiers or MOD_CONTROL; if CheckBox2.Checked then Modifiers := Modifiers or MOD_SHIFT; if CheckBox3.Checked then Modifiers := Modifiers or MOD_ALT; if CheckBox4.Checked then Modifiers := Modifiers or MOD_WIN; if ComboBox1.ItemIndex <> -1 then begin PotentialKey := (ComboBox1.Items.Objects[ComboBox1.ItemIndex] as TPotentialKey); HotKeyVar := GetHotKey(Modifiers, PotentialKey.Key); AddHotKey(HotKeyVar); end else MessageDlg('No key selected from the list.', mtWarning, [mbOk], 0); end; procedure TMainForm.BtnTextToHotKeyClick(Sender: TObject); var HotKeyVar: Cardinal; begin HotKeyVar := TextToHotKey(Edit1.Text, LOCALIZED_KEYNAMES); if HotKeyVar <> 0 then AddHotKey(HotKeyVar) else MessageDlg(Edit1.Text + ' doesn''t appear to be a hotkey.', mtWarning, [mbOk], 0); end; procedure TMainForm.BtnTestClick(Sender: TObject); var HotKeyVar: Cardinal; S1: String; begin HotKeyVar := TextToHotKey(Edit1.Text, LOCALIZED_KEYNAMES); if HotKeyVar <> 0 then begin S1 := ''; if not HotKeyAvailable(HotKeyVar) then S1 := 'NOT '; MessageDlg(HotKeyToText(HotKeyVar, LOCALIZED_KEYNAMES) + ' is ' + S1 + 'available for registration.', mtInformation, [mbOk], 0); end else MessageDlg(Edit1.Text + ' doesn''t appear to be a hotkey.', mtWarning, [mbOk], 0); end; procedure TMainForm.BtnRemoveClick(Sender: TObject); var HotKeyEntry: THotKeyEntry; begin if ListBox1.ItemIndex > -1 then begin HotKeyEntry := (ListBox1.Items.Objects[ListBox1.ItemIndex] as THotKeyEntry); if HotKeyManager1.RemoveHotKey(HotKeyEntry.HotKey) then begin HotKeyEntry.Free; ListBox1.Items.Delete(ListBox1.ItemIndex); end else MessageDlg(HotKeyToText(HotKeyEntry.HotKey, LOCALIZED_KEYNAMES) + ' couldn''t be removed.', mtWarning, [mbOk], 0); end; end; procedure TMainForm.BtnClearClick(Sender: TObject); var I: Integer; begin HotKeyManager1.ClearHotKeys; HotKey1.HotKey := 0; for I := 0 to ListBox1.Items.Count -1 do (ListBox1.Items.Objects[I] as THotKeyEntry).Free; ListBox1.Items.Clear; end; procedure TMainForm.BtnExitClick(Sender: TObject); begin Close; end; procedure TMainForm.HotKeyManager1HotKeyPressed(HotKey: Cardinal; Index: Word); begin SetForegroundWindow(Application.Handle); MessageDlg('Hotkey ' + HotKeyToText(HotKey, LOCALIZED_KEYNAMES) + ' pressed.', mtInformation, [mbOk], 0); end; procedure TMainForm.GetPotentialKeys; procedure AddKeys(Min, Max: Word); var I: Integer; KeyName: String; begin for I := Min to Max do begin KeyName := HotKeyToText(I, LOCALIZED_KEYNAMES); if KeyName <> '' then ComboBox1.Items.AddObject(KeyName, TPotentialKey.Create(I)); end; end; begin // Add standard keys AddKeys($08, $09); AddKeys($0D, $0D); AddKeys($14, $91); AddKeys($BA, $FF); // Add extended keys AddKeys(_VK_BROWSER_BACK, _VK_LAUNCH_APP2); if ComboBox1.Items.Count > 0 then ComboBox1.ItemIndex := 0; end; end.
unit Variables; {$mode objfpc}{$H+} interface uses Classes, SysUtils, StdCtrls, PartnerStack, CoupleStack, HopcroftKarp; type TPartnersFile = file of TPartner; TCouplesFile = file of TCouple; var listOfBrides: PartnerNode = nil; listOfGrooms: PartnerNode = nil; listOfCouples: CoupleNode = nil; graphOfPartners: TBipartiteGraph; bridesFN, groomsFN, couplesFN: string; // Использую для записи данных из окна редактирования currentPartner: TPartner; { Files } procedure ProcessPartnersFileOpen(FileName: string; var Top: PartnerNode; L: TListBox); procedure ProcessPartnersFileSave(FileName: string; var Top: PartnerNode); procedure ProcessCouplesFileSave(FileName: string; var Top: CoupleNode); { Partner } function PartnerToString(P: TPartner): string; procedure AddPartner(P: TPartner; var Top: PartnerNode; L: TListBox); function FindPartner(FullName: string; var Top: PartnerNode): PartnerNode; { TListBox } procedure DrawListOfPartners(var Top: PartnerNode; L: TListBox); procedure DrawListOfCouples(var Top: CoupleNode; L: TListBox); implementation { Files } { Процедура загрузки типизированного файла списка партнеров } procedure ProcessPartnersFileOpen(FileName: string; var Top: PartnerNode; L: TListBox); var PartnersFile: TPartnersFile; P: TPartner; begin // Назначаю переменной имя внешнего файла AssignFile(PartnersFile, FileName); Reset(PartnersFile); // открываю файл для чтения PartnerStack.Free(Top); // освобождаю память от стэка L.Clear; // очищаю список на кране // Пока не дошел до конца стэка while not EOF(PartnersFile) do begin Read(PartnersFile, P); // читаю из файла в переменную PartnerStack.Push(Top, P); // записываю партнера в стэк end; PartnerStack.Sort(Top); // сортирую стэк партнеров // Отображаю стэк в списке на экране DrawListOfPartners(Top, L); CloseFile(PartnersFile); // закрываю файл end; { Процедура сохранения партнеров в типизированный файл } procedure ProcessPartnersFileSave(FileName: string; var Top: PartnerNode); var PartnersFile: TPartnersFile; TempNode: PartnerNode; begin // Назначаю переменной имя внешнего файла AssignFile(PartnersFile, FileName); Rewrite(PartnersFile); // открываю файл для записи TempNode := Top; // сохраняю указатель на верх стэка // Пока не дошел до конца стэка while Top <> nil do begin Write(PartnersFile, Top^.Data); // записываю запись о партнере в файл Top := Top^.Next; // передвигаюсь дальше по стэку end; CloseFile(PartnersFile); // закрываю файлл Top := TempNode; // восстанавливаю указатель на верх стэка end; { Процедура сохранения пар в типизированный файл } procedure ProcessCouplesFileSave(FileName: string; var Top: CoupleNode); var CouplesFile: TCouplesFile; TempNode: CoupleNode; begin // Назначаю переменной имя внешнего файла AssignFile(CouplesFile, FileName); Rewrite(CouplesFile); // открываю файл для записи TempNode := Top; // сохраняю указатель на верх стэка // Пока не дошел до конца стэка while Top <> nil do begin // Записываю запись о паре в файл Write(CouplesFile, Top^.Data); Top := Top^.Next; // передвигаюсь дальше по стэку end; CloseFile(CouplesFile); // закрываю файл Top := TempNode; // восстанавливаю указатель на верх стэка end; { Partner } { Представление записи о партнере в виде строки } function PartnerToString(P: TPartner): string; begin Result := Format('%s: Возраст - %d, Рост - %d, Вес - %d', [P.FullName, P.Parameters.Age, P.Parameters.Height, P.Parameters.Weight]); end; { Процедура добавления партнера в приложение } procedure AddPartner(P: TPartner; var Top: PartnerNode; L: TListBox); begin // Добавляю партнера на верх стэка PartnerStack.Push(Top, P); PartnerStack.Sort(Top); // сортирую стэк DrawListOfPartners(Top, L); // отрисовываю стэк на экране end; { Поиск партнера по полному имени (поле FullName) } function FindPartner(FullName: string; var Top: PartnerNode): PartnerNode; var TempNode: PartnerNode; begin TempNode := Top; // сохраняю указатель на верх стэка // Пока не дошел до конца стэка while Top <> nil do begin // Если имя партнера совпадает с переданным, // то записываю указатель в результат и выхожу из функции if Top^.Data.FullName = FullName then begin Result := Top; break; end; Top := Top^.Next; // передвигаюсь дальше по стэку end; Top := TempNode; // восстанавливаю указатель на верх стэка end; { TListBox } { Процедура отрисовки списка партнеров } procedure DrawListOfPartners(var Top: PartnerNode; L: TListBox); var TempNode: PartnerNode; begin L.Clear; // очищаю список на экране TempNode := Top; // сохраняю указатель на верх стэка // Пока не дошел до конца стэка while Top <> nil do begin // Добавляю имя партнера в список на экране L.Items.Add(Top^.Data.FullName); Top := Top^.Next; // передвигаюсь дальше по стэку end; Top := TempNode; // восстанавливаю указатель на верх стэка end; { Процедура отрисовки списка пар } procedure DrawListOfCouples(var Top: CoupleNode; L: TListBox); var TempNode: CoupleNode; begin L.Clear; // очищаю список на экране TempNode := Top; // сохраняю указатель на верх стэка // Пока не дошел до конца стэка while Top <> nil do begin // Добавляю пару в список на экране L.Items.Add(Top^.Data.Bride.FullName + ' - ' + Top^.Data.Groom.FullName); Top := Top^.Next; // передвигаюсь дальше по стэку end; Top := TempNode; // восстанавливаю указатель на верх стэка end; end.
{******************************************************************************* 作者: dmzn@163.com 2012-02-03 描述: 业务常量定义 备注: *.所有In/Out数据,最好带有TBWDataBase基数据,且位于第一个元素. *******************************************************************************} unit UBusinessConst; interface uses Classes, SysUtils, UBusinessPacker, ULibFun, USysDB; const {*channel type*} cBus_Channel_Connection = $0002; cBus_Channel_Business = $0005; {*query field define*} cQF_Bill = $0001; {*business command*} cBC_GetSerialNO = $0001; //获取串行编号 cBC_ServerNow = $0002; //服务器当前时间 cBC_IsSystemExpired = $0003; //系统是否已过期 cBC_GetTruckPoundData = $0011; //获取车辆称重数据 cBC_SaveTruckPoundData = $0012; //保存车辆称重数据 cBC_SaveTruckInfo = $0013; //保存车辆信息 cBC_UpdateTruckInfo = $0014; //保存车辆信息 cBC_GetCardPoundData = $0015; //获取IC卡称重数据 cBC_SaveCardPoundData = $0016; //保存IC卡称重数据 cBC_SyncME25 = $0020; //同步销售到磅单 cBC_SyncME03 = $0021; //同步供应到磅单 cBC_GetOrderGYValue = $0022; //获取订单供应量 cBC_GetSQLQueryOrder = $0023; //查询订单语句 cBC_GetSQLQueryCustomer = $0024; //查询客户语句 cBC_GetSQLQueryDispatch = $0025; //查询调拨订单 cBC_GetOrderFHValue = $0026; //获取订单发货量 cBC_RemoteExecSQL = $1011; cBC_RemotePrint = $1012; cBC_IsTunnelOK = $1013; cBC_TunnelOC = $1014; {*Reader Index*} cReader_PoundID = 0; cReader_NetValue = 1; cReader_Truck = 2; cReader_MID = 3; cReader_MName = 4; cReader_CusID = 5; cReader_CusName = 6; cReader_SelfID = 7; cReader_SelfName = 8; cReader_TransName = 9; {*Reader name*} sCard_PoundID = 'Card_PoundID'; sCard_NetValue = 'Card_NetValue'; sCard_Truck = 'Card_Truck'; sCard_Transport = 'Card_Transport'; sCard_MaterialID = 'Card_MaterialID'; sCard_Material = 'Card_Material'; sCard_CustomerID = 'Card_CustomerID'; sCard_Customer = 'Card_Customer'; sCard_CompanyID = 'Card_CompanyID'; sCard_CompanyName = 'Card_CompanyName'; type PWorkerQueryFieldData = ^TWorkerQueryFieldData; TWorkerQueryFieldData = record FBase : TBWDataBase; FType : Integer; //类型 FData : string; //数据 end; PWorkerBusinessCommand = ^TWorkerBusinessCommand; TWorkerBusinessCommand = record FBase : TBWDataBase; FCommand : Integer; //命令 FData : string; //数据 FExtParam : string; //参数 end; TPoundStationData = record FStation : string; //磅站标识 FValue : Double; //皮重 FDate : TDateTime; //称重日期 FOperator : string; //操作员 end; PLadingBillItem = ^TLadingBillItem; TLadingBillItem = record FID : string; //交货单号 FZhiKa : string; //纸卡编号 FCusID : string; //客户编号 FCusName : string; //客户名称 FTruck : string; //车牌号码 FType : string; //品种类型 FStockNo : string; //品种编号 FStockName : string; //品种名称 FValue : Double; //提货量 FPrice : Double; //提货单价 FCard : string; //磁卡号 FIsVIP : string; //通道类型 FStatus : string; //当前状态 FNextStatus : string; //下一状态 FPData : TPoundStationData; //称皮 FMData : TPoundStationData; //称毛 FFactory : string; //工厂编号 FPModel : string; //称重模式 FPType : string; //业务类型 FPoundID : string; //称重记录 FSelected : Boolean; //选中状态 FYSValid : string; //验收结果,Y验收成功;N拒收; FKZValue : Double; //供应扣除 FMemo : string; //动作备注 FNCMemo : string; //NC备注信息 FPrinter : string; //打印机,根据过磅读卡器指定 end; TLadingBillItems = array of TLadingBillItem; //交货单列表 procedure AnalyseBillItems(const nData: string; var nItems: TLadingBillItems); //解析由业务对象返回的交货单数据 function CombineBillItmes(const nItems: TLadingBillItems): string; //合并交货单数据为业务对象能处理的字符串 procedure AnalyseCardItems(const nData: string; var nList: TStrings); //解析IC卡数据 function CombineCardItems(const nList: TStrings): string; //合并IC卡数据 resourcestring {*PBWDataBase.FParam*} sParam_NoHintOnError = 'NHE'; //不提示错误 {*plug module id*} sPlug_ModuleBus = '{DF261765-48DC-411D-B6F2-0B37B14E014E}'; //业务模块 sPlug_ModuleHD = '{B584DCD6-40E5-413C-B9F3-6DD75AEF1C62}'; //硬件守护 {*common function*} sSys_BasePacker = 'Sys_BasePacker'; //基本封包器 {*business mit function name*} sBus_ServiceStatus = 'Bus_ServiceStatus'; //服务状态 sBus_GetQueryField = 'Bus_GetQueryField'; //查询的字段 sBus_BusinessCommand = 'Bus_BusinessCommand'; //业务指令 sBus_HardwareCommand = 'Bus_HardwareCommand'; //硬件指令 {*client function name*} sCLI_ServiceStatus = 'CLI_ServiceStatus'; //服务状态 sCLI_GetQueryField = 'CLI_GetQueryField'; //查询的字段 sCLI_BusinessCommand = 'CLI_BusinessCommand'; //业务指令 sCLI_HardwareCommand = 'CLI_HardwareCommand'; //硬件指令 implementation //Date: 2014-09-17 //Parm: 交货单数据;解析结果 //Desc: 解析nData为结构化列表数据 procedure AnalyseBillItems(const nData: string; var nItems: TLadingBillItems); var nStr: string; nIdx,nInt: Integer; nListA,nListB: TStrings; begin nListA := TStringList.Create; nListB := TStringList.Create; try nListA.Text := PackerDecodeStr(nData); //bill list nInt := 0; SetLength(nItems, nListA.Count); for nIdx:=0 to nListA.Count - 1 do begin nListB.Text := PackerDecodeStr(nListA[nIdx]); //bill item with nListB,nItems[nInt] do begin FID := Values['ID']; FZhiKa := Values['ZhiKa']; FCusID := Values['CusID']; FCusName := Values['CusName']; FTruck := Values['Truck']; FType := Values['Type']; FStockNo := Values['StockNo']; FStockName := Values['StockName']; FCard := Values['Card']; FIsVIP := Values['IsVIP']; FStatus := Values['Status']; FNextStatus := Values['NextStatus']; FFactory := Values['Factory']; FPModel := Values['PModel']; FPType := Values['PType']; FPoundID := Values['PoundID']; FSelected := Values['Selected'] = sFlag_Yes; with FPData do begin FStation := Values['PStation']; FDate := Str2DateTime(Values['PDate']); FOperator := Values['PMan']; nStr := Trim(Values['PValue']); if (nStr <> '') and IsNumber(nStr, True) then FPData.FValue := StrToFloat(nStr) else FPData.FValue := 0; end; with FMData do begin FStation := Values['MStation']; FDate := Str2DateTime(Values['MDate']); FOperator := Values['MMan']; nStr := Trim(Values['MValue']); if (nStr <> '') and IsNumber(nStr, True) then FMData.FValue := StrToFloat(nStr) else FMData.FValue := 0; end; nStr := Trim(Values['Value']); if (nStr <> '') and IsNumber(nStr, True) then FValue := StrToFloat(nStr) else FValue := 0; nStr := Trim(Values['Price']); if (nStr <> '') and IsNumber(nStr, True) then FPrice := StrToFloat(nStr) else FPrice := 0; nStr := Trim(Values['KZValue']); if (nStr <> '') and IsNumber(nStr, True) then FKZValue := StrToFloat(nStr) else FKZValue := 0; FYSValid:= Values['YSValid']; FMemo := Values['Memo']; FNCMemo := Values['NCMemo']; FPrinter := Values['Printer']; end; Inc(nInt); end; finally nListB.Free; nListA.Free; end; end; //Date: 2014-09-18 //Parm: 交货单列表 //Desc: 将nItems合并为业务对象能处理的 function CombineBillItmes(const nItems: TLadingBillItems): string; var nIdx: Integer; nListA,nListB: TStrings; begin nListA := TStringList.Create; nListB := TStringList.Create; try Result := ''; nListA.Clear; nListB.Clear; for nIdx:=Low(nItems) to High(nItems) do with nItems[nIdx] do begin if not FSelected then Continue; //ignored with nListB do begin Values['ID'] := FID; Values['ZhiKa'] := FZhiKa; Values['CusID'] := FCusID; Values['CusName'] := FCusName; Values['Truck'] := FTruck; Values['Type'] := FType; Values['StockNo'] := FStockNo; Values['StockName'] := FStockName; Values['Value'] := FloatToStr(FValue); Values['Price'] := FloatToStr(FPrice); Values['Card'] := FCard; Values['IsVIP'] := FIsVIP; Values['Status'] := FStatus; Values['NextStatus'] := FNextStatus; Values['Factory'] := FFactory; Values['PModel'] := FPModel; Values['PType'] := FPType; Values['PoundID'] := FPoundID; with FPData do begin Values['PStation'] := FStation; Values['PValue'] := FloatToStr(FPData.FValue); Values['PDate'] := DateTime2Str(FDate); Values['PMan'] := FOperator; end; with FMData do begin Values['MStation'] := FStation; Values['MValue'] := FloatToStr(FMData.FValue); Values['MDate'] := DateTime2Str(FDate); Values['MMan'] := FOperator; end; if FSelected then Values['Selected'] := sFlag_Yes else Values['Selected'] := sFlag_No; Values['KZValue'] := FloatToStr(FKZValue); Values['YSValid'] := FYSValid; Values['Memo'] := FMemo; Values['NCMemo'] := FNCMemo; Values['Printer'] := FPrinter; end; nListA.Add(PackerEncodeStr(nListB.Text)); //add bill end; Result := PackerEncodeStr(nListA.Text); //pack all finally nListB.Free; nListA.Free; end; end; procedure AnalyseCardItems(const nData: string; var nList: TStrings); var nIdx: Integer; nListA: TStrings; begin if not Assigned(nList) then Exit; //无返回 if Length(nData) < 1 then Exit; //无数据 nListA := TStringList.Create; try nList.Clear; nListA.Clear; SplitStr(nData, nListA, 0, '|', False); for nIdx := 0 to nListA.Count-1 do begin if nIdx = cReader_PoundID then nList.Values[sCard_PoundID] := nListA[nIdx] else if nIdx = cReader_NetValue then nList.Values[sCard_NetValue] := nListA[nIdx] else if nIdx = cReader_Truck then nList.Values[sCard_Truck] := nListA[nIdx] else if nIdx = cReader_TransName then nList.Values[sCard_Transport] := nListA[nIdx] else if nIdx = cReader_MID then nList.Values[sCard_MaterialID] := nListA[nIdx] else if nIdx = cReader_MName then nList.Values[sCard_Material] := nListA[nIdx] else if nIdx = cReader_CusID then nList.Values[sCard_CustomerID] := nListA[nIdx] else if nIdx = cReader_CusName then nList.Values[sCard_Customer] := nListA[nIdx] else if nIdx = cReader_SelfID then nList.Values[sCard_CompanyID] := nListA[nIdx] else if nIdx = cReader_SelfName then nList.Values[sCard_CompanyName] := nListA[nIdx]; end; finally nListA.Free; end; end; function CombineCardItems(const nList: TStrings): string; begin Result := nList.Values[sCard_PoundID] + '|' + //磅单编号 nList.Values[sCard_NetValue] + '|' + //净重(吨) nList.Values[sCard_Truck] + '|' + //车牌号码 nList.Values[sCard_MaterialID] + '|' + //物料编号 nList.Values[sCard_Material] + '|' + //物料名称 nList.Values[sCard_CustomerID] + '|' + //客户编号 nList.Values[sCard_Customer] + '|' + //客户名称 nList.Values[sCard_CompanyID] + '|' + //公司编码 nList.Values[sCard_CompanyName] + '|' + //公司名称 nList.Values[sCard_Transport]; //运输单位 end; end.
unit ThreeGatesExperiment; interface uses System.SysUtils, System.StrUtils; type TThreeGatesExperiment = class(TObject) private _count: integer; function __play(changeDoor: boolean): boolean; public constructor Create(n: integer); procedure Run(changeDoor: boolean); end; implementation { TThreeGatesExperiment } constructor TThreeGatesExperiment.Create(n: integer); begin if n <= 0 then raise Exception.Create('N must be larger than 0!'); _count := n; end; procedure TThreeGatesExperiment.Run(changeDoor: boolean); var i, wins: integer; begin wins := 0; for i := 0 to _count do begin if __play(changeDoor) then Inc(wins); end; Writeln(IfThen(changeDoor, 'Change', 'not Change ')); Writeln(' winning rate: ' + (wins / _count).ToString); end; function TThreeGatesExperiment.__play(changeDoor: boolean): boolean; var prizeDoor: Integer; playerChoice: Integer; wins: Boolean; begin prizeDoor := Random(3); playerChoice := Random(3); if (playerChoice = prizeDoor) then begin if changeDoor then wins := False else wins := true end else begin if changeDoor then wins := true else wins := False end; Result := wins; end; end.
unit Boules; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Menus, ExtCtrls,variables ; procedure nouvelle_position(n:integer); {calcule tout } procedure collision(n1,n2 :integer); {calcul des vitesses après chocs} procedure bande(n:integer); procedure trou(n:integer); procedure ralentir(n:integer); procedure replacer_blanche(x,y:integer); function test_collision2(n1,n2:integer):boolean; function test_collision(n1,n2:integer):boolean; function distance(n1,n2:integer):single; function inv(m:integer):integer; {utilisé pour savoir qui n'a pas la main} implementation procedure nouvelle_position(n:integer); var i,j:integer; begin boule[n].xold := boule[n].x; boule[n].yold := boule[n].y; for i:=1 to 16 do if boule[i].etat<>0 then begin bande(i);trou(i); for j:=i+1 to 16 do begin if boule[j].etat<>0 then begin if test_collision(i,j) then begin collision(i,j); {si collision on assigne la couleur de la premiére boule touchée} if casse then begin if (i=1) and (jr[main].first=clblue) then jr[main].first:=boule[j].couleur; if (j=1) and (jr[main].first=clblue) then jr[main].first:=boule[i].couleur; end else casse:=true; end; end; end; boule[n].x:=boule[n].xold+boule[n].vx; boule[n].y:=boule[n].yold+boule[n].vy; end; ralentir(n); end; function test_collision(n1,n2:integer):boolean; {renvoie vrai s'il y collision entre les deux boules, sinon renvoie non} var dx,dy,dx2,dy2:single; begin dx:=(boule[n1].x+boule[n1].vx-boule[n2].x-boule[n2].vx); {ecart sur x entre les 2 boules} dy:=(boule[n1].y+boule[n1].vy-boule[n2].y-boule[n2].vy);{ecart sur y} dx2:=(boule[n1].x-boule[n2].x); dy2:=(boule[n1].y-boule[n2].y); if ((dx*dx+dy*dy)<={390}324) and ((dx2*dx2+dy2*dy2)>=320) {formule de pythagore} then result:=true else result:=false; end; function test_collision2(n1,n2:integer):boolean; {renvoie vrai s'il y collision entre les deux boules, sinon renvoie non} var dx,dy:single; begin dx:=(boule[n1].x-boule[n2].x); {ecart sur x entre les 2 boules} dy:=(boule[n1].y-boule[n2].y); {acart sur y} if (dx*dx+dy*dy)<={390}320 {formule de pythagore} then result:=true else result:=false; end; procedure collision(n1,n2 :integer); var dy,dx,v1x,v1y,v2x,v2y,a,stock:single; begin if test_collision2(n1,n2) then begin stock:=boule[n1].vx; boule[n1].vx:=boule[n2].vx*3/4+stock*1/4; boule[n2].vx:=stock*3/4+boule[n2].vx*1/4; stock:=boule[n1].vy; boule[n1].vy:=boule[n2].vy*3/4+stock*1/4; boule[n2].vy:=stock*3/4+boule[n2].vy*1/4 end; if test_collision(n1,n2) then dx:=(boule[n1].x+boule[n1].vx-boule[n2].x-boule[n2].vx); {idem} dy:=(boule[n1].y+boule[n1].vy-boule[n2].y-boule[n2].vy); {idem} a:=arctan(dy/(dx+0.00000001)); {angle formé par l'axe passant par les centres des boules et l'axe x} v1x:=boule[n1].vx; {0.000000001 pour enlever la division par 0} v2x:=boule[n2].vx; v1y:=boule[n1].vy; v2y:=boule[n2].vy; {nouvelles vitesses données par les relations simplificatrices des chocs entre boules} boule[n1].vx:=(v2x*cos(a)+v2y*sin(a))*cos(a)+(v1x*sin(a)-v1y*cos(a))*sin(a) ; boule[n1].vy:=(v2x*cos(a)+v2y*sin(a))*sin(a)+(-v1x*sin(a)+v1y*cos(a))*cos(a) ; boule[n2].vx:=(v1x*cos(a)+v1y*sin(a))*cos(a)+(v2x*sin(a)-v2y*cos(a))*sin(a) ; boule[n2].vy:=(v1x*cos(a)+v1y*sin(a))*sin(a)+(-v2x*sin(a)+v2y*cos(a))*cos(a) ; end; procedure bande(n:integer); var a,xx,yy:single; begin xx:=boule[n].x+boule[n].vx; yy:=boule[n].y+boule[n].vy; {bandes horizontales} if (( (xx>=xb) and (xx<=xc) ) or ( (xx>=xd) and (xx<=xe) )) and ( (yy<=yb) or (yy>=yk) ) then boule[n].vy:=-boule[n].vy; {bandes verticales} if ( (yy>=ya) and (yy<=yl) and ( (xx<=xa) or (xx>=xf) ) ) or ( (((xx>=xc) and (xx<=xcp)) or ((xx>=xdp) and (xx<=xd))) and ((yy<=ycp) or (yy>=yjp)) ) then boule[n].vx:=-boule[n].vx; {droites à 45 degré montantes} if ( (xx+yy<=xc+yb) and (xx>=xc) and (yy>=ycp) ) or ( (xx+yy>=xd+yk) and (xx<=xd) and (yy<=yjp) ) or ( (xx+yy<=xa+yl) and (yy>=yl) ) or ( (xx+yy>=xb+yk) and (xx<=xb) ) or ( (xx+yy<=xe+yb) and (xx>=xe) ) or ( (xx+yy>=xf+ya) and (yy<=ya) ) then begin a:=boule[n].vx; boule[n].vx:=-boule[n].vy; boule[n].vy:=-a; exit end; {droites à 45 degrés descendantes} if ( (xx-xd>=yy-yb) and (xx<=xd) and (yy>=ycp) ) or ( (xx-xc<=yy-yk) and (xx>=xc) and (yy<=yjp) ) or ( (xx-xa<=yy-ya) and (yy<=ya) ) or ( (xx-xb>=yy-yb) and (xx<=xb) ) or ( (xx-xe<=yy-yk) and (xx>=xe) ) or ( (xx-xf>=yy-yl) and (yy>=yl) ) then begin a:=boule[n].vx; boule[n].vx:=boule[n].vy; boule[n].vy:=a; exit end; end; procedure trou(n:integer); var pasmain:integer; {numéro du joueur qui n'a pas la main} begin {disparition des boules} if ((boule[n].y<=y1)or(boule[n].y>=y2)or(boule[n].x<=x1)or(boule[n].x>=x2)) then begin boule[n].etat:=2; boule[n].vx:=0; boule[n].vy:=0; {règles} if (n=1) and (faute<>-3) and (faute<>4) then faute:=1; if (n>=3) and (faute<>-3) and (faute<>4) then begin if (jr[main].couleur=clblue) then {assigne des couleurs aux joueurs} begin {jr[main].rentrees:=1;} faute:=-2; jr[main].couleur:=boule[n].couleur; pasmain:=inv(main); if jr[main].couleur=clred then jr[pasmain].couleur:=clyellow else jr[pasmain].couleur:=clred end else if boule[n].couleur=jr[main].couleur then begin faute:=-1-3*random(5); {éventuellemant écrasé si boules adverses rentrées ensuite} {jr[main].rentrees:=jr[main].rentrees+1;} end else begin if jr[main].rentrees=false then faute:=3; pasmain:=inv(main); {jr[pasmain].rentrees:=jr[pasmain].rentrees+1;} end; end; if n=2 then {boule noire!} begin if jr[main].rentrees=true then faute:=-3 else faute:=4; end; end; {effet donné par les bordures des trous, permet aussi à une boule de ne pas s'arreter dans le vide} {trou 1} if (((boule[n].x-xt1)*(boule[n].x-xt1)+(boule[n].y-yt1)*(boule[n].y-yt1))<=rtrou2) then begin boule[n].vy:=boule[n].vy-0.0007; boule[n].vx:=boule[n].vx-0.0007 end; {trou 2} if (((boule[n].x-xt2)*(boule[n].x-xt2)+(boule[n].y-yt2)*(boule[n].y-yt2))<=rtrou2) then boule[n].vy:=boule[n].vy-0.0007; {trou 3} if (((boule[n].x-xt3)*(boule[n].x-xt3)+(boule[n].y-yt1)*(boule[n].y-yt1))<=rtrou2) then begin boule[n].vy:=boule[n].vy-0.0007; boule[n].vx:=boule[n].vx+0.0007 end; {trou 4} if (((boule[n].x-xt1)*(boule[n].x-xt1)+(boule[n].y-yt4)*(boule[n].y-yt4))<=rtrou2) then begin boule[n].vy:=boule[n].vy+0.0007; boule[n].vx:=boule[n].vx-0.0007 end; {trou 5} if (((boule[n].x-xt2)*(boule[n].x-xt2)+(boule[n].y-yt5)*(boule[n].y-yt5))<=rtrou2) then boule[n].vy:=boule[n].vy+0.0007; {trou 6} if (((boule[n].x-xt3)*(boule[n].x-xt3)+(boule[n].y-yt4)*(boule[n].y-yt4))<=rtrou2) then begin boule[n].vy:=boule[n].vy+0.0007; boule[n].vx:=boule[n].vx+0.0007 end; end; procedure ralentir(n:integer); begin boule[n].vx:=boule[n].vx*kralentissement; boule[n].vy:=boule[n].vy*kralentissement; if abs(boule[n].vx)<0.01 then boule[n].vx:=0; if abs(boule[n].vy)<0.01 then boule[n].vy:=0; {autre essai infructueux : cette fois ci on soustrait au lieu de multiplier par un nombre : a:=arctan(boule[n].vy/boule[n].vx); boule[n].vx:=boule[n].vx-kralentissement*cos(a); boule[n].vy:=boule[n].vy-kralentissement*sin(a);} end; procedure replacer_blanche(x,y:integer); var contact:boolean; i:integer; d,dmin:single; {distances} begin contact:=false; dmin:=1000; {distance minimale} for i:=2 to 16 do begin d:=sqrt((x-boule[i].x)*(x-boule[i].x)+(y-boule[i].y)*(y-boule[i].y)); if dmin>d then dmin:=d; end; if dmin<=2*rboule then contact:= true; {évite le chevauchement avec une autre boule} {petite tricherie pour pas que la boule ne tombe pas ds le trou} if (x>45+rboule) and (x<=154) and (y>45+rboule) and (y<250-rboule) and not contact then begin boule[1].etat:=1; boule[1].x:=x; boule[1].y:=y; end; end; function distance(n1,n2:integer):single; begin result:=sqrt((boule[n1].x-boule[n2].x)*(boule[n1].x-boule[n2].x)+(boule[n1].y-boule[n2].y)*(boule[n1].y-boule[n2].y)) end; function inv(m:integer):integer; {utilisé pour savoir qui n'a pas la main} begin if m=1 then result:=2 else result:=1; end; end.
(****************************************************************) (* Programmname : PRIMITIV.PAS V1.5 *) (* Programmautor : Michael Rippl *) (* Compiler : Quick Pascal V1.0 *) (* Inhalt : Primitive Routinen fr den Videospeicher *) (* Bemerkung : Erkennt automatisch vorhandene Grafikkarte *) (* Letzte Žnderung : 10-Sep-1990 *) (****************************************************************) UNIT Primitiv; INTERFACE USES Dos, Crt; (* Units einbinden *) TYPE Keys = (EndPageUp, EndPageDown, EndEscape, EndTabulator, EndShiftTabulator, EndReturn, EndCursUp, EndCursDown); Colors = (Black, Blue, Green, Cyan, Red, Magenta, Brown, LightGrey, DarkGrey, LightBlue, LightGreen, LightCyan, LightRed, LightMagenta, Yellow, White); VideoModes = (MDA, CGA, EGA, mEGA, VGA, mVGA, MCGA, mMCGA); Direction = (Horizontal, Vertical); Scrolling = (Up, Down, Left, Right); Borders = (bSingle, bDouble, bDithering, bFull); KeySet = SET OF Keys; pVideo = ^Video; (* Zeigt auf Videospeicher *) Video = RECORD (* Ein Videospeicherplatz *) Character : CHAR; (* Ein Buchstabe *) Attribute : BYTE; (* Sein Attribut *) END; VAR NrOfLines, (* Anzahl der Zeilen *) NrOfColumns : BYTE; (* Anzahl der Spalten *) VideoMode : VideoModes; (* Aktive Grafikkarte *) VideoSegment, (* Segment des Video-Rams *) VideoOffset : WORD; (* Offset des Video-Rams *) ColorGraphic : BOOLEAN; (* Farbgrafik oder nicht *) (* Berechnet Zeiger in den Videospeicher *) FUNCTION VideoPointer(Line, Column : BYTE) : pVideo; (* Ein Teil des Videospeichers wird in einen Puffer gesichert *) PROCEDURE VideoSave(LeftEdge, TopEdge, Width, Height : BYTE; Target : POINTER); (* Ein Datenpuffer wird in den Videospeicher kopiert *) PROCEDURE VideoLoad(LeftEdge, TopEdge, Width, Height : BYTE; Source : POINTER); (* Erkennt automatisch eine vorhandene Grafikkarte im Rechner *) PROCEDURE GetVideoMode(VAR VideoAdapter : VideoModes; VAR Color : BOOLEAN; VAR Lines, Columns : BYTE; VAR VideoAddress : WORD); (* Den echten Cursor setzen *) PROCEDURE SetXY(X, Y : BYTE); (* Berechnet die Position X des echten Cursors *) FUNCTION GetX : BYTE; (* Berechnet die Position Y des echten Cursors *) FUNCTION GetY : BYTE; (* Ein Teilbereich des Videospeichers wird mit einem Zeichen aufgefllt *) PROCEDURE VideoFill(LeftEdge, TopEdge, Width, Height : BYTE; Character : CHAR; DetailPen, BlockPen : Colors); (* Ein Teilbereich des Bildschirms wird gescrollt *) PROCEDURE VideoScroll(LeftEdge, TopEdge, Width, Height, Delta : BYTE; DoScroll : Scrolling; DetailPen, BlockPen : Colors); (* Es wird eine horizontale oder vertikale Line gezeichnet *) PROCEDURE DrawLine(LeftEdge, TopEdge, LineLength : BYTE; Line : Direction; Character : CHAR; DetailPen, BlockPen : Colors); (* Es wird ein rechteckiger Rahmen auf den Bildschirm gezeichnet *) PROCEDURE DrawBorder(LeftEdge, TopEdge, Width, Height : BYTE; Border : Borders; DetailPen, BlockPen : Colors); (* Ein einzelnes Zeichen wird auf dem Bildschirm ausgegeben *) PROCEDURE PutChar(LeftEdge, TopEdge : BYTE; Character : CHAR; DetailPen, BlockPen : Colors); (* Ein Zeichenkette wird auf dem Bildschirm ausgegeben *) PROCEDURE PutString(LeftEdge, TopEdge : BYTE; TextString : STRING; DetailPen, BlockPen : Colors); (* Fllt einen Bereich des Videospeichers mit einem Attribut *) PROCEDURE PutAttributes(LeftEdge, TopEdge, Width, Height, Attribute : BYTE); (* Fllt einen Bereich mit einem Zeichen auf ohne deren Attribute zu „ndern *) PROCEDURE PutCharacters(LeftEdge, TopEdge, Width, Height : BYTE; Character : CHAR); (* Zeichen an einer bestimmten Bildschirmposition zurckgeben *) FUNCTION GetCharacter(LeftEdge, TopEdge : BYTE) : CHAR; (* Attribut an einer bestimmten Bildschirmposition zurckgeben *) FUNCTION GetAttribute(LeftEdge, TopEdge : BYTE) : BYTE; (* Es wird der gesamte Bildschirm gel”scht *) PROCEDURE ClearScreen; (* Die Gestalt des Cursors wird definiert *) PROCEDURE CursorDefine(Start, Stop : BYTE); (* Der Cursor wird vom Bildschirm entfernt *) PROCEDURE CursorOff; (* Der Cursor erh„lt die Gestalt eines vollen Blocks *) PROCEDURE CursorBlock; (* Der Cursor erh„lt die Gestalt einer Linie *) PROCEDURE CursorLine; (* Es wird eine Zeichenkette vom Bildschirm eingelesen *) PROCEDURE VideoRead(LeftEdge, TopEdge, Width : BYTE; VAR TextString : STRING; DetailPen, BlockPen : Colors; VAR EndKeys : KeySet; FillWidth, TextOutput : BOOLEAN); IMPLEMENTATION TYPE Address = RECORD (* Zugriff auf Zeiger *) Offset, Segment : WORD; END; (* Berechnet Zeiger in den Videospeicher *) FUNCTION VideoPointer(Line, Column : BYTE) : pVideo; BEGIN VideoPointer := Ptr(VideoSegment, VideoOffset + ((NrOfColumns * Line + Column) SHL 1)); END; (* VideoPointer *) (* Ein Teil des Videospeichers wird in einen Puffer gesichert *) PROCEDURE VideoSave(LeftEdge, TopEdge, Width, Height : BYTE; Target : POINTER); VAR NrOfBytes : INTEGER; k : BYTE; Source : pVideo; BEGIN NrOfBytes := Width SHL 1; (* Zu kopierende Bytes *) FOR k := 1 TO Height DO BEGIN Source := VideoPointer(TopEdge, LeftEdge); (* Quelladresse *) Move(Source^, Target^, NrOfBytes); (* Eine Zeile kopieren *) Inc(Address(Target).Offset, NrOfBytes); (* Neue Zieladresse *) Inc(TopEdge); (* Neue Zeile *) END; END; (* VideoSave *) (* Ein Datenpuffer wird in den Videospeicher kopiert *) PROCEDURE VideoLoad(LeftEdge, TopEdge, Width, Height : BYTE; Source : POINTER); VAR NrOfBytes : INTEGER; k : BYTE; Target : pVideo; BEGIN NrOfBytes := Width SHL 1; (* Zu kopierende Bytes *) FOR k := 1 TO Height DO BEGIN Target := VideoPointer(TopEdge, LeftEdge); (* Zieladresse *) Move(Source^, Target^, NrOfBytes); (* Eine Zeile kopieren *) Inc(Address(Source).Offset, NrOfBytes); (* Neue Zieladresse *) Inc(TopEdge); (* Neue Zeile *) END; END; (* VideoLoad *) (* Den echten Cursor setzen *) PROCEDURE SetXY(X, Y : BYTE); VAR Regs : REGISTERS; BEGIN Regs.AH := $2; (* Funktion 2 *) Regs.BH := 0; (* Bildschirmseite 0 *) Regs.DH := Y; (* Zeile setzen *) Regs.DL := X; (* Spalte setzen *) Intr($10, Regs); (* Video Interrupt *) END; (* SetXY *) (* Berechnet die Position X des echten Cursors *) FUNCTION GetX : BYTE; BEGIN GetX := WhereX - 1; END; (* GetX *) (* Berechnet die Position Y des echten Cursors *) FUNCTION GetY : BYTE; BEGIN GetY := WhereY - 1; END; (* GetY *) (* Ein einzelnes Zeichen wird ausgegeben *) PROCEDURE PutChar(LeftEdge, TopEdge : BYTE; Character : CHAR; DetailPen, BlockPen : Colors); VAR Target : pVideo; BEGIN Target := VideoPointer(TopEdge, LeftEdge); Target^.Character := Character; (* Zeichen eintragen *) Target^.Attribute := (Ord(BlockPen) SHL 4) OR Ord(DetailPen); END; (* PutChar *) (* Ein Zeichenkette wird auf dem Bildschirm ausgegeben *) PROCEDURE PutString(LeftEdge, TopEdge : BYTE; TextString : STRING; DetailPen, BlockPen : Colors); VAR k, Attribute : BYTE; Target : pVideo; BEGIN Attribute := (Ord(BlockPen) SHL 4) OR Ord(DetailPen); Target := VideoPointer(TopEdge, LeftEdge); FOR k := 1 TO Ord(TextString[0]) DO (* Text ausgeben *) BEGIN Target^.Character := TextString[k]; Target^.Attribute := Attribute; Inc(Address(Target).Offset, 2); (* N„chstes Zeichen *) END; END; (* PutString *) (* Fllt einen Bereich des Videospeichers mit einem Attribut *) PROCEDURE PutAttributes(LeftEdge, TopEdge, Width, Height, Attribute : BYTE); VAR i, k : BYTE; Target : pVideo; BEGIN FOR k := 1 TO Height DO BEGIN Target := VideoPointer(TopEdge, LeftEdge); FOR i := 1 TO Width DO BEGIN Target^.Attribute := Attribute; (* Attribut eintragen *) Inc(Address(Target).Offset, 2); (* N„chstes Attribut *) END; Inc(TopEdge); (* N„chste Zeile *) END; END; (* PutAttributes *) (* Fllt einen Bereich mit einem Zeichen auf ohne deren Attribute zu „ndern *) PROCEDURE PutCharacters(LeftEdge, TopEdge, Width, Height : BYTE; Character : CHAR); VAR i, k : BYTE; Target : pVideo; BEGIN FOR k := 1 TO Height DO BEGIN Target := VideoPointer(TopEdge, LeftEdge); FOR i := 1 TO Width DO BEGIN Target^.Character := Character; (* Zeichen eintragen *) Inc(Address(Target).Offset, 2); (* N„chstes Zeichen *) END; Inc(TopEdge); (* N„chste Zeile *) END; END; (* PutCharacters *) (* Zeichen an einer bestimmten Bildschirmposition zurckgeben *) FUNCTION GetCharacter(LeftEdge, TopEdge : BYTE) : CHAR; VAR Target : pVideo; BEGIN Target := VideoPointer(TopEdge, LeftEdge); GetCharacter := Target^.Character; (* Zeichen auslesen *) END; (* GetCharacter *) (* Attribut an einer bestimmten Bildschirmposition zurckgeben *) FUNCTION GetAttribute(LeftEdge, TopEdge : BYTE) : BYTE; VAR Target : pVideo; BEGIN Target := VideoPointer(TopEdge, LeftEdge); GetAttribute := Target^.Attribute; (* Attribut auslesen *) END; (* GetAttribute *) (* Es wird der gesamte Bildschirm gel”scht *) PROCEDURE ClearScreen; BEGIN PutCharacters(0, 0, NrOfColumns, NrOfLines, ' '); END; (* ClearScreen *) (* Der Cursor wird vom Bildschirm entfernt *) PROCEDURE CursorOff; VAR Regs : REGISTERS; BEGIN SetXY(0, NrOfLines + 1); (* Auáerhalb des Bildes *) END; (* CursorOff *) (* Die Gestalt des Cursors wird definiert *) PROCEDURE CursorDefine(Start, Stop : BYTE); VAR Regs : REGISTERS; BEGIN Regs.AH := $1; (* Funktion 1 *) Regs.CH := Start; (* Video Scan-Zeile Beginn *) Regs.CL := Stop; (* Video Scan-Zeile Ende *) Intr($10, Regs); (* Video Interrupt *) END; (* CursorDefine *) (* Der Cursor erh„lt die Gestalt eines vollen Blocks *) PROCEDURE CursorBlock; BEGIN IF ColorGraphic THEN (* Color Modus *) CursorDefine(0, 7) ELSE CursorDefine(0, 13); (* Monochrom Modus *) END; (* CursorBlock *) (* Der Cursor erh„lt die Gestalt einer Linie *) PROCEDURE CursorLine; BEGIN IF ColorGraphic THEN (* Color Modus *) CursorDefine(6, 7) ELSE CursorDefine(12, 13); (* Monochrom Modus *) END; (* CursorLine *) (* Es wird eine horizontale oder vertikale Linie gezeichnet *) PROCEDURE DrawLine(LeftEdge, TopEdge, LineLength : BYTE; Line : Direction; Character : CHAR; DetailPen, BlockPen : Colors); VAR k : BYTE; Target : pVideo; Attribute : BYTE; BEGIN Attribute := (Ord(BlockPen) SHL 4) OR Ord(DetailPen); IF Line = Horizontal THEN (* Horizontale Linie *) BEGIN Target := VideoPointer(TopEdge, LeftEdge); FOR k := 1 TO LineLength DO (* Linie zeichnen *) BEGIN Target^.Character := Character; (* Zeichen eintragen *) Target^.Attribute := Attribute; Inc(Address(Target).Offset, 2); (* N„chstes Zeichen *) END; END ELSE (* Vertikale Linie *) BEGIN FOR k := 1 TO LineLength DO (* Linie zeichnen *) BEGIN Target := VideoPointer(TopEdge, LeftEdge); Target^.Character := Character; (* Zeichen eintragen *) Target^.Attribute := Attribute; Inc(TopEdge); (* N„chstes Zeichen *) END; END; END; (* DrawLine *) (* Es wird ein rechteckiger Rahmen auf den Bildschirm gezeichnet *) PROCEDURE DrawBorder(LeftEdge, TopEdge, Width, Height : BYTE; Border : Borders; DetailPen, BlockPen : Colors); VAR Character : CHAR; BEGIN CASE Border OF (* Horizontale Linien *) bSingle : Character := Chr(196); bDouble : Character := Chr(205); bDithering : Character := Chr(177); bFull : Character := Chr(219); END; DrawLine(LeftEdge, TopEdge, Width, Horizontal, Character, DetailPen, BlockPen); DrawLine(LeftEdge, TopEdge + Height - 1, Width, Horizontal, Character, DetailPen, BlockPen); IF Border = bSingle THEN Character := Chr(179) (* Vertikale Linien *) ELSE IF Border = bDouble THEN Character := Chr(186); DrawLine(LeftEdge, TopEdge, Height, Vertical, Character, DetailPen, BlockPen); DrawLine(LeftEdge + Width - 1, TopEdge, Height, Vertical, Character, DetailPen, BlockPen); IF Border = bSingle THEN (* Eckpunkte zeichnen *) BEGIN PutChar(LeftEdge, TopEdge, Chr(218), DetailPen, BlockPen); PutChar(LeftEdge + Width - 1, TopEdge, Chr(191), DetailPen, BlockPen); PutChar(LeftEdge, TopEdge + Height - 1, Chr(192), DetailPen, BlockPen); PutChar(LeftEdge + Width - 1, TopEdge + Height - 1, Chr(217), DetailPen, BlockPen); END ELSE IF Border = bDouble THEN (* Eckpunkte zeichnen *) BEGIN PutChar(LeftEdge, TopEdge, Chr(201), DetailPen, BlockPen); PutChar(LeftEdge + Width - 1, TopEdge, Chr(187), DetailPen, BlockPen); PutChar(LeftEdge, TopEdge + Height - 1, Chr(200), DetailPen, BlockPen); PutChar(LeftEdge + Width - 1, TopEdge + Height - 1, Chr(188), DetailPen, BlockPen); END; END; (* DrawBorder *) (* Ein Teilbereich des Videospeichers wird mit einem Zeichen aufgefllt *) PROCEDURE VideoFill(LeftEdge, TopEdge, Width, Height : BYTE; Character : CHAR; DetailPen, BlockPen : Colors); VAR i, k, Attribute : BYTE; Target : pVideo; BEGIN Attribute := (Ord(BlockPen) SHL 4) OR Ord(DetailPen); FOR k := 1 TO Height DO BEGIN Target := VideoPointer(TopEdge, LeftEdge); FOR i := 1 TO Width DO BEGIN Target^.Character := Character; (* Zeichen eintragen *) Target^.Attribute := Attribute; Inc(Address(Target).Offset, 2); (* N„chstes Zeichen *) END; Inc(TopEdge); (* N„chste Zeile *) END; END; (* VideoFill *) (* Ein Teilbereich des Bildschirms wird gescrollt *) PROCEDURE VideoScroll(LeftEdge, TopEdge, Width, Height, Delta : BYTE; DoScroll : Scrolling; DetailPen, BlockPen : Colors); VAR NrOfBytes, LineOffset : INTEGER; k : BYTE; Source, Target : pVideo; BEGIN LineOffset := NrOfColumns SHL 1; (* Anzahl der Zeilen * 2 *) NrOfBytes := Width SHL 1; (* Breite * 2 *) CASE DoScroll OF Up : (* Nach oben scrollen *) BEGIN Target := VideoPointer(TopEdge, LeftEdge); Source := VideoPointer(TopEdge + Delta, LeftEdge); FOR k := 1 TO Height - Delta DO (* Zeilen kopieren *) BEGIN Move(Source^, Target^, NrOfBytes); Inc(Address(Source).Offset, LineOffset); Inc(Address(Target).Offset, LineOffset); END; VideoFill(LeftEdge, TopEdge + Height - Delta, Width, Delta, ' ', DetailPen, BlockPen); END; Down : (* Nach unten scrollen *) BEGIN Target := VideoPointer(TopEdge + Height - 1, LeftEdge); Source := VideoPointer(TopEdge + Height - 1 - Delta, LeftEdge); FOR k := 1 TO Height - Delta DO (* Zeilen kopieren *) BEGIN Move(Source^, Target^, NrOfBytes); Dec(Address(Source).Offset, LineOffset); Dec(Address(Target).Offset, LineOffset); END; VideoFill(LeftEdge, TopEdge, Width, Delta, ' ', DetailPen, BlockPen); END; Left : (* Nach links scrollen *) BEGIN Target := VideoPointer(TopEdge, LeftEdge); Source := VideoPointer(TopEdge, LeftEdge + Delta); FOR k := 1 TO Height DO (* Zeilen kopieren *) BEGIN Move(Source^, Target^, NrOfBytes - (Delta SHL 1)); Inc(Address(Source).Offset, LineOffset); Inc(Address(Target).Offset, LineOffset); END; VideoFill(LeftEdge + Width - Delta, TopEdge, Delta, Height, ' ', DetailPen, BlockPen); END; Right : (* Nach rechts scrollen *) BEGIN Target := VideoPointer(TopEdge, LeftEdge + Delta); Source := VideoPointer(TopEdge, LeftEdge); FOR k := 1 TO Height DO (* Zeilen kopieren *) BEGIN Move(Source^, Target^, NrOfBytes - (Delta SHL 1)); Inc(Address(Source).Offset, LineOffset); Inc(Address(Target).Offset, LineOffset); END; VideoFill(LeftEdge, TopEdge, Delta, Height, ' ', DetailPen, BlockPen); END; END; END; (* VideoScroll *) (* Es wird eine Zeichenkette vom Bildschirm eingelesen *) PROCEDURE VideoRead(LeftEdge, TopEdge, Width : BYTE; VAR TextString : STRING; DetailPen, BlockPen : Colors; VAR EndKeys : KeySet; FillWidth, TextOutput : BOOLEAN); CONST CR = 13; (* Carriage Return *) BS = 8; (* Back Space *) ESC = 27; (* Escape *) TAB = 9; (* Tabulator *) ShiftTab = 15; (* Shift Tabulator *) Pos1Key = 71; (* Pos1 Taste *) EndKey = 79; (* Ende Taste *) CurUp = 72; (* Cursor Up *) CurDown = 80; (* Cursor Down *) CurLeft = 75; (* Cursor Left *) CurRight = 77; (* Cursor Right *) PgDn = 81; (* Page Down *) PgUp = 73; (* Page Up *) Insert = 82; (* Insert Taste *) Delete = 83; (* Delete Taste *) ScanCode = 0; (* Taste liefert Scan Code *) VAR DoLoop, DoInsert : BOOLEAN; k, CursorX, (* Position des Cursors *) NrOfChars : BYTE; (* Eingegebene Buchstaben *) Character : CHAR; NrOfBytes : INTEGER; Source, Target : pVideo; BEGIN CursorLine; (* Cursor definieren *) SetXY(LeftEdge, TopEdge); IF FillWidth THEN (* Textbereich einf„rben *) PutAttributes(LeftEdge, TopEdge, Width, 1, (Ord(BlockPen) SHL 4) OR Ord(DetailPen)); NrOfChars := 0; (* Noch nichts eingegeben *) CursorX := 0; (* Cursor ganz links *) DoInsert := FALSE; (* Texte berschreiben *) DoLoop := TRUE; (* Eingaben entgegennehmen *) IF TextOutput THEN (* Defaulttext ausgeben *) BEGIN IF Ord(TextString[0]) > Width THEN TextString[0] := Chr(Width); NrOfChars := Ord(TextString[0]); (* Text bereits vorhanden *) PutString(LeftEdge, TopEdge, TextString, DetailPen, BlockPen); END; REPEAT REPEAT UNTIL KeyPressed; (* Warten auf Tastendruck *) Character := ReadKey; (* Zeichen einlesen *) IF Character = Chr(ScanCode) THEN (* Taste liefert Scan Code *) BEGIN Character := ReadKey; (* Tastencode einlesen *) CASE Ord(Character) OF CurLeft : (* Cursor nach links *) BEGIN IF CursorX > 0 THEN (* Kein linker Rand *) BEGIN SetXY(GetX - 1, GetY); (* Cursor setzen *) Dec(CursorX); END ELSE Write(Chr(7)); (* Unerlaubt = Piepston *) END; CurRight : (* Cursor nach rechts *) BEGIN IF (CursorX < NrOfChars) AND (CursorX < Width - 1) THEN BEGIN SetXY(GetX + 1, GetY); (* Cursor setzen *) Inc(CursorX); END ELSE Write(Chr(7)); (* Unerlaubt = Piepston *) END; Pos1Key : (* Cursor erste Position *) BEGIN SetXY(GetX - CursorX, GetY); (* Anfang Eingabefeld *) CursorX := 0; (* Cursor am Feldanfang *) END; EndKey : (* Cursor letzte Position *) BEGIN SetXY(GetX - CursorX + NrOfChars, GetY); CursorX := NrOfChars; (* Cursor am Feldende *) END; Insert : (* šberschreiben/Einfgen *) BEGIN DoInsert := NOT DoInsert; IF DoInsert THEN CursorBlock (* Block = Einfgen *) ELSE CursorLine; (* Line = šberschreiben *) END; Delete : (* Buchstabe l”schen *) BEGIN IF (NrOfChars = 0) OR (CursorX >= NrOfChars) THEN Write(Chr(7)) (* Nichts mehr zu l”schen *) ELSE BEGIN (* Buchstabe l”schen *) NrOfBytes := NrOfChars - CursorX; IF NrOfBytes > 0 THEN (* Text zu kopieren *) BEGIN Source := VideoPointer(TopEdge, LeftEdge + CursorX + 1); Target := VideoPointer(TopEdge, LeftEdge + CursorX); Move(Source^, Target^, NrOfBytes SHL 1); Move(TextString[CursorX + 2], TextString[CursorX + 1], NrOfBytes); END; PutChar(LeftEdge + NrOfChars - 1, TopEdge, ' ', DetailPen, BlockPen); Dec(NrOfChars); END; END; PgDn : (* Page Down Taste *) BEGIN IF EndPageDown IN EndKeys THEN (* PageDown = Ende *) BEGIN TextString[0] := Chr(NrOfChars); (* Textl„nge eintragen *) CursorLine; EndKeys := [EndPageDown]; (* Mit PageDown beendet *) DoLoop := FALSE; END ELSE Write(Chr(7)); (* Taste unzul„ssig *) END; PgUp : (* Page Up Taste *) BEGIN IF EndPageUp IN EndKeys THEN (* PageUp = Ende *) BEGIN TextString[0] := Chr(NrOfChars); (* Textl„nge eintragen *) CursorLine; EndKeys := [EndPageUp]; (* Mit PageUp beendet *) DoLoop := FALSE; END ELSE Write(Chr(7)); (* Taste unzul„ssig *) END; ShiftTab : (* Shift TAB Taste *) BEGIN IF EndShiftTabulator IN EndKeys THEN(* ShiftTabulator = Ende *) BEGIN TextString[0] := Chr(NrOfChars); (* Textl„nge eintragen *) CursorLine; EndKeys := [EndShiftTabulator]; (* Mit ShiftTab beendet *) DoLoop := FALSE; END ELSE Write(Chr(7)); (* Taste unzul„ssig *) END; CurUp : (* Cursor Up Taste *) BEGIN IF EndCursUp IN EndKeys THEN (* CursorUp = Ende *) BEGIN TextString[0] := Chr(NrOfChars); (* Textl„nge eintragen *) CursorLine; EndKeys := [EndCursUp]; (* Mit CursorUp beendet *) DoLoop := FALSE; END ELSE Write(Chr(7)); (* Taste unzul„ssig *) END; CurDown : (* Cursor Down Taste *) BEGIN IF EndCursDown IN EndKeys THEN (* CursorDown = Ende *) BEGIN TextString[0] := Chr(NrOfChars); (* Textl„nge eintragen *) CursorLine; EndKeys := [EndCursDown]; (* Mit CursorDown beendet *) DoLoop := FALSE; END ELSE Write(Chr(7)); (* Taste unzul„ssig *) END; ELSE Write(Chr(7)); (* Fremde Taste = Piepston *) END; END ELSE (* Normales Zeichen *) BEGIN CASE Ord(Character) OF BS : (* Back Space Taste *) BEGIN IF (CursorX = 0) OR (NrOfChars = 0) THEN Write(Chr(7)) (* Nichts mehr zu l”schen *) ELSE BEGIN (* Buchstabe l”schen *) NrOfBytes := NrOfChars - CursorX; IF NrOfBytes > 0 THEN (* Text zu kopieren *) BEGIN Source := VideoPointer(TopEdge, LeftEdge + CursorX); Target := VideoPointer(TopEdge, LeftEdge + CursorX - 1); Move(Source^, Target^, NrOfBytes SHL 1); Move(TextString[CursorX + 1], TextString[CursorX], NrOfBytes); END; PutChar(LeftEdge + NrOfChars - 1, TopEdge, ' ', DetailPen, BlockPen); Dec(CursorX); (* Cursor setzen *) SetXY(GetX - 1, GetY); Dec(NrOfChars); END; END; CR : (* Carriage Return Taste *) BEGIN IF EndReturn IN EndKeys THEN (* Return = Ende *) BEGIN TextString[0] := Chr(NrOfChars); (* Textl„nge eintragen *) CursorLine; EndKeys := [EndReturn]; (* Mit Return beendet *) DoLoop := FALSE; END ELSE Write(Chr(7)); (* Taste unzul„ssig *) END; ESC : (* Escape Taste *) BEGIN IF EndEscape IN EndKeys THEN (* Escape = Ende *) BEGIN TextString[0] := Chr(NrOfChars); (* Textl„nge eintragen *) CursorLine; EndKeys := [EndEscape]; (* Mit Escape beendet *) DoLoop := FALSE; END ELSE Write(Chr(7)); (* Taste unzul„ssig *) END; TAB : (* Tabulator Taste *) BEGIN IF EndTabulator IN EndKeys THEN (* Tabulator = Ende *) BEGIN TextString[0] := Chr(NrOfChars); (* Textl„nge eintragen *) CursorLine; EndKeys := [EndTabulator]; (* Mit Tabulator beendet *) DoLoop := FALSE; END ELSE Write(Chr(7)); (* Taste unzul„ssig *) END; ELSE (* Keine besondere Taste *) IF DoInsert THEN (* Text einfgen *) BEGIN IF NrOfChars = Width THEN (* Einfgen nicht m”glich *) Write(Chr(7)) (* Piepston *) ELSE BEGIN (* Einfgen m”glich *) NrOfBytes := NrOfChars - CursorX; IF NrOfBytes > 0 THEN (* Text zu kopieren *) BEGIN Source := VideoPointer(TopEdge, LeftEdge + CursorX); Target := VideoPointer(TopEdge, LeftEdge + CursorX + 1); Move(Source^, Target^, NrOfBytes SHL 1); Move(TextString[CursorX + 1], TextString[CursorX + 2], NrOfBytes); END; PutChar(LeftEdge + CursorX, TopEdge, Character, DetailPen, BlockPen); TextString[CursorX + 1] := Character; IF CursorX < Width - 1 THEN (* Noch kein rechter Rand *) BEGIN Inc(CursorX); SetXY(GetX + 1, GetY); END; Inc(NrOfChars); END; END ELSE (* Text berschreiben *) BEGIN PutChar(LeftEdge + CursorX, TopEdge, Character, DetailPen, BlockPen); TextString[CursorX + 1] := Character; IF (Width > 1) AND (CursorX = Width - 2) AND (CursorX = NrOfChars - 1) THEN (* Leider ein Spezialfall *) BEGIN Inc(CursorX); SetXY(GetX + 1, GetY); END ELSE (* šbliche Behandlung *) BEGIN IF CursorX < Width - 1 THEN (* Noch kein rechter Rand *) BEGIN Inc(CursorX); SetXY(GetX + 1, GetY); END; IF NrOfChars < CursorX THEN (* Platz zum Schreiben *) Inc(NrOfChars) ELSE IF NrOfChars = CursorX THEN (* Alles beschrieben *) BEGIN IF (CursorX = Width - 1) AND (NrOfChars < Width) THEN Inc(NrOfChars); END; END; END; END; END; UNTIL NOT DoLoop; END; (* VideoRead *) (* Erkennt automatisch eine vorhandene Grafikkarte im Rechner *) PROCEDURE GetVideoMode(VAR VideoAdapter : VideoModes; VAR Color : BOOLEAN; VAR Lines, Columns : BYTE; VAR VideoAddress : WORD); TYPE pByte = ^BYTE; VAR Regs : REGISTERS; Adapter : BYTE; BEGIN Adapter := $FF; (* Noch kein Videoadapter *) Regs.AX := $1A00; (* Test auf VGA oder MCGA *) Intr($10, Regs); (* Video Interrupt *) IF Regs.AL = $1A THEN (* VGA oder MCGA *) BEGIN Adapter := Regs.BL; CASE Adapter OF (* Aktiver Modus der VGA *) 1 : VideoAdapter := MDA; 2 : VideoAdapter := CGA; 4 : VideoAdapter := EGA; 5 : VideoAdapter := mEGA; 7 : VideoAdapter := mVGA; 8 : VideoAdapter := VGA; 10 : VideoAdapter := MCGA; 11 : VideoAdapter := mMCGA; 12 : VideoAdapter := MCGA; END; Color := NOT ((VideoAdapter = MDA) OR (VideoAdapter = mEGA)); END ELSE (* Keine VGA oder MCGA *) BEGIN Regs.AH := $12; (* Test auf EGA *) Regs.BL := $10; Intr($10, Regs); (* Video Interrupt *) IF Regs.BL <> $10 THEN (* EGA Karte installiert *) BEGIN Adapter := (Regs.CL SHR 1) DIV 3; CASE Adapter OF (* Modus der EGA *) 0 : VideoAdapter := EGA; 1 : VideoAdapter := EGA; 2 : VideoAdapter := mEGA; END; Color := VideoAdapter <> mEGA; END; END; Regs.AH := $F; (* Aktueller Videomodus *) Intr($10, Regs); (* Video Interrupt *) IF Regs.AL = 7 THEN VideoAddress := $B000 (* Monochrom Modus *) ELSE VideoAddress := $B800; (* Color Modus *) IF Adapter = $FF THEN (* Keine VGA, EGA, MCGA *) BEGIN IF Regs.AL = 7 THEN VideoAdapter := MDA ELSE VideoAdapter := CGA; NrOfLines := 25; (* 25 Zeilen Modus *) Color := NOT ((Regs.AL = 0) OR (Regs.AL = 2) OR (Regs.AL = 7)); END ELSE NrOfLines := pBYTE(Ptr($40, $84))^ + 1; (* Anzahl der Zeilen *) NrOfColumns := pBYTE(Ptr($40, $4A))^; (* Anzahl der Spalten *) Regs.AH := $5; (* Bildschirmseite Null *) Regs.AL := $0; Intr($10, Regs); (* Video Interrupt *) END; (* GetVideoMode *) BEGIN (* Primitiv *) GetVideoMode(VideoMode, ColorGraphic, NrOfLines, NrOfColumns, VideoSegment); VideoOffset := $0000; (* Anfang des Video-Rams *) END. (* Primitiv *)
{ ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(ORMBr Framework.) @created(20 Jul 2016) @author(Isaque Pinheiro <isaquepsp@gmail.com>) @author(Skype : ispinheiro) ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi. } unit dbcbr.metadata.model; interface uses SysUtils, dbcbr.metadata.extract, dbcbr.metadata.register, dbcbr.database.mapping, dbcbr.mapping.classes, dbcbr.mapping.explorer, dbebr.factory.interfaces; type TModelMetadata = class(TModelMetadataAbstract) public procedure GetCatalogs; override; procedure GetSchemas; override; procedure GetTables; override; procedure GetColumns(ATable: TTableMIK; AClass: TClass); override; procedure GetPrimaryKey(ATable: TTableMIK; AClass: TClass); override; procedure GetIndexeKeys(ATable: TTableMIK; AClass: TClass); override; procedure GetForeignKeys(ATable: TTableMIK; AClass: TClass); override; procedure GetChecks(ATable: TTableMIK; AClass: TClass); override; procedure GetSequences; override; procedure GetProcedures; override; procedure GetFunctions; override; procedure GetViews; override; procedure GetTriggers; override; procedure GetModelMetadata; override; end; implementation { TModelMetadata } procedure TModelMetadata.GetModelMetadata; begin GetCatalogs; end; procedure TModelMetadata.GetCatalogs; begin FCatalogMetadata.Name := ''; GetSchemas; end; procedure TModelMetadata.GetSchemas; begin FCatalogMetadata.Schema := ''; GetSequences; GetTables; end; procedure TModelMetadata.GetTables; var LClass: TClass; LTable: TTableMIK; LTableMap: TTableMapping; begin for LClass in TMappingExplorer.GetRepositoryMapping.List.Entitys do begin LTableMap := TMappingExplorer.GetMappingTable(LClass); if LTableMap <> nil then begin LTable := TTableMIK.Create(FCatalogMetadata); LTable.Name := LTableMap.Name; LTable.Description := LTableMap.Description; /// <summary> /// Extrair colunas /// </summary> GetColumns(LTable, LClass); /// <summary> /// Extrair Primary Key /// </summary> GetPrimaryKey(LTable, LClass); /// <summary> /// Extrair Foreign Keys /// </summary> GetForeignKeys(LTable, LClass); /// <summary> /// Extrair Indexes /// </summary> GetIndexeKeys(LTable, LClass); /// <summary> /// Extrair Indexes /// </summary> GetChecks(LTable, LClass); /// <summary> /// Adiciona na lista de tabelas extraidas /// </summary> FCatalogMetadata.Tables.Add(UpperCase(LTable.Name), LTable); end; end; end; procedure TModelMetadata.GetChecks(ATable: TTableMIK; AClass: TClass); var LCheck: TCheckMIK; LCheckMapList: TCheckMappingList; LCheckMap: TCheckMapping; begin LCheckMapList := TMappingExplorer.GetMappingCheck(AClass); if LCheckMapList <> nil then begin for LCheckMap in LCheckMapList do begin LCheck := TCheckMIK.Create(ATable); LCheck.Name := LCheckMap.Name; LCheck.Condition := LCheckMap.Condition; LCheck.Description := ''; ATable.Checks.Add(UpperCase(LCheck.Name), LCheck); end; end; end; procedure TModelMetadata.GetColumns(ATable: TTableMIK; AClass: TClass); var LColumn: TColumnMIK; LColumnMap: TColumnMapping; LColumnMapList: TColumnMappingList; begin LColumnMapList := TMappingExplorer.GetMappingColumn(AClass); if LColumnMapList <> nil then begin for LColumnMap in LColumnMapList do begin if LColumnMap.IsJoinColumn then Continue; LColumn := TColumnMIK.Create(ATable); LColumn.Name := LColumnMap.ColumnName; LColumn.Description := LColumnMap.Description; LColumn.Position := LColumnMap.FieldIndex; LColumn.NotNull := LColumnMap.IsNotNull; LColumn.DefaultValue := LColumnMap.DefaultValue; LColumn.Size := LColumnMap.Size; LColumn.Precision := LColumnMap.Precision; LColumn.Scale := LColumnMap.Scale; LColumn.FieldType := LColumnMap.FieldType; /// <summary> /// Resolve Field Type /// </summary> GetFieldTypeDefinition(LColumn); try ATable.Fields.Add(FormatFloat('000000', LColumn.Position), LColumn); except on E: Exception do begin raise Exception.Create('ORMBr Erro in GetColumns() : ' + sLineBreak + 'Table : [' + ATable.Name + ']' + sLineBreak + 'Column : [' + LColumn.Name + ']' + sLineBreak + 'Message: [' + e.Message + ']'); end; end; end; end; end; procedure TModelMetadata.GetForeignKeys(ATable: TTableMIK; AClass: TClass); var LForeignKey: TForeignKeyMIK; LForeignKeyMapList: TForeignKeyMappingList; LForeignKeyMap: TForeignKeyMapping; procedure GetForeignKeyColumns(AForeignKey: TForeignKeyMIK); var LFromField: TColumnMIK; LToField: TColumnMIK; LFor: Integer; begin /// FromColumns for LFor := 0 to LForeignKeyMap.FromColumns.Count -1 do begin LFromField := TColumnMIK.Create(ATable); LFromField.Name := LForeignKeyMap.FromColumns[LFor]; LFromField.Description := LForeignKeyMap.Description; LFromField.Position := LFor; AForeignKey.FromFields.Add(FormatFloat('000000', LFromField.Position), LFromField); end; /// ToColumns for LFor := 0 to LForeignKeyMap.ToColumns.Count -1 do begin LToField := TColumnMIK.Create(ATable); LToField.Name := LForeignKeyMap.ToColumns[LFor]; LToField.Description := LForeignKeyMap.Description; LToField.Position := LFor; AForeignKey.ToFields.Add(FormatFloat('000000', LToField.Position), LToField); end; end; begin LForeignKeyMapList := TMappingExplorer.GetMappingForeignKey(AClass); if LForeignKeyMapList <> nil then begin for LForeignKeyMap in LForeignKeyMapList do begin LForeignKey := TForeignKeyMIK.Create(ATable); LForeignKey.Name := LForeignKeyMap.Name; LForeignKey.FromTable := LForeignKeyMap.TableNameRef; LForeignKey.OnUpdate := LForeignKeyMap.RuleUpdate; LForeignKey.OnDelete := LForeignKeyMap.RuleDelete; LForeignKey.Description := LForeignKeyMap.Description; ATable.ForeignKeys.Add(UpperCase(LForeignKey.Name), LForeignKey); /// <summary> /// Estrai as columnas da indexe key /// </summary> GetForeignKeyColumns(LForeignKey); end; end; end; procedure TModelMetadata.GetFunctions; begin end; procedure TModelMetadata.GetPrimaryKey(ATable: TTableMIK; AClass: TClass); var LPrimaryKeyMap: TPrimaryKeyMapping; procedure GetPrimaryKeyColumns(APrimaryKey: TPrimaryKeyMIK); var LColumn: TColumnMIK; LFor: Integer; begin for LFor := 0 to LPrimaryKeyMap.Columns.Count -1 do begin LColumn := TColumnMIK.Create(ATable); LColumn.Name := LPrimaryKeyMap.Columns[LFor]; LColumn.Description := LPrimaryKeyMap.Description; LColumn.SortingOrder := LPrimaryKeyMap.SortingOrder; LColumn.AutoIncrement := LPrimaryKeyMap.AutoIncrement; LColumn.Position := LFor; APrimaryKey.Fields.Add(FormatFloat('000000', LColumn.Position), LColumn); end; end; begin LPrimaryKeyMap := TMappingExplorer.GetMappingPrimaryKey(AClass); if LPrimaryKeyMap <> nil then begin ATable.PrimaryKey.Name := Format('PK_%s', [ATable.Name]); ATable.PrimaryKey.Description := LPrimaryKeyMap.Description; ATable.PrimaryKey.AutoIncrement := LPrimaryKeyMap.AutoIncrement; /// <summary> /// Estrai as columnas da primary key /// </summary> GetPrimaryKeyColumns(ATable.PrimaryKey); end; end; procedure TModelMetadata.GetProcedures; begin end; procedure TModelMetadata.GetSequences; var LClass: TClass; LSequence: TSequenceMIK; LSequenceMap: TSequenceMapping; begin for LClass in TMappingExplorer.GetRepositoryMapping.List.Entitys do begin LSequenceMap := TMappingExplorer.GetMappingSequence(LClass); if LSequenceMap <> nil then begin LSequence := TSequenceMIK.Create(FCatalogMetadata); LSequence.TableName := LSequenceMap.TableName; LSequence.Name := LSequenceMap.Name; LSequence.Description := LSequenceMap.Description; LSequence.InitialValue := LSequenceMap.Initial; LSequence.Increment := LSequenceMap.Increment; if FConnection.GetDriverName = dnMySQL then FCatalogMetadata.Sequences.Add(UpperCase(LSequence.TableName), LSequence) else FCatalogMetadata.Sequences.Add(UpperCase(LSequence.Name), LSequence); end; end; end; procedure TModelMetadata.GetTriggers; begin end; procedure TModelMetadata.GetIndexeKeys(ATable: TTableMIK; AClass: TClass); var LIndexeKey: TIndexeKeyMIK; LIndexeKeyMapList: TIndexeMappingList; LIndexeKeyMap: TIndexeMapping; procedure GetIndexeKeyColumns(AIndexeKey: TIndexeKeyMIK); var LColumn: TColumnMIK; LFor: Integer; begin for LFor := 0 to LIndexeKeyMap.Columns.Count -1 do begin LColumn := TColumnMIK.Create(ATable); LColumn.Name := LIndexeKeyMap.Columns[LFor]; LColumn.Description := LIndexeKeyMap.Description; LColumn.SortingOrder := LIndexeKeyMap.SortingOrder; LColumn.Position := LFor; AIndexeKey.Fields.Add(FormatFloat('000000', LColumn.Position), LColumn); end; end; begin LIndexeKeyMapList := TMappingExplorer.GetMappingIndexe(AClass); if LIndexeKeyMapList <> nil then begin for LIndexeKeyMap in LIndexeKeyMapList do begin LIndexeKey := TIndexeKeyMIK.Create(ATable); LIndexeKey.Name := LIndexeKeyMap.Name; LIndexeKey.Unique := LIndexeKeyMap.Unique; LIndexeKey.Description := ''; ATable.IndexeKeys.Add(UpperCase(LIndexeKey.Name), LIndexeKey); /// <summary> /// Estrai as columnas da indexe key /// </summary> GetIndexeKeyColumns(LIndexeKey); end; end; end; procedure TModelMetadata.GetViews; begin end; end.
unit uGrid; interface uses Windows, Classes, Messages, ShellAPI, Graphics, Dialogs, uType, uFiguraInterface; const GRID_WIDTH = 15; GRID_HEIGHT = 29; //25 + 4(space for create figura) DEFAULT_CELL = 20; DEFAULT_COLOR = clGreen; type TBaseGrid = class FCell : Byte; FWidth : Byte; FHeigth : Byte; FColor : TColor; Canvas : TCanvas; private procedure DrawRect(ARect: TPoint; AColor: TColor; CreateSpace: Integer = 4); public constructor Create(ACanvas: TCanvas; AColor: Tcolor; AWidth: Integer; AHeight: Integer); virtual; property Color : TColor read FColor write FColor; property Widht : Byte read FWidth write FWidth default GRID_WIDTH; property Height : Byte read FHeigth write FHeigth default GRID_HEIGHT; property Cell : Byte read FCell write FCell default DEFAULT_CELL; end; TIsLine = TArray<Boolean>; TGrid = class(TBaseGrid) private FGridLine : Boolean; procedure CreateGrid; public constructor Create(ACanvas: TCanvas; AColor: Tcolor; AWidth: Integer; AHeight: Integer); override; // procedure UpdateAndClear; procedure Draw(const ACell: Integer = DEFAULT_CELL); public property GridLine : Boolean read FGridLine write FGridLine; end; TGridFigura = class(TBaseGrid) private Grid : TGrid; OldFigura : TFiguraPos; procedure BuildFigura(APos: TFiguraPos; AColor: TColor = clBtnFace); public Figura : IFigura; function TryMoveLeft : Boolean; function TryMoveRight: Boolean; function TryMoveDown : Boolean; function TryRotate : Boolean; function Add : Boolean; procedure Draw; // constructor Create(ACanvas: TCanvas; AColor: TColor; AWidth: Integer; AHeight: Integer); override; end; TField = class const POINTS = 100; public Grid : TGrid; GridFigura : TGridFigura; constructor Create(ACanvas: TCanvas; AWidth: Integer = GRID_WIDTH; AHeight: Integer = GRID_HEIGHT); override; destructor Destroy; override; // procedure Update; procedure Clear; function Recalculate: Word; end; var FGrid : TArray<TIsLine>; implementation uses SysUtils; constructor TBaseGrid.Create(ACanvas: TCanvas; AColor: Tcolor; AWidth, AHeight: Integer); begin Canvas := ACanvas; FColor := AColor; FCell := DEFAULT_CELL; FHeigth := AHeight; FWidth := AWidth; end; procedure TBaseGrid.DrawRect(ARect: TPoint; AColor: TColor); begin ARect.Y := ARect.Y - 4; //!!! -4 - use for bult figura upper Canvas.Brush.Color := AColor; Canvas.Brush.Style := bsSolid; Canvas.Rectangle(FCell*ARect.X, FCell*ARect.Y, FCell*ARect.X-FCell, FCell*ARect.Y-FCell); end; { TGrid } constructor TGrid.Create(ACanvas: TCanvas; AColor: TColor; AWidth, AHeight: Integer); begin inherited Create(ACanvas, AColor, AWidth, AHeight); FGridLine := True; CreateGrid; end; procedure TGrid.UpdateAndClear; begin with Canvas do begin Brush.Color := clBtnFace; Brush.Style := bsSolid; FillRect(Rect(0,0,1000,1000)); end; end; function TGridFigura.TryMoveDown: Boolean; var Pos : TFiguraPos; begin Result := False; If (Figura.GetDownPoint.Y >= Grid.Height) Then Exit; Pos := FIgura.GetPos; If Pos[1].Y > 0 Then if (FGrid[Pos[1].Y, Pos[1].X]) or (FGrid[Pos[2].Y, Pos[2].X]) or (FGrid[Pos[3].Y, Pos[3].X]) or (FGrid[Pos[4].Y, Pos[4].X]) then Exit; Result := True; end; function TGridFigura.TryMoveLeft: Boolean; var Pos : TFiguraPos; begin Result := False; If (Figura.GetLeftPoint.X <= 1) Then Exit; Pos := FIgura.GetPos; If Pos[1].Y > 0 Then if (FGrid[Pos[1].Y-1, Pos[1].X-1]) or (FGrid[Pos[2].Y-1, Pos[2].X-1]) or (FGrid[Pos[3].Y-1, Pos[3].X-1]) or (FGrid[Pos[4].Y-1, Pos[4].X-1]) then Exit; Result := True; end; function TGridFigura.TryMoveRight: Boolean; var Pos: TFiguraPos; begin Result := False; If (Figura.GetRightPoint.X = Grid.Widht) Then Exit; Pos := FIgura.GetPos; If Pos[1].Y > 0 Then if (FGrid[Pos[1].Y-1, Pos[1].X+1]) or (FGrid[Pos[2].Y-1, Pos[2].X+1]) or (FGrid[Pos[3].Y-1, Pos[3].X+1]) or (FGrid[Pos[4].Y-1, Pos[4].X+1]) then Exit; Result := True; end; function TGridFigura.TryRotate: Boolean; begin Result := True; end; function TGridFigura.Add: Boolean; procedure Add(APoint: TPoint); begin If (APoint.X > 0) and (APoint.Y > 0) Then FGrid[APoint.Y-1, APoint.X] := True; end; var pos : TFiguraPos; begin Result := True; // clear old figura - becouse figura disappear after add to grid FillChar(OldFigura, 4*SizeOf(TPoint),0); //Add figura fo grid pos := Figura.GetPos; add(pos[1]); add(pos[2]); add(pos[3]); add(pos[4]); // Check the End game If (pos[1].Y < 4) Then Exit(False); end; procedure TGridFigura.BuildFigura(APos: TFiguraPos; AColor: TColor); var I: Integer; begin For I := Low(APos) To High(APos) Do DrawRect(APos[i], AColor); end; constructor TGridFigura.Create(ACanvas: TCanvas; AColor: TColor; AWidth, AHeight: Integer); begin inherited Create(ACanvas, AColor, AWidth, AHeight); end; procedure TGridFigura.Draw; begin BuildFigura(OldFigura); if Assigned(FIgura) then begin OldFigura := FIgura.GetPos; BuildFigura(FIgura.GetPos, Color); end; end; constructor TField.Create(ACanvas: TCanvas; AWidth, AHeight: Integer); begin Grid := TGrid.Create(ACanvas, clGreen, AWidth, AHeight); GridFigura := TGridFigura.Create(ACanvas, clBlack, AWidth, AHeight); GridFigura.Grid := Grid; end; destructor TField.Destroy; begin Grid.Free; GridFigura.Free; inherited; end; function TField.Recalculate: Word; function isLine(ALine: TIsLine): Boolean; var i: Integer; begin Result:= True; For i := 1 to High(ALine) Do If ALine[i] = False Then Exit(False); end; procedure DropLine(Index: Integer); var k : TIsLine; begin // move line While Index > 0 Do begin k := FGrid[Index-1]; FGrid[Index] := k; Dec(Index); end; end; var FromLine, i : Integer; begin FromLine := GridFigura.Figura.GetDownPoint.Y; Result := 0; i := 1; While i < 5 Do begin If (FromLine >= i) and (isLine(FGrid[FromLine - i])) Then begin DropLine( FromLine - i ); Result := Result + POINTS; Update; end else inc(i); end; end; procedure TField.Update; var i, j : integer; begin with Grid.Canvas do begin if Grid.GridLine then Pen.Color := Grid.Color else Pen.Color := clBtnFace; Brush.Style := bsSolid; for i := 0 to Grid.Height -1 do for j := 0 to Grid.Widht +1 do begin if j = Grid.Widht+1 then Continue; If FGrid[i][j] = True Then Grid.DrawRect(Point(j, i+1), GridFigura.Color) else Grid.DrawRect(Point(j, i+1), clBtnFace); end; end; end; procedure TGrid.CreateGrid; var i: Integer; begin SetLength(FGrid, FHeigth); For I := 0 To FHeigth - 1 Do SetLength(FGrid[i], FWidth+1); end; procedure TField.Clear; begin // FillChar(Grid, SizeOf(Grid), #0); ZeroMemory(@FGrid[Low(FGrid)], Length(FGrid) * SizeOf(FGrid[Low(FGrid)])); Grid.CreateGrid; Update; end; procedure TGrid.Draw(const ACell: Integer); var i, j : integer; begin with Canvas do begin Brush.Color := clBtnFace; Brush.Style := bsClear; Pen.Color := FColor; for j := 0 to FWidth - 1 do for i := 0 to FHeigth - 5 do //!!! -5 - use for bult figura upper Rectangle(j * FCell, i * FCell, FCell + j * FCell, FCell + i * FCell); end; end; end.
{ Output meshes used in selected references, for example to build a list of meshes from a cell } unit UserScript; const sRefSignatures = 'REFR,ACHR,PGRE,PMIS,PHZD,PARW,PBAR,PBEA,PCON,PFLA'; var slModels: TStringList; function Initialize: integer; begin // list of models, ignore duplicated ones slModels := TStringList.Create; slModels.Sorted := True; slModels.Duplicates := dupIgnore; end; function Process(e: IInterface): integer; var s: string; r: IInterface; begin if Pos(Signature(e), sRefSignatures) = 0 then Exit; r := BaseRecord(e); if not Assigned(r) then Exit; r := WinningOverride(r); if Signature(r) = 'ARMO' then s := GetElementEditValues(r, 'Male world model\MOD2') else s := GetElementEditValues(r, 'Model\MODL'); if s <> '' then slModels.Add(LowerCase(s)) end; function Finalize: integer; begin AddMessage(slModels.Text); slModels.Free; end; end.
unit BaseTimingTest; {$mode objfpc}{$H+} {$CODEALIGN LOCALMIN=16} {$CODEALIGN CONSTMIN=16} interface uses Classes, SysUtils, fpcunit, testregistry, BaseTestCase, native, BZVectorMath; {$I config.inc} type { TGroupTimingTest } TGroupTimingTest = class(TVectorBaseTestCase) public class var Group: TReportGroup; class function RGString: string; end; { TVectorBaseTimingTest } TVectorBaseTimingTest = class(TGroupTimingTest) protected procedure TearDown; override; public TestDispName: string; procedure StartTimer; procedure StopTimer; procedure InitLists; end; procedure DoInitLists; const asmUnitVector : TBZVector4f = (X:1; Y:1; Z:1; W:1); natUnitVector : TNativeBZVector4f = (X:1; Y:1; Z:1; W:1); asmTwoVector : TBZVector4f = (X:2; Y:2; Z:2; W:2); natTwoVector : TNativeBZVector4f = (X:2; Y:2; Z:2; W:2); asmHalfVector : TBZVector4f = (X:0.5; Y:0.5; Z:0.5; W:0.5); natHalfVector : TNativeBZVector4f = (X:0.5; Y:0.5; Z:0.5; W:0.5); Iterations : integer = 20000000; IterationsQuarter = 5000000; IterationsTenth = 2000000; var StartTime, TotalTime, elapsedTime : double; etGain, etNativeMin, etAsmMin, etNativeMax, etAsmMax, etNativeAvg, etAsmAvg, etNative , etAsm : double; cnt: Integer; sl,ml,hl, fhl: TStringList; HeaderPos: integer; implementation uses strutils, BZProfiler, BZSystem; procedure DoInitLists; var infoStr, featuresStr: string; begin infoStr := Format('CPU Info: %s @ %d MHz', [Trim(BZCPUInfos.BrandName), BZCPUInfos.Speed]); featuresStr := 'CPU Features: ' + BZCPUInfos.FeaturesAsString; sl := TStringList.Create; sl.Add(infoStr); sl.Add(featuresStr); sl.Add('Compiler Flags: ' + REP_FLAGS); sl.Add('Test,Native,Assembler,Gain in %,Speed factor'); ml := TStringList.Create; ml.Add('| Compiler Flags | ' + REP_FLAGS + ' |'+#10); ml.Add('| -------------- | -------- |'+#10); ml.Add(''); ml.Add('| Test | Total Ticks | Min Ticks | Max Ticks | Avg Ticks | Gain in % | Speed factor |'+#10); ml.Add('| ------------------------ | ----------- | --------- | --------- | --------- | --------- | ------------ |'+#10); hl := TStringList.Create; with hl do begin Add('<html>'); Add('<head>'); Add('<meta charset="utf-8">'); Add('<title>FPC SSE/AVX Tests Case Result</title>'); //Add('<link href="minimal-table.css" rel="stylesheet" type="text/css">'); Add('<style>'); Add('html {font-family: sans-serif;}'); Add('table {border-collapse: collapse;border: 2px solid rgb(200,200,200);letter-spacing: 1px;font-size: 0.8rem;}'); Add('td, th {border: 1px solid rgb(60,60,60);padding: 10px 20px;}'); Add('th {background-color: rgb(205,205,205);}'); Add('th.maincol {background-color: rgb(195,195,195);}'); Add('td {text-align: center;}'); Add('tr:nth-child(odd) td {background-color: rgb(245,245,245);}'); Add('tr:nth-child(even) td {background-color: rgb(225,225,225);}'); Add('caption {padding: 10px;}'); Add('h1 {text-align: center;}'); Add('h5 {text-align: center;}'); Add('</style>'); Add('</head>'); Add('<div>'); HeaderPos := Add(''); Add('<h5>' + infoStr + '</h5>'); Add('<h5>' + featuresStr + '</h5>'); Add('<table>'); Add('<caption><b>Compiler Flags: ' + REP_FLAGS + '</b></caption>'); Add('<thead>'); Add('<tr>'); Add(' <th scope="col">Test Name</th>'); Add(' <td colspan="1"></td>'); Add(' <th scope="col">Total Time</th>'); Add(' <th scope="col">Min Time</th>'); Add(' <th scope="col">Max Time</th>'); Add(' <th scope="col">Average Time</th>'); Add(' <th scope="col">Gain in %</th>'); Add(' <th scope="col">Speed Factor</th>'); Add('</tr>'); Add('<tbody>'); end; //Add('<tr><td>Test</td><td>Total Ticks</td><td>Min Ticks</td><td>Max Ticks</td><td>Avg Ticks</td><td>Gain in %</td><td>Speed factor</td></tr>'); fhl := TStringList.Create; fhl.Add('[table]'); fhl.Add('[tr][td] | '+padright('Test',22)+'[/td][td] | '+padright('Total Ticks',16)+'[/td][td] | '+padright('Min Ticks',18)+'[/td][td] | '+padright('Max Ticks',18)+'[/td][td] | '+padright('Avg Ticks',18)+'[/td][td] | '+padright('Gain in %',17)+'[/td][td] | '+padright('Speed factor',14)+'[/td][/tr]'); end; procedure CheckResultsDir; var rg: TReportGroup; begin If Not DirectoryExists('Results') then CreateDir ('Results'); for rg := low(TReportGroup) to High(TReportGroup) do If Not DirectoryExists('Results' + DirectorySeparator + rgArray[rg]) then CreateDir ('Results' + DirectorySeparator + rgArray[rg]); end; function WriteTimer:String; begin Result := FloatToStr(elapsedTime)+' seconds'; TotalTime := TotalTime + elapsedTime; End; function WriteTime(et:double):String; begin Result := FloatToStrF(et,ffFixed,5,6); TotalTime := TotalTime + et; End; function WritePct(et:double):String; begin Result := FloatToStrF(et,ffFixed,5,3)+' %'; End; function WriteTestName(aTest : String):String; begin result := padRight(aTest,26-Length(aTest)); end; function WriteSpeedFactor: string; var sf : double; begin // sf := etNative/etAsm; sf := GlobalProfiler.Items[0].TotalTicks/GlobalProfiler.Items[1].TotalTicks; result := FloatToStrF(sf,ffFixed,5,6); end; {%region%====[ TGroupTimingTest ]=====================================} class function TGroupTimingTest.RGString: string; begin Result := rgArray[Group]; end; {%region%} {%region%====[ TVectorBaseTimingTest etc ]=====================================} procedure TVectorBaseTimingTest.StartTimer; begin StartTime := 0; StartTime := now; End; procedure TVectorBaseTimingTest.StopTimer; begin elapsedTime := 0; elapsedTime :=(Now() - StartTime) *24 * 60 * 60; End; procedure TVectorBaseTimingTest.InitLists; begin DoInitLists; end; procedure TVectorBaseTimingTest.TearDown; begin //etGain := 100-((100*etAsm)/etNative); etGain := 100 - ((100*GlobalProfiler.Items[1].TotalTicks)/GlobalProfiler.Items[0].TotalTicks); inherited TearDown; Sl.Add(WriteTestName(TestDispName) + ', ' + WriteTime(etNative) + ', ' + WriteTime(etAsm)+', '+WritePct(etGain)+', '+WriteSpeedFactor); ml.Add( '| ' + WriteTestName(TestDispName) + ' | ' + WriteTime(etNative) + ' | ' + WriteTime(etAsm) + ' | ' + WritePct(etGain) + ' | '+ WriteSpeedFactor+#10); //hl.Add('<tr><td>' + WriteTestName(TestDispName) + '</td><td>' + WriteTime(etNative) + '</td><td>' + WriteTime(etAsm) + '</td><td>' + WritePct(etGain) + '</td><td>' + WriteSpeedFactor + '</td></tr>'); with hl do begin Add('<tr>'); Add('<th class="maincol" rowspan="2" scope="rowgroup">'+WriteTestName(TestDispName)+'</th>'); Add(' <th scope="row">Native</th>'); Add(' <td>' + GlobalProfiler.Items[0].TotalTicksAsString + '</td>'); Add(' <td>' + GlobalProfiler.Items[0].MinTicksAsString + '</td>'); Add(' <td>' + GlobalProfiler.Items[0].MaxTicksAsString + '</td>'); Add(' <td>' + floattostrF( GlobalProfiler.Items[0].TotalTicks/Iterations,ffGeneral,15,3)+ '</td>'); //GlobalProfiler.Items[0].AvgTicksAsString + '</td>'); Add('</tr>'); Add('<tr>'); Add(' <th scope="row">Assembler</th>'); Add(' <td>' + GlobalProfiler.Items[1].TotalTicksAsString + '</td>'); Add(' <td>' + GlobalProfiler.Items[1].MinTicksAsString + '</td>'); Add(' <td>' + GlobalProfiler.Items[1].MaxTicksAsString + '</td>'); // Add(' <td>' + GlobalProfiler.Items[1].AvgTicksAsString + '</td>'); Add(' <td>' + floattostrF( GlobalProfiler.Items[1].TotalTicks/Iterations,ffGeneral,15,3)+ ' ms</td>'); Add(' <td>' + WritePct(etGain) + '</td><td>' + WriteSpeedFactor + '</td>'); Add('</tr>'); end; (* hl.Add('<tr><td> | ' + WriteTestName(TestDispName) + '</td><td></td><td></td><td></td><td></td><td></td></tr>'); hl.add('<tr><td> | Native </td><td> | ' + GlobalProfiler.Items[0].TotalTicksAsString + '</td>'+ '<td> | ' + GlobalProfiler.Items[0].MinTicksAsString + '</td>'+ '<td> | ' + GlobalProfiler.Items[0].MaxTicksAsString + '</td>'+ '<td> | ' + GlobalProfiler.Items[0].AvgTicksAsString + '</td>'+ '<td> | </td><td> | </td></tr>'); hl.add('<tr><td> | Assembler</td><td> | ' + GlobalProfiler.Items[1].TotalTicksAsString + '</td>'+ '<td> | ' + GlobalProfiler.Items[1].MinTicksAsString + '</td>'+ '<td> | ' + GlobalProfiler.Items[1].MaxTicksAsString + '</td>'+ '<td> | ' + GlobalProfiler.Items[1].AvgTicksAsString + '</td>'+ '<td> | ' + WritePct(etGain) + '</td><td> | ' + WriteSpeedFactor + '</td></tr>'); *) fhl.Add('[tr][td] | ' + WriteTestName(TestDispName) + '[/td][td][/td][td][/td][td][/td][td][/td][td][/td][/tr]'); fhl.add('[tr][td] | Native[/td][td] | ' + GlobalProfiler.Items[0].TotalTicksAsString + '[/td]'+ '[td] | ' + GlobalProfiler.Items[0].MinTicksAsString + '[/td]'+ '[td] | ' + GlobalProfiler.Items[0].MaxTicksAsString + '[/td]'+ '[td] | ' + GlobalProfiler.Items[0].AvgTicksAsString + '[/td]'+ '[td] | [/td][td] | [/td][/tr]'); fhl.add('[tr][td] | Assembler[/td][td] | ' + GlobalProfiler.Items[1].TotalTicksAsString + '[/td]'+ '[td] | ' + GlobalProfiler.Items[1].MinTicksAsString + '[/td]'+ '[td] | ' + GlobalProfiler.Items[1].MaxTicksAsString + '[/td]'+ '[td] | ' + GlobalProfiler.Items[1].AvgTicksAsString + '[/td]'+ '[td] | ' + WritePct(etGain) + '[/td][td] | ' + WriteSpeedFactor + '[/td][/tr]'); end; {%endregion%} initialization DoInitLists; CheckResultsDir; Finalization sl.Free; hl.Free; ml.Free; fhl.Free; end. end.
unit Work.Table.Tasks; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, System.Generics.Collections, Vcl.Grids, HGM.Controls.VirtualTable, SQLLang, SQLiteTable3, Work.DB; type TTableTasks = class; TTaskState = (tsDraft, tsInTheWork, tsWaitReport, tsDone); TTaskPriority = (tpLow, tpLowNormal, tpNormal, tpNormalHigh, tpHigh); TTaskStates = set of TTaskState; TTaskStateHelper = record helper for TTaskState function ToString:string; end; TTaskPriorityHelper = record helper for TTaskPriority function ToString:string; end; TItemTask = class private FModifed:Boolean; FOwner:TTableTasks; FEmpty:Boolean; function CreateTaskWorkDir(Path:string):string; public ID:Integer; Name:string; Customer:Integer; Priority:TTaskPriority; Date:TDateTime; Data:string; DateCreate:TDateTime; State:TTaskState; JiraLink:string; WorkPath:string; CustomerStr:string; property Modifed:Boolean read FModifed write FModifed; property Empty:Boolean read FEmpty write FEmpty; function CreateWorkDir(Path, WorkDirName:string):Boolean; procedure Update; procedure GetBack; constructor Create(AOwner:TTableTasks); end; TTableTasks = class(TTableData<TItemTask>) const TableName = 'Tasks'; const fnID = 'tkID'; const fnName = 'tkName'; const fnCustomer = 'tkCustomer'; const fnPriority = 'tkPriority'; const fnDate = 'tkDate'; const fnData = 'tkData'; const fnState = 'tkState'; const fnDateCreate = 'tkDateCreate'; const fnJiraLink = 'tkJiraLink'; const fnWorkPath = 'tkWorkPath'; private FDB:TDatabaseCore; FFilter:TTaskStates; FUseFilter:Boolean; FOrderBy: string; FOrderByDESC:Boolean; public procedure Load(CustomerID:Integer = -1); procedure Save; procedure GetBack(Index:Integer); overload; procedure GetBack(Item:TItemTask); overload; procedure Update(Index:Integer); overload; procedure Update(Item:TItemTask); overload; procedure Delete(Item:TItemTask); overload; procedure Delete(Index:Integer); overload; procedure Clear; override; property Filter:TTaskStates read FFilter write FFilter; property UseFilter:Boolean read FUseFilter write FUseFilter; property LoadTaskBy:string read FOrderBy write FOrderBy; property LoadTaskByDESC:Boolean read FOrderByDESC write FOrderByDESC; constructor Create(ADB:TDatabaseCore); overload; property DatabaseCore:TDatabaseCore read FDB write FDB; end; const HG_ActualBat = 'actual_hg.bat'; HG_Projects = 'projects.txt'; implementation uses Work.Table.Customers; { TTableTasks } procedure TTableTasks.Clear; var i:Integer; begin for i:= 0 to Count-1 do Items[i].Free; inherited; end; constructor TTableTasks.Create(ADB:TDatabaseCore); begin inherited Create; FOrderBy:=fnName; FOrderByDESC:=False; FDB:=ADB; if not FDB.SQL.TableExists(TableName) then with SQL.CreateTable(TableName) do begin AddField(fnID, ftInteger, True, True); AddField(fnName, ftString); AddField(fnCustomer, ftInteger); AddField(fnPriority, ftInteger); AddField(fnDate, ftDateTime); AddField(fnData, ftString); AddField(fnState, ftInteger); AddField(fnDateCreate, ftDateTime); AddField(fnJiraLink, ftString); AddField(fnWorkPath, ftString); FDB.SQL.ExecSQL(GetSQL); EndCreate; end; end; procedure TTableTasks.Delete(Item: TItemTask); begin with SQL.Delete(TableName) do begin WhereFieldEqual(fnID, Item.ID); FDB.SQL.ExecSQL(GetSQL); EndCreate; end; end; procedure TTableTasks.Delete(Index: Integer); begin Delete(Items[Index]); inherited; end; procedure TTableTasks.GetBack(Item: TItemTask); var RTable:TSQLiteTable; begin with SQL.Select(TableName) do begin AddField(fnName); AddField(fnCustomer); AddField(fnPriority); AddField(fnDate); AddField(fnData); AddField(fnState); AddField(fnDateCreate); AddField(fnJiraLink); AddField(fnWorkPath); WhereFieldEqual(fnID, Item.ID); RTable:=FDB.SQL.GetTable(GetSQL); if RTable.Count > 0 then begin Item.Name:=RTable.FieldAsString(0); Item.Customer:=RTable.FieldAsInteger(1); Item.Priority:=TTaskPriority(RTable.FieldAsInteger(2)); Item.Date:=RTable.FieldAsDateTime(3); Item.Data:=RTable.FieldAsString(4); Item.State:=TTaskState(RTable.FieldAsInteger(5)); Item.DateCreate:=RTable.FieldAsDateTime(6); Item.JiraLink:=RTable.FieldAsString(7); Item.WorkPath:=RTable.FieldAsString(8); Item.Modifed:=False; Item.Empty:=False; end; RTable.Free; EndCreate; end; end; function SetOfTaskStatesToStrArray(Value:TTaskStates):TArray<string>; var State:TTaskState; begin for State in Value do begin if State in Value then begin SetLength(Result, Length(Result)+1); Result[Length(Result)-1]:=IntToStr(Ord(State)); end; end; end; procedure TTableTasks.Load; var RTable, CTable:TSQLiteTable; Item:TItemTask; begin BeginUpdate; Clear; try with SQL.Select(TableName) do begin AddField(fnName); AddField(fnCustomer); AddField(fnPriority); AddField(fnDate); AddField(fnData); AddField(fnState); AddField(fnDateCreate); AddField(fnID); AddField(fnJiraLink); AddField(fnWorkPath); if UseFilter then WhereFieldIN(fnState, SetOfTaskStatesToStrArray(FFilter)); if CustomerID >= 0 then WhereFieldEqual(fnCustomer, CustomerID); OrderBy(FOrderBy, FOrderByDESC); RTable:=FDB.SQL.GetTable(GetSQL); while not RTable.EOF do begin Item:=TItemTask.Create(Self); Item.Name:=RTable.FieldAsString(0); Item.Customer:=RTable.FieldAsInteger(1); Item.Priority:=TTaskPriority(RTable.FieldAsInteger(2)); Item.Date:=RTable.FieldAsDateTime(3); Item.Data:=RTable.FieldAsString(4); Item.State:=TTaskState(RTable.FieldAsInteger(5)); Item.DateCreate:=RTable.FieldAsDateTime(6); Item.ID:=RTable.FieldAsInteger(7); Item.JiraLink:=RTable.FieldAsString(8); Item.WorkPath:=RTable.FieldAsString(9); Item.CustomerStr:=''; with SQL.Select(TTableCustomers.TableName) do begin AddField(TTableCustomers.fnF); AddField(TTableCustomers.fnI); AddField(TTableCustomers.fnO); WhereFieldEqual(TTableCustomers.fnID, Item.Customer); try CTable:=FDB.SQL.GetTable(GetSQL); if CTable.Count > 0 then begin Item.CustomerStr:=CreateFIO(CTable.FieldAsString(0), CTable.FieldAsString(1), CTable.FieldAsString(2)); end else Item.CustomerStr:=''; finally if Assigned(CTable) then CTable.Free; end; EndCreate; end; Item.Modifed:=False; Item.Empty:=False; Add(Item); RTable.Next; end; RTable.Free; EndCreate; end; finally EndUpdate; end; end; procedure TTableTasks.GetBack(Index: Integer); begin GetBack(Items[Index]); end; procedure TTableTasks.Save; var i:Integer; begin for i:= 0 to Count-1 do if Items[i].Modifed then Update(i); end; procedure TTableTasks.Update(Item: TItemTask); var Res:Integer; begin with SQL.Select(TableName) do begin AddField(fnID); WhereFieldEqual(fnID, Item.ID); Res:=FDB.SQL.GetTableValue(GetSQL); EndCreate; end; if Res < 0 then begin with SQL.InsertInto(TableName) do begin AddValue(fnName, Item.Name); AddValue(fnCustomer, Item.Customer); AddValue(fnPriority, Ord(Item.Priority)); AddValue(fnDate, Item.Date); AddValueAsParam(fnData, '?', True); AddValue(fnState, Ord(Item.State)); AddValue(fnDateCreate, Now); AddValue(fnJiraLink, Item.JiraLink); AddValue(fnWorkPath, Item.WorkPath); FDB.SQL.ExecSQL(GetSQL, [PAnsiChar(AnsiString(Item.Data))]); Item.ID:=FDB.SQL.GetLastInsertRowID; EndCreate; end; end else begin with SQL.Update(TableName) do begin AddValue(fnName, Item.Name); AddValue(fnCustomer, Item.Customer); AddValue(fnPriority, Ord(Item.Priority)); AddValue(fnDate, Item.Date); AddValueAsParam(fnData, '?', True); AddValue(fnState, Ord(Item.State)); AddValue(fnJiraLink, Item.JiraLink); AddValue(fnWorkPath, Item.WorkPath); WhereFieldEqual(fnID, Item.ID); FDB.SQL.ExecSQL(GetSQL, [PAnsiChar(AnsiString(Item.Data))]); EndCreate; end; end; Item.Modifed:=False; Item.Empty:=False; end; procedure TTableTasks.Update(Index: Integer); begin Update(Items[Index]); end; { TItemTask } function TItemTask.CreateTaskWorkDir(Path:string): string; var PName:string; i: Integer; begin Result:=''; if JiraLink <> '' then begin PName:=JiraLink; if PName[Length(PName)] = '/' then Delete(PName, Length(PName), 1); for i:= Length(PName) downto 1 do if PName[i] = '/' then begin PName:=Copy(PName, i, 255); Break; end; if PName = '' then PName:=Name; end else PName:=Name; if CreateDir(Path+PName) then Result:=Path+PName+'\'; end; constructor TItemTask.Create(AOwner:TTableTasks); begin inherited Create; FModifed:=True; FEmpty:=True; FOwner:=AOwner; end; function TItemTask.CreateWorkDir(Path, WorkDirName:string): Boolean; begin Result:=False; WorkPath:=CreateTaskWorkDir(Path); if DirectoryExists(WorkPath) then begin Result:=CreateDir(WorkPath+'\'+WorkDirName); CopyFile(PChar(Path+HG_ActualBat), PChar(WorkPath+HG_ActualBat), False); CopyFile(PChar(Path+HG_Projects), PChar(WorkPath+HG_Projects), False); end; end; procedure TItemTask.GetBack; begin FOwner.GetBack(Self); end; procedure TItemTask.Update; begin FOwner.Update(Self); end; { TTaskStateHelper } function TTaskStateHelper.ToString: string; begin case Self of tsDraft:Exit('Черновик'); tsInTheWork:Exit('В работе'); tsWaitReport:Exit('Отчёт'); tsDone:Exit('Готово'); end; end; { TTaskPriorityHelper } function TTaskPriorityHelper.ToString: string; begin case Self of tpLow:Exit('Низший'); tpLowNormal:Exit('Низкий'); tpNormal:Exit('Средний'); tpNormalHigh:Exit('Высокий'); tpHigh:Exit('Высший'); end; end; end.