text
stringlengths
14
6.51M
unit ExcelImportUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Grids, ExtCtrls, StdCtrls,SharedTypes,comobj, Spin; const atXLS=0; atCSV=1; type TExcelImportForm = class(TForm) FieldsGrid: TStringGrid; StringGrid1: TStringGrid; Splitter1: TSplitter; Panel1: TPanel; Button1: TButton; Button2: TButton; Edit1: TEdit; Label1: TLabel; OpenDialog1: TOpenDialog; SpinEdit1: TSpinEdit; Label2: TLabel; Button3: TButton; Label3: TLabel; procedure FieldsGridDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); procedure Button1Click(Sender: TObject); procedure FormShow(Sender: TObject); procedure Button2Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure FieldsGridKeyPress(Sender: TObject; var Key: Char); private { Private declarations } public { Public declarations } end; TExcel=class(TObject) accestype:byte; filename:string; csvcells:array of array of string; excel:variant; rowcount:integer; procedure open; procedure close; function getcell(r,c:integer):string; function getcellvalue(r,c:integer):string; end; var ExcelImportForm: TExcelImportForm; implementation uses studentunit, mainunit; {$R *.dfm} function parsedate(sd:string):string; const months:array[1..12] of string=('января','февраля','марта','апреля','мая','июня','июля','августа','сентября','октября','ноября','декабря'); delims:array[1..5] of string=(' ',':','-','.','/'); var sdt,d,m,y,yt,delim:string; n,i,nd,nm,ny:integer; begin n:=1; repeat sdt:=sd; delim:=delims[n]; d:=trim(copy(sdt,1,pos(delim,sdt)-1)); delete(sdt,1,pos(delim,sdt)); m:=trim(copy(sdt,1,pos(delim,sdt)-1)); delete(sdt,1,pos(delim,sdt)); y:=trim(sdt); nd:=-1; ny:=-1; nm:=-1; try nm:=-1; for i:=1 to 12 do begin if months[i]=ansilowercase(m) then nm:=i; end; if nm=-1 then nm:=strtoint(m); nd:=strtoint(d); yt:=''; for i:=1 to length(y) do if (y[i]>='0') and (y[i]<='9') then yt:=yt+y[i]; ny:=strtoint(yt); except end; inc(n); until (n>5) or ((nd<>-1) and (nm<>-1) and (ny<>-1)); if ny<100 then begin if ny<50 then ny:=ny+2000 else ny:=ny+1900; end; if nd=-1 then nd:=1; if nm=-1 then nm:=1; if ny=-1 then ny:=1; result:=format('%.2d-%.2d-%.4d',[nd,nm,ny]); end; function TExcel.getcell(r,c:integer):string; var i,cc:integer; begin cc:=c-1; result:=''; repeat result:=result+chr(cc mod 26+65); cc:=cc div 26; until cc=0; result:=result+inttostr(r); end; function TExcel.getcellvalue(r,c:integer):string; begin if self.accestype=atXLS then begin result:=Excel.Range[getcell(r,c)]; end else begin result:=''; if (r>=1) and (r<=high(self.csvcells)+1) and (c>=1) and (c<=high(self.csvcells[r-1])+1) then begin result:=self.csvcells[r-1][c-1]; end; end; end; procedure TExcel.open; var f:textfile; s:string; p:integer; begin try self.close; except end; self.accestype:=atXLS; try excel:=CreateOleObject('Excel.Application'); excel.workbooks.open(self.filename, 0, True); excel.visible:=false; except self.accestype:=atCSV; setlength(self.csvcells,0); assign(f,self.filename); reset(f); while not eof(f) do begin setlength(self.csvcells,length(self.csvcells)+1); readln(f,s); repeat setlength(self.csvcells[high(self.csvcells)],length(self.csvcells[high(self.csvcells)])+1); p:=pos(';',s); if p<=0 then self.csvcells[high(self.csvcells)][high(self.csvcells[high(self.csvcells)])]:=s else begin self.csvcells[high(self.csvcells)][high(self.csvcells[high(self.csvcells)])]:=copy(s,1,p-1); delete(s,1,p); end; until p<=0; end; closefile(F); end; end; procedure TExcel.close; begin if self.accestype=atXLS then begin Excel.DisplayAlerts:=False; Excel.ActiveWorkbook.Close; // Excel.Application.Disconnect; Excel.Application.Quit; Excel:=unassigned; end; if self.accestype=atCSV then begin end; end; procedure TExcelImportForm.FieldsGridDrawCell(Sender: TObject; ACol, ARow: Integer; Rect: TRect; State: TGridDrawState); begin StudentsForm.KursGridDrawCell(sender,acol,arow,rect,state); end; procedure TExcelImportForm.Button1Click(Sender: TObject); begin if self.OpenDialog1.Execute then self.Edit1.Text:=self.OpenDialog1.FileName; end; procedure TExcelImportForm.FormShow(Sender: TObject); var st,tst:tsettings; n,i:integer; begin st:=tsettings.create; st.LoadFromFile(extractfilepath(application.ExeName)+'import.ini','main'); tst:=tsettings.Create; tst.LoadFromFile(mainform.MainSettings.Settings.Values[templatepath]+'\'+mainform.FileSettings.Settings.Values['templ']+'.dtmpl','student'); try n:=strtoint(tst.Settings.Values['DiscCount']); except n:=0; end; self.FieldsGrid.RowCount:=st.Settings.Count+n; self.StringGrid1.RowCount:=self.FieldsGrid.RowCount; self.FieldsGrid.ColWidths[0]:=250; self.StringGrid1.ColWidths[0]:=250; self.StringGrid1.ColCount:=2; self.Button3.Enabled:=false; for i:=1 to st.Settings.Count-1 do begin self.FieldsGrid.Cells[0,i]:=st.Settings.Names[i-1]; self.StringGrid1.Cells[0,i]:=st.Settings.Names[i-1]; self.FieldsGrid.Cells[1,i]:=''; self.StringGrid1.Cells[1,i]:=''; end; for i:=1 to n do begin self.FieldsGrid.Cells[0,st.Settings.Count+i-1]:=tst.Settings.Values['Disc_'+inttostr(i)+'_1']; self.StringGrid1.Cells[0,st.Settings.Count+i-1]:=tst.Settings.Values['Disc_'+inttostr(i)+'_1']; self.FieldsGrid.Cells[1,st.Settings.Count+i-1]:=''; self.StringGrid1.Cells[1,st.Settings.Count+i-1]:=''; end; st.free; tst.free; end; procedure TExcelImportForm.Button2Click(Sender: TObject); var i,t:integer; excel:texcel; fl:boolean; begin self.StringGrid1.ColCount:=2; self.StringGrid1.RowCount:=self.FieldsGrid.RowCount; excel:=TExcel.Create; excel.filename:=self.Edit1.Text; excel.open; for i:=1 to self.FieldsGrid.RowCount do self.StringGrid1.Cells[0,i]:=self.FieldsGrid.Cells[0,i]; if fileexists(self.Edit1.Text) then begin //showmessage(excel.range[excel.Cells[2,5]]); t:=1; fl:=true; while fl do begin fl:=false; for i:=1 to self.FieldsGrid.RowCount do begin self.StringGrid1.ColCount:=t+1; self.StringGrid1.ColWidths[t]:=180; try self.StringGrid1.Cells[t,i]:=Excel.getcellvalue(t+self.SpinEdit1.Value-1,strtoint(self.FieldsGrid.Cells[1,i])); fl:=fl or (self.StringGrid1.Cells[t,i]<>''); except end; end; if (not fl) and (t>1) then self.StringGrid1.ColCount:=t; inc(t); end; end; excel.close; self.Button3.Enabled:=true; end; procedure TExcelImportForm.Button3Click(Sender: TObject); var i,t,n,k:integer; tst,st,st1,sqlst,sqlst1:tsettings; begin st:=Tsettings.Create; st1:=tsettings.Create; sqlst:=tsettings.Create; sqlst.LoadFromFile(extractfilepath(application.ExeName)+'import.ini','main'); sqlst1:=tsettings.Create; sqlst1.LoadFromFile(extractfilepath(application.ExeName)+'sql.ini','main'); for t:=1 to self.StringGrid1.ColCount-1 do begin st.Settings.Clear; st1.Settings.Clear; for i:=1 to sqlst.Settings.Count do begin st.Settings.Add(self.StringGrid1.Cells[0,i]+'='+self.StringGrid1.Cells[t,i]); end; tst:=tsettings.Create; tst.LoadFromFile(mainform.MainSettings.Settings.Values[templatepath]+'\'+mainform.FileSettings.Settings.Values['templ']+'.dtmpl','student'); mainform.convertsettings(tst,st1,sqlst1,false); mainform.convertsettings(st,st1,sqlst,false); {st1.Settings.Add('_DiscCount=4'); st1.Settings.Add('_Disc_1_1=Русский язык'); st1.Settings.Add('_Disc_1_2=0'); st1.Settings.Add('_Disc_1_3=0'); st1.Settings.Add('_Disc_1_4=5'); st1.Settings.Add('_Disc_2_1=Иностранный язык'); st1.Settings.Add('_Disc_2_2=0'); st1.Settings.Add('_Disc_2_3=0'); st1.Settings.Add('_Disc_2_4=5'); st1.Settings.Add('_Disc_3_1=Математика'); st1.Settings.Add('_Disc_3_2=0'); st1.Settings.Add('_Disc_3_3=0'); st1.Settings.Add('_Disc_3_4=5'); st1.Settings.Add('_Disc_4_1=Физическая культура'); st1.Settings.Add('_Disc_4_2=0'); st1.Settings.Add('_Disc_4_3=0'); st1.Settings.Add('_Disc_4_4=5');} try n:=strtoint(tst.Settings.Values['DiscCount']); except n:=0; end; st1.Settings.Add('_DiscCount='+inttostr(n)); for i:=1 to n do begin k:=sqlst.settings.count+i-1; st1.Settings.Add('_Disc_'+inttostr(i)+'_1='+self.StringGrid1.Cells[0,k]); st1.Settings.Add('_Disc_'+inttostr(i)+'_2=0'); st1.Settings.Add('_Disc_'+inttostr(i)+'_3=0'); st1.Settings.Add('_Disc_'+inttostr(i)+'_4='+self.StringGrid1.Cells[t,k]); end; for i:=1 to st1.Settings.Count do begin if copy(st1.Settings.Names[i-1],1,1)='D' then st1.Settings.ValueFromIndex[i-1]:=parsedate(st1.Settings.ValueFromIndex[i-1]); end; mainform.SaveStudent('',st1,false); end; mainform.refreshtable; self.ModalResult:=mrOk; end; procedure TExcelImportForm.FieldsGridKeyPress(Sender: TObject; var Key: Char); begin if ((key<'0') or (key>'9')) and (key>=#32) then key:=#0; end; end.
{ DBAExplorer - Oracle Admin Management Tool Copyright (C) 2008 Alpaslan KILICKAYA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. } unit OraPartitions; interface uses Classes, SysUtils, Ora, OraStorage, DB, VirtualTable; type PartitionColumn = record ColumnName : string; DataType: string; UpperBound: string; end; TPartitionColumn = ^PartitionColumn; SubpartitionColumn = record SubpartitionName, Tablespace, Value: string; end; TSubpartitionColumn = ^SubpartitionColumn; TIndexPartition = class(TObject) private FPartitionName: String; FPartitionColumns: TList; FSubpartitionColumns: TList; FLogging: TLoggingType; FHasSubpartitionNameType: integer; //0-UserNamed, 1-SystemNamed FPhsicalAttributes : TPhsicalAttributes; FHighValue: string; FPartitionPosition: integer; FPartitionClause : TPartitionClause; FIsDeleted: Boolean; function GetPartitionColumnItem(Index: Integer): TPartitionColumn; procedure SetPartitionColumnItem(Index: Integer; Column: TPartitionColumn); function GetPartitionColumnCount: Integer; function GetSubpartitionColumnItem(Index: Integer): TSubpartitionColumn; procedure SetSubpartitionColumnItem(Index: Integer; Column: TSubpartitionColumn); function GetSubpartitionColumnCount: Integer; public property PartitionName: string read FPartitionName write FPartitionName; property Logging: TLoggingType read FLogging write FLogging; property HasSubpartitionNameType: integer read FHasSubpartitionNameType write FHasSubpartitionNameType; property PhsicalAttributes: TPhsicalAttributes read FPhsicalAttributes write FPhsicalAttributes; property HighValue: string read FHighValue write FHighValue; property PartitionPosition: integer read FPartitionPosition write FPartitionPosition; property IsDeleted: boolean read FIsDeleted write FIsDeleted; constructor Create; destructor Destroy; override; procedure PartitionColumnAdd(Column: TPartitionColumn); procedure PartitionColumnDelete(Index: Integer); property PartitionColumnCount: Integer read GetPartitionColumnCount; property PartitionColumnItems[Index: Integer]: TPartitionColumn read GetPartitionColumnItem write SetPartitionColumnItem; procedure SubpartitionColumnAdd(Column: TSubpartitionColumn); procedure SubpartitionColumnDelete(Index: Integer); procedure SubpartitionColumnDeleteAll; property SubpartitionColumnCount: Integer read GetSubpartitionColumnCount; property SubpartitionColumnItems[Index: Integer]: TSubpartitionColumn read GetSubpartitionColumnItem write SetSubpartitionColumnItem; property PartitionClause : TPartitionClause read FPartitionClause write FPartitionClause; procedure SetDDL(ObjectName, ObjectOwner, PartitionName: string; OraSession: TOraSession); function GetDDL: string; end; TIndexPartitionList = class(TObject) private FInnerList: TList; FSubpartitionList: string; FSubpartitions: string; FPartitionClause : TPartitionClause; FObjectName, FObjectOwner: string; FIndexHashPartitionType: string; FIndexPartitionType: TIndexPartitionType; FIndexPartitionRangeType: TPartitionRangeType; FDSPartitionList: TVirtualTable; FOraSession: TOraSession; function GetItem(Index: Integer): TIndexPartition; procedure SetItem(Index: Integer; IndexPartition: TIndexPartition); function GetCount: Integer; public constructor Create; destructor Destroy; override; procedure Add(IndexPartition: TIndexPartition); procedure DeleteByName(PartitionName: string); function FindByPartitionId(PartitionName: string): integer; procedure DeleteAll; procedure Delete(Index: Integer); property Count: Integer read GetCount; property Items[Index: Integer]: TIndexPartition read GetItem write SetItem; property SubpartitionList: string read FSubpartitionList write FSubpartitionList; property Subpartitions: string read FSubpartitions write FSubpartitions; property PartitionClause : TPartitionClause read FPartitionClause write FPartitionClause; property ObjectName: string read FObjectName write FObjectName; property ObjectOwner: string read FObjectOwner write FObjectOwner; property IndexHashPartitionType: string read FIndexHashPartitionType write FIndexHashPartitionType; property IndexPartitionType: TIndexPartitionType read FIndexPartitionType write FIndexPartitionType; property IndexPartitionRangeType: TPartitionRangeType read FIndexPartitionRangeType write FIndexPartitionRangeType; property DSPartitionList: TVirtualTable read FDSPartitionList; property OraSession: TOraSession read FOraSession write FOraSession; procedure SetDDL; function GetDDL: string; function Clone: TIndexPartitionList; end; function GetTablePartitionedColumns: string; function GetTablePartitions: string; function GetTablePartition: string; function GetTableSubPartitionedColumns: string; function GetTableSubPartitions: string; implementation uses Util; {********************** TIndexPartition ***********************************} function GetTableSubPartitionedColumns: string; begin result := 'Select COLUMN_NAME, COLUMN_POSITION ' +' FROM ALL_SUBPART_KEY_COLUMNS ' +' WHERE name = :pName ' +' and owner = :pOwner ' +'ORDER BY NAME, COLUMN_POSITION '; end; function GetTableSubPartitions: string; begin result := 'Select * ' +' FROM ALL_TAB_SUBPARTITIONS ' +' WHERE table_name = :pName ' +' and table_owner = :pOwner ' +' ORDER BY SUBPARTITION_POSITION '; end; function GetTablePartitions: string; begin result := 'Select * ' +'FROM all_TAB_PARTITIONS ' +'WHERE table_name = :pName ' +' and table_owner = :pOwner ' +'ORDER BY PARTITION_POSITION '; end; function GetTablePartitionedColumns: string; begin result := 'Select COLUMN_NAME, COLUMN_POSITION ' +' FROM ALL_PART_KEY_COLUMNS ' +' WHERE name = :pName ' +' and owner = :pOwner ' +' ORDER BY NAME, COLUMN_POSITION '; end; function GetTablePartition: string; begin result := 'SELECT * ' +' FROM USER_PART_TABLES ' +' WHERE TABLE_NAME = :pTable'; end; function GetTableIndexPartitionDetail(IndexName, OwnerName, PartitionName: string): string; begin result := 'Select * FROM ALL_IND_PARTITIONS ' +' WHERE INDEX_OWNER = '+Str(OwnerName) +' and index_name = '+Str(IndexName); if PartitionName <> '' then Result := Result +' and PARTITION_NAME = '+Str(PartitionName); Result := Result +' ORDER BY INDEX_NAME, PARTITION_POSITION'; end; function GetTableIndexPartitionColumns: string; begin result := 'Select NAME, rtrim(object_type) object_type, COLUMN_NAME ' +' FROM ALL_PART_KEY_COLUMNS ' +' Where owner = :pOwner ' +' and object_type = ''INDEX'' ' +' and NAME = :pName ' +' ORDER BY NAME, COLUMN_POSITION '; end; function GetTableIndexSubPartition: string; begin result := 'Select * ' +' from ALL_IND_SUBPARTITIONS ' +' WHERE INDEX_OWNER = :pOwner ' +' and index_name = :pName ' +' and PARTITION_NAME = :pPartition ' +' order by PARTITION_NAME, SUBPARTITION_NAME '; end; function GetTablePartitionDetail(TableName, OwnerName, PartitionName: string): string; begin result := 'Select * FROM ALL_TAB_PARTITIONS ' +' WHERE TABLE_OWNER = '+Str(OwnerName) +' and TABLE_name = '+Str(TableName); if PartitionName <> '' then Result := Result +' and PARTITION_NAME = '+Str(PartitionName); Result := Result +' ORDER BY TABLE_NAME, PARTITION_POSITION'; end; function GetTablePartitionColumns: string; begin result := 'Select NAME, rtrim(object_type) object_type, COLUMN_NAME ' +' FROM ALL_PART_KEY_COLUMNS ' +' Where owner = :pOwner ' +' and object_type = ''TABLE'' ' +' and NAME = :pName ' +' ORDER BY NAME, COLUMN_POSITION '; end; function GetTableSubPartition: string; begin result := 'Select * ' +' from ALL_TAB_SUBPARTITIONS ' +' WHERE TABLE_OWNER = :pOwner ' +' and TABLE_name = :pName ' +' and PARTITION_NAME = :pPartition ' +' order by PARTITION_NAME, SUBPARTITION_NAME '; end; function GetTableSubPartitionKeys: string; begin result := 'Select OBJECT_TYPE, NAME, COLUMN_NAME ' +' FROM ALL_SUBPART_KEY_COLUMNS ' +' Where owner = :pOwner ' +' and object_type = ''TABLE'' ' +' and NAME = :pName ' +' ORDER BY NAME, COLUMN_POSITION '; end; constructor TIndexPartition.Create; begin FPartitionColumns := TList.Create; FSubpartitionColumns := TList.Create; FIsDeleted := false; end; destructor TIndexPartition.Destroy; var i : Integer; FPartitionColumn: TPartitionColumn; FSubpartitionColumn: TSubpartitionColumn; begin try if FPartitionColumns.Count > 0 then begin for i := FPartitionColumns.Count - 1 downto 0 do begin FPartitionColumn := FPartitionColumns.Items[i]; Dispose(FPartitionColumn); end; end; finally FPartitionColumns.Free; end; try if FSubpartitionColumns.Count > 0 then begin for i := FSubpartitionColumns.Count - 1 downto 0 do begin FSubpartitionColumn := FSubpartitionColumns.Items[i]; Dispose(FSubpartitionColumn); end; end; finally FSubpartitionColumns.Free; end; inherited; end; procedure TIndexPartition.PartitionColumnAdd(Column: TPartitionColumn); begin FPartitionColumns.Add(Column); end; procedure TIndexPartition.PartitionColumnDelete(Index: Integer); begin TObject(FPartitionColumns.Items[Index]).Free; FPartitionColumns.Delete(Index); end; function TIndexPartition.GetPartitionColumnItem(Index: Integer): TPartitionColumn; begin Result := FPartitionColumns.Items[Index]; end; procedure TIndexPartition.SetPartitionColumnItem(Index: Integer; Column: TPartitionColumn); begin if Assigned(Column) then begin FPartitionColumns.Items[Index] := Column; end; end; function TIndexPartition.GetPartitionColumnCount: Integer; begin Result := FPartitionColumns.Count; end; //GetSubpartitionColumn procedure TIndexPartition.SubpartitionColumnAdd(Column: TSubpartitionColumn); begin FSubpartitionColumns.Add(Column); end; procedure TIndexPartition.SubpartitionColumnDelete(Index: Integer); begin TObject(FSubpartitionColumns.Items[Index]).Free; FSubpartitionColumns.Delete(Index); end; procedure TIndexPartition.SubpartitionColumnDeleteAll; var i : Integer; begin try if FSubpartitionColumns.Count > 0 then begin for i := FSubpartitionColumns.Count - 1 downto 0 do begin FSubpartitionColumns.Delete(i); end; end; finally end; end; function TIndexPartition.GetSubpartitionColumnItem(Index: Integer): TSubpartitionColumn; begin Result := FSubpartitionColumns.Items[Index]; end; procedure TIndexPartition.SetSubpartitionColumnItem(Index: Integer; Column: TSubpartitionColumn); begin if Assigned(Column) then FSubpartitionColumns.Items[Index] := Column; end; function TIndexPartition.GetSubpartitionColumnCount: Integer; begin Result := FSubpartitionColumns.Count; end; procedure TIndexPartition.SetDDL(ObjectName, ObjectOwner, PartitionName: string; OraSession: TOraSession); var q,q2: TOraQuery; Column: TPartitionColumn; SubPartition: TSubpartitionColumn; SubpartitionCount: integer; begin if PartitionName = '' then exit; q := TOraQuery.Create(nil); q2 := TOraQuery.Create(nil); q.Session := OraSession; q2.Session := OraSession; q.close; if FPartitionClause = pcTable then q.SQL.Text := GetTablePartitionDetail(ObjectName,ObjectOwner,PartitionName) else q.SQL.Text := GetTableIndexPartitionDetail(ObjectName,ObjectOwner,PartitionName); q.Open; FLogging := ltDefault; if q.FieldByName('LOGGING').AsString = 'YES' then FLogging := ltLogging; if q.FieldByName('LOGGING').AsString = 'NO' then FLogging := ltNoLogging; if q.FieldByName('LOGGING').AsString = 'NO' then FLogging := ltNoLogging; FPartitionPosition := q.FieldByName('PARTITION_POSITION').AsInteger; FPartitionName := q.FieldByName('PARTITION_NAME').AsString; FHighValue := q.FieldByName('HIGH_VALUE').AsString; FPhsicalAttributes.Tablespace := q.FieldByName('TABLESPACE_NAME').AsString; FPhsicalAttributes.PercentFree := q.FieldByName('PCT_FREE').AsString; FPhsicalAttributes.InitialTrans:= q.FieldByName('INI_TRANS').AsString; FPhsicalAttributes.MaxTrans := q.FieldByName('MAX_TRANS').AsString; FPhsicalAttributes.InitialExtent := q.FieldByName('INITIAL_EXTENT').AsString; FPhsicalAttributes.MinExtent := q.FieldByName('MIN_EXTENT').AsString; FPhsicalAttributes.MaxExtent := q.FieldByName('MAX_EXTENT').AsString; FPhsicalAttributes.PctIncrease := q.FieldByName('PCT_INCREASE').AsString; FPhsicalAttributes.BufferPool := bpDefault; if q.FieldByName('BUFFER_POOL').AsString = 'KEEP' then FPhsicalAttributes.BufferPool := bpKeep; if q.FieldByName('BUFFER_POOL').AsString = 'RECYCLE' then FPhsicalAttributes.BufferPool := bpRecycle; FPhsicalAttributes.FreeLists := q.FieldByName('FREELISTS').AsString; FPhsicalAttributes.FreeGroups := q.FieldByName('FREELIST_GROUPS').AsString; SubpartitionCount := q.FieldByName('SUBPARTITION_COUNT').AsInteger; q.close; q2.close; if PartitionClause = pcTable then q2.SQL.Text := GetTablePartitionColumns else q2.SQL.Text := GetTableIndexPartitionColumns; q2.ParamByName('pName').AsString := ObjectName; q2.ParamByName('pOwner').AsString := ObjectOwner; q2.Open; while not q2.Eof do begin new(Column); Column^.ColumnName := q2.FieldByName('COLUMN_NAME').AsString; //DataType: string; Column^.UpperBound := FHighValue; PartitionColumnAdd(Column); q2.Next; end; if SubpartitionCount > 0 then begin q2.close; if PartitionClause = pcTable then q2.SQL.Text := GetTableSubPartition else q2.SQL.Text := GetTableIndexSubPartition; q2.ParamByName('pOwner').AsString := ObjectOwner; q2.ParamByName('pName').AsString := ObjectName; q2.ParamByName('pPartition').AsString := FPartitionName; //q.FieldByName('PARTITION_NAME').AsString; q2.Open; while not q2.Eof do begin new(SubPartition); SubPartition^.SubpartitionName := q2.FieldByName('SUBPARTITION_NAME').AsString; SubPartition^.Tablespace := q2.FieldByName('TABLESPACE_NAME').AsString; SubpartitionColumnAdd(SubPartition); q2.Next; end; end; q.close; q2.close; end; function TIndexPartition.GetDDL: string; begin result := ''; end; //GetDDL {********************** TIndexPartitionList ***********************************} constructor TIndexPartitionList.Create; begin FInnerList := TList.Create; FDSPartitionList := TVirtualTable.Create(nil); end; destructor TIndexPartitionList.Destroy; var i : Integer; begin try if FInnerList.Count > 0 then begin for i := FInnerList.Count - 1 downto 0 do begin TObject(FInnerList.Items[i]).Free; end; end; finally FInnerList.Free; end; FDSPartitionList.Free; inherited; end; procedure TIndexPartitionList.Add(IndexPartition: TIndexPartition); begin FInnerList.Add(IndexPartition); end; procedure TIndexPartitionList.DeleteByName(PartitionName: string); var i: integer; begin for i := 0 to FInnerList.Count -1 do begin if TIndexPartition(FInnerList.Items[i]).PartitionName = PartitionName then begin //Delete(i); TIndexPartition(FInnerList.Items[i]).IsDeleted := true; exit; end; end; end; function TIndexPartitionList.FindByPartitionId(PartitionName: string): integer; var i: integer; begin result := -1; for i := 0 to FInnerList.Count -1 do begin if TIndexPartition(FInnerList.Items[i]).PartitionName = PartitionName then begin result := i; exit; end; end; end; procedure TIndexPartitionList.DeleteAll; var Index: word; begin for index := FInnerList.Count -1 downto 0 do Delete(Index); end; procedure TIndexPartitionList.Delete(Index: Integer); begin TObject(FInnerList.Items[Index]).Free; FinnerList.Delete(Index); end; function TIndexPartitionList.GetItem(Index: Integer): TIndexPartition; begin Result := FInnerList.Items[Index]; end; procedure TIndexPartitionList.SetItem(Index: Integer; IndexPartition: TIndexPartition); begin if Assigned(IndexPartition) then FInnerList.Items[Index] := IndexPartition end; function TIndexPartitionList.GetCount: Integer; begin Result := FInnerList.Count; end; procedure TIndexPartitionList.SetDDL; var q: TOraQuery; FIndexPartition: TIndexPartition; begin if FObjectName = '' then exit; q := TOraQuery.Create(nil); q.Session := OraSession; q.close; if FPartitionClause = pcTable then q.SQL.Text := GetTablePartitionDetail(FObjectName, FObjectOwner, '') else q.SQL.Text := GetTableIndexPartitionDetail(FObjectName, FObjectOwner, ''); q.Open; CopyDataSet(q, FDSPartitionList); while not q.Eof do begin FIndexPartition := TIndexPartition.Create; FIndexPartition.PartitionPosition := q.FieldByName('PARTITION_POSITION').AsInteger; FIndexPartition.PartitionName := q.FieldByName('PARTITION_NAME').AsString; FIndexPartition.HighValue := q.FieldByName('HIGH_VALUE').AsString; FIndexPartition.PartitionClause := FPartitionClause; FIndexPartition.SetDDL(FObjectName, FObjectOwner, FIndexPartition.PartitionName, OraSession); Add(FIndexPartition); FIndexPartition.NewInstance; NewInstance; q.Next; end; q.Close; q.SQL.Text := GetTableSubPartitionKeys; q.ParamByName('pName').AsString := FObjectName; q.ParamByName('pOwner').AsString := FObjectOwner; q.Open; while not q.Eof do begin FSubpartitionList := FSubpartitionList + q.FieldByName('COLUMN_NAME').AsString; q.Next; if not q.Eof then FSubpartitionList := FSubpartitionList +','; end; q.close; end; function TIndexPartitionList.GetDDL: string; var i, j: integer; strPartitions: string; values: string; begin result := ''; strPartitions := ''; with TIndexPartition(FInnerList.Items[0]) do begin //Global if self.PartitionClause = pcGlobal then begin if self.IndexPartitionType = ptRange then strPartitions := ln+' GLOBAL PARTITION BY RANGE ('; if self.IndexPartitionType = ptHash then strPartitions := ln+' GLOBAL PARTITION BY HASH ('; for i := 0 to PartitionColumnCount -1 do begin strPartitions := strPartitions + PartitionColumnItems[i].ColumnName; if i <> PartitionColumnCount-1 then strPartitions := strPartitions +','; end; strPartitions := strPartitions + ')'+ln; end; // PartitionClause = Global //pcTable if self.PartitionClause = pcTable then begin if self.IndexPartitionType = ptRange then begin if self.IndexPartitionRangeType = rpRange then strPartitions := ln+' PARTITION BY RANGE (' else strPartitions := ln+' PARTITION BY LIST (' end; if self.IndexPartitionType = ptHash then strPartitions := ln+' PARTITION BY HASH ('; for i := 0 to PartitionColumnCount -1 do begin strPartitions := strPartitions + PartitionColumnItems[i].ColumnName; if i <> PartitionColumnCount-1 then strPartitions := strPartitions +','; end; strPartitions := strPartitions + ')'+ln; end; // PartitionClause = Global if (IndexPartitionType = ptRange) and (length(FSubpartitionList)>0) and (Subpartitions = '') then strPartitions := strPartitions +'SUBPARTITION BY HASH ('+FSubpartitionList+')'+ln; if Subpartitions <> '' then begin strPartitions := strPartitions +'SUBPARTITION BY LIST ('+FSubpartitionList+')'+ln; strPartitions := strPartitions +'SUBPARTITION TEMPLATE'+ln +'('+ln +Subpartitions+ln +')'+ln end; //local if PartitionClause = pcLocal then strPartitions := ln+'LOCAL '+ln; if IndexPartitionType = ptRange then strPartitions := strPartitions+' ('+ln; if (IndexPartitionType = ptHash) then begin if(IndexHashPartitionType = 'User Named') then strPartitions := strPartitions+' ('+ln else strPartitions := strPartitions+' STORE IN ('+ln; end; end; if IndexPartitionRangeType = rpRange then values := ' VALUES LESS THAN ' else values := ' VALUES '; if FInnerList.Count > 0 then begin for i:= 0 to FInnerList.Count - 1 do begin if TIndexPartition(FInnerList.Items[i]).IsDeleted then Continue; if IndexPartitionType = ptRange then begin strPartitions := strPartitions +' PARTITION '; if PartitionClause = pcLocal then strPartitions := strPartitions + TIndexPartition(FInnerList.Items[i]).PartitionName else strPartitions := strPartitions + TIndexPartition(FInnerList.Items[i]).PartitionName +values+' (' +TIndexPartition(FInnerList.Items[i]).HighValue +')'; if TIndexPartition(FInnerList.Items[i]).Logging = ltLogging then strPartitions := strPartitions +ln+ ' LOGGING'; if TIndexPartition(FInnerList.Items[i]).Logging = ltNoLogging then strPartitions := strPartitions +ln+ ' NOLOGGING'; strPartitions := strPartitions + GenerateStorage(TIndexPartition(FInnerList.Items[i]).PhsicalAttributes); if IndexPartitionRangeType = rpRange then begin if TIndexPartition(FInnerList.Items[i]).SubpartitionColumnCount > 1 then begin strPartitions := strPartitions+ln+' ('+ln; for j := 0 to TIndexPartition(FInnerList.Items[i]).SubpartitionColumnCount-1 do begin strPartitions := strPartitions+' SUBPARTITION '+TIndexPartition(FInnerList.Items[i]).SubpartitionColumnItems[j].SubpartitionName+' ' +'TABLESPACE '+TIndexPartition(FInnerList.Items[i]).SubpartitionColumnItems[j].Tablespace+' '; if j <> TIndexPartition(FInnerList.Items[i]).SubpartitionColumnCount-1 then strPartitions := strPartitions+','+ln; end; strPartitions := strPartitions+ln+' )'; end; end; end //Range else begin if IndexHashPartitionType = 'User Named' then begin strPartitions := strPartitions +' PARTITION '; strPartitions := strPartitions +TIndexPartition(FInnerList.Items[i]).PartitionName; if TIndexPartition(FInnerList.Items[i]).PhsicalAttributes.Tablespace <> '' then strPartitions := strPartitions +' TABLESPACE '+TIndexPartition(FInnerList.Items[i]).PhsicalAttributes.Tablespace; end else strPartitions := strPartitions +' '+ TIndexPartition(FInnerList.Items[i]).PhsicalAttributes.Tablespace; end; if i <> FInnerList.Count -1 then strPartitions := strPartitions+ ','+ln; end; //IndexPartitionLists.Count-1 end; //IndexPartitionLists.Count > 0 strPartitions := strPartitions +ln+ ' )'; result := strPartitions; end; function TIndexPartitionList.Clone: TIndexPartitionList; var i: integer; begin result := TIndexPartitionList.Create; for i := 0 to FInnerList.Count -1 do result.Add(FInnerList.Items[i]); result.SubpartitionList := FSubpartitionList; result.Subpartitions := FSubpartitions; result.PartitionClause := FPartitionClause; result.ObjectName := FObjectName; result.ObjectOwner := FObjectOwner; result.IndexHashPartitionType := FIndexHashPartitionType; result.IndexPartitionType := FIndexPartitionType; result.IndexPartitionRangeType := FIndexPartitionRangeType; result.OraSession := FOraSession; end; end.
{ behavior3delphi - a Behavior3 client library (Behavior Trees) for Delphi by Dennis D. Spreen <dennis@spreendigital.de> see Behavior3.pas header for full license information } unit Behavior3.Composites.Sequence; interface uses Behavior3, Behavior3.Core.Composite, Behavior3.Core.BaseNode, Behavior3.Core.Tick; type (** * The Sequence node ticks its children sequentially until one of them * returns `FAILURE`, `RUNNING` or `ERROR`. If all children return the * success state, the sequence also returns `SUCCESS`. * * @module b3 * @class Sequence * @extends Composite **) TB3Sequence = class(TB3Composite) private protected public constructor Create; override; (** * Tick method. * @method tick * @param {Tick} tick A tick instance. * @return {Constant} A state constant. **) function Tick(Tick: TB3Tick): TB3Status; override; end; implementation { TB3Sequence } uses Behavior3.Helper; constructor TB3Sequence.Create; begin inherited; (** * Node name. Default to `Sequence`. * @property {String} name * @readonly **) Name := 'Sequence'; end; function TB3Sequence.Tick(Tick: TB3Tick): TB3Status; var Child: TB3BaseNode; Status: TB3Status; begin for Child in Children do begin Status := Child._Execute(Tick); if Status <> Behavior3.Success then begin Result := Status; Exit; end; end; Result := Behavior3.Success; end; end.
(*----------------------------------------------------------------------------- Название: npUtils Автор: М. Морозов Назначение: История: $Id: vtNavigatorUtils.pas,v 1.9 2009/07/29 06:59:02 oman Exp $ $Log: vtNavigatorUtils.pas,v $ Revision 1.9 2009/07/29 06:59:02 oman - new: {RequestLink:158336069} Revision 1.8 2009/07/29 06:56:43 oman - new: {RequestLink:158336069} Revision 1.7 2008/06/27 11:13:12 oman - fix: Боремся с балончиками (cq29470) Revision 1.6 2008/06/27 10:37:03 oman - fix: Боремся с балончиками (cq29470) Revision 1.5 2007/08/15 15:15:19 lulin - не передаем лишний параметр. Revision 1.4 2007/08/14 19:31:40 lulin - оптимизируем очистку памяти. Revision 1.3 2005/12/01 14:11:01 mmorozov - bugfix: function npIsWindowMinimazed (cq: 00018418); Revision 1.2 2005/07/07 08:44:43 mmorozov new: global function npIsWindowMinimazed; Revision 1.1 2005/06/09 09:47:51 mmorozov - компоненты перенесены в библиотеку VT; Revision 1.8 2005/01/28 17:33:05 mmorozov remove: не используемый модуль; Revision 1.7 2005/01/28 17:30:37 mmorozov new: function npIsFloatingForm; new: function npIsInFloatNavigator; Revision 1.6 2004/10/01 09:19:41 mmorozov change: для Немезиса npIsModalForm использует IvcmEntityForm.IsModalForm; Revision 1.5 2004/09/30 07:21:42 mmorozov new: method npIsParentWindow; new: method npIsModalForm; Revision 1.4 2004/09/17 12:19:11 mmorozov new: overload npIsOwnerWindow; Revision 1.3 2004/08/23 11:34:01 mmorozov no message Revision 1.2 2004/08/23 11:33:19 mmorozov - add cvs log; -----------------------------------------------------------------------------*) unit vtNavigatorUtils; interface uses Classes, Controls, vtNavigator ; function npIsOwnerWindow(aOwner : TComponent; var aControl : TWinControl; aHandle : THandle) : Boolean; overload; {* - проверяет является ли aOwner прародителем окна с описателем aHandle. } function npIsOwnerWindow(aOwner : TComponent; aHandle : THandle) : Boolean; overload; {* - проверяет является ли aOwner прародителем окна с описателем aHandle. } function npIsParentWindow(aParent : TWinControl; aHandle : THandle) : Boolean; {* - определяет является ли aParent родителем aHandle. } function npFindWindow(aComponent : TComponent; aHandle : THandle) : TWinControl; {* - поиск в aComponent окна с описателем aHandle. При поиске проверяются Components и Controls всех вложенных компонентов. } function npIsModalForm(aHandle : THandle) : Boolean; {* - определяет является ли компонент с указанным Handle модальной формой. } function npIsFloatingForm(aHandle : THandle) : Boolean; {* - определяет является ли компонент с указанным Handle плавающей формой. } function npIsInFloatNavigator(aHandle : THandle) : Boolean; {* - окно находится в плавающем навигаторе. } function npIsWindowMinimazed(const aWindow : TWinControl) : Boolean; {* - определяет является ли aWindow минимизированным. } implementation uses Forms, Windows, {$IfDef Nemesis} SysUtils, vcmInterfaces, {$EndIf Nemesis} l3Base ; function npIsWindowMinimazed(const aWindow : TWinControl) : Boolean; {* - определяет является ли aWindow минимизированным. } var lWP : TWindowPlacement; begin Result := False; if Assigned(aWindow) and aWindow.HandleAllocated then begin l3FillChar(lWP, SizeOf(lWP)); lWP.length := SizeOf(lWP); Windows.GetWindowPlacement(aWindow.Handle, @lWP); Result := lWP.showCmd = SW_SHOWMINIMIZED; end; end; function npIsInFloatNavigator(aHandle : THandle) : Boolean; {* - окно находится в плавающем навигаторе. } var lControl : TWinControl; begin Result := False; lControl := FindControl(aHandle); if Assigned(lControl) then begin while Assigned(lControl) do begin if lControl is TnpFloatingWindow then begin Result := True; Break; end; lControl := lControl.Parent; end; end; end; function npIsModalForm(aHandle : THandle) : Boolean; {* - определяет является ли компонент с указанным Handle модальной формой. } var lControl : TWinControl; {$IfDef Nemesis} lForm : IvcmEntityForm; {$EndIf Nemesis} begin lControl := FindControl(aHandle); Result := Assigned(lControl) and (lControl is TCustomForm); if Result then {$IfDef Nemesis} if Supports(lControl, IvcmEntityForm, lForm) then try Result := lForm.IsModalForm; finally lForm := nil; end else Result := (fsModal in TCustomForm(lControl).FormState); {$Else} Result := (fsModal in TCustomForm(lControl).FormState); {$EndIf Nemesis} end; function npIsFloatingForm(aHandle : THandle) : Boolean; {* - определяет является ли компонент с указанным Handle плавающей формой. } var lControl : TWinControl; {$IfDef Nemesis} lForm : IvcmEntityForm; {$EndIf Nemesis} begin lControl := FindControl(aHandle); Result := Assigned(lControl) and (lControl is TCustomForm); if Result then {$IfDef Nemesis} if Supports(lControl, IvcmEntityForm, lForm) then try Result := (lForm.ZoneType in [vcm_ztFloating, vcm_ztSimpleFloat]); finally lForm := nil; end; {$Else} Result := TCustomForm(lControl).Owner = Application; {$EndIf Nemesis} end; function npIsOwnerWindow(aOwner : TComponent; aHandle : THandle) : Boolean; {* - проверяет является ли aOwner прародителем окна с описателем aHandle. } var lControl : TWinControl; begin Result := npIsOwnerWindow(aOwner, lControl, aHandle); end; function npIsOwnerWindow(aOwner : TComponent; var aControl : TWinControl; aHandle : THandle) : Boolean; var lOwner : TComponent; begin Result := False; aControl := FindControl(aHandle); if Assigned(aControl) then begin if aControl = aOwner then Result := True else begin lOwner := aControl.Owner; while Assigned(lOwner) do begin if (lOwner = aOwner) then begin Result := True; Break; end else lOwner := lOwner.Owner; end; end; end; end; function npIsParentWindow(aParent : TWinControl; aHandle : THandle) : Boolean; {* - определяет является ли aParent родителем aHandle. } var lControl : TWinControl; lParent : TWinControl; begin Result := False; lControl := FindControl(aHandle); if Assigned(lControl) then begin lParent := lControl.Parent; while Assigned(lParent) and (lParent <> aParent) do lParent := lParent.Parent; Result := Assigned(lParent); end; end; function npFindWindow(aComponent : TComponent; aHandle : THandle) : TWinControl; var lIndex, J : Integer; lControl : TWinControl; begin Result := nil; with aComponent do for lIndex := 0 to Pred(ComponentCount) do begin (* ребенок и есть искомое окно *) if (Components[lIndex] is TWinControl) then begin lControl := TWinControl(Components[lIndex]); if lControl.HandleAllocated and (lControl.Handle = aHandle) then Result := lControl; (* поищем в компонентах, которые на нём лежат *) if not Assigned(Result) then for J := 0 to Pred(lControl.ControlCount) do begin if (lControl.Controls[J] is TWinControl) and TWinControl(lControl.Controls[J]).HandleAllocated and (TWinControl(lControl.Controls[J]).Handle = aHandle) then Result := TWinControl(lControl.Controls[J]) else Result := npFindWindow(lControl.Controls[J], aHandle); if Assigned(Result) then Break; end; end; (* поищем в детях ребенка *) if not Assigned(Result) and (Components[lIndex].ComponentCount > 0) then Result := npFindWindow(Components[lIndex], aHandle); (* окно найдено, выходим *) if Assigned(Result) then Break; end; end; end.
unit BackupThread; interface uses Classes, SyncObjs, Collection, BackupInterfaces, Kernel, World; type TBackupThread = class(TThread) public constructor Create(Writer : IBackupWriter; Coll : TCollection; Lock : TCriticalSection; prior : TThreadPriority); destructor Destroy; override; private fWriter : IBackupWriter; fColl : TCollection; fLock : TCriticalSection; public procedure Execute; override; end; implementation uses SysUtils; // TBackupThread constructor TBackupThread.Create(Writer : IBackupWriter; Coll : TCollection; Lock : TCriticalSection; prior : TThreadPriority); begin inherited Create(true); fWriter := Writer; fColl := Coll; fLock := Lock; FreeOnTerminate := true; Priority := prior; Resume; end; destructor TBackupThread.Destroy; begin fColl.Free; inherited; end; procedure TBackupThread.Execute; var i : integer; cnt : integer; begin i := 0; cnt := fColl.Count; fWriter.WriteInteger('Count', cnt); while not Terminated and (i < cnt) do try fLock.Enter; try fWriter.WriteObject(IntToStr(i), fColl[i]); finally inc(i); fLock.Leave; end; except end; end; end.
unit kw_Form_MemoryUsage; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "View" // Модуль: "w:/garant6x/implementation/Garant/GbaNemesis/View/kw_Form_MemoryUsage.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> F1 Оболочка Без Прецедентов::F1 Without Usecases::View::Main::Tkw_Form_MemoryUsage // // Слово словаря для идентификатора формы MemoryUsage // ---- // *Пример использования*: // {code} // 'aControl' форма::MemoryUsage TryFocus ASSERT // {code} // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If not defined(Admin) AND not defined(Monitorings)} uses Classes {$If not defined(NoScripts)} , tfwControlString {$IfEnd} //not NoScripts ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} type Tkw_Form_MemoryUsage = class(TtfwControlString) {* Слово словаря для идентификатора формы MemoryUsage ---- *Пример использования*: [code] 'aControl' форма::MemoryUsage TryFocus ASSERT [code] } protected // overridden protected methods {$If not defined(NoScripts)} function GetString: AnsiString; override; {$IfEnd} //not NoScripts end;//Tkw_Form_MemoryUsage {$IfEnd} //not Admin AND not Monitorings implementation {$If not defined(Admin) AND not defined(Monitorings)} uses MemoryUsage_Form ; {$IfEnd} //not Admin AND not Monitorings {$If not defined(Admin) AND not defined(Monitorings)} // start class Tkw_Form_MemoryUsage {$If not defined(NoScripts)} function Tkw_Form_MemoryUsage.GetString: AnsiString; {-} begin Result := 'MemoryUsageForm'; end;//Tkw_Form_MemoryUsage.GetString {$IfEnd} //not NoScripts {$IfEnd} //not Admin AND not Monitorings initialization {$If not defined(Admin) AND not defined(Monitorings)} // Регистрация Tkw_Form_MemoryUsage Tkw_Form_MemoryUsage.Register('форма::MemoryUsage', TMemoryUsageForm); {$IfEnd} //not Admin AND not Monitorings end.
unit ddAutolinkArbitraryDocEntry; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // Библиотека "dd" // Модуль: "w:/common/components/rtl/Garant/dd/ddAutolinkArbitraryDocEntry.pas" // Родные Delphi интерфейсы (.pas) // Generated from UML model, root element: <<SimpleClass::Class>> Shared Delphi::dd::Autolink::TddAutolinkArbitraryDocEntry // // // Все права принадлежат ООО НПП "Гарант-Сервис". // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // ! Полностью генерируется с модели. Править руками - нельзя. ! interface uses l3LongintList, dt_Types, l3ProtoObject, ddAutolinkInterfaces ; type TddAutolinkArbitraryDocEntry = class(Tl3ProtoObject, IddAutolinkArbitraryDocEntry) private // private fields f_DocID : TDocID; f_TypesList : Tl3LongintList; protected // realized methods function Get_DocID: TDocID; function Get_TypesList: Tl3LongintList; protected // overridden protected methods procedure Cleanup; override; {* Функция очистки полей объекта. } public // public methods constructor Create(aDocID: TDocID; aTypesList: Tl3LongintList); reintroduce; class function Make(aDocID: TDocID; aTypesList: Tl3LongintList): IddAutolinkArbitraryDocEntry; reintroduce; {* Сигнатура фабрики TddAutolinkArbitraryDocEntry.Make } end;//TddAutolinkArbitraryDocEntry implementation uses SysUtils ; // start class TddAutolinkArbitraryDocEntry constructor TddAutolinkArbitraryDocEntry.Create(aDocID: TDocID; aTypesList: Tl3LongintList); //#UC START# *51F269D40190_51F258B701B2_var* //#UC END# *51F269D40190_51F258B701B2_var* begin //#UC START# *51F269D40190_51F258B701B2_impl* inherited Create; f_DocID := aDocID; if aTypesList <> nil then f_TypesList := aTypesList.Use; //#UC END# *51F269D40190_51F258B701B2_impl* end;//TddAutolinkArbitraryDocEntry.Create class function TddAutolinkArbitraryDocEntry.Make(aDocID: TDocID; aTypesList: Tl3LongintList): IddAutolinkArbitraryDocEntry; var l_Inst : TddAutolinkArbitraryDocEntry; begin l_Inst := Create(aDocID, aTypesList); try Result := l_Inst; finally l_Inst.Free; end;//try..finally end; function TddAutolinkArbitraryDocEntry.Get_DocID: TDocID; //#UC START# *51F2529E003F_51F258B701B2get_var* //#UC END# *51F2529E003F_51F258B701B2get_var* begin //#UC START# *51F2529E003F_51F258B701B2get_impl* Result := f_DocID; //#UC END# *51F2529E003F_51F258B701B2get_impl* end;//TddAutolinkArbitraryDocEntry.Get_DocID function TddAutolinkArbitraryDocEntry.Get_TypesList: Tl3LongintList; //#UC START# *51F252E8038B_51F258B701B2get_var* //#UC END# *51F252E8038B_51F258B701B2get_var* begin //#UC START# *51F252E8038B_51F258B701B2get_impl* Result := f_TypesList; //#UC END# *51F252E8038B_51F258B701B2get_impl* end;//TddAutolinkArbitraryDocEntry.Get_TypesList procedure TddAutolinkArbitraryDocEntry.Cleanup; //#UC START# *479731C50290_51F258B701B2_var* //#UC END# *479731C50290_51F258B701B2_var* begin //#UC START# *479731C50290_51F258B701B2_impl* FreeAndNil(f_TypesList); inherited; //#UC END# *479731C50290_51F258B701B2_impl* end;//TddAutolinkArbitraryDocEntry.Cleanup end.
unit daTableDescription; // Модуль: "w:\common\components\rtl\Garant\DA\daTableDescription.pas" // Стереотип: "UtilityPack" // Элемент модели: "daTableDescription" MUID: (55CB200E0058) {$Include w:\common\components\rtl\Garant\DA\daDefine.inc} interface uses l3IntfUses , l3ProtoObject , daInterfaces , daTypes , daFieldDescriptionList ; type TdaTableDescription = class(Tl3ProtoObject, IdaTableDescription) private f_Description: AnsiString; f_IsDublicate: Boolean; f_IsFake: Boolean; f_FieldList: TdaFieldDescriptionList; f_SQLName: AnsiString; f_Scheme: AnsiString; f_IsTree: Boolean; f_Code: AnsiString; f_FamilyID: TdaFamilyID; f_Kind: TdaTables; protected function Get_Description: AnsiString; function Get_IsDublicate: Boolean; function Get_IsFake: Boolean; function Get_Kind: TdaTables; function Get_Field(const FIeldName: AnsiString): IdaFieldDescription; function Get_SQLName: AnsiString; function Get_Scheme: AnsiString; function FieldByIndex(anIndex: Integer): IdaFieldDescription; function Get_FieldsCount: Integer; function Get_FieldsCountWithoutTree: Integer; function Get_IsTree: Boolean; function Get_Code: AnsiString; function Get_FamilyID: TdaFamilyID; procedure Cleanup; override; {* Функция очистки полей объекта. } procedure InitFields; override; public constructor Create(aKind: TdaTables; const aSQLName: AnsiString; const aDescription: AnsiString; const aCode: AnsiString; aFamilyID: TdaFamilyID; const aScheme: AnsiString = ''; aDublicate: Boolean = False; aFake: Boolean = False; aIsTree: Boolean = False); reintroduce; procedure AddField(const aField: IdaFieldDescription); procedure IterateFieldsF(anAction: daTableDescriptionIterator_IterateFieldsF_Action); public property Kind: TdaTables read f_Kind; end;//TdaTableDescription implementation uses l3ImplUses , l3Types , SysUtils , Classes , l3Base //#UC START# *55CB200E0058impl_uses* //#UC END# *55CB200E0058impl_uses* ; function CompareFields(Item1: Pointer; Item2: Pointer): Integer; //#UC START# *55CB2045030F_55CB200E0058_var* //#UC END# *55CB2045030F_55CB200E0058_var* begin //#UC START# *55CB2045030F_55CB200E0058_impl* Result := IdaFieldDescription(Item1).Index - IdaFieldDescription(Item2).Index; //#UC END# *55CB2045030F_55CB200E0058_impl* end;//CompareFields constructor TdaTableDescription.Create(aKind: TdaTables; const aSQLName: AnsiString; const aDescription: AnsiString; const aCode: AnsiString; aFamilyID: TdaFamilyID; const aScheme: AnsiString = ''; aDublicate: Boolean = False; aFake: Boolean = False; aIsTree: Boolean = False); //#UC START# *55360BAB0116_55360B420250_var* //#UC END# *55360BAB0116_55360B420250_var* begin //#UC START# *55360BAB0116_55360B420250_impl* inherited Create; f_Kind := aKind; f_Description := aDescription; f_IsDublicate := aDublicate; f_IsFake := aFake; f_SQLName := aSQLName; f_Scheme := aScheme; f_IsTree := aIsTree; f_Code := aCode; f_FamilyID := aFamilyID; //#UC END# *55360BAB0116_55360B420250_impl* end;//TdaTableDescription.Create procedure TdaTableDescription.AddField(const aField: IdaFieldDescription); //#UC START# *5538EA4402F6_55360B420250_var* //#UC END# *5538EA4402F6_55360B420250_var* begin //#UC START# *5538EA4402F6_55360B420250_impl* f_FieldList.Add(aField); aField.BindToTable(Self, f_FieldList.Count); //#UC END# *5538EA4402F6_55360B420250_impl* end;//TdaTableDescription.AddField function TdaTableDescription.Get_Description: AnsiString; //#UC START# *55360A96000F_55360B420250get_var* //#UC END# *55360A96000F_55360B420250get_var* begin //#UC START# *55360A96000F_55360B420250get_impl* Result := f_Description; //#UC END# *55360A96000F_55360B420250get_impl* end;//TdaTableDescription.Get_Description function TdaTableDescription.Get_IsDublicate: Boolean; //#UC START# *55360AB100E0_55360B420250get_var* //#UC END# *55360AB100E0_55360B420250get_var* begin //#UC START# *55360AB100E0_55360B420250get_impl* Result := f_IsDublicate; //#UC END# *55360AB100E0_55360B420250get_impl* end;//TdaTableDescription.Get_IsDublicate function TdaTableDescription.Get_IsFake: Boolean; //#UC START# *55360AF00014_55360B420250get_var* //#UC END# *55360AF00014_55360B420250get_var* begin //#UC START# *55360AF00014_55360B420250get_impl* Result := f_IsFake; //#UC END# *55360AF00014_55360B420250get_impl* end;//TdaTableDescription.Get_IsFake function TdaTableDescription.Get_Kind: TdaTables; //#UC START# *55378E13022E_55360B420250get_var* //#UC END# *55378E13022E_55360B420250get_var* begin //#UC START# *55378E13022E_55360B420250get_impl* Result := f_Kind; //#UC END# *55378E13022E_55360B420250get_impl* end;//TdaTableDescription.Get_Kind function TdaTableDescription.Get_Field(const FIeldName: AnsiString): IdaFieldDescription; //#UC START# *55379DA40290_55360B420250get_var* var l_Index: Integer; //#UC END# *55379DA40290_55360B420250get_var* begin //#UC START# *55379DA40290_55360B420250get_impl* if f_FieldList.FindData(FieldName, l_Index) then Result := f_FieldList[l_Index] else Result := nil; //#UC END# *55379DA40290_55360B420250get_impl* end;//TdaTableDescription.Get_Field procedure TdaTableDescription.IterateFieldsF(anAction: daTableDescriptionIterator_IterateFieldsF_Action); //#UC START# *55C860390259_55360B420250_var* var l_List: TList; function DoIt(aData : Pointer; anIndex : Integer) : Boolean; begin l_List.Add(Pointer(aData^)); Result := True; end; var Hack : Pointer absolute anAction; l_IDX: Integer; //#UC END# *55C860390259_55360B420250_var* begin //#UC START# *55C860390259_55360B420250_impl* l_List := TList.Create; try try f_FieldList.IterateAllF(l3L2IA(@DoIt)); l_List.Sort(@CompareFields); for l_IDX := 0 to l_List.Count - 1 do anAction(IdaFieldDescription(l_List[l_IDX])) finally l3FreeLocalStub(Hack); end;//try..finally finally FreeAndNil(l_List); end; //#UC END# *55C860390259_55360B420250_impl* end;//TdaTableDescription.IterateFieldsF function TdaTableDescription.Get_SQLName: AnsiString; //#UC START# *5608EE130006_55360B420250get_var* //#UC END# *5608EE130006_55360B420250get_var* begin //#UC START# *5608EE130006_55360B420250get_impl* Result := f_SQLName; //#UC END# *5608EE130006_55360B420250get_impl* end;//TdaTableDescription.Get_SQLName function TdaTableDescription.Get_Scheme: AnsiString; //#UC START# *566572560127_55360B420250get_var* //#UC END# *566572560127_55360B420250get_var* begin //#UC START# *566572560127_55360B420250get_impl* Result := f_Scheme; //#UC END# *566572560127_55360B420250get_impl* end;//TdaTableDescription.Get_Scheme function TdaTableDescription.FieldByIndex(anIndex: Integer): IdaFieldDescription; //#UC START# *569F6ADC0330_55360B420250_var* var l_Result: IdaFieldDescription; function lp_Find(aField: IdaFieldDescription): Boolean; begin Result := aField.Index <> anIndex; if not Result then l_Result := aField; end; //#UC END# *569F6ADC0330_55360B420250_var* begin //#UC START# *569F6ADC0330_55360B420250_impl* l_Result := nil; IterateFieldsF(L2DaTableDescriptionIteratorIterateFieldsFAction(@lp_Find)); Result := l_Result; //#UC END# *569F6ADC0330_55360B420250_impl* end;//TdaTableDescription.FieldByIndex function TdaTableDescription.Get_FieldsCount: Integer; //#UC START# *56A0C27502A5_55360B420250get_var* //#UC END# *56A0C27502A5_55360B420250get_var* begin //#UC START# *56A0C27502A5_55360B420250get_impl* Result := f_FieldList.Count; //#UC END# *56A0C27502A5_55360B420250get_impl* end;//TdaTableDescription.Get_FieldsCount function TdaTableDescription.Get_FieldsCountWithoutTree: Integer; //#UC START# *56A1E93B0132_55360B420250get_var* //#UC END# *56A1E93B0132_55360B420250get_var* begin //#UC START# *56A1E93B0132_55360B420250get_impl* Result := Get_FieldsCount; if f_IsTree then Dec(Result, 2); //#UC END# *56A1E93B0132_55360B420250get_impl* end;//TdaTableDescription.Get_FieldsCountWithoutTree function TdaTableDescription.Get_IsTree: Boolean; //#UC START# *56A1FDB80282_55360B420250get_var* //#UC END# *56A1FDB80282_55360B420250get_var* begin //#UC START# *56A1FDB80282_55360B420250get_impl* Result := f_IsTree; //#UC END# *56A1FDB80282_55360B420250get_impl* end;//TdaTableDescription.Get_IsTree function TdaTableDescription.Get_Code: AnsiString; //#UC START# *576D062600B3_55360B420250get_var* //#UC END# *576D062600B3_55360B420250get_var* begin //#UC START# *576D062600B3_55360B420250get_impl* Result := f_Code; //#UC END# *576D062600B3_55360B420250get_impl* end;//TdaTableDescription.Get_Code function TdaTableDescription.Get_FamilyID: TdaFamilyID; //#UC START# *577223F80158_55360B420250get_var* //#UC END# *577223F80158_55360B420250get_var* begin //#UC START# *577223F80158_55360B420250get_impl* Result := f_FamilyID; //#UC END# *577223F80158_55360B420250get_impl* end;//TdaTableDescription.Get_FamilyID procedure TdaTableDescription.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_55360B420250_var* //#UC END# *479731C50290_55360B420250_var* begin //#UC START# *479731C50290_55360B420250_impl* FreeAndNil(f_FieldList); inherited; //#UC END# *479731C50290_55360B420250_impl* end;//TdaTableDescription.Cleanup procedure TdaTableDescription.InitFields; //#UC START# *47A042E100E2_55360B420250_var* //#UC END# *47A042E100E2_55360B420250_var* begin //#UC START# *47A042E100E2_55360B420250_impl* inherited; f_FieldList := TdaFieldDescriptionList.MakeSorted(l3_dupError); //#UC END# *47A042E100E2_55360B420250_impl* end;//TdaTableDescription.InitFields end.
{ Date Created: 5/22/00 11:17:33 AM } unit InfoSYSTEMTable; interface uses Classes, DB, DBISAMTb, SysUtils, DBISAMTableAU, DataBuf; type TInfoSYSTEMRecord = record PSite: String[4]; PNextID: String[5]; End; TInfoSYSTEMBuffer = class(TDataBuf) protected function PtrIndex(Index:integer):Pointer;override; public Data: TInfoSYSTEMRecord end; TEIInfoSYSTEM = (InfoSYSTEMPrimaryKey); TInfoSYSTEMTable = class( TDBISAMTableAU ) private FDFSite: TStringField; FDFNextID: TStringField; procedure SetPSite(const Value: String); function GetPSite:String; procedure SetPNextID(const Value: String); function GetPNextID:String; procedure SetEnumIndex(Value: TEIInfoSYSTEM); function GetEnumIndex: TEIInfoSYSTEM; protected procedure CreateFields; virtual; procedure SetActive(Value: Boolean); override; procedure LoadFieldDefs(AStringList:TStringList);override; procedure LoadIndexDefs(AStringList:TStringList);override; public function GetDataBuffer:TInfoSYSTEMRecord; procedure StoreDataBuffer(ABuffer:TInfoSYSTEMRecord); property DFSite: TStringField read FDFSite; property DFNextID: TStringField read FDFNextID; property PSite: String read GetPSite write SetPSite; property PNextID: String read GetPNextID write SetPNextID; procedure Validate; virtual; published property Active write SetActive; property EnumIndex: TEIInfoSYSTEM read GetEnumIndex write SetEnumIndex; end; { TInfoSYSTEMTable } procedure Register; implementation procedure TInfoSYSTEMTable.CreateFields; begin FDFSite := CreateField( 'Site' ) as TStringField; FDFNextID := CreateField( 'NextID' ) as TStringField; end; { TInfoSYSTEMTable.CreateFields } procedure TInfoSYSTEMTable.SetActive(Value: Boolean); begin inherited SetActive(Value); if Active then CreateFields; end; { TInfoSYSTEMTable.SetActive } procedure TInfoSYSTEMTable.Validate; begin { Enter Validation Code Here } end; { TInfoSYSTEMTable.Validate } procedure TInfoSYSTEMTable.SetPSite(const Value: String); begin DFSite.Value := Value; end; function TInfoSYSTEMTable.GetPSite:String; begin result := DFSite.Value; end; procedure TInfoSYSTEMTable.SetPNextID(const Value: String); begin DFNextID.Value := Value; end; function TInfoSYSTEMTable.GetPNextID:String; begin result := DFNextID.Value; end; procedure TInfoSYSTEMTable.LoadFieldDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('Site, String, 4, N'); Add('NextID, String, 5, N'); end; end; procedure TInfoSYSTEMTable.LoadIndexDefs(AStringList: TStringList); begin inherited; with AstringList do begin Add('PrimaryKey, NextID, Y, Y, N, N'); end; end; procedure TInfoSYSTEMTable.SetEnumIndex(Value: TEIInfoSYSTEM); begin case Value of InfoSYSTEMPrimaryKey : IndexName := ''; end; end; function TInfoSYSTEMTable.GetDataBuffer:TInfoSYSTEMRecord; var buf: TInfoSYSTEMRecord; begin fillchar(buf, sizeof(buf), 0); buf.PSite := DFSite.Value; buf.PNextID := DFNextID.Value; result := buf; end; procedure TInfoSYSTEMTable.StoreDataBuffer(ABuffer:TInfoSYSTEMRecord); begin DFSite.Value := ABuffer.PSite; DFNextID.Value := ABuffer.PNextID; end; function TInfoSYSTEMTable.GetEnumIndex: TEIInfoSYSTEM; var iname : string; begin iname := uppercase(indexname); if iname = '' then result := InfoSYSTEMPrimaryKey; end; (********************************************) (************ Register Component ************) (********************************************) procedure Register; begin RegisterComponents( 'Info Tables', [ TInfoSYSTEMTable, TInfoSYSTEMBuffer ] ); end; { Register } function TInfoSYSTEMBuffer.PtrIndex(index:integer):Pointer; begin result := nil; case index of 1 : result := @Data.PSite; 2 : result := @Data.PNextID; end; end; end. { InfoSYSTEMTable }
unit vendetta_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} nz80,konami,main_engine,controls_engine,gfx_engine,rom_engine, pal_engine,sound_engine,ym_2151,k052109,k053260,k053246_k053247_k055673, k054000,k053251,timer_engine,eepromser; function iniciar_vendetta:boolean; implementation const //vendetta vendetta_rom:tipo_roms=(n:'081u01.17c';l:$40000;p:0;crc:$b4d9ade5); vendetta_sound:tipo_roms=(n:'081b02';l:$10000;p:0;crc:$4c604d9b); vendetta_tiles:array[0..1] of tipo_roms=( (n:'081a09';l:$80000;p:0;crc:$b4c777a9),(n:'081a08';l:$80000;p:2;crc:$272ac8d9)); vendetta_sprites:array[0..3] of tipo_roms=( (n:'081a04';l:$100000;p:0;crc:$464b9aa4),(n:'081a05';l:$100000;p:2;crc:$4e173759), (n:'081a06';l:$100000;p:4;crc:$e9fe6d80),(n:'081a07';l:$100000;p:6;crc:$8a22b29a)); vendetta_k053260:tipo_roms=(n:'081a03';l:$100000;p:0;crc:$14b6baea); vendetta_eeprom:tipo_roms=(n:'vendetta.nv';l:$80;p:0;crc:$fbac4e30); //DIP vendetta_dip_a:array [0..2] of def_dip=( (mask:$0f;name:'Coin A';number:16;dip:((dip_val:$02;dip_name:'4C 1C'),(dip_val:$05;dip_name:'3C 1C'),(dip_val:$08;dip_name:'2C 1C'),(dip_val:$04;dip_name:'3C 2C'),(dip_val:$01;dip_name:'4C 3C'),(dip_val:$0f;dip_name:'1C 1C'),(dip_val:$03;dip_name:'3C 4C'),(dip_val:$07;dip_name:'2C 3C'),(dip_val:$0e;dip_name:'1C 2C'),(dip_val:$06;dip_name:'2C 5C'),(dip_val:$0d;dip_name:'1C 3C'),(dip_val:$0c;dip_name:'1C 4C'),(dip_val:$0b;dip_name:'1C 5C'),(dip_val:$0a;dip_name:'1C 6C'),(dip_val:$09;dip_name:'1C 7C'),(dip_val:$0;dip_name:'Free Play'))), (mask:$f0;name:'Coin B';number:16;dip:((dip_val:$20;dip_name:'4C 1C'),(dip_val:$50;dip_name:'3C 1C'),(dip_val:$80;dip_name:'2C 1C'),(dip_val:$40;dip_name:'3C 2C'),(dip_val:$10;dip_name:'4C 3C'),(dip_val:$f0;dip_name:'1C 1C'),(dip_val:$30;dip_name:'3C 4C'),(dip_val:$70;dip_name:'2C 3C'),(dip_val:$e0;dip_name:'1C 2C'),(dip_val:$60;dip_name:'2C 5C'),(dip_val:$d0;dip_name:'1C 3C'),(dip_val:$c0;dip_name:'1C 4C'),(dip_val:$b0;dip_name:'1C 5C'),(dip_val:$a0;dip_name:'1C 6C'),(dip_val:$90;dip_name:'1C 7C'),(dip_val:$0;dip_name:'No Coin'))),()); vendetta_dip_b:array [0..3] of def_dip=( (mask:$3;name:'Lives';number:4;dip:((dip_val:$3;dip_name:'1'),(dip_val:$2;dip_name:'2'),(dip_val:$1;dip_name:'3'),(dip_val:$0;dip_name:'5'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$60;name:'Difficulty';number:4;dip:((dip_val:$60;dip_name:'Easy'),(dip_val:$40;dip_name:'Normal'),(dip_val:$20;dip_name:'Hard'),(dip_val:$0;dip_name:'Very Hard'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Demo Sounds';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); vendetta_dip_c:array [0..1] of def_dip=( (mask:$1;name:'Flip Screen';number:2;dip:((dip_val:$1;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); var tiles_rom,sprite_rom,k053260_rom:pbyte; sound_latch,sprite_colorbase,rom_bank1,video_bank,timer_n:byte; irq_enabled:boolean; layer_colorbase,layerpri:array[0..2] of byte; rom_bank:array[0..27,0..$1fff] of byte; procedure vendetta_cb(layer,bank:word;var code:dword;var color:word;var flags:word;var priority:word); begin code:=code or (((color and $03) shl 8) or ((color and $30) shl 6) or ((color and $0c) shl 10) or (bank shl 14)); color:=layer_colorbase[layer]+((color and $c0) shr 6); end; procedure vendetta_sprite_cb(var code:dword;var color:word;var priority_mask:word); var pri:integer; begin pri:=(color and $03e0) shr 4; // ??????? if (pri<=layerpri[2]) then priority_mask:=0 else if ((pri>layerpri[2]) and (pri<=layerpri[1])) then priority_mask:=1 else if ((pri>layerpri[1]) and (pri<=layerpri[0])) then priority_mask:=2 else priority_mask:=3; color:=sprite_colorbase+(color and $001f); end; procedure update_video_vendetta; var bg_colorbase:byte; sorted_layer:array[0..2] of byte; begin sprite_colorbase:=k053251_0.get_palette_index(K053251_CI1); layer_colorbase[0]:=k053251_0.get_palette_index(K053251_CI2); layer_colorbase[1]:=k053251_0.get_palette_index(K053251_CI3); layer_colorbase[2]:=k053251_0.get_palette_index(K053251_CI4); sorted_layer[0]:=0; layerpri[0]:=k053251_0.get_priority(K053251_CI2); sorted_layer[1]:=1; layerpri[1]:=k053251_0.get_priority(K053251_CI3); sorted_layer[2]:=2; layerpri[2]:=k053251_0.get_priority(K053251_CI4); konami_sortlayers3(@sorted_layer,@layerpri); bg_colorbase:=k053251_0.get_palette_index(K053251_CI0); if k053251_0.dirty_tmap[K053251_CI2] then begin k052109_0.clean_video_buffer_layer(0); k053251_0.dirty_tmap[K053251_CI2]:=false; end; if k053251_0.dirty_tmap[K053251_CI3] then begin k052109_0.clean_video_buffer_layer(1); k053251_0.dirty_tmap[K053251_CI3]:=false; end; if k053251_0.dirty_tmap[K053251_CI4] then begin k052109_0.clean_video_buffer_layer(2); k053251_0.dirty_tmap[K053251_CI4]:=false; end; k052109_0.draw_tiles; k053246_0.k053247_update_sprites; fill_full_screen(4,bg_colorbase*16); k053246_0.k053247_draw_sprites(3); k052109_0.draw_layer(sorted_layer[0],4); k053246_0.k053247_draw_sprites(2); k052109_0.draw_layer(sorted_layer[1],4); k053246_0.k053247_draw_sprites(1); k052109_0.draw_layer(sorted_layer[2],4); k053246_0.k053247_draw_sprites(0); actualiza_trozo_final(112,16,288,224,4); end; procedure eventos_vendetta; begin if event.arcade then begin //P1 if arcade_input.right[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or $1); if arcade_input.left[0] then marcade.in0:=(marcade.in0 and $Fd) else marcade.in0:=(marcade.in0 or $2); if arcade_input.up[0] then marcade.in0:=(marcade.in0 and $fb) else marcade.in0:=(marcade.in0 or $4); if arcade_input.down[0] then marcade.in0:=(marcade.in0 and $F7) else marcade.in0:=(marcade.in0 or $8); if arcade_input.but1[0] then marcade.in0:=(marcade.in0 and $ef) else marcade.in0:=(marcade.in0 or $10); if arcade_input.but0[0] then marcade.in0:=(marcade.in0 and $df) else marcade.in0:=(marcade.in0 or $20); if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $7f) else marcade.in0:=(marcade.in0 or $80); //P2 if arcade_input.right[1] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or $1); if arcade_input.left[1] then marcade.in1:=(marcade.in1 and $Fd) else marcade.in1:=(marcade.in1 or $2); if arcade_input.up[1] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or $4); if arcade_input.down[1] then marcade.in1:=(marcade.in1 and $F7) else marcade.in1:=(marcade.in1 or $8); if arcade_input.but1[1] then marcade.in1:=(marcade.in1 and $ef) else marcade.in1:=(marcade.in1 or $10); if arcade_input.but0[1] then marcade.in1:=(marcade.in1 and $df) else marcade.in1:=(marcade.in1 or $20); if arcade_input.coin[1] then marcade.in1:=(marcade.in1 and $7f) else marcade.in1:=(marcade.in1 or $80); //Service if arcade_input.start[0] then marcade.in2:=(marcade.in2 and $fe) else marcade.in2:=(marcade.in2 or $1); if arcade_input.start[1] then marcade.in2:=(marcade.in2 and $fd) else marcade.in2:=(marcade.in2 or $2); end; end; procedure vendetta_principal; var frame_m,frame_s:single; f:byte; begin init_controls(false,false,false,true); frame_m:=konami_0.tframes; frame_s:=z80_0.tframes; while EmuStatus=EsRuning do begin for f:=0 to $ff do begin //main konami_0.run(frame_m); frame_m:=frame_m+konami_0.tframes-konami_0.contador; //sound z80_0.run(frame_s); frame_s:=frame_s+z80_0.tframes-z80_0.contador; if f=239 then begin if irq_enabled then konami_0.change_irq(HOLD_LINE); update_video_vendetta; end; end; eventos_vendetta; video_sync; end; end; function vendetta_getbyte(direccion:word):byte; begin case direccion of 0..$1fff:vendetta_getbyte:=rom_bank[rom_bank1,direccion]; $2000..$3fff,$8000..$ffff:vendetta_getbyte:=memoria[direccion]; $4000..$4fff:if video_bank=0 then vendetta_getbyte:=k052109_0.read(direccion and $fff) else vendetta_getbyte:=k053246_0.k053247_r(direccion and $fff); $5f80..$5f9f:vendetta_getbyte:=k054000_0.read(direccion and $1f); $5fc0:vendetta_getbyte:=marcade.in0; //p1 $5fc1:vendetta_getbyte:=marcade.in1; //p2 $5fc2:vendetta_getbyte:=$ff; //p3 $5fc3:vendetta_getbyte:=$ff; //p3 $5fd0:vendetta_getbyte:=er5911_do_read+(er5911_ready_read shl 1)+$f4; $5fd1:vendetta_getbyte:=marcade.in2; //service $5fe4:begin z80_0.change_irq(HOLD_LINE); vendetta_getbyte:=0; end; $5fe6..$5fe7:vendetta_getbyte:=k053260_0.main_read(direccion and 1); $5fe8..$5fe9:vendetta_getbyte:=k053246_0.read(direccion and 1); $5fea:vendetta_getbyte:=0; $6000..$6fff:if video_bank=0 then vendetta_getbyte:=k052109_0.read($2000+(direccion and $fff)) else vendetta_getbyte:=buffer_paleta[direccion and $fff]; else vendetta_getbyte:=k052109_0.read(direccion and $3fff); end; end; procedure vendetta_putbyte(direccion:word;valor:byte); procedure cambiar_color(pos:word); var color:tcolor; valor:word; begin valor:=(buffer_paleta[pos*2] shl 8)+buffer_paleta[(pos*2)+1]; color.b:=pal5bit(valor shr 10); color.g:=pal5bit(valor shr 5); color.r:=pal5bit(valor); set_pal_color_alpha(color,pos); k052109_0.clean_video_buffer; end; begin case direccion of 0..$1fff,$8000..$ffff:; //ROM $2000..$3fff:memoria[direccion]:=valor; $4000..$4fff:if video_bank=0 then k052109_0.write(direccion and $fff,valor) else k053246_0.k053247_w(direccion and $fff,valor); $5f80..$5f9f:k054000_0.write(direccion and $1f,valor); $5fa0..$5faf:k053251_0.write(direccion and $f,valor); $5fb0..$5fb7:k053246_0.write(direccion and $7,valor); $5fe0:begin if (valor and $8)<>0 then k052109_0.set_rmrd_line(ASSERT_LINE) else k052109_0.set_rmrd_line(CLEAR_LINE); if (valor and $20)<>0 then k053246_0.set_objcha_line(ASSERT_LINE) else k053246_0.set_objcha_line(CLEAR_LINE); end; $5fe2:begin if valor=$ff then exit; irq_enabled:=((valor shr 6) and 1)<>0; video_bank:=valor and 1; er5911_di_write((valor shr 5) and 1); er5911_cs_write((valor shr 3) and 1); er5911_clk_write((valor shr 4) and 1); end; $5fe4:z80_0.change_irq(HOLD_LINE); $5fe6..$5fe7:k053260_0.main_write(direccion and 1,valor); $6000..$6fff:if video_bank=0 then begin direccion:=direccion and $fff; if ((direccion=$1d80) or (direccion=$1e00) or (direccion=$1f00)) then k052109_0.write(direccion,valor); k052109_0.write(direccion+$2000,valor); end else if buffer_paleta[direccion and $fff]<>valor then begin buffer_paleta[direccion and $fff]:=valor; cambiar_color((direccion and $fff) shr 1); end; else k052109_0.write(direccion and $3fff,valor); end; end; procedure vendetta_bank(valor:byte); begin rom_bank1:=valor and $1f; end; function vendetta_snd_getbyte(direccion:word):byte; begin case direccion of 0..$f7ff:vendetta_snd_getbyte:=mem_snd[direccion]; $f801:vendetta_snd_getbyte:=ym2151_0.status; $fc00..$fc2f:vendetta_snd_getbyte:=k053260_0.read(direccion and $3f); end; end; procedure vendetta_snd_putbyte(direccion:word;valor:byte); begin case direccion of 0..$efff:; //ROM $f000..$f7ff:mem_snd[direccion]:=valor; $f800:ym2151_0.reg(valor); $f801:ym2151_0.write(valor); $fa00:begin z80_0.change_nmi(ASSERT_LINE); timers.enabled(timer_n,true); end; $fc00..$fc2f:k053260_0.write(direccion and $3f,valor); end; end; procedure vendetta_clear_nmi; begin timers.enabled(timer_n,false); z80_0.change_nmi(CLEAR_LINE); end; procedure vendetta_sound_update; begin ym2151_0.update; k053260_0.update; end; //Main procedure reset_vendetta; begin konami_0.reset; z80_0.reset; k052109_0.reset; k053260_0.reset; k053251_0.reset; k054000_0.reset; k053246_0.reset; ym2151_0.reset; reset_audio; marcade.in0:=$ff; marcade.in1:=$ff; marcade.in2:=$ff; sound_latch:=0; rom_bank1:=0; irq_enabled:=false; video_bank:=0; end; procedure cerrar_vendetta; begin if k053260_rom<>nil then freemem(k053260_rom); if sprite_rom<>nil then freemem(sprite_rom); if tiles_rom<>nil then freemem(tiles_rom); k053260_rom:=nil; sprite_rom:=nil; tiles_rom:=nil; end; function iniciar_vendetta:boolean; var temp_mem:array[0..$3ffff] of byte; f:byte; begin llamadas_maquina.close:=cerrar_vendetta; llamadas_maquina.reset:=reset_vendetta; llamadas_maquina.bucle_general:=vendetta_principal; llamadas_maquina.fps_max:=59.17; iniciar_vendetta:=false; //Pantallas para el K052109 screen_init(1,512,256,true); screen_init(2,512,256,true); screen_mod_scroll(2,512,512,511,256,256,255); screen_init(3,512,256,true); screen_mod_scroll(3,512,512,511,256,256,255); screen_init(4,1024,1024,false,true); iniciar_video(288,224,true); iniciar_audio(true); //cargar roms y ponerlas en su sitio... if not(roms_load(@temp_mem,vendetta_rom)) then exit; copymemory(@memoria[$8000],@temp_mem[$38000],$8000); for f:=0 to 27 do copymemory(@rom_bank[f,0],@temp_mem[f*$2000],$2000); //cargar sonido if not(roms_load(@mem_snd,vendetta_sound)) then exit; //Main CPU konami_0:=cpu_konami.create(3000000,256); konami_0.change_ram_calls(vendetta_getbyte,vendetta_putbyte); konami_0.change_set_lines(vendetta_bank); //Sound CPU z80_0:=cpu_z80.create(3579545,256); z80_0.change_ram_calls(vendetta_snd_getbyte,vendetta_snd_putbyte); z80_0.init_sound(vendetta_sound_update); timer_n:=timers.init(z80_0.numero_cpu,90,vendetta_clear_nmi,nil,false); //Sound Chips ym2151_0:=ym2151_chip.create(3579545); getmem(k053260_rom,$100000); if not(roms_load(k053260_rom,vendetta_k053260)) then exit; k053260_0:=tk053260_chip.create(3579545,k053260_rom,$100000,0.70); //Iniciar video layer_colorbase[0]:=0; layer_colorbase[1]:=0; layer_colorbase[2]:=0; layerpri[0]:=0; layerpri[1]:=0; layerpri[2]:=0; sprite_colorbase:=0; //Prioridad k053251_0:=k053251_chip.create; //tiles getmem(tiles_rom,$100000); if not(roms_load32b(tiles_rom,vendetta_tiles)) then exit; k052109_0:=k052109_chip.create(1,2,3,0,vendetta_cb,tiles_rom,$100000); //sprites getmem(sprite_rom,$400000); if not(roms_load64b(sprite_rom,vendetta_sprites)) then exit; k053246_0:=k053246_chip.create(4,vendetta_sprite_cb,sprite_rom,$400000); k053246_0.k053247_start; //eeprom eepromser_init(ER5911,8); if not(roms_load(@temp_mem,vendetta_eeprom)) then exit; eepromser_load_data(@temp_mem,$80); //protection k054000_0:=k054000_chip.create; //DIP marcade.dswa:=$ff; marcade.dswa_val:=@vendetta_dip_a; marcade.dswb:=$5e; marcade.dswb_val:=@vendetta_dip_b; marcade.dswc:=$ff; marcade.dswc_val:=@vendetta_dip_c; //final reset_vendetta; iniciar_vendetta:=true; end; end.
unit UpdateConfigValueUnit; interface uses SysUtils, BaseExampleUnit, EnumsUnit; type TUpdateConfigValue = class(TBaseExample) public function Execute(Key, Value: String): boolean; end; implementation function TUpdateConfigValue.Execute(Key, Value: String): boolean; var ErrorString: String; begin Result := Route4MeManager.User.UpdateConfigValue(Key, Value, ErrorString); WriteLn(''); if (ErrorString = EmptyStr) then begin if Result then WriteLn('UpdateConfigValue successfully') else WriteLn('UpdateConfigValue error'); WriteLn(''); end else WriteLn(Format('UpdateConfigValue error: "%s"', [ErrorString])); end; end.
unit ntvProgressBars; {** * This file is part of the "Mini Library" * * @url http://www.sourceforge.net/projects/minilib * @license modifiedLGPL (modified of http://www.gnu.org/licenses/lgpl.html) * See the file COPYING.MLGPL, included in this distribution, * @author Belal Alhamed <belalhamed at gmail dot com> * @author Zaher Dirkey *} {$mode objfpc}{$H+} interface uses Classes, Messages, Controls, ExtCtrls, SysUtils, Contnrs, Graphics, Forms, LCLType, LCLIntf, LMessages, LCLProc, ntvutils; type TPaintStatus = (psMain, psSub, psAll); TPaintStatusSet = set of TPaintStatus; { TntvProgressBar } TntvProgressBar = class(TCustomControl) private FMin: integer; FMax: integer; FPosition: integer; FProgressColor: TColor; FStep: integer; FShowProgress: boolean; FSubStep: integer; FSubPosition: integer; FSubMax: integer; FSubMin: integer; FPaintStatus: TPaintStatusSet; FSubProgressColor: TColor; FSubHeight: integer; FFrameColor: TColor; procedure SetMax(Value: integer); procedure SetMin(Value: integer); procedure SetPosition(Value: integer); procedure SetProgressColor(const Value: TColor); procedure SetShowProgress(Value: boolean); procedure SetSubMax(Value: integer); procedure SetSubMin(Value: integer); procedure SetSubPosition(Value: integer); procedure SetSubProgressColor(const Value: TColor); procedure SetSubHeight(Value: Integer); function GetSubHeight: integer; //procedure WMNCPaint(var Message: TMessage); message WM_NCPAINT; //procedure WMNCCalcSize(var Message: TWMNCCalcSize); message WM_NCCALCSIZE; //procedure SetBorderStyle(const Value: TItemBorderStyle); procedure SetFrameColor(const Value: TColor); protected procedure DoOnResize; override; procedure CreateParams(var Params: TCreateParams); override; function GetClientRect: TRect; override; function ProgressWidth(APos, AMax, AMin: integer): integer; function ProgressStep: integer; function MainRect: TRect; function SubRect: TRect; function RemainRect: TRect; procedure SetText(const S:string); procedure RedrawBorder(const Clip: HRGN); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure EraseBackground(DC: HDC); override; procedure Paint; override; procedure StepIt; procedure Reset; procedure StepBy(vStep: integer); published property Min: integer read FMin write SetMin default 0; property Max: integer read FMax write SetMax default 100; property Position: integer read FPosition write SetPosition default 0; property Step: integer read FStep write FStep default 1; property SubMin: integer read FSubMin write SetSubMin default 0; property SubMax: integer read FSubMax write SetSubMax default 100; property SubHeight: integer read FSubHeight write SetSubHeight default 0; property SubPosition: integer read FSubPosition write SetSubPosition default 0; property SubStep: integer read FSubStep write FSubStep default 1; property ShowProgress: boolean read FShowProgress write SetShowProgress default True; property ProgressColor: TColor read FProgressColor write SetProgressColor default clNavy; property SubProgressColor: TColor read FSubProgressColor write SetSubProgressColor default clRed; property FrameColor: TColor read FFrameColor write SetFrameColor default clBlack; property Align; property Anchors; property BiDiMode; property ParentBiDiMode; property Color; property Font; property TabOrder; property TabStop; property Visible; property OnContextPopup; property OnDragDrop; property OnDragOver; property OnEndDock; property OnEndDrag; property OnEnter; property OnExit; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnStartDock; property OnStartDrag; end; implementation uses Types; { TntvProgressBar } constructor TntvProgressBar.Create(AOwner: TComponent); begin inherited; ControlStyle := [csCaptureMouse, csClickEvents, csSetCaption, csOpaque, csDoubleClicks]; Width := 150; Height := 16; FMin := 0; FMax := 100; FPosition := 0; FStep := 1; FSubMin := 0; FSubMax := 100; FSubHeight := 0; FSubPosition := 0; FSubStep := 1; //FBorderStyle := ibsLightRaised; FShowProgress := True; FProgressColor := clNavy; FSubProgressColor := clRed; Color := clGray; Font.Color := clWhite; ControlStyle := ControlStyle - [csOpaque]; FPaintStatus := []; //BevelKind := bkSoft; FFrameColor := clBlack; end; procedure TntvProgressBar.CreateParams(var Params: TCreateParams); begin inherited; with Params do begin end; end; destructor TntvProgressBar.Destroy; begin inherited; end; function TntvProgressBar.GetClientRect: TRect; begin Result := inherited GetClientRect; //InflateRect(Result, -1, -1); end; function TntvProgressBar.GetSubHeight: integer; begin if FSubHeight=0 then Result := Round(ClientHeight*0.30) else Result := FSubHeight; end; function TntvProgressBar.MainRect: TRect; begin Result := ClientRect; Result.Right := ProgressWidth (Position, Max, Min); end; procedure TntvProgressBar.Paint; var Tmp: string; aRect: TRect; begin with Canvas do begin if (psSub in FPaintStatus)or(psAll in FPaintStatus) then begin Brush.Color := SubProgressColor; aRect := SubRect; FillRect(aRect); ExcludeClipRect(Canvas, aRect); end; if (psMain in FPaintStatus)or(psAll in FPaintStatus) then begin Brush.Color := FProgressColor; FillRect(MainRect); Brush.Color := Color; FillRect(RemainRect); if ShowProgress and (FPosition <> FMin) then begin Tmp := IntToStr(Round((FPosition - FMin) * 100 / (FMax - FMin))) + ' %'; Canvas.Font.Assign(Self.Font); aRect := ClientRect; Brush.Color := Self.Color; //DrawString(Canvas, Tmp, aRect, [txtMiddle, txtCenter, txtClear]); end; end; FPaintStatus := []; end; end; function TntvProgressBar.ProgressStep: integer; begin Result := ClientWidth div 100; end; function TntvProgressBar.ProgressWidth(APos, AMax, AMin: Integer): integer; begin Result := MulDiv(ClientWidth, (APos - Min), (AMax - AMin)); end; procedure TntvProgressBar.RedrawBorder(const Clip: HRGN); {var DC: HDC; RW: TRect; OldDC: HDC;} begin {if (BorderStyle <> ibsNone) then begin DC := GetWindowDC(Handle); OldDc := Canvas.Handle; Canvas.Handle := DC; try GetWindowRect(Handle, RW); OffsetRect(RW, -RW.Left, -RW.Top); DrawItemFrame(Canvas, BorderStyle, RW, FrameColor); finally ReleaseDC(Handle, dc); Canvas.Handle := OldDC; end; end;} end; function TntvProgressBar.RemainRect: TRect; var w, mw, sw: Integer; begin //SubtractRect(Result, ClientRect, MainRect); Result := ClientRect; mw := ProgressWidth (Position, Max, Min); sw := ProgressWidth (Position, Max, Min); if mw>sw then Inc(Result.Left, mw) else Inc(Result.Left, sw); {Result.Right := ProgressWidth (Position, Max, Min); Result := ClientRect; Result.Right := ProgressWidth (SubPosition, SubMax, SubMin); Result.Top := Result.Bottom-GetSubHeight;} end; procedure TntvProgressBar.Reset; begin Position := 0; end; {procedure TntvProgressBar.SetBorderStyle(const Value: TItemBorderStyle); begin if FBorderStyle <> Value then begin FBorderStyle := Value; Perform(CM_BORDERCHANGED, 0, 0); end; end;} procedure TntvProgressBar.SetFrameColor(const Value: TColor); begin if FFrameColor<>Value then begin FFrameColor := Value; //Perform(CM_BORDERCHANGED, 0, 0); end; end; procedure TntvProgressBar.DoOnResize; begin inherited DoOnResize; SetPosition(Position); end; procedure TntvProgressBar.EraseBackground(DC: HDC); begin FPaintStatus := [psAll]; inherited EraseBackground(DC); end; procedure TntvProgressBar.SetMax(Value: integer); begin if (FMax <> Value) and (Value > FMin) then begin FMax := Value; Invalidate; end; end; procedure TntvProgressBar.SetMin(Value: integer); begin if (FMin <> Value) and (Value < FMax) then begin FMin := Value; Invalidate; end; end; procedure TntvProgressBar.SetPosition(Value: integer); var aVal: Integer; OldWidth, NewWidth: integer; begin if (Value >= Max) then aVal := Max else if (Value <= Min) then aVal := Min else aVal := Value; if FPosition<>aVal then begin OldWidth := ProgressWidth(FPosition, Max, Min); NewWidth := ProgressWidth(aVal, Max, Min); FPosition := aVal; if OldWidth<>NewWidth then begin include(FPaintStatus, psMain); Invalidate; //UpdateWindow(Parent.Handle); //Application.ProcessMessages; //Refresh; //Parent.Refresh; //Invalidate; //Update; //UpdateWindow(Handle); end; end; end; procedure TntvProgressBar.SetProgressColor(const Value: TColor); begin if FProgressColor <> Value then begin FProgressColor := Value; Invalidate; end; end; procedure TntvProgressBar.SetShowProgress(Value: boolean); begin if FShowProgress <> Value then begin FShowProgress := Value; Invalidate; end; end; procedure TntvProgressBar.SetSubHeight(Value: integer); var aVal: Integer; begin if FSubHeight<>Value then begin if Value<=0 then aVal:=0 else if Value>ClientHeight then aVal:=ClientHeight else aVal := Value; FSubHeight := aVal; Invalidate; end; end; procedure TntvProgressBar.SetSubMax(Value: integer); begin if (FSubMax <> Value) and (Value > FSubMin) then begin FSubMax := Value; Invalidate; end; end; procedure TntvProgressBar.SetSubMin(Value: integer); begin if (FSubMin <> Value) and (Value < FSubMax) then begin FSubMin := Value; Invalidate; end; end; procedure TntvProgressBar.SetSubPosition(Value: integer); var R: TRect; aVal: Integer; NeedInvalidate: boolean; OldWidth, NewWidth: integer; begin if (Value > SubMax) then aVal := SubMax else if (Value < SubMin) then aVal := SubMin else aVal := Value; if aVal <> FSubPosition then begin OldWidth := ProgressWidth(FSubPosition, SubMax, SubMin); NewWidth := ProgressWidth(aVal, SubMax, SubMin); FSubPosition := aVal; if OldWidth<>NewWidth then begin NeedInvalidate :=(aVal=SubMin)or(aVal=SubMax); if NeedInvalidate then begin include(FPaintStatus, psAll); Invalidate; end else begin include(FPaintStatus, psSub); R := SubRect; InvalidateRect(Handle, @R, False); end; UpdateWindow(Handle); end; end; end; procedure TntvProgressBar.SetSubProgressColor(const Value: TColor); begin if FSubProgressColor<>Value then begin FSubProgressColor := Value; Invalidate; end; end; procedure TntvProgressBar.SetText(const S: string); begin Exception.Create('not implement yet'); end; procedure TntvProgressBar.StepBy(vStep: integer); begin Position := Position + vStep; end; procedure TntvProgressBar.StepIt; begin Position := Position + FStep; end; function TntvProgressBar.SubRect: TRect; begin Result := ClientRect; Result.Right := ProgressWidth (SubPosition, SubMax, SubMin); Result.Top := Result.Bottom-GetSubHeight; end; {procedure TntvProgressBar.WMNCCalcSize(var Message: TWMNCCalcSize); begin //if BorderStyle<>ibsNone then //InflateRect(Message.CalcSize_Params^.rgrc[0], -1, -1); end;} {procedure TntvProgressBar.WMNCPaint(var Message: TMessage); begin //if BorderStyle<>ibsNone then //RedrawBorder(HRGN(Message.WParam)); end;} end.
unit ufrmSupplier; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ufrmDefault, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters, cxStyles, cxClasses, ActnList, dxBar, ExtCtrls, dxStatusBar, cxContainer, cxEdit, cxTextEdit, StdCtrls, ClientClassesUnit, ClientModule, cxCustomData, cxFilter, cxData, cxDataStorage, DB, cxDBData, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridLevel, cxGridCustomView, cxGrid, Grids, DBGrids, DBClient, Provider, cxPCdxBarPopupMenu, cxPC, cxMemo, ImgList, uModel, cxNavigator, System.Actions, dxBarExtDBItems, cxCheckBox, dxBarBuiltInMenu, System.ImageList, cxBarEditItem, dxBarExtItems, Vcl.Menus, cxButtons, Vcl.ComCtrls, uInterface, cxMaskEdit, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBExtLookupComboBox, uSupplier, uAccount; type TfrmSupplier = class(TfrmDefault, IForm) lblKode: TLabel; lblNama: TLabel; lblAlamat: TLabel; edKode: TcxTextEdit; edNama: TcxTextEdit; memAlamt: TcxMemo; grpRole: TGroupBox; chkSupplier: TCheckBox; chkPembeli: TCheckBox; chkSalesman: TCheckBox; edAkunHutang: TcxTextEdit; cbbAkunHutang: TcxExtLookupComboBox; lblParent: TLabel; lblAkunPiutang: TLabel; cbbAkunPiutang: TcxExtLookupComboBox; edAkunPiutang: TcxTextEdit; lblKelas: TLabel; edKelas: TcxTextEdit; procedure FormCreate(Sender: TObject); procedure ActionBaruExecute(Sender: TObject); procedure ActionHapusExecute(Sender: TObject); procedure ActionRefreshExecute(Sender: TObject); procedure ActionSimpanExecute(Sender: TObject); procedure cxGridDBTableOverviewCellDblClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); procedure cxGridDBTableSupplierEditing(Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem; var AAllow: Boolean); procedure cbbAkunHutangPropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); procedure cbbAkunPiutangPropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); private cdsAccount: tclientDataSet; FSupplier: TSupplier; function GetSupplier: TSupplier; procedure InisialisasiCBBAccount; // FSupplier: TSupplier; // function GetSupplier: TSupplier; { Private declarations } public function LoadData(AID : String): Boolean; stdcall; property Supplier: TSupplier read GetSupplier write FSupplier; // property Supplier: TSupplier read GetSupplier write FSupplier; { Public declarations } end; var frmSupplier: TfrmSupplier; implementation uses uDBUtils, uAppUtils; {$R *.dfm} procedure TfrmSupplier.FormCreate(Sender: TObject); begin inherited; InisialisasiCBBAccount; ActionBaruExecute(Sender); end; procedure TfrmSupplier.ActionBaruExecute(Sender: TObject); //var // sAkunHutangSupplier: string; // sAkunPiutangSupplier: string; begin inherited; LoadData(''); cxPCData.ActivePageIndex := 1; cbbAkunHutang.EditValue := TAppUtils.BacaRegistry('AKUN_HUTANG_SUPPLIER'); cbbAkunPiutang.EditValue := TAppUtils.BacaRegistry('AKUN_PIUTANG_SUPPLIER'); cdsAccount.Filtered := False; cdsAccount.Filter := ' id = ' + QuotedStr(TAppUtils.BacaRegistry('AKUN_HUTANG_SUPPLIER')); cdsAccount.Filtered := True; edAkunHutang.Text := cdsAccount.FieldByName('nama').AsString; cdsAccount.Filtered := False; cdsAccount.Filter := ' id = ' + QuotedStr(TAppUtils.BacaRegistry('AKUN_PIUTANG_SUPPLIER')); cdsAccount.Filtered := True; edAkunPiutang.Text := cdsAccount.FieldByName('nama').AsString; cdsAccount.Filtered := False; end; procedure TfrmSupplier.ActionHapusExecute(Sender: TObject); begin inherited; if not TAppUtils.Confirm('Anda yakin akan menghapus Data ?') then Exit; with TServerSupplierClient.Create(ClientDataModule.DSRestConnection, False) do begin try if Delete(Supplier) then begin ActionBaruExecute(Sender); ActionRefreshExecute(Sender); end; finally FreeAndNil(FSupplier); Free; end; end; end; procedure TfrmSupplier.ActionRefreshExecute(Sender: TObject); var sSQL: string; begin inherited; sSQL := 'select * from vBusinessPartner order by nama'; cxGridDBTableOverview.SetDataset(sSQL, True); cxGridDBTableOverview.SetVisibleColumns(['ID'], False); cxGridDBTableOverview.ApplyBestFit(); end; procedure TfrmSupplier.ActionSimpanExecute(Sender: TObject); begin inherited; if not ValidateEmptyCtrl([1]) then Exit; if (not chkSupplier.Checked) and (not chkPembeli.Checked) and (not chkSalesman.Checked) then begin TAppUtils.Warning('Role Belum Diset'); Exit; end; with TServerSupplierClient.Create(ClientDataModule.DSRestConnection, False) do begin try Supplier.Kode := UpperCase(edKode.Text); Supplier.Nama := UpperCase(edNama.Text); Supplier.Kelas := UpperCase(edKelas.Text); Supplier.Alamat := memAlamt.Text; Supplier.IsSupplier := TAppUtils.BoolToInt(chkSupplier.Checked); Supplier.IsPembeli := TAppUtils.BoolToInt(chkPembeli.Checked); Supplier.IsSalesman := TAppUtils.BoolToInt(chkSalesman.Checked); Supplier.AkunHutang := TAccount.CreateID(cbbAkunHutang.EditValue); Supplier.AkunPiutang:= TAccount.CreateID(cbbAkunPiutang.EditValue); if Save(Supplier) then begin TAppUtils.TulisRegistry('AKUN_HUTANG_SUPPLIER',cbbAkunHutang.EditValue); TAppUtils.TulisRegistry('AKUN_PIUTANG_SUPPLIER',cbbAkunPiutang.EditValue); ActionBaruExecute(Sender); ActionRefreshExecute(Sender); end; finally FreeAndNil(FSupplier); Free; end; end; end; procedure TfrmSupplier.cbbAkunHutangPropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); begin inherited; edAkunHutang.Text := cdsAccount.FieldByName('nama').AsString; end; procedure TfrmSupplier.cbbAkunPiutangPropertiesValidate(Sender: TObject; var DisplayValue: Variant; var ErrorText: TCaption; var Error: Boolean); begin inherited; edAkunPiutang.Text := cdsAccount.FieldByName('nama').AsString; end; procedure TfrmSupplier.cxGridDBTableOverviewCellDblClick(Sender: TcxCustomGridTableView; ACellViewInfo: TcxGridTableDataCellViewInfo; AButton: TMouseButton; AShift: TShiftState; var AHandled: Boolean); begin inherited; if LoadData(cxGridDBTableOverview.DS.FieldByName('ID').AsString) then cxPCData.ActivePageIndex := 1; end; procedure TfrmSupplier.cxGridDBTableSupplierEditing(Sender: TcxCustomGridTableView; AItem: TcxCustomGridTableItem; var AAllow: Boolean); begin inherited; AAllow := False; end; function TfrmSupplier.GetSupplier: TSupplier; begin if FSupplier = nil then FSupplier := TSupplier.Create; Result := FSupplier; end; procedure TfrmSupplier.InisialisasiCBBAccount; begin cdsAccount := TDBUtils.OpenDataset('Select ID,Kode,Nama' + ' From TAccount' + ' where isakuntransaksi = 1' + ' order by kode '); cbbAkunHutang.Properties.LoadFromCDS(cdsAccount,'ID','Kode',['ID'],Self); cbbAkunHutang.Properties.SetMultiPurposeLookup; cbbAkunPiutang.Properties.LoadFromCDS(cdsAccount,'ID','Kode',['ID'],Self); cbbAkunPiutang.Properties.SetMultiPurposeLookup; end; function TfrmSupplier.LoadData(AID : String): Boolean; begin Result := False; FreeAndNil(FSupplier); ClearByTag([0,1]); try FSupplier := ClientDataModule.ServerSupplierClient.Retrieve(AID); if FSupplier =nil then Exit; if FSupplier.ID = '' then Exit; edKode.Text := FSupplier.Kode; edNama.Text := FSupplier.Nama; edKelas.Text := FSupplier.Kelas; memAlamt.Text := FSupplier.Alamat; chkSupplier.Checked := FSupplier.IsSupplier =1; chkPembeli.Checked := FSupplier.IsPembeli =1; chkSalesman.Checked := FSupplier.IsSalesman =1; try cbbAkunHutang.EditValue := FSupplier.AkunHutang.ID; cdsAccount.Filtered := False; cdsAccount.Filter := ' id = ' + QuotedStr(FSupplier.AkunHutang.ID); cdsAccount.Filtered := True; edAkunHutang.Text := cdsAccount.FieldByName('nama').AsString; cbbAkunPiutang.EditValue := FSupplier.AkunPiutang.ID; cdsAccount.Filtered := False; cdsAccount.Filter := ' id = ' + QuotedStr(FSupplier.AkunPiutang.ID); cdsAccount.Filtered := True; edAkunPiutang.Text := cdsAccount.FieldByName('nama').AsString; finally cdsAccount.Filtered := False; end; except raise end; Result := True; end; end.
unit ListAnalizeKeywordsPack; {* Набор слов словаря для доступа к экземплярам контролов формы ListAnalize } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\List\Forms\ListAnalizeKeywordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "ListAnalizeKeywordsPack" MUID: (4E36959002CA_Pack) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3IntfUses ; {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL) implementation {$If NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL)} uses l3ImplUses , ListAnalize_Form , tfwControlString , TtfwClassRef_Proxy , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *4E36959002CA_Packimpl_uses* //#UC END# *4E36959002CA_Packimpl_uses* ; type Tkw_Form_ListAnalize = {final} class(TtfwControlString) {* Слово словаря для идентификатора формы ListAnalize ---- *Пример использования*: [code]форма::ListAnalize TryFocus ASSERT[code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Form_ListAnalize function Tkw_Form_ListAnalize.GetString: AnsiString; begin Result := 'ListAnalizeForm'; end;//Tkw_Form_ListAnalize.GetString class procedure Tkw_Form_ListAnalize.RegisterInEngine; begin inherited; TtfwClassRef.Register(TListAnalizeForm); end;//Tkw_Form_ListAnalize.RegisterInEngine class function Tkw_Form_ListAnalize.GetWordNameForRegister: AnsiString; begin Result := 'форма::ListAnalize'; end;//Tkw_Form_ListAnalize.GetWordNameForRegister initialization Tkw_Form_ListAnalize.RegisterInEngine; {* Регистрация Tkw_Form_ListAnalize } TtfwTypeRegistrator.RegisterType(TypeInfo(TListAnalizeForm)); {* Регистрация типа TListAnalizeForm } {$IfEnd} // NOT Defined(Admin) AND NOT Defined(Monitorings) AND NOT Defined(NoScripts) AND NOT Defined(NoVCL) end.
unit ResequenceRouteDestinationsUnit; interface uses SysUtils, BaseOptimizationExampleUnit, DataObjectUnit; type TResequenceRouteDestinations = class(TBaseOptimizationExample) public procedure Execute(Route: TDataObjectRoute); end; implementation uses AddressUnit, AddressesOrderInfoUnit; procedure TResequenceRouteDestinations.Execute(Route: TDataObjectRoute); var AddressesOrderInfo: TAddressesOrderInfo; Address: TAddress; AddressInfo: TAddressInfo; i: integer; SequenceNo: integer; ErrorString: String; NewRoute: TDataObjectRoute; begin if (Length(Route.Addresses) < 3) then begin WriteLn(Format('ResequenceRouteDestinations error: "%s"', ['Route.Addresses.Length < 3. Number of addresses should be >= 3'])); Exit; end; // Switch 2 addresses after departure address: AddressesOrderInfo := TAddressesOrderInfo.Create(Route.RouteID); try for i := 0 to Length(Route.Addresses) - 1 do begin Address := Route.Addresses[i]; SequenceNo := i; if (i = 1) then SequenceNo := 2 else if (i = 2) then SequenceNo := 1; AddressInfo := TAddressInfo.Create; AddressInfo.DestinationId := Address.RouteDestinationId.Value; AddressInfo.SequenceNo := SequenceNo; AddressInfo.IsDepot := (AddressInfo.SequenceNo = 0); AddressesOrderInfo.AddAddress(AddressInfo); end; NewRoute := Route4MeManager.Route.Resequence(AddressesOrderInfo, ErrorString); try PrintExampleOptimizationResult( 'ResequenceRouteDestinations, switch 2 addresses.', NewRoute, ErrorString); WriteLn(''); finally FreeAndNil(NewRoute); end; finally FreeAndNil(AddressesOrderInfo); end; end; end.
unit ContextSearchSupportUnit; // Модуль: "w:\garant6x\implementation\Garant\tie\Garant\GblAdapterLib\ContextSearchSupportUnit.pas" // Стереотип: "Interfaces" // Элемент модели: "ContextSearchSupport" MUID: (456FED4903D8) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface uses l3IntfUses ; type THighlightPosition = record {* Позиции для подсветки найденных слов. } start: Cardinal; {* начало выделения } finish: Cardinal; {* конец выделения } end;//THighlightPosition IHighlightPositionList = array of THighlightPosition; {* Список позиций для подсветки. } TContextSearchResult = record {* Результат поиска по контексту. } item_index: Cardinal; {* Индекс найденного элемента. } positions: ; {* позиции, найденные в результате поиска } end;//TContextSearchResult TSearchStatus = ( {* Зона поиска. } SS_GLOBAL {* Поиск по всему объекту. } , SS_CURENT {* Поиск от текущего элемента. } );//TSearchStatus TSearchDirection = ( {* Направление поиска. } SD_UP {* Поис вверх. } , SD_DOWN {* Поиск вниз. } );//TSearchDirection TSearchMode = record {* Перечислимый тип, определяющий способ поиска в линейных структурах (списках, текстах и т.п.). Сочетание ss_Global + sd_Up - поиск с конца вверх. Сочетание ss_Global + sd_Down - поиск сначала вниз. Сочетание c ss_Current - поиск от текущего элемента вверх или вниз. } status: TSearchStatus; {* результат поиска } direction: TSearchDirection; {* направление поиска } end;//TSearchMode implementation uses l3ImplUses ; end.
inherited dmTabelaIR: TdmTabelaIR OldCreateOrder = True inherited qryManutencao: TIBCQuery SQLInsert.Strings = ( 'INSERT INTO STWOPETTBIR' ' (CONTROLE, ALIQ_BASE, VLR_DEPEND, TETO_INSS, VLR_ISENTO, FAIXA' + '_1, FAIXA_2, FAIXA_3, FAIXA_4, FAIXA_5, DEDUCAO_1, DEDUCAO_2, DE' + 'DUCAO_3, DEDUCAO_4, DEDUCAO_5, ALIQ_1, ALIQ_2, ALIQ_3, ALIQ_4, A' + 'LIQ_5, VLR_MINIR, DT_ALTERACAO, OPERADOR)' 'VALUES' ' (:CONTROLE, :ALIQ_BASE, :VLR_DEPEND, :TETO_INSS, :VLR_ISENTO, ' + ':FAIXA_1, :FAIXA_2, :FAIXA_3, :FAIXA_4, :FAIXA_5, :DEDUCAO_1, :D' + 'EDUCAO_2, :DEDUCAO_3, :DEDUCAO_4, :DEDUCAO_5, :ALIQ_1, :ALIQ_2, ' + ':ALIQ_3, :ALIQ_4, :ALIQ_5, :VLR_MINIR, :DT_ALTERACAO, :OPERADOR)') SQLDelete.Strings = ( 'DELETE FROM STWOPETTBIR' 'WHERE' ' CONTROLE = :Old_CONTROLE') SQLUpdate.Strings = ( 'UPDATE STWOPETTBIR' 'SET' ' CONTROLE = :CONTROLE, ALIQ_BASE = :ALIQ_BASE, VLR_DEPEND = :VL' + 'R_DEPEND, TETO_INSS = :TETO_INSS, VLR_ISENTO = :VLR_ISENTO, FAIX' + 'A_1 = :FAIXA_1, FAIXA_2 = :FAIXA_2, FAIXA_3 = :FAIXA_3, FAIXA_4 ' + '= :FAIXA_4, FAIXA_5 = :FAIXA_5, DEDUCAO_1 = :DEDUCAO_1, DEDUCAO_' + '2 = :DEDUCAO_2, DEDUCAO_3 = :DEDUCAO_3, DEDUCAO_4 = :DEDUCAO_4, ' + 'DEDUCAO_5 = :DEDUCAO_5, ALIQ_1 = :ALIQ_1, ALIQ_2 = :ALIQ_2, ALIQ' + '_3 = :ALIQ_3, ALIQ_4 = :ALIQ_4, ALIQ_5 = :ALIQ_5, VLR_MINIR = :V' + 'LR_MINIR, DT_ALTERACAO = :DT_ALTERACAO, OPERADOR = :OPERADOR' 'WHERE' ' CONTROLE = :Old_CONTROLE') SQLRefresh.Strings = ( 'SELECT CONTROLE, ALIQ_BASE, VLR_DEPEND, TETO_INSS, VLR_ISENTO, F' + 'AIXA_1, FAIXA_2, FAIXA_3, FAIXA_4, FAIXA_5, DEDUCAO_1, DEDUCAO_2' + ', DEDUCAO_3, DEDUCAO_4, DEDUCAO_5, ALIQ_1, ALIQ_2, ALIQ_3, ALIQ_' + '4, ALIQ_5, VLR_MINIR, DT_ALTERACAO, OPERADOR FROM STWOPETTBIR' 'WHERE' ' CONTROLE = :Old_CONTROLE') SQLLock.Strings = ( 'SELECT NULL FROM STWOPETTBIR' 'WHERE' 'CONTROLE = :Old_CONTROLE' 'FOR UPDATE WITH LOCK') SQL.Strings = ( 'SELECT * FROM STWOPETTBIR') object qryManutencaoCONTROLE: TStringField FieldName = 'CONTROLE' Required = True Size = 1 end object qryManutencaoALIQ_BASE: TFloatField FieldName = 'ALIQ_BASE' end object qryManutencaoVLR_DEPEND: TFloatField FieldName = 'VLR_DEPEND' end object qryManutencaoTETO_INSS: TFloatField FieldName = 'TETO_INSS' end object qryManutencaoVLR_ISENTO: TFloatField FieldName = 'VLR_ISENTO' end object qryManutencaoFAIXA_1: TFloatField FieldName = 'FAIXA_1' end object qryManutencaoFAIXA_2: TFloatField FieldName = 'FAIXA_2' end object qryManutencaoFAIXA_3: TFloatField FieldName = 'FAIXA_3' end object qryManutencaoFAIXA_4: TFloatField FieldName = 'FAIXA_4' end object qryManutencaoFAIXA_5: TFloatField FieldName = 'FAIXA_5' end object qryManutencaoDEDUCAO_1: TFloatField FieldName = 'DEDUCAO_1' end object qryManutencaoDEDUCAO_2: TFloatField FieldName = 'DEDUCAO_2' end object qryManutencaoDEDUCAO_3: TFloatField FieldName = 'DEDUCAO_3' end object qryManutencaoDEDUCAO_4: TFloatField FieldName = 'DEDUCAO_4' end object qryManutencaoDEDUCAO_5: TFloatField FieldName = 'DEDUCAO_5' end object qryManutencaoALIQ_1: TFloatField FieldName = 'ALIQ_1' end object qryManutencaoALIQ_2: TFloatField FieldName = 'ALIQ_2' end object qryManutencaoALIQ_3: TFloatField FieldName = 'ALIQ_3' end object qryManutencaoALIQ_4: TFloatField FieldName = 'ALIQ_4' end object qryManutencaoALIQ_5: TFloatField FieldName = 'ALIQ_5' end object qryManutencaoVLR_MINIR: TFloatField FieldName = 'VLR_MINIR' end object qryManutencaoDT_ALTERACAO: TDateTimeField FieldName = 'DT_ALTERACAO' end object qryManutencaoOPERADOR: TStringField FieldName = 'OPERADOR' end end inherited qryLocalizacao: TIBCQuery SQL.Strings = ( 'SELECT * FROM STWOPETTBIR') object qryLocalizacaoCONTROLE: TStringField FieldName = 'CONTROLE' Required = True Size = 1 end object qryLocalizacaoALIQ_BASE: TFloatField FieldName = 'ALIQ_BASE' end object qryLocalizacaoVLR_DEPEND: TFloatField FieldName = 'VLR_DEPEND' end object qryLocalizacaoTETO_INSS: TFloatField FieldName = 'TETO_INSS' end object qryLocalizacaoVLR_ISENTO: TFloatField FieldName = 'VLR_ISENTO' end object qryLocalizacaoFAIXA_1: TFloatField FieldName = 'FAIXA_1' end object qryLocalizacaoFAIXA_2: TFloatField FieldName = 'FAIXA_2' end object qryLocalizacaoFAIXA_3: TFloatField FieldName = 'FAIXA_3' end object qryLocalizacaoFAIXA_4: TFloatField FieldName = 'FAIXA_4' end object qryLocalizacaoFAIXA_5: TFloatField FieldName = 'FAIXA_5' end object qryLocalizacaoDEDUCAO_1: TFloatField FieldName = 'DEDUCAO_1' end object qryLocalizacaoDEDUCAO_2: TFloatField FieldName = 'DEDUCAO_2' end object qryLocalizacaoDEDUCAO_3: TFloatField FieldName = 'DEDUCAO_3' end object qryLocalizacaoDEDUCAO_4: TFloatField FieldName = 'DEDUCAO_4' end object qryLocalizacaoDEDUCAO_5: TFloatField FieldName = 'DEDUCAO_5' end object qryLocalizacaoALIQ_1: TFloatField FieldName = 'ALIQ_1' end object qryLocalizacaoALIQ_2: TFloatField FieldName = 'ALIQ_2' end object qryLocalizacaoALIQ_3: TFloatField FieldName = 'ALIQ_3' end object qryLocalizacaoALIQ_4: TFloatField FieldName = 'ALIQ_4' end object qryLocalizacaoALIQ_5: TFloatField FieldName = 'ALIQ_5' end object qryLocalizacaoVLR_MINIR: TFloatField FieldName = 'VLR_MINIR' end object qryLocalizacaoDT_ALTERACAO: TDateTimeField FieldName = 'DT_ALTERACAO' end object qryLocalizacaoOPERADOR: TStringField FieldName = 'OPERADOR' end end inherited updManutencao: TIBCUpdateSQL InsertSQL.Strings = ( 'INSERT INTO STWOPETTBIR' ' (CONTROLE, ALIQ_BASE, VLR_DEPEND, TETO_INSS, VLR_ISENTO, FAIXA' + '_1, FAIXA_2, FAIXA_3, FAIXA_4, FAIXA_5, DEDUCAO_1, DEDUCAO_2, DE' + 'DUCAO_3, DEDUCAO_4, DEDUCAO_5, ALIQ_1, ALIQ_2, ALIQ_3, ALIQ_4, A' + 'LIQ_5, VLR_MINIR, DT_ALTERACAO, OPERADOR)' 'VALUES' ' (:CONTROLE, :ALIQ_BASE, :VLR_DEPEND, :TETO_INSS, :VLR_ISENTO, ' + ':FAIXA_1, :FAIXA_2, :FAIXA_3, :FAIXA_4, :FAIXA_5, :DEDUCAO_1, :D' + 'EDUCAO_2, :DEDUCAO_3, :DEDUCAO_4, :DEDUCAO_5, :ALIQ_1, :ALIQ_2, ' + ':ALIQ_3, :ALIQ_4, :ALIQ_5, :VLR_MINIR, :DT_ALTERACAO, :OPERADOR)') DeleteSQL.Strings = ( 'DELETE FROM STWOPETTBIR' 'WHERE' ' CONTROLE = :Old_CONTROLE') ModifySQL.Strings = ( 'UPDATE STWOPETTBIR' 'SET' ' CONTROLE = :CONTROLE, ALIQ_BASE = :ALIQ_BASE, VLR_DEPEND = :VL' + 'R_DEPEND, TETO_INSS = :TETO_INSS, VLR_ISENTO = :VLR_ISENTO, FAIX' + 'A_1 = :FAIXA_1, FAIXA_2 = :FAIXA_2, FAIXA_3 = :FAIXA_3, FAIXA_4 ' + '= :FAIXA_4, FAIXA_5 = :FAIXA_5, DEDUCAO_1 = :DEDUCAO_1, DEDUCAO_' + '2 = :DEDUCAO_2, DEDUCAO_3 = :DEDUCAO_3, DEDUCAO_4 = :DEDUCAO_4, ' + 'DEDUCAO_5 = :DEDUCAO_5, ALIQ_1 = :ALIQ_1, ALIQ_2 = :ALIQ_2, ALIQ' + '_3 = :ALIQ_3, ALIQ_4 = :ALIQ_4, ALIQ_5 = :ALIQ_5, VLR_MINIR = :V' + 'LR_MINIR, DT_ALTERACAO = :DT_ALTERACAO, OPERADOR = :OPERADOR' 'WHERE' ' CONTROLE = :Old_CONTROLE') RefreshSQL.Strings = ( 'SELECT CONTROLE, ALIQ_BASE, VLR_DEPEND, TETO_INSS, VLR_ISENTO, F' + 'AIXA_1, FAIXA_2, FAIXA_3, FAIXA_4, FAIXA_5, DEDUCAO_1, DEDUCAO_2' + ', DEDUCAO_3, DEDUCAO_4, DEDUCAO_5, ALIQ_1, ALIQ_2, ALIQ_3, ALIQ_' + '4, ALIQ_5, VLR_MINIR, DT_ALTERACAO, OPERADOR FROM STWOPETTBIR' 'WHERE' ' CONTROLE = :Old_CONTROLE') end end
unit GX_ProofreaderCorrection; {$I GX_CondDefine.inc} interface uses GX_ProofreaderData, GX_EditorChangeServices; type IAutoTypeWriterNotifier = interface(IGxEditorNotification) ['{D66A2AD2-27F4-11D4-A87C-000000000000}'] procedure Detach; end; function GetNewAutoTypeWriterNotifier(const ProofreaderData: TProofreaderData): IAutoTypeWriterNotifier; implementation uses {$IFOPT D+} GX_DbugIntf, {$ENDIF} SysUtils, Classes, ToolsAPI, GX_OtaUtils, GX_GenericUtils, GX_ProofreaderUtils, GX_EditorFormServices, GX_KibitzComp, GX_IdeUtils, StrUtils; type IEditorPositionInformation = interface(IUnknown) ['{35CA9CB1-33E2-11D4-A8A7-000000000000}'] function GetBufferCharIndex: Longint; function GetCharPos: TOTACharPos; function GetCursorPos: TOTAEditPos; function GetEditView: IOTAEditView; function GetRelativePlacement: Boolean; function GetRelativePosition: TOTAEditPos; procedure SetBufferCharIndex(const Value: Longint); procedure SetCharPos(const Value: TOTACharPos); procedure SetCursorPos(const Value: TOTAEditPos); procedure SetRelativePlacement(const Value: Boolean); procedure SetRelativePosition(const Value: TOTAEditPos); property EditView: IOTAEditView read GetEditView; property CursorPos: TOTAEditPos read GetCursorPos write SetCursorPos; property CharPos: TOTACharPos read GetCharPos write SetCharPos; property BufferCharIndex: Longint read GetBufferCharIndex write SetBufferCharIndex; property RelativePlacement: Boolean read GetRelativePlacement write SetRelativePlacement; property RelativePosition: TOTAEditPos read GetRelativePosition write SetRelativePosition; end; TEditorPositionInformation = class(TInterfacedObject, IEditorPositionInformation) private FEditView: IOTAEditView; FCursorPos: TOTAEditPos; FCharPos: TOTACharPos; FBufferCharIndex: Longint; FRelativePlacement: Boolean; FRelativePosition: TOTAEditPos; function GetBufferCharIndex: Longint; function GetCharPos: TOTACharPos; function GetCursorPos: TOTAEditPos; function GetEditView: IOTAEditView; function GetRelativePlacement: Boolean; function GetRelativePosition: TOTAEditPos; procedure SetBufferCharIndex(const Value: Longint); procedure SetCharPos(const Value: TOTACharPos); procedure SetCursorPos(const Value: TOTAEditPos); procedure SetRelativePlacement(const Value: Boolean); procedure SetRelativePosition(const Value: TOTAEditPos); public constructor Create(const EditView: IOTAEditView); destructor Destroy; override; end; type TAutoTypeWriterNotifier = class(TNotifierObject, IGxEditorNotification, IAutoTypeWriterNotifier) private FChangeServiceNotifierIndex: Integer; FProofreaderData: TProofreaderData; private // When the proofreader corrects text it will // cause another editor notification message // to be sent. This might result in re-entrancy. // The FModifyingSelf Boolean flag prevents the // re-entrancy problem by exiting if True. FModifyingSelf: Boolean; // procedure AppendHistory(const CorrectionKind: TCorrectionKind; const SourceLanguage: TReplacementSource; const InfoString, OriginalText: string); procedure AppendAutoCorrectHistory(const SourceLanguage: TReplacementSource; const FromString, ToString: string); procedure AppendWordHistory(const SourceLanguage: TReplacementSource; const FromString, ToString: string); procedure AppendKibitzHistory(const SourceLanguage: TReplacementSource; const FromString, ToString: string); // procedure BeepOnDemand; function DetermineReplacementSource(const Element: Integer; const SyntaxHighlighter: TGXSyntaxHighlighter; var Source: TReplacementSource): Boolean; private function PerformDictionaryReplacement(const SourceEditor: IOTASourceEditor; const EditorPositionInformation: IEditorPositionInformation; const ReplacementSourceTable: TReplacementSource; const TrailingCharacters, SourceString: string): Boolean; function PerformKibitzReplacement(const SourceEditor: IOTASourceEditor; const EditorPositionInformation: IEditorPositionInformation; const ReplacementSourceTable: TReplacementSource; const TrailingCharacters, SourceString, OriginalSourceString: string): Boolean; function PerformReplacementAtEnd(const SourceEditor: IOTASourceEditor; const EditorPositionInformation: IEditorPositionInformation; const ReplacementSourceTable: TReplacementSource; const TrailingCharacters, SourceString: string): Boolean; function PerformReplacementAtBeginning(const SourceEditor: IOTASourceEditor; const EditorPositionInformation: IEditorPositionInformation; const ReplacementSourceTable: TReplacementSource; const SourceString: string): Boolean; function SetupProofing(const SourceEditor: IOTASourceEditor; var EditorPositionInformation: IEditorPositionInformation; var ReplacementSourceTable: TReplacementSource; var SourceString: string): Boolean; protected // IGxEditorNotification procedure NewModuleOpened(const Module: IOTAModule); procedure SourceEditorModified(const SourceEditor: IOTASourceEditor); procedure FormEditorModified(const FormEditor: IOTAFormEditor); procedure ComponentRenamed(const FormEditor: IOTAFormEditor; Component: IOTAComponent; const OldName, NewName: string); function EditorKeyPressed(const SourceEditor: IOTASourceEditor; CharCode: Word; KeyData: Integer): Boolean; function GetIndex: Integer; protected procedure Attach; public constructor Create(const Client: TProofreaderData); destructor Destroy; override; procedure Detach; end; function GetNewAutoTypeWriterNotifier(const ProofreaderData: TProofreaderData): IAutoTypeWriterNotifier; begin Result := TAutoTypeWriterNotifier.Create(ProofreaderData) as IAutoTypeWriterNotifier; end; { TAutoTypeWriterNotifier} constructor TAutoTypeWriterNotifier.Create(const Client: TProofreaderData); begin inherited Create; FProofreaderData := Client; FChangeServiceNotifierIndex := -1; Attach; end; destructor TAutoTypeWriterNotifier.Destroy; begin Detach; inherited Destroy; end; function TAutoTypeWriterNotifier.DetermineReplacementSource(const Element: Integer; const SyntaxHighlighter: TGXSyntaxHighlighter; var Source: TReplacementSource): Boolean; const shsSource = [atWhiteSpace, atReservedWord, atIdentifier, atSymbol, atNumber, atFloat, atOctal, atHex, atCharacter, atIllegal, SyntaxOff]; begin Result := True; if (SyntaxHighlighter = gxpPAS) and (Element in shsSource) then Source := rtPasSrc else if (SyntaxHighlighter = gxpCPP) and (Element in shsSource) then Source := rtCPPSrc else if (SyntaxHighlighter = gxpCPP) and (Element in [atPreproc]) then Source := rtPreproc else if (SyntaxHighlighter = gxpSQL) and (Element in shsSource) then Source := rtSQLSrc else if (SyntaxHighlighter = gxpCS) and (Element in shsSource) then Source := rtCSSrc else if Element in [atAssembler] then Source := rtAssembler else if Element in [atString] then Source := rtString else if Element in [atComment] then Source := rtComment else Result := False end; procedure TAutoTypeWriterNotifier.AppendHistory(const CorrectionKind: TCorrectionKind; const SourceLanguage: TReplacementSource; const InfoString, OriginalText: string); var Correction: TCorrectionItem; begin try Correction := TCorrectionItem.Create; try Correction.CorrectionKind := CorrectionKind; Correction.SourceLanguage := SourceLanguage; Correction.OriginalText := OriginalText; Correction.InfoString := InfoString; Correction.Time := Now; except on E: Exception do begin FreeAndNil(Correction); end; end; FProofreaderData.History.Add(Correction); except on E: Exception do begin // Swallow exceptions end; end; end; procedure TAutoTypeWriterNotifier.AppendAutoCorrectHistory(const SourceLanguage: TReplacementSource; const FromString, ToString: string); begin AppendHistory(ckAutoCorrection, SourceLanguage, Format('AutoCorrect: "%s" --> "%s"', [FromString, ToString]), FromString); end; procedure TAutoTypeWriterNotifier.AppendWordHistory(const SourceLanguage: TReplacementSource; const FromString, ToString: string); begin AppendHistory(ckWord, SourceLanguage, Format('Dictionary Word: "%s" --> "%s"', [FromString, ToString]), FromString); end; procedure TAutoTypeWriterNotifier.AppendKibitzHistory(const SourceLanguage: TReplacementSource; const FromString, ToString: string); begin AppendHistory(ckWord, SourceLanguage, Format('Compiler Correct: "%s" --> "%s"', [FromString, ToString]), FromString); end; procedure TAutoTypeWriterNotifier.BeepOnDemand; begin if FProofreaderData.BeepOnReplace then Beep; end; function InternalNeedsReplacement(const ReplaceItem: TReplacementItem; const ReplaceString: string; Beginning: Boolean): Boolean; var PartialReplaceString: string; CharIndex: Integer; PrevCharIsIdent: Boolean; begin if ReplaceItem = nil then begin Result := False; Exit; end; PartialReplaceString := Copy(ReplaceString, Length(ReplaceString) - Length(ReplaceItem.Replace) + 1, Length(ReplaceItem.Replace)); Result := (AnsiCompareStr(ReplaceItem.Replace, PartialReplaceString) <> 0) or ((PartialReplaceString = '') and (ReplaceItem.Replace = '')); // Allow replace with nothing CharIndex := Length(ReplaceString) - Length(ReplaceItem.Typed); Assert(CharIndex >= 0); PrevCharIsIdent := (CharIndex > 0) and IsCharIdentifier(ReplaceString[CharIndex]); if Beginning then Result := Result and ((ReplaceItem.Where = wrAnywhere) or (ReplaceItem.Where = wrWordBegin) and (not PrevCharIsIdent)) else Result := Result and ((ReplaceItem.Where = wrWordEnd) or (ReplaceItem.Where = wrWholeWord) and (not PrevCharIsIdent)); end; function NeedsReplacementEnd(const ReplaceItem: TReplacementItem; const ReplaceString: string): Boolean; begin Result := InternalNeedsReplacement(ReplaceItem, ReplaceString, False); end; function NeedsReplacementBegin(const ReplaceItem: TReplacementItem; const ReplaceString: string): Boolean; begin Result := InternalNeedsReplacement(ReplaceItem, ReplaceString, True); end; // Adjusts the cursor position for the editor column based on // the text that was replaced and the text that was inserted // to substitute the replaced text. procedure AdjustEditorPosition(const EditorPositionInformation: IEditorPositionInformation; const Replacement, ReplacedText: string); var NewCursorPos: TOTAEditPos; ColumnOffset: Integer; begin Assert(Assigned(EditorPositionInformation)); NewCursorPos := EditorPositionInformation.CursorPos; if EditorPositionInformation.RelativePlacement then begin Inc(NewCursorPos.Col, EditorPositionInformation.RelativePosition.Col - Length(ReplacedText)); Inc(NewCursorPos.Line, EditorPositionInformation.RelativePosition.Line); end else begin if EditorPositionInformation.CharPos.CharIndex > 0 then begin ColumnOffset := Length(Replacement) - Length(ReplacedText); Inc(NewCursorPos.Col, ColumnOffset); end; end; EditorPositionInformation.EditView.CursorPos := NewCursorPos; EditorPositionInformation.EditView.MoveViewToCursor; EditorPositionInformation.EditView.Paint; end; procedure ReplaceTextAt(const SourceEditor: IOTASourceEditor; const EditorPositionInformation: IEditorPositionInformation; const TextToReplace, Replacement, TrailingCharacters: string); var EditWriter: IOTAEditWriter; EditorCharIndex: Longint; begin Assert(Assigned(SourceEditor)); Assert(Assigned(EditorPositionInformation)); EditWriter := GxOtaGetEditWriterForSourceEditor(SourceEditor); Assert(Assigned(EditWriter)); EditorCharIndex := EditorPositionInformation.BufferCharIndex; EditWriter.CopyTo(EditorCharIndex - Length(TextToReplace) - Length(TrailingCharacters)); EditWriter.DeleteTo(EditorCharIndex); // Note: Insert doesn't preserve trailing spaces EditWriter.Insert(PAnsiChar(ConvertToIDEEditorString(Replacement + TrailingCharacters))); EditWriter := nil; // Explicitly release interface here and now end; function CharPosAreEqual(const a, b: TOTACharPos): Boolean; begin Result := (a.Line = b.Line) and (a.CharIndex = b.CharIndex); end; function TAutoTypeWriterNotifier.PerformDictionaryReplacement(const SourceEditor: IOTASourceEditor; const EditorPositionInformation: IEditorPositionInformation; const ReplacementSourceTable: TReplacementSource; const TrailingCharacters, SourceString: string): Boolean; var ReplacementString: string; begin Result := False; ReplacementString := FProofreaderData.FindDictionary(ReplacementSourceTable, SourceString); if ReplacementString <> '' then begin ReplaceTextAt(SourceEditor, EditorPositionInformation, SourceString, ReplacementString, TrailingCharacters); BeepOnDemand; AdjustEditorPosition(EditorPositionInformation, ReplacementString, SourceString); AppendWordHistory(ReplacementSourceTable, SourceString, ReplacementString); Result := True; end; end; function TAutoTypeWriterNotifier.PerformKibitzReplacement(const SourceEditor: IOTASourceEditor; const EditorPositionInformation: IEditorPositionInformation; const ReplacementSourceTable: TReplacementSource; const TrailingCharacters, SourceString, OriginalSourceString: string): Boolean; var GxEditFormProxy: IGxEditFormProxy; CharPos: TOTACharPos; ReplacementString: string; slKibitz: TStrings; //OriginalPos: TOTAEditPos; begin Result := False; GxEditFormProxy := GxEditorFormServices.CurrentProxy; Assert(Assigned(GxEditFormProxy)); if not GxEditFormProxy.IsSourceEditor then Exit; // When using Kibitz OTA support, it only works well when the cursor position // matches the position you want to gather code completion for. So we have to // either backup the cursor one character to the end of the previous identifier // (which breaks parameter hints), or limit the corrections to only happen // after whitespace is typed, when the IDE seems to correct better, so we only // support correcting in Delphi files after whitespace. if KibitzOta and (GxOtaGetCurrentSyntaxHighlighter(SourceEditor) = gxpPAS) and NotEmpty(OriginalSourceString) and (not IsCharWhiteSpace(RightStr(OriginalSourceString, 1)[1])) then Exit; Assert(Assigned(EditorPositionInformation)); CharPos := EditorPositionInformation.CharPos; { // Moving of the cursor allows the more accurate IDE Kibitz info to be obtained, // but disables parameter insight, for example OriginalPos := EditorPositionInformation.EditView.CursorPos; if KibitzOta then // We need to back the cursor up one character, so it gets the code completion for the previous identifier GxOtaMoveEditCursorColumn(EditorPositionInformation.EditView, -1); try } slKibitz := TStringList.Create; try GetKibitzSymbols(SourceEditor, GxEditFormProxy.EditControl, EditorPositionInformation.EditView, CharPos.CharIndex - Length(TrailingCharacters), CharPos.Line, SourceString, TrailingCharacters, slKibitz); ReplacementString := FProofreaderData.FindInStrings(slKibitz, False, SourceString); finally FreeAndNil(slKibitz); end; { except if KibitzOta then EditorPositionInformation.EditView.CursorPos := OriginalPos; raise; end; } if ReplacementString <> '' then begin ReplaceTextAt(SourceEditor, EditorPositionInformation, SourceString, ReplacementString, TrailingCharacters); BeepOnDemand; AdjustEditorPosition(EditorPositionInformation, ReplacementString, SourceString); AppendKibitzHistory(ReplacementSourceTable, SourceString, ReplacementString); Result := True; end { else if KibitzOta then EditorPositionInformation.EditView.CursorPos := OriginalPos; } end; // Return the offset of the caret locator from left, top in string // This routine is agnostic to line-break styles. function RemoveCaretPositioningFromString(var s: string; out RelativeCaretCoord: TOTAEditPos): Boolean; const CaretLocator = '|'; var CaretPosition: Integer; Iterator: Integer; Source: PChar; MultiByteSequenceLen: Cardinal; begin CaretPosition := Pos(CaretLocator, s); Result := (CaretPosition > 0); if Result then begin RelativeCaretCoord.Line := 0; RelativeCaretCoord.Col := 0; Iterator := CaretPosition; Source := Pointer(S); while Iterator > 1 do // Do not count the CaretLocator itself - hence not > 0 begin case Source^ of #10: begin RelativeCaretCoord.Col := 0; Inc(RelativeCaretCoord.Line); Dec(Iterator); Inc(Source); end; #13: begin RelativeCaretCoord.Col := 0; Inc(RelativeCaretCoord.Line); if Source[1] = #10 then begin Dec(Iterator); Inc(Source); end; Dec(Iterator); Inc(Source); end; else if IsLeadChar(Source^) then begin MultiByteSequenceLen := StrNextChar(Source) - Source; { TODO 4 -cIssue -oAnyone: Does the editor count a multi-byte character sequence as a * single column -> Inc(Result.Col, 1); * multiple columns -> Inc(Result.Col, MultiByteSequenceLen); } Inc(RelativeCaretCoord.Col); Dec(Iterator, MultiByteSequenceLen); Inc(Source, MultiByteSequenceLen) end else begin Inc(RelativeCaretCoord.Col); Dec(Iterator); Inc(Source); end; end; end; Delete(s, CaretPosition, Length(CaretLocator)); end; end; function TAutoTypeWriterNotifier.PerformReplacementAtEnd(const SourceEditor: IOTASourceEditor; const EditorPositionInformation: IEditorPositionInformation; const ReplacementSourceTable: TReplacementSource; const TrailingCharacters, SourceString: string): Boolean; var ReplaceItem: TReplacementItem; ReplacementString: string; ReplacedPartOfSource: string; CaretLocation: TOTAEditPos; begin Result := False; ReplaceItem := FProofreaderData.FindReplacement(ReplacementSourceTable, SourceString); if NeedsReplacementEnd(ReplaceItem, SourceString) then begin ReplacementString := ReplaceItem.Replace; if RemoveCaretPositioningFromString(ReplacementString, CaretLocation) then begin EditorPositionInformation.RelativePlacement := True; Dec(CaretLocation.Col, Length(TrailingCharacters)); EditorPositionInformation.RelativePosition := CaretLocation; end; ReplaceTextAt(SourceEditor, EditorPositionInformation, ReplaceItem.Typed, ReplacementString, TrailingCharacters); BeepOnDemand; AdjustEditorPosition(EditorPositionInformation, ReplaceItem.Replace, ReplaceItem.Typed); ReplacedPartOfSource := Copy(SourceString, Length(SourceString) - Length(ReplaceItem.Typed) + 1, Length(SourceString)); AppendAutoCorrectHistory(ReplacementSourceTable, ReplacedPartOfSource, ReplaceItem.Replace); Result := True; end; end; function TAutoTypeWriterNotifier.PerformReplacementAtBeginning(const SourceEditor: IOTASourceEditor; const EditorPositionInformation: IEditorPositionInformation; const ReplacementSourceTable: TReplacementSource; const SourceString: string): Boolean; var ReplaceItem: TReplacementItem; ReplacementString: string; ReplacedPartOfSource: string; CaretLocation: TOTAEditPos; begin Result := False; // Checking SourceString for needing replacement ReplaceItem := FProofreaderData.FindReplacement(ReplacementSourceTable, SourceString); if NeedsReplacementBegin(ReplaceItem, SourceString) then begin ReplacementString := ReplaceItem.Replace; if RemoveCaretPositioningFromString(ReplacementString, CaretLocation) then begin EditorPositionInformation.RelativePlacement := True; EditorPositionInformation.RelativePosition := CaretLocation; end; ReplaceTextAt(SourceEditor, EditorPositionInformation, ReplaceItem.Typed, ReplacementString, ''); BeepOnDemand; if EditorPositionInformation.RelativePlacement then AdjustEditorPosition(EditorPositionInformation, ReplacementString, ReplaceItem.Typed); ReplacedPartOfSource := Copy(SourceString, Length(SourceString) - Length(ReplaceItem.Typed) + 1, Length(SourceString)); AppendAutoCorrectHistory(ReplacementSourceTable, ReplacedPartOfSource, ReplaceItem.Replace); Result := True; end; end; function TAutoTypeWriterNotifier.SetupProofing(const SourceEditor: IOTASourceEditor; var EditorPositionInformation: IEditorPositionInformation; var ReplacementSourceTable: TReplacementSource; var SourceString: string): Boolean; var SyntaxHighlighter: TGXSyntaxHighlighter; Element: Integer; Element2: Integer; LineFlag: Integer; EditView: IOTAEditView; CursorPos: TOTAEditPos; CharPos: TOTACharPos; begin Result := False; if not CharPosAreEqual(SourceEditor.BlockStart, SourceEditor.BlockAfter) then Exit; // Editor change notifiers may fire if the IDE auto-creates some // code behind the scenes. Since we only want to react on user // input, we exit if there is no edit view active. if not GxOtaTryGetTopMostEditView(SourceEditor, EditView) then Exit; EditorPositionInformation := TEditorPositionInformation.Create(EditView); EditorPositionInformation.CursorPos := EditView.CursorPos; // Convert from a CursorPos to a CharPos CursorPos := EditorPositionInformation.CursorPos; EditView.ConvertPos(True, CursorPos, CharPos); EditorPositionInformation.CharPos := CharPos; // Read the part of the text in the current source line // that is located in front of the current cursor position. SourceString := GxOtaGetPreceedingCharactersInLine(EditView); if IsEmpty(SourceString) then Exit; EditView.GetAttributeAtPos(CursorPos, False, Element, LineFlag); // Get the element type of one char to the left: Dec(CursorPos.Col); EditView.GetAttributeAtPos(CursorPos, False, Element2, LineFlag); if Element = atWhiteSpace then begin if GxOtaIsWhiteSpaceInComment(EditView, EditorPositionInformation.CursorPos) then Element := atComment else if GxOtaIsWhiteSpaceInString(EditView, EditorPositionInformation.CursorPos) then Element := atString; end; // Don't mess with compiler directives or comments: if (Element = atWhiteSpace) and (Element2 in [atComment, atPreproc]) then begin Exit; end; SyntaxHighlighter := GxOtaGetCurrentSyntaxHighlighter(SourceEditor); if not DetermineReplacementSource(Element, SyntaxHighlighter, ReplacementSourceTable) then Exit; Result := True; end; procedure TAutoTypeWriterNotifier.SourceEditorModified(const SourceEditor: IOTASourceEditor); var TrailingChars: string; SourceString: string; OriginalSourceString: string; EditorPositionInformation: IEditorPositionInformation; ReplacementSourceTable: TReplacementSource; n: Integer; DoCompiler: Boolean; begin if FModifyingSelf then Exit; FModifyingSelf := True; try if IsReplaceConfirmDialogOnScreen then Exit; // Only correct when the active form is an IDE TEditWindow. // This prevents some unwanted corrections when other experts, // the form designer, or the IDE features make changes. if not GxOtaCurrentlyEditingSource then Exit; try if not FProofreaderData.ReplacerActive and not FProofreaderData.DictionaryActive and not FProofreaderData.CompilerActive then begin Exit; end; if not SetupProofing( // In: SourceEditor, // Out: EditorPositionInformation, ReplacementSourceTable, SourceString) then begin Exit; end; OriginalSourceString := SourceString; // No point in continuing checking for a correction of an empty string if Length(SourceString) = 0 then Exit; // Check the replacement table for matches not requiring a // whole word match ("AutoCorrect" functionality) if FProofreaderData.ReplacerActive then begin if PerformReplacementAtBeginning(SourceEditor, EditorPositionInformation, ReplacementSourceTable, SourceString) then begin Exit; end; end; // The rest of the replacement tests replace whole words only // and cannot possibly match if the last char is alphanumeric n := Length(SourceString); // We know from the Exit above that Length(SourceString) > 0. // Check the last character in the buffer that we copied. // // Usually[*] this will be the character that the user typed // into the editor buffer. [*] The user may have pasted a long text. // // If that last character is in the set of alpha-numeric characters, // the user is not done typing the word, identifier, or statement. // Do not make an attempt to correct anything in that case. if IsCharIdentifier(SourceString[n]) then Exit; // We now split the buffer we retrieved into two halves: // * At the end of the buffer, we find what the user just typed in // (almost always a single char - see above) // * At the beginning of the buffer we find a completed word // that we look at for proofing. // Only copy the LAST character; this is slightly wrong, as the user // may have pasted the string "(i: Integer)" following "showmessage". // In this case, we simply do not detect that the word "showmessage" // has been completed and needs to be corrected. // Unfortunately, we have no means to do it any better, so it will // have to remain slightly wrong for the time being. TrailingChars := Copy(SourceString, n, n); Delete(SourceString, n, n); if (Length(SourceString) = 0) or not (IsCharIdentifier(SourceString[Length(SourceString)])) then begin Exit; end; if FProofreaderData.ReplacerActive then begin if PerformReplacementAtEnd(SourceEditor, EditorPositionInformation, ReplacementSourceTable, TrailingChars, SourceString) then begin EditorPositionInformation.EditView.Paint; Exit; end; end; // Make sure that we only have alphanumeric characters left in s by // stripping out all leading non-alphanumeric characters. n := Length(SourceString); while (n > 0) and IsCharIdentifier(SourceString[n]) do Dec(n); Delete(SourceString, 1, n); // At this stage, s contains the word that we are // looking at for proofreading. c contains all the // characters that follow that word on this line - // typically (if not always), this is only a single // character, and typically it will be a space or bracket. // Example: // Assuming that we read the character sequence // " showmessage(" // from the editor buffer, the variables s and c have // the values // s = 'showmessage' // c = '(' if FProofreaderData.CompilerActive and (ReplacementSourceTable in [rtPasSrc, rtCPPSrc]) then begin DoCompiler := True; // If the dictionary contains the typed word, don't bother with compiler // replacement, since the dictionary serves as an override to not // correct things the compiler might be bad at, like keywords (then, etc.) // We could also ignore certain element types, such as atReservedWord, atNumber, etc. if FProofreaderData.DictionaryActive then DoCompiler := not FProofreaderData.FindExactDictionary(ReplacementSourceTable, SourceString); if DoCompiler and PerformKibitzReplacement(SourceEditor, EditorPositionInformation, ReplacementSourceTable, TrailingChars, SourceString, OriginalSourceString) then begin EditorPositionInformation.EditView.Paint; Exit; end; end; if FProofreaderData.DictionaryActive then begin if PerformDictionaryReplacement(SourceEditor, EditorPositionInformation, ReplacementSourceTable, TrailingChars, SourceString) then begin EditorPositionInformation.EditView.Paint; // Exit; end; end; except on E: Exception do begin GxLogException(E, 'Proofreader exception in SourceEditorModified'); {$IFOPT D+} SendDebug('Proofreader exception: ' + E.Message); {$ENDIF} // Swallow exception end; end; finally FModifyingSelf := False; end; end; procedure TAutoTypeWriterNotifier.FormEditorModified(const FormEditor: IOTAFormEditor); begin //{$IFOPT D+} SendDebug('Proofreader: Form modified'); {$ENDIF} end; procedure TAutoTypeWriterNotifier.NewModuleOpened(const Module: IOTAModule); begin //{$IFOPT D+} SendDebug('Proofreader: New module opened'); {$ENDIF} end; procedure TAutoTypeWriterNotifier.Detach; begin GxEditorChangeServices.RemoveNotifierIfNecessary(FChangeServiceNotifierIndex); end; procedure TAutoTypeWriterNotifier.Attach; begin Assert(FChangeServiceNotifierIndex = -1); FChangeServiceNotifierIndex := GxEditorChangeServices.AddNotifier(Self); end; procedure TAutoTypeWriterNotifier.ComponentRenamed( const FormEditor: IOTAFormEditor; Component: IOTAComponent; const OldName, NewName: string); begin // Nothing end; function TAutoTypeWriterNotifier.GetIndex: Integer; begin Result := FChangeServiceNotifierIndex; end; function TAutoTypeWriterNotifier.EditorKeyPressed( const SourceEditor: IOTASourceEditor; CharCode: Word; KeyData: Integer): Boolean; begin Result := False; // Do nothing for now end; { TEditorPositionInformation } const InvalidBufferCharIndex = -1; constructor TEditorPositionInformation.Create(const EditView: IOTAEditView); begin inherited Create; FBufferCharIndex := InvalidBufferCharIndex; FEditView := EditView; end; destructor TEditorPositionInformation.Destroy; begin FEditView := nil; inherited Destroy; end; function TEditorPositionInformation.GetBufferCharIndex: Longint; begin Result := FBufferCharIndex; if Result = InvalidBufferCharIndex then begin Assert(Assigned(FEditView)); // We perform a delayed calculation of the character index // and remember it for the future. // For D4 we were forced to determine BufferCharIndex at a // much earlier state - we have a cached copy of that // calculation already. Result := FEditView.CharPosToPos(FCharPos); FBufferCharIndex := Result; end; end; function TEditorPositionInformation.GetCharPos: TOTACharPos; begin Result := FCharPos; end; function TEditorPositionInformation.GetCursorPos: TOTAEditPos; begin Result := FCursorPos; end; function TEditorPositionInformation.GetEditView: IOTAEditView; begin Result := FEditView; end; function TEditorPositionInformation.GetRelativePlacement: Boolean; begin Result := FRelativePlacement; end; function TEditorPositionInformation.GetRelativePosition: TOTAEditPos; begin Result := FRelativePosition; end; procedure TEditorPositionInformation.SetBufferCharIndex(const Value: Longint); begin FBufferCharIndex := Value; end; procedure TEditorPositionInformation.SetCharPos(const Value: TOTACharPos); begin FCharPos := Value; end; procedure TEditorPositionInformation.SetCursorPos(const Value: TOTAEditPos); begin FCursorPos := Value; end; procedure TEditorPositionInformation.SetRelativePlacement(const Value: Boolean); begin FRelativePlacement := Value; end; procedure TEditorPositionInformation.SetRelativePosition(const Value: TOTAEditPos); begin FRelativePosition := Value; end; end.
{ ***************************************************************************** * * * This file is part of the iPhone Laz Extension * * * * See the file COPYING.modifiedLGPL.txt, included in this distribution, * * for details about the copyright. * * * * 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. * * * ***************************************************************************** } unit xcodetemplate; {$mode objfpc}{$H+} interface uses Classes, SysUtils, contnrs; procedure PrepareTemplateFile(Src, TemplateValues: TStrings; BuildSettings: TFPStringHashTable); const XCodeProjectTemplateIconID : AnsiString ='0AE3FFA610F3C9AF00A9B007,'; XCodeProjectTemplateIcon : AnsiString = '0AE3FFA610F3C9AF00A9B007 /* Icon.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = Icon.png; sourceTree = "<group>"; };'; XCodeIconFile : AnsiString = '0A2C67AE10F3CFB800F48811,'; XCodeIconFileRef : AnsiString = '0A2C67AE10F3CFB800F48811 /* Icon.png in Resources */ = {isa = PBXBuildFile; fileRef = 0AE3FFA610F3C9AF00A9B007 /* Icon.png */; };'; XCodeProjectTemplate : AnsiString = '// !$*UTF8*$!'#10+ '{'#10+ ' archiveVersion = 1;'#10+ ' classes = {'#10+ ' };'#10+ ' objectVersion = 45;'#10+ ' objects = {'#10+ ' '#10+ ' ??iconfileref'#10+ ' '#10+ '/* Begin PBXFileReference section */'#10+ ' 0A85A8AE10F0D28700AB8400 /* ??bundle */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = ??bundle; sourceTree = BUILT_PRODUCTS_DIR; };'#10+ ' 0A85A8B110F0D28700AB8400 /* ??plist */ = {isa = PBXFileReference; explicitFileType = text.plist.xml; name = ??plist; path = ??plist; sourceTree = SOURCE_ROOT; };'#10+ ' ??icon'#10+ '/* End PBXFileReference section */'#10+ ''#10+ '/* Begin PBXGroup section */'#10+ ' 0A52AE8110F0D05300478C4F = {'#10+ ' isa = PBXGroup;'#10+ ' children = ('#10+ ' ??iconid'#10+ ' 0A85A8AF10F0D28700AB8400 /* Products */,'#10+ ' 0A85A8B110F0D28700AB8400 /* ??plist */,'#10+ ' );'#10+ ' sourceTree = "<group>";'#10+ ' };'#10+ ' 0A85A8AF10F0D28700AB8400 /* Products */ = {'#10+ ' isa = PBXGroup;'#10+ ' children = ('#10+ ' 0A85A8AE10F0D28700AB8400 /* ??bundle */,'#10+ ' );'#10+ ' name = Products;'#10+ ' sourceTree = "<group>";'#10+ ' };'#10+ '/* End PBXGroup section */'#10+ ''#10+ '/* Begin PBXNativeTarget section */'#10+ ' 0A85A8AD10F0D28700AB8400 = {'#10+ ' isa = PBXNativeTarget;'#10+ ' buildConfigurationList = 0A85A8B410F0D28800AB8400 /* Build configuration list for PBXNativeTarget */;'#10+ ' buildPhases = ('#10+ ' 0A85A8B810F0D2D400AB8400 /* ShellScript */,'#10+ ' 0A2C67A610F3CEFA00F48811 /* Resources */,'#10+ ' );'#10+ ' buildRules = ('#10+ ' );'#10+ ' dependencies = ('#10+ ' );'#10+ ' name = ??targetname;'#10+ ' productName = ??productname;'#10+ ' productReference = 0A85A8AE10F0D28700AB8400 /* ??bundle */;'#10+ ' productType = "com.apple.product-type.application";'#10+ ' };'#10+ '/* End PBXNativeTarget section */'#10+ ''#10+ '/* Begin PBXProject section */'#10+ ' 0A52AE8310F0D05300478C4F /* Project object */ = {'#10+ ' isa = PBXProject;'#10+ ' buildConfigurationList = 0A52AE8610F0D05300478C4F /* Build configuration list for PBXProject "project1" */;'#10+ ' compatibilityVersion = "Xcode 3.1";'#10+ ' hasScannedForEncodings = 0;'#10+ ' mainGroup = 0A52AE8110F0D05300478C4F;'#10+ ' productRefGroup = 0A85A8AF10F0D28700AB8400 /* Products */;'#10+ ' projectDirPath = "";'#10+ ' projectRoot = "";'#10+ ' targets = ('#10+ ' 0A85A8AD10F0D28700AB8400,'#10+ ' );'#10+ ' };'#10+ '/* End PBXProject section */'#10+ ''#10+ '/* Begin PBXResourcesBuildPhase section */'#10+ ' 0A2C67A610F3CEFA00F48811 /* Resources */ = {'#10+ ' isa = PBXResourcesBuildPhase;'#10+ ' buildActionMask = 2147483647;'#10+ ' files = ('#10+ ' ??iconfile'#10+ ' );'#10+ ' runOnlyForDeploymentPostprocessing = 0;'#10+ ' };'#10+ '/* End PBXResourcesBuildPhase section */'#10+ ''#10+ '/* Begin PBXShellScriptBuildPhase section */'#10+ ' 0A85A8B810F0D2D400AB8400 /* ShellScript */ = {'#10+ ' isa = PBXShellScriptBuildPhase;'#10+ ' buildActionMask = 2147483647;'#10+ ' files = ('#10+ ' );'#10+ ' inputPaths = ('#10+ ' );'#10+ ' outputPaths = ('#10+ ' );'#10+ ' runOnlyForDeploymentPostprocessing = 0;'#10+ ' shellPath = /bin/sh;'#10+ ' shellScript = "if [ x\"$ACTION\" != \"xbuild\" ]; then\n # in case running scripts during cleaning gets fixed\n exit 0\nfi\n\necho $FPC_COMPILER_PATH $FPC_COMPILER_OPTIONS $FPC_MAIN_FILE\n\n$FPC_COMPILER_PATH $FPC_COMPILER_OPTIONS $FPC_MAIN_FILE";'#10+ ' };'#10+ '/* End PBXShellScriptBuildPhase section */'#10+ ''#10+ '/* Begin XCBuildConfiguration section */'#10+ ' 0A52AE8510F0D05300478C4F /* Release */ = {'#10+ ' isa = XCBuildConfiguration;'#10+ ' buildSettings = {'#10+ ' ARCHS = "$(ARCHS_STANDARD_32_BIT)";'#10+ ' "ARCHS[sdk=iphonesimulator*]" = "$(ARCHS_STANDARD_32_BIT)";'#10+ ' COPY_PHASE_STRIP = YES;'#10+ ' FPC_OUTPUT_FILE = $BUILT_PRODUCTS_DIR/$EXECUTABLE_PATH;'#10+ ' FPC_COMPILER_OPTIONS = "-Parm -o$FPC_OUTPUT_FILE $FPC_CUSTOM_OPTIONS";'#10+ ' "FPC_COMPILER_OPTIONS[sdk=iphonesimulator*]" = "-Tiphonesim -Pi386 -o$FPC_OUTPUT_FILE $FPC_CUSTOM_OPTIONS";'#10+ ' FPC_COMPILER_PATH = ;'#10+ ' FPC_CUSTOM_OPTIONS = ;'#10+ ' "FPC_CUSTOM_OPTIONS[sdk=iphonesimulator*]" = ;'#10+ ' FPC_MAIN_FILE = ;'#10+ ' SDKROOT = iphoneos2.0;'#10+ ' VALID_ARCHS = "armv6 armv7";'#10+ ' };'#10+ ' name = Release;'#10+ ' };'#10+ ' 0A85A8B310F0D28800AB8400 /* Release */ = {'#10+ ' isa = XCBuildConfiguration;'#10+ ' buildSettings = {'#10+ ' ALWAYS_SEARCH_USER_PATHS = YES;'#10+ ' COPY_PHASE_STRIP = YES;'#10+ ' DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";'#10+ ' GCC_ENABLE_FIX_AND_CONTINUE = NO;'#10+ ' GCC_PRECOMPILE_PREFIX_HEADER = YES;'#10+ ' GCC_PREFIX_HEADER = "$(SYSTEM_LIBRARY_DIR)/Frameworks/UIKit.framework/Headers/UIKit.h";'#10+ ' INFOPLIST_FILE = ??plist;'#10+ ' INSTALL_PATH = "$(HOME)/Applications";'#10+ ' OTHER_LDFLAGS = ('#10+ ' "-framework",'#10+ ' Foundation,'#10+ ' "-framework",'#10+ ' UIKit,'#10+ ' );'#10+ ' PREBINDING = NO;'#10+ ' PRODUCT_NAME = ??productname;'#10+ ' SDKROOT = iphoneos2.0;'#10+ ' ZERO_LINK = NO;'#10+ ' };'#10+ ' name = Release;'#10+ ' };'#10+ '/* End XCBuildConfiguration section */'#10+ ' '#10+ '/* Begin XCConfigurationList section */'#10+ ' 0A52AE8610F0D05300478C4F /* Build configuration list for PBXProject "project1" */ = {'#10+ ' isa = XCConfigurationList;'#10+ ' buildConfigurations = ('#10+ ' 0A52AE8510F0D05300478C4F /* Release */,'#10+ ' );'#10+ ' defaultConfigurationIsVisible = 0;'#10+ ' defaultConfigurationName = Release;'#10+ ' };'#10+ ' 0A85A8B410F0D28800AB8400 /* Build configuration list for PBXNativeTarget */ = {'#10+ ' isa = XCConfigurationList;'#10+ ' buildConfigurations = ('#10+ ' 0A85A8B310F0D28800AB8400 /* Release */,'#10+ ' );'#10+ ' defaultConfigurationIsVisible = 0;'#10+ ' defaultConfigurationName = Release;'#10+ ' };'#10+ '/* End XCConfigurationList section */'#10+ ' };'#10+ ' rootObject = 0A52AE8310F0D05300478C4F /* Project object */;'#10+ '}'#10; implementation function GetValueName(const Source: String; idx: Integer): String; var i : integer; InQuote: boolean; const //todo: expand symbols charset Symbols: set of char = [#9, #32, #10,#13, '=',':',';','-','+','*','/','\','!','@','#', '$','%','^','&','(',')','~','`','''']; begin InQuote:=false; for i:=idx to length(Source) do begin if InQuote then begin if Source[i]='"' then InQuote := false; end else if Source[i] = '"' then InQuote := true else if Source[i] in Symbols then begin Result:=Copy(Source, idx, i-idx); Exit; end; end; Result:=Copy(Source, idx, length(Source)-idx+1); end; function ChangeValues(const Prefix, Source: String; Values: TStrings): String; var i : integer; nm : string; v : string; begin Result:=Source; i:=Pos(Prefix, Result); while i>0 do begin nm:=GetValueName(Result, i+length(Prefix)); Delete(Result, i, length(Prefix)+length(nm)); v:=Values.Values[nm]; if Pos(Prefix, v) <= 0 then // don't allow circular prefix used, to avoid infinite loops Insert(v, Result, i); i:=Pos(Prefix, Result); end; end; procedure PrepareTemplateFile(Src, TemplateValues: TStrings; BuildSettings: TFPStringHashTable); //todo: Better code to update XCode project file! var i, j : Integer; nm, s, v : String; isSettings : Boolean; begin if not Assigned(Src) then Exit; if Assigned(TemplateValues) then for i:=0 to Src.Count-1 do Src[i]:=ChangeValues('??', Src[i], TemplateValues); isSettings:=false; if Assigned(BuildSettings) and (BuildSettings.Count>0) then begin for i:=0 to Src.Count-1 do begin if not isSettings then isSettings:=Pos('buildSettings', Src[i])>0 else begin if Trim(Src[i])='};' then isSettings:=false else begin j:=1; s:=Src[i]; while (j<=length(s)) and (s[j] in [#9, #32]) do inc(j); nm:=GetValueName(s, j); if Assigned(BuildSettings.Find(nm)) then begin v:=BuildSettings.Items[nm]; Src[i]:=Copy(Src[i], 1, j-1)+nm+ ' = ' + v + ';'; end; end; end; {of else} end; end; end; end.
// the code formatter expert as an editor expert // Original Author: Thomas Mueller (http://blog.dummzeuch.de) unit GX_eCodeFormatter; {$I GX_CondDefine.inc} interface uses SysUtils, Classes, GX_EditorExpert, GX_CodeFormatterExpert, GX_ConfigurationInfo, GX_KbdShortCutBroker, GX_GenericUtils; type TeCodeFormatterExpert = class(TEditorExpert) private FExpert: TCodeFormatterExpert; protected function GetBitmapFileName: string; override; procedure InternalLoadSettings(Settings: TExpertSettings); override; procedure InternalSaveSettings(Settings: TExpertSettings); override; public class function GetName: string; override; constructor Create; override; destructor Destroy; override; function GetDefaultShortCut: TShortCut; override; function GetDisplayName: string; override; procedure Configure; override; procedure Execute(Sender: TObject); override; function GetHelpString: string; override; function HasConfigOptions: Boolean; override; function IsDefaultActive: Boolean; override; procedure AddToCapitalization(const _Identifier: TGXUnicodeString); end; var gblCodeFormatter: TeCodeFormatterExpert; implementation uses {$IFOPT D+}GX_DbugIntf, {$ENDIF} Menus, GX_IdeUtils; { TeCodeFormatterExpert } procedure TeCodeFormatterExpert.AddToCapitalization(const _Identifier: TGXUnicodeString); var GExpertsSettings: TGExpertsSettings; ExpSettings: TExpertSettings; begin FExpert.AddToCapitalization(_Identifier); ExpSettings := nil; GExpertsSettings := TGExpertsSettings.Create; try ExpSettings := GExpertsSettings.CreateExpertSettings(ConfigurationKey); InternalSaveSettings(ExpSettings); finally FreeAndNil(ExpSettings); FreeAndNil(GExpertsSettings); end; end; procedure TeCodeFormatterExpert.Configure; begin FExpert.Configure; end; constructor TeCodeFormatterExpert.Create; begin inherited Create; FExpert := TCodeFormatterExpert.Create; gblCodeFormatter := Self; end; destructor TeCodeFormatterExpert.Destroy; begin gblCodeFormatter := nil; FreeAndNil(FExpert); inherited; end; function TeCodeFormatterExpert.IsDefaultActive: Boolean; begin Result := not RunningRSXEOrGreater; end; procedure TeCodeFormatterExpert.Execute(Sender: TObject); begin FExpert.Execute; end; function TeCodeFormatterExpert.GetBitmapFileName: string; begin Result := 'TCodeFormatterExpert'; end; function TeCodeFormatterExpert.GetDefaultShortCut: TShortCut; begin if RunningRS2010OrGreater then begin // Strarting with Delphi 2010 it has a built in code formatter // it doesn't work very well in the early incarnations but // if the user wants to replace it, he should configure it himself. Result := Menus.ShortCut(Word('F'), [ssCtrl, ssAlt]) end else begin // for older versions, hijack the Ctrl+D shortcut that in later versions is // used by the built in code formatter Result := Menus.ShortCut(Word('D'), [ssCtrl]); end; end; function TeCodeFormatterExpert.GetDisplayName: string; begin Result := 'Code Formatter'; end; function TeCodeFormatterExpert.GetHelpString: string; resourcestring SFormatterHelp = 'This expert is the source code formatter formerly known as ' + 'DelForEx. To switch between different configuration sets, ' + 'use the tools button.' + sLineBreak + 'To force a configuration set for a particular unit, add' + sLineBreak + ' {GXFormatter.config=<configname>}' + sLineBreak + 'as the first line to the unit.' + sLineBreak + 'You can also use a GXFormatter.ini per directory with content ' + 'like:' + sLineBreak + ' [FileSettings]' + sLineBreak + ' <mask>=<configname>' + sLineBreak + 'The formatter will use the first match for the file name. ' + 'An empty <configname> means that it should work ' + 'as configured in this dialog.' + sLineBreak + 'You can also export your own configuration as' + sLineBreak + ' FormatterSettings-<YourName>.ini' + sLineBreak + 'and put it into the GExperts installation directory.' + sLineBreak + 'After doing this <YourName> can be used as <configname> as ' + 'described above.'; begin Result := SFormatterHelp; end; class function TeCodeFormatterExpert.GetName: string; begin Result := 'CodeFormatter'; end; function TeCodeFormatterExpert.HasConfigOptions: Boolean; begin Result := True; end; procedure TeCodeFormatterExpert.InternalLoadSettings(Settings: TExpertSettings); begin inherited; FExpert.InternalLoadSettings(Settings); end; procedure TeCodeFormatterExpert.InternalSaveSettings(Settings: TExpertSettings); begin inherited; FExpert.InternalSaveSettings(Settings); end; initialization RegisterEditorExpert(TeCodeFormatterExpert); end.
Unit udmCatCheckList; interface uses System.SysUtils, System.Classes, udmPadrao, DBAccess, IBC, Data.DB, MemDS; type TdmCatCheckList = class(TdmPadrao) qryManutencaoTP_VEICULO: TSmallintField; qryManutencaoCATEGORIA: TStringField; qryManutencaoDESCRICAO: TStringField; qryManutencaoSTATUS: TStringField; qryManutencaoOPERADOR: TStringField; qryManutencaoDTALTERACAO: TDateTimeField; qryLocalizacaoTP_VEICULO: TSmallintField; qryLocalizacaoCATEGORIA: TStringField; qryLocalizacaoDESCRICAO: TStringField; qryLocalizacaoSTATUS: TStringField; qryLocalizacaoOPERADOR: TStringField; qryLocalizacaoDTALTERACAO: TDateTimeField; protected procedure MontaSQLBusca(DataSet: TDataSet = nil); override; procedure MontaSQLRefresh; override; private FTp_Veiculo: integer; FCategoria: string; function GetSQL_DEFAULT: string; { Private declarations } public property Tp_Veiculo: integer read FTp_Veiculo write FTp_Veiculo; property Categoria: string read FCategoria write FCategoria; property SqlDefault: string read GetSQL_DEFAULT; function LocalizarPorCategoria(DataSet: TDataSet = nil): Boolean; end; const SQL_DEFAULT = 'SELECT TP_VEICULO,' + ' CATEGORIA,' + ' DESCRICAO,' + ' STATUS,' + ' OPERADOR,' + ' DTALTERACAO' + ' FROM CHECKLIST'; var dmCatCheckList: TdmCatCheckList; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} uses udmPrincipal; { TdmCatCheckList } function TdmCatCheckList.GetSQL_DEFAULT: string; begin result := SQL_DEFAULT; end; function TdmCatCheckList.LocalizarPorCategoria(DataSet: TDataSet): Boolean; begin if DataSet = nil then DataSet := qryLocalizacao; with (DataSet as TIBCQuery) do begin close; SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add(' WHERE CATEGORIA = :CATEGORIA'); ParamByName('CATEGORIA').AsString := FCategoria; Open; Result := not IsEmpty; end; end; procedure TdmCatCheckList.MontaSQLBusca(DataSet: TDataSet); begin inherited; with (DataSet as TIBCQuery) do begin SQL.Clear; SQL.Add(SQL_DEFAULT); SQL.Add(' WHERE TP_VEICULO = :TP_VEICULO '); SQL.Add(' AND CATEGORIA = :CATEGORIA'); ParamByName('TP_VEICULO').AsInteger := FTp_Veiculo; ParamByName('CATEGORIA').AsString := FCategoria; end; end; procedure TdmCatCheckList.MontaSQLRefresh; begin inherited; with qryManutencao do begin close; SQL.Clear; SQL.Add(SQL_DEFAULT); open; end; end; end.
unit TelematicActionsUnit; interface uses SysUtils, BaseActionUnit, VendorUnit, EnumsUnit, NullableBasicTypesUnit, CommonTypesUnit; type TTelematicActions = class(TBaseAction) public /// <summary> /// GET a telematics vendor /// </summary> function Get(VendorId: integer; out ErrorString: String): TVendor; overload; /// <summary> /// GET all telematics vendors /// </summary> function Get(out ErrorString: String): TVendorList; overload; /// <summary> /// Search vendors /// </summary> function Search(Size: NullableVendorSizeType; IsIntegrated: NullableBoolean; Feature, Country, Search: NullableString; Page: NullableInteger; PerPage: NullableInteger; out ErrorString: String): TVendorList; /// <summary> /// Compare elected vendors /// </summary> function Compare(VendorIds: TStringArray; out ErrorString: String): TVendorList; end; implementation { TTelematicActions } uses SettingsUnit, GenericParametersUnit, GetVendorsResponseUnit; function TTelematicActions.Get(VendorId: integer; out ErrorString: String): TVendor; var Parameters: TGenericParameters; begin Parameters := TGenericParameters.Create; try Parameters.AddParameter('vendor_id', IntToStr(VendorId)); Result := FConnection.Get(TSettings.EndPoints.TelematicsGateway, Parameters, TVendor, ErrorString) as TVendor; finally FreeAndNil(Parameters); end; end; function TTelematicActions.Compare(VendorIds: TStringArray; out ErrorString: String): TVendorList; var Parameters: TGenericParameters; Response: TGetVendorsResponse; i: integer; VendorsString: String; begin Result := TVendorList.Create; Parameters := TGenericParameters.Create; try VendorsString := EmptyStr; for i := 0 to High(VendorIds) do begin VendorsString := VendorsString + VendorIds[i]; if (i <> High(VendorIds)) then VendorsString := VendorsString + ','; end; Parameters.AddParameter('vendors', VendorsString); Response := FConnection.Get(TSettings.EndPoints.TelematicsGateway, Parameters, TGetVendorsResponse, ErrorString) as TGetVendorsResponse; try if (Response <> nil) then Result.AddRange(Response.Vendors); finally FreeAndNil(Response); end; finally FreeAndNil(Parameters); end; end; function TTelematicActions.Get(out ErrorString: String): TVendorList; var Parameters: TGenericParameters; Response: TGetVendorsResponse; begin Result := TVendorList.Create; Parameters := TGenericParameters.Create; try Response := FConnection.Get(TSettings.EndPoints.TelematicsGateway, Parameters, TGetVendorsResponse, ErrorString) as TGetVendorsResponse; try if (Response <> nil) then Result.AddRange(Response.Vendors); finally FreeAndNil(Response); end; finally FreeAndNil(Parameters); end; end; function TTelematicActions.Search(Size: NullableVendorSizeType; IsIntegrated: NullableBoolean; Feature, Country, Search: NullableString; Page: NullableInteger; PerPage: NullableInteger; out ErrorString: String): TVendorList; var Parameters: TGenericParameters; Response: TGetVendorsResponse; begin Result := TVendorList.Create; Parameters := TGenericParameters.Create; try if (IsIntegrated.IsNotNull) then if (IsIntegrated.Value) then Parameters.AddParameter('is_integrated', '1') else Parameters.AddParameter('is_integrated', '0'); if (Feature.IsNotNull) then Parameters.AddParameter('feature', Feature); if (Size.IsNotNull) then Parameters.AddParameter('size', TVendorSizeTypeDescription[Size.Value]); if (Country.IsNotNull) then Parameters.AddParameter('country', Country); if (Search.IsNotNull) then Parameters.AddParameter('search', Search); if (Page.IsNotNull) then Parameters.AddParameter('page', IntToStr(Page)); if (PerPage.IsNotNull) then Parameters.AddParameter('per_page', IntToStr(PerPage)); Response := FConnection.Get(TSettings.EndPoints.TelematicsGateway, Parameters, TGetVendorsResponse, ErrorString) as TGetVendorsResponse; try if (Response <> nil) then Result.AddRange(Response.Vendors); finally FreeAndNil(Response); end; finally FreeAndNil(Parameters); end; end; end.
unit Land; interface uses Windows, Graphics; type TLandVisualClassId = word; const lndPrimaryClassShift = 8; lndSecondaryClassShift = 4; lndTypeShift = 12; lndVarShift = 0; type TLandClass = ( lncZone1, lncZone2, lncZone3, lncZone4, lncZone5, lncZone6, lncZone7, lncZone8, lncZone9, lncZone10, lncZone11, lncZone12, lncZone13, lncZone14, lncZone15, lncZone16 ); TLandType = ( ldtCenter, ldtN, ldtE, ldtS, ldtW, ldtNEo, ldtSEo, ldtSWo, ldtNWo, ldtNEi, ldtSEi, ldtSWi, ldtNWi, ldtSpecial ); const PrimaryLandClassIds : array[TLandClass] of TLandVisualClassId = ( ord(lncZone1) shl lndPrimaryClassShift, ord(lncZone2) shl lndPrimaryClassShift, ord(lncZone3) shl lndPrimaryClassShift, ord(lncZone4) shl lndPrimaryClassShift, ord(lncZone5) shl lndPrimaryClassShift, ord(lncZone6) shl lndPrimaryClassShift, ord(lncZone7) shl lndPrimaryClassShift, ord(lncZone8) shl lndPrimaryClassShift, ord(lncZone9) shl lndPrimaryClassShift, ord(lncZone10) shl lndPrimaryClassShift, ord(lncZone11) shl lndPrimaryClassShift, ord(lncZone12) shl lndPrimaryClassShift, ord(lncZone13) shl lndPrimaryClassShift, ord(lncZone14) shl lndPrimaryClassShift, ord(lncZone15) shl lndPrimaryClassShift, ord(lncZone16) shl lndPrimaryClassShift ); SecondaryLandClassIds : array[TLandClass] of TLandVisualClassId = ( ord(lncZone1) shl lndSecondaryClassShift, ord(lncZone2) shl lndSecondaryClassShift, ord(lncZone3) shl lndSecondaryClassShift, ord(lncZone4) shl lndSecondaryClassShift, ord(lncZone5) shl lndSecondaryClassShift, ord(lncZone6) shl lndSecondaryClassShift, ord(lncZone7) shl lndSecondaryClassShift, ord(lncZone8) shl lndSecondaryClassShift, ord(lncZone9) shl lndSecondaryClassShift, ord(lncZone10) shl lndSecondaryClassShift, ord(lncZone11) shl lndSecondaryClassShift, ord(lncZone12) shl lndSecondaryClassShift, ord(lncZone13) shl lndSecondaryClassShift, ord(lncZone14) shl lndSecondaryClassShift, ord(lncZone15) shl lndSecondaryClassShift, ord(lncZone16) shl lndSecondaryClassShift ); LandTypeIds : array[TLandType] of TLandVisualClassId = ( ord(ldtCenter) shl lndTypeShift, ord(ldtN) shl lndTypeShift, ord(ldtE) shl lndTypeShift, ord(ldtS) shl lndTypeShift, ord(ldtW) shl lndTypeShift, ord(ldtNEo) shl lndTypeShift, ord(ldtSEo) shl lndTypeShift, ord(ldtSWo) shl lndTypeShift, ord(ldtNWo) shl lndTypeShift, ord(ldtNEi) shl lndTypeShift, ord(ldtSEi) shl lndTypeShift, ord(ldtSWi) shl lndTypeShift, ord(ldtNWi) shl lndTypeShift, 0 ); const NoLand = high(TLandVisualClassId); const lndPrimaryClassMask = $FFFF shl lndPrimaryClassShift; lndSecondaryClassMask = $FFFF shl lndSecondaryClassShift; lndClassMask = lndPrimaryClassMask or lndSecondaryClassMask; lndTypeMask = $FFFF shl lndTypeShift and not lndClassMask; lndVarMask = $FFFF shl lndVarShift and not(lndClassMask or lndTypeMask); function LandIdOf( PrimaryLandClass, SecondaryLandClass : TLandClass; LandType : TLandType; LandVar : integer ) : TLandVisualClassId; function LandIsPure ( landId, classId : TLandVisualClassId ) : boolean; function LandPrimaryClassOf ( landId : TLandVisualClassId ) : TLandClass; function LandSecondaryClassOf( landId : TLandVisualClassId ) : TLandClass; function LandTypeOf ( landId : TLandVisualClassId ) : TLandType; function LandVarOf ( landId : TLandVisualClassId ) : integer; type TLandAngle = (ang90, ang270); function LandRotate( landId : TLandVisualClassId; angle : TLandAngle ) : TLandVisualClassId; // Land Interfaces type ILandClassInfo = interface function GetLandVisualClassId : TLandVisualClassId; function GetImageURL( zoomlevel : integer ) : string; function GetAlterColor : TColor; end; ILandClassesInfo = interface function GetClass( LandVisualClassId : TLandVisualClassId ) : ILandClassInfo; end; ILandInfo = interface function LandSize : TPoint; function LandVisualClassAt( x, y : integer ) : TLandVisualClassId; function LandClassAt( x, y : integer ) : TLandClass; function LandTypeAt( x, y : integer ) : TLandType; end; implementation function LandIdOf( PrimaryLandClass, SecondaryLandClass : TLandClass; LandType : TLandType; LandVar : integer ) : TLandVisualClassId; begin result := PrimaryLandClassIds[PrimaryLandClass] or SecondaryLandClassIds[SecondaryLandClass] or LandTypeIds[LandType] or LandVar; end; function LandIsPure( landId, classId : TLandVisualClassId ) : boolean; begin result := landId and lndTypeMask = 0; end; function LandPrimaryClassOf( landId : TLandVisualClassId ) : TLandClass; begin result := TLandClass((landId and lndClassMask) shr lndPrimaryClassShift); end; function LandSecondaryClassOf( landId : TLandVisualClassId ) : TLandClass; begin result := TLandClass((landId and lndClassMask) shr lndSecondaryClassShift); end; function LandTypeOf( landId : TLandVisualClassId ) : TLandType; var typeidx : integer; begin typeidx := (landId and lndTypeMask) shr lndTypeShift; if typeidx < ord(high(TLandType)) then result := TLandType(typeidx) else result := ldtSpecial; end; function LandVarOf( landId : TLandVisualClassId ) : integer; begin result := (landId and lndVarMask) shr lndVarShift; end; function LandRotate( landId : TLandVisualClassId; angle : TLandAngle ) : TLandVisualClassId; const RotatedLand : array[TLandType, TLandAngle] of TLandType = ( (ldtCenter, ldtCenter), // ldtCenter (ldtW, ldtE), // ldtN (ldtN, ldtS), // ldtE (ldtE, ldtW), // ldtS (ldtS, ldtN), // ldtW (ldtNWo, ldtSEo), // ldtNEo (ldtNEo, ldtSWo), // ldtSEo (ldtSEo, ldtNWo), // ldtSWo (ldtSWo, ldtNEo), // ldtNWo (ldtNWi, ldtSEi), // ldtNEi (ldtNEi, ldtSWi), // ldtSEi (ldtSEi, ldtNWi), // ldtSWi (ldtSWi, ldtNEi), // ldtNWi (ldtSpecial, ldtSpecial)); // ldtSpecial begin result := LandIdOf( LandPrimaryClassOf( landId ), LandSecondaryClassOf( landId ), RotatedLand[LandTypeOf( landId ), angle], LandVarOf( landId ) ); end; end.
unit k051316; interface uses {$IFDEF WINDOWS}windows,{$ENDIF}gfx_engine,main_engine; type t_k051316_cb=procedure(var code:word;var color:word;var priority_mask:word); k051316_chip=class constructor create(pant,ngfx:byte;call_back:t_k051316_cb;rom:pbyte;rom_size:dword;tipo:byte); destructor free; public procedure reset; function read(direccion:word):byte; function rom_read(direccion:word):byte; procedure write(direccion:word;valor:byte); procedure draw(screen:byte); procedure control_w(direccion,valor:byte); procedure clean_video_buffer; private ram:array[0..$7ff] of byte; rom:pbyte; control:array[0..$f] of byte; rom_size,rom_mask:dword; k051316_cb:t_k051316_cb; pant,ngfx,pixels_per_byte:byte; end; const BPP4=0; BPP7=1; var k051316_0:k051316_chip; implementation constructor k051316_chip.create(pant,ngfx:byte;call_back:t_k051316_cb;rom:pbyte;rom_size:dword;tipo:byte); const pc_x_4:array[0..15] of dword=(0*4, 1*4, 2*4, 3*4, 4*4, 5*4, 6*4, 7*4, 8*4, 9*4, 10*4, 11*4, 12*4, 13*4, 14*4, 15*4); pc_y_4:array[0..15] of dword=(0*64, 1*64, 2*64, 3*64, 4*64, 5*64, 6*64, 7*64, 8*64, 9*64, 10*64, 11*64, 12*64, 13*64, 14*64, 15*64); pc_x_7:array[0..15] of dword=(0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 8*8, 9*8, 10*8, 11*8, 12*8, 13*8, 14*8, 15*8); pc_y_7:array[0..15] of dword=(0*128, 1*128, 2*128, 3*128, 4*128, 5*128, 6*128, 7*128, 8*128, 9*128, 10*128, 11*128, 12*128, 13*128, 14*128, 15*128); begin self.pant:=pant; self.rom:=rom; self.rom_size:=rom_size; self.rom_mask:=rom_size-1; self.k051316_cb:=call_back; self.ngfx:=ngfx; init_gfx(ngfx,16,16,rom_size div 256); gfx[ngfx].trans[0]:=true; case tipo of BPP4:begin gfx_set_desc_data(4,0,8*128,0,1,2,3); convert_gfx(ngfx,0,rom,@pc_x_4,@pc_y_4,false,false); self.pixels_per_byte:=2; end; BPP7:begin gfx_set_desc_data(7,0,8*256,1,2,3,4,5,6,7); convert_gfx(ngfx,0,rom,@pc_x_7,@pc_y_7,false,false); self.pixels_per_byte:=1; end; end; end; destructor k051316_chip.free; begin end; procedure k051316_chip.reset; begin fillchar(self.control,$10,0); end; procedure k051316_chip.clean_video_buffer; begin fillchar(gfx[self.ngfx].buffer,$400,1); end; function k051316_chip.rom_read(direccion:word):byte; var addr:dword; begin if ((self.control[$e] and $1)=0) then begin addr:=direccion+(self.control[$0c] shl 11)+(self.control[$0d] shl 19); addr:=(addr div self.pixels_per_byte) and self.rom_mask; rom_read:=self.rom[addr]; end else rom_read:=0; end; procedure k051316_chip.control_w(direccion,valor:byte); begin self.control[direccion and $f]:=valor; end; function k051316_chip.read(direccion:word):byte; begin read:=self.ram[direccion]; end; procedure k051316_chip.write(direccion:word;valor:byte); begin self.ram[direccion]:=valor; gfx[self.ngfx].buffer[direccion and $3ff]:=true; end; procedure k051316_chip.draw(screen:byte); var f,color,nchar,pri:word; x,y:byte; startx,starty,incxx,incxy,incyx,incyy:integer; begin pri:=0; for f:=0 to $3ff do begin //Background if gfx[self.ngfx].buffer[f] then begin x:=f mod 32; y:=f div 32; color:=self.ram[f+$400]; nchar:=self.ram[f]; self.k051316_cb(nchar,color,pri); put_gfx_trans(x*16,y*16,nchar,color shl 7,self.pant,self.ngfx); gfx[self.ngfx].buffer[f]:=false; end; end; startx:=smallint((self.control[0] shl 8)+self.control[1]) shl 8; starty:=smallint((self.control[6] shl 8)+self.control[7]) shl 8; incxx:=smallint(256*self.control[$02]+self.control[$03]); incyx:=smallint(256*self.control[$04]+self.control[$05]); incxy:=smallint(256*self.control[$08]+self.control[$09]); incyy:=smallint(256*self.control[$0a]+self.control[$0b]); startx:=startx-(16*incyx); starty:=starty-(16*incyy); startx:=startx-(89*incxx); starty:=starty-(89*incxy); actualiza_trozo(0,0,512,512,self.pant,0,0,512,512,screen); //scroll_x_y(4,5,startx shr 3,starty shr 3); end; end.
unit LabelMenu; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, menus; type TFFSPopupMenu = class(TPopupMenu) public constructor create(AOwner:TComponent);override; end; TLabelMenu = class(TLabel) private FPopupMenu: TPopupMenu; procedure SetPopupMenu(const Value: TPopupMenu); { Private declarations } protected { Protected declarations } procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; public { Public declarations } published { Published declarations } property PopupMenu:TPopupMenu read FPopupMenu write SetPopupMenu; end; procedure Register; implementation procedure Register; begin RegisterComponents('FFS Controls', [TLabelMenu, TFFSPopupMenu]); end; { TLabelMenu } procedure TLabelMenu.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var xy : TPoint; begin if Button <> mbLeft then exit; if not assigned(FPopupMenu) then exit; // go ahead xy.x := left; xy.y := top; xy := ClienttoScreen(xy); FPopupMenu.Popup(xy.x-left,xy.y-top+height); end; procedure TLabelMenu.SetPopupMenu(const Value: TPopupMenu); begin FPopupMenu := Value; end; { TFFSPopupMenu } constructor TFFSPopupMenu.create(AOwner: TComponent); begin inherited; TrackButton := tbLeftButton; end; end.
unit np.url; Interface uses np.Buffer, sysUtils; type TNameValue = record Name : string; Value : string; end; TNameValues = TArray<TNameValue>; EURL = class(Exception); TURL = record private FSchema: string; FUserName: string; FPassword: string; FHostName: String; FHost : String; FPort: word; FParams: TNameValues; FPath : String; FfullPath : String; FSplitPath : TArray<String>; function GetPort: word; function GetSplitPath : TArray<String>; function GetDocument: string; public procedure Parse(const AURL: BufferRef); overload; procedure Parse(const AURL: String); overload; class function _DecodeURL(const s : string) : string; static; function HttpHost: string; function IsDefaultPort: Boolean; function HasCredentials : Boolean; function TryGetParam(const AName : String; Out AValue: String; CaseSens:Boolean = false) : Boolean; function ToString : string; property Schema : string read FSchema; property UserName: string read FUserName; property Password: string read FPassword; property HostName: string read FHostName; property Host : string read FHost; property Port: word read GetPort; property Path: string read FPath; property SplitPath : TArray<String> read GetSplitPath; property FullPath: string read FFullPath; property Params: TNameValues read FParams; property Document: string read GetDocument; end; implementation uses np.ut, np.NetEncoding; function _dec(Input: BufferRef): UTF8String; function DecodeHexChar(const C: UTF8Char): Byte; begin case C of '0'..'9': Result := Ord(C) - Ord('0'); 'A'..'F': Result := Ord(C) - Ord('A') + 10; 'a'..'f': Result := Ord(C) - Ord('a') + 10; else raise EConvertError.Create(''); end; end; function DecodeHexPair(const C1, C2: UTF8Char): UTF8Char; inline; begin Result := UTF8Char( DecodeHexChar(C1) shl 4 + DecodeHexChar(C2) ); end; var I: Integer; begin SetLength(result, Input.length * 4); I := 1; while (Input.length > 0) and (I <= Length(result)) do begin case UTF8Char(Input.ref^) of '+': result[I] := ' '; '%': begin Input.TrimL(1); // Look for an escaped % (%%) if UTF8Char(Input.ref^) = '%' then result[I] := '%' else begin // Get an encoded byte, may is a single byte (%<hex>) // or part of multi byte (%<hex>%<hex>...) character if (Input.length < 2) then break; result[I] := DecodeHexPair( UTF8Char( Input.ref[0] ), UTF8Char( Input.ref[1] )); Input.TrimL(1); end; end; else result[I] := UTF8Char(Input.ref^) end; Inc(I); Input.TrimL(1); end; SetLength(result, I-1); end; { TURL } procedure TURL.Parse(const AURL: BufferRef); var I,paramCount,k : integer; url,hostPort,Auth,Path,Params: BufferRef; hasColon,eop:Boolean; begin self := default(TURL); url := Buffer.Create([AURL,Buffer.Create([0])]); I := url.Find( Buffer.Create('://') ); if i >= 0 then begin FSchema := LowerCase( url.slice(0,I).AsUtf8String ); url.TrimL(I+3); end; Auth := Buffer.Null; hostPort := Buffer.Null; path := Buffer.Null; Params := Buffer.Null; I := 0; repeat case url.ref[i] of ord('/'),ord('?'),0: begin hostPort := url.slice(0,i); url.TrimL(i); I := 0; break; end; ord('@'): if (Auth.length=0) then begin Auth := url.slice(0,i); url.TrimL(I+1); I:=0; continue; end; end; inc(i); until false; repeat case url.ref[i] of ord('?'),0: begin path := url.slice(0,i); FfullPath := _dec(url.slice(0,url.length-1) ); url.TrimL(i); I := 0; break; end; end; inc(i); until false; FPath := _dec(path); repeat case url.ref[i] of ord('#'),0: begin params := url.slice(0,i); url.TrimL(i); I := 0; break; end; end; inc(i); until false; // WriteLn('Schema: ', FSchema); // WriteLn('Auth: ', Auth.AsString(CP_USASCII)); if Auth.length > 0 then begin hasColon := false; for i := 0 to Auth.length-1 do begin if auth.ref[i] = ord(':') then begin hasColon := true; FUserName := _dec(Auth.slice(0,i)); FPassword := _dec(Auth.slice(i+1)); break; end; end; if not hasColon then FUserName := _dec( Auth ); end; if Params.length > 0 then begin paramCount := 1; Params.TrimL(1); for i := 0 to Params.length-1 do if params.ref[i] = ord('&') then inc(paramCount); SetLength( FParams, paramCount); i := 0; k := 0; repeat eop := (i=params.length) or (params.ref[i] = ord('&')); if (Fparams[k].Name = '') and ((params.ref[i] = ord('=')) or eop) then begin Fparams[k].Name := _dec( params.slice(0,i)); params.TrimL(i+1); i := 0; end else if (Fparams[k].Value = '') and (eop) then begin Fparams[k].Value := _dec(params.slice(0,i)); params.TrimL(i+1); i := 0; end else inc(i); if eop then inc(k); until k = paramCount; end; FHost := _dec( hostPort ); if hostPort.length > 0 then begin hasColon := false; for i := 0 to hostPort.length-1 do begin if hostPort.ref[i] = ord(':') then begin hasColon := true; FHostName := _dec( hostPort.slice(0,i) ); FPort := StrToIntDef( hostPort.slice(i+1).AsUtf8String, 0) and $FFFF; break; end; end; if not hasColon then FHostName := FHost; end; if FPath = '' then FPath := '/'; end; procedure TURL.parse(const AURL: String); begin parse(Buffer.Create(AUrl)); end; function _enc(const s : string ) : string; inline; begin result := TNetEncoding.URL.Encode(s); end; function TURL.ToString: string; begin if FSchema <> '' then result := FSchema + '://' else result := ''; if HasCredentials then begin result := result + _enc( FUserName )+':'+ _enc( FPassword ) +'@'; end; result := result + _enc(HostName); if not IsDefaultPort then result := result + ':' + UIntToStr(GetPort); result := result + _enc( FfullPath ); end; function TURL.TryGetParam(const AName: String; out AValue: String; CaseSens: Boolean): Boolean; var i : integer; begin result := false; for I := 0 to length(FParams)-1 do begin if (CaseSens and UnicodeSameText(FParams[i].Name,AName)) or (not CaseSens and (FParams[i].Name=AName)) then begin AValue := FParams[i].Value; exit(true); end; end; end; class function TURL._DecodeURL(const s: string): string; begin try // result := TNetEncoding.URL.Decode(s); result := _dec(Buffer.Create(s)); except raise EURL.CreateFmt('Can not decode URL %s',[s]); end; end; function TURL.GetDocument: string; var sp : TArray<String>; inx : integer; begin sp := SplitPath; inx := length(sp)-1; if inx >= 0 then result := sp[inx] else result := ''; end; function TURL.GetPort: word; begin if FPort <> 0 then exit(FPort); if SameText(FSchema,'http') then exit(80); if SameText(FSchema,'https') then exit(443); if SameText(FSchema,'rtsp') then exit(554); raise EURL.Create('Uknown Schema'); end; function TURL.GetSplitPath: TArray<String>; begin if not assigned(FSplitPath) then begin SplitString(FPath, FSplitPath, ['/']); end; result := FSplitPath; end; function TURL.HasCredentials: Boolean; begin result := (FUserName <> '') or (FPassword <> ''); end; function TURL.HttpHost: string; begin if SameText(FSchema,'http') and (Port = 80) then exit(FHost) else exit(Format('%s:%u',[FHostName,Port])); end; function TURL.IsDefaultPort: Boolean; begin if FSchema = '' then exit(true); if SameText(FSchema,'http') and (Port = 80) then exit(true); if SameText(FSchema,'https') and (Port = 443) then exit(true); if SameText(FSchema,'rtsp') and (Port = 554) then exit(true); exit(false); end; end.
unit tutankham_hw; interface uses {$IFDEF WINDOWS}windows,{$ENDIF} m6809,main_engine,controls_engine,gfx_engine,rom_engine, pal_engine,konami_snd,sound_engine; function iniciar_tutankham:boolean; implementation const tutan_rom:array[0..14] of tipo_roms=( (n:'m1.1h';l:$1000;p:$0;crc:$da18679f),(n:'m2.2h';l:$1000;p:$1000;crc:$a0f02c85), (n:'3j.3h';l:$1000;p:$2000;crc:$ea03a1ab),(n:'m4.4h';l:$1000;p:$3000;crc:$bd06fad0), (n:'m5.5h';l:$1000;p:$4000;crc:$bf9fd9b0),(n:'j6.6h';l:$1000;p:$5000;crc:$fe079c5b), (n:'c1.1i';l:$1000;p:$6000;crc:$7eb59b21),(n:'c2.2i';l:$1000;p:$7000;crc:$6615eff3), (n:'c3.3i';l:$1000;p:$8000;crc:$a10d4444),(n:'c4.4i';l:$1000;p:$9000;crc:$58cd143c), (n:'c5.5i';l:$1000;p:$a000;crc:$d7e7ae95),(n:'c6.6i';l:$1000;p:$b000;crc:$91f62b82), (n:'c7.7i';l:$1000;p:$c000;crc:$afd0a81f),(n:'c8.8i';l:$1000;p:$d000;crc:$dabb609b), (n:'c9.9i';l:$1000;p:$e000;crc:$8ea9c6a6)); tutan_sound:array[0..1] of tipo_roms=( (n:'s1.7a';l:$1000;p:0;crc:$b52d01fa),(n:'s2.8a';l:$1000;p:$1000;crc:$9db5c0ce)); //Dip tutan_dip_a:array [0..2] of def_dip=( (mask:$0f;name:'Coin A';number:16;dip:((dip_val:$2;dip_name:'4C 1C'),(dip_val:$5;dip_name:'3C 1C'),(dip_val:$8;dip_name:'2C 1C'),(dip_val:$4;dip_name:'3C 2C'),(dip_val:$1;dip_name:'4C 3C'),(dip_val:$f;dip_name:'1C 1C'),(dip_val:$3;dip_name:'3C 4C'),(dip_val:$7;dip_name:'2C 3C'),(dip_val:$e;dip_name:'1C 2C'),(dip_val:$6;dip_name:'2C 5C'),(dip_val:$d;dip_name:'1C 3C'),(dip_val:$c;dip_name:'1C 4C'),(dip_val:$b;dip_name:'1C 5C'),(dip_val:$a;dip_name:'1C 6C'),(dip_val:$9;dip_name:'1C 7C'),(dip_val:$0;dip_name:'Free Play'))), (mask:$f0;name:'Coin B';number:15;dip:((dip_val:$20;dip_name:'4C 1C'),(dip_val:$50;dip_name:'3C 1C'),(dip_val:$80;dip_name:'2C 1C'),(dip_val:$40;dip_name:'3C 2C'),(dip_val:$10;dip_name:'4C 3C'),(dip_val:$f0;dip_name:'1C 1C'),(dip_val:$30;dip_name:'3C 4C'),(dip_val:$70;dip_name:'2C 3C'),(dip_val:$e0;dip_name:'1C 2C'),(dip_val:$60;dip_name:'2C 5C'),(dip_val:$d0;dip_name:'1C 3C'),(dip_val:$c0;dip_name:'1C 4C'),(dip_val:$b0;dip_name:'1C 5C'),(dip_val:$a0;dip_name:'1C 6C'),(dip_val:$90;dip_name:'1C 7C'),())),()); tutan_dip_b:array [0..6] of def_dip=( (mask:$3;name:'Lives';number:4;dip:((dip_val:$3;dip_name:'3'),(dip_val:$1;dip_name:'4'),(dip_val:$2;dip_name:'5'),(dip_val:$0;dip_name:'255'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$4;name:'Cabinet';number:2;dip:((dip_val:$0;dip_name:'Upright'),(dip_val:$4;dip_name:'Cocktail'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$8;name:'Bonus Life';number:2;dip:((dip_val:$8;dip_name:'30K'),(dip_val:$0;dip_name:'40K'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$30;name:'Difficulty';number:4;dip:((dip_val:$30;dip_name:'Easy'),(dip_val:$20;dip_name:'Normal'),(dip_val:$10;dip_name:'Hard'),(dip_val:$0;dip_name:'Hardest'),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$40;name:'Flash Bomb';number:2;dip:((dip_val:$40;dip_name:'1 per Life'),(dip_val:$0;dip_name:'1 per Game'),(),(),(),(),(),(),(),(),(),(),(),(),(),())), (mask:$80;name:'Demo Sounds';number:2;dip:((dip_val:$80;dip_name:'Off'),(dip_val:$0;dip_name:'On'),(),(),(),(),(),(),(),(),(),(),(),(),(),())),()); var irq_enable:boolean; xorx,xory,rom_nbank,scroll_y:byte; rom_bank:array[0..$f,0..$fff] of byte; procedure update_video_tutankham; var x,y,effx,yscroll,effy,vrambyte,shifted:byte; punt:array[0..$ffff] of word; begin for y:=0 to 255 do begin for x:=0 to 255 do begin effy:=y xor xory; if effy<192 then yscroll:=scroll_y else yscroll:=0; effx:=(x xor xorx)+yscroll; vrambyte:=memoria[effx*128+effy shr 1]; shifted:=vrambyte shr (4*(effy and 1)); punt[y*256+x]:=paleta[shifted and $0f]; end; end; putpixel(0,0,$10000,@punt,1); actualiza_trozo(16,0,224,256,1,0,0,224,256,PANT_TEMP); end; procedure eventos_tutankham; begin if event.arcade then begin //marcade.in1 if arcade_input.up[0] then marcade.in1:=(marcade.in1 and $fb) else marcade.in1:=(marcade.in1 or $4); if arcade_input.down[0] then marcade.in1:=(marcade.in1 and $f7) else marcade.in1:=(marcade.in1 or $8); if arcade_input.left[0] then marcade.in1:=(marcade.in1 and $fe) else marcade.in1:=(marcade.in1 or $1); if arcade_input.right[0] then marcade.in1:=(marcade.in1 and $fd) else marcade.in1:=(marcade.in1 or $2); if arcade_input.but0[0] then marcade.in1:=(marcade.in1 and $df) else marcade.in1:=(marcade.in1 or $20); if arcade_input.but1[0] then marcade.in1:=(marcade.in1 and $ef) else marcade.in1:=(marcade.in1 or $10); if arcade_input.but2[0] then marcade.in1:=(marcade.in1 and $bf) else marcade.in1:=(marcade.in1 or $40); //marcade.in2 if arcade_input.up[1] then marcade.in2:=(marcade.in2 and $fb) else marcade.in2:=(marcade.in2 or $4); if arcade_input.down[1] then marcade.in2:=(marcade.in2 and $f7) else marcade.in2:=(marcade.in2 or $8); if arcade_input.left[1] then marcade.in2:=(marcade.in2 and $fe) else marcade.in2:=(marcade.in2 or $1); if arcade_input.right[1] then marcade.in2:=(marcade.in2 and $fd) else marcade.in2:=(marcade.in2 or $2); if arcade_input.but0[1] then marcade.in2:=(marcade.in2 and $df) else marcade.in2:=(marcade.in2 or $20); if arcade_input.but1[1] then marcade.in2:=(marcade.in2 and $ef) else marcade.in2:=(marcade.in2 or $10); if arcade_input.but2[1] then marcade.in2:=(marcade.in2 and $bf) else marcade.in2:=(marcade.in2 or $40); //service if arcade_input.start[0] then marcade.in0:=(marcade.in0 and $f7) else marcade.in0:=(marcade.in0 or $8); if arcade_input.start[1] then marcade.in0:=(marcade.in0 and $ef) else marcade.in0:=(marcade.in0 or $10); if arcade_input.coin[0] then marcade.in0:=(marcade.in0 and $fe) else marcade.in0:=(marcade.in0 or 1); if arcade_input.coin[1] then marcade.in0:=(marcade.in0 and $fd) else marcade.in0:=(marcade.in0 or 2); end; end; procedure tutankham_principal; var frame_m:single; f:byte; irq_req:boolean; begin init_controls(false,false,false,true); frame_m:=m6809_0.tframes; irq_req:=false; while EmuStatus=EsRuning do begin for f:=0 to $ff do begin //Main CPU m6809_0.run(frame_m); frame_m:=frame_m+m6809_0.tframes-m6809_0.contador; //Sound CPU konamisnd_0.run; if f=239 then begin if (irq_req and irq_enable) then m6809_0.change_irq(ASSERT_LINE); update_video_tutankham; end; end; irq_req:=not(irq_req); eventos_tutankham; video_sync; end; end; function tutankham_getbyte(direccion:word):byte; begin case direccion of 0..$7fff,$8100,$8800..$8fff,$a000..$ffff:tutankham_getbyte:=memoria[direccion]; $8000..$80ff:tutankham_getbyte:=buffer_paleta[direccion and $f]; $8160..$816f:tutankham_getbyte:=marcade.dswb; $8180..$818f:tutankham_getbyte:=marcade.in0; $81a0..$81af:tutankham_getbyte:=marcade.in1; $81c0..$81cf:tutankham_getbyte:=marcade.in2; $81e0..$81ef:tutankham_getbyte:=marcade.dswa; $9000..$9fff:tutankham_getbyte:=rom_bank[rom_nbank,direccion and $fff]; end; end; procedure tutankham_putbyte(direccion:word;valor:byte); var color:tcolor; begin case direccion of 0..$7fff,$8800..$8fff:memoria[direccion]:=valor; $8000..$80ff:begin color.r:=pal3bit(valor shr 0); color.g:=pal3bit(valor shr 3); color.b:=pal2bit(valor shr 6); set_pal_color(color,direccion and $f); buffer_paleta[direccion and $f]:=valor; end; $8100..$810f:scroll_y:=valor; $8200..$82ff:case (direccion and $7) of 0:begin irq_enable:=(valor and 1)<>0; if not(irq_enable) then m6809_0.change_irq(CLEAR_LINE); end; 6:xory:=255*(valor and 1); 7:xorx:=255*(not(valor) and 1); //La x esta invertida... end; $8300..$83ff:rom_nbank:=valor and $f; $8600..$86ff:konamisnd_0.pedir_irq:=HOLD_LINE; $8700..$87ff:konamisnd_0.sound_latch:=valor; $9000..$ffff:; //ROM end; end; //Main procedure reset_tutankham; begin m6809_0.reset; reset_audio; konamisnd_0.reset; marcade.in0:=$ff; marcade.in1:=$ff; marcade.in2:=$ff; irq_enable:=false; end; function iniciar_tutankham:boolean; var f:byte; memoria_temp:array[0..$efff] of byte; begin llamadas_maquina.bucle_general:=tutankham_principal; llamadas_maquina.reset:=reset_tutankham; iniciar_tutankham:=false; iniciar_audio(false); //Pantallas screen_init(1,256,256); iniciar_video(224,256); //Main CPU m6809_0:=cpu_m6809.Create(1536000,$100,TCPU_M6809); m6809_0.change_ram_calls(tutankham_getbyte,tutankham_putbyte); //Sound Chip konamisnd_0:=konamisnd_chip.create(4,TIPO_TIMEPLT,1789772,$100); if not(roms_load(@konamisnd_0.memoria,tutan_sound)) then exit; //cargar roms if not(roms_load(@memoria_temp,tutan_rom)) then exit; copymemory(@memoria[$a000],@memoria_temp[0],$6000); for f:=0 to 8 do copymemory(@rom_bank[f,0],@memoria_temp[$6000+(f*$1000)],$1000); //DIP marcade.dswa:=$ff; marcade.dswb:=$7b; marcade.dswa_val:=@tutan_dip_a; marcade.dswb_val:=@tutan_dip_b; //final reset_tutankham; iniciar_tutankham:=true; end; end.
unit D_ShowInfo; { $Id: D_ShowInfo.pas,v 1.17 2014/08/14 10:48:49 dinishev Exp $ } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, OvcBase, vtlister, StdCtrls, Buttons, ExtCtrls, BottomBtnDlg, HelpCnst, vtStringLister, afwControl, afwInputControl, l3Types, l3Interfaces, evEditorWindow, evMultiSelectEditorWindow, evCustomEditor, evEditorWithOperations, evCustomMemo, evMemo, arInterfaces, afwControlPrim, afwBaseControl, nevControl, evCustomEditorWindowPrim, evCustomEditorWindow, evCustomEditorWindowModelPart, evCustomEditorModelPart; type TShowInfoDlg = class(TBottomBtnDlg, IInfoOut) emInfo: TevMemo; private { Private declarations } public constructor Create(AOwner: TComponent; aCaption : string); reintroduce; procedure AddString(const aStr : string; aFormat : Tl3ClipboardFormat = cf_Text); procedure StartData; procedure EndData; end; procedure ShowInfoDialog(const aCaption: AnsiString; anHelpId: Integer; const aFillProc: TarFillDocInfo); implementation {$R *.DFM} {$Include l3Define.inc} uses l3Base, evTypes, evdStyles, evFacadTextSource, evFacadeSelection ; constructor TShowInfoDlg.Create(AOwner: TComponent; aCaption : string); begin inherited Create(AOwner); Caption := aCaption; emInfo.ReadOnly := True; emInfo.TextSource.Processor.DefaultStyle := ev_saInterface; end; procedure TShowInfoDlg.AddString(const aStr : string; aFormat : Tl3ClipboardFormat = cf_Text); begin evAddStringToTextSource(emInfo.TextSource, aStr, aFormat); end; procedure TShowInfoDlg.EndData; begin emInfo.Modified := False; emInfo.Processor.UndoBuffer.Clear; emInfo.ReadOnly := True; end; procedure TShowInfoDlg.StartData; begin emInfo.ReadOnly := False; end; procedure ShowInfoDialog(const aCaption: AnsiString; anHelpId: Integer; const aFillProc: TarFillDocInfo); var l_Dlg: TShowInfoDlg; begin l_Dlg := TShowInfoDlg.Create(nil, aCaption); try l_Dlg.HelpContext := anHelpId; aFillProc(l_Dlg as IInfoOut); l_Dlg.ShowModal; finally FreeAndNil(l_Dlg); end; end; end.
unit ssSpeedButton; interface uses SysUtils, Classes, Controls, Buttons, Windows, Types, Graphics, CommCtrl, Messages, ImgList, ActnList; const cl_HotTrack = 550944437; cl_HotBorder = 543892488; type TssSpeedButton = class; TssButtonStyle = (ssbsFlat, ssbsUser); TssButtonState = (ssbsUp, ssbsDown, ssbsDisabled); TssButtonType = (ssbtStandard, ssbtChecked); TssButtonViewStyle = (ssvsCaptionGlyph, ssvsCaptionOnly, ssvsGlyphOnly); TssSpeedButtonActionLink = class(TControlActionLink) protected FClient: TssSpeedButton; procedure AssignClient(AClient: TObject); override; function IsCheckedLinked: Boolean; override; function IsGroupIndexLinked: Boolean; override; procedure SetGroupIndex(Value: Integer); override; procedure SetChecked(Value: Boolean); override; procedure SetCaption(const Value: string); override; end; TssSpeedButton = class(TGraphicControl) private FActive: Boolean; FAlignment: TAlignment; FAllwaysShowFrame: boolean; FButtonType: TssButtonType; FChecked: boolean; FColor: TColor; FDisabledImages: TImageList; FDisImageIndex: TImageIndex; FDisImagesChangeLink: TChangeLink; FDropped: Boolean; FDroppedDown: Boolean; FDroppedDownArrowRange: Integer; FGlyph: TBitmap; FGrEndColor: TColor; FGroupIndex: Integer; FGrStartColor: TColor; FHotBorderColor: TColor; FHotTrackColor: TColor; FImageIndex: TImageIndex; FImageRect: TRect; FImages: TImageList; FImagesChangeLink: TChangeLink; FLeftMargin: integer; FOffset: integer; FOver: boolean; FParentColorEx: Boolean; FPopupYOffset: Integer; FShowSeparator: Boolean; FStyle: TssButtonStyle; FTextRect: TRect; FUseGlyph: Boolean; FViewStyle: TssButtonViewStyle; function GetGlyph: TBitmap; procedure CMMouseEnter(var Msg: TMessage); message CM_MOUSEENTER; procedure CMMouseLeave(var Msg: TMessage); message CM_MOUSELEAVE; procedure DrawImage; procedure Get_Glyph; procedure ImageListChange(Sender: TObject); procedure PaintFrame; procedure SetActive(const Value: Boolean); procedure SetAlignment(const Value: TAlignment); procedure SetAllwaysShowFrame(const Value: boolean); procedure SetBorderColor(const Value: TColor); procedure SetButtonType(const Value: TssButtonType); procedure SetChecked(const Value: boolean); procedure SetColor(const Value: TColor); procedure SetDisabledImages(const Value: TImageList); procedure SetDisImageIndex(const Value: TImageIndex); procedure SetDroppedDown(const Value: Boolean); procedure SetDroppedDownArrowRange(const Value: Integer); procedure SetGrEndColor(const Value: TColor); procedure SetGroupIndex(const Value: Integer); procedure SetGrStartColor(const Value: TColor); procedure SetHotTrackColor(const Value: TColor); procedure SetImageIndex(const Value: TImageIndex); procedure SetImages(const Value: TImageList); procedure SetLeftMargin(const Value: integer); procedure SetOffset(const Value: integer); procedure SetParentColorEx(const Value: Boolean); procedure SetShowSeparator(const Value: Boolean); procedure SetStyle(const Value: TssButtonStyle); procedure SetUseGlyph(const Value: Boolean); procedure SetViewStyle(const Value: TssButtonViewStyle); protected FState: TssButtonState; function GetActionLinkClass: TControlActionLinkClass; override; procedure ActionChange(Sender: TObject; CheckDefaults: Boolean); override; procedure Click; override; procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override; procedure Paint; override; procedure SetEnabled(Value: Boolean); override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Loaded; override; property Glyph: TBitmap read GetGlyph; property GrEndColor: TColor read FGrEndColor write SetGrEndColor; property GrStartColor: TColor read FGrStartColor write SetGrStartColor; property UseGlyph: Boolean read FUseGlyph write SetUseGlyph default False; published property Action; property Active: Boolean read FActive write SetActive default False; property Alignment: TAlignment read FAlignment write SetAlignment; property AllwaysShowFrame: boolean read FAllwaysShowFrame write SetAllwaysShowFrame; property Anchors; property BiDiMode; property ButtonType: TssButtonType read FButtonType write SetButtonType; property Checked: boolean read FChecked write SetChecked; property Constraints; property Caption; property Color: TColor read FColor write SetColor default clBtnFace; property DisabledImages: TImageList read FDisabledImages write SetDisabledImages; property DisabledImageIndex: TImageIndex read FDisImageIndex write SetDisImageIndex default -1; property DroppedDown: Boolean read FDroppedDown write SetDroppedDown default False; property DroppedDownArrowRange: Integer read FDroppedDownArrowRange write SetDroppedDownArrowRange default 15; property Enabled; property Font; property GroupIndex: Integer read FGroupIndex write SetGroupIndex; property Height default 25; property HotBorderColor: TColor read FHotBorderColor write SetBorderColor default cl_HotBorder; property HotTrackColor: TColor read FHotTrackColor write SetHotTrackColor default cl_HotTrack; property ImageIndex: TImageIndex read FImageIndex write SetImageIndex; property Images: TImageList read FImages write SetImages; property LeftMargin: integer read FLeftMargin write SetLeftMargin; property Offset: integer read FOffset write SetOffset default 1; property ParentFont; property ParentColorEx: Boolean read FParentColorEx write SetParentColorEx default True; property ParentShowHint; property ParentBiDiMode; property PopupMenu; property PopupYOffset: Integer read FPopupYOffset write FPopupYOffset default 0; property ShowHint; property ShowSeparator: Boolean read FShowSeparator write SetShowSeparator default True; property Style: TssButtonStyle read FStyle write SetStyle; property ViewStyle: TssButtonViewStyle read FViewStyle write SetViewStyle; property Visible; property Width default 25; property OnClick; property OnDblClick; property OnMouseDown; property OnMouseMove; property OnMouseUp; end; //============================================================================================== //============================================================================================== //============================================================================================== implementation uses ExtCtrls, ssGraphUtil; //============================================================================================== procedure TssSpeedButton.ActionChange(Sender: TObject; CheckDefaults: Boolean); begin inherited ActionChange(Sender, CheckDefaults); if Sender is TCustomAction then with TCustomAction(Sender) do begin if Self.ImageIndex <> ImageIndex then Self.ImageIndex := ImageIndex; if Self.Checked <> Checked then Self.Checked := Checked; if Self.GroupIndex <> GroupIndex then Self.GroupIndex := GroupIndex; Invalidate; end; end; //============================================================================================== procedure TssSpeedButton.Click; begin if (FButtonType = ssbtChecked) then begin if Assigned(Action) then begin if not FChecked or (GroupIndex = 0) then TCustomAction(Action).Checked := not FChecked; end else begin if not Checked or (GroupIndex = 0) then Checked := not Checked; end; end; inherited; end; //============================================================================================== procedure TssSpeedButton.CMMouseEnter(var Msg: TMessage); begin inherited; FOver := True; Invalidate; end; //============================================================================================== procedure TssSpeedButton.CMMouseLeave(var Msg: TMessage); begin inherited; FOver := False; FState := ssbsUp; Invalidate; end; //============================================================================================== constructor TssSpeedButton.Create(AOwner: TComponent); begin inherited; FGrStartColor := $00F6F6F6; FGrEndColor := $00F2D8B8; FShowSeparator := True; FParentColorEx := True; FImagesChangeLink := TChangeLink.Create; FImagesChangeLink.OnChange := ImageListChange; FDisImagesChangeLink := TChangeLink.Create; FDisImagesChangeLink.OnChange := ImageListChange; FDisImageIndex := -1; FColor := clBtnFace; Width := 25; Height := 25; FOffset := 1; FDroppedDownArrowRange := 15; FHotBorderColor := cl_HotBorder; FHotTrackColor := cl_HotTrack; FViewStyle := ssvsGlyphOnly; FLeftMargin := 4; FGlyph := TBitmap.Create; FGlyph.Transparent := True; FGlyph.TransparentMode := tmAuto; end; //============================================================================================== destructor TssSpeedButton.Destroy; begin FImagesChangeLink.Free; FDisImagesChangeLink.Free; FGlyph.Free; inherited; end; //============================================================================================== procedure TssSpeedButton.DrawImage; var //FX, FY: Integer; FIndex: Integer; begin if FImages <> nil then begin {if FOver and Enabled and not (csDesigning in ComponentState) then begin FImages.Draw(Canvas, FImageRect.Left, FImageRect.Top, FImageIndex, False); OffsetRect(FImageRect, -1, -1); end; } if (FState = ssbsDown) and not FChecked and not FDropped then OffsetRect(FImageRect, FOffset, FOffset); FIndex := FImageIndex; if not Enabled and (FDisImageIndex <> -1) then FIndex := FDisImageIndex; if not UseGlyph then begin if not Enabled and (FDisabledImages <> nil) then FDisabledImages.Draw(Canvas, FImageRect.Left, FImageRect.Top, FIndex, True) else FImages.Draw(Canvas, FImageRect.Left, FImageRect.Top, FIndex, Enabled); end else begin with Canvas do begin FGlyph.TransparentMode := tmAuto; Draw(FImageRect.Left, FImageRect.Top, FGlyph); end; end; end else if UseGlyph then begin with Canvas do begin FGlyph.TransparentMode := tmAuto; Draw(FImageRect.Left, FImageRect.Top, FGlyph); end; end; end; //============================================================================================== function TssSpeedButton.GetActionLinkClass: TControlActionLinkClass; begin Result := TssSpeedButtonActionLink; end; //============================================================================================== function TssSpeedButton.GetGlyph: TBitmap; begin Result := FGlyph; end; //============================================================================================== procedure TssSpeedButton.Get_Glyph; begin if not Enabled and (FDisabledImages <> nil) then begin if FDisImageIndex >= 0 then FDisabledImages.GetBitmap(FDisImageIndex, FGlyph) else if FImageIndex >= 0 then FDisabledImages.GetBitmap(FImageIndex, FGlyph) else FGlyph.Height := 0; end else begin if (FImageIndex >= 0) and (FImages <> nil) then FImages.GetBitmap(FImageIndex, FGlyph) else FGlyph.Height := 0; end; FGlyph.Transparent := True; //FGlyph.TransparentColor := clFuchsia; end; //============================================================================================== procedure TssSpeedButton.ImageListChange(Sender: TObject); begin Invalidate; end; //============================================================================================== procedure TssSpeedButton.Loaded; begin inherited; end; //============================================================================================== procedure TssSpeedButton.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var P: TPoint; begin inherited MouseDown(Button, Shift, X, Y); FOver := True; if Button = mbLeft then begin FState := ssbsDown; if FDroppedDown and (X > Width - FDroppedDownArrowRange) then FDropped := True; Invalidate; if FDroppedDown and (X > Width - FDroppedDownArrowRange) and Assigned(PopupMenu) then begin P := ClientToScreen(Point(0, Height)); PopupMenu.Popup(P.X, P.Y + FPopupYOffset); FState := ssbsUp; FOver := False; FDropped := False; end; Invalidate; end; end; //============================================================================================== procedure TssSpeedButton.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if FOver and (Button = mbLeft) then FState := ssbsUp; FDropped := False; Invalidate; inherited MouseUp(Button, Shift, X, Y); end; //============================================================================================== procedure TssSpeedButton.Paint; var R: TRect; TH, TW: integer; clTemp: TColor; FArrowRange: Integer; FX, FY: Integer; begin R := GetClientRect; if not Enabled then FState := ssbsDisabled else if Checked and Enabled then FState := ssbsDown; with Canvas do begin Font.Assign(Self.Font); TH := TextHeight('H'); TW := TextWidth(Caption); Brush.Bitmap := AllocPatternBitmap(clBtnFace, clBtnHighlight); if not FDropped and (not FChecked or (not Enabled)) then begin Brush.Color := FColor; end; if FParentColorEx then Brush.Style := bsClear; if not (csDesigning in ComponentState) and (FStyle = ssbsUser) and FOver and not FDropped and Enabled then begin //DrawGradient(Canvas, R, FGrStartColor, FGrEndColor, gdVertical); Brush.Color := FHotTrackColor; end; FillRect(R); Brush.Style := bsSolid; if not (csDesigning in ComponentState) and not (FState = ssbsDisabled) then begin if (FStyle = ssbsUser) and FOver and not FDropped then begin Brush.Color := FHotTrackColor; if FState = ssbsDown then InflateRect(R, -1, -1); //DrawGradient(Canvas, R, FGrStartColor, FGrEndColor, gdVertical); FillRect(R); end else if (FStyle = ssbsUser) and FActive and not FDropped then begin InflateRect(R, -1, -1); DrawGradient(Canvas, R, FGrStartColor, clBtnFace{FGrEndColor}, gdVertical); end else if (FStyle in [ssbsFlat, ssbsUser]) and FChecked and not FOver then begin Brush.Bitmap := AllocPatternBitmap(clBtnFace, clBtnHighlight); //Brush.Color := clBtnHighlight; //Brush.Style := bsDiagCross; FillRect(R); end; end; clTemp := Brush.Color; PaintFrame; if csDesigning in ComponentState then begin Brush.Color := clBlack; FrameRect(R); end; if DroppedDown then FArrowRange := FDroppedDownArrowRange else FArrowRange := 0; if FViewStyle in [ssvsCaptionGlyph, ssvsGlyphOnly] then begin if FImages <> nil then begin case FViewStyle of ssvsGlyphOnly: begin case FAlignment of taLeftJustify: FImageRect.Left := FLeftMargin; taCenter: FImageRect.Left := (Width - FArrowRange - FImages.Width) div 2; taRightJustify:FImageRect.Left := Width - FArrowRange - FImages.Width - FLeftMargin; end; FImageRect.Right := FImageRect.Left + FImages.Width; FImageRect.Top := (Height - FImages.Height) div 2; FImageRect.Bottom := FImageRect.Top + FImages.Height; end; ssvsCaptionGlyph: begin case FAlignment of taLeftJustify: FImageRect.Left := FLeftMargin; taCenter: FImageRect.Left := (Width - FArrowRange - FImages.Width - TW - 4) div 2; taRightJustify:FImageRect.Left := Width - FArrowRange - FImages.Width - TW - 4 - FLeftMargin; end; FImageRect.Right := FImageRect.Left + FImages.Width; FImageRect.Top := (Height - FImages.Height) div 2; FImageRect.Bottom := FImageRect.Top + FImages.Height; end; end; end; // if FImages <> nil if FChecked and not FDropped then OffsetRect(FImageRect, Offset, Offset); DrawImage; end; // if FViewStyle in [ssvsCaptionGlyph, ssvsGlyphOnly] if FDroppedDown then with Canvas do begin Pen.Color := clBlack; FX := Width - FDroppedDownArrowRange + (FDroppedDownArrowRange - 5) div 2; FY := (Height - 3) div 2; if FState = ssbsDown then begin Inc(FX); Inc(FY); end; MoveTo(FX, FY); LineTo(FX + 5, FY); MoveTo(FX + 1, FY + 1); LineTo(FX + 3, FY + 1); LineTo(FX + 2, FY + 3); end; if (FViewStyle in [ssvsCaptionGlyph, ssvsCaptionOnly]) and (Length(Caption) > 0) then begin Brush.Color := clTemp; Font := Self.Font; if not Enabled then Font.Color := clGray; FTextRect.Top := (Self.Height - TH) div 2; if FViewStyle = ssvsCaptionOnly then begin case FAlignment of taLeftJustify: FTextRect.Left := FLeftMargin; taCenter: FTextRect.Left := (Self.Width - FArrowRange - TW) div 2; taRightJustify:FTextRect.Left := Self.Width - FArrowRange - TW - FLeftMargin; end; end else FTextRect.Left := FImageRect.Right + 3; if ((FState = ssbsDown)) and not FDropped and not Checked then begin FTextRect.Top := FTextRect.Top + FOffset; FTextRect.Left := FTextRect.Left + FOffset; end; Brush.Style := bsClear; TextOut(FTextRect.Left, FTextRect.Top, Caption); end; end; end; //============================================================================================== procedure TssSpeedButton.PaintFrame; var R, R1: TRect; begin R := GetClientRect; if csDesigning in ComponentState then begin Frame3D(Canvas, R, clBtnHighLight, clBtnShadow, 1); Exit; end; if (not Enabled) and (not FAllwaysShowFrame) then Exit; if FOver or FChecked or FAllwaysShowFrame then begin case FStyle of ssbsFlat: begin if (FState = ssbsDown) or FChecked then Frame3D(Canvas, R, clBtnShadow, clBtnHighLight, 1) else Frame3D(Canvas, R, clBtnHighLight, clBtnShadow, 1); end; ssbsUser: begin if not FDropped then begin Canvas.Brush.Color := FHotBorderColor; Canvas.Pen.Color := FHotBorderColor; end else begin Canvas.Pen.Color := clBtnShadow; Canvas.Brush.Color := clBtnShadow; end; Canvas.FrameRect(R); if FShowSeparator and FDroppedDown and not FDropped then begin Canvas.MoveTo(Self.Width - FDroppedDownArrowRange, 0); Canvas.LineTo(Self.Width - FDroppedDownArrowRange, Self.Height); end; end;//ssbsUser: end; // case FStyle end else if FActive and (FStyle = ssbsUser) then begin Canvas.Brush.Color := clBtnShadow; Canvas.Pen.Color := clBtnShadow; Canvas.MoveTo(R.Left, R.Top); Canvas.LineTo(R.Right, R.Top); R1 := R; R1.Right := R1.Left + 1; DrawGradient(Canvas, R1, clBtnShadow, clBtnFace, gdVertical); R1 := R; R1.Left := R1.Right - 1; DrawGradient(Canvas, R1, clBtnShadow, clBtnFace, gdVertical); end; end; //============================================================================================== procedure TssSpeedButton.SetActive(const Value: Boolean); begin FActive := Value; Invalidate; end; //============================================================================================== procedure TssSpeedButton.SetAlignment(const Value: TAlignment); begin FAlignment := Value; Invalidate; end; //============================================================================================== procedure TssSpeedButton.SetAllwaysShowFrame(const Value: boolean); begin FAllwaysShowFrame := Value; Invalidate; end; //============================================================================================== procedure TssSpeedButton.SetBorderColor(const Value: TColor); begin FHotBorderColor := Value; Invalidate; end; //============================================================================================== procedure TssSpeedButton.SetButtonType(const Value: TssButtonType); begin if Value <> FButtonType then begin if (Value = ssbtStandard) and FChecked then FChecked := False; FButtonType := Value; Invalidate; end; end; //============================================================================================== procedure TssSpeedButton.SetChecked(const Value: boolean); var i: Integer; begin if Value <> FChecked then begin if (FButtonType = ssbtStandard) and Value then FChecked := False else FChecked := Value; Invalidate; if Value and (FButtonType = ssbtChecked) and (GroupIndex > 0) then begin for i := 0 to Parent.ControlCount - 1 do if (Parent.Controls[i] is TssSpeedButton) and (TssSpeedButton(Parent.Controls[i]).GroupIndex = Self.GroupIndex) and (Parent.Controls[i] <> Self) then TssSpeedButton(Parent.Controls[i]).Checked := False; end; end; end; //============================================================================================== procedure TssSpeedButton.SetColor(const Value: TColor); begin FColor := Value; Invalidate; end; //============================================================================================== procedure TssSpeedButton.SetDisabledImages(const Value: TImageList); begin if FDisabledImages <> nil then FDisabledImages.UnRegisterChanges(FDisImagesChangeLink); FDisabledImages := Value; if FDisabledImages <> nil then FDisabledImages.RegisterChanges(FDisImagesChangeLink); Get_Glyph; Invalidate; end; //============================================================================================== procedure TssSpeedButton.SetDisImageIndex(const Value: TImageIndex); begin FDisImageIndex := Value; Get_Glyph; Invalidate; end; //============================================================================================== procedure TssSpeedButton.SetDroppedDown(const Value: Boolean); begin FDroppedDown := Value; Invalidate; end; //============================================================================================== procedure TssSpeedButton.SetDroppedDownArrowRange(const Value: Integer); begin FDroppedDownArrowRange := Value; end; //============================================================================================== procedure TssSpeedButton.SetEnabled(Value: Boolean); begin inherited; if Value <> Enabled then begin Get_Glyph; Invalidate; end; end; //============================================================================================== procedure TssSpeedButton.SetGrEndColor(const Value: TColor); begin FGrEndColor := Value; Invalidate; end; //============================================================================================== procedure TssSpeedButton.SetGroupIndex(const Value: Integer); begin FGroupIndex := Value; end; //============================================================================================== procedure TssSpeedButton.SetGrStartColor(const Value: TColor); begin FGrStartColor := Value; Invalidate; end; //============================================================================================== procedure TssSpeedButton.SetHotTrackColor(const Value: TColor); begin FHotTrackColor := Value; Invalidate; end; //============================================================================================== procedure TssSpeedButton.SetImageIndex(const Value: TImageIndex); begin if FImageIndex <> Value then begin FImageIndex := Value; Get_Glyph; Invalidate; end; end; //============================================================================================== procedure TssSpeedButton.SetImages(const Value: TImageList); begin if FImages <> nil then FImages.UnRegisterChanges(FImagesChangeLink); FImages := Value; if FImages <> nil then FImages.RegisterChanges(FImagesChangeLink); Get_Glyph; Invalidate; end; //============================================================================================== procedure TssSpeedButton.SetLeftMargin(const Value: integer); begin FLeftMargin := Value; Invalidate; end; //============================================================================================== procedure TssSpeedButton.SetOffset(const Value: integer); begin FOffset := Value; Invalidate; end; //============================================================================================== procedure TssSpeedButton.SetParentColorEx(const Value: Boolean); begin FParentColorEx := Value; Invalidate; end; //============================================================================================== procedure TssSpeedButton.SetShowSeparator(const Value: Boolean); begin FShowSeparator := Value; Invalidate; end; //============================================================================================== procedure TssSpeedButton.SetStyle(const Value: TssButtonStyle); begin FStyle := Value; Invalidate; end; //============================================================================================== procedure TssSpeedButton.SetUseGlyph(const Value: Boolean); begin FUseGlyph := Value; Invalidate; end; //============================================================================================== procedure TssSpeedButton.SetViewStyle(const Value: TssButtonViewStyle); begin if Value <> FViewStyle then begin FViewStyle := Value; Invalidate; end; end; //============================================================================================== //============================================================================================== //============================================================================================== { TssSpeedButtonActionLink } procedure TssSpeedButtonActionLink.AssignClient(AClient: TObject); begin inherited AssignClient(AClient); FClient := AClient as TssSpeedButton; end; //============================================================================================== function TssSpeedButtonActionLink.IsCheckedLinked: Boolean; begin Result := inherited IsCheckedLinked and (FClient.GroupIndex <> 0) and {FClient.AllowAllUp and }(FClient.Checked = (Action as TCustomAction).Checked); end; //============================================================================================== function TssSpeedButtonActionLink.IsGroupIndexLinked: Boolean; begin Result := (FClient is TssSpeedButton) and (TssSpeedButton(FClient).GroupIndex = (Action as TCustomAction).GroupIndex); end; //============================================================================================== procedure TssSpeedButtonActionLink.SetCaption(const Value: string); begin FClient.Caption := Value; FClient.Invalidate; end; //============================================================================================== procedure TssSpeedButtonActionLink.SetChecked(Value: Boolean); begin if IsCheckedLinked then begin TssSpeedButton(FClient).Checked := Value; TssSpeedButton(FClient).Invalidate; end; end; //============================================================================================== procedure TssSpeedButtonActionLink.SetGroupIndex(Value: Integer); begin if IsGroupIndexLinked then TssSpeedButton(FClient).GroupIndex := Value; end; end.
program Project1; type nameType=string[50]; ageType=0..150; {age range: from 0 to 150} var name:nameType; age:ageType; begin write('Enter your name: '); readln(name); write('Enter your age: '); readln(age); writeln; writeln('Your name: ',name); writeln('Your age: ',age); readln; end.
unit Model.ControleTransporte; interface type TControleTransporte = class private var FID: Integer; FDataTransporte: System.TDate; FCliente: Integer; FOperacao: String; FPlaca: String; FMotorista: Integer; FKmSaida: Double; FHoraSaida: System.TTime; FKmRetorno: Double; FHoraRetorno: System.TTime; FKmrodado: Double; FServico: String; FObs: String; FValServico: Double; FStatus: Integer; FLog: String; public property ID: Integer read FID write FID; property DataTransporte: System.TDate read FDataTransporte write FDataTransporte; property Cliente: Integer read FCliente write FCliente; property Operacao: String read FOperacao write FOperacao; property Placa: String read FPlaca write FPlaca; property Motorista: Integer read FMotorista write FMotorista; property KmSaida: Double read FKmSaida write FKmSaida; property HoraSaida: System.TTime read FHoraSaida write FHoraSaida; property KmRetorno: Double read FKmRetorno write FKmRetorno; property HoraRetorno: System.TTime read FHoraRetorno write FHoraRetorno; property KmRodado: Double read FKmrodado write FKmrodado; property Servico: String read FServico write FServico; property Obs: String read FObs write FObs; property ValServico: Double read FValServico write FValServico; property Status: Integer read FStatus write FStatus; property Log: String read FLog write FLog; constructor Create; overload; constructor Create(pFID: Integer; pFDataTransporte: System.TDate; pFCliente: Integer; pFOperacao: String; pFPlaca: String; pFMotorista: Integer; pFKmSaida: Double; pFHoraSaida: System.TTime; pFKmRetorno: Double; pFHoraRetorno: System.TTime; pFKmRodado: Double; pFServico: String; pFObs: String; pFValServico: Double; pFStatus: Integer; pFLog: String); overload; end; implementation constructor TControleTransporte.Create; begin inherited Create; end; constructor TControleTransporte.Create(pFID: Integer; pFDataTransporte: System.TDate; pFCliente: Integer; pFOperacao: String; pFPlaca: String; pFMotorista: Integer; pFKmSaida: Double; pFHoraSaida: System.TTime; pFKmRetorno: Double; pFHoraRetorno: System.TTime; pFKmRodado: Double; pFServico: String; pFObs: String; pFValServico: Double; pFStatus: Integer; pFLog: String); begin FID := pFID; FDataTransporte := pFDataTransporte; FCliente := pFCliente; FOperacao := pFOperacao; FPlaca := pFPlaca; FMotorista := pFMotorista; FKmSaida := pFKmSaida; FHoraSaida := pFHoraSaida; FKmRetorno := pFKmRetorno; FHoraRetorno := pFHoraRetorno; FKmrodado := pFKmrodado; FServico := pFServico; FObs := pFObs; FValServico := pFValServico; FStatus := pFStatus; FLog := pFLog; end; end.
PROGRAM Xref (input, output); {Generate a cross-reference listing from a text file.} CONST MaxWordLength = 20; WordTableSize = 500; NumberTableSize = 2000; MaxLineNumber = 999; TYPE charIndexRange = 1..MaxWordLength; wordIndexRange = 1..WordTableSize; numberIndexRange = 0..NumberTableSize; lineNumberRange = 1..MaxLineNumber; wordType = ARRAY [charIndexRange] OF char; {string type} wordEntryType = RECORD {entry in word table} word : wordType; {word string} firstNumberIndex, {head and tail of } lastNumberIndex { linked number list} : numberIndexRange; END; numberEntryType = RECORD {entry in number table} number : lineNumberRange; {line number} nextIndex {index of next } : numberIndexRange; { in linked list} END; wordTableType = ARRAY [wordIndexRange] OF wordEntryType; numberTableType = ARRAY [numberIndexRange] OF numberEntryType; VAR wordTable : wordTableType; numberTable : numberTableType; nextWordIndex : wordIndexRange; nextNumberIndex : numberIndexRange; lineNumber : lineNumberRange; wordTableFull, numberTableFull : boolean; newLine : boolean; FUNCTION NextChar : char; {Fetch and echo the next character. Print the line number before each new line.} CONST blank = ' '; VAR ch : char; BEGIN newLine := eoln; IF newLine THEN BEGIN readln; writeln; lineNumber := lineNumber + 1; write(lineNumber:5, ' : '); END; IF newLine OR eof THEN BEGIN ch := blank; END ELSE BEGIN read(ch); write(ch); END; NextChar := ch; END; FUNCTION IsLetter(ch : char) : boolean; {Return true if the character is a letter, false otherwise.} BEGIN IsLetter := ((ch >= 'a') AND (ch <= 'z')) OR ((ch >= 'A') AND (ch <= 'Z')); END; FUNCTION ReadWord(VAR buffer : wordType) : boolean; {Extract the next word and place it into the buffer.} CONST blank = ' '; VAR charcount : integer; ch : char; BEGIN ReadWord := false; {Skip over any preceding non-letters.} IF NOT eof THEN BEGIN REPEAT ch := NextChar; UNTIL eof OR IsLetter(ch); END; {Find a letter?} IF NOT eof THEN BEGIN charcount := 0; {Place the word's letters into the buffer. Downshift uppercase letters.} WHILE IsLetter(ch) DO BEGIN IF charcount < MaxWordLength THEN BEGIN IF (ch >= 'A') AND (ch <= 'Z') THEN BEGIN ch := chr(ord(ch) + (ord('a') - ord('A'))); END; charcount := charcount + 1; buffer[charcount] := ch; END; ch := NextChar; END; {Pad the rest of the buffer with blanks.} FOR charcount := charcount + 1 TO MaxWordLength DO BEGIN buffer[charcount] := blank; END; ReadWord := true; END; END; PROCEDURE AppendLineNumber(VAR entry : wordEntryType); {Append the current line number to the end of the current word entry's linked list of numbers.} BEGIN IF nextNumberIndex < NumberTableSize THEN BEGIN {entry.lastnumberindex is 0 if this is the word's first number. Otherwise, it is the number table index of the last number in the list, which we now extend for the new number.} IF entry.lastNumberIndex = 0 THEN BEGIN entry.firstNumberIndex := nextNumberIndex; END ELSE BEGIN numberTable[entry.lastNumberIndex].nextIndex := nextNumberIndex; END; {Set the line number at the end of the list.} numberTable[nextNumberIndex].number := lineNumber; numberTable[nextNumberIndex].nextIndex := 0; entry.lastNumberIndex := nextNumberIndex; nextNumberIndex := nextNumberIndex + 1; END ELSE BEGIN numberTableFull := true; END; END; PROCEDURE EnterWord; {Enter the current word into the word table. Each word is first read into the end of the table.} VAR i : wordIndexRange; BEGIN {By the time we process a word at the end of an input line, lineNumber has already been incremented, so temporarily decrement it.} IF newLine THEN lineNumber := lineNumber - 1; {Search to see if the word had already been entered previously. Each time it's read in, it's placed at the end of the word table.} i := 1; WHILE wordTable[i].word <> wordTable[nextWordIndex].word DO BEGIN i := i + 1; END; {Entered previously: Update the existing entry.} IF i < nextWordIndex THEN BEGIN AppendLineNumber(wordTable[i]); END {New word: Initialize the entry at the end of the table.} ELSE IF nextWordIndex < WordTableSize THEN BEGIN wordTable[i].lastNumberIndex := 0; AppendLineNumber(wordTable[i]); nextWordIndex := nextWordIndex + 1; END {Oops. Table overflow!} ELSE wordTableFull := true; IF newLine THEN lineNumber := lineNumber + 1; END; PROCEDURE SortWords; {Sort the words alphabetically.} VAR i, j : wordIndexRange; temp : wordEntryType; BEGIN FOR i := 1 TO nextWordIndex - 2 DO BEGIN FOR j := i + 1 TO nextWordIndex - 1 DO BEGIN IF wordTable[i].word > wordTable[j].word THEN BEGIN temp := wordTable[i]; wordTable[i] := wordTable[j]; wordTable[j] := temp; END; END; END; END; PROCEDURE PrintNumbers(i : numberIndexRange); {Print a word's linked list of line numbers.} BEGIN REPEAT write(numberTable[i].number:4); i := numberTable[i].nextIndex; UNTIL i = 0; writeln; END; PROCEDURE PrintXref; {Print the cross reference listing.} VAR i : wordIndexRange; BEGIN SortWords; writeln; writeln; writeln('Cross-reference'); writeln('---------------'); writeln; FOR i := 1 TO nextWordIndex - 1 DO BEGIN write(wordTable[i].word); PrintNumbers(wordTable[i].firstNumberIndex); END; END; BEGIN {Xref} wordTableFull := false; numberTableFull := false; nextWordIndex := 1; nextNumberIndex := 1; lineNumber := 1; write(' 1 : '); {First read the words.} WHILE NOT (eof OR wordTableFull OR numberTableFull) DO BEGIN {Read each word into the last entry of the word table and then enter it into its correct location.} IF ReadWord(wordtable[nextwordIndex].Word) THEN BEGIN EnterWord; END; END; {Then print the cross reference listing if all went well.} IF wordTableFull THEN BEGIN writeln; writeln('*** The word table is not large enough. ***'); END ELSE IF numberTableFull THEN BEGIN writeln; writeln('*** The number table is not large enough. ***'); END ELSE BEGIN PrintXref; END; {Print final stats.} writeln; writeln((nextWordIndex - 1):5, ' word entries.'); writeln((nextNumberIndex - 1):5, ' line number entries.'); END {Xref}.
unit NtUtils.Processes; interface uses Winapi.WinNt, Ntapi.ntpsapi, NtUtils.Exceptions; const // Ntapi.ntpsapi NtCurrentProcess: THandle = THandle(-1); type TProcessHandleEntry = Ntapi.ntpsapi.TProcessHandleTableEntryInfo; // Open a process (always succeeds for the current PID) function NtxOpenProcess(out hProcess: THandle; PID: NativeUInt; DesiredAccess: TAccessMask; HandleAttributes: Cardinal = 0): TNtxStatus; // Reopen a handle to the current process with the specific access function NtxOpenCurrentProcess(out hProcess: THandle; DesiredAccess: TAccessMask; HandleAttributes: Cardinal = 0): TNtxStatus; // Query variable-size information function NtxQueryProcess(hProcess: THandle; InfoClass: TProcessInfoClass; out Status: TNtxStatus): Pointer; // Set variable-size information function NtxSetProcess(hProcess: THandle; InfoClass: TProcessInfoClass; Data: Pointer; DataSize: Cardinal): TNtxStatus; type NtxProcess = class // Query fixed-size information class function Query<T>(hProcess: THandle; InfoClass: TProcessInfoClass; out Buffer: T): TNtxStatus; static; // Set fixed-size information class function SetInfo<T>(hProcess: THandle; InfoClass: TProcessInfoClass; const Buffer: T): TNtxStatus; static; end; // Enumerate handles of a process function NtxEnumerateHandlesProcess(hProcess: THandle; out Handles: TArray<TProcessHandleEntry>): TNtxStatus; // Query a string function NtxQueryStringProcess(hProcess: THandle; InfoClass: TProcessInfoClass; out Str: String): TNtxStatus; // Try to query image name in Win32 format function NtxTryQueryImageProcessById(PID: NativeUInt): String; // Fail if the current process is running under WoW64 function NtxAssertNotWoW64: TNtxStatus; implementation uses Ntapi.ntdef, Ntapi.ntstatus, Ntapi.ntobapi, Ntapi.ntseapi, NtUtils.Objects, NtUtils.Access.Expected; function NtxOpenProcess(out hProcess: THandle; PID: NativeUInt; DesiredAccess: TAccessMask; HandleAttributes: Cardinal = 0): TNtxStatus; var ClientId: TClientId; ObjAttr: TObjectAttributes; begin if PID = NtCurrentProcessId then begin hProcess := NtCurrentProcess; Result.Status := STATUS_SUCCESS; end else begin InitializeObjectAttributes(ObjAttr, nil, HandleAttributes); ClientId.Create(PID, 0); Result.Location := 'NtOpenProcess'; Result.LastCall.CallType := lcOpenCall; Result.LastCall.AccessMask := DesiredAccess; Result.LastCall.AccessMaskType := @ProcessAccessType; Result.Status := NtOpenProcess(hProcess, DesiredAccess, ObjAttr, ClientId); end; end; function NtxOpenCurrentProcess(out hProcess: THandle; DesiredAccess: TAccessMask; HandleAttributes: Cardinal): TNtxStatus; var Flags: Cardinal; begin // Duplicating the pseudo-handle is more reliable then opening process by PID if DesiredAccess = MAXIMUM_ALLOWED then begin Flags := DUPLICATE_SAME_ACCESS; DesiredAccess := 0; end else Flags := 0; Result.Location := 'NtDuplicateObject'; Result.Status := NtDuplicateObject(NtCurrentProcess, NtCurrentProcess, NtCurrentProcess, hProcess, DesiredAccess, HandleAttributes, Flags); end; function NtxQueryProcess(hProcess: THandle; InfoClass: TProcessInfoClass; out Status: TNtxStatus): Pointer; var BufferSize, Required: Cardinal; begin Status.Location := 'NtQueryInformationProcess'; Status.LastCall.CallType := lcQuerySetCall; Status.LastCall.InfoClass := Cardinal(InfoClass); Status.LastCall.InfoClassType := TypeInfo(TProcessInfoClass); RtlxComputeProcessQueryAccess(Status.LastCall, InfoClass); BufferSize := 0; repeat Result := AllocMem(BufferSize); Required := 0; Status.Status := NtQueryInformationProcess(hProcess, InfoClass, Result, BufferSize, @Required); if not Status.IsSuccess then begin FreeMem(Result); Result := nil; end; until not NtxExpandBuffer(Status, BufferSize, Required); end; function NtxSetProcess(hProcess: THandle; InfoClass: TProcessInfoClass; Data: Pointer; DataSize: Cardinal): TNtxStatus; begin Result.Location := 'NtSetInformationProcess'; Result.LastCall.CallType := lcQuerySetCall; Result.LastCall.InfoClass := Cardinal(InfoClass); Result.LastCall.InfoClassType := TypeInfo(TProcessInfoClass); RtlxComputeProcessSetAccess(Result.LastCall, InfoClass); Result.Status := NtSetInformationProcess(hProcess, InfoClass, Data, DataSize); end; class function NtxProcess.Query<T>(hProcess: THandle; InfoClass: TProcessInfoClass; out Buffer: T): TNtxStatus; begin Result.Location := 'NtQueryInformationProcess'; Result.LastCall.CallType := lcQuerySetCall; Result.LastCall.InfoClass := Cardinal(InfoClass); Result.LastCall.InfoClassType := TypeInfo(TProcessInfoClass); RtlxComputeProcessQueryAccess(Result.LastCall, InfoClass); Result.Status := NtQueryInformationProcess(hProcess, InfoClass, @Buffer, SizeOf(Buffer), nil); end; class function NtxProcess.SetInfo<T>(hProcess: THandle; InfoClass: TProcessInfoClass; const Buffer: T): TNtxStatus; begin Result := NtxSetProcess(hProcess, InfoClass, @Buffer, SizeOf(Buffer)); end; function NtxEnumerateHandlesProcess(hProcess: THandle; out Handles: TArray<TProcessHandleEntry>): TNtxStatus; var Buffer: PProcessHandleSnapshotInformation; i: Integer; begin Buffer := NtxQueryProcess(hProcess, ProcessHandleInformation, Result); if Result.IsSuccess then begin SetLength(Handles, Buffer.NumberOfHandles); for i := 0 to High(Handles) do Handles[i] := Buffer.Handles{$R-}[i]{$R+}; FreeMem(Buffer); end; end; function NtxQueryStringProcess(hProcess: THandle; InfoClass: TProcessInfoClass; out Str: String): TNtxStatus; var Buffer: PUNICODE_STRING; begin case InfoClass of ProcessImageFileName, ProcessImageFileNameWin32, ProcessCommandLineInformation: begin Buffer := NtxQueryProcess(hProcess, InfoClass, Result); if Result.IsSuccess then begin Str := Buffer.ToString; FreeMem(Buffer); end; end; else Result.Location := 'NtxQueryStringProcess'; Result.Status := STATUS_INVALID_INFO_CLASS; Exit; end; end; function NtxTryQueryImageProcessById(PID: NativeUInt): String; var hProcess: THandle; begin Result := ''; if not NtxOpenProcess(hProcess, PID, PROCESS_QUERY_LIMITED_INFORMATION ).IsSuccess then Exit; NtxQueryStringProcess(hProcess, ProcessImageFileNameWin32, Result); NtxSafeClose(hProcess); end; function NtxAssertNotWoW64: TNtxStatus; var IsWoW64: NativeUInt; begin Result := NtxProcess.Query<NativeUInt>(NtCurrentProcess, ProcessWow64Information, IsWoW64); if Result.IsSuccess and (IsWoW64 <> 0) then begin Result.Location := '[WoW64 assertion]'; Result.Status := STATUS_ASSERTION_FAILURE; end; end; end.
unit lukIDGenerator; { Генератор номеров документов для документов ЛУКойла } interface uses l3Base, l3ValLst; type TlukGetSelfID = procedure (out NewID: Integer) of Object; TlukGetLinkID = procedure (const aFileName: String; out NewID: Integer) of Object; TlukIDGenerator = class(Tl3Base) private f_CurDocID: Integer; f_Files: Tl3ValueList; f_NextDocID: Integer; f_SegmentID: Integer; function ConvertFileNameToID(const aFileName: String): Integer; function GetFileName(const aFileName: String): string; function pm_GetNextDocID: Integer; protected procedure Cleanup; override; public constructor Create; procedure AddFileName(const aFileName: String); procedure GetLinkID(const aFileName: String; out NewID: Integer); function GetRelID: Integer; procedure GetSelfID(out NewID: Integer); property NextDocID: Integer read pm_GetNextDocID write f_NextDocID; property SegmentID: Integer read f_SegmentID write f_SegmentID; end; implementation uses SysUtils, StrUtils; constructor TlukIDGenerator.Create; begin inherited Create; f_Files := Tl3ValueList.Create(); end; procedure TlukIDGenerator.Cleanup; begin FreeAndNil(f_Files); inherited Cleanup; end; procedure TlukIDGenerator.AddFileName(const aFileName: String); // сюда приходит полный путь var l_FileName: String; begin l_FileName:= Format('\%d\%s', [f_SegmentID, ChangeFileExt(ExtractFileName(aFileName), '.sdf')]); f_CurDocID:= ConvertFileNameToID(l_FileName); end; function TlukIDGenerator.ConvertFileNameToID(const aFileName: String): Integer; begin Result:= StrToIntDef(f_Files.Values[AnsiUpperCase(aFileName)], 0); if Result = 0 then begin Result:= NextDocID; f_Files.Values[AnsiUpperCase(aFileName)]:= IntToStr(Result); end; end; function TlukIDGenerator.GetFileName(const aFileName: String): string; begin Result := ChangeFileExt(ExtractFileName(aFileName), '.sdf'); end; procedure TlukIDGenerator.GetLinkID(const aFileName: String; out NewID: Integer); // Сюда приходит "огрызок" - /segment/file var l_FileName: String; begin l_FileName:= AnsiReplaceStr(aFileName , '/', '\'); if ExtractFileExt(l_FileName) = '' then l_FileName:= ChangeFileExt(l_FileName, '.sdf'); NewID:= ConvertFileNameToID(l_FileName); end; function TlukIDGenerator.GetRelID: Integer; begin Result := NextDocID; end; procedure TlukIDGenerator.GetSelfID(out NewID: Integer); begin NewID:= f_CurDocID; end; function TlukIDGenerator.pm_GetNextDocID: Integer; begin Result := f_NextDocID; Inc(f_NextDocID); end; end.
{=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=] Copyright (c) 2013, Jarl K. <Slacky> Holta || http://github.com/WarPie All rights reserved. For more info see: Copyright.txt [=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=} {* Returns a cropped area of the matrix. *} function GetArea(const Mat:T2DByteArray; x1,y1,x2,y2:Int32): T2DByteArray; overload; var Y,W,H:Integer; begin H := High(Mat); if (H = -1) then NewException('Matrix must be initalized'); W := High(Mat[0]); x2 := Min(x2, W); y2 := Min(y2, H); SetLength(Result, y2-y1+1, x2-x1+1); for Y:=y1 to y2 do Move(Mat[y][x1], Result[y-y1][0], (x2-x1+1)*SizeOf(Byte)); end; function GetArea(const Mat:T2DIntArray; x1,y1,x2,y2:Int32): T2DIntArray; overload; var Y,W,H:Integer; begin H := High(Mat); if (H = -1) then NewException('Matrix must be initalized'); W := High(Mat[0]); x2 := Min(x2, W); y2 := Min(y2, H); SetLength(Result, y2-y1+1, x2-x1+1); for Y:=y1 to y2 do Move(Mat[y][x1], Result[y-y1][0], (x2-x1+1)*SizeOf(Int32)); end; function GetArea(const Mat:T2DFloatArray; x1,y1,x2,y2:Int32): T2DFloatArray; overload; var Y,W,H:Integer; begin H := High(Mat); if (H = -1) then NewException('Matrix must be initalized'); W := High(Mat[0]); x2 := Min(x2, W); y2 := Min(y2, H); SetLength(Result, y2-y1+1, x2-x1+1); for Y:=y1 to y2 do Move(Mat[y][x1], Result[y-y1][0], (x2-x1+1)*SizeOf(Single)); end; function GetArea(const Mat:T2DDoubleArray; x1,y1,x2,y2:Int32): T2DDoubleArray; overload; var Y,W,H:Integer; begin H := High(Mat); if (H = -1) then NewException('Matrix must be initalized'); W := High(Mat[0]); x2 := Min(x2, W); y2 := Min(y2, H); SetLength(Result, y2-y1+1, x2-x1+1); for Y:=y1 to y2 do Move(Mat[y][x1], Result[y-y1][0], (x2-x1+1)*SizeOf(Double)); end; function GetArea(const Mat:T2DExtArray; x1,y1,x2,y2:Int32): T2DExtArray; overload; var Y,W,H:Integer; begin H := High(Mat); if (H = -1) then NewException('Matrix must be initalized'); W := High(Mat[0]); x2 := Min(x2, W); y2 := Min(y2, H); SetLength(Result, y2-y1+1, x2-x1+1); for Y:=y1 to y2 do Move(Mat[y][x1], Result[y-y1][0], (x2-x1+1)*SizeOf(Extended)); end;
unit DeleteAvoidanceZoneUnit; interface uses SysUtils, BaseExampleUnit; type TDeleteAvoidanceZone = class(TBaseExample) public procedure Execute(TerritoryId: String); end; implementation procedure TDeleteAvoidanceZone.Execute(TerritoryId: String); var ErrorString: String; begin Route4MeManager.AvoidanceZone.Remove(TerritoryId, ErrorString); WriteLn(''); if (ErrorString = EmptyStr) then begin WriteLn('DeleteAvoidanceZone executed successfully'); WriteLn(Format('Territory ID: %s', [TerritoryId])); end else WriteLn(Format('DeleteAvoidanceZone error: "%s"', [ErrorString])); end; end.
Program horas_extras; {Uma empresa decidiu dar uma gratificação de Natal a seus funcionários, baseada no número de horas extras e no número de horas que o funcionário faltou ao trabalho. O valor do prêmio é obtido pela consulta à tabela que se segue, na qual: H = número de horas extras – (2/3 * (número de horas falta)) h (MiNuTos) PrêMio (r$) > = 2.400 - 500,00 1.800 2.400 - 400,00 1.200 1.800 - 300,00 600 1.200 - 200,00 < 600 - 100,00} var horas_ext, horas_fal, tot_hor : real; Begin write('Total de horas extras: '); readln(horas_ext); write('Total de horas faltas: '); readln(horas_fal); tot_hor := horas_ext - 2/3 * horas_fal; writeln('Você fez um total de ',tot_hor:0:2,' horas extras no ano.'); if tot_hor >= 2400 then writeln('Seu prêmio será de R$ 500,00') else if tot_hor >= 1800 then writeln('Seu prêmio será de R$ 400,00') else if tot_hor >= 1200 then writeln('Seu prêmio será de R$ 300,00') else if tot_hor >= 600 then writeln('Seu prêmio será de R$ 200,00') else writeln('Seu prêmio será de R$ 100,00'); readln; End.
{******************************************************************************} { } { Library: Fundamentals 5.00 } { File name: flcUtils.pas } { File version: 5.76 } { Description: Utility functions. } { } { Copyright: Copyright (c) 2000-2021, David J Butler } { 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. } { 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 REGENTS 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. } { } { Github: https://github.com/fundamentalslib } { E-mail: fundamentals.library at gmail.com } { } { Revision history: } { } { 2000/02/02 0.01 Initial version. } { 2000/03/08 1.02 Added array functions. } { 2000/04/10 1.03 Added Append, Renamed Delete to Remove and added } { StringArrays. } { 2000/05/03 1.04 Added Path functions. } { 2000/05/08 1.05 Revision. } { 2000/06/01 1.06 Added Range and Dup constructors for dynamic arrays. } { 2000/06/03 1.07 Added ArrayInsert functions. } { 2000/06/06 1.08 Added bit functions from cMaths. } { 2000/06/08 1.09 Removed data structure classes. } { 2000/06/10 1.10 Added linked lists for Integer, Int64, Extended and } { String. } { 2000/06/14 1.11 cUtils now generated from a template using a source } { pre-processor. } { 2000/07/04 1.12 Revision for first Fundamentals release. } { 2000/07/24 1.13 Added TrimArray functions. } { 2000/07/26 1.14 Added Difference functions. } { 2000/09/02 1.15 Added RemoveDuplicates functions. } { Added Count functions. } { 2000/09/27 1.16 Fixed bug in ArrayInsert. } { 2000/11/29 1.17 Moved SetFPUPrecision to cSysUtils. } { 2001/05/03 1.18 Improved bit functions. Added Pascal versions of } { assembly routines. } { 2001/05/13 1.19 Added CharCount. } { 2001/05/15 1.20 Added PosNext (ClassType, ObjectArray). } { 2001/05/18 1.21 Added hashing functions from cMaths. } { 2001/07/07 1.22 Added TBinaryTreeNode. } { 2001/11/11 2.23 Revision. } { 2002/01/03 2.24 Added EncodeBase64, DecodeBase64 from cMaths and } { optimized. Added LongWordToHex, HexToLongWord. } { 2002/03/30 2.25 Fixed bug in DecodeBase64. } { 2002/04/02 2.26 Removed dependencies on all other units to remove } { initialization code associated with SysUtils. This } { allows usage of cUtils in projects and still have } { very small binaries. } { Fixed bug in LongWordToHex. } { 2002/05/31 3.27 Refactored for Fundamentals 3. } { Moved linked lists to cLinkedLists. } { 2002/08/09 3.28 Added HashInteger. } { 2002/10/06 3.29 Renamed Cond to iif. } { 2002/12/12 3.30 Small revisions. } { 2003/03/14 3.31 Removed ApproxZero. Added FloatZero, FloatsEqual and } { FloatsCompare. Added documentation and test cases for } { comparison functions. } { Added support for Currency type. } { 2003/07/27 3.32 Added fast ZeroMem and FillMem routines. } { 2003/09/11 3.33 Added InterfaceArray functions. } { 2004/01/18 3.34 Added WideStringArray functions. } { 2004/07/24 3.35 Optimizations of Sort functions. } { 2004/08/01 3.36 Improved validation in base conversion routines. } { 2004/08/22 3.37 Compilable with Delphi 8. } { 2005/06/10 4.38 Compilable with FreePascal 2 Win32 i386. } { 2005/08/19 4.39 Compilable with FreePascal 2 Linux i386. } { 2005/09/21 4.40 Revised for Fundamentals 4. } { 2006/03/04 4.41 Compilable with Delphi 2006 Win32/.NET. } { 2007/06/08 4.42 Compilable with FreePascal 2.04 Win32 i386 } { 2007/08/08 4.43 Changes to memory functions for Delphi 2006/2007. } { 2008/06/06 4.44 Fixed bug in case insensitive hashing functions. } { 2009/10/09 4.45 Compilable with Delphi 2009 Win32/.NET. } { 2010/06/27 4.46 Compilable with FreePascal 2.4.0 OSX x86-64. } { 2012/04/03 4.47 Support for Delphi XE string and integer types. } { 2012/04/04 4.48 Moved dynamic arrays functions to cDynArrays. } { 2012/04/11 4.49 StringToFloat/FloatToStr functions. } { 2012/08/26 4.50 UnicodeString versions of functions. } { 2013/01/29 4.51 Compilable with Delphi XE3 x86-64. } { 2013/03/22 4.52 Minor fixes. } { 2013/05/12 4.53 Added string type definitions. } { 2013/11/15 4.54 Revision. } { 2015/03/13 4.55 RawByteString functions. } { 2015/05/06 4.56 Add UTF functions from unit cUnicodeCodecs. } { 2015/06/07 4.57 Moved bit functions to unit cBits32. } { 2016/01/09 5.58 Revised for Fundamentals 5. } { 2016/01/29 5.59 StringRefCount functions. } { 2017/10/07 5.60 Moved functions to units flcBase64, flcUTF, flcCharSet. } { 2017/11/01 5.61 Added TBytes functions. } { 2018/07/11 5.62 Moved functions to units flcFloats, flcASCII. } { 2018/07/11 5.63 Moved standard types to unit flcStdTypes. } { 2018/08/12 5.64 Removed WideString functions and CLR code. } { 2018/08/14 5.65 ByteChar changes. } { 2019/04/02 5.66 Swap changes. } { 2020/03/13 5.67 NativeInt changes. } { 2020/03/30 5.68 EqualMem optimisations and tests. } { 2020/06/02 5.69 String to/from UInt64 conversion functions. } { 2020/06/07 5.70 Remove IInterface definition for Delphi 5. } { 2020/06/15 5.71 Byte/Word versions of memory functions. } { 2020/07/20 5.72 Replace Bounded functions with IsInRange functions. } { 2020/07/25 5.73 Optimise EqualMem and EqualMemNoAsciiCase. } { 2020/07/25 5.74 Add common String and Ascii functions. } { 2020/12/12 5.75 Compilable with Delphi 2007 Win32. } { 2021/01/20 5.76 Move tests to seperate unit. } { } { Supported compilers: } { } { Delphi 7-10.4 Win32/Win64 5.76 2021/01/20 } { Delphi 10.2-10.4 Linux64 5.69 2020/06/02 } { FreePascal 3.0.4 Win64 5.69 2020/06/02 } { } {******************************************************************************} {$INCLUDE ..\flcInclude.inc} {$IFDEF FREEPASCAL} {$WARNINGS OFF} {$HINTS OFF} {$ENDIF} unit flcUtils; interface uses { System } SysUtils, { Fundamentals } flcStdTypes; { } { Release } { } const FundamentalsRelease = '5.0.9'; FundamentalsTitleText = 'Fundamentals Library ' + FundamentalsRelease; { } { Exception } { } type ERangeCheckError = class(Exception) public constructor Create; end; { } { Integer functions } { } { Min returns smallest of A and B } { Max returns greatest of A and B } function MinInt(const A, B: Int64): Int64; {$IFDEF UseInline}inline;{$ENDIF} function MaxInt(const A, B: Int64): Int64; {$IFDEF UseInline}inline;{$ENDIF} function MinUInt(const A, B: UInt64): UInt64; {$IFDEF UseInline}inline;{$ENDIF} function MaxUInt(const A, B: UInt64): UInt64; {$IFDEF UseInline}inline;{$ENDIF} function MinNatInt(const A, B: NativeInt): NativeInt; {$IFDEF UseInline}inline;{$ENDIF} function MaxNatInt(const A, B: NativeInt): NativeInt; {$IFDEF UseInline}inline;{$ENDIF} function MinNatUInt(const A, B: NativeUInt): NativeUInt; {$IFDEF UseInline}inline;{$ENDIF} function MaxNatUInt(const A, B: NativeUInt): NativeUInt; {$IFDEF UseInline}inline;{$ENDIF} { IsInRange returns True if Value is in range of type } function IsIntInInt32Range(const Value: Int64): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function IsIntInInt16Range(const Value: Int64): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function IsIntInInt8Range(const Value: Int64): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function IsUIntInInt32Range(const Value: UInt64): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function IsUIntInInt16Range(const Value: UInt64): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function IsUIntInInt8Range(const Value: UInt64): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function IsIntInUInt32Range(const Value: Int64): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function IsIntInUInt16Range(const Value: Int64): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function IsIntInUInt8Range(const Value: Int64): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function IsUIntInUInt32Range(const Value: UInt64): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function IsUIntInUInt16Range(const Value: UInt64): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function IsUIntInUInt8Range(const Value: UInt64): Boolean; {$IFDEF UseInline}inline;{$ENDIF} { } { Memory operations } { } const Bytes1KB = 1024; Bytes1MB = 1024 * Bytes1KB; Bytes1GB = 1024 * Bytes1MB; Bytes64KB = 64 * Bytes1KB; Bytes64MB = 64 * Bytes1MB; Bytes2GB = 2 * Word32(Bytes1GB); procedure FillMem(var Buf; const Count: NativeInt; const Value: Byte); {$IFDEF UseInline}inline;{$ENDIF} procedure ZeroMem(var Buf; const Count: NativeInt); {$IFDEF UseInline}inline;{$ENDIF} procedure GetZeroMem(var P: Pointer; const Size: NativeInt); {$IFDEF UseInline}inline;{$ENDIF} procedure MoveMem(const Source; var Dest; const Count: NativeInt); {$IFDEF UseInline}inline;{$ENDIF} function EqualMem(const Buf1; const Buf2; const Count: NativeInt): Boolean; function EqualMemNoAsciiCaseB(const Buf1; const Buf2; const Count: NativeInt): Boolean; function EqualMemNoAsciiCaseW(const Buf1; const Buf2; const Count: NativeInt): Boolean; function CompareMemB(const Buf1; const Buf2; const Count: NativeInt): Integer; function CompareMemW(const Buf1; const Buf2; const Count: NativeInt): Integer; function CompareMemNoAsciiCaseB(const Buf1; const Buf2; const Count: NativeInt): Integer; function CompareMemNoAsciiCaseW(const Buf1; const Buf2; const Count: NativeInt): Integer; function LocateMemB(const Buf1; const Count1: NativeInt; const Buf2; const Count2: NativeInt): NativeInt; function LocateMemW(const Buf1; const Count1: NativeInt; const Buf2; const Count2: NativeInt): NativeInt; function LocateMemNoAsciiCaseB(const Buf1; const Count1: NativeInt; const Buf2; const Count2: NativeInt): NativeInt; function LocateMemNoAsciiCaseW(const Buf1; const Count1: NativeInt; const Buf2; const Count2: NativeInt): NativeInt; procedure ReverseMem(var Buf; const Size: NativeInt); { } { ByteChar ASCII constants } { } const AsciiNULL = ByteChar(#0); AsciiSOH = ByteChar(#1); AsciiSTX = ByteChar(#2); AsciiETX = ByteChar(#3); AsciiEOT = ByteChar(#4); AsciiENQ = ByteChar(#5); AsciiACK = ByteChar(#6); AsciiBEL = ByteChar(#7); AsciiBS = ByteChar(#8); AsciiHT = ByteChar(#9); AsciiLF = ByteChar(#10); AsciiVT = ByteChar(#11); AsciiFF = ByteChar(#12); AsciiCR = ByteChar(#13); AsciiSO = ByteChar(#14); AsciiSI = ByteChar(#15); AsciiDLE = ByteChar(#16); AsciiDC1 = ByteChar(#17); AsciiDC2 = ByteChar(#18); AsciiDC3 = ByteChar(#19); AsciiDC4 = ByteChar(#20); AsciiNAK = ByteChar(#21); AsciiSYN = ByteChar(#22); AsciiETB = ByteChar(#23); AsciiCAN = ByteChar(#24); AsciiEM = ByteChar(#25); AsciiEOF = ByteChar(#26); AsciiESC = ByteChar(#27); AsciiFS = ByteChar(#28); AsciiGS = ByteChar(#29); AsciiRS = ByteChar(#30); AsciiUS = ByteChar(#31); AsciiSP = ByteChar(#32); AsciiDEL = ByteChar(#127); AsciiXON = AsciiDC1; AsciiXOFF = AsciiDC3; AsciiCRLF = AsciiCR + AsciiLF; AsciiDecimalPoint = ByteChar(#46); AsciiComma = ByteChar(#44); AsciiBackSlash = ByteChar(#92); AsciiForwardSlash = ByteChar(#47); AsciiPercent = ByteChar(#37); AsciiAmpersand = ByteChar(#38); AsciiPlus = ByteChar(#43); AsciiMinus = ByteChar(#45); AsciiEqualSign = ByteChar(#61); AsciiSingleQuote = ByteChar(#39); AsciiDoubleQuote = ByteChar(#34); AsciiDigit0 = ByteChar(#48); AsciiDigit9 = ByteChar(#57); AsciiUpperA = ByteChar(#65); AsciiUpperZ = ByteChar(#90); AsciiLowerA = ByteChar(#97); AsciiLowerZ = ByteChar(#122); { } { ASCII low case lookup } { } const AsciiLowCaseLookup: array[Byte] of Byte = ( $00, $01, $02, $03, $04, $05, $06, $07, $08, $09, $0A, $0B, $0C, $0D, $0E, $0F, $10, $11, $12, $13, $14, $15, $16, $17, $18, $19, $1A, $1B, $1C, $1D, $1E, $1F, $20, $21, $22, $23, $24, $25, $26, $27, $28, $29, $2A, $2B, $2C, $2D, $2E, $2F, $30, $31, $32, $33, $34, $35, $36, $37, $38, $39, $3A, $3B, $3C, $3D, $3E, $3F, $40, $61, $62, $63, $64, $65, $66, $67, $68, $69, $6A, $6B, $6C, $6D, $6E, $6F, $70, $71, $72, $73, $74, $75, $76, $77, $78, $79, $7A, $5B, $5C, $5D, $5E, $5F, $60, $61, $62, $63, $64, $65, $66, $67, $68, $69, $6A, $6B, $6C, $6D, $6E, $6F, $70, $71, $72, $73, $74, $75, $76, $77, $78, $79, $7A, $7B, $7C, $7D, $7E, $7F, $80, $81, $82, $83, $84, $85, $86, $87, $88, $89, $8A, $8B, $8C, $8D, $8E, $8F, $90, $91, $92, $93, $94, $95, $96, $97, $98, $99, $9A, $9B, $9C, $9D, $9E, $9F, $A0, $A1, $A2, $A3, $A4, $A5, $A6, $A7, $A8, $A9, $AA, $AB, $AC, $AD, $AE, $AF, $B0, $B1, $B2, $B3, $B4, $B5, $B6, $B7, $B8, $B9, $BA, $BB, $BC, $BD, $BE, $BF, $C0, $C1, $C2, $C3, $C4, $C5, $C6, $C7, $C8, $C9, $CA, $CB, $CC, $CD, $CE, $CF, $D0, $D1, $D2, $D3, $D4, $D5, $D6, $D7, $D8, $D9, $DA, $DB, $DC, $DD, $DE, $DF, $E0, $E1, $E2, $E3, $E4, $E5, $E6, $E7, $E8, $E9, $EA, $EB, $EC, $ED, $EE, $EF, $F0, $F1, $F2, $F3, $F4, $F5, $F6, $F7, $F8, $F9, $FA, $FB, $FC, $FD, $FE, $FF); { } { WideChar ASCII constants } { } const WideNULL = WideChar(#0); WideSOH = WideChar(#1); WideSTX = WideChar(#2); WideETX = WideChar(#3); WideEOT = WideChar(#4); WideENQ = WideChar(#5); WideACK = WideChar(#6); WideBEL = WideChar(#7); WideBS = WideChar(#8); WideHT = WideChar(#9); WideLF = WideChar(#10); WideVT = WideChar(#11); WideFF = WideChar(#12); WideCR = WideChar(#13); WideSO = WideChar(#14); WideSI = WideChar(#15); WideDLE = WideChar(#16); WideDC1 = WideChar(#17); WideDC2 = WideChar(#18); WideDC3 = WideChar(#19); WideDC4 = WideChar(#20); WideNAK = WideChar(#21); WideSYN = WideChar(#22); WideETB = WideChar(#23); WideCAN = WideChar(#24); WideEM = WideChar(#25); WideEOF = WideChar(#26); WideESC = WideChar(#27); WideFS = WideChar(#28); WideGS = WideChar(#29); WideRS = WideChar(#30); WideUS = WideChar(#31); WideSP = WideChar(#32); WideDEL = WideChar(#127); WideXON = WideDC1; WideXOFF = WideDC3; {$IFDEF DELPHI5} WideCRLF = WideString(#13#10); {$ELSE} {$IFDEF DELPHI7_DOWN} WideCRLF = WideString(WideCR) + WideString(WideLF); {$ELSE} WideCRLF = WideCR + WideLF; {$ENDIF} {$ENDIF} { } { Character functions } { } function CharCompareB(const A, B: ByteChar): Integer; {$IFDEF UseInline}inline;{$ENDIF} function CharCompareW(const A, B: WideChar): Integer; {$IFDEF UseInline}inline;{$ENDIF} function CharCompare(const A, B: Char): Integer; {$IFDEF UseInline}inline;{$ENDIF} function CharCompareNoAsciiCaseB(const A, B: ByteChar): Integer; {$IFDEF UseInline}inline;{$ENDIF} function CharCompareNoAsciiCaseW(const A, B: WideChar): Integer; {$IFDEF UseInline}inline;{$ENDIF} function CharCompareNoAsciiCase(const A, B: Char): Integer; {$IFDEF UseInline}inline;{$ENDIF} function CharEqualNoAsciiCaseB(const A, B: ByteChar): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function CharEqualNoAsciiCaseW(const A, B: WideChar): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function CharEqualNoAsciiCase(const A, B: Char): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function CharIsAsciiB(const C: ByteChar): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function CharIsAsciiW(const C: WideChar): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function CharIsAscii(const C: Char): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function CharIsAsciiUpperCaseB(const C: ByteChar): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function CharIsAsciiUpperCaseW(const C: WideChar): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function CharIsAsciiUpperCase(const C: Char): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function CharIsAsciiLowerCaseB(const C: ByteChar): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function CharIsAsciiLowerCaseW(const C: WideChar): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function CharIsAsciiLowerCase(const C: Char): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function CharAsciiLowCaseB(const C: ByteChar): ByteChar; {$IFDEF UseInline}inline;{$ENDIF} function CharAsciiLowCaseW(const C: WideChar): WideChar; {$IFDEF UseInline}inline;{$ENDIF} function CharAsciiLowCase(const C: Char): Char; {$IFDEF UseInline}inline;{$ENDIF} function CharAsciiUpCaseB(const C: ByteChar): ByteChar; {$IFDEF UseInline}inline;{$ENDIF} function CharAsciiUpCaseW(const C: WideChar): WideChar; {$IFDEF UseInline}inline;{$ENDIF} function CharAsciiUpCase(const C: Char): Char; {$IFDEF UseInline}inline;{$ENDIF} function CharAsciiHexValueB(const C: ByteChar): Integer; {$IFDEF UseInline}inline;{$ENDIF} function CharAsciiHexValueW(const C: WideChar): Integer; {$IFDEF UseInline}inline;{$ENDIF} function CharAsciiIsHexB(const C: ByteChar): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function CharAsciiIsHexW(const C: WideChar): Boolean; {$IFDEF UseInline}inline;{$ENDIF} { } { String construction from buffer } { } {$IFDEF SupportAnsiString} function StrPToStrA(const P: PAnsiChar; const L: NativeInt): AnsiString; {$ENDIF} function StrPToStrB(const P: Pointer; const L: NativeInt): RawByteString; function StrPToStrU(const P: PWideChar; const L: NativeInt): UnicodeString; function StrPToStr(const P: PChar; const L: NativeInt): String; function StrZLenA(const S: Pointer): NativeInt; function StrZLenW(const S: PWideChar): NativeInt; function StrZLen(const S: PChar): NativeInt; {$IFDEF SupportAnsiString} function StrZPasA(const A: PAnsiChar): AnsiString; {$ENDIF} function StrZPasB(const A: PByteChar): RawByteString; function StrZPasU(const A: PWideChar): UnicodeString; function StrZPas(const A: PChar): String; { } { RawByteString conversion functions } { } procedure RawByteBufToWideBuf(const Buf: Pointer; const BufSize: NativeInt; const DestBuf: Pointer); function RawByteStrPtrToUnicodeString(const S: Pointer; const Len: NativeInt): UnicodeString; function RawByteStringToUnicodeString(const S: RawByteString): UnicodeString; procedure WideBufToRawByteBuf(const Buf: Pointer; const Len: NativeInt; const DestBuf: Pointer); function WideBufToRawByteString(const P: PWideChar; const Len: NativeInt): RawByteString; function UnicodeStringToRawByteString(const S: UnicodeString): RawByteString; { } { String conversion functions } { } {$IFDEF SupportAnsiString} function ToAnsiString(const A: String): AnsiString; {$IFDEF UseInline}inline;{$ENDIF} {$ENDIF} function ToRawByteString(const A: String): RawByteString; {$IFDEF UseInline}inline;{$ENDIF} function ToUnicodeString(const A: String): UnicodeString; {$IFDEF UseInline}inline;{$ENDIF} { } { String internals } { } {$IFNDEF SupportStringRefCount} {$IFDEF DELPHI} function StringRefCount(const S: RawByteString): Integer; overload; {$IFDEF UseInline}inline;{$ENDIF} function StringRefCount(const S: UnicodeString): Integer; overload; {$IFDEF UseInline}inline;{$ENDIF} {$DEFINE ImplementsStringRefCount} {$ENDIF} {$ENDIF} { } { String append functions } { } {$IFDEF SupportAnsiString} procedure StrAppendChA(var A: AnsiString; const C: AnsiChar); {$IFDEF UseInline}inline;{$ENDIF} {$ENDIF} procedure StrAppendChB(var A: RawByteString; const C: ByteChar); {$IFDEF UseInline}inline;{$ENDIF} procedure StrAppendChU(var A: UnicodeString; const C: WideChar); {$IFDEF UseInline}inline;{$ENDIF} procedure StrAppendCh(var A: String; const C: Char); {$IFDEF UseInline}inline;{$ENDIF} { } { ByteCharSet functions } { } function WideCharInCharSet(const A: WideChar; const C: ByteCharSet): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function CharInCharSet(const A: Char; const C: ByteCharSet): Boolean; {$IFDEF UseInline}inline;{$ENDIF} { } { String functions } { } { Compare returns: } { -1 if A < B } { 0 if A = B } { 1 if A > B } { } function StrPCompareB(const A, B: Pointer; const Len: NativeInt): Integer; {$IFDEF UseInline}inline;{$ENDIF} function StrPCompareW(const A, B: PWideChar; const Len: NativeInt): Integer; {$IFDEF UseInline}inline;{$ENDIF} function StrPCompare(const A, B: PChar; const Len: NativeInt): Integer; {$IFDEF UseInline}inline;{$ENDIF} function StrPCompareNoAsciiCaseB(const A, B: Pointer; const Len: NativeInt): Integer; {$IFDEF UseInline}inline;{$ENDIF} function StrPCompareNoAsciiCaseW(const A, B: PWideChar; const Len: NativeInt): Integer; {$IFDEF UseInline}inline;{$ENDIF} function StrPCompareNoAsciiCase(const A, B: PChar; const Len: NativeInt): Integer; {$IFDEF UseInline}inline;{$ENDIF} function StrPEqualB(const A, B: Pointer; const Len: NativeInt): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function StrPEqualW(const A, B: PWideChar; const Len: NativeInt): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function StrPEqual(const A, B: PChar; const Len: NativeInt): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function StrPEqualNoAsciiCaseB(const A, B: Pointer; const Len: NativeInt): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function StrPEqualNoAsciiCaseW(const A, B: PWideChar; const Len: NativeInt): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function StrPEqualNoAsciiCase(const A, B: PChar; const Len: NativeInt): Boolean; {$IFDEF UseInline}inline;{$ENDIF} {$IFDEF SupportAnsiString} function StrCompareA(const A, B: AnsiString): Integer; {$ENDIF} function StrCompareB(const A, B: RawByteString): Integer; function StrCompareU(const A, B: UnicodeString): Integer; function StrCompare(const A, B: String): Integer; {$IFDEF SupportAnsiString} function StrCompareNoAsciiCaseA(const A, B: AnsiString): Integer; {$ENDIF} function StrCompareNoAsciiCaseB(const A, B: RawByteString): Integer; function StrCompareNoAsciiCaseU(const A, B: UnicodeString): Integer; function StrCompareNoAsciiCase(const A, B: String): Integer; function StrEqualNoAsciiCaseB(const A, B: RawByteString): Boolean; function StrEqualNoAsciiCaseU(const A, B: UnicodeString): Boolean; function StrEqualNoAsciiCase(const A, B: String): Boolean; function StrStartsWithB(const A, B: RawByteString): Boolean; function StrStartsWithU(const A, B: UnicodeString): Boolean; function StrStartsWith(const A, B: String): Boolean; function StrStartsWithNoAsciiCaseB(const A, B: RawByteString): Boolean; function StrStartsWithNoAsciiCaseU(const A, B: UnicodeString): Boolean; function StrStartsWithNoAsciiCase(const A, B: String): Boolean; function StrEndsWithB(const A, B: RawByteString): Boolean; function StrEndsWithU(const A, B: UnicodeString): Boolean; function StrEndsWith(const A, B: String): Boolean; function StrEndsWithNoAsciiCaseB(const A, B: RawByteString): Boolean; function StrEndsWithNoAsciiCaseU(const A, B: UnicodeString): Boolean; function StrEndsWithNoAsciiCase(const A, B: String): Boolean; function StrPosB(const S, M: RawByteString): Int32; {$IFDEF UseInline}inline;{$ENDIF} function StrPosU(const S, M: UnicodeString): Int32; {$IFDEF UseInline}inline;{$ENDIF} function StrPos(const S, M: String): Int32; {$IFDEF UseInline}inline;{$ENDIF} function StrPosNoAsciiCaseB(const S, M: RawByteString): Int32; {$IFDEF UseInline}inline;{$ENDIF} function StrPosNoAsciiCaseU(const S, M: UnicodeString): Int32; {$IFDEF UseInline}inline;{$ENDIF} function StrPosNoAsciiCase(const S, M: String): Int32; {$IFDEF UseInline}inline;{$ENDIF} {$IFDEF SupportAnsiString} function StrAsciiUpperCaseA(const S: AnsiString): AnsiString; {$ENDIF} function StrAsciiUpperCaseB(const S: RawByteString): RawByteString; function StrAsciiUpperCaseU(const S: UnicodeString): UnicodeString; function StrAsciiUpperCase(const S: String): String; {$IFDEF UseInline}inline;{$ENDIF} procedure StrAsciiConvertUpperCaseB(var S: RawByteString); procedure StrAsciiConvertUpperCaseU(var S: UnicodeString); procedure StrAsciiConvertUpperCase(var S: String); {$IFDEF UseInline}inline;{$ENDIF} {$IFDEF SupportAnsiString} function StrAsciiLowerCaseA(const S: AnsiString): AnsiString; {$ENDIF} function StrAsciiLowerCaseB(const S: RawByteString): RawByteString; function StrAsciiLowerCaseU(const S: UnicodeString): UnicodeString; function StrAsciiLowerCase(const S: String): String; {$IFDEF UseInline}inline;{$ENDIF} procedure StrAsciiConvertLowerCaseB(var S: RawByteString); procedure StrAsciiConvertLowerCaseU(var S: UnicodeString); procedure StrAsciiConvertLowerCase(var S: String); {$IFDEF UseInline}inline;{$ENDIF} procedure StrAsciiConvertFirstUpB(var S: RawByteString); procedure StrAsciiConvertFirstUpU(var S: UnicodeString); procedure StrAsciiConvertFirstUp(var S: String); function StrAsciiFirstUpB(const S: RawByteString): RawByteString; {$IFDEF UseInline}inline;{$ENDIF} function StrAsciiFirstUpU(const S: UnicodeString): UnicodeString; {$IFDEF UseInline}inline;{$ENDIF} function StrAsciiFirstUp(const S: String): String; {$IFDEF UseInline}inline;{$ENDIF} function IsAsciiBufB(const Buf: Pointer; const Len: NativeInt): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function IsAsciiBufW(const Buf: Pointer; const Len: NativeInt): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function IsAsciiStringB(const S: RawByteString): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function IsAsciiStringU(const S: UnicodeString): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function IsAsciiString(const S: String): Boolean; {$IFDEF UseInline}inline;{$ENDIF} { } { Swap } { } procedure Swap(var X, Y: Boolean); overload; procedure Swap(var X, Y: Byte); overload; procedure Swap(var X, Y: Word); overload; procedure Swap(var X, Y: Word32); overload; procedure Swap(var X, Y: ShortInt); overload; procedure Swap(var X, Y: SmallInt); overload; procedure Swap(var X, Y: Int32); overload; procedure Swap(var X, Y: Int64); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure SwapLW(var X, Y: LongWord); {$IFDEF UseInline}inline;{$ENDIF} procedure SwapLI(var X, Y: LongInt); {$IFDEF UseInline}inline;{$ENDIF} procedure SwapInt(var X, Y: Integer); {$IFDEF UseInline}inline;{$ENDIF} procedure SwapCrd(var X, Y: Cardinal); {$IFDEF UseInline}inline;{$ENDIF} procedure Swap(var X, Y: Single); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Swap(var X, Y: Double); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure SwapExt(var X, Y: Extended); {$IFDEF UseInline}inline;{$ENDIF} procedure Swap(var X, Y: Currency); overload; {$IFDEF UseInline}inline;{$ENDIF} {$IFDEF SupportAnsiString} procedure SwapA(var X, Y: AnsiString); {$IFDEF UseInline}inline;{$ENDIF} {$ENDIF} procedure SwapB(var X, Y: RawByteString); {$IFDEF UseInline}inline;{$ENDIF} procedure SwapU(var X, Y: UnicodeString); {$IFDEF UseInline}inline;{$ENDIF} procedure Swap(var X, Y: String); overload; {$IFDEF UseInline}inline;{$ENDIF} procedure Swap(var X, Y: TObject); overload; procedure SwapObjects(var X, Y); procedure Swap(var X, Y: Pointer); overload; { } { Inline if } { } { iif returns TrueValue if Expr is True, otherwise it returns FalseValue. } { } function iif(const Expr: Boolean; const TrueValue: Integer; const FalseValue: Integer = 0): Integer; overload; {$IFDEF UseInline}inline;{$ENDIF} function iif(const Expr: Boolean; const TrueValue: Int64; const FalseValue: Int64 = 0): Int64; overload; {$IFDEF UseInline}inline;{$ENDIF} function iif(const Expr: Boolean; const TrueValue: Extended; const FalseValue: Extended = 0.0): Extended; overload; {$IFDEF UseInline}inline;{$ENDIF} {$IFDEF SupportAnsiString} function iifA(const Expr: Boolean; const TrueValue: AnsiString; const FalseValue: AnsiString = ''): AnsiString; {$IFDEF UseInline}inline;{$ENDIF} {$ENDIF} function iifB(const Expr: Boolean; const TrueValue: RawByteString; const FalseValue: RawByteString = ''): RawByteString; {$IFDEF UseInline}inline;{$ENDIF} function iifU(const Expr: Boolean; const TrueValue: UnicodeString; const FalseValue: UnicodeString = ''): UnicodeString; {$IFDEF UseInline}inline;{$ENDIF} function iif(const Expr: Boolean; const TrueValue: String; const FalseValue: String = ''): String; overload; {$IFDEF UseInline}inline;{$ENDIF} function iif(const Expr: Boolean; const TrueValue: TObject; const FalseValue: TObject = nil): TObject; overload; {$IFDEF UseInline}inline;{$ENDIF} { } { Compare result } { Generic compare result enumeration. } { } type TCompareResult = ( crLess, crEqual, crGreater, crUndefined ); TCompareResultSet = set of TCompareResult; function InverseCompareResult(const C: TCompareResult): TCompareResult; { } { Direct comparison } { } { Compare(I1, I2) returns crLess if I1 < I2, crEqual if I1 = I2 or } { crGreater if I1 > I2. } { } function Compare(const I1, I2: Boolean): TCompareResult; overload; function Compare(const I1, I2: Integer): TCompareResult; overload; function Compare(const I1, I2: Int64): TCompareResult; overload; function Compare(const I1, I2: Double): TCompareResult; overload; {$IFDEF SupportAnsiString} function CompareA(const I1, I2: AnsiString): TCompareResult; {$ENDIF} function CompareB(const I1, I2: RawByteString): TCompareResult; function CompareU(const I1, I2: UnicodeString): TCompareResult; function CompareChB(const I1, I2: ByteChar): TCompareResult; function CompareChW(const I1, I2: WideChar): TCompareResult; function Sgn(const A: Int64): Integer; overload; function Sgn(const A: Double): Integer; overload; { } { Convert result } { } type TConvertResult = ( convertOK, convertFormatError, convertOverflow ); { } { Integer-String conversions } { } const StrHexDigitsUpper : String = '0123456789ABCDEF'; StrHexDigitsLower : String = '0123456789abcdef'; function ByteCharDigitToInt(const A: ByteChar): Integer; {$IFDEF UseInline}inline;{$ENDIF} function WideCharDigitToInt(const A: WideChar): Integer; {$IFDEF UseInline}inline;{$ENDIF} function CharDigitToInt(const A: Char): Integer; {$IFDEF UseInline}inline;{$ENDIF} function IntToByteCharDigit(const A: Integer): ByteChar; {$IFDEF UseInline}inline;{$ENDIF} function IntToWideCharDigit(const A: Integer): WideChar; {$IFDEF UseInline}inline;{$ENDIF} function IntToCharDigit(const A: Integer): Char; {$IFDEF UseInline}inline;{$ENDIF} function IsHexByteCharDigit(const Ch: ByteChar): Boolean; function IsHexWideCharDigit(const Ch: WideChar): Boolean; function IsHexCharDigit(const Ch: Char): Boolean; {$IFDEF UseInline}inline;{$ENDIF} function HexByteCharDigitToInt(const A: ByteChar): Integer; function HexWideCharDigitToInt(const A: WideChar): Integer; function HexCharDigitToInt(const A: Char): Integer; {$IFDEF UseInline}inline;{$ENDIF} function IntToUpperHexByteCharDigit(const A: Integer): ByteChar; function IntToUpperHexWideCharDigit(const A: Integer): WideChar; function IntToUpperHexCharDigit(const A: Integer): Char; {$IFDEF UseInline}inline;{$ENDIF} function IntToLowerHexByteCharDigit(const A: Integer): ByteChar; function IntToLowerHexWideCharDigit(const A: Integer): WideChar; function IntToLowerHexCharDigit(const A: Integer): Char; {$IFDEF UseInline}inline;{$ENDIF} {$IFDEF SupportAnsiString} function IntToStringA(const A: Int64): AnsiString; {$ENDIF} function IntToStringB(const A: Int64): RawByteString; function IntToStringU(const A: Int64): UnicodeString; function IntToString(const A: Int64): String; {$IFDEF SupportAnsiString} function UIntToStringA(const A: UInt64): AnsiString; {$ENDIF} function UIntToStringB(const A: UInt64): RawByteString; function UIntToStringU(const A: UInt64): UnicodeString; function UIntToString(const A: UInt64): String; {$IFDEF SupportAnsiString} function Word32ToStrA(const A: Word32; const Digits: Integer = 0): AnsiString; {$ENDIF} function Word32ToStrB(const A: Word32; const Digits: Integer = 0): RawByteString; function Word32ToStrU(const A: Word32; const Digits: Integer = 0): UnicodeString; function Word32ToStr(const A: Word32; const Digits: Integer = 0): String; {$IFDEF SupportAnsiString} function Word32ToHexA(const A: Word32; const Digits: Integer = 0; const UpperCase: Boolean = True): AnsiString; {$ENDIF} function Word32ToHexB(const A: Word32; const Digits: Integer = 0; const UpperCase: Boolean = True): RawByteString; function Word32ToHexU(const A: Word32; const Digits: Integer = 0; const UpperCase: Boolean = True): UnicodeString; function Word32ToHex(const A: Word32; const Digits: Integer = 0; const UpperCase: Boolean = True): String; {$IFDEF SupportAnsiString} function Word32ToOctA(const A: Word32; const Digits: Integer = 0): AnsiString; {$ENDIF} function Word32ToOctB(const A: Word32; const Digits: Integer = 0): RawByteString; function Word32ToOctU(const A: Word32; const Digits: Integer = 0): UnicodeString; function Word32ToOct(const A: Word32; const Digits: Integer = 0): String; {$IFDEF SupportAnsiString} function Word32ToBinA(const A: Word32; const Digits: Integer = 0): AnsiString; {$ENDIF} function Word32ToBinB(const A: Word32; const Digits: Integer = 0): RawByteString; function Word32ToBinU(const A: Word32; const Digits: Integer = 0): UnicodeString; function Word32ToBin(const A: Word32; const Digits: Integer = 0): String; function TryStringToInt64PB(const BufP: Pointer; const BufLen: Integer; out Value: Int64; out StrLen: Integer): TConvertResult; function TryStringToInt64PW(const BufP: Pointer; const BufLen: Integer; out Value: Int64; out StrLen: Integer): TConvertResult; function TryStringToInt64P(const BufP: Pointer; const BufLen: Integer; out Value: Int64; out StrLen: Integer): TConvertResult; {$IFDEF SupportAnsiString} function TryStringToInt64A(const S: AnsiString; out A: Int64): Boolean; {$ENDIF} function TryStringToInt64B(const S: RawByteString; out A: Int64): Boolean; function TryStringToInt64U(const S: UnicodeString; out A: Int64): Boolean; function TryStringToInt64(const S: String; out A: Int64): Boolean; {$IFNDEF DELPHI7} {$IFDEF SupportAnsiString} function TryStringToUInt64A(const S: AnsiString; out A: UInt64): Boolean; {$ENDIF} function TryStringToUInt64B(const S: RawByteString; out A: UInt64): Boolean; function TryStringToUInt64U(const S: UnicodeString; out A: UInt64): Boolean; function TryStringToUInt64(const S: String; out A: UInt64): Boolean; {$IFDEF SupportAnsiString} function StringToInt64DefA(const S: AnsiString; const Default: Int64): Int64; {$ENDIF} function StringToInt64DefB(const S: RawByteString; const Default: Int64): Int64; function StringToInt64DefU(const S: UnicodeString; const Default: Int64): Int64; function StringToInt64Def(const S: String; const Default: Int64): Int64; {$IFDEF SupportAnsiString} function StringToUInt64DefA(const S: AnsiString; const Default: UInt64): UInt64; {$ENDIF} function StringToUInt64DefB(const S: RawByteString; const Default: UInt64): UInt64; function StringToUInt64DefU(const S: UnicodeString; const Default: UInt64): UInt64; function StringToUInt64Def(const S: String; const Default: UInt64): UInt64; {$IFDEF SupportAnsiString} function StringToInt64A(const S: AnsiString): Int64; {$ENDIF} function StringToInt64B(const S: RawByteString): Int64; function StringToInt64U(const S: UnicodeString): Int64; function StringToInt64(const S: String): Int64; {$IFDEF SupportAnsiString} function StringToUInt64A(const S: AnsiString): UInt64; {$ENDIF} function StringToUInt64B(const S: RawByteString): UInt64; function StringToUInt64U(const S: UnicodeString): UInt64; function StringToUInt64(const S: String): UInt64; {$ENDIF ~DELPHI7} {$IFDEF SupportAnsiString} function TryStringToIntA(const S: AnsiString; out A: Integer): Boolean; {$ENDIF} function TryStringToIntB(const S: RawByteString; out A: Integer): Boolean; function TryStringToIntU(const S: UnicodeString; out A: Integer): Boolean; function TryStringToInt(const S: String; out A: Integer): Boolean; {$IFDEF SupportAnsiString} function StringToIntDefA(const S: AnsiString; const Default: Integer): Integer; {$ENDIF} function StringToIntDefB(const S: RawByteString; const Default: Integer): Integer; function StringToIntDefU(const S: UnicodeString; const Default: Integer): Integer; function StringToIntDef(const S: String; const Default: Integer): Integer; {$IFDEF SupportAnsiString} function StringToIntA(const S: AnsiString): Integer; {$ENDIF} function StringToIntB(const S: RawByteString): Integer; function StringToIntU(const S: UnicodeString): Integer; function StringToInt(const S: String): Integer; {$IFDEF SupportAnsiString} function TryStringToWord32A(const S: AnsiString; out A: Word32): Boolean; {$ENDIF} function TryStringToWord32B(const S: RawByteString; out A: Word32): Boolean; function TryStringToWord32U(const S: UnicodeString; out A: Word32): Boolean; function TryStringToWord32(const S: String; out A: Word32): Boolean; {$IFDEF SupportAnsiString} function StringToWord32A(const S: AnsiString): Word32; {$ENDIF} function StringToWord32B(const S: RawByteString): Word32; function StringToWord32U(const S: UnicodeString): Word32; function StringToWord32(const S: String): Word32; {$IFDEF SupportAnsiString} function HexToUIntA(const S: AnsiString): UInt64; {$ENDIF} function HexToUIntB(const S: RawByteString): UInt64; function HexToUIntU(const S: UnicodeString): UInt64; function HexToUInt(const S: String): UInt64; {$IFDEF SupportAnsiString} function TryHexToWord32A(const S: AnsiString; out A: Word32): Boolean; {$ENDIF} function TryHexToWord32B(const S: RawByteString; out A: Word32): Boolean; function TryHexToWord32U(const S: UnicodeString; out A: Word32): Boolean; function TryHexToWord32(const S: String; out A: Word32): Boolean; {$IFDEF SupportAnsiString} function HexToWord32A(const S: AnsiString): Word32; {$ENDIF} function HexToWord32B(const S: RawByteString): Word32; function HexToWord32U(const S: UnicodeString): Word32; function HexToWord32(const S: String): Word32; {$IFDEF SupportAnsiString} function TryOctToWord32A(const S: AnsiString; out A: Word32): Boolean; {$ENDIF} function TryOctToWord32B(const S: RawByteString; out A: Word32): Boolean; function TryOctToWord32U(const S: UnicodeString; out A: Word32): Boolean; function TryOctToWord32(const S: String; out A: Word32): Boolean; {$IFDEF SupportAnsiString} function OctToWord32A(const S: AnsiString): Word32; {$ENDIF} function OctToWord32B(const S: RawByteString): Word32; function OctToWord32U(const S: UnicodeString): Word32; function OctToWord32(const S: String): Word32; {$IFDEF SupportAnsiString} function TryBinToWord32A(const S: AnsiString; out A: Word32): Boolean; {$ENDIF} function TryBinToWord32B(const S: RawByteString; out A: Word32): Boolean; function TryBinToWord32U(const S: UnicodeString; out A: Word32): Boolean; function TryBinToWord32(const S: String; out A: Word32): Boolean; {$IFDEF SupportAnsiString} function BinToWord32A(const S: AnsiString): Word32; {$ENDIF} function BinToWord32B(const S: RawByteString): Word32; function BinToWord32U(const S: UnicodeString): Word32; function BinToWord32(const S: String): Word32; {$IFDEF SupportAnsiString} function BytesToHexA(const P: Pointer; const Count: NativeInt; const UpperCase: Boolean = True): AnsiString; {$ENDIF} { } { Network byte order } { } function hton16(const A: Word): Word; function ntoh16(const A: Word): Word; function hton32(const A: Word32): Word32; function ntoh32(const A: Word32): Word32; function hton64(const A: Int64): Int64; function ntoh64(const A: Int64): Int64; { } { Pointer-String conversions } { } {$IFDEF SupportAnsiString} function PointerToStrA(const P: Pointer): AnsiString; {$ENDIF} function PointerToStrB(const P: Pointer): RawByteString; function PointerToStrU(const P: Pointer): UnicodeString; function PointerToStr(const P: Pointer): String; {$IFDEF SupportAnsiString} function StrToPointerA(const S: AnsiString): Pointer; {$ENDIF} function StrToPointerB(const S: RawByteString): Pointer; function StrToPointerU(const S: UnicodeString): Pointer; function StrToPointer(const S: String): Pointer; function ObjectClassName(const O: TObject): String; function ClassClassName(const C: TClass): String; function ObjectToStr(const O: TObject): String; { } { Hashing functions } { } { HashBuf uses a every byte in the buffer to calculate a hash. } { } { HashStr is a general purpose string hashing function. } { } { If Slots = 0 the hash value is in the Word32 range (0-$FFFFFFFF), } { otherwise the value is in the range from 0 to Slots-1. Note that the } { 'mod' operation, which is used when Slots <> 0, is comparitively slow. } { } function HashBuf(const Hash: Word32; const Buf; const BufSize: NativeInt): Word32; {$IFDEF SupportAnsiString} function HashStrA(const S: AnsiString; const Index: NativeInt = 1; const Count: NativeInt = -1; const AsciiCaseSensitive: Boolean = True; const Slots: Word32 = 0): Word32; {$ENDIF} function HashStrB(const S: RawByteString; const Index: NativeInt = 1; const Count: NativeInt = -1; const AsciiCaseSensitive: Boolean = True; const Slots: Word32 = 0): Word32; function HashStrU(const S: UnicodeString; const Index: NativeInt = 1; const Count: NativeInt = -1; const AsciiCaseSensitive: Boolean = True; const Slots: Word32 = 0): Word32; function HashStr(const S: String; const Index: NativeInt = 1; const Count: NativeInt = -1; const AsciiCaseSensitive: Boolean = True; const Slots: Word32 = 0): Word32; function HashInteger(const I: Integer; const Slots: Word32 = 0): Word32; function HashNativeUInt(const I: NativeUInt; const Slots: Word32): Word32; function HashWord32(const I: Word32; const Slots: Word32 = 0): Word32; { } { Dynamic arrays } { } procedure FreeObjectArray(var V); overload; procedure FreeObjectArray(var V; const LoIdx, HiIdx: Integer); overload; procedure FreeAndNilObjectArray(var V: ObjectArray); { } { TBytes functions } { } procedure BytesSetLengthAndZero(var V: TBytes; const NewLength: NativeInt); procedure BytesInit(var V: TBytes; const R: Byte); overload; procedure BytesInit(var V: TBytes; const S: String); overload; procedure BytesInit(var V: TBytes; const S: array of Byte); overload; function BytesAppend(var V: TBytes; const R: Byte): NativeInt; overload; function BytesAppend(var V: TBytes; const R: TBytes): NativeInt; overload; function BytesAppend(var V: TBytes; const R: array of Byte): NativeInt; overload; function BytesAppend(var V: TBytes; const R: String): NativeInt; overload; function BytesCompare(const A, B: TBytes): Integer; function BytesEqual(const A, B: TBytes): Boolean; implementation uses { System } Math; { } { CPU identification } { } {$IFDEF ASM386_DELPHI} var CPUIDInitialised : Boolean = False; CPUIDSupport : Boolean = False; MMXSupport : Boolean = False; procedure InitialiseCPUID; assembler; asm // Set CPUID flag PUSHFD POP EAX OR EAX, $200000 PUSH EAX POPFD // Check if CPUID flag is still set PUSHFD POP EAX AND EAX, $200000 JNZ @CPUIDSupported // CPUID not supported MOV BYTE PTR [CPUIDSupport], 0 MOV BYTE PTR [MMXSupport], 0 JMP @CPUIDFin // CPUID supported @CPUIDSupported: MOV BYTE PTR [CPUIDSupport], 1 PUSH EBX // Perform CPUID function 1 MOV EAX, 1 {$IFDEF DELPHI5_DOWN} DW 0FA2h {$ELSE} CPUID {$ENDIF} // Check if MMX feature flag is set AND EDX, $800000 SETNZ AL MOV BYTE PTR [MMXSupport], AL POP EBX @CPUIDFin: MOV BYTE PTR [CPUIDInitialised], 1 end; {$ENDIF} { } { Range check error } { } constructor ERangeCheckError.Create; begin inherited Create('Range check error'); end; { } { Integer } { } function MinInt(const A, B: Int64): Int64; begin if A < B then Result := A else Result := B; end; function MaxInt(const A, B: Int64): Int64; begin if A > B then Result := A else Result := B; end; function MinUInt(const A, B: UInt64): UInt64; begin if A < B then Result := A else Result := B; end; function MaxUInt(const A, B: UInt64): UInt64; begin if A > B then Result := A else Result := B; end; function MinNatInt(const A, B: NativeInt): NativeInt; begin if A < B then Result := A else Result := B; end; function MaxNatInt(const A, B: NativeInt): NativeInt; begin if A > B then Result := A else Result := B; end; function MinNatUInt(const A, B: NativeUInt): NativeUInt; begin if A < B then Result := A else Result := B; end; function MaxNatUInt(const A, B: NativeUInt): NativeUInt; begin if A > B then Result := A else Result := B; end; function IsIntInInt32Range(const Value: Int64): Boolean; begin Result := (Value >= MinInt32) and (Value <= MaxInt32); end; function IsIntInInt16Range(const Value: Int64): Boolean; begin Result := (Value >= MinInt16) and (Value <= MaxInt16); end; function IsIntInInt8Range(const Value: Int64): Boolean; begin Result := (Value >= MinInt8) and (Value <= MaxInt8); end; function IsUIntInInt32Range(const Value: UInt64): Boolean; begin Result := Value <= MaxInt32; end; function IsUIntInInt16Range(const Value: UInt64): Boolean; begin Result := Value <= MaxInt16; end; function IsUIntInInt8Range(const Value: UInt64): Boolean; begin Result := Value <= MaxInt8; end; function IsIntInUInt32Range(const Value: Int64): Boolean; begin Result := (Value >= MinUInt32) and (Value <= MaxUInt32); end; function IsIntInUInt16Range(const Value: Int64): Boolean; begin Result := (Value >= MinUInt16) and (Value <= MaxUInt16); end; function IsIntInUInt8Range(const Value: Int64): Boolean; begin Result := (Value >= MinUInt8) and (Value <= MaxUInt8); end; function IsUIntInUInt32Range(const Value: UInt64): Boolean; begin Result := Value <= MaxUInt32; end; function IsUIntInUInt16Range(const Value: UInt64): Boolean; begin Result := Value <= MaxUInt16; end; function IsUIntInUInt8Range(const Value: UInt64): Boolean; begin Result := Value <= MaxUInt8; end; { } { Memory } { } {$IFOPT Q+}{$DEFINE QOn}{$Q-}{$ELSE}{$UNDEF QOn}{$ENDIF} procedure FillMem(var Buf; const Count: NativeInt; const Value: Byte); begin FillChar(Buf, Count, Value); end; procedure ZeroMem(var Buf; const Count: NativeInt); begin FillChar(Buf, Count, #0); end; procedure GetZeroMem(var P: Pointer; const Size: NativeInt); begin GetMem(P, Size); ZeroMem(P^, Size); end; procedure MoveMem(const Source; var Dest; const Count: NativeInt); begin Move(Source, Dest, Count); end; function EqualMem24(const Buf1; const Buf2): Boolean; {$IFDEF UseInline}inline;{$ENDIF} var P : Pointer; Q : Pointer; begin P := @Buf1; Q := @Buf2; if PWord16(P)^ = PWord16(Q)^ then begin Inc(PWord16(P)); Inc(PWord16(Q)); Result := PByte(P)^ = PByte(Q)^; end else Result := False; end; function EqualMemTo64(const Buf1; const Buf2; const Count: Byte): Boolean; {$IFDEF UseInline}inline;{$ENDIF} var P : Pointer; Q : Pointer; begin P := @Buf1; Q := @Buf2; case Count of 0 : Result := True; 1 : Result := PByte(P)^ = PByte(Q)^; 2 : Result := PWord16(P)^ = PWord16(Q)^; 3 : Result := EqualMem24(P^, Q^); 4 : Result := PWord32(P)^ = PWord32(Q)^; 5 : begin Result := PWord32(P)^ = PWord32(Q)^; if Result then begin Inc(PWord32(P)); Inc(PWord32(Q)); Result := PByte(P)^ = PByte(Q)^; end; end; 6 : begin Result := PWord32(P)^ = PWord32(Q)^; if Result then begin Inc(PWord32(P)); Inc(PWord32(Q)); Result := PWord16(P)^ = PWord16(Q)^; end; end; 7 : begin Result := PWord32(P)^ = PWord32(Q)^; if Result then begin Inc(PWord32(P)); Inc(PWord32(Q)); Result := EqualMem24(P^, Q^); end; end; 8 : Result := PWord64(P)^ = PWord64(Q)^; else Result := False; end; end; function EqualMem(const Buf1; const Buf2; const Count: NativeInt): Boolean; var P : Pointer; Q : Pointer; I : NativeInt; begin if Count <= 0 then begin Result := True; exit; end; P := @Buf1; Q := @Buf2; if P = Q then begin Result := True; exit; end; if Count <= 8 then begin Result := EqualMemTo64(P^, Q^, Byte(Count)); exit; end; I := Count; while I >= SizeOf(Word64) do if PWord64(P)^ = PWord64(Q)^ then begin Inc(PWord64(P)); Inc(PWord64(Q)); Dec(I, SizeOf(Word64)); end else begin Result := False; exit; end; if I > 0 then begin Assert(I < SizeOf(Word64)); Result := EqualMemTo64(P^, Q^, Byte(I)); end else Result := True; end; function EqualWord8NoAsciiCaseB(const A, B: Byte): Boolean; {$IFDEF UseInline}inline;{$ENDIF} var C, D : Byte; begin if A = B then Result := True else begin C := A; D := B; if C in [Ord('A')..Ord('Z')] then Inc(C, 32); if D in [Ord('A')..Ord('Z')] then Inc(D, 32); if C = D then Result := True else Result := False; end; end; function EqualWord16NoAsciiCaseB(const A, B: Word16): Boolean; {$IFDEF UseInline}inline;{$ENDIF} begin if A = B then Result := True else Result := EqualWord8NoAsciiCaseB(Byte(A), Byte(B)) and EqualWord8NoAsciiCaseB(Byte(A shr 8), Byte(B shr 8)); end; function EqualWord32NoAsciiCaseB(const A, B: Word32): Boolean; {$IFDEF UseInline}inline;{$ENDIF} begin if A = B then Result := True else Result := EqualWord16NoAsciiCaseB(Word16(A), Word16(B)) and EqualWord16NoAsciiCaseB(Word16(A shr 16), Word16(B shr 16)); end; function EqualWord64NoAsciiCaseB(const A, B: Word64): Boolean; {$IFDEF UseInline}inline;{$ENDIF} begin if A = B then Result := True else Result := EqualWord32NoAsciiCaseB(Word32(A), Word32(B)) and EqualWord32NoAsciiCaseB(Word32(A shr 32), Word32(B shr 32)); end; function EqualMemTo64NoAsciiCaseB(const Buf1; const Buf2; const Count: Byte): Boolean; {$IFDEF UseInline}inline;{$ENDIF} var P : Pointer; Q : Pointer; begin P := @Buf1; Q := @Buf2; case Count of 0 : Result := True; 1 : Result := EqualWord8NoAsciiCaseB(PByte(P)^, PByte(Q)^); 2 : Result := EqualWord16NoAsciiCaseB(PWord16(P)^, PWord16(Q)^); 3 : begin if EqualWord16NoAsciiCaseB(PWord16(P)^, PWord16(Q)^) then begin Inc(PWord16(P)); Inc(PWord16(Q)); Result := EqualWord8NoAsciiCaseB(PByte(P)^, PByte(Q)^); end else Result := False; end; 4 : Result := EqualWord32NoAsciiCaseB(PWord32(P)^, PWord32(Q)^); 5 : begin if EqualWord32NoAsciiCaseB(PWord32(P)^, PWord32(Q)^) then begin Inc(PWord32(P)); Inc(PWord32(Q)); Result := EqualWord8NoAsciiCaseB(PByte(P)^, PByte(Q)^); end else Result := False; end; 6 : begin if EqualWord32NoAsciiCaseB(PWord32(P)^, PWord32(Q)^) then begin Inc(PWord32(P)); Inc(PWord32(Q)); Result := EqualWord16NoAsciiCaseB(PWord16(P)^, PWord16(Q)^); end else Result := False; end; 7 : begin if EqualWord32NoAsciiCaseB(PWord32(P)^, PWord32(Q)^) then begin Inc(PWord32(P)); Inc(PWord32(Q)); if EqualWord16NoAsciiCaseB(PWord16(P)^, PWord16(Q)^) then begin Inc(PWord16(P)); Inc(PWord16(Q)); Result := EqualWord8NoAsciiCaseB(PByte(P)^, PByte(Q)^); end else Result := False; end else Result := False; end; 8 : Result := EqualWord64NoAsciiCaseB(PWord64(P)^, PWord64(Q)^); else Result := False; end; end; function EqualMemNoAsciiCaseB(const Buf1; const Buf2; const Count: NativeInt): Boolean; var P, Q : Pointer; I : NativeInt; begin if Count <= 0 then begin Result := True; exit; end; P := @Buf1; Q := @Buf2; if P = Q then begin Result := True; exit; end; if Count <= 8 then begin Result := EqualMemTo64NoAsciiCaseB(P^, Q^, Byte(Count)); exit; end; I := Count; while I >= SizeOf(Word64) do begin if not EqualWord64NoAsciiCaseB(PWord64(P)^, PWord64(Q)^) then begin Result := False; exit; end; Inc(PWord64(P)); Inc(PWord64(Q)); Dec(I, SizeOf(Word64)); end; if I > 0 then begin Assert(I < SizeOf(Word64)); Result := EqualMemTo64NoAsciiCaseB(P^, Q^, Byte(I)); end else Result := True; end; function EqualWord16NoAsciiCaseW(const A, B: Word16): Boolean; {$IFDEF UseInline}inline;{$ENDIF} var C, D : Word16; begin if A = B then Result := True else begin C := A; D := B; if C in [Ord('A')..Ord('Z')] then Inc(C, 32); if D in [Ord('A')..Ord('Z')] then Inc(D, 32); if C = D then Result := True else Result := False; end; end; function EqualWord32NoAsciiCaseW(const A, B: Word32): Boolean; {$IFDEF UseInline}inline;{$ENDIF} begin if A = B then Result := True else Result := EqualWord16NoAsciiCaseW(Word16(A), Word16(B)) and EqualWord16NoAsciiCaseW(Word16(A shr 16), Word16(B shr 16)); end; function EqualWord64NoAsciiCaseW(const A, B: Word64): Boolean; {$IFDEF UseInline}inline;{$ENDIF} begin if A = B then Result := True else Result := EqualWord32NoAsciiCaseW(Word32(A), Word32(B)) and EqualWord32NoAsciiCaseW(Word32(A shr 32), Word32(B shr 32)); end; function EqualMemTo64NoAsciiCaseW(const P: Pointer; const Q: Pointer; const Count: Byte): Boolean; {$IFDEF UseInline}inline;{$ENDIF} var A, B : PByte; begin case Count of 0 : Result := True; 1 : begin Result := EqualWord16NoAsciiCaseW(PWord16(P)^, PWord16(Q)^); exit; end; 2 : begin Result := EqualWord32NoAsciiCaseW(PWord32(P)^, PWord32(Q)^); exit; end; 3 : begin if EqualWord32NoAsciiCaseW(PWord32(P)^, PWord32(Q)^) then begin A := P; B := Q; Inc(PWord32(A)); Inc(PWord32(B)); Result := EqualWord16NoAsciiCaseW(PWord16(A)^, PWord16(B)^); end else Result := False; exit; end; 4 : begin Result := EqualWord64NoAsciiCaseW(PWord64(P)^, PWord64(Q)^); exit; end; else Result := False; end; end; function EqualMemNoAsciiCaseW(const Buf1; const Buf2; const Count: NativeInt): Boolean; var P, Q : Pointer; I : NativeInt; begin if Count <= 0 then begin Result := True; exit; end; P := @Buf1; Q := @Buf2; if P = Q then begin Result := True; exit; end; if Count <= 4 then begin Result := EqualMemTo64NoAsciiCaseW(P, Q, Byte(Count)); exit; end; I := Count; while I >= SizeOf(Word64) div SizeOf(WideChar) do begin if not EqualWord64NoAsciiCaseW(PWord64(P)^, PWord64(Q)^) then begin Result := False; exit; end; Inc(PWord64(P)); Inc(PWord64(Q)); Dec(I, SizeOf(Word64) div SizeOf(WideChar)); end; if I > 0 then begin Assert(I < SizeOf(Word64) div SizeOf(WideChar)); Result := EqualMemTo64NoAsciiCaseW(P, Q, Byte(I)); end else Result := True; end; function CompareMemB(const Buf1; const Buf2; const Count: NativeInt): Integer; var P, Q : Pointer; I : NativeInt; C, D : Byte; begin if Count <= 0 then begin Result := 0; exit; end; P := @Buf1; Q := @Buf2; if P = Q then begin Result := 0; exit; end; I := Count; while I >= SizeOf(Word64) do if PWord64(P)^ = PWord64(Q)^ then begin Inc(PWord64(P)); Inc(PWord64(Q)); Dec(I, SizeOf(Word64)); end else break; while I > 0 do begin C := PByte(P)^; D := PByte(Q)^; if C = D then begin Inc(PByte(P)); Inc(PByte(Q)); end else begin if C < D then Result := -1 else Result := 1; exit; end; Dec(I); end; Result := 0; end; function CompareMemW(const Buf1; const Buf2; const Count: NativeInt): Integer; var P, Q : Pointer; I : NativeInt; C, D : Word16; begin if Count <= 0 then begin Result := 0; exit; end; P := @Buf1; Q := @Buf2; if P = Q then begin Result := 0; exit; end; I := Count; while I >= SizeOf(Word64) div SizeOf(WideChar) do if PWord64(P)^ = PWord64(Q)^ then begin Inc(PWord64(P)); Inc(PWord64(Q)); Dec(I, SizeOf(Word64) div SizeOf(WideChar)); end else break; while I > 0 do begin C := PWord16(P)^; D := PWord16(Q)^; if C = D then begin Inc(PWord16(P)); Inc(PWord16(Q)); end else begin if C < D then Result := -1 else Result := 1; exit; end; Dec(I); end; Result := 0; end; function CompareMemNoAsciiCaseB(const Buf1; const Buf2; const Count: NativeInt): Integer; var P, Q : Pointer; I : Integer; C, D : Byte; begin if Count <= 0 then begin Result := 0; exit; end; P := @Buf1; Q := @Buf2; if P = Q then begin Result := 0; exit; end; for I := 1 to Count do begin C := PByte(P)^; D := PByte(Q)^; if C in [Ord('A')..Ord('Z')] then C := C or 32; if D in [Ord('A')..Ord('Z')] then D := D or 32; if C = D then begin Inc(PByte(P)); Inc(PByte(Q)); end else begin if C < D then Result := -1 else Result := 1; exit; end; end; Result := 0; end; function CompareMemNoAsciiCaseW(const Buf1; const Buf2; const Count: NativeInt): Integer; var P, Q : Pointer; I : Integer; C, D : Word16; begin if Count <= 0 then begin Result := 0; exit; end; P := @Buf1; Q := @Buf2; if P = Q then begin Result := 0; exit; end; for I := 1 to Count do begin C := PWord16(P)^; D := PWord16(Q)^; if (C >= Ord('A')) and (C <= Ord('Z')) then C := C or 32; if (D >= Ord('A')) and (D <= Ord('Z')) then D := D or 32; if C = D then begin Inc(PWord16(P)); Inc(PWord16(Q)); end else begin if C < D then Result := -1 else Result := 1; exit; end; end; Result := 0; end; function LocateMemB(const Buf1; const Count1: NativeInt; const Buf2; const Count2: NativeInt): NativeInt; var P, Q : PByte; I : NativeInt; begin if (Count1 <= 0) or (Count2 <= 0) or (Count2 > Count1) then begin Result := -1; exit; end; P := @Buf1; Q := @Buf2; for I := 0 to Count1 - Count2 do begin if P = Q then begin Result := I; exit; end; if EqualMem(P^, Q^, Count2) then begin Result := I; exit; end; Inc(P); end; Result := -1; end; function LocateMemW(const Buf1; const Count1: NativeInt; const Buf2; const Count2: NativeInt): NativeInt; var P, Q : PWord16; I : NativeInt; begin if (Count1 <= 0) or (Count2 <= 0) or (Count2 > Count1) then begin Result := -1; exit; end; P := @Buf1; Q := @Buf2; for I := 0 to Count1 - Count2 do begin if P = Q then begin Result := I; exit; end; if EqualMem(P^, Q^, Count2 * SizeOf(WideChar)) then begin Result := I; exit; end; Inc(P); end; Result := -1; end; function LocateMemNoAsciiCaseB(const Buf1; const Count1: NativeInt; const Buf2; const Count2: NativeInt): NativeInt; var P, Q : PByte; I : NativeInt; begin if (Count1 <= 0) or (Count2 <= 0) or (Count2 > Count1) then begin Result := -1; exit; end; P := @Buf1; Q := @Buf2; for I := 0 to Count1 - Count2 do begin if P = Q then begin Result := I; exit; end; if EqualMemNoAsciiCaseB(P^, Q^, Count2) then begin Result := I; exit; end; Inc(P); end; Result := -1; end; function LocateMemNoAsciiCaseW(const Buf1; const Count1: NativeInt; const Buf2; const Count2: NativeInt): NativeInt; var P, Q : PWord16; I : NativeInt; begin if (Count1 <= 0) or (Count2 <= 0) or (Count2 > Count1) then begin Result := -1; exit; end; P := @Buf1; Q := @Buf2; for I := 0 to Count1 - Count2 do begin if P = Q then begin Result := I; exit; end; if EqualMemNoAsciiCaseW(P^, Q^, Count2) then begin Result := I; exit; end; Inc(P); end; Result := -1; end; procedure ReverseMem(var Buf; const Size: NativeInt); var I : NativeInt; P : PByte; Q : PByte; T : Byte; begin P := @Buf; Q := P; Inc(Q, Size - 1); for I := 1 to Size div 2 do begin T := P^; P^ := Q^; Q^ := T; Inc(P); Dec(Q); end; end; {$IFDEF QOn}{$Q+}{$ENDIF} { } { Character compare functions } { } function CharCompareB(const A, B: ByteChar): Integer; begin if Ord(A) = Ord(B) then Result := 0 else if Ord(A) < Ord(B) then Result := -1 else Result := 1; end; function CharCompareW(const A, B: WideChar): Integer; begin if Ord(A) = Ord(B) then Result := 0 else if Ord(A) < Ord(B) then Result := -1 else Result := 1; end; function CharCompare(const A, B: Char): Integer; begin {$IFDEF CharIsWide} Result := CharCompareW(A, B); {$ELSE} Result := CharCompareB(A, B); {$ENDIF} end; function CharCompareNoAsciiCaseB(const A, B: ByteChar): Integer; var C, D : Byte; begin C := Byte(A); D := Byte(B); if C = D then Result := 0 else begin if C in [Ord('A')..Ord('Z')] then Inc(C, 32); if D in [Ord('A')..Ord('Z')] then Inc(D, 32); if C = D then Result := 0 else if C < D then Result := -1 else Result := 1; end; end; function CharCompareNoAsciiCaseW(const A, B: WideChar): Integer; var C, D : Word16; begin C := Word16(A); D := Word16(B); if C = D then Result := 0 else begin case C of Ord('A')..Ord('Z') : Inc(C, 32); end; case D of Ord('A')..Ord('Z') : Inc(D, 32); end; if C = D then Result := 0 else if C < D then Result := -1 else Result := 1; end; end; function CharCompareNoAsciiCase(const A, B: Char): Integer; begin {$IFDEF StringIsUnicode} Result := CharCompareNoAsciiCaseW(A, B); {$ELSE} Result := CharCompareNoAsciiCaseB(A, B); {$ENDIF} end; function CharEqualNoAsciiCaseB(const A, B: ByteChar): Boolean; var C, D : Byte; begin C := Byte(A); D := Byte(B); if C = D then Result := True else begin if C in [Ord('A')..Ord('Z')] then Inc(C, 32); if D in [Ord('A')..Ord('Z')] then Inc(D, 32); Result := C = D; end; end; function CharEqualNoAsciiCaseW(const A, B: WideChar): Boolean; var C, D : Word16; begin C := Word16(A); D := Word16(B); if C = D then Result := True else begin case C of Ord('A')..Ord('Z') : Inc(C, 32); end; case D of Ord('A')..Ord('Z') : Inc(D, 32); end; Result := C = D; end; end; function CharEqualNoAsciiCase(const A, B: Char): Boolean; begin {$IFDEF StringIsUnicode} Result := CharEqualNoAsciiCaseW(A, B); {$ELSE} Result := CharEqualNoAsciiCaseB(A, B); {$ENDIF} end; function CharIsAsciiB(const C: ByteChar): Boolean; begin Result := Ord(C) <= 127; end; function CharIsAsciiW(const C: WideChar): Boolean; begin Result := Ord(C) <= 127; end; function CharIsAscii(const C: Char): Boolean; begin Result := Ord(C) <= 127; end; function CharIsAsciiUpperCaseB(const C: ByteChar): Boolean; begin Result := Ord(C) in [Ord('A')..Ord('Z')]; end; function CharIsAsciiUpperCaseW(const C: WideChar): Boolean; begin case Ord(C) of Ord('A')..Ord('Z') : Result := True; else Result := False; end; end; function CharIsAsciiUpperCase(const C: Char): Boolean; begin {$IFDEF CharIsWide} Result := CharIsAsciiUpperCaseW(C); {$ELSE} Result := CharIsAsciiUpperCaseB(C); {$ENDIF} end; function CharIsAsciiLowerCaseB(const C: ByteChar): Boolean; begin Result := Ord(C) in [Ord('a')..Ord('z')]; end; function CharIsAsciiLowerCaseW(const C: WideChar): Boolean; begin case Ord(C) of Ord('a')..Ord('z') : Result := True; else Result := False; end; end; function CharIsAsciiLowerCase(const C: Char): Boolean; begin {$IFDEF CharIsWide} Result := CharIsAsciiUpperCaseW(C); {$ELSE} Result := CharIsAsciiUpperCaseB(C); {$ENDIF} end; function CharAsciiLowCaseB(const C: ByteChar): ByteChar; begin if Ord(C) in [Ord('A')..Ord('Z')] then Result := ByteChar(Ord(C) + 32) else Result := C; end; function CharAsciiLowCaseW(const C: WideChar): WideChar; begin case Ord(C) of Ord('A')..Ord('Z') : Result := WideChar(Ord(C) + 32) else Result := C; end; end; function CharAsciiLowCase(const C: Char): Char; begin {$IFDEF CharIsWide} Result := CharAsciiLowCaseW(C); {$ELSE} Result := CharAsciiLowCaseB(C); {$ENDIF} end; function CharAsciiUpCaseB(const C: ByteChar): ByteChar; begin if Ord(C) in [Ord('a')..Ord('a')] then Result := ByteChar(Ord(C) - 32) else Result := C; end; function CharAsciiUpCaseW(const C: WideChar): WideChar; begin case Ord(C) of Ord('a')..Ord('z') : Result := WideChar(Ord(C) - 32) else Result := C; end; end; function CharAsciiUpCase(const C: Char): Char; begin {$IFDEF CharIsWide} Result := CharAsciiUpCaseW(C); {$ELSE} Result := CharAsciiUpCaseB(C); {$ENDIF} end; function CharAsciiHexValueB(const C: ByteChar): Integer; begin case Ord(C) of Ord('0')..Ord('9') : Result := Ord(C) - Ord('0'); Ord('A')..Ord('F') : Result := Ord(C) - Ord('A') + 10; Ord('a')..Ord('f') : Result := Ord(C) - Ord('a') + 10; else Result := -1; end; end; function CharAsciiHexValueW(const C: WideChar): Integer; begin if Ord(C) >= $80 then Result := -1 else Result := CharAsciiHexValueB(ByteChar(Ord(C))); end; function CharAsciiIsHexB(const C: ByteChar): Boolean; begin Result := CharAsciiHexValueB(C) >= 0; end; function CharAsciiIsHexW(const C: WideChar): Boolean; begin Result := CharAsciiHexValueW(C) >= 0; end; { } { String construction from buffer } { } {$IFDEF SupportAnsiString} function StrPToStrA(const P: PAnsiChar; const L: NativeInt): AnsiString; begin if L <= 0 then SetLength(Result, 0) else begin SetLength(Result, L); MoveMem(P^, Pointer(Result)^, L); end; end; {$ENDIF} function StrPToStrB(const P: Pointer; const L: NativeInt): RawByteString; begin if L <= 0 then SetLength(Result, 0) else begin SetLength(Result, L); MoveMem(P^, Pointer(Result)^, L); end; end; function StrPToStrU(const P: PWideChar; const L: NativeInt): UnicodeString; begin if L <= 0 then SetLength(Result, 0) else begin SetLength(Result, L); MoveMem(P^, Pointer(Result)^, L * SizeOf(WideChar)); end; end; function StrPToStr(const P: PChar; const L: NativeInt): String; begin if L <= 0 then SetLength(Result, 0) else begin SetLength(Result, L); MoveMem(P^, Pointer(Result)^, L * SizeOf(Char)); end; end; { } { String construction from zero terminated buffer } { } function StrZLenA(const S: Pointer): NativeInt; var P : PByteChar; begin if not Assigned(S) then Result := 0 else begin Result := 0; P := S; while Ord(P^) <> 0 do begin Inc(Result); Inc(P); end; end; end; function StrZLenW(const S: PWideChar): NativeInt; var P : PWideChar; begin if not Assigned(S) then Result := 0 else begin Result := 0; P := S; while P^ <> #0 do begin Inc(Result); Inc(P); end; end; end; function StrZLen(const S: PChar): NativeInt; var P : PChar; begin if not Assigned(S) then Result := 0 else begin Result := 0; P := S; while P^ <> #0 do begin Inc(Result); Inc(P); end; end; end; {$IFDEF SupportAnsiString} function StrZPasA(const A: PAnsiChar): AnsiString; var I, L : NativeInt; P : PAnsiChar; begin L := StrZLenA(A); SetLength(Result, L); if L = 0 then exit; I := 0; P := A; while I < L do begin Result[I + 1] := P^; Inc(I); Inc(P); end; end; {$ENDIF} function StrZPasB(const A: PByteChar): RawByteString; var I, L : NativeInt; P : PByteChar; begin L := StrZLenA(A); SetLength(Result, L); if L = 0 then exit; I := 0; P := A; while I < L do begin Result[I + 1] := P^; Inc(I); Inc(P); end; end; function StrZPasU(const A: PWideChar): UnicodeString; var I, L : NativeInt; begin L := StrZLenW(A); SetLength(Result, L); if L = 0 then exit; I := 0; while I < L do begin Result[I + 1] := A[I]; Inc(I); end; end; function StrZPas(const A: PChar): String; var I, L : NativeInt; begin L := StrZLen(A); SetLength(Result, L); if L = 0 then exit; I := 0; while I < L do begin Result[I + 1] := A[I]; Inc(I); end; end; { } { RawByteString conversion functions } { } const SRawByteStringConvertError = 'RawByteString conversion error'; procedure RawByteBufToWideBuf( const Buf: Pointer; const BufSize: NativeInt; const DestBuf: Pointer); var I : NativeInt; P : Pointer; Q : Pointer; V : Word32; begin if BufSize <= 0 then exit; P := Buf; Q := DestBuf; for I := 1 to BufSize div 4 do begin // convert 4 characters per iteration V := PWord32(P)^; Inc(PWord32(P)); PWord32(Q)^ := (V and $FF) or ((V and $FF00) shl 8); Inc(PWord32(Q)); V := V shr 16; PWord32(Q)^ := (V and $FF) or ((V and $FF00) shl 8); Inc(PWord32(Q)); end; // convert remaining (<4) for I := 1 to BufSize mod 4 do begin PWord(Q)^ := PByte(P)^; Inc(PByte(P)); Inc(PWord(Q)); end; end; function RawByteStrPtrToUnicodeString(const S: Pointer; const Len: NativeInt): UnicodeString; begin if Len <= 0 then Result := '' else begin SetLength(Result, Len); RawByteBufToWideBuf(S, Len, PWideChar(Result)); end; end; function RawByteStringToUnicodeString(const S: RawByteString): UnicodeString; var L : Integer; begin L := Length(S); SetLength(Result, L); if L > 0 then RawByteBufToWideBuf(Pointer(S), L, PWideChar(Result)); end; procedure WideBufToRawByteBuf( const Buf: Pointer; const Len: NativeInt; const DestBuf: Pointer); var I : NativeInt; S : PWideChar; Q : PByte; V : Word32; W : Word; begin if Len <= 0 then exit; S := Buf; Q := DestBuf; for I := 1 to Len div 2 do begin // convert 2 characters per iteration V := PWord32(S)^; if V and $FF00FF00 <> 0 then raise EConvertError.Create(SRawByteStringConvertError); Q^ := Byte(V); Inc(Q); Q^ := Byte(V shr 16); Inc(Q); Inc(S, 2); end; // convert remaining character if Len mod 2 = 1 then begin W := Ord(S^); if W > $FF then raise EConvertError.Create(SRawByteStringConvertError); Q^ := Byte(W); end; end; function WideBufToRawByteString(const P: PWideChar; const Len: NativeInt): RawByteString; var I : NativeInt; S : PWideChar; Q : PByte; V : WideChar; begin if Len <= 0 then begin Result := ''; exit; end; SetLength(Result, Len); S := P; Q := Pointer(Result); for I := 1 to Len do begin V := S^; if Ord(V) > $FF then raise EConvertError.Create(SRawByteStringConvertError); Q^ := Byte(V); Inc(S); Inc(Q); end; end; function UnicodeStringToRawByteString(const S: UnicodeString): RawByteString; begin Result := WideBufToRawByteString(PWideChar(S), Length(S)); end; { } { String conversion functions } { } {$IFDEF SupportAnsiString} function ToAnsiString(const A: String): AnsiString; begin {$IFDEF StringIsUnicode} Result := AnsiString(A); {$ELSE} Result := A; {$ENDIF} end; {$ENDIF} function ToRawByteString(const A: String): RawByteString; begin {$IFDEF StringIsUnicode} Result := RawByteString(A); {$ELSE} Result := A; {$ENDIF} end; function ToUnicodeString(const A: String): UnicodeString; begin Result := UnicodeString(A); end; { } { String internals functions } { } {$IFNDEF SupportStringRefCount} {$IFDEF DELPHI} function StringRefCount(const S: UnicodeString): Integer; var P : PInt32; begin P := Pointer(S); if not Assigned(P) then Result := 0 else begin Dec(P, 2); Result := P^; end; end; function StringRefCount(const S: RawByteString): Integer; var P : PInt32; begin P := Pointer(S); if not Assigned(P) then Result := 0 else begin Dec(P, 2); Result := P^; end; end; {$ENDIF} {$ENDIF} { } { String append functions } { } {$IFDEF SupportAnsiString} procedure StrAppendChA(var A: AnsiString; const C: AnsiChar); begin A := A + C; end; {$ENDIF} procedure StrAppendChB(var A: RawByteString; const C: ByteChar); begin A := A + C; end; procedure StrAppendChU(var A: UnicodeString; const C: WideChar); begin A := A + C; end; procedure StrAppendCh(var A: String; const C: Char); begin A := A + C; end; { } { ByteCharSet functions } { } function WideCharInCharSet(const A: WideChar; const C: ByteCharSet): Boolean; begin if Ord(A) >= $100 then Result := False else Result := ByteChar(Ord(A)) in C; end; function CharInCharSet(const A: Char; const C: ByteCharSet): Boolean; begin {$IFDEF CharIsWide} if Ord(A) >= $100 then Result := False else Result := ByteChar(Ord(A)) in C; {$ELSE} Result := A in C; {$ENDIF} end; { } { String compare functions } { } function StrPCompareB(const A, B: Pointer; const Len: NativeInt): Integer; begin Result := CompareMemB(A^, B^, Len); end; function StrPCompareW(const A, B: PWideChar; const Len: NativeInt): Integer; begin Result := CompareMemW(A^, B^, Len); end; function StrPCompare(const A, B: PChar; const Len: NativeInt): Integer; begin {$IFDEF CharIsWide} Result := StrPCompareW(A, B, Len); {$ELSE} Result := StrPCompareB(A, B, Len); {$ENDIF} end; function StrPCompareNoAsciiCaseB(const A, B: Pointer; const Len: NativeInt): Integer; begin Result := CompareMemNoAsciiCaseB(A^, B^, Len); end; function StrPCompareNoAsciiCaseW(const A, B: PWideChar; const Len: NativeInt): Integer; begin Result := CompareMemNoAsciiCaseW(A^, B^, Len); end; function StrPCompareNoAsciiCase(const A, B: PChar; const Len: NativeInt): Integer; begin {$IFDEF CharIsWide} Result := StrPCompareNoAsciiCaseW(A, B, Len); {$ELSE} Result := StrPCompareNoAsciiCaseB(A, B, Len); {$ENDIF} end; function StrPEqualB(const A, B: Pointer; const Len: NativeInt): Boolean; begin Result := EqualMem(A^, B^, Len); end; function StrPEqualW(const A, B: PWideChar; const Len: NativeInt): Boolean; begin Result := EqualMem(A^, B^, Len * SizeOf(WideChar)); end; function StrPEqual(const A, B: PChar; const Len: NativeInt): Boolean; begin {$IFDEF CharIsWide} Result := EqualMem(A^, B^, Len * SizeOf(WideChar)); {$ELSE} Result := EqualMem(A^, B^, Len); {$ENDIF} end; function StrPEqualNoAsciiCaseB(const A, B: Pointer; const Len: NativeInt): Boolean; begin Result := EqualMemNoAsciiCaseB(A^, B^, Len); end; function StrPEqualNoAsciiCaseW(const A, B: PWideChar; const Len: NativeInt): Boolean; begin Result := EqualMemNoAsciiCaseW(A^, B^, Len); end; function StrPEqualNoAsciiCase(const A, B: PChar; const Len: NativeInt): Boolean; begin {$IFDEF CharIsWide} Result := EqualMemNoAsciiCaseW(A^, B^, Len); {$ELSE} Result := EqualMemNoAsciiCaseB(A^, B^, Len); {$ENDIF} end; {$IFDEF SupportAnsiString} function StrCompareA(const A, B: AnsiString): Integer; var L, M, I : NativeInt; begin L := Length(A); M := Length(B); if L < M then I := L else I := M; Result := StrPCompareB(Pointer(A), Pointer(B), I); if Result <> 0 then exit; if L = M then Result := 0 else if L < M then Result := -1 else Result := 1; end; {$ENDIF} function StrCompareB(const A, B: RawByteString): Integer; var L, M, I : NativeInt; begin L := Length(A); M := Length(B); if L < M then I := L else I := M; Result := StrPCompareB(Pointer(A), Pointer(B), I); if Result <> 0 then exit; if L = M then Result := 0 else if L < M then Result := -1 else Result := 1; end; function StrCompareU(const A, B: UnicodeString): Integer; var L, M, I : NativeInt; begin L := Length(A); M := Length(B); if L < M then I := L else I := M; Result := StrPCompareW(Pointer(A), Pointer(B), I); if Result <> 0 then exit; if L = M then Result := 0 else if L < M then Result := -1 else Result := 1; end; function StrCompare(const A, B: String): Integer; var L, M, I : NativeInt; begin L := Length(A); M := Length(B); if L < M then I := L else I := M; Result := StrPCompare(Pointer(A), Pointer(B), I); if Result <> 0 then exit; if L = M then Result := 0 else if L < M then Result := -1 else Result := 1; end; {$IFDEF SupportAnsiString} function StrCompareNoAsciiCaseA(const A, B: AnsiString): Integer; var L, M, I: NativeInt; begin L := Length(A); M := Length(B); if L < M then I := L else I := M; Result := StrPCompareNoAsciiCaseB(PByteChar(A), PByteChar(B), I); if Result <> 0 then exit; if L = M then Result := 0 else if L < M then Result := -1 else Result := 1; end; {$ENDIF} function StrCompareNoAsciiCaseB(const A, B: RawByteString): Integer; var L, M, I: NativeInt; begin L := Length(A); M := Length(B); if L < M then I := L else I := M; Result := StrPCompareNoAsciiCaseB(PByteChar(A), PByteChar(B), I); if Result <> 0 then exit; if L = M then Result := 0 else if L < M then Result := -1 else Result := 1; end; function StrCompareNoAsciiCaseU(const A, B: UnicodeString): Integer; var L, M, I: NativeInt; begin L := Length(A); M := Length(B); if L < M then I := L else I := M; Result := StrPCompareNoAsciiCaseW(Pointer(A), Pointer(B), I); if Result <> 0 then exit; if L = M then Result := 0 else if L < M then Result := -1 else Result := 1; end; function StrCompareNoAsciiCase(const A, B: String): Integer; var L, M, I: Integer; begin L := Length(A); M := Length(B); if L < M then I := L else I := M; Result := StrPCompareNoAsciiCase(Pointer(A), Pointer(B), I); if Result <> 0 then exit; if L = M then Result := 0 else if L < M then Result := -1 else Result := 1; end; function StrEqualNoAsciiCaseB(const A, B: RawByteString): Boolean; var L, M : NativeInt; begin L := Length(A); M := Length(B); if L <> M then Result := False else Result := StrPEqualNoAsciiCaseB(PByteChar(A), PByteChar(B), L); end; function StrEqualNoAsciiCaseU(const A, B: UnicodeString): Boolean; var L, M : NativeInt; begin L := Length(A); M := Length(B); if L <> M then Result := False else Result := StrPEqualNoAsciiCaseW(PWideChar(A), PWideChar(B), L); end; function StrEqualNoAsciiCase(const A, B: String): Boolean; var L, M : NativeInt; begin L := Length(A); M := Length(B); if L <> M then Result := False else Result := StrPEqualNoAsciiCase(PChar(A), PChar(B), L); end; function StrStartsWithB(const A, B: RawByteString): Boolean; var L, M : NativeInt; begin L := Length(A); M := Length(B); if L < M then Result := False else Result := StrPEqualB(PByteChar(A), PByteChar(B), M); end; function StrStartsWithU(const A, B: UnicodeString): Boolean; var L, M : NativeInt; begin L := Length(A); M := Length(B); if L < M then Result := False else Result := StrPEqualW(PWideChar(A), PWideChar(B), M); end; function StrStartsWith(const A, B: String): Boolean; var L, M : NativeInt; begin L := Length(A); M := Length(B); if L < M then Result := False else Result := StrPEqual(PChar(A), PChar(B), M); end; function StrStartsWithNoAsciiCaseB(const A, B: RawByteString): Boolean; var L, M : NativeInt; begin L := Length(A); M := Length(B); if L < M then Result := False else Result := StrPEqualNoAsciiCaseB(PByteChar(A), PByteChar(B), M); end; function StrStartsWithNoAsciiCaseU(const A, B: UnicodeString): Boolean; var L, M : NativeInt; begin L := Length(A); M := Length(B); if L < M then Result := False else Result := StrPEqualNoAsciiCaseW(PWideChar(A), PWideChar(B), M); end; function StrStartsWithNoAsciiCase(const A, B: String): Boolean; var L, M : NativeInt; begin L := Length(A); M := Length(B); if L < M then Result := False else Result := StrPEqualNoAsciiCase(PChar(A), PChar(B), M); end; function StrEndsWithB(const A, B: RawByteString): Boolean; var L, M : NativeInt; P : PByteChar; begin L := Length(A); M := Length(B); if L < M then Result := False else begin P := PByteChar(A); Inc(P, L - M); Result := StrPEqualB(P, PByteChar(B), M); end; end; function StrEndsWithU(const A, B: UnicodeString): Boolean; var L, M : NativeInt; P : PWideChar; begin L := Length(A); M := Length(B); if L < M then Result := False else begin P := PWideChar(A); Inc(P, L - M); Result := StrPEqualW(P, PWideChar(B), M); end; end; function StrEndsWith(const A, B: String): Boolean; var L, M : NativeInt; P : PChar; begin L := Length(A); M := Length(B); if L < M then Result := False else begin P := PChar(A); Inc(P, L - M); Result := StrPEqual(P, PChar(B), M); end; end; function StrEndsWithNoAsciiCaseB(const A, B: RawByteString): Boolean; var L, M : NativeInt; P : PByteChar; begin L := Length(A); M := Length(B); if L < M then Result := False else begin P := PByteChar(A); Inc(P, L - M); Result := StrPEqualNoAsciiCaseB(P, PByteChar(B), M); end; end; function StrEndsWithNoAsciiCaseU(const A, B: UnicodeString): Boolean; var L, M : NativeInt; P : PWideChar; begin L := Length(A); M := Length(B); if L < M then Result := False else begin P := PWideChar(A); Inc(P, L - M); Result := StrPEqualNoAsciiCaseW(P, PWideChar(B), M); end; end; function StrEndsWithNoAsciiCase(const A, B: String): Boolean; var L, M : NativeInt; P : PChar; begin L := Length(A); M := Length(B); if L < M then Result := False else begin P := PChar(A); Inc(P, L - M); Result := StrPEqualNoAsciiCase(P, PChar(B), M); end; end; function StrPosB(const S, M: RawByteString): Int32; begin Result := LocateMemB(Pointer(S)^, Length(S), Pointer(M)^, Length(M)); end; function StrPosU(const S, M: UnicodeString): Int32; begin Result := LocateMemW(Pointer(S)^, Length(S), Pointer(M)^, Length(M)); end; function StrPos(const S, M: String): Int32; begin {$IFDEF StringIsUnicode} Result := StrPosU(S, M); {$ELSE} Result := StrPosB(S, M); {$ENDIF} end; function StrPosNoAsciiCaseB(const S, M: RawByteString): Int32; begin Result := LocateMemNoAsciiCaseB(Pointer(S)^, Length(S), Pointer(M)^, Length(M)); end; function StrPosNoAsciiCaseU(const S, M: UnicodeString): Int32; begin Result := LocateMemNoAsciiCaseW(Pointer(S)^, Length(S), Pointer(M)^, Length(M)); end; function StrPosNoAsciiCase(const S, M: String): Int32; begin {$IFDEF StringIsUnicode} Result := StrPosNoAsciiCaseU(S, M); {$ELSE} Result := StrPosNoAsciiCaseB(S, M); {$ENDIF} end; {$IFDEF SupportAnsiString} function StrAsciiUpperCaseA(const S: AnsiString): AnsiString; var U : Boolean; P : PAnsiChar; Q : PAnsiChar; L : NativeInt; I : NativeInt; B : AnsiChar; begin Result := S; U := False; P := Pointer(S); Q := Pointer(Result); L := Length(S); for I := 0 to L - 1 do begin B := P^; if B in ['a'..'z'] then begin B := AnsiChar(Ord(B) - 32); if not U then begin UniqueString(Result); U := True; Q := Pointer(Result); Inc(Q, I); end; Q^ := B; end; Inc(P); Inc(Q); end; end; {$ENDIF} function StrAsciiUpperCaseB(const S: RawByteString): RawByteString; var U : Boolean; P : PByteChar; Q : PByteChar; L : NativeInt; I : NativeInt; B : Byte; begin Result := S; U := False; P := Pointer(S); Q := Pointer(Result); L := Length(S); for I := 0 to L - 1 do begin B := Ord(P^); if B in [Ord('a')..Ord('z')] then begin Dec(B, 32); if not U then begin {$IFDEF SupportAnsiString} UniqueString(AnsiString(Result)); {$ELSE} Result := Copy(S, 1, L); {$ENDIF} U := True; Q := Pointer(Result); Inc(Q, I); end; Q^ := ByteChar(B); end; Inc(P); Inc(Q); end; end; function StrAsciiUpperCaseU(const S: UnicodeString): UnicodeString; var U : Boolean; P : PWideChar; Q : PWideChar; L : NativeInt; I : NativeInt; B : Word16; begin Result := S; U := False; P := Pointer(S); Q := Pointer(Result); L := Length(S); for I := 0 to L - 1 do begin B := Ord(P^); case B of Ord('a')..Ord('z') : begin Dec(B, 32); if not U then begin UniqueString(Result); U := True; Q := Pointer(Result); Inc(Q, I); end; Q^ := WideChar(B); end; end; Inc(P); Inc(Q); end; end; function StrAsciiUpperCase(const S: String): String; begin {$IFDEF StringIsUnicode} Result := StrAsciiUpperCaseU(S); {$ELSE} Result := StrAsciiUpperCaseB(S); {$ENDIF} end; procedure StrAsciiConvertUpperCaseB(var S: RawByteString); begin S := StrAsciiUpperCaseB(S); end; procedure StrAsciiConvertUpperCaseU(var S: UnicodeString); begin S := StrAsciiUpperCaseU(S); end; procedure StrAsciiConvertUpperCase(var S: String); begin {$IFDEF StringIsUnicode} StrAsciiConvertUpperCaseU(S); {$ELSE} StrAsciiConvertUpperCaseB(S); {$ENDIF} end; {$IFDEF SupportAnsiString} function StrAsciiLowerCaseA(const S: AnsiString): AnsiString; var U : Boolean; P : PAnsiChar; Q : PAnsiChar; L : NativeInt; I : NativeInt; B : AnsiChar; begin Result := S; U := False; P := Pointer(S); Q := Pointer(Result); L := Length(S); for I := 0 to L - 1 do begin B := P^; if B in ['A'..'Z'] then begin B := AnsiChar(Ord(B) + 32); if not U then begin UniqueString(Result); U := True; Q := Pointer(Result); Inc(Q, I); end; Q^ := B; end; Inc(P); Inc(Q); end; end; {$ENDIF} function StrAsciiLowerCaseB(const S: RawByteString): RawByteString; var U : Boolean; P : PByteChar; Q : PByteChar; L : NativeInt; I : NativeInt; B : Byte; begin Result := S; U := False; P := Pointer(S); Q := Pointer(Result); L := Length(S); for I := 0 to L - 1 do begin B := Ord(P^); if B in [Ord('A')..Ord('Z')] then begin Inc(B, 32); if not U then begin {$IFDEF SupportAnsiString} UniqueString(AnsiString(Result)); {$ELSE} Result := Copy(S, 1, L); {$ENDIF} U := True; Q := Pointer(Result); Inc(Q, I); end; Q^ := ByteChar(B); end; Inc(P); Inc(Q); end; end; function StrAsciiLowerCaseU(const S: UnicodeString): UnicodeString; var U : Boolean; P : PWideChar; Q : PWideChar; L : NativeInt; I : NativeInt; B : Word16; begin Result := S; U := False; P := Pointer(S); Q := Pointer(Result); L := Length(S); for I := 0 to L - 1 do begin B := Ord(P^); case B of Ord('A')..Ord('Z') : begin Inc(B, 32); if not U then begin UniqueString(Result); U := True; Q := Pointer(Result); Inc(Q, I); end; Q^ := WideChar(B); end; end; Inc(P); Inc(Q); end; end; function StrAsciiLowerCase(const S: String): String; begin {$IFDEF StringIsUnicode} Result := StrAsciiLowerCaseU(S); {$ELSE} Result := StrAsciiLowerCaseB(S); {$ENDIF} end; procedure StrAsciiConvertLowerCaseB(var S: RawByteString); begin S := StrAsciiLowerCaseB(S); end; procedure StrAsciiConvertLowerCaseU(var S: UnicodeString); begin S := StrAsciiLowerCaseU(S); end; procedure StrAsciiConvertLowerCase(var S: String); begin {$IFDEF StringIsUnicode} StrAsciiConvertLowerCaseU(S); {$ELSE} StrAsciiConvertLowerCaseB(S); {$ENDIF} end; procedure StrAsciiConvertFirstUpB(var S: RawByteString); var C : ByteChar; begin if S <> '' then begin C := S[1]; if C in [AsciiLowerA..AsciiLowerZ] then S[1] := CharAsciiUpCaseB(C); end; end; procedure StrAsciiConvertFirstUpU(var S: UnicodeString); var C : WideChar; begin if S <> '' then begin C := S[1]; if (Ord(C) >= Ord(AsciiLowerA)) and (Ord(C) <= Ord(AsciiLowerZ)) then S[1] := CharAsciiUpCaseW(C); end; end; procedure StrAsciiConvertFirstUp(var S: String); var C : Char; begin if S <> '' then begin C := S[1]; if (Ord(C) >= Ord(AsciiLowerA)) and (Ord(C) <= Ord(AsciiLowerZ)) then S[1] := CharAsciiUpCase(C); end; end; function StrAsciiFirstUpB(const S: RawByteString): RawByteString; begin Result := S; StrAsciiConvertFirstUpB(Result); end; function StrAsciiFirstUpU(const S: UnicodeString): UnicodeString; begin Result := S; StrAsciiConvertFirstUpU(Result); end; function StrAsciiFirstUp(const S: String): String; begin Result := S; StrAsciiConvertFirstUp(Result); end; function IsAsciiBufB(const Buf: Pointer; const Len: NativeInt): Boolean; var I : NativeInt; P : PByte; begin P := Buf; for I := 1 to Len do if P^ >= $80 then begin Result := False; exit; end else Inc(P); Result := True; end; function IsAsciiBufW(const Buf: Pointer; const Len: NativeInt): Boolean; var I : NativeInt; P : PWord16; begin P := Buf; for I := 1 to Len do if P^ >= $80 then begin Result := False; exit; end else Inc(P); Result := True; end; function IsAsciiStringB(const S: RawByteString): Boolean; begin Result := IsAsciiBufB(Pointer(S), Length(S)); end; function IsAsciiStringU(const S: UnicodeString): Boolean; begin Result := IsAsciiBufW(PWideChar(S), Length(S)); end; function IsAsciiString(const S: String): Boolean; begin {$IFDEF StringIsUnicode} Result := IsAsciiStringU(S); {$ELSE} Result := IsAsciiStringB(S); {$ENDIF} end; { } { Swap } { } {$IFDEF ASM386_DELPHI} procedure Swap(var X, Y: Boolean); register; assembler; asm MOV CL, [EDX] XCHG BYTE PTR [EAX], CL MOV [EDX], CL end; {$ELSE} procedure Swap(var X, Y: Boolean); var F : Boolean; begin F := X; X := Y; Y := F; end; {$ENDIF} {$IFDEF ASM386_DELPHI} procedure Swap(var X, Y: Byte); register; assembler; asm MOV CL, [EDX] XCHG BYTE PTR [EAX], CL MOV [EDX], CL end; {$ELSE} procedure Swap(var X, Y: Byte); var F : Byte; begin F := X; X := Y; Y := F; end; {$ENDIF} {$IFDEF ASM386_DELPHI} procedure Swap(var X, Y: ShortInt); register; assembler; asm MOV CL, [EDX] XCHG BYTE PTR [EAX], CL MOV [EDX], CL end; {$ELSE} procedure Swap(var X, Y: ShortInt); var F : ShortInt; begin F := X; X := Y; Y := F; end; {$ENDIF} {$IFDEF ASM386_DELPHI} procedure Swap(var X, Y: Word); register; assembler; asm MOV CX, [EDX] XCHG WORD PTR [EAX], CX MOV [EDX], CX end; {$ELSE} procedure Swap(var X, Y: Word); var F : Word; begin F := X; X := Y; Y := F; end; {$ENDIF} {$IFDEF ASM386_DELPHI} procedure Swap(var X, Y: SmallInt); register; assembler; asm MOV CX, [EDX] XCHG WORD PTR [EAX], CX MOV [EDX], CX end; {$ELSE} procedure Swap(var X, Y: SmallInt); var F : SmallInt; begin F := X; X := Y; Y := F; end; {$ENDIF} {$IFDEF ASM386_DELPHI} procedure Swap(var X, Y: Int32); register; assembler; asm MOV ECX, [EDX] XCHG [EAX], ECX MOV [EDX], ECX end; {$ELSE} procedure Swap(var X, Y: Int32); var F : Int32; begin F := X; X := Y; Y := F; end; {$ENDIF} {$IFDEF ASM386_DELPHI} procedure Swap(var X, Y: Word32); register; assembler; asm MOV ECX, [EDX] XCHG [EAX], ECX MOV [EDX], ECX end; {$ELSE} procedure Swap(var X, Y: Word32); var F : Word32; begin F := X; X := Y; Y := F; end; {$ENDIF} {$IFDEF ASM386_DELPHI} procedure Swap(var X, Y: Pointer); register; assembler; asm MOV ECX, [EDX] XCHG [EAX], ECX MOV [EDX], ECX end; {$ELSE} procedure Swap(var X, Y: Pointer); var F : Pointer; begin F := X; X := Y; Y := F; end; {$ENDIF} {$IFDEF ASM386_DELPHI} procedure Swap(var X, Y: TObject); register; assembler; asm MOV ECX, [EDX] XCHG [EAX], ECX MOV [EDX], ECX end; {$ELSE} procedure Swap(var X, Y: TObject); var F : TObject; begin F := X; X := Y; Y := F; end; {$ENDIF} procedure Swap(var X, Y: Int64); var F : Int64; begin F := X; X := Y; Y := F; end; procedure SwapLW(var X, Y: LongWord); var F : LongWord; begin F := X; X := Y; Y := F; end; procedure SwapLI(var X, Y: LongInt); var F : LongInt; begin F := X; X := Y; Y := F; end; procedure SwapInt(var X, Y: Integer); var F : Integer; begin F := X; X := Y; Y := F; end; procedure SwapCrd(var X, Y: Cardinal); var F : Cardinal; begin F := X; X := Y; Y := F; end; procedure Swap(var X, Y: Single); var F : Single; begin F := X; X := Y; Y := F; end; procedure Swap(var X, Y: Double); var F : Double; begin F := X; X := Y; Y := F; end; procedure SwapExt(var X, Y: Extended); var F : Extended; begin F := X; X := Y; Y := F; end; procedure Swap(var X, Y: Currency); var F : Currency; begin F := X; X := Y; Y := F; end; {$IFDEF SupportAnsiString} procedure SwapA(var X, Y: AnsiString); var F : AnsiString; begin F := X; X := Y; Y := F; end; {$ENDIF} procedure SwapB(var X, Y: RawByteString); var F : RawByteString; begin F := X; X := Y; Y := F; end; procedure SwapU(var X, Y: UnicodeString); var F : UnicodeString; begin F := X; X := Y; Y := F; end; procedure Swap(var X, Y: String); var F : String; begin F := X; X := Y; Y := F; end; {$IFDEF ASM386_DELPHI} procedure SwapObjects(var X, Y); register; assembler; asm MOV ECX, [EDX] XCHG [EAX], ECX MOV [EDX], ECX end; {$ELSE} procedure SwapObjects(var X, Y); var F: TObject; begin F := TObject(X); TObject(X) := TObject(Y); TObject(Y) := F; end; {$ENDIF} { } { iif } { } function iif(const Expr: Boolean; const TrueValue, FalseValue: Integer): Integer; begin if Expr then Result := TrueValue else Result := FalseValue; end; function iif(const Expr: Boolean; const TrueValue, FalseValue: Int64): Int64; begin if Expr then Result := TrueValue else Result := FalseValue; end; function iif(const Expr: Boolean; const TrueValue, FalseValue: Extended): Extended; begin if Expr then Result := TrueValue else Result := FalseValue; end; function iif(const Expr: Boolean; const TrueValue, FalseValue: String): String; begin if Expr then Result := TrueValue else Result := FalseValue; end; {$IFDEF SupportAnsiString} function iifA(const Expr: Boolean; const TrueValue, FalseValue: AnsiString): AnsiString; begin if Expr then Result := TrueValue else Result := FalseValue; end; {$ENDIF} function iifB(const Expr: Boolean; const TrueValue, FalseValue: RawByteString): RawByteString; begin if Expr then Result := TrueValue else Result := FalseValue; end; function iifU(const Expr: Boolean; const TrueValue, FalseValue: UnicodeString): UnicodeString; begin if Expr then Result := TrueValue else Result := FalseValue; end; function iif(const Expr: Boolean; const TrueValue, FalseValue: TObject): TObject; begin if Expr then Result := TrueValue else Result := FalseValue; end; { } { Compare } { } function InverseCompareResult(const C: TCompareResult): TCompareResult; begin if C = crLess then Result := crGreater else if C = crGreater then Result := crLess else Result := C; end; function Compare(const I1, I2: Integer): TCompareResult; begin if I1 < I2 then Result := crLess else if I1 > I2 then Result := crGreater else Result := crEqual; end; function Compare(const I1, I2: Int64): TCompareResult; begin if I1 < I2 then Result := crLess else if I1 > I2 then Result := crGreater else Result := crEqual; end; function Compare(const I1, I2: Double): TCompareResult; begin if I1 < I2 then Result := crLess else if I1 > I2 then Result := crGreater else Result := crEqual; end; function Compare(const I1, I2: Boolean): TCompareResult; begin if I1 = I2 then Result := crEqual else if I1 then Result := crGreater else Result := crLess; end; {$IFDEF SupportAnsiString} function CompareA(const I1, I2: AnsiString): TCompareResult; begin case StrCompareA(I1, I2) of -1 : Result := crLess; 1 : Result := crGreater; else Result := crEqual; end; end; {$ENDIF} function CompareB(const I1, I2: RawByteString): TCompareResult; begin case StrCompareB(I1, I2) of -1 : Result := crLess; 1 : Result := crGreater; else Result := crEqual; end; end; function CompareU(const I1, I2: UnicodeString): TCompareResult; begin if I1 = I2 then Result := crEqual else if I1 > I2 then Result := crGreater else Result := crLess; end; function CompareChB(const I1, I2: ByteChar): TCompareResult; begin if I1 = I2 then Result := crEqual else if I1 > I2 then Result := crGreater else Result := crLess; end; function CompareChW(const I1, I2: WideChar): TCompareResult; begin if I1 = I2 then Result := crEqual else if I1 > I2 then Result := crGreater else Result := crLess; end; function Sgn(const A: Int64): Integer; begin if A < 0 then Result := -1 else if A > 0 then Result := 1 else Result := 0; end; function Sgn(const A: Double): Integer; begin if A < 0 then Result := -1 else if A > 0 then Result := 1 else Result := 0; end; { } { Ascii char conversion lookup } { } const AsciiHexLookup: array[Byte] of Byte = ( $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, $FF, $FF, $FF, $FF, $FF, $FF, $FF, 10, 11, 12, 13, 14, 15, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, 10, 11, 12, 13, 14, 15, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF, $FF); { } { Integer-String conversions } { } function ByteCharDigitToInt(const A: ByteChar): Integer; begin if A in [ByteChar(Ord('0'))..ByteChar(Ord('9'))] then Result := Ord(A) - Ord('0') else Result := -1; end; function WideCharDigitToInt(const A: WideChar): Integer; begin if (Ord(A) >= Ord('0')) and (Ord(A) <= Ord('9')) then Result := Ord(A) - Ord('0') else Result := -1; end; function CharDigitToInt(const A: Char): Integer; begin {$IFDEF CharIsWide} Result := WideCharDigitToInt(A); {$ELSE} Result := ByteCharDigitToInt(A); {$ENDIF} end; function IntToByteCharDigit(const A: Integer): ByteChar; begin if (A < 0) or (A > 9) then Result := ByteChar($00) else Result := ByteChar(48 + A); end; function IntToWideCharDigit(const A: Integer): WideChar; begin if (A < 0) or (A > 9) then Result := WideChar($00) else Result := WideChar(48 + A); end; function IntToCharDigit(const A: Integer): Char; begin {$IFDEF CharIsWide} Result := IntToWideCharDigit(A); {$ELSE} Result := IntToByteCharDigit(A); {$ENDIF} end; function IsHexByteCharDigit(const Ch: ByteChar): Boolean; begin Result := AsciiHexLookup[Ord(Ch)] <= 15; end; function IsHexWideCharDigit(const Ch: WideChar): Boolean; begin if Ord(Ch) <= $FF then Result := AsciiHexLookup[Ord(Ch)] <= 15 else Result := False; end; function IsHexCharDigit(const Ch: Char): Boolean; begin {$IFDEF CharIsWide} Result := IsHexWideCharDigit(Ch); {$ELSE} Result := IsHexByteCharDigit(Ch); {$ENDIF} end; function HexByteCharDigitToInt(const A: ByteChar): Integer; var B : Byte; begin B := AsciiHexLookup[Ord(A)]; if B = $FF then Result := -1 else Result := B; end; function HexWideCharDigitToInt(const A: WideChar): Integer; var B : Byte; begin if Ord(A) > $FF then Result := -1 else begin B := AsciiHexLookup[Ord(A)]; if B = $FF then Result := -1 else Result := B; end; end; function HexCharDigitToInt(const A: Char): Integer; begin {$IFDEF CharIsWide} Result := HexWideCharDigitToInt(A); {$ELSE} Result := HexByteCharDigitToInt(A); {$ENDIF} end; function IntToUpperHexByteCharDigit(const A: Integer): ByteChar; begin if (A < 0) or (A > 15) then Result := ByteChar($00) else if A <= 9 then Result := ByteChar(48 + A) else Result := ByteChar(55 + A); end; function IntToUpperHexWideCharDigit(const A: Integer): WideChar; begin if (A < 0) or (A > 15) then Result := #$00 else if A <= 9 then Result := WideChar(48 + A) else Result := WideChar(55 + A); end; function IntToUpperHexCharDigit(const A: Integer): Char; begin {$IFDEF CharIsWide} Result := IntToUpperHexWideCharDigit(A); {$ELSE} Result := IntToUpperHexByteCharDigit(A); {$ENDIF} end; function IntToLowerHexByteCharDigit(const A: Integer): ByteChar; begin if (A < 0) or (A > 15) then Result := ByteChar($00) else if A <= 9 then Result := ByteChar(48 + A) else Result := ByteChar(87 + A); end; function IntToLowerHexWideCharDigit(const A: Integer): WideChar; begin if (A < 0) or (A > 15) then Result := #$00 else if A <= 9 then Result := WideChar(48 + A) else Result := WideChar(87 + A); end; function IntToLowerHexCharDigit(const A: Integer): Char; begin {$IFDEF CharIsWide} Result := IntToLowerHexWideCharDigit(A); {$ELSE} Result := IntToLowerHexByteCharDigit(A); {$ENDIF} end; {$IFDEF SupportAnsiString} function IntToStringA(const A: Int64): AnsiString; var T : Int64; L : Integer; I : Integer; begin // special cases if A = 0 then begin Result := ToAnsiString('0'); exit; end; if A = MinInt64 then begin Result := ToAnsiString('-9223372036854775808'); exit; end; // calculate string length if A < 0 then L := 1 else L := 0; T := A; while T <> 0 do begin T := T div 10; Inc(L); end; // convert SetLength(Result, L); I := 0; T := A; if T < 0 then begin Result[1] := ByteChar(Ord('-')); T := -T; end; while T > 0 do begin Result[L - I] := IntToByteCharDigit(T mod 10); T := T div 10; Inc(I); end; end; {$ENDIF} function IntToStringB(const A: Int64): RawByteString; var T : Int64; L : Integer; I : Integer; begin // special cases if A = 0 then begin Result := ToRawByteString('0'); exit; end; if A = MinInt64 then begin Result := ToRawByteString('-9223372036854775808'); exit; end; // calculate string length if A < 0 then L := 1 else L := 0; T := A; while T <> 0 do begin T := T div 10; Inc(L); end; // convert SetLength(Result, L); I := 0; T := A; if T < 0 then begin Result[1] := '-'; T := -T; end; while T > 0 do begin Result[L - I] := UTF8Char(IntToByteCharDigit(T mod 10)); T := T div 10; Inc(I); end; end; function IntToStringU(const A: Int64): UnicodeString; var T : Int64; L : Integer; I : Integer; begin // special cases if A = 0 then begin Result := '0'; exit; end; if A = MinInt64 then begin Result := '-9223372036854775808'; exit; end; // calculate string length if A < 0 then L := 1 else L := 0; T := A; while T <> 0 do begin T := T div 10; Inc(L); end; // convert SetLength(Result, L); I := 0; T := A; if T < 0 then begin Result[1] := '-'; T := -T; end; while T > 0 do begin Result[L - I] := IntToWideCharDigit(T mod 10); T := T div 10; Inc(I); end; end; function IntToString(const A: Int64): String; var T : Int64; L : Integer; I : Integer; begin // special cases if A = 0 then begin Result := '0'; exit; end; if A = MinInt64 then begin Result := '-9223372036854775808'; exit; end; // calculate string length if A < 0 then L := 1 else L := 0; T := A; while T <> 0 do begin T := T div 10; Inc(L); end; // convert SetLength(Result, L); I := 0; T := A; if T < 0 then begin Result[1] := '-'; T := -T; end; while T > 0 do begin Result[L - I] := IntToCharDigit(T mod 10); T := T div 10; Inc(I); end; end; {$IFDEF SupportAnsiString} function UIntToBaseA( const Value: UInt64; const Digits: Integer; const Base: Byte; const UpperCase: Boolean = True): AnsiString; var D : UInt64; L : Integer; V : Byte; begin Assert((Base >= 2) and (Base <= 16)); if Value = 0 then // handle zero value begin if Digits = 0 then L := 1 else L := Digits; SetLength(Result, L); for V := 0 to L - 1 do Result[1 + V] := ByteChar(Ord('0')); exit; end; // determine number of digits in result L := 0; D := Value; while D > 0 do begin Inc(L); D := D div Base; end; if L < Digits then L := Digits; // do conversion SetLength(Result, L); D := Value; while D > 0 do begin V := D mod Base + 1; if UpperCase then Result[L] := ByteChar(StrHexDigitsUpper[V]) else Result[L] := ByteChar(StrHexDigitsLower[V]); Dec(L); D := D div Base; end; while L > 0 do begin Result[L] := ByteChar(Ord('0')); Dec(L); end; end; {$ENDIF} function UIntToBaseB( const Value: UInt64; const Digits: Integer; const Base: Byte; const UpperCase: Boolean = True): RawByteString; var D : UInt64; L : Integer; V : Byte; begin Assert((Base >= 2) and (Base <= 16)); if Value = 0 then // handle zero value begin if Digits = 0 then L := 1 else L := Digits; SetLength(Result, L); for V := 0 to L - 1 do Result[1 + V] := '0'; exit; end; // determine number of digits in result L := 0; D := Value; while D > 0 do begin Inc(L); D := D div Base; end; if L < Digits then L := Digits; // do conversion SetLength(Result, L); D := Value; while D > 0 do begin V := D mod Base + 1; if UpperCase then Result[L] := UTF8Char(StrHexDigitsUpper[V]) else Result[L] := UTF8Char(StrHexDigitsLower[V]); Dec(L); D := D div Base; end; while L > 0 do begin Result[L] := '0'; Dec(L); end; end; function UIntToBaseU( const Value: UInt64; const Digits: Integer; const Base: Byte; const UpperCase: Boolean = True): UnicodeString; var D : UInt64; L : Integer; V : Byte; begin Assert((Base >= 2) and (Base <= 16)); if Value = 0 then // handle zero value begin if Digits = 0 then L := 1 else L := Digits; SetLength(Result, L); for V := 1 to L do Result[V] := '0'; exit; end; // determine number of digits in result L := 0; D := Value; while D > 0 do begin Inc(L); D := D div Base; end; if L < Digits then L := Digits; // do conversion SetLength(Result, L); D := Value; while D > 0 do begin V := D mod Base + 1; if UpperCase then Result[L] := WideChar(StrHexDigitsUpper[V]) else Result[L] := WideChar(StrHexDigitsLower[V]); Dec(L); D := D div Base; end; while L > 0 do begin Result[L] := '0'; Dec(L); end; end; function UIntToBase( const Value: UInt64; const Digits: Integer; const Base: Byte; const UpperCase: Boolean = True): String; var D : UInt64; L : Integer; V : Byte; begin Assert((Base >= 2) and (Base <= 16)); if Value = 0 then // handle zero value begin if Digits = 0 then L := 1 else L := Digits; SetLength(Result, L); for V := 1 to L do Result[V] := '0'; exit; end; // determine number of digits in result L := 0; D := Value; while D > 0 do begin Inc(L); D := D div Base; end; if L < Digits then L := Digits; // do conversion SetLength(Result, L); D := Value; while D > 0 do begin V := D mod Base + 1; if UpperCase then Result[L] := Char(StrHexDigitsUpper[V]) else Result[L] := Char(StrHexDigitsLower[V]); Dec(L); D := D div Base; end; while L > 0 do begin Result[L] := '0'; Dec(L); end; end; {$IFDEF SupportAnsiString} function UIntToStringA(const A: UInt64): AnsiString; begin Result := UIntToBaseA(A, 0, 10); end; {$ENDIF} function UIntToStringB(const A: UInt64): RawByteString; begin Result := UIntToBaseB(A, 0, 10); end; function UIntToStringU(const A: UInt64): UnicodeString; begin Result := UIntToBaseU(A, 0, 10); end; function UIntToString(const A: UInt64): String; begin Result := UIntToBase(A, 0, 10); end; {$IFDEF SupportAnsiString} function Word32ToStrA(const A: Word32; const Digits: Integer): AnsiString; begin Result := UIntToBaseA(A, Digits, 10); end; {$ENDIF} function Word32ToStrB(const A: Word32; const Digits: Integer): RawByteString; begin Result := UIntToBaseB(A, Digits, 10); end; function Word32ToStrU(const A: Word32; const Digits: Integer): UnicodeString; begin Result := UIntToBaseU(A, Digits, 10); end; function Word32ToStr(const A: Word32; const Digits: Integer): String; begin Result := UIntToBase(A, Digits, 10); end; {$IFDEF SupportAnsiString} function Word32ToHexA(const A: Word32; const Digits: Integer; const UpperCase: Boolean): AnsiString; begin Result := UIntToBaseA(A, Digits, 16, UpperCase); end; {$ENDIF} function Word32ToHexB(const A: Word32; const Digits: Integer; const UpperCase: Boolean): RawByteString; begin Result := UIntToBaseB(A, Digits, 16, UpperCase); end; function Word32ToHexU(const A: Word32; const Digits: Integer; const UpperCase: Boolean): UnicodeString; begin Result := UIntToBaseU(A, Digits, 16, UpperCase); end; function Word32ToHex(const A: Word32; const Digits: Integer; const UpperCase: Boolean): String; begin Result := UIntToBase(A, Digits, 16, UpperCase); end; {$IFDEF SupportAnsiString} function Word32ToOctA(const A: Word32; const Digits: Integer): AnsiString; begin Result := UIntToBaseA(A, Digits, 8); end; {$ENDIF} function Word32ToOctB(const A: Word32; const Digits: Integer): RawByteString; begin Result := UIntToBaseB(A, Digits, 8); end; function Word32ToOctU(const A: Word32; const Digits: Integer): UnicodeString; begin Result := UIntToBaseU(A, Digits, 8); end; function Word32ToOct(const A: Word32; const Digits: Integer): String; begin Result := UIntToBase(A, Digits, 8); end; {$IFDEF SupportAnsiString} function Word32ToBinA(const A: Word32; const Digits: Integer): AnsiString; begin Result := UIntToBaseA(A, Digits, 2); end; {$ENDIF} function Word32ToBinB(const A: Word32; const Digits: Integer): RawByteString; begin Result := UIntToBaseB(A, Digits, 2); end; function Word32ToBinU(const A: Word32; const Digits: Integer): UnicodeString; begin Result := UIntToBaseU(A, Digits, 2); end; function Word32ToBin(const A: Word32; const Digits: Integer): String; begin Result := UIntToBase(A, Digits, 2); end; {$IFNDEF DELPHI7} {$IFOPT Q+}{$DEFINE QOn}{$Q-}{$ELSE}{$UNDEF QOn}{$ENDIF} // Delphi 7 incorrectly overflowing for -922337203685477580 * 10 function TryStringToUInt64PB(const BufP: Pointer; const BufLen: Integer; out Value: UInt64; out StrLen: Integer): TConvertResult; var ChP : PByte; Len : Integer; HasDig : Boolean; Res : UInt64; Ch : Byte; DigVal : Integer; begin if BufLen <= 0 then begin Value := 0; StrLen := 0; Result := convertFormatError; exit; end; Assert(Assigned(BufP)); ChP := BufP; Len := 0; HasDig := False; // skip leading zeros while (Len < BufLen) and (ChP^ = Ord('0')) do begin Inc(Len); Inc(ChP); HasDig := True; end; // convert digits Res := 0; while Len < BufLen do begin Ch := ChP^; if Ch in [Ord('0')..Ord('9')] then begin HasDig := True; {$IFDEF DELPHI7} if (PWord64Rec(@Res)^.Word32Hi > $19999999) or ((PWord64Rec(@Res)^.Word32Hi = $19999999) and (PWord64Rec(@Res)^.Word32Lo > $99999999)) then {$ELSE} if (Res > 1844674407370955161) then {$ENDIF} begin Value := 0; StrLen := Len; Result := convertOverflow; exit; end; Res := Res * 10; DigVal := ByteCharDigitToInt(ByteChar(Ch)); {$IFDEF DELPHI7} if (PWord64Rec(@Res)^.Word32Hi = $FFFFFFFF) and (PWord64Rec(@Res)^.Word32Lo = $FFFFFFFA) and (DigVal > 5) then {$ELSE} if (Res = 18446744073709551610) and (DigVal > 5) then {$ENDIF} begin Value := 0; StrLen := Len; Result := convertOverflow; exit; end; Inc(Res, DigVal); Inc(Len); Inc(ChP); end else break; end; StrLen := Len; if not HasDig then begin Value := 0; Result := convertFormatError; end else begin Value := Res; Result := convertOK; end; end; function TryStringToUInt64PW(const BufP: Pointer; const BufLen: Integer; out Value: UInt64; out StrLen: Integer): TConvertResult; var ChP : PWideChar; Len : Integer; HasDig : Boolean; Res : UInt64; Ch : WideChar; DigVal : Integer; begin if BufLen <= 0 then begin Value := 0; StrLen := 0; Result := convertFormatError; exit; end; Assert(Assigned(BufP)); ChP := BufP; Len := 0; HasDig := False; // skip leading zeros while (Len < BufLen) and (ChP^ = '0') do begin Inc(Len); Inc(ChP); HasDig := True; end; // convert digits Res := 0; while Len < BufLen do begin Ch := ChP^; if (Ch >= '0') and (Ch <= '9') then begin HasDig := True; {$IFDEF DELPHI7} if (PWord64Rec(@Res)^.Word32Hi > $19999999) or ((PWord64Rec(@Res)^.Word32Hi = $19999999) and (PWord64Rec(@Res)^.Word32Lo > $99999999)) then {$ELSE} if (Res > 1844674407370955161) then {$ENDIF} begin Value := 0; StrLen := Len; Result := convertOverflow; exit; end; Res := Res * 10; DigVal := WideCharDigitToInt(Ch); {$IFDEF DELPHI7} if (PWord64Rec(@Res)^.Word32Hi = $FFFFFFFF) and (PWord64Rec(@Res)^.Word32Lo = $FFFFFFFA) and (DigVal > 5) then {$ELSE} if (Res = 18446744073709551610) and (DigVal > 5) then {$ENDIF} begin Value := 0; StrLen := Len; Result := convertOverflow; exit; end; Inc(Res, DigVal); Inc(Len); Inc(ChP); end else break; end; StrLen := Len; if not HasDig then begin Value := 0; Result := convertFormatError; end else begin Value := Res; Result := convertOK; end; end; function TryStringToUInt64P(const BufP: Pointer; const BufLen: Integer; out Value: UInt64; out StrLen: Integer): TConvertResult; {$IFDEF UseInline}inline;{$ENDIF} begin {$IFDEF StringIsUnicode} Result := TryStringToUInt64PW(BufP, BufLen, Value, StrLen); {$ELSE} Result := TryStringToUInt64PB(BufP, BufLen, Value, StrLen); {$ENDIF} end; {$ENDIF} function TryStringToInt64PB(const BufP: Pointer; const BufLen: Integer; out Value: Int64; out StrLen: Integer): TConvertResult; var Len : Integer; DigVal : Integer; P : PByte; Ch : Byte; HasDig : Boolean; Neg : Boolean; Res : Int64; begin if BufLen <= 0 then begin Value := 0; StrLen := 0; Result := convertFormatError; exit; end; P := BufP; Len := 0; // check sign Ch := P^; if Ch in [Ord('+'), Ord('-')] then begin Inc(Len); Inc(P); Neg := Ch = Ord('-'); end else Neg := False; // skip leading zeros HasDig := False; while (Len < BufLen) and (P^ = Ord('0')) do begin Inc(Len); Inc(P); HasDig := True; end; // convert digits Res := 0; while Len < BufLen do begin Ch := P^; if Ch in [Ord('0')..Ord('9')] then begin HasDig := True; if (Res > 922337203685477580) or (Res < -922337203685477580) then begin Value := 0; StrLen := Len; Result := convertOverflow; exit; end; Res := Res * 10; DigVal := ByteCharDigitToInt(ByteChar(Ch)); if ((Res = 9223372036854775800) and (DigVal > 7)) or ((Res = -9223372036854775800) and (DigVal > 8)) then begin Value := 0; StrLen := Len; Result := convertOverflow; exit; end; if Neg then Dec(Res, DigVal) else Inc(Res, DigVal); Inc(Len); Inc(P); end else break; end; StrLen := Len; if not HasDig then begin Value := 0; Result := convertFormatError; end else begin Value := Res; Result := convertOK; end; end; function TryStringToInt64PW(const BufP: Pointer; const BufLen: Integer; out Value: Int64; out StrLen: Integer): TConvertResult; var Len : Integer; DigVal : Integer; P : PWideChar; Ch : WideChar; HasDig : Boolean; Neg : Boolean; Res : Int64; begin if BufLen <= 0 then begin Value := 0; StrLen := 0; Result := convertFormatError; exit; end; P := BufP; Len := 0; // check sign Ch := P^; if (Ch = '+') or (Ch = '-') then begin Inc(Len); Inc(P); Neg := Ch = '-'; end else Neg := False; // skip leading zeros HasDig := False; while (Len < BufLen) and (P^ = '0') do begin Inc(Len); Inc(P); HasDig := True; end; // convert digits Res := 0; while Len < BufLen do begin Ch := P^; if (Ch >= '0') and (Ch <= '9') then begin HasDig := True; if (Res > 922337203685477580) or (Res < -922337203685477580) then begin Value := 0; StrLen := Len; Result := convertOverflow; exit; end; Res := Res * 10; DigVal := WideCharDigitToInt(Ch); if ((Res = 9223372036854775800) and (DigVal > 7)) or ((Res = -9223372036854775800) and (DigVal > 8)) then begin Value := 0; StrLen := Len; Result := convertOverflow; exit; end; if Neg then Dec(Res, DigVal) else Inc(Res, DigVal); Inc(Len); Inc(P); end else break; end; StrLen := Len; if not HasDig then begin Value := 0; Result := convertFormatError; end else begin Value := Res; Result := convertOK; end; end; function TryStringToInt64P(const BufP: Pointer; const BufLen: Integer; out Value: Int64; out StrLen: Integer): TConvertResult; var Len : Integer; DigVal : Integer; P : PChar; Ch : Char; HasDig : Boolean; Neg : Boolean; Res : Int64; begin if BufLen <= 0 then begin Value := 0; StrLen := 0; Result := convertFormatError; exit; end; P := BufP; Len := 0; // check sign Ch := P^; if (Ch = '+') or (Ch = '-') then begin Inc(Len); Inc(P); Neg := Ch = '-'; end else Neg := False; // skip leading zeros HasDig := False; while (Len < BufLen) and (P^ = '0') do begin Inc(Len); Inc(P); HasDig := True; end; // convert digits Res := 0; while Len < BufLen do begin Ch := P^; if (Ch >= '0') and (Ch <= '9') then begin HasDig := True; if (Res > 922337203685477580) or (Res < -922337203685477580) then begin Value := 0; StrLen := Len; Result := convertOverflow; exit; end; Res := Res * 10; DigVal := CharDigitToInt(Ch); if ((Res = 9223372036854775800) and (DigVal > 7)) or ((Res = -9223372036854775800) and (DigVal > 8)) then begin Value := 0; StrLen := Len; Result := convertOverflow; exit; end; if Neg then Dec(Res, DigVal) else Inc(Res, DigVal); Inc(Len); Inc(P); end else break; end; StrLen := Len; if not HasDig then begin Value := 0; Result := convertFormatError; end else begin Value := Res; Result := convertOK; end; end; {$IFDEF QOn}{$Q+}{$ENDIF} {$IFDEF SupportAnsiString} function TryStringToInt64A(const S: AnsiString; out A: Int64): Boolean; var L, N : Integer; begin L := Length(S); Result := TryStringToInt64PB(PAnsiChar(S), L, A, N) = convertOK; if Result then if N < L then Result := False; end; {$ENDIF} function TryStringToInt64B(const S: RawByteString; out A: Int64): Boolean; var L, N : Integer; begin L := Length(S); Result := TryStringToInt64PB(Pointer(S), L, A, N) = convertOK; if Result then if N < L then Result := False; end; function TryStringToInt64U(const S: UnicodeString; out A: Int64): Boolean; var L, N : Integer; begin L := Length(S); Result := TryStringToInt64PW(PWideChar(S), L, A, N) = convertOK; if Result then if N < L then Result := False; end; function TryStringToInt64(const S: String; out A: Int64): Boolean; var L, N : Integer; begin L := Length(S); Result := TryStringToInt64P(PChar(S), L, A, N) = convertOK; if Result then if N < L then Result := False; end; {$IFNDEF DELPHI7} {$IFDEF SupportAnsiString} function TryStringToUInt64A(const S: AnsiString; out A: UInt64): Boolean; var L, N : Integer; begin L := Length(S); Result := TryStringToUInt64PB(PAnsiChar(S), L, A, N) = convertOK; if Result then if N < L then Result := False; end; {$ENDIF} function TryStringToUInt64B(const S: RawByteString; out A: UInt64): Boolean; var L, N : Integer; begin L := Length(S); Result := TryStringToUInt64PB(Pointer(S), L, A, N) = convertOK; if Result then if N < L then Result := False; end; function TryStringToUInt64U(const S: UnicodeString; out A: UInt64): Boolean; var L, N : Integer; begin L := Length(S); Result := TryStringToUInt64PW(PWideChar(S), L, A, N) = convertOK; if Result then if N < L then Result := False; end; function TryStringToUInt64(const S: String; out A: UInt64): Boolean; var L, N : Integer; begin L := Length(S); Result := TryStringToUInt64P(PChar(S), L, A, N) = convertOK; if Result then if N < L then Result := False; end; {$IFDEF SupportAnsiString} function StringToInt64DefA(const S: AnsiString; const Default: Int64): Int64; begin if not TryStringToInt64A(S, Result) then Result := Default; end; {$ENDIF} function StringToInt64DefB(const S: RawByteString; const Default: Int64): Int64; begin if not TryStringToInt64B(S, Result) then Result := Default; end; function StringToInt64DefU(const S: UnicodeString; const Default: Int64): Int64; begin if not TryStringToInt64U(S, Result) then Result := Default; end; function StringToInt64Def(const S: String; const Default: Int64): Int64; begin if not TryStringToInt64(S, Result) then Result := Default; end; {$IFDEF SupportAnsiString} function StringToUInt64DefA(const S: AnsiString; const Default: UInt64): UInt64; begin if not TryStringToUInt64A(S, Result) then Result := Default; end; {$ENDIF} function StringToUInt64DefB(const S: RawByteString; const Default: UInt64): UInt64; begin if not TryStringToUInt64B(S, Result) then Result := Default; end; function StringToUInt64DefU(const S: UnicodeString; const Default: UInt64): UInt64; begin if not TryStringToUInt64U(S, Result) then Result := Default; end; function StringToUInt64Def(const S: String; const Default: UInt64): UInt64; begin if not TryStringToUInt64(S, Result) then Result := Default; end; {$IFDEF SupportAnsiString} function StringToInt64A(const S: AnsiString): Int64; begin if not TryStringToInt64A(S, Result) then raise ERangeCheckError.Create; end; {$ENDIF} function StringToInt64B(const S: RawByteString): Int64; begin if not TryStringToInt64B(S, Result) then raise ERangeCheckError.Create; end; function StringToInt64U(const S: UnicodeString): Int64; begin if not TryStringToInt64U(S, Result) then raise ERangeCheckError.Create; end; function StringToInt64(const S: String): Int64; begin if not TryStringToInt64(S, Result) then raise ERangeCheckError.Create; end; {$IFDEF SupportAnsiString} function StringToUInt64A(const S: AnsiString): UInt64; begin if not TryStringToUInt64A(S, Result) then raise ERangeCheckError.Create; end; {$ENDIF} function StringToUInt64B(const S: RawByteString): UInt64; begin if not TryStringToUInt64B(S, Result) then raise ERangeCheckError.Create; end; function StringToUInt64U(const S: UnicodeString): UInt64; begin if not TryStringToUInt64U(S, Result) then raise ERangeCheckError.Create; end; function StringToUInt64(const S: String): UInt64; begin if not TryStringToUInt64(S, Result) then raise ERangeCheckError.Create; end; {$ENDIF ~DELPHI7} {$IFDEF SupportAnsiString} function TryStringToIntA(const S: AnsiString; out A: Integer): Boolean; var B : Int64; begin Result := TryStringToInt64A(S, B); if not Result then begin A := 0; exit; end; if (B < MinInteger) or (B > MaxInteger) then begin A := 0; Result := False; exit; end; A := Integer(B); Result := True; end; {$ENDIF} function TryStringToIntB(const S: RawByteString; out A: Integer): Boolean; var B : Int64; begin Result := TryStringToInt64B(S, B); if not Result then begin A := 0; exit; end; if (B < MinInteger) or (B > MaxInteger) then begin A := 0; Result := False; exit; end; A := Integer(B); Result := True; end; function TryStringToIntU(const S: UnicodeString; out A: Integer): Boolean; var B : Int64; begin Result := TryStringToInt64U(S, B); if not Result then begin A := 0; exit; end; if (B < MinInteger) or (B > MaxInteger) then begin A := 0; Result := False; exit; end; A := Integer(B); Result := True; end; function TryStringToInt(const S: String; out A: Integer): Boolean; var B : Int64; begin Result := TryStringToInt64(S, B); if not Result then begin A := 0; exit; end; if (B < MinInteger) or (B > MaxInteger) then begin A := 0; Result := False; exit; end; A := Integer(B); Result := True; end; {$IFDEF SupportAnsiString} function StringToIntDefA(const S: AnsiString; const Default: Integer): Integer; begin if not TryStringToIntA(S, Result) then Result := Default; end; {$ENDIF} function StringToIntDefB(const S: RawByteString; const Default: Integer): Integer; begin if not TryStringToIntB(S, Result) then Result := Default; end; function StringToIntDefU(const S: UnicodeString; const Default: Integer): Integer; begin if not TryStringToIntU(S, Result) then Result := Default; end; function StringToIntDef(const S: String; const Default: Integer): Integer; begin if not TryStringToInt(S, Result) then Result := Default; end; {$IFDEF SupportAnsiString} function StringToIntA(const S: AnsiString): Integer; begin if not TryStringToIntA(S, Result) then raise ERangeCheckError.Create; end; {$ENDIF} function StringToIntB(const S: RawByteString): Integer; begin if not TryStringToIntB(S, Result) then raise ERangeCheckError.Create; end; function StringToIntU(const S: UnicodeString): Integer; begin if not TryStringToIntU(S, Result) then raise ERangeCheckError.Create; end; function StringToInt(const S: String): Integer; begin if not TryStringToInt(S, Result) then raise ERangeCheckError.Create; end; {$IFDEF SupportAnsiString} function TryStringToWord32A(const S: AnsiString; out A: Word32): Boolean; var B : Int64; begin Result := TryStringToInt64A(S, B); if not Result then begin A := 0; exit; end; if (B < MinWord32) or (B > MaxWord32) then begin A := 0; Result := False; exit; end; A := Word32(B); Result := True; end; {$ENDIF} function TryStringToWord32B(const S: RawByteString; out A: Word32): Boolean; var B : Int64; begin Result := TryStringToInt64B(S, B); if not Result then begin A := 0; exit; end; if (B < MinWord32) or (B > MaxWord32) then begin A := 0; Result := False; exit; end; A := Word32(B); Result := True; end; function TryStringToWord32U(const S: UnicodeString; out A: Word32): Boolean; var B : Int64; begin Result := TryStringToInt64U(S, B); if not Result then begin A := 0; exit; end; if (B < MinWord32) or (B > MaxWord32) then begin A := 0; Result := False; exit; end; A := Word32(B); Result := True; end; function TryStringToWord32(const S: String; out A: Word32): Boolean; var B : Int64; begin Result := TryStringToInt64(S, B); if not Result then begin A := 0; exit; end; if (B < MinWord32) or (B > MaxWord32) then begin A := 0; Result := False; exit; end; A := Word32(B); Result := True; end; {$IFDEF SupportAnsiString} function StringToWord32A(const S: AnsiString): Word32; begin if not TryStringToWord32A(S, Result) then raise ERangeCheckError.Create; end; {$ENDIF} function StringToWord32B(const S: RawByteString): Word32; begin if not TryStringToWord32B(S, Result) then raise ERangeCheckError.Create; end; function StringToWord32U(const S: UnicodeString): Word32; begin if not TryStringToWord32U(S, Result) then raise ERangeCheckError.Create; end; function StringToWord32(const S: String): Word32; begin if not TryStringToWord32(S, Result) then raise ERangeCheckError.Create; end; {$IFDEF SupportAnsiString} function BaseStrToUIntA(const S: AnsiString; const BaseLog2: Byte; var Valid: Boolean): UInt64; var N : Byte; L : Integer; M : Byte; C : Byte; begin Assert(BaseLog2 <= 4); // maximum base 16 L := Length(S); if L = 0 then // empty string is invalid begin Valid := False; Result := 0; exit; end; M := (1 shl BaseLog2) - 1; // maximum digit value N := 0; Result := 0; repeat C := AsciiHexLookup[Ord(S[L])]; if C > M then // invalid digit begin Valid := False; Result := 0; exit; end; {$IFDEF FPC} Result := Result + UInt64(C) shl N; {$ELSE} Inc(Result, UInt64(C) shl N); {$ENDIF} Inc(N, BaseLog2); if N > 64 then // overflow begin Valid := False; Result := 0; exit; end; Dec(L); until L = 0; Valid := True; end; {$ENDIF} function BaseStrToUIntB(const S: RawByteString; const BaseLog2: Byte; var Valid: Boolean): UInt64; var N : Byte; L : Integer; M : Byte; C : Byte; begin Assert(BaseLog2 <= 4); // maximum base 16 L := Length(S); if L = 0 then // empty string is invalid begin Valid := False; Result := 0; exit; end; M := (1 shl BaseLog2) - 1; // maximum digit value N := 0; Result := 0; repeat C := AsciiHexLookup[Ord(S[L])]; if C > M then // invalid digit begin Valid := False; Result := 0; exit; end; {$IFDEF FPC} Result := Result + UInt64(C) shl N; {$ELSE} Inc(Result, UInt64(C) shl N); {$ENDIF} Inc(N, BaseLog2); if N > 64 then // overflow begin Valid := False; Result := 0; exit; end; Dec(L); until L = 0; Valid := True; end; function BaseStrToUIntU(const S: UnicodeString; const BaseLog2: Byte; var Valid: Boolean): UInt64; var N : Byte; L : Integer; M : Byte; C : Byte; D : WideChar; begin Assert(BaseLog2 <= 4); // maximum base 16 L := Length(S); if L = 0 then // empty string is invalid begin Valid := False; Result := 0; exit; end; M := (1 shl BaseLog2) - 1; // maximum digit value N := 0; Result := 0; repeat D := S[L]; if Ord(D) > $FF then C := $FF else C := AsciiHexLookup[Ord(D)]; if C > M then // invalid digit begin Valid := False; Result := 0; exit; end; {$IFDEF FPC} Result := Result + UInt64(C) shl N; {$ELSE} Inc(Result, UInt64(C) shl N); {$ENDIF} Inc(N, BaseLog2); if N > 64 then // overflow begin Valid := False; Result := 0; exit; end; Dec(L); until L = 0; Valid := True; end; function BaseStrToUInt(const S: String; const BaseLog2: Byte; var Valid: Boolean): UInt64; var N : Byte; L : Integer; M : Byte; C : Byte; D : Char; begin Assert(BaseLog2 <= 4); // maximum base 16 L := Length(S); if L = 0 then // empty string is invalid begin Valid := False; Result := 0; exit; end; M := (1 shl BaseLog2) - 1; // maximum digit value N := 0; Result := 0; repeat D := S[L]; {$IFDEF CharIsWide} if Ord(D) > $FF then C := $FF else C := AsciiHexLookup[Ord(D)]; {$ELSE} C := AsciiHexLookup[Ord(D)]; {$ENDIF} if C > M then // invalid digit begin Valid := False; Result := 0; exit; end; {$IFDEF FPC} Result := Result + UInt64(C) shl N; {$ELSE} Inc(Result, UInt64(C) shl N); {$ENDIF} Inc(N, BaseLog2); if N > 64 then // overflow begin Valid := False; Result := 0; exit; end; Dec(L); until L = 0; Valid := True; end; {$IFDEF SupportAnsiString} function HexToUIntA(const S: AnsiString): UInt64; var R : Boolean; begin Result := BaseStrToUIntA(S, 4, R); if not R then raise ERangeCheckError.Create; end; {$ENDIF} function HexToUIntB(const S: RawByteString): UInt64; var R : Boolean; begin Result := BaseStrToUIntB(S, 4, R); if not R then raise ERangeCheckError.Create; end; function HexToUIntU(const S: UnicodeString): UInt64; var R : Boolean; begin Result := BaseStrToUIntU(S, 4, R); if not R then raise ERangeCheckError.Create; end; function HexToUInt(const S: String): UInt64; var R : Boolean; begin Result := BaseStrToUInt(S, 4, R); if not R then raise ERangeCheckError.Create; end; {$IFDEF SupportAnsiString} function TryHexToWord32A(const S: AnsiString; out A: Word32): Boolean; begin A := BaseStrToUIntA(S, 4, Result); end; {$ENDIF} function TryHexToWord32B(const S: RawByteString; out A: Word32): Boolean; begin A := BaseStrToUIntB(S, 4, Result); end; function TryHexToWord32U(const S: UnicodeString; out A: Word32): Boolean; begin A := BaseStrToUIntU(S, 4, Result); end; function TryHexToWord32(const S: String; out A: Word32): Boolean; begin A := BaseStrToUInt(S, 4, Result); end; {$IFDEF SupportAnsiString} function HexToWord32A(const S: AnsiString): Word32; var R : Boolean; begin Result := BaseStrToUIntA(S, 4, R); if not R then raise ERangeCheckError.Create; end; {$ENDIF} function HexToWord32B(const S: RawByteString): Word32; var R : Boolean; begin Result := BaseStrToUIntB(S, 4, R); if not R then raise ERangeCheckError.Create; end; function HexToWord32U(const S: UnicodeString): Word32; var R : Boolean; begin Result := BaseStrToUIntU(S, 4, R); if not R then raise ERangeCheckError.Create; end; function HexToWord32(const S: String): Word32; var R : Boolean; begin Result := BaseStrToUInt(S, 4, R); if not R then raise ERangeCheckError.Create; end; {$IFDEF SupportAnsiString} function TryOctToWord32A(const S: AnsiString; out A: Word32): Boolean; begin A := BaseStrToUIntA(S, 3, Result); end; {$ENDIF} function TryOctToWord32B(const S: RawByteString; out A: Word32): Boolean; begin A := BaseStrToUIntB(S, 3, Result); end; function TryOctToWord32U(const S: UnicodeString; out A: Word32): Boolean; begin A := BaseStrToUIntU(S, 3, Result); end; function TryOctToWord32(const S: String; out A: Word32): Boolean; begin A := BaseStrToUInt(S, 3, Result); end; {$IFDEF SupportAnsiString} function OctToWord32A(const S: AnsiString): Word32; var R : Boolean; begin Result := BaseStrToUIntA(S, 3, R); if not R then raise ERangeCheckError.Create; end; {$ENDIF} function OctToWord32B(const S: RawByteString): Word32; var R : Boolean; begin Result := BaseStrToUIntB(S, 3, R); if not R then raise ERangeCheckError.Create; end; function OctToWord32U(const S: UnicodeString): Word32; var R : Boolean; begin Result := BaseStrToUIntU(S, 3, R); if not R then raise ERangeCheckError.Create; end; function OctToWord32(const S: String): Word32; var R : Boolean; begin Result := BaseStrToUInt(S, 3, R); if not R then raise ERangeCheckError.Create; end; {$IFDEF SupportAnsiString} function TryBinToWord32A(const S: AnsiString; out A: Word32): Boolean; begin A := BaseStrToUIntA(S, 1, Result); end; {$ENDIF} function TryBinToWord32B(const S: RawByteString; out A: Word32): Boolean; begin A := BaseStrToUIntB(S, 1, Result); end; function TryBinToWord32U(const S: UnicodeString; out A: Word32): Boolean; begin A := BaseStrToUIntU(S, 1, Result); end; function TryBinToWord32(const S: String; out A: Word32): Boolean; begin A := BaseStrToUInt(S, 1, Result); end; {$IFDEF SupportAnsiString} function BinToWord32A(const S: AnsiString): Word32; var R : Boolean; begin Result := BaseStrToUIntA(S, 1, R); if not R then raise ERangeCheckError.Create; end; {$ENDIF} function BinToWord32B(const S: RawByteString): Word32; var R : Boolean; begin Result := BaseStrToUIntB(S, 1, R); if not R then raise ERangeCheckError.Create; end; function BinToWord32U(const S: UnicodeString): Word32; var R : Boolean; begin Result := BaseStrToUIntU(S, 1, R); if not R then raise ERangeCheckError.Create; end; function BinToWord32(const S: String): Word32; var R : Boolean; begin Result := BaseStrToUInt(S, 1, R); if not R then raise ERangeCheckError.Create; end; {$IFDEF SupportAnsiString} function BytesToHexA(const P: Pointer; const Count: NativeInt; const UpperCase: Boolean): AnsiString; var Q : PByte; D : PAnsiChar; L : NativeInt; V : Byte; begin Q := P; L := Count; if (L <= 0) or not Assigned(Q) then begin Result := ''; exit; end; SetLength(Result, Count * 2); D := Pointer(Result); while L > 0 do begin V := Q^ shr 4 + 1; if UpperCase then D^ := AnsiChar(StrHexDigitsUpper[V]) else D^ := AnsiChar(StrHexDigitsLower[V]); Inc(D); V := Q^ and $F + 1; if UpperCase then D^ := AnsiChar(StrHexDigitsUpper[V]) else D^ := AnsiChar(StrHexDigitsLower[V]); Inc(D); Inc(Q); Dec(L); end; end; {$ENDIF} { } { Network byte order } { } function hton16(const A: Word): Word; begin Result := Word(A shr 8) or Word(A shl 8); end; function ntoh16(const A: Word): Word; begin Result := Word(A shr 8) or Word(A shl 8); end; function hton32(const A: Word32): Word32; var BufH : array[0..3] of Byte; BufN : array[0..3] of Byte; begin PWord32(@BufH)^ := A; BufN[0] := BufH[3]; BufN[1] := BufH[2]; BufN[2] := BufH[1]; BufN[3] := BufH[0]; Result := PWord32(@BufN)^; end; function ntoh32(const A: Word32): Word32; var BufH : array[0..3] of Byte; BufN : array[0..3] of Byte; begin PWord32(@BufH)^ := A; BufN[0] := BufH[3]; BufN[1] := BufH[2]; BufN[2] := BufH[1]; BufN[3] := BufH[0]; Result := PWord32(@BufN)^; end; function hton64(const A: Int64): Int64; var BufH : array[0..7] of Byte; BufN : array[0..7] of Byte; begin PInt64(@BufH)^ := A; BufN[0] := BufH[7]; BufN[1] := BufH[6]; BufN[2] := BufH[5]; BufN[3] := BufH[4]; BufN[4] := BufH[3]; BufN[5] := BufH[2]; BufN[6] := BufH[1]; BufN[7] := BufH[0]; Result := PInt64(@BufN)^; end; function ntoh64(const A: Int64): Int64; var BufH : array[0..7] of Byte; BufN : array[0..7] of Byte; begin PInt64(@BufH)^ := A; BufN[0] := BufH[7]; BufN[1] := BufH[6]; BufN[2] := BufH[5]; BufN[3] := BufH[4]; BufN[4] := BufH[3]; BufN[5] := BufH[2]; BufN[6] := BufH[1]; BufN[7] := BufH[0]; Result := PInt64(@BufN)^; end; { } { Pointer-String conversions } { } {$IFDEF SupportAnsiString} function PointerToStrA(const P: Pointer): AnsiString; begin Result := UIntToBaseA(NativeUInt(P), NativeWordSize * 2, 16, True); end; {$ENDIF} function PointerToStrB(const P: Pointer): RawByteString; begin Result := UIntToBaseB(NativeUInt(P), NativeWordSize * 2, 16, True); end; function PointerToStrU(const P: Pointer): UnicodeString; begin Result := UIntToBaseU(NativeUInt(P), NativeWordSize * 2, 16, True); end; function PointerToStr(const P: Pointer): String; begin Result := UIntToBase(NativeUInt(P), NativeWordSize * 2, 16, True); end; {$IFDEF SupportAnsiString} function StrToPointerA(const S: AnsiString): Pointer; var V : Boolean; begin Result := Pointer(BaseStrToUIntA(S, 4, V)); end; {$ENDIF} function StrToPointerB(const S: RawByteString): Pointer; var V : Boolean; begin Result := Pointer(BaseStrToUIntB(S, 4, V)); end; function StrToPointerU(const S: UnicodeString): Pointer; var V : Boolean; begin Result := Pointer(BaseStrToUIntU(S, 4, V)); end; function StrToPointer(const S: String): Pointer; var V : Boolean; begin Result := Pointer(BaseStrToUInt(S, 4, V)); end; function ObjectClassName(const O: TObject): String; begin if not Assigned(O) then Result := 'nil' else Result := O.ClassName; end; function ClassClassName(const C: TClass): String; begin if not Assigned(C) then Result := 'nil' else Result := C.ClassName; end; function ObjectToStr(const O: TObject): String; begin if not Assigned(O) then Result := 'nil' else Result := O.ClassName + '@' + PointerToStr(Pointer(O)); end; { } { Hash functions } { Derived from a CRC32 algorithm. } { } var HashTableInit : Boolean = False; HashTable : array[Byte] of Word32; HashPoly : Word32 = $EDB88320; procedure InitHashTable; var I, J : Byte; R : Word32; begin for I := $00 to $FF do begin R := I; for J := 8 downto 1 do if R and 1 <> 0 then R := (R shr 1) xor HashPoly else R := R shr 1; HashTable[I] := R; end; HashTableInit := True; end; function HashByte(const Hash: Word32; const C: Byte): Word32; {$IFDEF UseInline}inline;{$ENDIF} begin Result := HashTable[Byte(Hash) xor C] xor (Hash shr 8); end; function HashCharB(const Hash: Word32; const Ch: ByteChar): Word32; {$IFDEF UseInline}inline;{$ENDIF} begin Result := HashByte(Hash, Byte(Ch)); end; function HashCharW(const Hash: Word32; const Ch: WideChar): Word32; {$IFDEF UseInline}inline;{$ENDIF} var C1, C2 : Byte; begin C1 := Byte(Ord(Ch) and $FF); C2 := Byte(Ord(Ch) shr 8); Result := Hash; Result := HashByte(Result, C1); Result := HashByte(Result, C2); end; function HashChar(const Hash: Word32; const Ch: Char): Word32; {$IFDEF UseInline}inline;{$ENDIF} begin {$IFDEF CharIsWide} Result := HashCharW(Hash, Ch); {$ELSE} Result := HashCharB(Hash, Ch); {$ENDIF} end; function HashCharNoAsciiCaseB(const Hash: Word32; const Ch: ByteChar): Word32; {$IFDEF UseInline}inline;{$ENDIF} var C : Byte; begin C := Byte(Ch); if C in [Ord('A')..Ord('Z')] then C := C or 32; Result := HashCharB(Hash, ByteChar(C)); end; function HashCharNoAsciiCaseW(const Hash: Word32; const Ch: WideChar): Word32; {$IFDEF UseInline}inline;{$ENDIF} var C : Word; begin C := Word(Ch); if C <= $FF then if Byte(C) in [Ord('A')..Ord('Z')] then C := C or 32; Result := HashCharW(Hash, WideChar(C)); end; function HashCharNoAsciiCase(const Hash: Word32; const Ch: Char): Word32; {$IFDEF UseInline}inline;{$ENDIF} begin {$IFDEF CharIsWide} Result := HashCharNoAsciiCaseW(Hash, Ch); {$ELSE} Result := HashCharNoAsciiCaseB(Hash, Ch); {$ENDIF} end; function HashBuf(const Hash: Word32; const Buf; const BufSize: NativeInt): Word32; var P : PByte; I : NativeInt; begin if not HashTableInit then InitHashTable; Result := Hash; P := @Buf; for I := 0 to BufSize - 1 do begin Result := HashByte(Result, P^); Inc(P); end; end; {$IFDEF SupportAnsiString} function HashStrA( const S: AnsiString; const Index: NativeInt; const Count: NativeInt; const AsciiCaseSensitive: Boolean; const Slots: Word32): Word32; var I, L, A, B : NativeInt; begin if not HashTableInit then InitHashTable; A := Index; if A < 1 then A := 1; L := Length(S); B := Count; if B < 0 then B := L else begin B := A + B - 1; if B > L then B := L; end; Result := $FFFFFFFF; if AsciiCaseSensitive then for I := A to B do Result := HashCharB(Result, S[I]) else for I := A to B do Result := HashCharNoAsciiCaseB(Result, S[I]); if Slots > 0 then Result := Result mod Slots; end; {$ENDIF} function HashStrB( const S: RawByteString; const Index: NativeInt; const Count: NativeInt; const AsciiCaseSensitive: Boolean; const Slots: Word32): Word32; var I, L, A, B : NativeInt; begin if not HashTableInit then InitHashTable; A := Index; if A < 1 then A := 1; L := Length(S); B := Count; if B < 0 then B := L else begin B := A + B - 1; if B > L then B := L; end; Result := $FFFFFFFF; if AsciiCaseSensitive then for I := A to B do Result := HashCharB(Result, ByteChar(S[I])) else for I := A to B do Result := HashCharNoAsciiCaseB(Result, ByteChar(S[I])); if Slots > 0 then Result := Result mod Slots; end; function HashStrU( const S: UnicodeString; const Index: NativeInt; const Count: NativeInt; const AsciiCaseSensitive: Boolean; const Slots: Word32): Word32; var I, L, A, B : NativeInt; begin if not HashTableInit then InitHashTable; A := Index; if A < 1 then A := 1; L := Length(S); B := Count; if B < 0 then B := L else begin B := A + B - 1; if B > L then B := L; end; Result := $FFFFFFFF; if AsciiCaseSensitive then for I := A to B do Result := HashCharW(Result, S[I]) else for I := A to B do Result := HashCharNoAsciiCaseW(Result, S[I]); if Slots > 0 then Result := Result mod Slots; end; function HashStr( const S: String; const Index: NativeInt; const Count: NativeInt; const AsciiCaseSensitive: Boolean; const Slots: Word32): Word32; var I, L, A, B : NativeInt; begin if not HashTableInit then InitHashTable; A := Index; if A < 1 then A := 1; L := Length(S); B := Count; if B < 0 then B := L else begin B := A + B - 1; if B > L then B := L; end; Result := $FFFFFFFF; if AsciiCaseSensitive then for I := A to B do Result := HashChar(Result, S[I]) else for I := A to B do Result := HashCharNoAsciiCase(Result, S[I]); if Slots > 0 then Result := Result mod Slots; end; { HashInteger based on the CRC32 algorithm. It is a very good all purpose hash } { with a highly uniform distribution of results. } function HashInteger(const I: Integer; const Slots: Word32): Word32; var P : PByte; J : Integer; begin if not HashTableInit then InitHashTable; Result := $FFFFFFFF; P := @I; for J := 0 to SizeOf(Integer) - 1 do begin Result := HashTable[Byte(Result) xor P^] xor (Result shr 8); Inc(P); end; if Slots <> 0 then Result := Result mod Slots; end; function HashNativeUInt(const I: NativeUInt; const Slots: Word32): Word32; var P : PByte; J : Integer; begin if not HashTableInit then InitHashTable; Result := $FFFFFFFF; P := @I; for J := 0 to SizeOf(NativeUInt) - 1 do begin Result := HashTable[Byte(Result) xor P^] xor (Result shr 8); Inc(P); end; if Slots <> 0 then Result := Result mod Slots; end; function HashWord32(const I: Word32; const Slots: Word32): Word32; var P : PByte; begin if not HashTableInit then InitHashTable; Result := $FFFFFFFF; P := @I; Result := HashTable[Byte(Result) xor P^] xor (Result shr 8); Inc(P); Result := HashTable[Byte(Result) xor P^] xor (Result shr 8); Inc(P); Result := HashTable[Byte(Result) xor P^] xor (Result shr 8); Inc(P); Result := HashTable[Byte(Result) xor P^] xor (Result shr 8); if Slots <> 0 then Result := Result mod Slots; end; { } { FreeAndNil } { } procedure FreeAndNil(var Obj); var Temp : TObject; begin Temp := TObject(Obj); Pointer(Obj) := nil; Temp.Free; end; procedure FreeObjectArray(var V); var I : Integer; A : ObjectArray absolute V; begin for I := Length(A) - 1 downto 0 do FreeAndNil(A[I]); end; procedure FreeObjectArray(var V; const LoIdx, HiIdx: Integer); var I : Integer; A : ObjectArray absolute V; begin for I := HiIdx downto LoIdx do FreeAndNil(A[I]); end; // Note: The parameter can not be changed to be untyped and then typecasted // using an absolute variable, as in FreeObjectArray. The reference counting // will be done incorrectly. procedure FreeAndNilObjectArray(var V: ObjectArray); var W : ObjectArray; begin W := V; V := nil; FreeObjectArray(W); end; { } { TBytes functions } { } procedure BytesSetLengthAndZero(var V: TBytes; const NewLength: NativeInt); var OldLen, NewLen : NativeInt; begin NewLen := NewLength; if NewLen < 0 then NewLen := 0; OldLen := Length(V); if OldLen = NewLen then exit; SetLength(V, NewLen); if OldLen > NewLen then exit; ZeroMem(V[OldLen], NewLen - OldLen); end; procedure BytesInit(var V: TBytes; const R: Byte); begin SetLength(V, 1); V[0] := R; end; procedure BytesInit(var V: TBytes; const S: String); var L, I : Integer; begin L := Length(S); SetLength(V, L); for I := 0 to L - 1 do V[I] := Ord(S[I + 1]); end; procedure BytesInit(var V: TBytes; const S: array of Byte); var L, I : Integer; begin L := Length(S); SetLength(V, L); for I := 0 to L - 1 do V[I] := S[I]; end; function BytesAppend(var V: TBytes; const R: Byte): NativeInt; begin Result := Length(V); SetLength(V, Result + 1); V[Result] := R; end; function BytesAppend(var V: TBytes; const R: TBytes): NativeInt; var L : NativeInt; begin Result := Length(V); L := Length(R); if L > 0 then begin SetLength(V, Result + L); MoveMem(R[0], V[Result], L); end; end; function BytesAppend(var V: TBytes; const R: array of Byte): NativeInt; var L : NativeInt; begin Result := Length(V); L := Length(R); if L > 0 then begin SetLength(V, Result + L); MoveMem(R[0], V[Result], L); end; end; function BytesAppend(var V: TBytes; const R: String): NativeInt; var L, I : NativeInt; begin Result := Length(V); L := Length(R); if L > 0 then begin SetLength(V, Result + L); for I := 1 to L do V[Result] := Ord(R[I]); end; end; function BytesCompare(const A, B: TBytes): Integer; var L, N : NativeInt; begin L := Length(A); N := Length(B); if L < N then Result := -1 else if L > N then Result := 1 else Result := CompareMemB(Pointer(A)^, Pointer(B)^, L); end; function BytesEqual(const A, B: TBytes): Boolean; var L, N : NativeInt; begin L := Length(A); N := Length(B); if L <> N then Result := False else Result := EqualMem(Pointer(A)^, Pointer(B)^, L); end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpSecP521R1Curve; {$I ..\..\..\..\Include\CryptoLib.inc} interface uses ClpHex, ClpBits, ClpNat, ClpECCurve, ClpIECInterface, ClpISecP521R1FieldElement, ClpSecP521R1Point, ClpISecP521R1Curve, ClpISecP521R1Point, ClpIECFieldElement, ClpBigInteger, ClpCryptoLibTypes; type TSecP521R1Curve = class sealed(TAbstractFpCurve, ISecP521R1Curve) strict private type TSecP521R1LookupTable = class sealed(TInterfacedObject, ISecP521R1LookupTable, IECLookupTable) strict private var Fm_outer: ISecP521R1Curve; Fm_table: TCryptoLibUInt32Array; Fm_size: Int32; function GetSize: Int32; virtual; public constructor Create(const outer: ISecP521R1Curve; const table: TCryptoLibUInt32Array; size: Int32); function Lookup(index: Int32): IECPoint; virtual; property size: Int32 read GetSize; end; const SECP521R1_DEFAULT_COORDS = Int32(TECCurve.COORD_JACOBIAN); SECP521R1_FE_INTS = Int32(17); class var Fq: TBigInteger; class function GetSecP521R1Curve_Q: TBigInteger; static; inline; class constructor SecP521R1Curve(); strict protected var Fm_infinity: ISecP521R1Point; function GetQ: TBigInteger; virtual; function GetFieldSize: Int32; override; function GetInfinity: IECPoint; override; function CloneCurve(): IECCurve; override; function CreateRawPoint(const x, y: IECFieldElement; withCompression: Boolean): IECPoint; overload; override; function CreateRawPoint(const x, y: IECFieldElement; const zs: TCryptoLibGenericArray<IECFieldElement>; withCompression: Boolean): IECPoint; overload; override; public constructor Create(); function FromBigInteger(const x: TBigInteger): IECFieldElement; override; function SupportsCoordinateSystem(coord: Int32): Boolean; override; function CreateCacheSafeLookupTable(const points : TCryptoLibGenericArray<IECPoint>; off, len: Int32) : IECLookupTable; override; property Q: TBigInteger read GetQ; property Infinity: IECPoint read GetInfinity; property FieldSize: Int32 read GetFieldSize; class property SecP521R1Curve_Q: TBigInteger read GetSecP521R1Curve_Q; end; implementation uses // included here to avoid circular dependency :) ClpSecP521R1FieldElement; { TSecP521R1Curve } class function TSecP521R1Curve.GetSecP521R1Curve_Q: TBigInteger; begin result := Fq; end; class constructor TSecP521R1Curve.SecP521R1Curve; begin Fq := TBigInteger.Create(1, THex.Decode ('01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF') ); end; constructor TSecP521R1Curve.Create; begin Inherited Create(Fq); Fm_infinity := TSecP521R1Point.Create(Self as IECCurve, Nil, Nil); Fm_a := FromBigInteger(TBigInteger.Create(1, THex.Decode ('01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC')) ); Fm_b := FromBigInteger(TBigInteger.Create(1, THex.Decode ('0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00')) ); Fm_order := TBigInteger.Create(1, THex.Decode ('01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409') ); Fm_cofactor := TBigInteger.One; Fm_coord := SECP521R1_DEFAULT_COORDS; end; function TSecP521R1Curve.CloneCurve: IECCurve; begin result := TSecP521R1Curve.Create(); end; function TSecP521R1Curve.CreateCacheSafeLookupTable(const points : TCryptoLibGenericArray<IECPoint>; off, len: Int32): IECLookupTable; var table: TCryptoLibUInt32Array; pos, i: Int32; p: IECPoint; begin System.SetLength(table, len * SECP521R1_FE_INTS * 2); pos := 0; for i := 0 to System.Pred(len) do begin p := points[off + i]; TNat.Copy(SECP521R1_FE_INTS, (p.RawXCoord as ISecP521R1FieldElement).x, 0, table, pos); pos := pos + SECP521R1_FE_INTS; TNat.Copy(SECP521R1_FE_INTS, (p.RawYCoord as ISecP521R1FieldElement).x, 0, table, pos); pos := pos + SECP521R1_FE_INTS; end; result := TSecP521R1LookupTable.Create(Self as ISecP521R1Curve, table, len); end; function TSecP521R1Curve.CreateRawPoint(const x, y: IECFieldElement; withCompression: Boolean): IECPoint; begin result := TSecP521R1Point.Create(Self as IECCurve, x, y, withCompression); end; function TSecP521R1Curve.CreateRawPoint(const x, y: IECFieldElement; const zs: TCryptoLibGenericArray<IECFieldElement>; withCompression: Boolean) : IECPoint; begin result := TSecP521R1Point.Create(Self as IECCurve, x, y, zs, withCompression); end; function TSecP521R1Curve.FromBigInteger(const x: TBigInteger): IECFieldElement; begin result := TSecP521R1FieldElement.Create(x); end; function TSecP521R1Curve.GetFieldSize: Int32; begin result := Fq.BitLength; end; function TSecP521R1Curve.GetInfinity: IECPoint; begin result := Fm_infinity; end; function TSecP521R1Curve.GetQ: TBigInteger; begin result := Fq; end; function TSecP521R1Curve.SupportsCoordinateSystem(coord: Int32): Boolean; begin case coord of COORD_JACOBIAN: result := True else result := False; end; end; { TSecP521R1Curve.TSecP521R1LookupTable } constructor TSecP521R1Curve.TSecP521R1LookupTable.Create (const outer: ISecP521R1Curve; const table: TCryptoLibUInt32Array; size: Int32); begin Inherited Create(); Fm_outer := outer; Fm_table := table; Fm_size := size; end; function TSecP521R1Curve.TSecP521R1LookupTable.GetSize: Int32; begin result := Fm_size; end; function TSecP521R1Curve.TSecP521R1LookupTable.Lookup(index: Int32): IECPoint; var x, y: TCryptoLibUInt32Array; pos, i, J: Int32; MASK: UInt32; begin x := TNat.Create(SECP521R1_FE_INTS); y := TNat.Create(SECP521R1_FE_INTS); pos := 0; for i := 0 to System.Pred(Fm_size) do begin MASK := UInt32(TBits.Asr32((i xor index) - 1, 31)); for J := 0 to System.Pred(SECP521R1_FE_INTS) do begin x[J] := x[J] xor (Fm_table[pos + J] and MASK); y[J] := y[J] xor (Fm_table[pos + SECP521R1_FE_INTS + J] and MASK); end; pos := pos + (SECP521R1_FE_INTS * 2); end; result := Fm_outer.CreateRawPoint(TSecP521R1FieldElement.Create(x) as ISecP521R1FieldElement, TSecP521R1FieldElement.Create(y) as ISecP521R1FieldElement, False); end; end.
{ Double Commander ------------------------------------------------------------------------- Plugins options page Copyright (C) 2006-2018 Alexander Koblov (alexx2000@mail.ru) 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. } unit fOptionsPluginsBase; {$mode objfpc}{$H+} interface uses //Lazarus, Free-Pascal, etc. Classes, SysUtils, ComCtrls, StdCtrls, Grids, Buttons, Controls, ExtCtrls, //DC fOptionsFrame, uGlobs; type { TfrmOptionsPluginsBase } TfrmOptionsPluginsBase = class(TOptionsEditor) pnlPlugIn: TPanel; lblPlugInDescription: TLabel; stgPlugins: TStringGrid; pnlButton: TPanel; btnToggleOptionPlugins: TBitBtn; btnAddPlugin: TBitBtn; btnEnablePlugin: TBitBtn; btnRemovePlugin: TBitBtn; btnTweakPlugin: TBitBtn; btnConfigPlugin: TBitBtn; ImgSwitchEnable: TImage; ImgSwitchDisable: TImage; ImgByPlugin: TImage; ImgByExtension: TImage; procedure btnPluginsNotImplementedClick(Sender: TObject); procedure btnRemovePluginClick(Sender: TObject); procedure btnTweakPluginClick(Sender: TObject); procedure stgPluginsDblClick(Sender: TObject); procedure stgPluginsDragOver(Sender, {%H-}Source: TObject; X, Y: integer; {%H-}State: TDragState; var Accept: boolean); procedure stgPluginsDragDrop(Sender, {%H-}Source: TObject; X, Y: integer); procedure stgPluginsGetCellHint(Sender: TObject; ACol, ARow: integer; var HintText: string); procedure stgPluginsShowHint(Sender: TObject; HintInfo: PHintInfo); function GetPluginFilenameToSave(const Filename: string): string; private FPluginType: TPluginType; protected property PluginType: TPluginType read FPluginType write FPluginType; procedure Init; override; procedure ShowPluginsTable; virtual; procedure stgPluginsOnSelection(Sender: TObject; {%H-}aCol, {%H-}aRow: integer); virtual; procedure ActualDeletePlugin({%H-}iIndex: integer); virtual; procedure ActualPluginsMove({%H-}iSource, {%H-}iDestination: integer); virtual; public class function GetIconIndex: integer; override; function IsSignatureComputedFromAllWindowComponents: boolean; override; end; implementation {$R *.lfm} uses //Lazarus, Free-Pascal, etc. StrUtils, LCLProc, Forms, Dialogs, //DC udcutils, uLng, uShowMsg, fTweakPlugin, uDefaultPlugins; { TfrmOptionsPluginsBase } { TfrmOptionsPluginsBase.Init } procedure TfrmOptionsPluginsBase.Init; begin // Localize plugins. stgPlugins.Columns.Items[0].Title.Caption := rsOptPluginsActive; stgPlugins.Columns.Items[1].Title.Caption := rsOptPluginsName; stgPlugins.Columns.Items[2].Title.Caption := rsOptPluginsRegisteredFor; stgPlugins.Columns.Items[3].Title.Caption := rsOptPluginsFileName; stgPlugins.OnSelection := @stgPluginsOnSelection; end; { TfrmOptionsPluginsBase } procedure TfrmOptionsPluginsBase.ShowPluginsTable; begin //empty end; { TfrmOptionsPluginsBase.stgPluginsOnSelection} procedure TfrmOptionsPluginsBase.stgPluginsOnSelection(Sender: TObject; aCol, aRow: integer); begin //empty end; { TfrmOptionsPluginsBase.ActualDeletePlugin } procedure TfrmOptionsPluginsBase.ActualDeletePlugin(iIndex: integer); begin //empty end; { TfrmOptionsPluginsBase.ActualPluginsMove } procedure TfrmOptionsPluginsBase.ActualPluginsMove(iSource, iDestination: integer); begin //empty end; { TfrmOptionsPluginsBase.GetIconIndex } class function TfrmOptionsPluginsBase.GetIconIndex: integer; begin Result := 6; end; { TfrmOptionsPluginsBase.IsSignatureComputedFromAllWindowComponents } function TfrmOptionsPluginsBase.IsSignatureComputedFromAllWindowComponents: boolean; begin Result := False; end; { TfrmOptionsPluginsBase.btnPluginsNotImplementedClick } procedure TfrmOptionsPluginsBase.btnPluginsNotImplementedClick(Sender: TObject); begin msgError(rsMsgNotImplemented); end; { TfrmOptionsPluginsBase.btnRemovePluginClick } procedure TfrmOptionsPluginsBase.btnRemovePluginClick(Sender: TObject); var iCurrentSelection: integer; begin iCurrentSelection := stgPlugins.Row; if iCurrentSelection < stgPlugins.FixedRows then Exit; self.ActualDeletePlugin(pred(iCurrentSelection)); stgPlugins.DeleteColRow(False, iCurrentSelection); if iCurrentSelection < stgPlugins.RowCount then stgPlugins.Row := iCurrentSelection else if stgPlugins.RowCount > 1 then stgPlugins.Row := pred(stgPlugins.RowCount) else stgPlugins.Row := -1; stgPluginsOnSelection(stgPlugins, 0, stgPlugins.Row); end; { TfrmOptionsPluginsBase. } procedure TfrmOptionsPluginsBase.btnTweakPluginClick(Sender: TObject); var iPluginIndex: integer; begin iPluginIndex := stgPlugins.Row - stgPlugins.FixedRows; if iPluginIndex < 0 then Exit; if ShowTweakPluginDlg(PluginType, iPluginIndex) then ShowPluginsTable; end; { TfrmOptionsPluginsBase.stgPluginsDblClick } procedure TfrmOptionsPluginsBase.stgPluginsDblClick(Sender: TObject); begin if btnTweakPlugin.Enabled then btnTweakPlugin.Click; end; { TfrmOptionsPluginsBase.stgPluginsDragOver } procedure TfrmOptionsPluginsBase.stgPluginsDragOver(Sender, Source: TObject; X, Y: integer; State: TDragState; var Accept: boolean); var iDestCol: integer = 0; iDestRow: integer = 0; begin stgPlugins.MouseToCell(X, Y, iDestCol, iDestRow); Accept := (iDestRow > 0); end; { TfrmOptionsPluginsBase.stgPluginsDragDrop } procedure TfrmOptionsPluginsBase.stgPluginsDragDrop(Sender, Source: TObject; X, Y: integer); var iDestCol, iDestRow, iSourceRow: integer; begin stgPlugins.MouseToCell(X, Y, {%H-}iDestCol, {%H-}iDestRow); if iDestRow > 0 then begin iSourceRow := stgPlugins.Row; //We need to that because after having done the following "MoveColRow", the "stgPlugins.Row" changed! So we need to remember original index. stgPlugins.MoveColRow(False, iSourceRow, iDestRow); ActualPluginsMove(pred(iSourceRow), pred(iDestRow)); end; end; { TfrmOptionsPluginsBase.stgPluginsGetCellHint } procedure TfrmOptionsPluginsBase.stgPluginsGetCellHint(Sender: TObject; ACol, ARow: integer; var HintText: string); var sMaybeHint: string; begin //The actual "pipe" symbol interfere when showing the hint. Let's replace it with a similar look-alike symbol. sMaybeHint := Stringreplace(stgPlugins.Cells[ACol, ARow], '|', '¦', [rfReplaceAll]); HintText := IfThen(((stgPlugins.Canvas.TextWidth(sMaybeHint) + 10) > stgPlugins.ColWidths[ACol]), sMaybeHint, ''); end; { TfrmOptionsPluginsWLX.stgPluginsShowHint } procedure TfrmOptionsPluginsBase.stgPluginsShowHint(Sender: TObject; HintInfo: PHintInfo); begin if gFileInfoToolTipValue[Ord(gToolTipHideTimeOut)] <> -1 then HintInfo^.HideTimeout := gFileInfoToolTipValue[Ord(gToolTipHideTimeOut)]; end; { GetPluginFilenameToSave } function TfrmOptionsPluginsBase.GetPluginFilenameToSave(const Filename: string): string; var sMaybeBasePath, SubWorkingPath, MaybeSubstitionPossible: string; begin Result := Filename; sMaybeBasePath := IfThen((gPluginFilenameStyle = pfsRelativeToDC), EnvVarCommanderPath, gPluginPathToBeRelativeTo); case gPluginFilenameStyle of pfsAbsolutePath: ; pfsRelativeToDC, pfsRelativeToFollowingPath: begin SubWorkingPath := IncludeTrailingPathDelimiter(mbExpandFileName(sMaybeBasePath)); MaybeSubstitionPossible := ExtractRelativePath(IncludeTrailingPathDelimiter(SubWorkingPath), Filename); if MaybeSubstitionPossible <> Filename then Result := IncludeTrailingPathDelimiter(sMaybeBasePath) + MaybeSubstitionPossible; end; end; end; end.
UNIT squeue; INTERFACE USES deftypes; PROCEDURE InitQueue(VAR q : Queue); PROCEDURE EnQueue(VAR tn : Tree; VAR q : Queue); PROCEDURE DeQueue(VAR q : Queue; VAR tn : Tree); FUNCTION IsQueueEmpty(VAR q : Queue) : Boolean; IMPLEMENTATION PROCEDURE InitQueue(VAR q : Queue); BEGIN WITH q DO BEGIN front := NIL; backend := NIL; size := 0 END END; FUNCTION IsQueueEmpty(VAR q : Queue) : Boolean; BEGIN IsQueueEmpty := (q.size = 0); END; PROCEDURE EnQueue(VAR tn : Tree; VAR q : Queue); VAR p, t : ElemPtr; BEGIN p := NIL; t := NIL; New(p); IF Assigned(p) THEN BEGIN p^.tr := tn; p^.next := NIL END ELSE BEGIN Writeln('Memory Allocation Failed! Halting...'); Halt() END; IF (q.front = NIL) AND (q.backend = NIL) THEN BEGIN q.front := p; q.backend := p; (* enter an empty queue *) END ELSE BEGIN t := q.backend; t^.next := p; q.backend := p; END; Inc(q.size); Writeln('after enter queue, new size: ', q.size) END; PROCEDURE DeQueue(VAR q : Queue; VAR tn : Tree); VAR p : ElemPtr; BEGIN IF (q.front = NIL) AND (q.backend = NIL) THEN tn := NIL ELSE BEGIN tn := (q.front)^.tr; IF q.size = 1 THEN BEGIN (* pop the only element from the queue *) q.front := NIL; q.backend := NIL END ELSE BEGIN p := (q.front)^.next; q.front := p END; Dec(q.size); Writeln('after depart queue, new size: ', q.size) END END; END.
{ Routines to add call arguments to the current call opcode. } module sst_r_syn_arg; define sst_r_syn_arg_syn; define sst_r_syn_arg_match; %include 'sst_r_syn.ins.pas'; { ******************************************************************************** * * Subroutine SST_R_SYN_ARG_SYN * * Add SYN (the SYN library use state) as the next call argument to the current * opcode. } procedure sst_r_syn_arg_syn; {add SYN as next call argument} val_param; begin sst_call_arg_var ( {add SYN argument} sst_opc_p^, {opcode to add call argument to} def_syn_p^.sym_p^.proc.first_arg_p^.sym_p^); {variable being passed} end; { ******************************************************************************** * * Subroutine SST_R_SYN_ARG_MATCH * * Add the local MATCH variable as the next call argument to the current * opcode. } procedure sst_r_syn_arg_match; {add MATCH as next call argument} val_param; begin sst_call_arg_var ( {add SYN argument} sst_opc_p^, {opcode to add call argument to} match_var_p^.mod1.top_sym_p^); {variable being passed} end;
unit Services.Cliente; interface uses System.SysUtils, System.Classes, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.ConsoleUI.Wait, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs, System.JSON, DataSet.Serialize, Vcl.Dialogs; type TServiceCliente = class(TDataModule) Connection: TFDConnection; qryCadastro: TFDQuery; qryPesquisa: TFDQuery; qryCadastroid: TFDAutoIncField; qryCadastronome: TStringField; qryCadastrosobrenome: TStringField; qryCadastroemail: TStringField; qryPesquisaid: TFDAutoIncField; qryPesquisanome: TStringField; qryPesquisasobrenome: TStringField; qryPesquisaemail: TStringField; private { Private declarations } public function ListAll: TFDQuery; function Append(const AJson: TJSONObject): Boolean; procedure Delete(AId: integer); function Update(const AJson: TJSONObject; AId: integer): Boolean; function GetById(const AId: string): TFDQuery; end; implementation {%CLASSGROUP 'System.Classes.TPersistent'} {$R *.dfm} { TServiceCliente } function TServiceCliente.Append(const AJson: TJSONObject): Boolean; begin qryCadastro.SQL.Add('where 1<>1'); qryCadastro.Open(); qryCadastro.LoadFromJSON(AJson, False); Result := qryCadastro.ApplyUpdates(0) = 0; end; procedure TServiceCliente.Delete(AId: integer); begin qryCadastro.SQL.Clear; qryCadastro.SQL.Add('DELETE FROM CLIENTES WHERE ID = :ID'); qryCadastro.ParamByName('ID').Value := AId; qryCadastro.ExecSQL; end; function TServiceCliente.ListAll: TFDQuery; begin qryPesquisa.Open(); Result := qryPesquisa; end; function TServiceCliente.Update(const AJson: TJSONObject; AId: integer): Boolean; begin qryCadastro.Close; qryCadastro.SQL.Add('where id = :id'); qryCadastro.ParamByName('ID').Value := AId; qryCadastro.Open(); qryCadastro.MergeFromJSONObject(AJson, False); Result := qryCadastro.ApplyUpdates(0) = 0; end; function TServiceCliente.GetById(const AId: string): TFDQuery; begin qryCadastro.SQL.Add('where id = :id'); qryCadastro.ParamByName('id').AsInteger := AId.ToInteger; qryCadastro.Open(); Result := qryCadastro; end; end.
{ behavior3delphi - a Behavior3 client library (Behavior Trees) for Delphi by Dennis D. Spreen <dennis@spreendigital.de> see Behavior3.pas header for full license information } unit Behavior3.NodeTypes; interface uses System.Generics.Collections, System.Generics.Defaults, Behavior3.Core.BaseNode; type TB3NodeTypes = class(TDictionary<String, TB3BaseNodeClass>) public procedure Add(const Value: TB3BaseNodeClass); overload; function CreateNode(const NodeName: String): TB3BaseNode; virtual; constructor Create(ACapacity: Integer = 0; WithDefaultTypes: Boolean = True); overload;virtual; end; var B3NodeTypes: TB3NodeTypes; implementation { TBehavior3NodeTypes } uses Behavior3, // add all node types Behavior3.Actions.Error, Behavior3.Actions.Failer, Behavior3.Actions.Runner, Behavior3.Actions.Succeeder, Behavior3.Actions.Wait, Behavior3.Composites.MemPriority, Behavior3.Composites.MemSequence, Behavior3.Composites.Priority, Behavior3.Composites.Sequence, Behavior3.Decorators.Inverter, Behavior3.Decorators.Limiter, Behavior3.Decorators.MaxTime, Behavior3.Decorators.Repeater, Behavior3.Decorators.RepeatUntilFailure, Behavior3.Decorators.RepeatUntilSuccess; procedure TB3NodeTypes.Add(const Value: TB3BaseNodeClass); var Instance: TB3BaseNode; begin // Create an instance to retrieve the name Instance := Value.Create; try Add(Instance.Name, Value); finally Instance.Free; end; end; constructor TB3NodeTypes.Create(ACapacity: Integer = 0; WithDefaultTypes: Boolean = True); begin // Set default capacity to 15 before adding the 15 default node types if (WithDefaultTypes) and (ACapacity < 15) then ACapacity := 15; inherited Create(ACapacity); if WithDefaultTypes then begin Add(TB3RepeatUntilSuccess); Add(TB3RepeatUntilFailure); Add(TB3Repeater); Add(TB3MaxTime); Add(TB3Limiter); Add(TB3Inverter); Add(TB3Sequence); Add(TB3Priority); Add(TB3MemSequence); Add(TB3MemPriority); Add(TB3Wait); Add(TB3Succeeder); Add(TB3Runner); Add(TB3Failer); Add(TB3Error); end; end; function TB3NodeTypes.CreateNode(const NodeName: String): TB3BaseNode; var NodeClass: TB3BaseNodeClass; begin if not TryGetValue(NodeName, NodeClass) then raise EB3NodeclassMissingException.CreateFmt('Invalid node class %s', [NodeName]); Result := NodeClass.Create; end; initialization B3NodeTypes := NIL; finalization if Assigned(B3NodeTypes) then B3NodeTypes.Free; end.
unit ChangePasswordForm; interface uses WinTypes, WinProcs, Classes, Graphics, Forms, Controls, StdCtrls, Buttons, ExtCtrls, LMDCustomButton, LMDButton, LMDCustomControl, LMDCustomPanel, LMDCustomBevelPanel, LMDBaseEdit, LMDCustomEdit, FFSMaskEdit, dcEdit, LMDCustomParentPanel, LMDBackPanel, FFSDataBackground, FFSTypes, AdvEdit,slabel; type TfrmChangePassword = class(TForm) Label1: TsLabel; edtOldPassword: TdcEdit; edtNewPassword1: TdcEdit; edtNewPassword2: TdcEdit; Label2: TsLabel; Label3: TsLabel; FFSDataBackground1: TFFSDataBackground; CancelBtn: TLMDButton; OKBtn: TLMDButton; procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); private { Private declarations } public Constructor Create(Owner: TComponent); Override; end; implementation {$R *.DFM} constructor TfrmChangePassword.Create(Owner: TComponent); begin inherited; Color := FFSColor[fcsDataBackground]; end; procedure TfrmChangePassword.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin canclose := edtNewPassword1.text = edtnewpassword2.text; if not canclose then MessageBox(Handle, 'The new passwords do not match.','Validation Error', mb_Ok); end; end.
// Nanocurrency EdDSA unit, Copyleft 2019 FL4RE - Daniel Mazur unit ED25519_Blake2b; interface uses System.SysUtils, Velthuis.BigIntegers, ClpBigInteger, HlpBlake2BConfig, HlpBlake2B, HlpHashFactory, ClpDigestUtilities, HlpIHash, misc, secp256k1; function nano_privToPub(sk: AnsiString): AnsiString; function nano_signature(m, sk, pk: AnsiString): AnsiString; implementation type EDPoint = array[0..3] of BigInteger; var Bpow: array[0..252] of EdPoint; function pymodulus(left, right: BigInteger): BigInteger; begin left := left mod right; while (left < 0) do left := left + right; result := left; //thx Piter end; function getB: BigInteger; begin Exit(256) end; function getQ: BigInteger; begin Exit((BigInteger.Pow(2, 255) - 19)) end; function getL: BigInteger; begin Exit(BIgInteger.Pow(2, 252) + BigInteger.Parse('27742317777372353535851937790883648493')); end; function H(m: AnsiString): AnsiString; var Blake2b: IHash; begin Blake2b := THashFactory.TCrypto.CreateBlake2B_512(); Blake2b.Initialize(); Blake2b.TransformBytes(hexatotbytes(m), 0, Length(m) div 2); Result := Blake2b.TransformFinal.ToString(); end; function pow2(x, p: BigInteger): BigInteger; begin while p > 0 do begin x := pymodulus(BigInteger.Multiply(x, x), getQ); p := p - 1; end; Exit(x); end; function inv(z: BigInteger): BigInteger; var z2, z9, z11, z2_5_0, z2_10_0, z2_20_0, z2_40_0, z2_50_0, z2_100_0, z2_200_0, z2_250_0: BigInteger; begin z2 := pymodulus(z * z, getQ); z9 := pymodulus(Pow2(z2, 2) * z, getQ); z11 := pymodulus(z9 * z2, getQ); z2_5_0 := pymodulus((z11 * z11), getQ) * pymodulus(z9, getQ); z2_10_0 := pymodulus(pow2(z2_5_0, 5) * z2_5_0, getQ); z2_20_0 := pymodulus(pow2(z2_10_0, 10) * z2_10_0, getQ); z2_40_0 := pymodulus(pow2(z2_20_0, 20) * z2_20_0, getQ); z2_50_0 := pymodulus(pow2(z2_40_0, 10) * z2_10_0, getQ); z2_100_0 := pymodulus(pow2(z2_50_0, 50) * z2_50_0, getQ); z2_200_0 := pymodulus(pow2(z2_100_0, 100) * z2_100_0, getQ); z2_250_0 := pymodulus(Pow2(z2_200_0, 50) * z2_50_0, getQ); Exit(pymodulus(pow2(z2_250_0, 5) * z11, getQ)); end; function getD: BigInteger; begin Exit(-121665 * inv(121666) mod getQ); end; function getI: BigInteger; begin Exit(BigInteger.ModPow(2, (getQ - 1) div 4, getQ)); end; function xrecover(y: BigInteger): BigInteger; var xx, x: BigInteger; begin xx := (y * y - 1) * inv(getD * y * y + 1); x := BigInteger.ModPow(xx, (getQ + 3) div 8, getQ); if (x * x - xx) mod getQ <> 0 then x := pymodulus((x * getI), getQ); if x mod 2 <> 0 then x := getQ - x; Exit(x); end; function By: BigInteger; begin Exit(4 * inv(5)); end; function Bx: BigInteger; begin Exit(xrecover(By)); end; function B: EdPoint; begin Result[0] := pymodulus(Bx, getQ); Result[1] := pymodulus(By, getQ); Result[2] := 1; Result[3] := pymodulus((Bx * By), getQ); end; function ident: EDPoint; begin result[0] := 0; Result[1] := 1; Result[2] := 1; Result[3] := 0; end; function edwards_add(P, Q: EDPoint): EDPoint; var x1, y1, z1, t1, x2, y2, z2, t2, a, b, c, dd, e, f, g, h, x3, y3, t3, z3: BigInteger; begin x1 := P[0]; y1 := P[1]; z1 := P[2]; t1 := P[3]; x2 := Q[0]; y2 := Q[1]; z2 := Q[2]; t2 := Q[3]; a := pymodulus((y1 - x1) * (y2 - x2), getQ); b := pymodulus((y1 + x1) * (y2 + x2), getQ); c := pymodulus(t1 * 2 * getD * t2, getQ); dd := pymodulus(z1 * 2 * z2, getQ); e := b - a; f := dd - c; g := dd + c; h := b + a; x3 := e * f; y3 := g * h; t3 := e * h; z3 := f * g; Result[0] := pymodulus(x3, getq); Result[1] := pymodulus(y3, getq); Result[2] := pymodulus(z3, getQ); Result[3] := pymodulus(t3, GetQ); end; function edwards_double(P: EDPoint): EDPoint; var x1, y1, z1, t1, a, b, c, e, g, f, h, x3, y3, t3, z3: BigInteger; begin x1 := P[0]; y1 := P[1]; z1 := P[2]; t1 := P[3]; a := pymodulus((x1 * x1), getq); b := pymodulus((y1 * y1), getq); c := pymodulus((2 * z1 * z1), getQ); e := pymodulus((((x1 + y1) * (x1 + y1)) - a - b), getQ); g := (0 - a + b); f := (g - c); h := (0 - a - b); x3 := (e * f); // y3 := (g * h); t3 := (e * h); z3 := (f * g); // Result[0] := pymodulus(x3, getQ); Result[1] := pymodulus(y3, getQ); Result[2] := pymodulus(z3, getQ); Result[3] := pymodulus(t3, getQ); end; function scalarmult(P: EDPoint; e: Integer): EDPoint; var Q: EDPoint; begin if e = 0 then Exit(ident); Q := scalarmult(P, e div 2); Q := edwards_double(Q); if e and 1 = 1 then Q := edwards_add(Q, P); result := Q; end; procedure make_Bpow; var P: EDPoint; i: integer; begin P := b; for i := 0 to 252 do begin Bpow[i] := P; P := edwards_double(P); end; end; function scalarmult_B(e: BigInteger): EdPoint; var P: EDPoint; i: Integer; begin e := e mod getL; P := ident; for i := 0 to 252 do begin if e and 1 = 1 then P := edwards_add(P, Bpow[i]); e := e div 2; end; result := P; end; function encodeint(y: BigInteger): AnsiString; var i: integer; bitString: string; sum, j: integer; bb: system.UInt8; begin result := ''; bitString := ''; for i := 0 to 255 do if (y shr i) and 1 = 1 then bitString := bitString + '1' else bitString := bitString + '0'; for i := 0 to 31 do begin sum := 0; for j := 0 to 7 do begin bb := StrToIntdef(bitString[{$IF DEFINED(MSWINDOWS) OR DEFINED(LINUX)}1 + {$ENDIF}(i * 8 + j)],0); sum := sum + system.uint8(bb shl j) end; result := result + inttohex(sum, 2); end; bitString := ''; end; function encodepoint(P: EDPoint): AnsiString; var zi, x, y, z, t: BigInteger; bi: BigInteger; bitString: string; i, j: integer; sum: integer; bb: system.uint8; begin result := ''; x := P[0]; y := P[1]; z := P[2]; t := P[3]; zi := inv(z); x := pymodulus((x * zi), getQ); y := pymodulus((y * zi), getQ); bitString := ''; for i := 0 to 254 do if (y shr i) and 1 = 1 then bitString := bitString + '1' else bitString := bitString + '0'; if x and 1 = 1 then bitString := bitString + '1' else bitString := bitString + '0'; for i := 0 to 31 do begin sum := 0; for j := 0 to 7 do begin bb := StrToIntdef(bitString[{$IF DEFINED(MSWINDOWS) OR DEFINED(LINUX)}1 + {$ENDIF}(i * 8 + j)],0); sum := sum + system.uint8(bb shl j) end; result := result + inttohex(sum, 2); end; bitString := ''; end; function bit(h: TBytes; i: Integer): integer; begin Result := (h[i div 8] shr (i mod 8)) and 1; end; function nano_privToPub(sk: AnsiString): AnsiString; var a: BigInteger; sum: BigInteger; i: integer; tb: Integer; AP: EDPoint; bextsk: tArray<Byte>; s: ansistring; begin bextsk := hexatotbytes(h(sk)); {bextsk[0]:=bextsk[0] and 248; bextsk[31]:=bextsk[31] and 127; bextsk[31]:=bextsk[31] OR 64; } for i := 3 to 253 do begin if bit(bextsk, i) = 1 then tb := 1 else tb := 0; sum := sum + (BigInteger.Pow(2, i) * tb); end; a := BigInteger.Pow(2, 254) + sum; AP := scalarmult_B(a); result := encodepoint(AP); end; function Hint(m: ansistring): ansistring; var hh: tbytes; sum: BigInteger; i, tb: integer; begin hh := hexatotbytes(h(m)); for i := 0 to 511 do begin if bit((hh), i) = 1 then tb := 1 else tb := 0; sum := sum + (BigInteger.Pow(2, i) * tb); end; result := sum.tostring(16); end; function nano_signature(m, sk, pk: AnsiString): AnsiString; var hh: tbytes; rh, r: AnsiString; i: integer; a: BigInteger; sum, SS: BigInteger; RR: EDPoint; tb: integer; begin hh := hexatotbytes(h(sk)); for i := 3 to 253 do begin if bit((hh), i) = 1 then tb := 1 else tb := 0; sum := sum + (BigInteger.Pow(2, i) * tb); end; a := BigInteger.Pow(2, 254) + sum; rh := ''; for i := 32 to 63 do rh := rh + IntToHex(hh[i], 2); r := Hint(rh + m); RR := scalarmult_b(BigInteger.Parse('+0x00' + r)); SS := pymodulus(BigInteger.Parse('+0x00' + r) + BigInteger.Parse('+0x00' + Hint(encodepoint(RR) + pk + m)) * a, getL); result := encodepoint(RR) + encodeint(SS); end; initialization BigInteger.Decimal; BigInteger.AvoidPartialFlagsStall(True); make_Bpow(); end.
unit ssGroupBox; interface uses SysUtils, Classes, Controls, cxControls, cxGroupBox, Graphics, cxGraphics, Messages, ssBevel; const clXPHotTrack = $206B2408; type TxMouseMoveEvent = procedure(Sender: TObject) of object; TssGroupBox = class(TcxGroupBox) private FCaptionBkPicture: TPicture; FHotTrack: Boolean; FHotTrackColor: TColor; FOver: Boolean; FOnMouseLeave: TxMouseMoveEvent; FOnMouseEnter: TxMouseMoveEvent; FHideCaption: Boolean; FEdges: TssBevelEdges; procedure SetCaptionBkPicture(const Value: TPicture); procedure SetHotTrack(const Value: Boolean); procedure SetHotTrackColor(const Value: TColor); procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER; procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; procedure SetHideCaption(const Value: Boolean); procedure SetEdges(const Value: TssBevelEdges); protected procedure Paint; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property CaptionBkPicture: TPicture read FCaptionBkPicture write SetCaptionBkPicture; property Edges: TssBevelEdges read FEdges write SetEdges; property HideCaption: Boolean read FHideCaption write SetHideCaption default False; property HotTrack: Boolean read FHotTrack write SetHotTrack default True; property HotTrackColor: TColor read FHotTrackColor write SetHotTrackColor default clXPHotTrack; property OnMouseEnter: TxMouseMoveEvent read FOnMouseEnter write FOnMouseEnter; property OnMouseLeave: TxMouseMoveEvent read FOnMouseLeave write FOnMouseLeave; end; implementation uses Windows, Types, dxThemeConsts, dxThemeManager, dxUxTheme, cxEditUtils, cxContainer, cxEditPaintUtils, cxLookAndFeels, ssBaseConst; { TssGroupBox } procedure TssGroupBox.CMMouseEnter(var Message: TMessage); var FControl: TControl; begin if not FHotTrack then Exit; FControl := Self.Parent.ControlAtPos(Self.Parent.ScreenToClient(Mouse.CursorPos), False, True); if (FControl = Self) and not FOver then begin FOver := True; Invalidate; if Assigned(FOnMouseEnter) then FOnMouseEnter(Self); // PostMessage(ph, WM_USER + 1, 0,0); end; end; procedure TssGroupBox.CMMouseLeave(var Message: TMessage); var FControl: TControl; begin if not FHotTrack then Exit; FControl := Self.Parent.ControlAtPos(Self.Parent.ScreenToClient(Mouse.CursorPos), False, True); if FControl <> Self then begin FOver := False; Invalidate; if Assigned(FOnMouseLeave) then FOnMouseLeave(Self); // PostMessage(ph, WM_USER + 1, 1,0); end; end; constructor TssGroupBox.Create(AOwner: TComponent); begin inherited; FCaptionBkPicture := TPicture.Create; FEdges := [beLeft, beRight, beTop, beBottom]; FHotTrack := True; FHotTrackColor := clXPHotTrack; end; destructor TssGroupBox.Destroy; begin FCaptionBkPicture.Free; inherited; end; procedure TssGroupBox.Paint; procedure BevelLine(C: TColor; X1, Y1, X2, Y2: Integer); begin with Canvas do begin Pen.Color := C; MoveTo(X1, Y1); LineTo(X2, Y2); end; end; var H, W, D, tX, tY: Integer; ATextRect, ABodyRect, AControlRect, AHeaderRect: TRect; Ft : hFont; TTM : TTextMetric; TLF : TLogFont; ACaptionSize: TSize; ANativeState: Integer; ATheme: TTheme; ARgn: TcxRegion; AColor{, OldColor}: Cardinal; begin inherited Paint; with Canvas do begin // Initial settings Brush.Color := Self.Color; Font := Self.Font; tX := 0; tY := 0; // Adjustments H := TextHeight('0'); W := TextWidth(Text); if Alignment in [alLeftTop, alLeftCenter, alLeftBottom, alRightTop, alRightCenter, alRightBottom] then begin GetTextMetrics(Handle, TTM); if (TTM.tmPitchAndFamily and TMPF_TRUETYPE) = 0 then begin Font.Name := 'Arial'; H := TextHeight('Wg'); W := TextWidth(Text); end; end; D := H div 2 - 1; // ABodeRect calculations ABodyRect := ClientRect; case Alignment of alTopLeft, alTopCenter, alTopRight: ABodyRect.Top := ABodyRect.Top + D; alLeftTop, alLeftCenter, alLeftBottom: ABodyRect.Left := ABodyRect.Left + D; alRightTop, alRightCenter, alRightBottom: ABodyRect.Right := ABodyRect.Right - D; alBottomLeft, alBottomCenter, alBottomRight: ABodyRect. Bottom := ABodyRect.Bottom - D; end; // ATextRect calculations if Text <> '' then begin case Alignment of alTopLeft: begin ATextRect := Rect(8, 1, 8 + W, H); tX := 8; tY := 0; end; alTopCenter: begin ATextRect := Rect((Width - W) div 2, 1, (Width - W) div 2 + W, H); tX := (Width - W) div 2; tY := 0; end; alTopRight: begin ATextRect := Rect(Width - W - 8, 1, Width - 8, H); tX := Width - W - 8; tY := 0; end; alBottomLeft: begin ATextRect := Rect(8, Height - H, 8 + W, Height); tX := 8; tY := Height - H; end; alBottomCenter: begin ATextRect := Rect((Width - W) div 2, Height - H, (Width - W) div 2 + W, Height); tX := (Width - W) div 2; tY := Height - H; end; alBottomRight: begin ATextRect := Rect(Width - W - 8, Height - H, Width - 8, Height); tX := Width - W - 8; tY := Height - H; end; alLeftTop: begin ATextRect := Rect(0, 8, H, 8 + W); tX := 0; tY := 8 + W; end; alLeftCenter: begin ATextRect := Rect(0, (Height - W) div 2, H, (Height - W) div 2 + W); tX := 0; tY := (Height - W) div 2 + W; end; alLeftBottom: begin ATextRect := Rect(0, Height - W - 8, H, Height - 8); tX := 0; tY := Height - 8; end; alRightTop: begin ATextRect := Rect(Width - H, 8, Width, 8 + W); tX := Width; tY := 8; end; alRightCenter: begin ATextRect := Rect(Width - H, (Height - W) div 2, Width, (Height - W) div 2 + W); tX := Width; tY := (Height - W) div 2; end; alRightBottom: begin ATextRect := Rect(Width - H, Height - W - 8, Width, Height - 8); tX := Width; tY := Height - 8 -W; end; alCenterCenter: begin ATextRect := Rect((Width - W) div 2, (Height - H) div 2, (Width - W) div 2 + W, (Height - H) div 2 + H); tX := (Width - W) div 2; tY := (Height - H) div 2; end; else begin ATextRect := Rect (8, 0, 8 + W, H); tX := 0; tY := 0; end; end; if Alignment in [alLeftTop, alLeftCenter, alLeftBottom] then begin GetTextMetrics(Handle, TTM); if (TTM.tmPitchAndFamily and TMPF_TRUETYPE) = 0 then Font.Name := 'Arial'; GetObject(Font.Handle, SizeOf(TLF), @TLF); TLF.lfEscapement := 900; Ft := CreateFontIndirect(TLF); Font.Handle := Ft; end; if Alignment in [alRightTop, alRightCenter, alRightBottom] then begin GetTextMetrics(Handle, TTM); if (TTM.tmPitchAndFamily and TMPF_TRUETYPE) = 0 then Font.Name := 'Arial'; GetObject(Font.Handle, SizeOf(TLF), @TLF); TLF.lfEscapement := 2700; Ft := CreateFontIndirect(TLF); Font.Handle := Ft; end; end; if AreVisualStylesMustBeUsed(LookAndFeel.NativeStyle, totButton) then begin if Caption = '' then FillChar(ATextRect, SizeOf(ATextRect), 0) else begin GetTextExtentPoint32(Handle, PChar(Caption), Length(Caption), ACaptionSize); ARgn := GetClipRegion; AControlRect := GetControlRect(Self); ExcludeClipRect(ATextRect); ATheme := OpenTheme(totButton); if Enabled then ANativeState := GBS_NORMAL else ANativeState := GBS_DISABLED; if IsThemeBackgroundPartiallyTransparent(ATheme, BP_GROUPBOX, ANativeState) then DrawThemeParentBackground(Handle, Canvas.Handle, @AControlRect) else cxEditFillRect(Canvas.Handle, AControlRect, GetSolidBrush(Canvas, Self.Color)); DrawThemeBackground(ATheme, Canvas.Handle, BP_GROUPBOX, ANativeState, @ABodyRect); SetClipRegion(ARgn, roSet); Brush.Style := bsSolid; GetThemeColor(ATheme, BP_GROUPBOX, ANativeState, TMT_TEXTCOLOR, AColor); Font.Color := AColor; end; end else begin // Not native drawing FillRect(ClientRect); case LookAndFeel.Kind of lfUltraFlat: begin Brush.Color := Self.Color; if FHideCaption then ABodyRect := ClientRect else InflateRect(ABodyRect, -1, -1); if FOver and FHotTrack then Brush.Color := FHotTrackColor else Brush.Color := clBtnShadow; if beLeft in FEdges then BevelLine(Brush.Color, ABodyRect.Left, ABodyRect.Top, ABodyRect.Left, ABodyRect.Bottom); if beRight in FEdges then BevelLine(Brush.Color, ABodyRect.Right - 1, ABodyRect.Top, ABodyRect.Right - 1, ABodyRect.Bottom); if beTop in FEdges then BevelLine(Brush.Color, ABodyRect.Left, ABodyRect.Top, ABodyRect.Right, ABodyRect.Top); if beBottom in FEdges then BevelLine(Brush.Color, ABodyRect.Left, ABodyRect.Bottom - 1, ABodyRect.Right, ABodyRect.Bottom - 1); // FrameRect(ABodyRect); end; lfFlat: begin Brush.Color := clBtnHighLight; FrameRect(ABodyRect); InflateRect(ABodyRect, -1, -1); Brush.Color := clBtnShadow; FrameRect(ABodyRect); end; lfStandard: begin Brush.Color := clBtnHighlight; FrameRect(ABodyRect); OffsetRect(ABodyRect, -1, -1); Brush.Color := clBtnShadow; FrameRect(ABodyRect); end; end; Brush.Color := Self.Color; if not FHideCaption then FillRect(ATextRect); Brush.Color := CaptionBkColor; end; if FHideCaption then Exit; SetBkMode(Handle, TRANSPARENT); if Alignment in [alLeftTop, alLeftCenter, alLeftBottom, alRightTop, alRightCenter, alRightBottom] then ExtTextOut(Handle, tX, tY, ETO_CLIPPED, @ATextRect, PChar(Text), Length(Text), nil) else begin if ATextRect.Top>=2 then AHeaderRect.Top:=ATextRect.Top-2 else AHeaderRect.Top:=0; if ATextRect.Bottom<Self.Height-3 then AHeaderRect.Bottom:=ATextRect.Bottom+3 else AHeaderRect.Bottom:=Self.Height; AHeaderRect.Left:=ATextRect.Left; AHeaderRect.Right:=Self.Width-ATextRect.Left; if (FCaptionBkPicture<>nil) and (FCaptionBkPicture.Width>0) then begin Canvas.StretchDraw(AHeaderRect, FCaptionBkPicture.Bitmap); Canvas.Brush.Color := clBtnShadow; Canvas.FrameRect(AHeaderRect); end; SetBkMode(Handle, TRANSPARENT); DrawText(Text, ATextRect, cxShowPrefix or cxSingleLine); end; end; end; procedure TssGroupBox.SetCaptionBkPicture(const Value: TPicture); begin FCaptionBkPicture.Assign(Value); Repaint; end; procedure TssGroupBox.SetEdges(const Value: TssBevelEdges); begin FEdges := Value; Invalidate; end; procedure TssGroupBox.SetHideCaption(const Value: Boolean); begin FHideCaption := Value; Invalidate; end; procedure TssGroupBox.SetHotTrack(const Value: Boolean); begin FHotTrack := Value; Invalidate; end; procedure TssGroupBox.SetHotTrackColor(const Value: TColor); begin FHotTrackColor := Value; end; end.
{*********************************************************************** * Unit Name: GX_eSampleEditorExpert * Purpose : To show one way of coding an Editor Expert. * This expert puts up a modal window and does nothing else * Author : Scott Mattes <smattes@erols.com> ***********************************************************************} unit GX_eSampleEditorExpert; {$I GX_CondDefine.inc} interface uses SysUtils, Classes, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ComCtrls, GX_Experts, GX_EditorExpert, GX_ConfigurationInfo, GX_BaseForm; type ///<summary> /// Use this sample editor expert as a starting point for your own expert. /// Do not forget to rename the unit and the class(es). /// Many of the methods are optional and you can omit them if the default /// behaviour is suitable for your expert. </summary> TGxSampleEditorExpert = class(TEditorExpert) private FData: string; public // optional, defaults to ClassName class function GetName: string; override; constructor Create; override; // optional, defauls to true function CanHaveShortCut: boolean; override; // optional if HasConfigOptions returns false procedure Configure; override; procedure Execute(Sender: TObject); override; // optional, defaults to GetName which in turn defaults to the class name function GetBitmapFileName: string; override; // optional, defaults to no shortcut function GetDefaultShortCut: TShortCut; override; function GetDisplayName: string; override; // optional, but recommended function GetHelpString: string; override; // optional, default to true function HasConfigOptions: Boolean; override; // Overrride to load any configuration settings procedure InternalLoadSettings(Settings: TExpertSettings); override; // Overrride to save any configuration settings procedure InternalSaveSettings(Settings: TExpertSettings); override; end; type TfmSampleEditorExpertConfig = class(TfmBaseForm) btnCancel: TButton; btnOK: TButton; lblData: TLabel; edtData: TEdit; lblNote: TLabel; end; implementation {$R *.dfm} uses {$IFOPT D+} GX_DbugIntf, {$ENDIF} Menus, Registry, ToolsAPI, GX_GenericUtils, GX_GExperts; { TGxSampleEditorExpert } //********************************************************* // Name: TGxSampleEditorExpert.CanHaveShortCut // Purpose: Determines whether this expert can have a // hotkey assigned to it // Note: If it returns false, no hotkey configuration // control is shown in the configuratoin dialog. // If your expert can have a hotkey, you can // simply delete this function, since the // inherited funtion already returns true. //********************************************************* function TGxSampleEditorExpert.CanHaveShortCut: boolean; begin Result := True; end; //********************************************************* // Name: TGxSampleEditorExpert.Configure // Purpose: Shows the config form and if the user selects // OK then the settings are saved // Note: If you have no config items, delete this method // (and its declaration from the interface section) // and the declaration of the form in the interface // section, and remove the and set FHasConfigOptions // to False in the Create method //********************************************************* procedure TGxSampleEditorExpert.Configure; begin with TfmSampleEditorExpertConfig.Create(nil) do try edtData.Text := FData; if ShowModal = mrOk then begin FData := edtData.Text; SaveSettings; end; finally Free; end; end; //********************************************************* // Name: TGxSampleEditorExpert.Create // Purpose: Sets up basic information about your editor expert //********************************************************* constructor TGxSampleEditorExpert.Create; begin inherited Create; // Set default values for any data FData := 'editor data'; // LoadSettings is called automatically for the expert upon creation. end; //********************************************************* // Name: TGxSampleEditorExpert.Execute // Purpose: Called when your hot-key is pressed, this is // where you code what the expert should do //********************************************************* procedure TGxSampleEditorExpert.Execute(Sender: TObject); resourcestring SNotice = 'This is where your editor expert would do something useful.'; begin ShowMessage(SNotice); end; //********************************************************* // Name: TGxSampleEditorExpert.GetBitmapFileName // Purpose: Return the file name of an icon associated with // the expert. Do not specify a path. // Defaults to the expert's class name. // Note: This bitmap must be included in the // GXIcons.rc file which in turn can be created // from all .bmp files located in the Images // directory by calling the _CreateGXIconsRc.bat // script located in that directory. // It is possible to return an empty string. This // signals that no icon file is available. // You can remove this function from your expert // and simply provide the bitmap as // <TYourExpert>.bmp //********************************************************* function TGxSampleEditorExpert.GetBitmapFileName: string; begin Result := inherited GetBitmapFileName; end; //********************************************************* // Name: TGxSampleEditorExpert.GetDefaultShortCut // Purpose: The default shortcut to call your expert. // Notes: It is perfectly fine not to assign a default // shortcut and let the expert be called via // the menu only. The user can always assign // a shortcut to it in the configuration dialog. // Available shortcuts have become a very rare // resource in the Delphi IDE. // The value of ShortCut is touchy, use the ShortCut // button on the Editor Experts tab of menu item // GExperts/GExperts Configuration... on an existing // editor expert to see if you can use a specific // combination for your expert. //********************************************************* function TGxSampleEditorExpert.GetDefaultShortCut: TShortCut; begin Result := Menus.ShortCut(Ord('?'), [ssCtrl, ssAlt]); end; //********************************************************* // Name: TGxSampleEditorExpert.DisplayName // Purpose: The expert name that appears in Editor Experts box on the // Editor tab of menu item GExperts/GExperts Configuration... // Experts tab on menu item GExperts/GExperts Configuration... //********************************************************* function TGxSampleEditorExpert.GetDisplayName: string; resourcestring SDisplayName = 'Sample Editor Expert'; begin Result := SDisplayName; end; //********************************************************* // Name: TGxSampleEditorExpert.GetHelpString // Purpose: To provide your text on what this editor expert // does to the expert description hint that is shown // when the user puts the mouse over the expert's icon // in the configuration dialog. //********************************************************* function TGxSampleEditorExpert.GetHelpString: string; resourcestring SSampleEditorExpertHelp = 'This is the text that will appear in the explanation hint on the ' + 'Editor tab of menu item GExperts/GExperts Configuration...' + sLineBreak + sLineBreak + 'You can allow the text to wrap automatically, or you can force your ' + 'own line breaks, or both.'; begin Result := SSampleEditorExpertHelp; end; //********************************************************* // Name: TGxSampleEditorExpert.GetName // Purpose: Each editor expert needs to provide a name // that represents this editor expert. // Note: This string will be used to construct an action // name and therefore must be a valid identifier. // The inherited implementation returns the // expert's class name. This is usually fine // as long as it is unique within GExperts. // Feel free to omit this method from your expert. //********************************************************* class function TGxSampleEditorExpert.GetName: string; const SName = 'SampleEditorExpert'; begin Result := SName; end; //********************************************************* // Name: TGxSampleEditorExpert.HasConfigOptions // Purpose: Let the world know whether this expert has // configuration options. //********************************************************* function TGxSampleEditorExpert.HasConfigOptions: Boolean; begin Result := True; end; procedure TGxSampleEditorExpert.InternalLoadSettings(Settings: TExpertSettings); begin inherited InternalLoadSettings(Settings); FData := Settings.ReadString('TestData', FData); end; procedure TGxSampleEditorExpert.InternalSaveSettings(Settings: TExpertSettings); begin inherited InternalSaveSettings(Settings); Settings.WriteString('TestData', FData); end; //******************************************************************* // Purpose: Tells GExperts about the existance of this editor expert //******************************************************************* initialization RegisterEditorExpert(TGxSampleEditorExpert); end.
{ \file DGLE_CoreRenderer.pas \author Korotkov Andrey aka DRON \version 2:0.3.1 \date 17.11.2014 (c)Korotkov Andrey \brief This header provides interface of low-level DGLE rendering API. This header is a part of DGLE_SDK. } unit DGLE_CoreRenderer; interface {$I include.inc} {$IFNDEF DGLE_CRENDERER} {$DEFINE DGLE_CRENDERER} {$ENDIF} uses DGLE_Types, DGLE_Base; type E_CORE_RENDERER_TYPE = ( CRT_UNKNOWN = 0, CRT_OPENGL_LEGACY = 1 { For future needs CRT_OPENGL_4_1 = 2, CRT_OPENGL_ES_1_1 = 3, CRT_OPENGL_ES_2_0 = 4, CRT_DIRECT_3D_9_0c = 5, CRT_DIRECT_3D_11 = 6 } ); E_CORE_RENDERER_FEATURE_TYPE = ( CRFT_BUILTIN_FULLSCREEN_MODE = 0, CRFT_BUILTIN_STATE_FILTER = 1, CRFT_MULTISAMPLING = 2, CRFT_VSYNC = 3, CRFT_PROGRAMMABLE_PIPELINE = 4, CRFT_LEGACY_FIXED_FUNCTION_PIPELINE_API = 5, CRFT_BGRA_DATA_FORMAT = 6, CRFT_TEXTURE_COMPRESSION = 7, CRFT_NON_POWER_OF_TWO_TEXTURES = 8, CRFT_DEPTH_TEXTURES = 9, CRFT_TEXTURE_ANISOTROPY = 10, CRFT_TEXTURE_MIPMAP_GENERATION = 11, CRFT_TEXTURE_MIRRORED_REPEAT = 12, CRFT_TEXTURE_MIRROR_CLAMP = 13, CRFT_GEOMETRY_BUFFER = 14, CRFT_FRAME_BUFFER = 15 ); E_MATRIX_TYPE = ( MT_PROJECTION = 0, MT_MODELVIEW = 1, MT_TEXTURE = 2 ); E_TEXTURE_TYPE = ( TT_2D = 0, TT_3D = 1 ); E_CORE_RENDERER_METRIC_TYPE = ( CRMT_MAX_TEXTURE_RESOLUTION = 0, CRMT_MAX_TEXTURE_LAYERS = 1, CRMT_MAX_ANISOTROPY_LEVEL = 2 ); E_COMPARISON_FUNC = ( CF_NEVER = 0, CF_LESS = 1, CF_EQUAL = 2, CF_LESS_EQUAL = 3, CF_GREATER = 4, CF_NOT_EQUAL = 5, CF_GREATER_EQUAL = 6, CF_ALWAYS = 7 ); E_POLYGON_CULL_MODE = ( PCM_NONE = 0, PCM_FRONT = 1, PCM_BACK = 2 ); { For future needs E_STENCIL_OPERATION = ( SO_KEEP = 0, SO_ZERO = 1, SO_REPLACE = 2, SO_INVERT = 3, SO_INCR = 4, SO_DECR = 5, ); E_BLEND_OPERATION = ( BO_ADD = 0, BO_SUBTRACT = 1, BO_REV_SUBTRACT = 2, BO_MIN = 3, BO_MAX = 4 ); } E_BLEND_FACTOR = ( BF_ZERO = 0, BF_ONE = 1, BF_SRC_COLOR = 2, BF_SRC_ALPHA = 3, BF_DST_COLOR = 4, BF_DST_ALPHA = 5, BF_ONE_MINUS_SRC_COLOR = 6, BF_ONE_MINUS_SRC_ALPHA = 7 { For future needs BF_ONE_MINUS_DST_COLOR = 8, BF_ONE_MINUS_DST_ALPHA = 9, BF_SRC_ALPHA_SATURATE? = 10, BF_SRC1_COLOR = 11, BF_ONE_MINUS_SRC1_COLOR = 12, BF_SRC1_ALPHA = 13, BF_ONE_MINUS_SRC1_ALPHA = 14 } ); E_CORE_RENDERER_DATA_ALIGNMENT = ( CRDA_ALIGNED_BY_4 = 0, CRDA_ALIGNED_BY_1 = 1 ); E_CORE_RENDERER_BUFFER_TYPE = ( CRBT_SOFTWARE = 0, CRBT_HARDWARE_STATIC = 1, CRBT_HARDWARE_DYNAMIC = 2 ); E_CORE_RENDERER_DRAW_MODE = ( CRDM_POINTS = 0, CRDM_LINES = 1, CRDM_TRIANGLES = 2, CRDM_LINE_STRIP = 3, CRDM_TRIANGLE_STRIP = 4, CRDM_TRIANGLE_FAN = 5 ); E_ATTRIBUTE_DATA_TYPE = ( ADT_FLOAT = 0, ADT_BYTE = 1, ADT_UBYTE = 2, ADT_SHORT = 3, ADT_USHORT = 4, ADT_INT = 5, ADT_UINT = 6 ); E_ATTRIBUTE_COMPONENTS_COUNT = ( ACC_ONE = 0, ACC_TWO = 1, ACC_THREE = 2, ACC_FOUR = 3 ); type TBlendStateDesc = packed record bEnabled: Boolean; eSrcFactor: E_BLEND_FACTOR; eDstFactor: E_BLEND_FACTOR; { For future needs eOperation: E_BLEND_OPERATION; bSeparate: Boolean; eSrcAlpha: E_BLEND_FACTOR; eDstAlpha: E_BLEND_FACTOR; eOpAlpha : E_BLEND_OPERATION; } {$IFDEF DGLE_PASCAL_RECORDCONSTRUCTORS} constructor Create(Dummy: Byte); {$ENDIF} end; { For future needs TStencilFaceDesc = Record eStencilFailOp: E_STENCIL_OPERATION; eStencilDepthFailOp: E_STENCIL_OPERATION; eStencilPassOp: E_STENCIL_OPERATION; eStencilFunc: E_COMPARISON_FUNC; end; } TDepthStencilDesc = packed record bDepthTestEnabled: Boolean; bWriteToDepthBuffer: Boolean; eDepthFunc: E_COMPARISON_FUNC; { For future needs bStencilEnabled: Boolean; ui8StencilReadMask: Byte; ui8StencilWriteMask: Byte; stFrontFace: TStencilFaceDesc stBackFace: TStencilFaceDesc; } {$IFDEF DGLE_PASCAL_RECORDCONSTRUCTORS} constructor Create(Dummy: Byte); {$ENDIF} end; TRasterizerStateDesc = packed record bWireframe: Boolean; eCullMode: E_POLYGON_CULL_MODE; bFrontCounterClockwise: Boolean; bScissorEnabled: Boolean; bAlphaTestEnabled: Boolean; eAlphaTestFunc: E_COMPARISON_FUNC; fAlphaTestRefValue: Single; { For future needs iDepthBias: Integer; fDepthBiasClamp: Single; fSlopeScaledDepthBias: Single; bDepthClipEnabled: Boolean; } {$IFDEF DGLE_PASCAL_RECORDCONSTRUCTORS} constructor Create(Dummy: Byte); {$ENDIF} end; TDrawDataAttributes = packed record uiAttribOffset: array[0..7] of Cardinal; uiAttribStride: array[0..7] of Cardinal; eAttribDataType: array[0..7] of E_ATTRIBUTE_DATA_TYPE; eAttribCompsCount: array[0..7] of E_ATTRIBUTE_COMPONENTS_COUNT; {$IFDEF DGLE_PASCAL_RECORDCONSTRUCTORS} constructor Create(Dummy: Byte); {$ENDIF} end; PDrawDataAttributes = ^TDrawDataAttributes; TDrawDataDesc = packed record pData: Pointer; //Must be start of the vertex data. 2 or 3 floats uiVertexStride: Cardinal; bVertices2D: Boolean; uiNormalOffset : Cardinal; //3 floats uiNormalStride : Cardinal; uiTextureVertexOffset: Cardinal; //2 floats uiTextureVertexStride: Cardinal; uiColorOffset: Cardinal; //4 floats uiColorStride: Cardinal; {not implemeted} uiTangentOffset, uiBinormalOffset: Cardinal; //6 floats, 3 for tangent and 3 for binormal {not implemeted} uiTangentStride, uiBinormalStride: Cardinal; {not implemeted} pAttribs: PDrawDataAttributes; pIndexBuffer: Pointer; //May point to separate memory. uint16 or uint32 data pointer. bIndexBuffer32: Boolean; {$IFDEF DGLE_PASCAL_RECORDCONSTRUCTORS} constructor Create(Dummy: Byte); overload; constructor Create(pDataPointer: Pointer; uiNormalDataOffset: Cardinal; uiTextureVertexDataOffset: Cardinal; bIs2d: Boolean); overload; {$ENDIF} {$IFDEF DGLE_PASCAL_RECORDOPERATORS} class operator {$IFDEF FPC} = {$ELSE} Equal {$ENDIF}(const this, desc: TDrawDataDesc): Boolean; inline; {$ENDIF} end; PDrawDataDesc = ^TDrawDataDesc; IBaseRenderObjectContainer = interface(IDGLE_Base) ['{5C5C5973-D826-42ED-B641-A84DDDAAE2A3}'] function GetObjectType(out eType: E_ENGINE_OBJECT_TYPE): DGLE_RESULT; stdcall; end; IOpenGLTextureContainer = interface(IBaseRenderObjectContainer) ['{7264D8D2-C3AF-4ED3-91D1-90E02BE6A4EE}'] function GetTexture(out texture: GLuint): DGLE_RESULT; stdcall; end; IOpenGLBufferContainer = interface(IBaseRenderObjectContainer) ['{152B744F-7C1B-414F-BEC1-CD40A308E5DF}'] function GetVertexBufferObject(out vbo: GLuint): DGLE_RESULT; stdcall; function GetIndexBufferObject(out vbo: GLuint): DGLE_RESULT; stdcall; end; ICoreTexture = interface(IDGLE_Base) ['{8BFF07F9-2A8E-41D0-8505-3128C1B8160A}'] function GetSize(out width, height: Cardinal): DGLE_RESULT; stdcall; function GetDepth(out depth: Cardinal): DGLE_RESULT; stdcall; function GetType(out eType: E_TEXTURE_TYPE): DGLE_RESULT; stdcall; function GetFormat(out eFormat: E_TEXTURE_DATA_FORMAT): DGLE_RESULT; stdcall; function GetLoadFlags(out eLoadFlags: {E_TEXTURE_LOAD_FLAGS} cARDINAL): DGLE_RESULT; stdcall; function GetPixelData(pData: Pointer; out uiDataSize: Cardinal; uiLodLevel: Cardinal = 0): DGLE_RESULT; stdcall; function SetPixelData(const pData: Pointer; uiDataSize: Cardinal; uiLodLevel: Cardinal = 0): DGLE_RESULT; stdcall; function Reallocate(const pData: Pointer; uiWidth: Cardinal; uiHeight: Cardinal; eDataFormat: E_TEXTURE_DATA_FORMAT): DGLE_RESULT; stdcall; function GetBaseObject(out prObj: IBaseRenderObjectContainer): DGLE_RESULT; stdcall; function Free(): DGLE_RESULT; stdcall; end; ICoreGeometryBuffer = interface(IDGLE_Base) ['{9A77DCFF-9E4B-4716-9BBB-A316BF217F7A}'] function GetGeometryData(out stDesc: TDrawDataDesc; uiVerticesDataSize, iIndexesDataSize: Cardinal): DGLE_RESULT; stdcall; function SetGeometryData(const stDesc: TDrawDataDesc; uiVerticesDataSize, uiIndexesDataSize: Cardinal): DGLE_RESULT; stdcall; function Reallocate(const stDesc: TDrawDataDesc; uiVerticesCount: Cardinal; uiIndexesCount: Cardinal; eMode: E_CORE_RENDERER_DRAW_MODE): DGLE_RESULT; stdcall; function GetBufferDimensions(out uiVerticesDataSize, uiVerticesCount, uiIndexesDataSize, uiIndexesCount: Cardinal): DGLE_RESULT; stdcall; function GetBufferDrawDataDesc(out stDesc: TDrawDataDesc): DGLE_RESULT; stdcall; function GetBufferDrawMode(out eMode: E_CORE_RENDERER_DRAW_MODE): DGLE_RESULT; stdcall; function GetBufferType(out eType: E_CORE_RENDERER_BUFFER_TYPE): DGLE_RESULT; stdcall; function GetBaseObject(out prObj: IBaseRenderObjectContainer): DGLE_RESULT; stdcall; function Free(): DGLE_RESULT; stdcall; end; IFixedFunctionPipeline = interface; ICoreRenderer = interface(IEngineSubSystem) ['{C3B687A1-57B0-4E21-BE4C-4D92F3FAB311}'] //Must not be called by user function Prepare(out stResults: TCRndrInitResults): DGLE_RESULT; stdcall; function Initialize(out stResults: TCRndrInitResults): DGLE_RESULT; stdcall; function Finalize(): DGLE_RESULT; stdcall; function AdjustMode(out stNewWin: TEngineWindow): DGLE_RESULT; stdcall; // function MakeCurrent(): DGLE_RESULT; stdcall; function Present(): DGLE_RESULT; stdcall; function SetClearColor(const stColor: TColor4): DGLE_RESULT; stdcall; function GetClearColor(out stColor: TColor4): DGLE_RESULT; stdcall; function Clear(bColor: Boolean = True; bDepth: Boolean = True; bStencil: Boolean = True): DGLE_RESULT; stdcall; function SetViewport(x, y, width, height: Cardinal): DGLE_RESULT; stdcall; function GetViewport(out x, y, width, height: Cardinal): DGLE_RESULT; stdcall; function SetScissorRectangle(x, y, width, height: Cardinal): DGLE_RESULT; stdcall; function GetScissorRectangle(out x, y, width, height: Cardinal): DGLE_RESULT; stdcall; function SetLineWidth(fWidth: Single): DGLE_RESULT; stdcall; function GetLineWidth(out fWidth: Single): DGLE_RESULT; stdcall; function SetPointSize(fSize: Single): DGLE_RESULT; stdcall; function GetPointSize(out fSize: Single): DGLE_RESULT; stdcall; function ReadFrameBuffer(uiX, uiY, uiWidth, uiHeight: Cardinal; pData: Pointer; uiDataSize: Cardinal; eDataFormat: E_TEXTURE_DATA_FORMAT): DGLE_RESULT; stdcall; function SetRenderTarget(pTexture: ICoreTexture): DGLE_RESULT; stdcall; function GetRenderTarget(out prTexture: ICoreTexture): DGLE_RESULT; stdcall; function CreateTexture(out prTex: ICoreTexture; const pData: Pointer; uiWidth, uiHeight: Cardinal; bMipmapsPresented: Boolean; eDataAlignment: E_CORE_RENDERER_DATA_ALIGNMENT; eDataFormat: E_TEXTURE_DATA_FORMAT; eLoadFlags: {E_TEXTURE_LOAD_FLAGS} Cardinal): DGLE_RESULT; stdcall; function CreateGeometryBuffer(out prBuffer: ICoreGeometryBuffer; const stDrawDesc: TDrawDataDesc; uiVerticesCount, uiIndexesCount: Cardinal; eMode: E_CORE_RENDERER_DRAW_MODE; eType: E_CORE_RENDERER_BUFFER_TYPE): DGLE_RESULT; stdcall; function ToggleStateFilter(bEnabled: Boolean): DGLE_RESULT; stdcall; function InvalidateStateFilter(): DGLE_RESULT; stdcall; function PushStates(): DGLE_RESULT; stdcall; function PopStates(): DGLE_RESULT; stdcall; function SetMatrix(const stMatrix: TMatrix4x4; eMatType: E_MATRIX_TYPE = MT_MODELVIEW): DGLE_RESULT; stdcall; function GetMatrix(out stMatrix: TMatrix4x4; eMatType: E_MATRIX_TYPE = MT_MODELVIEW): DGLE_RESULT; stdcall; function Draw(const stDrawDesc: TDrawDataDesc; eMode: E_CORE_RENDERER_DRAW_MODE; uiCount: Cardinal): DGLE_RESULT; stdcall; function DrawBuffer(pBuffer: ICoreGeometryBuffer): DGLE_RESULT; stdcall; function SetColor(const stColor: TColor4): DGLE_RESULT; stdcall; function GetColor(out stColor: TColor4): DGLE_RESULT; stdcall; function ToggleBlendState(bEnabled: Boolean): DGLE_RESULT; stdcall; function ToggleAlphaTestState(bEnabled: Boolean): DGLE_RESULT; stdcall; function SetBlendState(const stState: TBlendStateDesc): DGLE_RESULT; stdcall; function GetBlendState(out stState: TBlendStateDesc): DGLE_RESULT; stdcall; function SetDepthStencilState(const stState: TDepthStencilDesc): DGLE_RESULT; stdcall; function GetDepthStencilState(out stState: TDepthStencilDesc): DGLE_RESULT; stdcall; function SetRasterizerState(const stState: TRasterizerStateDesc): DGLE_RESULT; stdcall; function GetRasterizerState(out stState: TRasterizerStateDesc): DGLE_RESULT; stdcall; function BindTexture(pTex: ICoreTexture; uiTextureLayer: Cardinal = 0): DGLE_RESULT; stdcall; function GetBindedTexture(out prTex: ICoreTexture; uiTextureLayer: Cardinal): DGLE_RESULT; stdcall; function GetFixedFunctionPipelineAPI(out prFFP: IFixedFunctionPipeline): DGLE_RESULT; stdcall; function GetDeviceMetric(eMetric: E_CORE_RENDERER_METRIC_TYPE; out iValue: Integer): DGLE_RESULT; stdcall; function IsFeatureSupported(eFeature: E_CORE_RENDERER_FEATURE_TYPE; out bIsSupported: Boolean): DGLE_RESULT; stdcall; function GetRendererType(out eType: E_CORE_RENDERER_TYPE): DGLE_RESULT; stdcall; end; IFixedFunctionPipeline = interface(IDGLE_Base) ['{CA99FAF4-D818-4E16-BF96-C84D4E5F3A8F}'] function PushStates(): DGLE_RESULT; stdcall; function PopStates(): DGLE_RESULT; stdcall; function SetMaterialDiffuseColor(const stColor: TColor4): DGLE_RESULT; stdcall; function SetMaterialSpecularColor(const stColor: TColor4): DGLE_RESULT; stdcall; function SetMaterialShininess(fShininess: Single): DGLE_RESULT; stdcall; function GetMaterialDiffuseColor(out stColor: TColor4): DGLE_RESULT; stdcall; function GetMaterialSpecularColor(out stColor: TColor4): DGLE_RESULT; stdcall; function GetMaterialShininess(out fShininess: Single): DGLE_RESULT; stdcall; function ToggleGlobalLighting(bEnabled: Boolean): DGLE_RESULT; stdcall; function SetGloablAmbientLight(const stColor: TColor4): DGLE_RESULT; stdcall; function GetMaxLightsPerPassCount(out uiCount: Cardinal): DGLE_RESULT; stdcall; function IsGlobalLightingEnabled(out bEnabled: Boolean): DGLE_RESULT; stdcall; function GetGloablAmbientLight(out stColor: TColor4): DGLE_RESULT; stdcall; function SetLightEnabled(uiIdx: Cardinal; bEnabled: Boolean): DGLE_RESULT; stdcall; function SetLightColor(uiIdx: Cardinal; const stColor: TColor4): DGLE_RESULT; stdcall; function SetLightIntensity(uiIdx: Cardinal; fIntensity: Single): DGLE_RESULT; stdcall; function ConfigureDirectionalLight(uiIdx: Cardinal; const stDirection: TVector3): DGLE_RESULT; stdcall; function ConfigurePointLight(uiIdx: Cardinal; const stPosition: TPoint3; fRange: Single): DGLE_RESULT; stdcall; function ConfigureSpotLight(uiIdx: Cardinal; const stPosition: TPoint3; const stDirection: TVector3; fRange, fSpotAngle: Single): DGLE_RESULT; stdcall; function GetLightEnabled(uiIdx: Cardinal; out bEnabled: Boolean): DGLE_RESULT; stdcall; function GetLightColor(uiIdx: Cardinal; out stColor: TColor4): DGLE_RESULT; stdcall; function GetLightIntensity(uiIdx: Cardinal; out fIntensity: Single): DGLE_RESULT; stdcall; function GetLightType(uiIdx: Cardinal; out eType: E_LIGHT_TYPE ): DGLE_RESULT; stdcall; function GetDirectionalLightConfiguration(uiIdx: Cardinal; out stDirection: TVector3): DGLE_RESULT; stdcall; function GetPointLightConfiguration(uiIdx: Cardinal; out stPosition: TPoint3; out fRange: Single): DGLE_RESULT; stdcall; function GetSpotLightConfiguration(uiIdx: Cardinal; out stPosition: TPoint3; out stDirection: TVector3; out fRange, fSpotAngle: Single): DGLE_RESULT; stdcall; function SetFogEnabled(bEnabled: Boolean): DGLE_RESULT; stdcall; function SetFogColor(const stColor: TColor4): DGLE_RESULT; stdcall; function ConfigureFog(fStart, fEnd, fDensity: Single): DGLE_RESULT; stdcall; function GetFogEnabled(out bEnabled: Boolean): DGLE_RESULT; stdcall; function GetFogColor(out stColor: TColor4): DGLE_RESULT; stdcall; function GetFogConfiguration(out fStart, fEnd, fDensity: Single): DGLE_RESULT; stdcall; end; function BlendStateDesc(): TBlendStateDesc; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function DepthStencilDesc(): TDepthStencilDesc; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function RasterizerStateDesc(): TRasterizerStateDesc; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function DrawDataAttributes(): TDrawDataAttributes; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function DrawDataDesc(): TDrawDataDesc; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} function DrawDataDesc(pDataPointer: Pointer; uiNormalDataOffset: Cardinal; uiTextureVertexDataOffset: Cardinal; bIs2d: Boolean): TDrawDataDesc; overload; {$IFDEF DGLE_PASCAL_INLINE}inline;{$ENDIF} implementation function BlendStateDesc(): TBlendStateDesc; begin Result.bEnabled := False; Result.eSrcFactor := BF_SRC_ALPHA; Result.eDstFactor := BF_ONE_MINUS_SRC_ALPHA; end; function DepthStencilDesc(): TDepthStencilDesc; begin Result.bDepthTestEnabled := True; Result.bWriteToDepthBuffer := True; Result.eDepthFunc := CF_LESS_EQUAL; end; function RasterizerStateDesc(): TRasterizerStateDesc; begin Result.bWireframe := False; Result.eCullMode := PCM_NONE; Result.bFrontCounterClockwise := True; Result.bScissorEnabled := False; Result.bAlphaTestEnabled := False; Result.eAlphaTestFunc := CF_GREATER; Result.fAlphaTestRefValue := 0.25; end; function DrawDataAttributes(): TDrawDataAttributes; var i: Integer; begin for i := 0 to 7 do Result.uiAttribOffset[i] := Minus1; end; function DrawDataDesc(): TDrawDataDesc; begin Result.pData := nil; Result.uiVertexStride := 0; Result.bVertices2D := False; Result.uiNormalOffset := Minus1; Result.uiNormalStride := 0; Result.uiTextureVertexOffset := Minus1; Result.uiTextureVertexStride := 0; Result.uiColorOffset := Minus1; Result.uiColorStride := 0; Result.uiTangentOffset := Minus1; Result.uiBinormalOffset := Minus1; Result.uiTangentStride := 0; Result.uiBinormalStride := 0; Result.pIndexBuffer := nil; Result.bIndexBuffer32 := False; Result.pAttribs := nil; end; function DrawDataDesc(pDataPointer: Pointer; uiNormalDataOffset: Cardinal; uiTextureVertexDataOffset: Cardinal; bIs2d: Boolean): TDrawDataDesc; begin Result.pData := pDataPointer; Result.uiVertexStride := 0; Result.bVertices2D := bIs2d; Result.uiNormalOffset := uiNormalDataOffset; Result.uiNormalStride := 0; Result.uiTextureVertexOffset := uiTextureVertexDataOffset; Result.uiTextureVertexStride := 0; Result.uiColorOffset := Minus1; Result.uiColorStride := 0; Result.uiTangentOffset := Minus1; Result.uiBinormalOffset := Minus1; Result.uiTangentStride := 0; Result.uiBinormalStride := 0; Result.pIndexBuffer := nil; Result.bIndexBuffer32 := False; Result.pAttribs := nil; end; {$IFDEF DGLE_PASCAL_RECORDCONSTRUCTORS} constructor TBlendStateDesc.Create(Dummy: Byte); begin Self := BlendStateDesc(); end; constructor TDepthStencilDesc.Create(Dummy: Byte); begin Self := DepthStencilDesc(); end; constructor TRasterizerStateDesc.Create(Dummy: Byte); begin Self := RasterizerStateDesc(); end; constructor TDrawDataAttributes.Create(Dummy: Byte); begin Self := DrawDataAttributes(); end; constructor TDrawDataDesc.Create(Dummy: Byte); begin Self := DrawDataDesc(); end; constructor TDrawDataDesc.Create(pDataPointer: Pointer; uiNormalDataOffset: Cardinal; uiTextureVertexDataOffset: Cardinal; bIs2d: Boolean); begin Self := DrawDataDesc(pDataPointer, uiNormalDataOffset, uiTextureVertexDataOffset, bIs2d); end; {$ENDIF} {$IFDEF DGLE_PASCAL_RECORDOPERATORS} class operator TDrawDataDesc.{$IFDEF FPC} = {$ELSE} Equal {$ENDIF}(const this, desc: TDrawDataDesc): Boolean; begin Result := (this.pData = desc.pData) and (this.uiVertexStride = desc.uiVertexStride) and (this.bVertices2D = desc.bVertices2D) and (this.uiNormalOffset = desc.uiNormalOffset) and (this.uiNormalStride = desc.uiNormalStride) and (this.uiTextureVertexOffset = desc.uiTextureVertexOffset) and (this.uiTextureVertexStride = desc.uiTextureVertexStride) and (this.uiColorOffset = desc.uiColorOffset) and (this.uiColorStride = desc.uiColorStride) and (this.uiTangentOffset = desc.uiTangentOffset) and (this.uiBinormalOffset = desc.uiBinormalOffset) and (this.uiTangentStride = desc.uiTangentStride) and (this.uiBinormalStride = desc.uiBinormalStride) and (this.pAttribs = desc.pAttribs) and (this.pIndexBuffer = desc.pIndexBuffer) and (this.bIndexBuffer32 = desc.bIndexBuffer32); end; {$ENDIF} end.
unit uLicenseDM; interface uses System.SysUtils, System.Classes, OnGuard, OgUtil, IniFiles, Forms; type TLicenseDataModule = class(TDataModule) OgDateCode: TOgDateCode; procedure DataModuleCreate(Sender: TObject); procedure OgDateCodeChecked(Sender: TObject; Status: TCodeStatus); procedure OgDateCodeGetCode(Sender: TObject; var Code: TCode); procedure OgDateCodeGetKey(Sender: TObject; var Key: TKey); private { Private declarations } public CurrentDir : string; FKey : TKey; FCode : TCode; IsRegistered : boolean; ExpireDate : TDateTime; procedure ReadRegistration; function CheckLicense: Boolean; end; var LicenseDataModule: TLicenseDataModule; implementation {%CLASSGROUP 'Vcl.Controls.TControl'} {$R *.dfm} function TLicenseDataModule.CheckLicense: Boolean; begin ReadRegistration; OgDateCode.CheckCode(true); end; procedure TLicenseDataModule.DataModuleCreate(Sender: TObject); var PathLength : integer; begin IsRegistered := False; CurrentDir := ExtractFilePath(ParamStr(0)); PathLength := Length(CurrentDir); if (PathLength > 3) and (CurrentDir[PathLength] <> '\') then CurrentDir := CurrentDir + '\'; end; procedure TLicenseDataModule.OgDateCodeChecked(Sender: TObject; Status: TCodeStatus); var S:String; begin case Status of ogValidCode : begin IsRegistered := True; ExpireDate := OgDateCode.GetValue; Exit; end; ogPastEndDate : begin IsRegistered := False; ExpireDate := OgDateCode.GetValue; Exit; end; ogInvalidCode : IsRegistered := False; end; end; procedure TLicenseDataModule.OgDateCodeGetCode(Sender: TObject; var Code: TCode); begin Code := FCode end; procedure TLicenseDataModule.OgDateCodeGetKey(Sender: TObject; var Key: TKey); begin Key := FKey; end; procedure TLicenseDataModule.ReadRegistration; var IniFile: TIniFile; S: string; begin IniFile := TIniFile.Create(ChangeFileExt(Application.ExeName,'.key')); try S := IniFile.ReadString('Code', 'Value', ''); HexToBuffer(S, FCode, SizeOf(FCode)); S := IniFile.ReadString('Key', 'Value', ''); HexToBuffer(S, FKey, SizeOf(FKey)) finally IniFile.Free; end; end; end.
UNIT VectorD; {$mode objfpc}{$H+} INTERFACE USES {$IFDEF UNIX}{$IFDEF UseCThreads} cthreads, cmem {$ENDIF}{$ENDIF} math, sysutils; TYPE Cls_Vector = class Private xCell: array of extended; OrdenN: integer; Function GetCell(i: integer): extended; Procedure SetCell(i: integer; num: extended); //en estos comentarios 'Vec' representa al objeto de la clase VectorD (this en C o self en objet pascal) {Advertencia: para el algebra de vectores como la suma o resta de vectores la clase Cls_Vector no realiza verificacion del ordenN de cada vector respectivamente queda a responsabilidad del usuario programador verificar que ambos sean del mismo orden para no producir salidas incorrectas Adv2: no olvidar inicializar orden N de los vectores y/o matrices antes de usar EJEMPLO de uso de vector: VAR A: Cls_Vector; BEGIN A:= Cls_Vector.CREAR(), por defecto N=10 // A:= Cls_Vector.crear(VALOR) A.cells[i]:= 4; A.free(); o A.destroy(); OJO!!! si en vez de "crear" se utiliza el constructor por defecto create a:= Cls_Vector.create(); a.redimensionar(VALOR); ---> si o si, sino el vector apunta a nill END.} Public //************************************************************/ //************************************************************/ constructor crear(cant: integer = 10); //por defecto crea un vector con 10 elementos, num es opcional Property cells[i: integer]: extended READ GetCell WRITE SetCell; Property N: integer READ OrdenN WRITE OrdenN; //N Function Norma_1(): extended;//SUM(abs(i)), i=1..N Function Norma_2(): extended;//euclidea sqrt(SUM(i^2)), i=1..N Function Norma_Infinita(): extended; //MAYOR(abs(i)), i=1..N Procedure Opuesto(); //Vec:= -Vec; Procedure Opuesto(vecX: Cls_Vector); //Vec:= -VecX; Procedure xEscalar(num: extended);//Vec:= num*Vec[i], i=1..N; Function Indice_Mayor_abs(): integer; //devuelve el indice del mayor numero dentro del vector en valor absoluto Function Indice_Mayor(): integer; //devuelve el indice del mayor numero dentro del vector Procedure Limpia(k: extended = 0);//Llena de un num k, por defecto cero al vector //Redimensiona vector dinamico agrandando el vector o perdiendo elementos al achicar segun sea el caso Procedure Redimensionar(cant: integer); Procedure Intercambiar(const i: integer; const j: integer); Procedure eliminaX(const pos: integer); Procedure insertarX(const elemento: extended; const pos: integer); function subVector(posini:integer; cant:integer):Cls_Vector; //retorna un sub-Vector (desde, cantidad); {Muestra el vector por consola (usando Write), por defecto en Horizontal, con opcion de mandar como parametro entero 1 para que lo muestre vertical al vector Ejemplos: vecA.mostrar(); ----> muestra horizontal vecA.mostrar(0); ----> muestra horizontal vecA.mostrar(cualquier valor entero <> 1); ----> muestra Horizontal vecA.mostrar(1); ----> muestra vertical vecA.mostrar('titulo')----> muestra horizontal con titulo vecA.mostrar('titulo', cualquier valor entero <> 1); ----> muestra Horizontal con titulo vecA.mostrar('titulo',1)----> muestra vertical con titulo} Procedure mostrar(titulo: String = ''; s: byte = 0; mascara: integer =2); //consola procedure mostrar(s: byte); //consola {OJO!!! al ser un objetos si realizamos VecA:= VecB en el programa directamente, copia los punteros y no los atributos de los objetos respectivamente por eso es obligatorio usar el siguiente procedimiento} Procedure Copiar(VecX: Cls_Vector); //copia elemento a elemento---> Vec:= VecX; //Se pueden usar Para sumar o restar (usando Opuesto) Procedure Suma(VecA, VecB : Cls_Vector); //Vec:= VecA + VecB; Procedure Suma(VecX: Cls_Vector); //Vec:= Vec + VecX; Function ToString(mascara: byte = 0):String; end; implementation //************************************************************** //***********************VECTORES******************************* //************************************************************** constructor Cls_Vector.crear(cant: integer = 10); Begin SetLength(xCell, cant); //crea elementos desde 0 hasta Len-1 OrdenN:= cant-1; limpia(); end; Procedure Cls_Vector.setCell(i: integer; num: extended); Begin xCell[i]:= num end; Function Cls_Vector.getCell(i: integer): extended; Begin RESULT:= xCell[i]; end; Procedure Cls_Vector.Redimensionar(cant: integer); Begin setlength(xCell, cant); N:= cant-1; end; Procedure Cls_Vector.Intercambiar(const i: integer; const j: integer); VAR aux: extended; Begin if ((0<= i) and (i<= N)) then Begin if ((0<= j) and (j<= N)) then Begin if (i<>j) then begin aux:= cells[i]; cells[i]:= cells[j]; cells[j]:= aux; end end else writeln('Error intercambiar... posicion j = ',j,' incorrecta...'); end else writeln('Error intercambiar... posicion i = ',i,' incorrecta...'); end; Procedure Cls_Vector.eliminaX(const pos: integer); VAR i:integer; Begin if ((0<= pos) and (pos<= N)) then begin for i:= pos to N-1 do cells[i]:= cells[i+1]; Redimensionar(N); end else writeln('Error eliminaX... posicion: ',pos,' incorrecta...') end; Procedure Cls_Vector.insertarX(const elemento: extended; const pos: integer); VAR i: integer; Begin if ((0<= pos) and (pos<= N)) then begin Redimensionar(N+2); for i:=N downto pos+1 do cells[i]:= cells[i-1]; cells[pos]:= elemento; end else writeln('Error insertarX... posicion: ',pos,' incorrecta...') end; Procedure Cls_Vector.Limpia(k: extended = 0);//Llena de un num k, por defecto cero al vector var i: integer; Begin for i:=0 to N do cells[i]:= k; end; procedure Cls_Vector.mostrar(titulo:String=''; s: byte = 0; mascara: integer =2); //consola VAR i:integer; Begin writeln; if (titulo <>'') then writeln(titulo); if (s = 1) then //muestra vertical for i:= 0 to N do writeln(cells[i]:0:MASCARA) else begin//muestra horizontal por defecto, con cualquier valor en s <>1 for i:= 0 to N do write(cells[i]:0:MASCARA,' '); writeln; end; end; procedure Cls_Vector.mostrar(s: byte); //consola VAR i:integer; Begin writeln; if (s = 1) then //muestra vertical for i:= 0 to N do writeln(cells[i]:0:2) else begin//muestra horizontal por defecto, con cualquier valor en s <>1 for i:= 0 to N do write(cells[i]:0:2,' '); writeln; end; end; {Calculo de la norma infinita} function Cls_Vector.Norma_Infinita ():extended; var i:integer; mayor : extended; begin mayor:=0; for i:=0 to N do if (Abs(cells[i]) > mayor) then mayor:=Abs(cells[i]); Result:= mayor; end; function Cls_Vector.Norma_2 ():extended; var i:integer; resu:extended; begin resu:=0; for i:=0 to N do resu:= resu + power(cells[i],2); Result:= power(resu,(1/2)); end; function Cls_Vector.Norma_1():extended; var i:integer; resu:extended; begin resu:= 0; for i:= 0 to N do resu:= resu + Abs(cells[i]); Result:= resu; end; //El procedimiento modifica el vector cambiandolo por su opuesto //vec:= -vec procedure Cls_Vector.Opuesto(); var i: integer; begin for i:=0 to N do cells[i]:= (-1)*cells[i]; end; //vec:= -VecX Procedure Cls_Vector.Opuesto(vecX: Cls_Vector); //Vec:= -VecX; begin self.copiar(vecX); self.opuesto(); end; //VecX:= VecA + VecB; Procedure Cls_Vector.Suma(VecA, VecB : Cls_Vector); var i: integer; begin if (VecA.N = VecB.N) then begin for i:= 0 to N do cells[i] := vecA.cells[i] + vecB.cells[i]; end else writeln('cls_Vector: Error Suma :Los vectores son de distinto tam. '); end; //VecX:= VecX + Vec; Procedure Cls_Vector.Suma(VecX: Cls_Vector); Var i: integer; begin if (N = VecX.N) then begin for i:=0 to N do cells[i]:= cells[i] + vecX.cells[i]; end else writeln('cls_Vector: Error Suma :Los vectores son de distinto tam.'); end; Function Cls_Vector.ToString(mascara: byte = 0):String; Var i: integer; cad,aux: string; Begin case mascara of //Mascara Optima elimina los 0 demas 0: Begin for i:=0 to N do cad:= cad + ' ' + FloatToStr(cells[i]); end; 11: Begin //sin mascara for i:=0 to N do Begin STR(cells[i],aux); cad:= cad + ' ' +aux; end; end; else Begin //con Mascara controlando digitos decimales for i:=0 to N do Begin STR(cells[i]:0:Mascara, aux); cad:= cad + ' ' + aux; end; end; end; //case RESULT:= cad; end; //efectua la suma componente a componente Procedure Cls_Vector.copiar(vecX: Cls_Vector); VAR i:integer; Begin redimensionar(vecX.N+1); for i:=0 to N do cells[i]:= vecX.Cells[i]; end; function Cls_Vector.indice_mayor_abs(): integer; VAR m,i:integer; mayor:extended; Begin m:= 0; mayor:= 0; for i:=0 to N do if (abs(cells[i]) > mayor) then Begin mayor:= abs(cells[i]); m:=i; end; Result:= m; end; function Cls_Vector.indice_mayor(): integer; VAR m,i:integer; mayor:extended; Begin m:= 0; mayor:= 0; for i:=0 to N do if (cells[i] > mayor) then Begin mayor:= cells[i]; m:=i; end; Result:= m; end; Procedure Cls_Vector.xEscalar(num: extended);//Vec:= num*Vec[i], i=1..N; var i:integer; Begin for i:=0 to N do cells[i]:= num*cells[i]; end; function Cls_Vector.subVector(posini:integer; cant:integer):Cls_Vector; var vectorAux:cls_Vector; i:byte; begin if (cant>0) and (posini>=0) and (posini+cant<=self.N+1) then begin vectorAux:=cls_Vector.crear(cant); //vector.crear(cantidad) cantidad>=1 for i:=0 to cant-1 do vectorAux.cells[i]:=self.cells[i+posini]; result:=vectorAux; end else result:=nil; end; BEGIN END.
unit aeCamera; interface uses types, aeSceneNode, aeSceneObject, aeMaths, aeTransform, aeDebugHelpers; type TaeCameraViewType = (AE_CAMERA_VIEW_LOOKATCENTER, AE_CAMERA_VIEW_LOOKFROMCENTER); // type // IaeBaseCamera = Interface(IInterface) // procedure LookAt(pos: TPoint3D); // End; // // type // TaeArcBallCamera = class(TInterfacedObject, IaeBaseCamera) // // end; type TaeCamera = class public Constructor Create(targetObject: TaeSceneObject); procedure SetCenterObject(o: TaeSceneObject); procedure SetMousePosition(p: TPoint); procedure SetDistance(d: single); procedure SetCameraViewType(vt: TaeCameraViewType); function GetCameraViewtype: TaeCameraViewType; function GetCameraTarget: TaeSceneObject; procedure MoveForward(dist: single); function GetSphere: TaeSphere; function GetTransformMatrix: TaeMatrix44; procedure SetMinHeight(m: single); function getPosition: TPoint3D; function GetProjectionMatrix: TaeMatrix44; procedure SetViewPortSize(w, h: integer); procedure SetFieldOfView(fov: single); function GetFieldOfView: single; procedure SetZNearClippingPlane(zn: single); procedure SetZFarClippingPlane(zf: single); private // used for arcball orientation _arcBallCenter: TaeSceneObject; _transform: TaeTransform; _projectionMatrix: TaeMatrix44; _viewPortWidth, _viewPortHeight: integer; _projectionChanged: boolean; _fovY: single; _zNear, _zFar: single; _sensitivity: single; _sphere: TaeSphere; _viewType: TaeCameraViewType; _speed: single; // if current height is lower than this, we need to adjust. _minHeight: single; function GetLookAtPoint: TPoint3D; end; implementation { TaeCamera } constructor TaeCamera.Create(targetObject: TaeSceneObject); begin if (targetObject <> nil) then begin self.SetCenterObject(targetObject); end; self._transform := TaeTransform.Create; self._sphere.Create(5.0); self._sensitivity := 0.01; self._speed := 1.0; self._viewType := AE_CAMERA_VIEW_LOOKATCENTER; // by default, we want an arcball cam. // default self._fovY := 60.0; self._zNear := 0.1; self._zFar := 10000.0; // aspect 1920/1080 self._projectionMatrix.SetPerspective(self._fovY, 1.7777, self._zNear, self._zFar); self._projectionChanged := false; end; function TaeCamera.GetCameraTarget: TaeSceneObject; begin Result := self._arcBallCenter; end; function TaeCamera.GetCameraViewtype: TaeCameraViewType; begin Result := self._viewType; end; function TaeCamera.GetFieldOfView: single; begin Result := self._fovY; end; function TaeCamera.GetLookAtPoint: TPoint3D; begin case self._viewType of AE_CAMERA_VIEW_LOOKATCENTER: Result := self._arcBallCenter.getPosition; AE_CAMERA_VIEW_LOOKFROMCENTER: Result := self._sphere.Get3DPoint(AE_AXIS_ORDER_XZY) + self.getPosition(); end; end; function TaeCamera.getPosition: TPoint3D; begin case self._viewType of AE_CAMERA_VIEW_LOOKATCENTER: Result := self._sphere.Get3DPoint(AE_AXIS_ORDER_XZY) + self._arcBallCenter.getPosition; AE_CAMERA_VIEW_LOOKFROMCENTER: Result := self._arcBallCenter.getPosition; end; end; function TaeCamera.GetProjectionMatrix: TaeMatrix44; begin if (self._projectionChanged) then begin self._projectionMatrix.SetPerspective(self._fovY, self._viewPortWidth / self._viewPortHeight, self._zNear, self._zFar); self._projectionChanged := false; end; Result := self._projectionMatrix; end; function TaeCamera.GetSphere: TaeSphere; begin Result := self._sphere; end; function TaeCamera.GetTransformMatrix: TaeMatrix44; var trans: TaeMatrix44; pos: TPoint3D; begin case self._viewType of AE_CAMERA_VIEW_LOOKATCENTER: self._transform.LookAt(self.getPosition(), self._arcBallCenter.getPosition, Point3D(0.0, 1.0, 0.0)); AE_CAMERA_VIEW_LOOKFROMCENTER: self._transform.LookAt(self.getPosition(), self._sphere.Get3DPoint(AE_AXIS_ORDER_XZY) + self.getPosition(), Point3D(0.0, 1.0, 0.0)); end; trans.loadIdentity; pos := self.getPosition(); if (pos.Y < self._minHeight) then pos.Y := self._minHeight; trans.SetTranslation(pos); Result.loadIdentity; Result := Result * self._transform.GetRotation; Result := Result * trans; // we need to invert camera's transform matrix to make it a view matrix. // view_mat = trans_mat^-1 Result := Result.Invert; // end; procedure TaeCamera.MoveForward(dist: single); var forwardVector, newPos, oldPos: TPoint3D; begin forwardVector := (self.GetLookAtPoint - self.getPosition).Normalize; // forwardVector := forwardVector.Negative; case self._viewType of AE_CAMERA_VIEW_LOOKATCENTER: begin oldPos := self.getPosition; newPos := oldPos + forwardVector.Scale(self._speed * dist); PrintDebugMessage('OldPos : ' + PrintPoint3D(oldPos) + ' | NewPos : ' + PrintPoint3D(newPos)); self._arcBallCenter.Move(newPos); end; AE_CAMERA_VIEW_LOOKFROMCENTER: begin newPos := self.getPosition; newPos := newPos + forwardVector.Scale(self._speed * dist); self._arcBallCenter.Move(newPos); end; end; end; procedure TaeCamera.SetCameraViewType(vt: TaeCameraViewType); begin self._viewType := vt; end; procedure TaeCamera.SetDistance(d: single); begin // Distance is irrelevant when we look from center into world. if (self._viewType = AE_CAMERA_VIEW_LOOKATCENTER) then begin self._sphere.Radius := self._sphere.Radius + d; if (self._sphere.Radius < 1.0) then self._sphere.Radius := 1.0; end; end; procedure TaeCamera.SetFieldOfView(fov: single); begin self._fovY := fov; self._projectionChanged := true; end; procedure TaeCamera.SetMinHeight(m: single); begin self._minHeight := m; end; procedure TaeCamera.SetMousePosition(p: TPoint); begin self._sphere.theta := self._sphere.theta + p.Y * _sensitivity; self._sphere.phi := self._sphere.phi - p.x * _sensitivity; end; procedure TaeCamera.SetViewPortSize(w, h: integer); begin self._viewPortWidth := w; self._viewPortHeight := h; self._projectionChanged := true; end; procedure TaeCamera.SetZFarClippingPlane(zf: single); begin self._zFar := zf; self._projectionChanged := true; end; procedure TaeCamera.SetZNearClippingPlane(zn: single); begin self._zNear := zn; self._projectionChanged := true; end; procedure TaeCamera.SetCenterObject(o: TaeSceneObject); begin self._arcBallCenter := o; end; end.
//Exercicio : Dizemos que um número inteiro positivo é triangular se ele for o produto de três números naturais consecutivos. //Por exemplo, o número 120 é triangular, pois 120 = 4 X 5 X 6. Escreva um algoritmo que receba um número inteiro positivo n //e verifique se ele é triangular. { Solução em Portugol Algoritmo Exercicio ; Var n,primeiro,segundo,terceiro, triangular: inteiro; Inicio primeiro <- 1; // São os 3 primeiros inteiros positivos. Eles mudam de valor a cada loop. segundo <- 2; terceiro <- 3; exiba("Programa que avalia se um número inteiro positivo é triangular."); exiba("Digite o número que será avaliado: "); leia(n); enquanto(n <= 0)faça // Consistência de dados. exiba("Digite um número inteiro positivo."); leia(n); fimenquanto; enquanto(primeiro * segundo * terceiro <= n)faça // Multiplicações são feitas até que o produto passe o valor de n se(primeiro * segundo * terceiro = n) // se uma das multiplicações resultarem em n, o número é triangular. então triangular <-1; fimse; primeiro <- segundo; segundo <- terceiro; terceiro <- terceiro + 1; fimenquanto; se(triangular = 1) então exiba(n," é triangular.") senão exiba(n," não é triangular."); fimse; Fim. } // Solução em Pascal Program Exercicio; uses crt; var n,primeiro,segundo,terceiro,triangular: integer; begin clrscr; primeiro := 1; // São os 3 primeiros inteiros positivos. Eles mudam de valor a cada loop. segundo := 2; terceiro := 3; writeln('Programa que avalia se um número inteiro positivo é triangular.'); writeln('Digite o número que será avaliado: '); readln(n); while(n <= 0)do // Consistência de dados. Begin writeln('Digite um número inteiro positivo.'); readln(n); End; while(primeiro * segundo * terceiro <= n)do // Multiplicações são feitas até que o produto passe o valor de n Begin // se uma das multiplicações resultarem em n, o número é triangular. if(primeiro * segundo * terceiro = n) then triangular := 1; primeiro := segundo; segundo := terceiro; terceiro := terceiro + 1; End; if(triangular = 1) then writeln(n,' é triangular.') else writeln(n,' não é triangular.'); repeat until keypressed; end.
unit RDOObjectRegistry; interface uses Classes; const NoId = 0; type TRegistryEntries = TList; type TRDOObjectsRegistry = class private fRegistryEntries : TRegistryEntries; procedure CleanUpRegistryEntries; public constructor Create; destructor Destroy; override; public procedure RegisterObject( ObjectName : string; ObjectId : integer ); function GetObjectId( ObjectName : string ) : integer; end; implementation type TRegistryEntry = record ObjectName : string; ObjectId : integer; end; PRegistryEntry = ^TRegistryEntry; constructor TRDOObjectsRegistry.Create; begin inherited Create; fRegistryEntries := TRegistryEntries.Create; end; destructor TRDOObjectsRegistry.Destroy; begin CleanUpRegistryEntries; fRegistryEntries.Free; inherited Destroy end; procedure TRDOObjectsRegistry.RegisterObject( ObjectName : string; ObjectId : integer ); var NewRegEntry : PRegistryEntry; begin New( NewRegEntry ); NewRegEntry.ObjectName := ObjectName; NewRegEntry.ObjectId := ObjectId; fRegistryEntries.Add( NewRegEntry ) end; function TRDOObjectsRegistry.GetObjectId( ObjectName : string ) : integer; var RegEntryIdx : integer; begin RegEntryIdx := 0; with fRegistryEntries do begin while ( RegEntryIdx < Count ) and ( ObjectName <> PRegistryEntry( Items[ RegEntryIdx ] ).ObjectName ) do inc( RegEntryIdx ); if RegEntryIdx < Count then Result := PRegistryEntry( Items[ RegEntryIdx ] ).ObjectId else Result := NoId end end; procedure TRDOObjectsRegistry.CleanUpRegistryEntries; var RegEntryIdx : integer; begin with fRegistryEntries do for RegEntryIdx := 0 to Count - 1 do Dispose( PRegistryEntry( Items[ RegEntryIdx ] ) ); end; end.
unit Exportar; interface uses Windows, SysUtils, Classes, Graphics, Forms, Controls, StdCtrls, Buttons, ExtCtrls, Dialogs, Mask, DB, DBClient, JvToolEdit, JvExMask; type TExportDlg = class(TForm) OKBtn: TButton; CancelBtn: TButton; Bevel1: TBevel; Label1: TLabel; OpenDlg: TOpenDialog; rgFormato: TRadioGroup; rgReg: TRadioGroup; Label2: TLabel; edTitulo: TEdit; CdsXMLConvert: TClientDataSet; cbArchivo: TJvComboEdit; procedure cbArchivoButtonClick(Sender: TObject); procedure rgFormatoClick(Sender: TObject); private { Private declarations } procedure SetNombre(Indice: integer); public { Public declarations } function ConvertiraXML( DataSet: TDataSet ): boolean; end; var ExportDlg: TExportDlg; implementation {$R *.dfm} procedure TExportDlg.cbArchivoButtonClick(Sender: TObject); begin if OpenDlg.Execute then cbArchivo.Text := OpenDlg.FileName; end; procedure TExportDlg.rgFormatoClick(Sender: TObject); begin SetNombre( rgFormato.ItemIndex ); end; procedure TExportDlg.SetNombre( Indice: integer ); var Extension: string; begin case ( rgFormato.ItemIndex ) of 0: Extension := '.TXT'; 1: Extension := '.XLS'; 2: Extension := '.HTML'; // 3: end; cbArchivo.Text := ChangeFileExt( cbArchivo.Text, Extension ); end; function TExportDlg.ConvertiraXML( DataSet: TDataSet ): boolean; var x: integer; begin with CdsXMLConvert do try DataSet.DisableControls; for x:=0 to DataSet.FieldCount-1 do with FieldDefs.AddFieldDef do begin DataType := DataSet.Fields[ x ].DataType; Size := DataSet.Fields[ x ].Size; Name := DataSet.Fields[ x ].FieldName; // showmessage( Name ); end; CreateDataSet; DataSet.First; while not DataSet.eof do begin Append; for x:= 0 to DataSet.FieldCount-1 do Fields[ x ].Value := DataSet.Fields[ x ].value; Post; DataSet.next; end; MergeChangeLog; SaveToFile( DataSet.Name + '.xml', dfXML ); // Showmessage( 'Conversion completada con exito' ); Result := true; EmptyDataSet; Close; finally DataSet.EnableControls; FieldDefs.Clear; Screen.cursor := crDefault; end; end; end.
unit tfwScriptsRunningAndDebugging; // Модуль: "w:\common\components\rtl\Garant\ScriptEngine\tfwScriptsRunningAndDebugging.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "tfwScriptsRunningAndDebugging" MUID: (56F556230193) {$Include w:\common\components\rtl\Garant\ScriptEngine\seDefine.inc} interface {$If NOT Defined(NoScripts)} uses l3IntfUses ; {$IfEnd} // NOT Defined(NoScripts) implementation {$If NOT Defined(NoScripts)} uses l3ImplUses , tfwGlobalKeyWord , tfwScriptingInterfaces , TypInfo , tfwScriptEngine , tfwOutToFileScriptCaller , tfwDebugScriptCaller , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes //#UC START# *56F556230193impl_uses* //#UC END# *56F556230193impl_uses* ; type TkwScriptRunFromFile = {final} class(TtfwGlobalKeyWord) {* Слово скрипта script:RunFromFile } private procedure script_RunFromFile(const aCtx: TtfwContext; const aFile: AnsiString; const anOutputFile: AnsiString); {* Реализация слова скрипта script:RunFromFile } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; end;//TkwScriptRunFromFile procedure TkwScriptRunFromFile.script_RunFromFile(const aCtx: TtfwContext; const aFile: AnsiString; const anOutputFile: AnsiString); {* Реализация слова скрипта script:RunFromFile } //#UC START# *56F5564A035F_56F5564A035F_Word_var* //#UC END# *56F5564A035F_56F5564A035F_Word_var* begin //#UC START# *56F5564A035F_56F5564A035F_Word_impl* if (anOutputFile = '') then TtfwScriptEngine.ScriptFromFile(aFile, TtfwDebugScriptCaller.Make) else TtfwScriptEngine.ScriptFromFile(aFile, TtfwOutToFileScriptCaller.Make(anOutputFile)); //#UC END# *56F5564A035F_56F5564A035F_Word_impl* end;//TkwScriptRunFromFile.script_RunFromFile class function TkwScriptRunFromFile.GetWordNameForRegister: AnsiString; begin Result := 'script:RunFromFile'; end;//TkwScriptRunFromFile.GetWordNameForRegister function TkwScriptRunFromFile.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := @tfw_tiVoid; end;//TkwScriptRunFromFile.GetResultTypeInfo function TkwScriptRunFromFile.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 2; end;//TkwScriptRunFromFile.GetAllParamsCount function TkwScriptRunFromFile.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([@tfw_tiString, @tfw_tiString]); end;//TkwScriptRunFromFile.ParamsTypes procedure TkwScriptRunFromFile.DoDoIt(const aCtx: TtfwContext); var l_aFile: AnsiString; var l_anOutputFile: AnsiString; begin try l_aFile := aCtx.rEngine.PopDelphiString; except on E: Exception do begin RunnerError('Ошибка при получении параметра aFile: AnsiString : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except try l_anOutputFile := aCtx.rEngine.PopDelphiString; except on E: Exception do begin RunnerError('Ошибка при получении параметра anOutputFile: AnsiString : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except script_RunFromFile(aCtx, l_aFile, l_anOutputFile); end;//TkwScriptRunFromFile.DoDoIt initialization TkwScriptRunFromFile.RegisterInEngine; {* Регистрация script_RunFromFile } TtfwTypeRegistrator.RegisterType(@tfw_tiString); {* Регистрация типа AnsiString } {$IfEnd} // NOT Defined(NoScripts) end.
unit PreviewFormUnit; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, OvcBase, arCommonTypes, afwControlPrim, afwBaseControl, afwControl, afwCustomCommonControlPrim, afwCustomCommonControl, vtPreviewPanel; type TPreviewForm = class(TForm) vtPreviewPanel1: TvtPreviewPanel; procedure FormCreate(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FormClose(Sender: TObject; var Action: TCloseAction); private f_LinkOwner: Pointer; {-} procedure SetLinkOwner(const Value: IevClearPreviewLink); { Private declarations } public { Public declarations } procedure StopPreivew; {-} property PreviewLinkOwner: IevClearPreviewLink write SetLinkOwner; {-} end; implementation {$R *.dfm} procedure TPreviewForm.FormCreate(Sender: TObject); begin if Owner <> nil then Caption := Caption + (Owner as TForm).Caption; f_LinkOwner := nil; end; procedure TPreviewForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin StopPreivew; end; procedure TPreviewForm.StopPreivew; begin if (vtPreviewPanel1.Preview <> nil) AND vtPreviewPanel1.Preview.InProcess then vtPreviewPanel1.Preview.Stop(Handle); end; procedure TPreviewForm.FormClose(Sender: TObject; var Action: TCloseAction); begin Action := caFree; if f_LinkOwner <> nil then IevClearPreviewLink(f_LinkOwner).ClearPreview; f_LinkOwner := nil; end; procedure TPreviewForm.SetLinkOwner(const Value: IevClearPreviewLink); begin f_LinkOwner := Pointer(Value); end; end.
unit Unit1; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, XPMan, ComCtrls, Menus, ImgList, IdCoderQuotedPrintable, IdCoderXXE, IdCoderUUE, IdCoder, IdCoder3to4, IdCoderMIME, IdBaseComponent; type TForm1 = class(TForm) MainMenu1: TMainMenu; N1: TMenuItem; N2: TMenuItem; N3: TMenuItem; N4: TMenuItem; N5: TMenuItem; RichEdit1: TRichEdit; XPManifest1: TXPManifest; GroupBox1: TGroupBox; RichEdit2: TRichEdit; PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; TabSheet3: TTabSheet; N6: TMenuItem; SaveDialog1: TSaveDialog; OpenDialog1: TOpenDialog; ImageList1: TImageList; IdEncoderMIME1: TIdEncoderMIME; IdDecoderMIME1: TIdDecoderMIME; IdEncoderUUE1: TIdEncoderUUE; IdDecoderUUE1: TIdDecoderUUE; IdEncoderXXE1: TIdEncoderXXE; IdDecoderXXE1: TIdDecoderXXE; IdEncoderQuotedPrintable1: TIdEncoderQuotedPrintable; IdDecoderQuotedPrintable1: TIdDecoderQuotedPrintable; Label1: TLabel; RadioButton1: TRadioButton; RadioButton2: TRadioButton; RadioButton3: TRadioButton; RadioButton4: TRadioButton; Label2: TLabel; RadioButton5: TRadioButton; RadioButton6: TRadioButton; RadioButton7: TRadioButton; RadioButton8: TRadioButton; Button1: TButton; Label3: TLabel; Edit1: TEdit; Label4: TLabel; Edit2: TEdit; Button2: TButton; Label5: TLabel; Edit3: TEdit; Button3: TButton; N7: TMenuItem; N8: TMenuItem; Label6: TLabel; Label7: TLabel; Label8: TLabel; Label9: TLabel; procedure FormCreate(Sender: TObject); procedure FormResize(Sender: TObject); procedure N5Click(Sender: TObject); procedure N6Click(Sender: TObject); procedure N3Click(Sender: TObject); procedure N2Click(Sender: TObject); procedure RadioButton1Click(Sender: TObject); procedure RadioButton2Click(Sender: TObject); procedure RadioButton3Click(Sender: TObject); procedure RadioButton4Click(Sender: TObject); procedure RadioButton5Click(Sender: TObject); procedure RadioButton6Click(Sender: TObject); procedure RadioButton7Click(Sender: TObject); procedure RadioButton8Click(Sender: TObject); procedure Button1Click(Sender: TObject); procedure N8Click(Sender: TObject); procedure Button3Click(Sender: TObject); procedure Button2Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; Des: integer; implementation uses Unit2, Unit3; {$R *.dfm} Procedure Resized(); begin // Ограничение размеров формы if Form1.ClientHeight<200 then Form1.ClientHeight:=200; if Form1.ClientWidth<500 then Form1.ClientWidth:=500; // Расположение групового окна (box) на форме Form1.GroupBox1.Top:=0; Form1.GroupBox1.Left:=Round(Form1.ClientWidth)-Round(Form1.GroupBox1.Width)-5; Form1.GroupBox1.Height:=Round(Form1.ClientHeight)-8; // Расположение текстового окна 1 на форме Form1.Richedit1.Top:=0+8; Form1.Richedit1.Left:=5; Form1.Richedit1.Height:=StrToInt(FloatToStr(Round(Form1.ClientHeight/2)))-7; Form1.Richedit1.Width:=Round(Form1.GroupBox1.Left)-15; // Расположение текстового окна 2 на форме Form1.Richedit2.Top:=Round(Form1.RichEdit1.Height)+5; Form1.Richedit2.Left:=5; Form1.Richedit2.Height:=StrToInt(FloatToStr(Round(Form1.ClientHeight/2)))-7; Form1.Richedit2.Width:=Round(Form1.GroupBox1.Left)-15; // Расположение PageControl1 на GroupBox1 Form1.PageControl1.Height:=Form1.ClientHeight-36; end; procedure TForm1.FormCreate(Sender: TObject); begin Resized; RichEdit1.Clear; RichEdit2.Clear; Des:=1; end; procedure TForm1.FormResize(Sender: TObject); begin Resized(); end; procedure TForm1.N5Click(Sender: TObject); begin if (Application.MessageBox('Вы действительно хотите выйти из программы?','Выход из программы',MB_ICONQUESTION+MB_YESNOCANCEL)=IDYes) then Application.Terminate; end; procedure TForm1.N6Click(Sender: TObject); begin if SaveDialog1.Execute then RichEdit1.Lines.SaveToFile(SaveDialog1.FileName+'.cro'); end; procedure TForm1.N3Click(Sender: TObject); begin if SaveDialog1.Execute then RichEdit2.Lines.SaveToFile(SaveDialog1.FileName+'.cro'); end; procedure TForm1.N2Click(Sender: TObject); begin if OpenDialog1.Execute then RichEdit1.Lines.LoadFromFile(OpenDialog1.FileName); end; procedure TForm1.RadioButton1Click(Sender: TObject); begin Des:=1; end; procedure TForm1.RadioButton2Click(Sender: TObject); begin Des:=2; end; procedure TForm1.RadioButton3Click(Sender: TObject); begin Des:=3; end; procedure TForm1.RadioButton4Click(Sender: TObject); begin Des:=4; end; procedure TForm1.RadioButton5Click(Sender: TObject); begin Des:=11; end; procedure TForm1.RadioButton6Click(Sender: TObject); begin Des:=12; end; procedure TForm1.RadioButton7Click(Sender: TObject); begin Des:=13; end; procedure TForm1.RadioButton8Click(Sender: TObject); begin Des:=14; end; procedure TForm1.Button1Click(Sender: TObject); begin Form2.Show; Form2.Update; case des of 1: RichEdit2.Text:=form1.IdEncoderMIME1.Encode(RichEdit1.Text); 2: RichEdit2.Text:=Form1.IdEncoderUUE1.Encode(RichEdit1.Text); 3: RichEdit2.Text:=Form1.IdEncoderXXE1.Encode(RichEdit1.Text); 4: RichEdit2.Text:=Form1.IdEncoderQuotedPrintable1.Encode(RichEdit1.Text); 11: RichEdit2.Text:=Form1.IdDecoderMIME1.DecodeToString(RichEdit1.Text); 12: RichEdit2.Text:=Form1.IdDecoderUUE1.DecodeToString(RichEdit1.Text); 13: RichEdit2.Text:=Form1.IdDecoderXXE1.DecodeToString(RichEdit1.Text); 14: RichEdit2.Text:=Form1.IdDecoderQuotedPrintable1.DecodeToString(Richedit1.Text) end; Form2.Label1.Caption:='Выполнено'; Form2.Hide; Form2.Label1.Caption:='Выполняется кодирование-декодирование. Ждите'; end; procedure TForm1.N8Click(Sender: TObject); begin Form3.ShowModal; end; procedure TForm1.Button3Click(Sender: TObject); var at: string; im,al,i: integer; begin Form2.Show; Form2.ProgressBar1.Visible:=true; al:=Length(Form1.Richedit1.Text); at:=Form1.Richedit1.text; Form2.ProgressBar1.Max:=al; for i:=1 to al do begin at[i]:=chr(ord(at[i])+strtoint(Form1.Edit3.Text)); Form2.ProgressBar1.Position:=i; Form2.Update; Sleep(0); Form2.ProgressBar1.Update; end; Form2.ProgressBar1.Position:=al; RichEdit2.Text:=at; Form2.Label1.Caption:='Выполнено.'; Form2.ProgressBar1.Visible:=false; Form2.Hide; Form2.Label1.Caption:='Выполняется кодирование-декодирование. Ждите...'; end; procedure TForm1.Button2Click(Sender: TObject); var md: PChar; um: string; sm,m,d: integer; begin sm:=length(Form1.RichEdit1.Text); um:=Richedit1.Text; Form2.Show; Form2.Update; Form2.ProgressBar1.Visible:=true; Form2.ProgressBar1.Max:=sm; for m:=1 to sm do begin if um[m]=Edit1.Text then begin md:=StrPCopy(md,Edit2.Text); um[m]:=chr(ord(';')); end; end; end; end.
unit ZXIng.ByteSegments; interface type /// <summary> /// implements the ByteSegments (which was declared as a TList<TArray<Byte>> /// throughout the code as reference-counted interface object) /// </summary> IByteSegments = Interface ['{0994FC90-E8F5-40D8-8A48-9B05DFFF2635}'] function Count: integer; procedure Clear; function GetCapacity: integer; procedure SetCapacity(const Value: integer); property Capacity: integer read GetCapacity write SetCapacity; function Add(const item: TArray<byte>): integer; end; function ByteSegmentsCreate: IByteSegments; implementation uses system.SysUtils, Generics.Collections; type TByteSegments = class(TInterfacedObject, IByteSegments) private FList: TList<TArray<byte>>; function Count: integer; procedure Clear; constructor Create; function GetCapacity: integer; procedure SetCapacity(const Value: integer); function Add(const item: TArray<byte>): integer; public destructor Destroy; override; end; function ByteSegmentsCreate: IByteSegments; begin result := TByteSegments.Create; end; { TByteSegments } function TByteSegments.Add(const item: TArray<byte>): integer; begin result := FList.Add(item); end; procedure TByteSegments.Clear; begin FList.Clear; end; function TByteSegments.Count: integer; begin result := FList.Count; end; constructor TByteSegments.Create; begin FList := TList < TArray < byte >>.Create; inherited Create; end; destructor TByteSegments.Destroy; begin FList.Free; inherited; end; function TByteSegments.GetCapacity: integer; begin result := FList.Capacity; end; procedure TByteSegments.SetCapacity(const Value: integer); begin FList.Capacity := Value; end; end.
{ MIT License Copyright (c) 2017 Marcos Douglas B. Santos 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 James.Format.XML.Clss; {$include james.inc} interface uses Classes, SysUtils, James.Data, Laz2_DOM, laz2_XMLRead, laz2_XMLWrite; type TXMLDocument = Laz2_DOM.TXMLDocument; TDOMNode = Laz2_DOM.TDOMNode; TXMLComponent = class private FDocument: TXMLDocument; public constructor Create(Stream: TStream); constructor Create(Stream: IDataStream); constructor Create(Strings: TStrings); constructor Create(const S: string); destructor Destroy; override; function Document: TXMLDocument; function SaveTo(Stream: TStream): TXMLComponent; function SaveTo(Strings: TStrings): TXMLComponent; function SaveTo(const FileName: string): TXMLComponent; function AsString: string; end; implementation { TXMLComponent } constructor TXMLComponent.Create(Stream: TStream); begin inherited Create; Stream.Position := 0; ReadXMLFile(FDocument, Stream); end; constructor TXMLComponent.Create(Stream: IDataStream); var Buf: TMemoryStream; begin Buf := TMemoryStream.Create; try Stream.Save(Buf); Create(Buf); finally Buf.Free; end; end; constructor TXMLComponent.Create(Strings: TStrings); var Buf: TMemoryStream; begin Buf := TMemoryStream.Create; try Strings.SaveToStream(Buf); Create(Buf); finally Buf.Free; end; end; constructor TXMLComponent.Create(const S: string); var Buf: TStringStream; begin Buf := TStringStream.Create(S); try Create(Buf); finally Buf.Free; end; end; destructor TXMLComponent.Destroy; begin FDocument.Free; inherited Destroy; end; function TXMLComponent.Document: TXMLDocument; begin Result := FDocument; end; function TXMLComponent.SaveTo(Stream: TStream): TXMLComponent; begin Result := Self; WriteXMLFile(FDocument, Stream); Stream.Position := 0; end; function TXMLComponent.SaveTo(Strings: TStrings): TXMLComponent; var Buf: TMemoryStream; begin Result := Self; Buf := TMemoryStream.Create; try SaveTo(Buf); Strings.LoadFromStream(Buf); finally Buf.Free; end; end; function TXMLComponent.SaveTo(const FileName: string): TXMLComponent; var Buf: TMemoryStream; begin Result := Self; Buf := TMemoryStream.Create; try SaveTo(Buf); Buf.SaveToFile(FileName); finally Buf.Free; end; end; function TXMLComponent.AsString: string; var Buf: TStrings; begin Buf := TStringList.Create; try SaveTo(Buf); Result := Buf.Text; finally Buf.Free; end; end; end.
unit BinCoffs; interface uses tfNumerics; function BinomialCoff(N, K: Cardinal): BigCardinal; procedure WriteCoff(N, K: Cardinal); implementation function BinomialCoff(N, K: Cardinal): BigCardinal; var L: Cardinal; begin if N < K then Result:= 0 // Error else begin if K > N - K then K:= N - K; // Optimization Result:= 1; L:= 0; while L < K do begin Result:= Result * (N - L); Inc(L); Result:= Result div L; end; end; end; procedure WriteCoff(N, K: Cardinal); begin Writeln(' C(', N, ',', K, ')= ', BinomialCoff(N, K).ToString); end; end.
unit ActivityRequestUnit; interface uses REST.Json.Types, System.Generics.Collections, JSONNullableAttributeUnit, GenericParametersUnit, NullableBasicTypesUnit, EnumsUnit; type /// <summary> /// Activity /// </summary> /// <remarks> /// https://github.com/route4me/json-schemas/blob/master/Activity.dtd /// </remarks> TActivity = class(TGenericParameters) private [JSONName('activity_id')] [Nullable] FActivityId: NullableString; [JSONName('route_id')] [Nullable] FRouteId: NullableString; [JSONName('route_destination_id')] [Nullable] FRouteDestinationId: NullableInteger; [JSONName('activity_type')] [Nullable] FActivityType: NullableString; [JSONName('member_id')] [Nullable] FMemberId: NullableInteger; [JSONName('activity_message')] [Nullable] FActivityMessage: NullableString; function GetActivityType: TActivityType; procedure SetActivityType(const Value: TActivityType); public /// <remarks> /// Constructor with 0-arguments must be and be public. /// For JSON-deserialization. /// </remarks> constructor Create; override; function Equals(Obj: TObject): Boolean; override; /// <summary> /// Activity ID /// </summary> property Id: NullableString read FActivityId write FActivityId; /// <summary> /// Route ID /// </summary> property RouteId: NullableString read FRouteId write FRouteId; /// <summary> /// Route destination ID /// </summary> property RouteDestinationId: NullableInteger read FRouteDestinationId write FRouteDestinationId; /// <summary> /// Member Id /// </summary> property MemberId: NullableInteger read FMemberId write FMemberId; /// <summary> /// Activity type /// </summary> property ActivityType: TActivityType read GetActivityType write SetActivityType; /// <summary> /// Activity message /// </summary> property ActivityMessage: NullableString read FActivityMessage write FActivityMessage; end; TActivityArray = TArray<TActivity>; TActivityList = TObjectList<TActivity>; implementation { TActivity } constructor TActivity.Create; begin Inherited; FActivityId := NullableString.Null; FRouteId := NullableString.Null; FRouteDestinationId := NullableInteger.Null; FActivityType := NullableString.Null; FMemberId := NullableInteger.Null; FActivityMessage := NullableString.Null; end; function TActivity.Equals(Obj: TObject): Boolean; var Other: TActivity; begin Result := False; if not (Obj is TActivity) then Exit; Other := TActivity(Obj); Result := (FActivityId = Other.FActivityId) and (FRouteId = Other.FRouteId) and (FRouteDestinationId = Other.FRouteDestinationId) and (FActivityType = Other.FActivityType) and (FMemberId = Other.FMemberId) and (FActivityMessage = Other.FActivityMessage); end; function TActivity.GetActivityType: TActivityType; var ActivityType: TActivityType; begin Result := TActivityType.atUnknown; if FActivityType.IsNotNull then for ActivityType := Low(TActivityType) to High(TActivityType) do if (FActivityType = TActivityTypeDescription[ActivityType]) then Exit(ActivityType); end; procedure TActivity.SetActivityType(const Value: TActivityType); begin FActivityType := TActivityTypeDescription[Value]; end; end.
unit ex.CalculatorDisplay; interface uses ex.Operations, SysUtils; type TCalculatorDisplay = class public procedure Press(key: string); Function GetDisplay(): string; end; var display: string; lastArgument: Integer; res: Integer; newArgument: Boolean = false; shouldReset: Boolean = false; lastOperation: TOperationType; //end implementation procedure TCalculatorDisplay.Press(key: string); var currentArgument : Integer; begin if (CompareStr(key, 'C') = 0) then display := '' else if (CompareStr(key, '+') = 0) then begin lastOperation := Plus; lastArgument := strtoint(display); newArgument := true end else begin if (CompareStr(key, '/') = 0) then begin lastOperation := Divide; lastArgument := strtoint(display); newArgument := true; end else begin if (CompareStr(key, '=') = 0) then begin currentArgument := strtoint(display); if (lastOperation = Plus) then display := inttostr (lastArgument+currentArgument); if (lastOperation = Divide) and (currentArgument = 0) then display := 'Division By Zero Error'; shouldReset := true; end else begin if shouldReset then display :=''; shouldReset := false; if newArgument then display :=''; shouldReset := false; display := display + key; end end end end; function TCalculatorDisplay.GetDisplay(): string; begin if (CompareStr(display, EmptyStr) = 0) then Result := '0' else Result := display end; end.
unit HopfieldApp; (*Elric Werst*) interface uses GBMatrixOperations, HopFieldNetwork, Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, Grids, AdvObj, BaseGrid, AdvGrid, Shader, AdvSmoothLabel; type THopfieldForm = class(TForm) sheet: TAdvStringGrid; Shader: TShader; TrainBtn: TButton; matchBtn: TButton; ClearBtn: TButton; EraseBtn: TButton; TitleLbl: TAdvSmoothLabel; procedure FormCreate(Sender: TObject); procedure sheetClickCell(Sender: TObject; ARow, ACol: Integer); procedure TrainBtnClick(Sender: TObject); procedure ClearBtnClick(Sender: TObject); procedure EraseBtnClick(Sender: TObject); procedure matchBtnClick(Sender: TObject); private (*hopfield network*) network : HopfieldNet; (*grid contains boolean values corresponding to the sheet*) grid : T2DBoolean; procedure redrawGrid; end; var HopfieldForm: THopfieldForm; implementation {$R *.dfm} (*clear button event- sets ever cell in the sheet white*) procedure THopfieldForm.ClearBtnClick(Sender: TObject); var r,c : integer; begin for r := 0 to sheet.RowCount-1 do for c := 0 to sheet.ColCount-1 do begin sheet.ColorRect(c,r,c,r,clWhite); grid[r,c] := false; end; sheet.SelectionColor := clWhite; end; (*Erase button event-sets all the weights in the network to zero*) procedure THopfieldForm.EraseBtnClick(Sender: TObject); begin ClearBtnClick(sender); network.EraseMatrix; end; procedure THopfieldForm.FormCreate(Sender: TObject); begin caption := 'Hopfield Network'; TrainBtn.Caption := 'Train'; MatchBtn.Caption := 'Match pattern'; ClearBtn.Caption := 'Clear Table'; EraseBtn.Caption := 'Erase matrix'; TitleLbl.Caption.Text := caption; setLength(grid,sheet.RowCount, sheet.ColCount); network := HopfieldNet.Create(sheet.RowCount*sheet.ColCount); clearBtnClick(sender); network.EraseMatrix; end; (*Match button event*) procedure THopfieldForm.matchBtnClick(Sender: TObject); begin grid := network.MatchMatrix(grid); sheet.SelectionColor := clGreen; redrawGrid; end; (*loops through the grid and sets the cell to either black or white*) procedure THopfieldForm.redrawGrid; var r,c : integer; begin for r := 0 to sheet.RowCount-1 do for c := 0 to sheet.ColCount-1 do if grid[r,c] then sheet.ColorRect(c,r,c,r,clBlack) else sheet.ColorRect(c,r,c,r,clWhite); end; (*Event triggered when the mouse clicks on a cell in the sheet*) procedure THopfieldForm.sheetClickCell(Sender: TObject; ARow, ACol: Integer); begin grid[aRow,aCol] := not grid[aRow,aCol]; if grid[aRow,aCol] then begin sheet.ColorRect(aCol,aRow,aCol,aRow,clBlack); sheet.SelectionColor := clBlack; end else begin sheet.SelectionColor := clWhite; sheet.ColorRect(aCol,aRow,aCol,aRow,clWhite); end; end; (*train button event*) procedure THopfieldForm.TrainBtnClick(Sender: TObject); begin (*trains current pattern displayed*) network.TrainMatrix(grid); end; end.
unit UPipeline; { Copyright (c) 2019 by Herman Schoenfeld Distributed under the MIT software license, see the accompanying file LICENSE or visit http://www.opensource.org/licenses/mit-license.php. This unit is a part of the PascalCoin Project, an infinitely scalable cryptocurrency. Find us here: Web: https://www.pascalcoin.org Source: https://github.com/PascalCoin/PascalCoin THIS LICENSE HEADER MUST NOT BE REMOVED. } {$IFDEF FPC} {$MODE Delphi} {$ENDIF} interface uses Generics.Collections, Classes, SyncObjs, SysUtils, UThread; Type { TPipelineQueue } TPipelineQueue<T> = class(TComponent) private type __TArray_T = TArray<T>; { TStageQueue } TStageQueue = class private FDirty : Boolean; FLock : TMultiReadExclusiveWriteSynchronizer; FItems : TList<T>; function GetDirty : Boolean; procedure SetDirty (AValue : Boolean); function GetItems : TArray<T>; public constructor Create; overload; destructor Destroy; override; property Dirty : Boolean read GetDirty write SetDirty; property Lock : TMultiReadExclusiveWriteSynchronizer read FLock; property Items : TArray<T> read GetItems; end; { TErrorResult } TErrorResult = record Item : T; ErrorMessage : String; end; { TPipelineWorkerThread} TPipelineWorkerThread = class(TPCThread) private FPipeline : TPipelineQueue<T>; FStage : Integer; protected procedure BCExecute; override; public constructor Create(const APipelineQueue : TPipelineQueue<T>; AStage : Integer); overload; end; private FQueues : TArray<TStageQueue>; FMaxWorkerThreads : Integer; FActiveWorkerThreads : Integer; {$IFDEF UNITTESTS} FHistoricalMaxActiveWorkerThreads : Integer; {$ENDIF} procedure Initialize(AStageCount : Integer; AMaxWorkerThreadCount : Integer); procedure Enqueue(AStage : Integer; const AItem : T); overload; procedure EnqueueRange(AStage : Integer; const AItems : array of T); overload; procedure NotifyPipelineAppended(AStage : Integer); function GetStageCount : Integer; inline; protected function ProcessStage(AStageNum : Integer; const AItems : TArray<T>; out TErrors : TArray<TErrorResult>) : TArray<T>; virtual; abstract; procedure HandleErrorItems(const AErrorItems : array of TErrorResult); virtual; abstract; procedure HandleFinishedItems(const AItems : array of T); virtual; abstract; public property StageCount : Integer read GetStageCount; {$IFDEF UNITTESTS} property HistoricalMaxActiveWorkerThreads : Integer read FHistoricalMaxActiveWorkerThreads; {$ENDIF} constructor Create(AOwner : TComponent; AStageCount, AMaxWorkerThreads : Integer); overload; destructor Destroy; override; procedure Enqueue(const AItem : T); overload; procedure EnqueueRange(const AItems : array of T); overload; end; implementation { TPipelineQueue } constructor TPipelineQueue<T>.Create(AOwner : TComponent; AStageCount, AMaxWorkerThreads : Integer); begin inherited Create(AOwner); Initialize(AStageCount, AMaxWorkerThreads); end; destructor TPipelineQueue<T>.Destroy; var i : Integer; begin inherited; for i := 0 to High(FQueues) do FreeAndNil(FQueues[i]); end; procedure TPipelineQueue<T>.Initialize(AStageCount : Integer; AMaxWorkerThreadCount : Integer); var i : integer; begin if AStageCount <= 0 then raise EArgumentException.Create('AStageCount must be greater than 0'); if AMaxWorkerThreadCount <= 0 then raise EArgumentException.Create('AMaxWorkerThreadCount must be greater than 0'); FMaxWorkerThreads := AMaxWorkerThreadCount; FActiveWorkerThreads := 0; SetLength(FQueues, AStagecount); for i := 0 to AStageCount - 1 do begin FQueues[i] := TStageQueue.Create; end; end; procedure TPipelineQueue<T>.Enqueue(AStage : Integer; const AItem : T); begin EnqueueRange(AStage, [AItem]); end; procedure TPipelineQueue<T>.EnqueueRange(AStage : Integer; const AItems : array of T); begin FQueues[AStage].Lock.BeginWrite; try FQueues[AStage].FDirty := True; // Dirty accessed without lock FQueues[AStage].FItems.AddRange(AItems); finally FQueues[AStage].Lock.EndWrite; end; NotifyPipelineAppended(AStage); end; procedure TPipelineQueue<T>.Enqueue(const AItem : T); begin Enqueue(0, AItem); end; procedure TPipelineQueue<T>.EnqueueRange(const AItems : array of T); begin EnqueueRange(0, AItems); end; procedure TPipelineQueue<T>.NotifyPipelineAppended(AStage : Integer); begin if (FActiveWorkerThreads = 0) OR (FActiveWorkerThreads < FMaxWorkerThreads) then begin // Start a new worker thread to process TPipelineWorkerThread.Create(Self, AStage); {$IFDEF UNITTESTS} if (FActiveWorkerThreads > FHistoricalMaxActiveWorkerThreads) then FHistoricalMaxActiveWorkerThreads := FActiveWorkerThreads; {$ENDIF} end; end; function TPipelineQueue<T>.GetStageCount : Integer; begin Result := Length(FQueues); end; { TPipelineQueue<T>.TStageQueue } constructor TPipelineQueue<T>.TStageQueue.Create; begin inherited; FDirty := False; FLock := TMultiReadExclusiveWriteSynchronizer.Create; FItems := TList<T>.Create; end; destructor TPipelineQueue<T>.TStageQueue.Destroy; begin inherited; FreeAndNil(FLock); FreeAndNil(FItems); end; function TPipelineQueue<T>.TStageQueue.GetDirty : Boolean; begin FLock.BeginRead; try Result := FDirty; finally FLock.EndRead; end; end; procedure TPipelineQueue<T>.TStageQueue.SetDirty ( AValue : Boolean ); begin FLock.BeginWrite; try FDirty := AValue; finally FLock.EndWrite; end; end; function TPipelineQueue<T>.TStageQueue.GetItems : TArray<T>; begin begin FLock.BeginRead; try Result := FItems.ToArray; finally FLock.EndRead; end; end; end; { TPipelineQueue<T>.TPipelineWorkerThread } constructor TPipelineQueue<T>.TPipelineWorkerThread.Create(const APipelineQueue : TPipelineQueue<T>; AStage : Integer); begin inherited Create(False); Self.FreeOnTerminate := true; FPipeline := APipelineQueue; FStage := AStage; Inc(FPipeline.FActiveWorkerThreads); end; procedure TPipelineQueue<T>.TPipelineWorkerThread.BCExecute; var i : Integer; LHasMore : Boolean; LIn : TArray<T>; LOut : TArray<T>; LErrorOut : TArray<TErrorResult>; begin repeat // protect against excessive worker threads if FPipeline.FActiveWorkerThreads > FPipeline.FMaxWorkerThreads then exit; // double-check ensure still dirty if not FPipeline.FQueues[FStage].FDirty then exit; // Extract items from pipeline stage FPipeline.FQueues[FStage].Lock.BeginWrite; try LIn := FPipeline.FQueues[FStage].FItems.ToArray; FPipeline.FQueues[FStage].FItems.Clear; FPipeline.FQueues[FStage].FDirty := False; finally FPipeline.FQueues[FStage].Lock.EndWrite; end; // process items LOut := FPipeline.ProcessStage(FStage, LIn, LErrorOut); // process errors if Length(LErrorOut) > 0 then FPipeline.HandleErrorItems(LErrorOut); // send output to next queue (or finish) if FStage = FPipeline.StageCount - 1 then FPipeline.HandleFinishedItems(LOut) else begin // send to next queue FPipeline.EnqueueRange(FStage + 1, LOut); end; // keep working until all stages are completed LHasMore := False; for i := 0 to High(FPipeline.FQueues) do begin if FPipeline.FQueues[i].Dirty then FStage := i; end; until not LHasMore; Dec(FPipeline.FActiveWorkerThreads); end; end.
unit K361038156; {* [RequestLink:361038156] } // Модуль: "w:\common\components\rtl\Garant\Archi_Tests\K361038156.pas" // Стереотип: "TestCase" // Элемент модели: "K361038156" MUID: (4FA138AB0003) // Имя типа: "TK361038156" {$Include w:\common\components\rtl\Garant\Archi_Tests\TestDefine.inc.pas} interface {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3IntfUses , ArchiStorageTest ; type TK361038156 = class(TArchiStorageTest) {* [RequestLink:361038156] } protected function GetFolder: AnsiString; override; {* Папка в которую входит тест } function GetModelElementGUID: AnsiString; override; {* Идентификатор элемента модели, который описывает тест } end;//TK361038156 {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) implementation {$If Defined(nsTest) AND NOT Defined(NoScripts)} uses l3ImplUses , TestFrameWork //#UC START# *4FA138AB0003impl_uses* //#UC END# *4FA138AB0003impl_uses* ; function TK361038156.GetFolder: AnsiString; {* Папка в которую входит тест } begin Result := 'Storage'; end;//TK361038156.GetFolder function TK361038156.GetModelElementGUID: AnsiString; {* Идентификатор элемента модели, который описывает тест } begin Result := '4FA138AB0003'; end;//TK361038156.GetModelElementGUID initialization TestFramework.RegisterTest(TK361038156.Suite); {$IfEnd} // Defined(nsTest) AND NOT Defined(NoScripts) end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.4 2004.02.03 5:43:52 PM czhower Name changes Rev 1.3 1/21/2004 3:11:06 PM JPMugaas InitComponent Rev 1.2 10/26/2003 09:11:50 AM JPMugaas Should now work in NET. Rev 1.1 2003.10.12 4:03:56 PM czhower compile todos Rev 1.0 11/13/2002 07:55:16 AM JPMugaas } unit IdIPMCastBase; interface {$I IdCompilerDefines.inc} //here to flip FPC into Delphi mode uses {$IFDEF WORKAROUND_INLINE_CONSTRUCTORS} Classes, {$ENDIF} IdComponent, IdException, IdGlobal, IdSocketHandle, IdStack; const IPMCastLo = 224; IPMCastHi = 239; type TIdIPMv6Scope = ( IdIPv6MC_InterfaceLocal, { Interface-Local scope spans only a single interface on a node and is useful only for loopback transmission of multicast.} IdIPv6MC_LinkLocal, { Link-Local multicast scope spans the same topological region as the corresponding unicast scope. } IdIPv6MC_AdminLocal, { Admin-Local scope is the smallest scope that must be administratively configured, i.e., not automatically derived from physical connectivity or other, non-multicast-related configuration.} IdIPv6MC_SiteLocal, { Site-Local scope is intended to span a single site. } IdIPv6MC_OrgLocal, {Organization-Local scope is intended to span multiple sites belonging to a single organization.} IdIPv6MC_Global); TIdIPMCValidScopes = 0..$F; TIdIPMCastBase = class(TIdComponent) protected FDsgnActive: Boolean; FMulticastGroup: String; FPort: Integer; FIPVersion: TIdIPVersion; FReuseSocket: TIdReuseSocket; // procedure CloseBinding; virtual; abstract; function GetActive: Boolean; virtual; function GetBinding: TIdSocketHandle; virtual; abstract; procedure Loaded; override; procedure SetActive(const Value: Boolean); virtual; procedure SetMulticastGroup(const Value: string); virtual; procedure SetPort(const Value: integer); virtual; function GetIPVersion: TIdIPVersion; virtual; procedure SetIPVersion(const AValue: TIdIPVersion); virtual; // property Active: Boolean read GetActive write SetActive Default False; property MulticastGroup: string read FMulticastGroup write SetMulticastGroup; property Port: Integer read FPort write SetPort; property IPVersion: TIdIPVersion read GetIPVersion write SetIPVersion default ID_DEFAULT_IP_VERSION; procedure InitComponent; override; public {$IFDEF WORKAROUND_INLINE_CONSTRUCTORS} constructor Create(AOwner: TComponent); reintroduce; overload; {$ENDIF} function IsValidMulticastGroup(const Value: string): Boolean; {These two items are helper functions that allow you to specify the scope for a Variable Scope Multicast Addresses. Some are listed in IdAssignedNumbers as the Id_IPv6MC_V_ constants. You can't use them out of the box in the MulticastGroup property because you need to specify the scope. This provides you with more flexibility than you would get with IPv4 multicasting.} class function SetIPv6AddrScope(const AVarIPv6Addr : String; const AScope : TIdIPMv6Scope ) : String; overload; class function SetIPv6AddrScope(const AVarIPv6Addr : String; const AScope : TIdIPMCValidScopes): String; overload; // property ReuseSocket: TIdReuseSocket read FReuseSocket write FReuseSocket default rsOSDependent; published end; EIdMCastException = Class(EIdException); EIdMCastNoBindings = class(EIdMCastException); EIdMCastNotValidAddress = class(EIdMCastException); EIdMCastReceiveErrorZeroBytes = class(EIdMCastException); const DEF_IPv6_MGROUP = 'FF01:0:0:0:0:0:0:1'; implementation uses IdAssignedNumbers, IdResourceStringsCore, IdStackConsts, SysUtils; { TIdIPMCastBase } {$IFDEF WORKAROUND_INLINE_CONSTRUCTORS} constructor TIdIPMCastBase.Create(AOwner: TComponent); begin inherited Create(AOwner); end; {$ENDIF} function TIdIPMCastBase.GetIPVersion: TIdIPVersion; begin Result := FIPVersion; end; procedure TIdIPMCastBase.InitComponent; begin inherited InitComponent; FMultiCastGroup := Id_IPMC_All_Systems; FIPVersion := ID_DEFAULT_IP_VERSION; FReuseSocket := rsOSDependent; end; function TIdIPMCastBase.GetActive: Boolean; begin Result := FDsgnActive; end; function TIdIPMCastBase.IsValidMulticastGroup(const Value: string): Boolean; begin //just here to prevent a warning from Delphi about an unitialized result Result := False; case FIPVersion of Id_IPv4 : Result := GStack.IsValidIPv4MulticastGroup(Value); Id_IPv6 : Result := GStack.IsValidIPv6MulticastGroup(Value); end; end; procedure TIdIPMCastBase.Loaded; var b: Boolean; begin inherited Loaded; b := FDsgnActive; FDsgnActive := False; Active := b; end; procedure TIdIPMCastBase.SetActive(const Value: Boolean); begin if Active <> Value then begin if not (IsDesignTime or IsLoading) then begin if Value then begin GetBinding; end else begin CloseBinding; end; end else begin // don't activate at designtime (or during loading of properties) {Do not Localize} FDsgnActive := Value; end; end; end; class function TIdIPMCastBase.SetIPv6AddrScope(const AVarIPv6Addr: String; const AScope: TIdIPMv6Scope): String; begin case AScope of IdIPv6MC_InterfaceLocal : Result := SetIPv6AddrScope(AVarIPv6Addr,$1); IdIPv6MC_LinkLocal : Result := SetIPv6AddrScope(AVarIPv6Addr,$2); IdIPv6MC_AdminLocal : Result := SetIPv6AddrScope(AVarIPv6Addr,$4); IdIPv6MC_SiteLocal : Result := SetIPv6AddrScope(AVarIPv6Addr,$5); IdIPv6MC_OrgLocal : Result := SetIPv6AddrScope(AVarIPv6Addr,$8); IdIPv6MC_Global : Result := SetIPv6AddrScope(AVarIPv6Addr,$E); else Result := AVarIPv6Addr; end; end; class function TIdIPMCastBase.SetIPv6AddrScope(const AVarIPv6Addr: String; const AScope: TIdIPMCValidScopes): String; begin //Replace the X in the Id_IPv6MC_V_ constants with the specified scope Result := StringReplace(AVarIPv6Addr,'X',IntToHex(AScope,1),[]); end; procedure TIdIPMCastBase.SetIPVersion(const AValue: TIdIPVersion); begin if AValue <> IPVersion then begin Active := False; FIPVersion := AValue; case AValue of Id_IPv4: FMulticastGroup := Id_IPMC_All_Systems; Id_IPv6: FMulticastGroup := DEF_IPv6_MGROUP; end; end; end; procedure TIdIPMCastBase.SetMulticastGroup(const Value: string); begin if (FMulticastGroup <> Value) then begin if IsValidMulticastGroup(Value) then begin Active := False; FMulticastGroup := Value; end else begin Raise EIdMCastNotValidAddress.Create(RSIPMCastInvalidMulticastAddress); end; end; end; procedure TIdIPMCastBase.SetPort(const Value: integer); begin if FPort <> Value then begin Active := False; FPort := Value; end; end; end.
{ tcutils.pas General utility functions Copyright (C) 2007 Felipe Monteiro de Carvalho This file is part of Turbo Circuit. Turbo Circuit is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. Turbo Circuit 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. Please note that the General Public License version 2 does not permit incorporating Turbo Circuit into proprietary programs. AUTHORS: Felipe Monteiro de Carvalho } unit tcutils; {$mode objfpc}{$H+} interface uses Classes, SysUtils, {StrUtils,} constants; function SeparateString(AString: string; ASeparator: Char): T10Strings; operator = (const A, B: TPoint): Boolean; implementation {@@ Reads a string and separates it in substring using ASeparator to delimite them. Limits: Number of substrings: 10 (indexed 0 to 9) Length of each substring: 255 (they are shortstrings) } function SeparateString(AString: string; ASeparator: Char): T10Strings; var i, CurrentPart: Integer; begin CurrentPart := 0; { Clears the result } for i := 0 to 9 do Result[i] := ''; { Iterates througth the string, filling strings } for i := 1 to Length(AString) do begin if Copy(AString, i, 1) = ASeparator then begin Inc(CurrentPart); { Verifies if the string capacity wasn't exceeded } if CurrentPart > 9 then Exit; end else Result[CurrentPart] := Result[CurrentPart] + Copy(AString, i, 1); end; end; operator = (const A, B: TPoint): Boolean; begin Result := (A.X = B.X) and (A.Y = B.Y); end; end.
{ CoreGraphics - CGFunction.h * Copyright (c) 1999-2002 Apple Computer, Inc. (unpublished) * All rights reserved. } { Pascal Translation: Peter N Lewis, <peter@stairways.com.au>, August 2005 } { Modified for use with Free Pascal Version 210 Please report any bugs to <gpc@microbizz.nl> } {$mode macpas} {$packenum 1} {$macro on} {$inline on} {$calling mwpascal} unit CGFunction; interface {$setc UNIVERSAL_INTERFACES_VERSION := $0342} {$setc GAP_INTERFACES_VERSION := $0210} {$ifc not defined USE_CFSTR_CONSTANT_MACROS} {$setc USE_CFSTR_CONSTANT_MACROS := TRUE} {$endc} {$ifc defined CPUPOWERPC and defined CPUI386} {$error Conflicting initial definitions for CPUPOWERPC and CPUI386} {$endc} {$ifc defined FPC_BIG_ENDIAN and defined FPC_LITTLE_ENDIAN} {$error Conflicting initial definitions for FPC_BIG_ENDIAN and FPC_LITTLE_ENDIAN} {$endc} {$ifc not defined __ppc__ and defined CPUPOWERPC} {$setc __ppc__ := 1} {$elsec} {$setc __ppc__ := 0} {$endc} {$ifc not defined __i386__ and defined CPUI386} {$setc __i386__ := 1} {$elsec} {$setc __i386__ := 0} {$endc} {$ifc defined __ppc__ and __ppc__ and defined __i386__ and __i386__} {$error Conflicting definitions for __ppc__ and __i386__} {$endc} {$ifc defined __ppc__ and __ppc__} {$setc TARGET_CPU_PPC := TRUE} {$setc TARGET_CPU_X86 := FALSE} {$elifc defined __i386__ and __i386__} {$setc TARGET_CPU_PPC := FALSE} {$setc TARGET_CPU_X86 := TRUE} {$elsec} {$error Neither __ppc__ nor __i386__ is defined.} {$endc} {$setc TARGET_CPU_PPC_64 := FALSE} {$ifc defined FPC_BIG_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := TRUE} {$setc TARGET_RT_LITTLE_ENDIAN := FALSE} {$elifc defined FPC_LITTLE_ENDIAN} {$setc TARGET_RT_BIG_ENDIAN := FALSE} {$setc TARGET_RT_LITTLE_ENDIAN := TRUE} {$elsec} {$error Neither FPC_BIG_ENDIAN nor FPC_LITTLE_ENDIAN are defined.} {$endc} {$setc ACCESSOR_CALLS_ARE_FUNCTIONS := TRUE} {$setc CALL_NOT_IN_CARBON := FALSE} {$setc OLDROUTINENAMES := FALSE} {$setc OPAQUE_TOOLBOX_STRUCTS := TRUE} {$setc OPAQUE_UPP_TYPES := TRUE} {$setc OTCARBONAPPLICATION := TRUE} {$setc OTKERNEL := FALSE} {$setc PM_USE_SESSION_APIS := TRUE} {$setc TARGET_API_MAC_CARBON := TRUE} {$setc TARGET_API_MAC_OS8 := FALSE} {$setc TARGET_API_MAC_OSX := TRUE} {$setc TARGET_CARBON := TRUE} {$setc TARGET_CPU_68K := FALSE} {$setc TARGET_CPU_MIPS := FALSE} {$setc TARGET_CPU_SPARC := FALSE} {$setc TARGET_OS_MAC := TRUE} {$setc TARGET_OS_UNIX := FALSE} {$setc TARGET_OS_WIN32 := FALSE} {$setc TARGET_RT_MAC_68881 := FALSE} {$setc TARGET_RT_MAC_CFM := FALSE} {$setc TARGET_RT_MAC_MACHO := TRUE} {$setc TYPED_FUNCTION_POINTERS := TRUE} {$setc TYPE_BOOL := FALSE} {$setc TYPE_EXTENDED := FALSE} {$setc TYPE_LONGLONG := TRUE} uses MacTypes,CGBase,CFBase; {$ALIGN POWER} {! @header CGFunction * A general floating-point function evaluator, using a callback mapping * an arbitrary number of float inputs to an arbitrary number of float * outputs. } type CGFunctionRef = ^SInt32; { an opaque 32-bit type } {! @typedef CGFunctionEvaluateCallback * This callback evaluates a function, using <tt>in</tt> as inputs, and * places the result in <tt>out</tt>. * * @param info * The info parameter passed to CGFunctionCreate. * * @param inData * An array of <tt>domainDimension</tt> floats. * * @param outData * An array of <tt>rangeDimension</tt> floats. } type CGFunctionEvaluateCallback = procedure( info: UnivPtr; inp: {const} Float32Ptr; out: Float32Ptr ); {! @typedef CGFunctionReleaseInfoCallback * This callback releases the info parameter passed to the CGFunction * creation functions when the function is deallocated. * * @param info * The info parameter passed to CGFunctionCreate. } type CGFunctionReleaseInfoCallback = procedure( info: UnivPtr ); {! @typedef CGFunctionCallbacks * Structure containing the callbacks of a CGFunction. * * @field version * The version number of the structure passed to the CGFunction creation * functions. This structure is version 0. * * @field evaluate * The callback used to evaluate the function. * * @field releaseInfo * If non-NULL, the callback used to release the info parameter passed to * the CGFunction creation functions when the function is deallocated. } type CGFunctionCallbacks = record version: UInt32; evaluate: CGFunctionEvaluateCallback; releaseInfo: CGFunctionReleaseInfoCallback; end; {! @function CGFunctionGetTypeID * Return the CFTypeID for CGFunctionRefs. } function CGFunctionGetTypeID: CFTypeID; external name '_CGFunctionGetTypeID'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) {! @function CGFunctionCreate * Create a function. * * @param info * The parameter passed to the callback functions. * * @param domainDimension * The number of inputs to the function. * * @param domain * An array of <tt>2*domainDimension</tt> floats used to specify the * valid intervals of input values. For each <tt>k</tt> from <tt>0</tt> * to <tt>domainDimension - 1</tt>, <tt>domain[2*k]</tt> must be less * than or equal to <tt>domain[2*k+1]</tt>, and the <tt>k</tt>'th input * value <tt>in[k]</tt> will be clipped to lie in the interval * <tt>domain[2*k] <= in[k] <= domain[2*k+1]</tt>. If this parameter is * NULL, then the input values are not clipped. However, it's strongly * recommended that this parameter be specified; each domain interval * should specify reasonable values for the minimum and maximum in each * dimension. * * @param rangeDimension * The number of outputs from the function. * * @param range * An array of <tt>2*rangeDimension</tt> floats used to specify the valid * intervals of output values. For each <tt>k</tt> from <tt>0</tt> to * <tt>rangeDimension - 1</tt>, <tt>range[2*k]</tt> must be less than or * equal to <tt>range[2*k+1]</tt>, and the <tt>k</tt>'th output value * <tt>out[k]</tt> will be clipped to lie in the interval <tt>range[2*k] * <= out[k] <= range[2*k+1]</tt>. If this parameter is NULL, then the * output values are not clipped. However, it's strongly recommended * that this parameter be specified; each range interval should specify * reasonable values for the minimum and maximum in each dimension. * * @param callbacks * A pointer to a CGFunctionCallbacks structure. The function uses these * callbacks to evaluate values. The contents of the callbacks structure * is copied, so, for example, a pointer to a structure on the stack can * be passed in. } function CGFunctionCreate( info: UnivPtr; domainDimension: size_t; domain: {const} Float32Ptr; rangeDimension: size_t; range: {const} Float32Ptr; const (*var*) callbacks: CGFunctionCallbacks ): CGFunctionRef; external name '_CGFunctionCreate'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) {! @function CGFunctionRetain * * Equivalent to <tt>CFRetain(function)</tt>. } function CGFunctionRetain( func: CGFunctionRef ): CGFunctionRef; external name '_CGFunctionRetain'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) {! @function CGFunctionRelease * * Equivalent to <tt>CFRelease(function)</tt>. } procedure CGFunctionRelease( func: CGFunctionRef ); external name '_CGFunctionRelease'; (* AVAILABLE_MAC_OS_X_VERSION_10_2_AND_LATER *) end.
unit functions_file; {$mode objfpc}{$H+} interface uses Classes, SysUtils, U_ExtFileCopy; function fb_FindFiles( var astl_FilesList: TStringList; as_StartDir : String ; const as_FileMask: string ; const ab_CopyAll : Boolean ):Boolean; Function fb_CopyFile ( const as_Source, as_Destination : String ; const ab_AppendFile, ab_CreateBackup : Boolean ):Integer; function fb_InternalCopyDirectory ( const as_Source, as_Destination, as_Mask : String ; const ab_CopyStructure, ab_DestinationIsFile, ab_CopyAll, ab_CreateBackup : Boolean ; const aEfc_FileCopyComponent : TExtFileCopy ):Boolean; function fb_InternalCopyFile ( const as_Source, as_Destination : String ; const ab_DestinationIsFile, ab_CreateBackup : Boolean ; const aEfc_FileCopyComponent : TExtFileCopy ):Boolean; function fb_CreateDirectoryStructure ( const as_DirectoryToCreate : String ) : Boolean ; implementation uses StrUtils, Dialogs, Forms ; // Recursive procedure to build a list of files function fb_FindFiles( var astl_FilesList: TStringList; as_StartDir : String ; const as_FileMask: string ; const ab_CopyAll : Boolean ):Boolean; var SR: TSearchRec; IsFound: Boolean; begin Result := False ; if astl_FilesList = nil then astl_FilesList := TstringList.Create ; if as_StartDir[length(as_StartDir)] <> DirectorySeparator then as_StartDir := as_StartDir + DirectorySeparator; { Build a list of the files in directory as_StartDir (not the directories!) } if ab_copyAll Then try IsFound := FindFirst(as_StartDir + '*', faDirectory, SR) = 0 ; while IsFound do begin if (( SR.Name <> '.' ) and ( SR.Name <> '..' )) and DirectoryExists ( as_StartDir + SR.Name ) then Begin astl_FilesList.Add(as_StartDir + SR.Name); End ; IsFound := FindNext(SR) = 0; Result := True ; end; FindClose(SR); Except FindClose(SR); End ; try IsFound := FindFirst(as_StartDir+as_FileMask, faAnyFile-faDirectory, SR) = 0; while IsFound do begin if FileExists ( as_StartDir + SR.Name ) Then astl_FilesList.Add(as_StartDir + SR.Name); IsFound := FindNext(SR) = 0; Result := True ; end; FindClose(SR); Except FindClose(SR); End ; end; Function fb_CopyFile ( const as_Source, as_Destination : String ; const ab_AppendFile, ab_CreateBackup : Boolean ):Integer; var li_SizeRead,li_SizeWrite,li_TotalW : Longint; li_HandleSource,li_HandleDest, li_pos : integer; ls_FileName, ls_FileExt,ls_Destination : String ; lb_FoundFile,lb_Error : Boolean; lsr_data : Tsearchrec; FBuffer : array[0..2047] of char; begin Result := CST_COPYFILES_ERROR_UNKNOWN ; { FindFirst(as_Source,faanyfile,lsr_data); li_TotalW := 0; findclose(lsr_data); } li_TotalW := 0; li_HandleSource := fileopen(as_Source,fmopenread); ls_Destination := as_Destination ; if ab_AppendFile and fileexists(as_Destination) then Begin FindFirst(as_Destination,faanyfile,lsr_data); li_HandleDest := FileOpen(as_Destination, fmopenwrite ); FileSeek ( li_HandleDest, lsr_data.Size, 0 ); findclose(lsr_data); End Else Begin If fileexists(ls_Destination) then Begin FindFirst(as_Destination,faanyfile,lsr_data); if ( ab_CreateBackup ) Then Begin ls_FileName := lsr_data.Name; ls_FileExt := '' ; li_pos := 1; while ( PosEx ( '.', ls_FileName, li_pos + 1 ) > 0 ) Do li_pos := PosEx ( '.', ls_FileName, li_pos + 1 ); if ( li_Pos > 1 ) Then Begin ls_FileExt := Copy ( ls_FileName, li_pos, length ( ls_FileName ) - li_pos + 1 ); ls_FileName := Copy ( ls_FileName, 1, li_pos - 1 ); End ; li_pos := 0 ; while FileExists ( ls_Destination ) do Begin inc ( li_pos ); ls_Destination := ExtractFilePath ( as_Destination ) + DirectorySeparator + ls_FileName + '-' + IntToStr ( li_pos ) + ls_FileExt ; End End Else Deletefile(as_Destination); findclose(lsr_data); End ; li_HandleDest := filecreate(ls_Destination); end ; lb_FoundFile := False; lb_Error := false; while not lb_FoundFile do begin li_SizeRead := FileRead(li_HandleSource,FBuffer,high ( Fbuffer ) + 1); if li_SizeRead < high ( Fbuffer ) + 1 then lb_FoundFile := True; li_SizeWrite := Filewrite(li_HandleDest,Fbuffer,li_SizeRead); inc( li_TotalW, li_SizeWrite ); if li_SizeWrite < li_SizeRead then lb_Error := True; end; filesetdate(li_HandleDest,filegetdate(li_HandleSource)); fileclose(li_HandleSource); fileclose(li_HandleDest); if lb_Error = False then Begin Result := 0 ; End ; //Application.ProcessMessages ; end; function fb_CreateDirectoryStructure ( const as_DirectoryToCreate : String ) : Boolean ; var lsr_data : Tsearchrec; li_Pos : Integer ; ls_Temp : String ; begin Result := False ; if DirectoryExists ( as_DirectoryToCreate ) Then Begin Result := True; End Else try li_Pos := 1 ; while ( Posex ( DirectorySeparator, as_DirectoryToCreate, li_pos + 1 ) > 1 ) do li_Pos := Posex ( DirectorySeparator, as_DirectoryToCreate, li_pos + 1 ); if ( li_pos > 1 ) Then ls_Temp := Copy ( as_DirectoryToCreate, 1 , li_pos - 1 ) Else Exit ; if not DirectoryExists ( ls_Temp ) Then Begin fb_CreateDirectoryStructure ( ls_Temp ); End ; if DirectoryExists ( ls_Temp ) then Begin FindFirst ( ls_Temp,faanyfile,lsr_data); if ( DirectoryExists ( ls_Temp )) Then try CreateDir ( as_DirectoryToCreate ); Result := True ; except End Else Result := False ; FindClose ( lsr_data ); end; Finally End ; End ; function fb_InternalCopyFile ( const as_Source, as_Destination : String ; const ab_DestinationIsFile, ab_CreateBackup : Boolean ; const aEfc_FileCopyComponent : TExtFileCopy ):Boolean; var lsr_AttrSource : TSearchRec ; begin Result := True ; Result := fb_CreateDirectoryStructure ( as_Destination ); if FileExists ( as_Destination ) Then Begin if ( DirectoryExists ( as_Destination ) ) Then Begin FindFirst ( as_Source, faAnyFile, lsr_AttrSource ); if assigned ( aEfc_FileCopyComponent ) Then Result := aEfc_FileCopyComponent.CopyFile ( as_Source, as_Destination + DirectorySeparator + lsr_AttrSource.Name, ab_DestinationIsFile, ab_CreateBackup ) <> 0 Else Result := fb_CopyFile ( as_Source, as_Destination + DirectorySeparator + lsr_AttrSource.Name, ab_DestinationIsFile, ab_CreateBackup ) <> 0 End Else Begin if assigned ( aEfc_FileCopyComponent ) Then Result := aEfc_FileCopyComponent.CopyFile ( as_Source, as_Destination, ab_DestinationIsFile, ab_CreateBackup ) <> 0 else Result := fb_CopyFile ( as_Source, as_Destination, ab_DestinationIsFile, ab_CreateBackup ) <> 0 End ; End Else if assigned ( aEfc_FileCopyComponent ) Then aEfc_FileCopyComponent.EventualFailure ( CST_COPYFILES_ERROR_DIRECTORY_CREATE, GS_COPYFILES_ERROR_DIRECTORY_CREATE + ' ' + as_Destination ); End ; function fb_InternalCopyDirectory ( const as_Source, as_Destination, as_Mask : String ; const ab_CopyStructure, ab_DestinationIsFile, ab_CopyAll, ab_CreateBackup : Boolean ; const aEfc_FileCopyComponent : TExtFileCopy ):Boolean; var li_Error, li_i : Integer ; ls_Source , ls_destination : String ; lstl_StringList : TStringList ; lsr_AttrSource : Tsearchrec; begin if not fb_CreateDirectoryStructure ( as_Destination ) Then Begin li_Error := CST_COPYFILES_ERROR_DIRECTORY_CREATE ; if assigned ( aEfc_FileCopyComponent ) Then Result := aEfc_FileCopyComponent.EventualFailure ( li_Error, as_Destination ); Exit ; End ; if assigned ( @aEfc_FileCopyComponent ) and Assigned ( @aEfc_FileCopyComponent.OnChange ) Then aEfc_FileCopyComponent.OnChange ( aEfc_FileCopyComponent, as_Source, as_Destination ); Result := True ; lstl_StringList := nil ; if fb_FindFiles ( lstl_StringList, as_Source, as_Mask, ab_CopyAll ) Then for li_i := 0 to lstl_StringList.count - 1 do Begin ls_Source := lstl_StringList.Strings [ li_i ]; FindFirst( ls_Source,faanyfile,lsr_AttrSource); if DirectoryExists ( ls_Source ) Then Begin if ab_CopyStructure then ls_destination := as_Destination + DirectorySeparator + lsr_AttrSource.Name Else ls_destination := as_Destination ; Result := fb_InternalCopyDirectory ( ls_Source, ls_Destination, as_Mask, ab_CopyStructure, ab_DestinationIsFile, ab_CopyAll, ab_CreateBackup, aEfc_FileCopyComponent ); End Else if FileExists ( ls_Source ) Then Begin if assigned ( aEfc_FileCopyComponent ) Then Begin Result := aEfc_FileCopyComponent.InternalDefaultCopyFile ( ls_Source, as_Destination + DirectorySeparator + lsr_AttrSource.Name ); End Else Result := fb_InternalCopyFile ( ls_Source, as_Destination + DirectorySeparator + lsr_AttrSource.Name, ab_DestinationIsFile, ab_CreateBackup, aEfc_FileCopyComponent ); End ; End ; lstl_StringList.Free ; End ; end.
unit ConflictsTree; {$mode objfpc}{$H+} interface uses Classes, SysUtils, sqldb, FileUtil, Forms, Controls, Graphics, Dialogs, ComCtrls, MetaData, ConflictsMeta, Filters, References; type { TConflictsTreeForm } TConflictsTreeForm = class(TForm) TreeView: TTreeView; procedure FormShow(Sender: TObject); procedure TreeViewDblClick(Sender: TObject); public procedure BuildTree; procedure InsertConflicts(ANode: TTreeNode; AID: Integer); end; var ConflictsTreeForm: TConflictsTreeForm; implementation { TConflictsTreeForm } procedure TConflictsTreeForm.InsertConflicts(ANode: TTreeNode; AID: Integer); var i: Integer; Pairs: TConflictPairs; tmpNode: TTreeNode; begin Pairs := ConflictsModule.ConflictPairs[AID]; for i := 0 to High(Pairs) do begin tmpNode := TreeView.Items.AddChild(ANode, Format('Конфликт между %d и %d', [Pairs[i].x, Pairs[i].y])); tmpNode.Data := @ConflictsModule.ConflictPairs[AID][i]; end; end; procedure TConflictsTreeForm.BuildTree; var i: Integer; rootNode, currLvlNode: TTreeNode; begin rootNode := TreeView.Items.Add(nil, 'Конфликты'); //ShowMessage(inttostr(High(Conflicts))); for i := 0 to High(Conflicts) do begin currLvlNode := TreeView.Items.AddChild(rootNode, Format('%d. %s', [i + 1, Conflicts[i].FName])); InsertConflicts(currLvlNode, i); end; rootNode.Expanded := True; end; procedure TConflictsTreeForm.FormShow(Sender: TObject); begin BuildTree; end; procedure TConflictsTreeForm.TreeViewDblClick(Sender: TObject); var a, b: integer; Reference_form: TReferenceForm; begin if TreeView.Selected = nil then Exit; with TPoint(TreeView.Selected.Data^) do begin a := x; b := y; end; Reference_form:= TReferenceForm.Create(Schedule_Table,[a,b]); Reference_form.Show_Table(Schedule_Table); end; {$R *.lfm} end.
{ @abstract(Сервисы Firebird) @author(Николай Войнов) @created(2006-03-27) @lastmod() } unit uFBServices; interface uses SysUtils, Classes, fib, IB_Services; type TServerSettings = record SrvrName: string; UserName: string; UserPass: string; end; TFBServiceClass = class of TpFIBCustomService; TFirebirdServer = class private FServerName: string; FUserName: string; FUserPass: string; FOnTextNotify: TServiceGetTextNotify; FProtocol: TProtocol; FClientLib: string; function CreateServiceWitAuth(ServiceClass: TFBServiceClass): TpFIBCustomService; public constructor Create; destructor Destroy; override; class function Instance(const SrvName, UserName, password: string; Protocol: TProtocol = TCP; const ClientLib: string = 'gds32.dll'): TFirebirdServer; function BackupDB(const DBName, BkName: string; Optns: TBackupOptions = [NoGarbageCollection]): Boolean; function RestoreDB(const BkName, DBName: string; Optns: TRestoreOptions = [CreateNewDB]; APageSize: Integer = 8192): Boolean; function ShutdownDB(const DBName: string; Mode: TShutdownMode = Forced; Timeout: Integer = 0): Boolean; function OnlineDB(const DBName: string): Boolean; function GetDBStat(const DBName: string; Optns: TStatOptions = [HeaderPages]): Boolean; // LimboTransactions, CheckDB, IgnoreChecksum, KillShadows, MendDB, SweepDB, ValidateDB, ValidateFull function ValidateDatabase(const DBName: string; Optns: TValidateOptions = []): Boolean; function CheckDatabase(const DBName: string): Boolean; function SweepDatabase(const DBName: string): Boolean; function MendDatabase(const DBName: string): Boolean; function GetServerPropeties(Optns: TPropertyOptions = [Version, Database]): TpFIBServerProperties; procedure GetServerLog; function GetSecurityService: TpFIBSecurityService; procedure SetupSweepInterval(ASweepInterval: Integer); procedure SetupSQLDialect(ASQLDialect: Integer); procedure SetupPageBuffers(APageBuffers: Integer); procedure SetupReserveSpace(AReserveSpace: Boolean); procedure SetupReadOnly(AReadOnly: Boolean); procedure SetupAsyncMode(AsyncMode: Boolean); procedure ExecActivateShadow; property ServerName: string read FServerName write FServerName; property UserName: string read FUserName write FUserName; property UserPass: string read FUserPass write FUserPass; property Protocol: TProtocol read FProtocol write FProtocol; property ClientLib: string read FClientLib write FClientLib; property OnFbTextNotify: TServiceGetTextNotify read FOnTextNotify write FOnTextNotify; end; implementation { TFirebirdServer } function TFirebirdServer.BackupDB(const DBName, BkName: string; Optns: TBackupOptions): Boolean; var ErrorFound: Boolean; LogStr: string; Srv, DB: String; i: Integer; begin i := pos(':', DBName); if i > 2 then begin // игнорим c:\ Srv := copy(DBName, 1, i - 1); DB := copy(DBName, i + 1, 255); end else begin Srv := ''; DB := DBName; end; with TpFIBBackupService(CreateServiceWitAuth(TpFIBBackupService)) do try DatabaseName := DB; BackupFile.Add(BkName); if Srv <> '' then begin Protocol := TCP; ServerName := Srv; end; LoginPrompt := False; Options := Optns; OnTextNotify := FOnTextNotify; Verbose := Assigned(OnTextNotify); Attach; ServiceStart; ErrorFound := False; while not Eof do begin LogStr := GetNextLine; if not ErrorFound then ErrorFound := pos('GBAK: ERROR', AnsiUpperCase(LogStr)) > 0; end; Result := not ErrorFound; finally if Active then Detach; Free; end; end; function TFirebirdServer.CreateServiceWitAuth(ServiceClass: TFBServiceClass): TpFIBCustomService; begin Result := ServiceClass.Create(nil); Result.ServerName := ServerName; Result.Protocol := Protocol; Result.LibraryName := ClientLib; Result.LoginPrompt := False; Result.Params.Values['user_name'] := UserName; Result.Params.Values['password'] := UserPass; // Result.LibraryName := 'fbclient.dll'; end; function TFirebirdServer.RestoreDB(const BkName, DBName: string; Optns: TRestoreOptions; APageSize: Integer): Boolean; var ErrorFound: Boolean; LogStr: string; begin with TpFIBRestoreService(CreateServiceWitAuth(TpFIBRestoreService)) do try DatabaseName.Add(DBName); BackupFile.Add(BkName); Options := Optns; // PageSize := APageSize; // PageBuffers := APageBuffers; OnTextNotify := FOnTextNotify; Verbose := Assigned(OnTextNotify); Attach; ServiceStart; ErrorFound := False; while not Eof do begin LogStr := GetNextLine; if not ErrorFound then ErrorFound := pos('GBAK: ERROR', AnsiUpperCase(LogStr)) > 0; end; Result := not ErrorFound; finally if Active then Detach; Free; end; end; function TFirebirdServer.ShutdownDB(const DBName: string; Mode: TShutdownMode; Timeout: Integer): Boolean; begin with TpFIBConfigService(CreateServiceWitAuth(TpFIBConfigService)) do try DatabaseName := DBName; Attach; ShutdownDatabase(Mode, Timeout); Result := True; finally if Active then Detach; Free; end; end; function TFirebirdServer.OnlineDB(const DBName: string): Boolean; begin with TpFIBConfigService(CreateServiceWitAuth(TpFIBConfigService)) do try DatabaseName := DBName; Attach; BringDatabaseOnline; Result := True; finally if Active then Detach; Free; end; end; function TFirebirdServer.GetDBStat(const DBName: string; Optns: TStatOptions): Boolean; var LogStr: String; begin with TpFIBStatisticalService(CreateServiceWitAuth(TpFIBStatisticalService)) do try DatabaseName := DBName; Options := Optns; OnTextNotify := FOnTextNotify; Attach; ServiceStart; while not Eof do LogStr := GetNextLine; Result := True; finally if Active then Detach; Free; end; end; function TFirebirdServer.GetServerPropeties(Optns: TPropertyOptions): TpFIBServerProperties; var srvc: TpFIBCustomService; begin srvc := CreateServiceWitAuth(TpFIBServerProperties); Result := TpFIBServerProperties(srvc); with Result do try Options := Optns; Attach; Fetch; finally Detach; end; end; procedure TFirebirdServer.GetServerLog; begin with TpFIBLogService(CreateServiceWitAuth(TpFIBLogService)) do try OnTextNotify := FOnTextNotify; Attach; ServiceStart; while not Eof do GetNextLine; finally Detach; end; end; function TFirebirdServer.GetSecurityService: TpFIBSecurityService; begin Result := TpFIBSecurityService(CreateServiceWitAuth(TpFIBSecurityService)); with Result do try Attach; DisplayUsers; finally Detach; end; end; var FBServerList: TStringList; i: Integer; class function TFirebirdServer.Instance(const SrvName, UserName, password: string; Protocol: TProtocol; const ClientLib: string): TFirebirdServer; var KeyStr: string; KeyIdx: Integer; begin if not Assigned(FBServerList) then FBServerList := TStringList.Create; KeyStr := UpperCase(SrvName + ';' + UserName + ';' + password + ';' + IntToStr(Integer(Protocol)) + ';' + ClientLib); KeyIdx := FBServerList.IndexOf(KeyStr); if KeyIdx < 0 then begin Result := TFirebirdServer.Create; Result.ServerName := SrvName; Result.UserName := UserName; Result.UserPass := password; Result.Protocol := Protocol; Result.ClientLib := ClientLib; KeyIdx := FBServerList.AddObject(KeyStr, Result); end; Result := TFirebirdServer(FBServerList.Objects[KeyIdx]); end; destructor TFirebirdServer.Destroy; begin inherited; end; constructor TFirebirdServer.Create; begin inherited; end; procedure TFirebirdServer.SetupSweepInterval(ASweepInterval: Integer); begin with TpFIBConfigService(CreateServiceWitAuth(TpFIBConfigService)) do try Attach; SetSweepInterval(ASweepInterval); finally Detach; end; end; procedure TFirebirdServer.SetupSQLDialect(ASQLDialect: Integer); begin with TpFIBConfigService(CreateServiceWitAuth(TpFIBConfigService)) do try Attach; SetDBSqlDialect(ASQLDialect); finally Detach; end; end; procedure TFirebirdServer.SetupPageBuffers(APageBuffers: Integer); begin with TpFIBConfigService(CreateServiceWitAuth(TpFIBConfigService)) do try Attach; SetPageBuffers(APageBuffers); finally Detach; end; end; procedure TFirebirdServer.ExecActivateShadow; begin with TpFIBConfigService(CreateServiceWitAuth(TpFIBConfigService)) do try Attach; ActivateShadow; finally Detach; end; end; procedure TFirebirdServer.SetupReserveSpace(AReserveSpace: Boolean); begin with TpFIBConfigService(CreateServiceWitAuth(TpFIBConfigService)) do try Attach; SetReserveSpace(AReserveSpace); finally Detach; end; end; procedure TFirebirdServer.SetupAsyncMode(AsyncMode: Boolean); begin with TpFIBConfigService(CreateServiceWitAuth(TpFIBConfigService)) do try Attach; SetAsyncMode(AsyncMode); finally Detach; end; end; procedure TFirebirdServer.SetupReadOnly(AReadOnly: Boolean); begin with TpFIBConfigService(CreateServiceWitAuth(TpFIBConfigService)) do try Attach; SetReadOnly(AReadOnly); finally Detach; end; end; function TFirebirdServer.ValidateDatabase(const DBName: string; Optns: TValidateOptions): Boolean; var cnt: Integer; begin with TpFIBValidationService(CreateServiceWitAuth(TpFIBValidationService)) do try Options := Optns; DatabaseName := DBName; Attach; ServiceStart; cnt := 0; while not Eof do begin GetNextLine; Inc(cnt); end; finally Detach; end; Result := cnt = 1; end; function TFirebirdServer.CheckDatabase(const DBName: string): Boolean; begin Result := ValidateDatabase(DBName, [CheckDB, ValidateDB, ValidateFull]); end; function TFirebirdServer.MendDatabase(const DBName: string): Boolean; begin Result := ValidateDatabase(DBName, [MendDB, ValidateFull]); end; function TFirebirdServer.SweepDatabase(const DBName: string): Boolean; begin Result := ValidateDatabase(DBName, [SweepDB]); end; initialization finalization if Assigned(FBServerList) then begin for i := 0 to FBServerList.Count - 1 do if Assigned(FBServerList.Objects[i]) then FBServerList.Objects[i].Free; FBServerList.Clear; FBServerList.Free; end; end.
{:: This unit contains the reader and writer classes to support ANSI (*.TXT) files } {$IFNDEF CLRUNIT}unit WPIOHTTAGS; {$ELSE}unit WPTools.IO.HTTAGS; {$ENDIF} { ----------------------------------------------------------------------------- Copyright (C) 2002-2014 by wpcubed GmbH - Author: Julian Ziersch info: http://www.wptools.de mailto:support@wptools.de __ __ ___ _____ _ _____ / / /\ \ \/ _ \/__ \___ ___ | |___ |___ | \ \/ \/ / /_)/ / /\/ _ \ / _ \| / __| / / \ /\ / ___/ / / | (_) | (_) | \__ \ / / \/ \/\/ \/ \___/ \___/|_|___/ /_/ ***************************************************************************** THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. ----------------------------------------------------------------------------- } //****************************************************************************** // WPIOHTTags - WPTools 7 HTML Tag Reader //****************************************************************************** interface {$I WPINC.INC} uses Classes, Sysutils, WPRTEDefs, WPRTEDefsConsts, WPRTEPlatform, Graphics; type {:: This class is used to read text which was saved in HTML format. It will not interpret the HTML tags but creat objects to display them. Please note that any hard paragraph breaks are not used in this mode.<br> To select this reader please choose 'HTMLTAGS' in the property TextLoadFormat. To display the tags the reader creates objects of the type 'wpobjSPANStyle. The setting 'Style' is not used. } TWPHTMLTagReader = class(TWPCustomTextReader) { from WPTools.RTE.Defs } private fUTF8: Boolean; protected class function UseForFilterName(const Filtername: string): Boolean; override; public function Parse(datastream: TStream): TWPRTFDataBlock; override; end; {:: This class is used to save text which was loaded using the TWPHTMLTagReader } TWPHTMLTagWriter = class(TWPCustomTextWriter) { from WPTools.RTE.Defs } private ffirstobj : Boolean; protected class function UseForFilterName(const Filtername: string): Boolean; override; // RTF, HTML or classname public function WriteHeader: Boolean; override; function WriteChar(aChar: Word): Boolean; override; function WriteObject(txtobj: TWPTextObj; par: TParagraph; posinpar: Integer): Boolean; override; function WriteParagraphStart( par: TParagraph; ParagraphType: TWPParagraphType; Style: TWPTextStyle): Boolean; override; function WriteParagraphEnd(par: TParagraph; ParagraphType: TWPParagraphType; NeedNL: Boolean): Boolean; override; end; implementation { ----------------------------------------------------------------------------- } class function TWPHTMLTagWriter.UseForFilterName(const Filtername: string): Boolean; begin Result := inherited UseForFilterName(Filtername) or (CompareText(Filtername, 'XMLTAGS') = 0) or (CompareText(Filtername, 'HTMLTAGS') = 0) or (CompareText(Filtername, 'xsd') = 0); end; function TWPHTMLTagWriter.WriteHeader: Boolean; begin ffirstobj := true; if OptUTF8 then Result := WriteString('<?xml version="1.0" encoding="UTF-8"?>' + #13 + #10) else if OptCodePage=0 then Result := WriteString('<?xml version="1.0" encoding="windows-1250"?>' + #13 + #10) else Result := WriteString('<?xml version="1.0" encoding="windows-' + IntToStr(OptCodePage) + '"?>' + #13 + #10) end; function TWPHTMLTagWriter.WriteChar(aChar: Word): Boolean; var c: AnsiChar; s : AnsiString; begin {$IFDEF DELPHI6ANDUP} if OptUTF8 then begin s := UTF8Encode(WideChar(aChar)); Result := WriteString(s); end else {$ENDIF} begin c := AnsiChar(aChar); Result := WriteString(c); end; end; function TWPHTMLTagWriter.WriteObject(txtobj: TWPTextObj; par: TParagraph; posinpar: Integer): Boolean; var s, t : AnsiString; begin Result := true; if txtobj.ObjType=wpobjCode then begin if ffirstobj and (txtobj.Name = 'xml') then begin // Ignore that .... FNeedEndPar := false; end else begin ffirstobj := false; if wpobjIsOpening in txtobj.Mode then begin s := '<'; t := '>'; end else if wpobjIsClosing in txtobj.Mode then begin s := '</'; t := '>'; end else begin s := '<'; t := '/>'; end; WriteString( s ); {$IFNDEF VER130} if OptUtf8 then WriteString( Utf8Encode(txtobj.Name) ) else {$ENDIF} WriteString( txtobj.Name ); Result := WriteString( t ); end; end else if (txtobj.ObjType=wpobjTextObject) and txtobj.NameIs('SYMBOL') then begin WriteString( '<symbol name="' ); WriteString( txtobj.Source);; WriteString( '"/>' ); end {$IFDEF WPPREMIUM} else if (txtobj.ObjType = wpobjFootnote) and (txtobj.Source = '') then begin _rtfdataobj := RTFDataCollection.Find(wpIsFootnote, wpraOnAllPages, txtobj.Name); if _rtfdataobj <> nil then begin WriteString('<footnote>'); PushBLOCK; WriteBody; PopBLOCK; Result := WriteString('</footnote>'); end else Result := FALSE; exit; end {$ENDIF} ; end; function TWPHTMLTagWriter.WriteParagraphStart( par: TParagraph; ParagraphType: TWPParagraphType; Style: TWPTextStyle): Boolean; begin FNeedEndPar := true; Result := true; end; function TWPHTMLTagWriter.WriteParagraphEnd(par: TParagraph; ParagraphType: TWPParagraphType; NeedNL: Boolean): Boolean; begin if par.next=nil then Result := true else Result := WriteString( #13+#10 ); end; { ----------------------------------------------------------------------------- } class function TWPHTMLTagReader.UseForFilterName(const Filtername: string): Boolean; begin Result := inherited UseForFilterName(Filtername) or (CompareText(Filtername, 'XMLTAGS') = 0) or (CompareText(Filtername, 'HTMLTAGS') = 0) or (CompareText(Filtername, 'xsd') = 0); end; function TWPHTMLTagReader.Parse(datastream: TStream): TWPRTFDataBlock; var D, UTF8Sequence: Integer; V: Integer; ch, ch2, i: Integer; IsUNI: Boolean; Entity : AnsiString; EscapeCloseTag : String; ret: TWPToolsIOErrCode; FReadStringBuffer: TWPStringBuilder; ReadEntity, FIgnoreText, FReadingPRE, FReadingHead, EscapeCloseTagActive, FReadingVariable: Boolean; aTag: TWPCustomHTMLTag; aSpanObj, obj: TWPTextObj; aTagName, aTagText: string; begin Result := inherited Parse(datastream); ret := wpNoError; V := 0; ReadEntity := FALSE; FIgnoreText := FALSE; EscapeCloseTagActive := FALSE; FReadingVariable := FALSE; FReadingHead := FALSE; Entity := ''; EscapeCloseTag := ''; FReadStringBuffer := TWPStringBuilder.Create; try try // We select the body to ad the data SelectRTFData(wpIsBody, wpraIgnored, ''); // and create the first paragraph NewParagraph; repeat IsUNI := FALSE; ch := ReadChar; // http://fundementals.sourceforge.net/cUnicodeCodecs.html if OptUTF8 and (ch >= $80) then // UTF8... begin if ch and $C0 = $80 then begin // UTF8Sequence := 1; end; if ch and $20 = 0 then // 2-byte sequence begin UTF8Sequence := 2; V := ch and $1F; end else if ch and $10 = 0 then // 3-byte sequence begin UTF8Sequence := 3; V := ch and $0F; end else if ch and $08 = 0 then // 4-byte sequence (max needed for Unicode $0-$1FFFFF) begin UTF8Sequence := 4; V := ch and $07; end else begin UTF8Sequence := 1; // error end; for I := 1 to UTF8Sequence - 1 do begin D := ReadChar; if D and $C0 <> $80 then // following byte must start with 10xxxxxx begin // UTF8Sequence := 1; break; end; V := (V shl 6) or (D and $3F); // decode 6 bits end; Ch := V; IsUNI := true; end; if ch <= 0 then break else // Support entities without closing ";" ---------------------------------- if ReadEntity then begin if (ch = Integer(';')) or (ch <= 32) then begin if not FIgnoreText then begin PrintAChar('&'); for ch2 := 1 to Length(Entity) do PrintAChar(Entity[ch2]); end; ReadEntity := FALSE; end else begin Entity := Entity + AnsiChar(ch); ch2 := WPTranslateEntity(Entity); if ch2 > 0 then begin if not FIgnoreText then begin PrintWideChar(WideChar(ch2)); end; Entity := ''; ch := ReadChar; if ch <> Integer(';') then UnReadChar; ReadEntity := FALSE; end; continue; end; end; // ----------------------------------------------------------------------- if EscapeCloseTagActive then begin if lowercase(Char(ch)) = EscapeCloseTag[1] then begin i := 2; while i < Length(EscapeCloseTag) do begin ch2 := ReadChar; if lowercase(Char(ch2)) <> EscapeCloseTag[i] then break; inc(i); end; if i = Length(EscapeCloseTag) then begin UnReadChar(Length(EscapeCloseTag) - 1); EscapeCloseTagActive := FALSE; end else begin UnReadChar(1); for ch := 1 to i do FReadStringBuffer.AppendChar(EscapeCloseTag[ch]); end; end else begin FReadStringBuffer.AppendChar(Char(ch)); end; end else if ch = Integer('&') then begin ch := ReadChar; if ch = Integer('#') then begin ch := ReadInteger; if (ch > 0) and not FIgnoreText then PrintWideChar(WideChar(ch)); ch := ReadChar; if ch <> Integer(';') then UnReadChar; end else begin UnReadChar; ReadEntity := TRUE; Entity := ''; end; end // ---------------- Read Tag --------------------------------------------- else if ch = Integer('<') then begin aTag := TWPCustomHTMLTag.ReadCreate(Self); {$IFDEF WPPREMIUM} if aTag.NameEqual('footnote') then begin if aTag.Typ = wpXMLOpeningTag then begin obj := PrintTextObj(wpobjFootnote, '', '', false, false, false); obj.Name := RTFDataCollection.UniqueName(wpIsFootnote, 'FOOT_'); FWorkRTFData := FRTFDataCollection.Append(wpIsFootnote, wpraOnAllPages, obj.Name); FCurrentParagraph := FWorkRTFData.FirstPar; FParLevel := 0; end else if aTag.Typ = wpXMLClosingTag then begin SelectRTFData(wpIsBody, wpraOnAllPages, ''); FCurrentParagraph := FWorkRTFData.LastPar.LastInnerChild; end; end else if aTag.NameEqual('symbol') then begin PrintTextObj(wpobjTextObject, 'SYMBOL', aTag.ParamString('name',''), false, false, false); end else {$ENDIF} try aTagName := aTag.Name; aTagText := aTag.Text; try {$IFNDEF VER130} if OptUTF8 then aTagName := UTF8Decode(aTagName); aTagText := UTF8Decode(aTagText); {$ENDIF} except end; //aSpanObj := PrintTextObj(wpobjCode, // wpobjSPANStyle, aTagName, Trim(TrimRight(aTagText)), (aTag.Typ in [wpXMLOpeningTag, wpXMLClosingTag]) and not (aTag.NameEqual('hr') or aTag.NameEqual('br') or aTag.NameEqual('img')), aTag.Typ = wpXMLClosingTag, false); if ((aTag.Typ = wpXMLClosingTag) and (aTag.NameEqual('table') or aTag.NameEqual('tr') or aTag.NameEqual('p'))) or ((aTag.Typ = wpXMLOpeningTag) and aTag.NameEqual('table')) then NewParagraph; finally aTag.Free; end; end else if FReadingVariable then FReadStringBuffer.AppendChar(Char(ch)) else if not FReadingHead and not FIgnoreText and (FCurrentParagraph<>nil) and not(FCurrentParagraph.ParagraphType in [wpIsTable, wpIsTableRow]) then if {FReadingPRE and}(ch = 13) then NewParagraph else if (ch <> 13) and (ch > 0) and (ch <> 10) then begin if IsUNI then begin if (ch = $BD) and (OptCodePage <> 1252) then begin PrintWideChar(ch); //V5.24.2 - must be 1/2 end else PrintWideChar(ch); //V5.24.2 end else PrintAChar(AnsiChar(ch), OptCodePage); end; until ret <> wpNoError; ResetReadBuffer; except FReadingError := TRUE; raise; end; finally FReadStringBuffer.Free; end; end; initialization if GlobalWPToolsCustomEnviroment <> nil then begin GlobalWPToolsCustomEnviroment.RegisterReader([TWPHTMLTagReader]); GlobalWPToolsCustomEnviroment.RegisterWriter([TWPHTMLTagWriter]); end; end.
// // ASN1 Parser for Delphi 7 and above // 2015 Alexey Pokroy (apokroy@gmail.com) // // TODO: // Parse stream sequentially (like XML SAX parsers) // Support Indefinite length tags // Support Real tag // Pass test by Yury Strozhevsky http://www.strozhevsky.com/free_docs/free_asn1_testsuite_descr.pdf // // Initial development inspired by XAdES Starter Kit for Microsoft .NET 3.5 2010 Microsoft France // http://www.microsoft.com/france/openness/open-source/interoperabilite_xades.aspx // unit ASNOne; interface uses SysUtils, Classes, MSXml2; type {$IFNDEF UNICODE} RawByteString = AnsiString; UnicodeString = WideString; {$ENDIF} TAsn1TagClasses = ( asn1Universal = 0, asn1Application = 1, asn1ContextSpecific = 2, asn1Private = 3 ); TAsn1TagConstructed = ( asn1Primitive = 0, asn1Constructed = 1 ); TAsn1UniversalTags = ( asn1Eoc = $00, //0: End-of-contents octets asn1Boolean = $01, //1: Boolean asn1Integer = $02, //2: Integer asn1BitString = $03, //3: Bit string asn1OctetString = $04, //4: Byte string asn1NullTag = $05, //5: Null asn1Oid = $06, //6: Object Identifier asn1ObjDescriptor = $07, //7: Object Descriptor asn1External = $08, //8: External asn1Real = $09, //9: Real asn1Enumerated = $0A, //10: Enumerated asn1Embedded_Pdv = $0B, //11: Embedded Presentation Data Value asn1Utf8String = $0C, //12: UTF8 string asn1Sequence = $10, //16: Sequence/sequence of asn1Set = $11, //17: Set/set of asn1NumericString = $12, //18: Numeric string asn1PrintableString = $13, //19: Printable string (ASCII subset) asn1T61String = $14, //20: T61/Teletex string asn1VideotexString = $15, //21: Videotex string asn1IA5String = $16, //22: IA5/ASCII string asn1UtcTime = $17, //23: UTC time asn1GeneralizedTime = $18, //24: Generalized time asn1GraphicString = $19, //25: Graphic string asn1VisibleString = $1A, //26: Visible string (ASCII subset) asn1GeneralString = $1B, //27: General string asn1UniversalString = $1C, //28: Universal string asn1BmpString = $1E //30: Basic Multilingual Plane/Unicode string ); const ASN1_ERROR_NONE = $00; ASN1_ERROR_WARNING = $01; ASN1_ERROR_FATAL = $0F; type PAsn1Item = ^TAsn1Item; TAsn1Item = record TagClass: TAsn1TagClasses; TagConstructedFlag: TAsn1TagConstructed; Tag: TAsn1UniversalTags; TagName: string; Encapsulates: Boolean; Offset: Integer; HeaderLength: Integer; Length: Integer; Bytes: RawByteString; ErrorMessage: string; ErrorSeverity: Integer; end; EAsn1Exception = class(Exception) private FSeverity: Integer; FItem: TAsn1Item; FHasItem: Boolean; public constructor Create(const Msg: string; const Item: PAsn1Item; Severity: Integer); property HasItem: Boolean read FHasItem; property Item: TAsn1Item read FItem; property Severity: Integer read FSeverity; end; type TAsn1ParserOutputOption = ( asn1OutputClass, asn1OutputEncapsulates, asn1OutputOffset, asn1OutputLength, asn1OutputHeaderLength, asn1OutputRaw ); TAsn1ParserOutputOptions = set of TAsn1ParserOutputOption; const Asn1ParserDefaultOutputOptions = [asn1OutputClass, asn1OutputEncapsulates, asn1OutputOffset, asn1OutputLength, asn1OutputHeaderLength, asn1OutputRaw]; type TAsn1Parser = class(TPersistent) private FErrors: TStrings; FExceptionSeverity: Integer; FIgnoreErrors: Boolean; FOutputOptions: TAsn1ParserOutputOptions; FRootName: string; FTree: IXmlDomElement; protected function IsText(S: RawByteString): string; function ParseItem(const Data: RawByteString; var Index: Integer; var Item: TAsn1Item): Boolean; function TryParseItem(const Data: RawByteString; var Item: TAsn1Item): Boolean; procedure Error(const Msg: string; Item: PAsn1Item; Severity: Integer); procedure ParseAsn1Item(ParentNode: IXmlDomElement; Parent: PAsn1Item; const S: RawByteString); public constructor Create; destructor Destroy; override; procedure Parse(const S: RawByteString); overload; procedure Parse(Stream: TStream); overload; procedure ParseFile(const FileName: string); property Errors: TStrings read FErrors; property ExceptionSeverity: Integer read FExceptionSeverity write FExceptionSeverity default ASN1_ERROR_FATAL; property OutputOptions: TAsn1ParserOutputOptions read FOutputOptions write FOutputOptions default Asn1ParserDefaultOutputOptions; property RootName: string read FRootName write FRootName; property Tree: IXmlDomElement read FTree; end; Asn1 = class public class function DecodeUniversalString(const Data: RawByteString): UnicodeString; class function DecodeBMPString(const Data: RawByteString): UnicodeString; class function DecodeUtcTime(const Data: RawByteString): string; class function DecodeTime(const Data: RawByteString): string; class function EncodeOID(const OID: string): RawByteString; end; const Asn1TagClasses: array[TAsn1TagClasses] of string = ( 'Universal', 'Application', 'ContextSpecific', 'Private' ); Asn1TagConstructed: array[TAsn1TagConstructed] of string = ( 'Primitive', 'Constructed' ); Asn1UniversalTags: array[TAsn1UniversalTags] of string = ( 'Eoc', 'Boolean', 'Integer', 'BitString', 'OctetString', 'NullTag', 'Oid', 'ObjDescriptor', 'External', 'Real', 'Enumerated', 'Embedded_Pdv', 'Utf8String', '', '', '', 'Sequence', 'Set', 'NumericString', 'PrintableString', 'T61String', 'VideotexString', 'IA5String', 'UtcTime', 'GeneralizedTime', 'GraphicString', 'VisibleString', 'GeneralString', 'UniversalString', '', 'BmpString' ); implementation uses Base64, ActiveX; const TagNumberMask = $1F; //Bits 5 - 1 TagConstructedFlagMask = $20; //Bit 6 TagClassMask = $C0; //Bits 7 - 8 Bit8Mask = $80; //Indefinite or long form Bits7Mask = $7F; //Bits 7 - 1 { Asn1 } //TODO: Not tested yet class function Asn1.DecodeUniversalString(const Data: RawByteString): UnicodeString; var Char: Word; I: Integer; begin Result := ''; I := 0; while I < Length(Data) do begin Char := Word(Data[I + 2]) shl 8 + Word(Data[I + 3]); Result := Result + WideChar(Char); Inc(I, 4); end; end; class function Asn1.DecodeBMPString(const Data: RawByteString): UnicodeString; var Char: Word; I: Integer; begin Result := ''; I := 1; while I < Length(Data) do begin Char := Word(Data[I]) shl 8 + Word(Data[I + 1]); Result := Result + WideChar(Char); Inc(I, 2); end; end; class function Asn1.DecodeUtcTime(const Data: RawByteString): string; begin if Byte(Data[1]) < $35 then Result := '20' else Result := '19'; Result := Result + Data[1]; Result := Result + Data[2]; Result := Result + '-'; Result := Result + Data[3]; Result := Result + Data[4]; Result := Result + '-'; Result := Result + Data[5]; Result := Result + Data[6]; Result := Result + 'T'; Result := Result + Data[7]; Result := Result + Data[8]; Result := Result + ':'; Result := Result + Data[9]; Result := Result + Data[10]; Result := Result + ':'; Result := Result + Data[11]; Result := Result + Data[12]; Result := Result + 'Z'; end; class function Asn1.DecodeTime(const Data: RawByteString): string; var I: Integer; begin Result := Result + Data[1]; Result := Result + Data[2]; Result := Result + Data[3]; Result := Result + Data[4]; Result := Result + '-'; Result := Result + Data[5]; Result := Result + Data[6]; Result := Result + '-'; Result := Result + Data[7]; Result := Result + Data[8]; Result := Result + 'T'; Result := Result + Data[9]; Result := Result + Data[10]; Result := Result + ':'; Result := Result + Data[11]; Result := Result + Data[12]; Result := Result + ':'; Result := Result + Data[13]; Result := Result + Data[14]; for I := 15 to Length(Data) do begin if Data[I] = 'Z' then Break; Result := Result + Data[I]; end; Result := Result + 'Z'; end; class function Asn1.EncodeOID(const OID: string): RawByteString; var S: RawByteString; C: Integer; procedure MakeBase128(SID: Cardinal; First: Boolean); begin if SID > 127 then MakeBase128( SID div 128, False); SID := SID mod 128; if First then Byte(S[C]) := Byte(SID) else Byte(S[C]) := Bit8Mask or Byte(SID); Inc(C); end; var SID: array of Cardinal; I, P, N: Integer; begin Result := ''; if OID = '' then Exit; N := 0; P := 1; for I := 1 to Length(OID) do if OID[I] = '.' then begin Inc(N); SetLength(SID, N); SID[N - 1] := Cardinal(StrToInt(Copy(OID, P, I - P))); P := I + 1; end; SetLength(SID, N + 1); SID[N] := Cardinal(StrToInt(Copy(OID, P, MaxInt))); SetLength(S, 128); C := 1; if N = 1 then MakeBase128(SID[0] * 40, True) else begin MakeBase128(SID[0] * 40 + SID[1], True); for I := 2 to N do MakeBase128(SID[I], True); end; Result := Copy(S, 1, C - 1); end; { EAsn1Exception } constructor EAsn1Exception.Create(const Msg: string; const Item: PAsn1Item; Severity: Integer); begin FHasItem := Item <> nil; if FHasItem then FItem := Item^; FSeverity := Severity; inherited Create(Msg); end; { TAsn1Parser } constructor TAsn1Parser.Create; begin inherited Create; FExceptionSeverity := ASN1_ERROR_FATAL; FOutputOptions := Asn1ParserDefaultOutputOptions; FRootName := 'Asn1'; FErrors := TStringList.Create; end; destructor TAsn1Parser.Destroy; begin FreeAndNil(FErrors); inherited; end; procedure TAsn1Parser.ParseFile(const FileName: string); const BufferSize = 256; var Stream: TFileStream; S: RawByteString; Buffer: array[0..BufferSize - 1] of Char; Size: Integer; begin Stream := TFileStream.Create(FileName, fmOpenRead); try S := ''; Size := Stream.Read(Buffer, BufferSize); while Size > 0 do begin S := S + Copy(Buffer, 0, Size); Size := Stream.Read(Buffer, BufferSize); end; finally Stream.Free; end; Parse(S); end; procedure TAsn1Parser.Parse(Stream: TStream); var Buffer: RawByteString; begin SetLength(Buffer, Stream.Size - Stream.Position); Stream.Read(Buffer[1], Length(Buffer)); Parse(Buffer); end; procedure TAsn1Parser.Parse(const S: RawByteString); var Dom: IXmlDomDocument; begin CoInitialize(nil); try FErrors.Clear; Dom := CoDomDocument.Create; FTree := Dom.createElement(RootName); Dom.appendChild(FTree); ParseAsn1Item(FTree, nil, S); finally CoUninitialize; end; end; function TAsn1Parser.IsText(S: RawByteString): string; var I: Integer; begin for I := 1 to Length(S) do //Alphas, Digits and punctuation if not (Byte(S[I]) in [$32..$23, $25..$2A, $2C..$3B, $3F..$5D, $5F..$7B, $7D, $A1, $AB, $AD, $B7, $BB, $BF..$C0]) then begin Result := ''; Exit; end; Result := S; end; function TAsn1Parser.TryParseItem(const Data: RawByteString; var Item: TAsn1Item): Boolean; var Dummy: Integer; begin Dummy := 1; try FIgnoreErrors := True; Result := ParseItem(Data, Dummy, Item); except Result := False; end; FIgnoreErrors := False; end; function TAsn1Parser.ParseItem(const Data: RawByteString; var Index: Integer; var Item: TAsn1Item): Boolean; var Buffer, Buffer2: Integer; LengthLength, LengthCounter: Cardinal; begin Result := True; LengthLength := 0; //Tag info Buffer := Byte(Data[Index]); Inc(Index); Item.TagClass := TAsn1TagClasses((Buffer and TagClassMask) shr 6); Item.TagConstructedFlag := TAsn1TagConstructed((Buffer and TagConstructedFlagMask) shr 5); Item.Tag := TAsn1UniversalTags(Buffer and TagNumberMask); Item.Encapsulates := False; if Item.TagClass = asn1Universal then Item.TagName := Asn1UniversalTags[Item.Tag] else Item.TagName := 'Context_' + IntToStr(Integer(Item.Tag)); //Tag length Item.Length := Byte(Data[Index]); Inc(Index); if (Item.Length and Bit8Mask) <> 0 then begin //We have a multiple byte length LengthLength := Item.Length and Bits7Mask; if LengthLength = 0 then begin Error('Indefinite length not supported', @Item, ASN1_ERROR_FATAL); Result := False; end; if LengthLength > 4 then begin Error('Bad length (' + IntToStr(LengthLength) + ') encountered', @Item, ASN1_ERROR_FATAL); Result := False; end; Item.Length := 0; for LengthCounter := 0 to LengthLength - 1 do begin Buffer2 := Byte(Data[Index]); Inc(Index); Item.Length := (Item.Length shl 8) or Buffer2; end; end; Item.HeaderLength := LengthLength + 2; Item.Bytes := Copy(Data, Index, Item.Length); Inc(Index, Item.Length); end; procedure TAsn1Parser.ParseAsn1Item(ParentNode: IXmlDomElement; Parent: PAsn1Item; const S: RawByteString); function GetHexString(const Item: TAsn1Item): RawByteString; var I: Integer; begin Result := ''; for I := 1 to Item.Length do Result := Result + IntToHex(Byte(Item.Bytes[I]), 2); end; //TODO: Very ineffective function BitStringToBytes(const S: string): RawByteString; var I, J, C: Integer; Bits: RawByteString; B: Byte; begin Result := ''; C := 0; I := Length(S); while I > 0 do begin Inc(C); if Length(Result) < C then SetLength(Result, C + 15); if I >= 8 then Bits := Copy(S, I - 7, 8) else Bits := Copy(S, 1, I); B := 0; for J := Length(Bits) downto 1 do begin B := (B shl 1); if Bits[J] = '1' then B := B or 1; end; Byte(Result[C]) := B; Dec(I, 8); end; SetLength(Result, C); end; var Buffer, Buffer2: Integer; I: Integer; ChildNode: IXmlDomElement; Value: WideString; IntegerBuffer: Int64; Item, ProbeItem: TAsn1Item; Index: Integer; Bytes: RawByteString; UnusedBits, Bitmask, BitCounter: Byte; begin Index := 1; while Index < Length(S) do begin Value := ''; if Parent = nil then Item.Offset := Index - 1 else Item.Offset := Index + Parent.Offset + Parent.HeaderLength - 1; ParseItem(S, Index, Item); ChildNode := ParentNode.OwnerDocument.CreateElement(Item.TagName); ParentNode.AppendChild(ChildNode); try if Item.TagConstructedFlag = asn1Constructed then begin ParseAsn1Item(ChildNode, @Item, Item.Bytes); end else begin ProbeItem.Bytes := ''; Value := GetHexString(Item); if Item.TagClass = asn1Universal then begin case Item.Tag of asn1Boolean: begin if Byte(Item.Bytes[1]) = 0 then Value := 'False' else Value := 'True'; end; asn1Oid: begin if Item.Length > 32 then Error('OID length (' + IntToStr(Item.Length) + ') exceeds 32', @Item, ASN1_ERROR_WARNING); Buffer := Byte(Item.Bytes[1]) div 40; Buffer2 := Byte(Item.Bytes[1]) mod 40; if Buffer > 2 then begin //Some OID magic: shave of any excess (>2) of buffer and add to buffer2 Buffer2 := Buffer2 + (Buffer - 2) * 40; Buffer := 2; end; Value := IntToStr(Buffer) + '.' + IntToStr(Buffer2); Buffer := 0; for I := 2 to Item.Length do begin Buffer := (Buffer shl 7) or (Byte(Item.Bytes[I]) and Bits7Mask); if (Byte(Item.Bytes[I]) and Bit8Mask) = 0 then begin Value := Value + '.' + IntToStr(Buffer); Buffer := 0; end; end; end; asn1Integer, asn1Enumerated: begin if Item.Length < 19 then begin IntegerBuffer := 0; for I := 1 to Item.Length do IntegerBuffer := (IntegerBuffer shl 8) or Byte(Item.Bytes[I]); Value := IntToStr(IntegerBuffer); end; end; asn1OctetString: begin if TryParseItem(Item.Bytes, ProbeItem) then begin if (ProbeItem.Length + probeItem.HeaderLength) = Item.Length then begin Item.Encapsulates := True; ParseAsn1Item(ChildNode, @Item, Item.Bytes); end; end; end; asn1Utf8String: Value := Utf8Decode(Copy(Item.Bytes, 1, Item.Length)); asn1UniversalString: Value := Asn1.DecodeUniversalString(Copy(Item.Bytes, 1, Item.Length)); asn1IA5String: Value := Copy(Item.Bytes, 1, Item.Length); asn1BmpString: Value := Asn1.DecodeBMPString(Copy(Item.Bytes, 1, Item.Length)); asn1NumericString: Value := Item.Bytes; asn1VisibleString, //TODO: VisibleString is not the same as PrintableString asn1PrintableString: Value := Copy(Item.Bytes, 1, Item.Length); asn1GeneralizedTime: begin if Item.Length < 15 then Error('Generalized time has to be at least 15 bytes long (' + IntToStr(Item.Length) + ')', @Item, ASN1_ERROR_WARNING) else Value := Asn1.DecodeTime(Item.Bytes); end; asn1UtcTime: begin if Item.Length <> 13 then Error('UTC time has to be 13 bytes long (' + IntToStr(Item.Length) + ')', @Item, ASN1_ERROR_WARNING) else Value := Asn1.DecodeUtcTime(Item.Bytes); end; asn1BitString: begin UnusedBits := Byte(Item.Bytes[1]); if UnusedBits > 7 then Error('Unused bits of bistring out of range [1-7] (' + IntToStr(UnusedBits) + ')', @Item, ASN1_ERROR_WARNING) else begin Value := ''; Bitmask := Bit8Mask; for I := 2 to Item.Length do begin if I <> Item.Length then begin for BitCounter := 0 to 7 do begin if ((Bitmask shr BitCounter) and Byte(Item.Bytes[I])) = 0 then Value := '0' + Value else Value := '1' + Value; end end else begin for BitCounter := 0 to 7 - UnusedBits do begin if ((Bitmask shr BitCounter) and Byte(Item.Bytes[I])) = 0 then Value := '0' + Value else Value := '1' + Value; end; end; end; Bytes := BitStringToBytes(Value); if TryParseItem(Bytes, ProbeItem) and ((ProbeItem.Length + ProbeItem.HeaderLength + 1) = Item.Length) then begin Value := ''; Item.Encapsulates := True; ParseAsn1Item(ChildNode, @Item, Bytes); end; ChildNode.SetAttribute('UnusedBits', UnusedBits); end; end; else if Item.Length > 0 then Error('Unsupported tag (' + IntToStr(Integer(Item.Tag)) + ')', @Item, ASN1_ERROR_WARNING); end; end else begin Value := IsText(Item.Bytes); if Value = '' then Value := GetHexString(Item); end; end; finally if Item.ErrorMessage <> '' then begin ChildNode.setAttribute('Error', Item.ErrorMessage); ChildNode.setAttribute('Severity', Item.ErrorSeverity); end; if (Item.TagConstructedFlag <> asn1Constructed) and (Value <> '') then ChildNode.SetAttribute('Value', Value); if asn1OutputClass in OutputOptions then ChildNode.setAttribute('Class', Asn1TagClasses[Item.TagClass]); if (asn1OutputEncapsulates in OutputOptions) and Item.Encapsulates then ChildNode.setAttribute('Encapsulates', 'True'); if asn1OutputOffset in OutputOptions then ChildNode.setAttribute('Offset', Item.Offset); if asn1OutputLength in OutputOptions then ChildNode.setAttribute('Length', Item.Length); if asn1OutputHeaderLength in OutputOptions then ChildNode.setAttribute('HeaderLength', Item.HeaderLength); if asn1OutputRaw in OutputOptions then ChildNode.setAttribute('Raw', EncodeBase64(Item.Bytes)); end; end; end; procedure TAsn1Parser.Error(const Msg: string; Item: PAsn1Item; Severity: Integer); begin if FIgnoreErrors then Exit; if Item <> nil then begin Item.ErrorMessage := Msg; Item.ErrorSeverity := Severity; end; FErrors.Add(Msg); if Severity >= ExceptionSeverity then raise EAsn1Exception.Create(Msg, Item, Severity); end; end.
unit ADCommander_TLB; // ************************************************************************ // // WARNING // ------- // The types declared in this file were generated from data read from a // Type Library. If this type library is explicitly or indirectly (via // another type library referring to this type library) re-imported, or the // 'Refresh' command of the Type Library Editor activated while editing the // Type Library, the contents of this file will be regenerated and all // manual modifications will be lost. // ************************************************************************ // // $Rev: 52393 $ // File generated on 13.09.2018 14:35:41 from Type Library described below. // ************************************************************************ // // Type Lib: D:\Projects\ADCommander\ElevationMoniker\ADCmdUAC (1) // LIBID: {90228991-EF3C-4C19-A4F2-C58AE05C677A} // LCID: 0 // Helpfile: // HelpString: AD Commander ActiveX Library // DepndLst: // (1) v2.0 stdole, (C:\Windows\SysWOW64\stdole2.tlb) // SYS_KIND: SYS_WIN32 // ************************************************************************ // {$TYPEDADDRESS OFF} // Unit must be compiled without type-checked pointers. {$WARN SYMBOL_PLATFORM OFF} {$WRITEABLECONST ON} {$VARPROPSETTER ON} {$ALIGN 4} interface uses Winapi.Windows, System.Classes, System.Variants, System.Win.StdVCL, Vcl.Graphics, Vcl.OleServer, Winapi.ActiveX; // *********************************************************************// // GUIDS declared in the TypeLibrary. Following prefixes are used: // Type Libraries : LIBID_xxxx // CoClasses : CLASS_xxxx // DISPInterfaces : DIID_xxxx // Non-DISP interfaces: IID_xxxx // *********************************************************************// const // TypeLibrary Major and minor versions ADCommanderMajorVersion = 1; ADCommanderMinorVersion = 0; LIBID_ADCommander: TGUID = '{90228991-EF3C-4C19-A4F2-C58AE05C677A}'; IID_IElevationMoniker: TGUID = '{44B30677-801B-406F-9925-6CB4A2E9B12D}'; CLASS_ElevationMoniker: TGUID = '{B8A05C5C-72B1-4E0F-AE1E-CAE0249B3D89}'; type // *********************************************************************// // Forward declaration of types defined in TypeLibrary // *********************************************************************// IElevationMoniker = interface; IElevationMonikerDisp = dispinterface; // *********************************************************************// // Declaration of CoClasses defined in Type Library // (NOTE: Here we map each CoClass to its Default Interface) // *********************************************************************// ElevationMoniker = IElevationMoniker; // *********************************************************************// // Interface: IElevationMoniker // Flags: (320) Dual OleAutomation // GUID: {44B30677-801B-406F-9925-6CB4A2E9B12D} // *********************************************************************// IElevationMoniker = interface(IUnknown) ['{44B30677-801B-406F-9925-6CB4A2E9B12D}'] procedure RegisterUCMAComponents(AClassID: PWideChar); safecall; procedure UnregisterUCMAComponents(AClassID: PWideChar); safecall; procedure SaveControlEventsList(AFileName: PWideChar; const AXMLStream: IUnknown); safecall; procedure DeleteControlEventsList(AFileName: PWideChar); safecall; function CreateAccessDatabase(AConnectionString: PWideChar; const AFieldCatalog: IUnknown): IUnknown; safecall; function CreateExcelBook(const AFieldCatalog: IUnknown): IDispatch; safecall; procedure SaveExcelBook(const ABook: IDispatch; AFileName: PWideChar; AFormat: Shortint); safecall; end; // *********************************************************************// // DispIntf: IElevationMonikerDisp // Flags: (320) Dual OleAutomation // GUID: {44B30677-801B-406F-9925-6CB4A2E9B12D} // *********************************************************************// IElevationMonikerDisp = dispinterface ['{44B30677-801B-406F-9925-6CB4A2E9B12D}'] procedure RegisterUCMAComponents(AClassID: {NOT_OLEAUTO(PWideChar)}OleVariant); dispid 101; procedure UnregisterUCMAComponents(AClassID: {NOT_OLEAUTO(PWideChar)}OleVariant); dispid 102; procedure SaveControlEventsList(AFileName: {NOT_OLEAUTO(PWideChar)}OleVariant; const AXMLStream: IUnknown); dispid 103; procedure DeleteControlEventsList(AFileName: {NOT_OLEAUTO(PWideChar)}OleVariant); dispid 104; function CreateAccessDatabase(AConnectionString: {NOT_OLEAUTO(PWideChar)}OleVariant; const AFieldCatalog: IUnknown): IUnknown; dispid 105; function CreateExcelBook(const AFieldCatalog: IUnknown): IDispatch; dispid 106; procedure SaveExcelBook(const ABook: IDispatch; AFileName: {NOT_OLEAUTO(PWideChar)}OleVariant; AFormat: Shortint); dispid 107; end; // *********************************************************************// // The Class CoElevationMoniker provides a Create and CreateRemote method to // create instances of the default interface IElevationMoniker exposed by // the CoClass ElevationMoniker. The functions are intended to be used by // clients wishing to automate the CoClass objects exposed by the // server of this typelibrary. // *********************************************************************// CoElevationMoniker = class class function Create: IElevationMoniker; class function CreateRemote(const MachineName: string): IElevationMoniker; end; implementation uses System.Win.ComObj; class function CoElevationMoniker.Create: IElevationMoniker; begin Result := CreateComObject(CLASS_ElevationMoniker) as IElevationMoniker; end; class function CoElevationMoniker.CreateRemote(const MachineName: string): IElevationMoniker; begin Result := CreateRemoteComObject(MachineName, CLASS_ElevationMoniker) as IElevationMoniker; end; end.
//============================================================================= // sgText.pas //============================================================================= // // The Font unit relates to writing text to the screen, // and to loading and styling the associated fonts. // // Change History: // // Version 3.0: // - 2010-03-18: Andtew : Altered font loading to provide mappings for all fonts. // - 2010-02-02: Andrew : Added string to FontAlignment // - 2009-12-07: Andrew : Added font loading and freeing code.. // - 2009-06-05: Andrew : Using sgShared // // Version 2.0: // - 2009-07-14: Andrew : Removed loading and freeing code. // - 2009-01-05: Andrew : Added Unicode rendering // - 2008-12-17: Andrew : Moved all integers to LongInt // - 2008-12-12: Andrew : Added simple string printing // - 2008-12-10: Andrew : Fixed printing of string // // Version 1.1: // - 2008-03-09: Andrew : Added extra exception handling // - 2008-01-30: Andrew : Fixed Print strings for EOL as last char // - 2008-01-25: Andrew : Fixed compiler hints // - 2008-01-21: Andrew : Added Point/Rectangle overloads // - 2008-01-17: Aki + Andrew: Refactor // // Version 1.0: // - Various //============================================================================= ///@module Text ///@static unit sgText; //============================================================================= interface uses sgTypes; //============================================================================= //---------------------------------------------------------------------------- // Font mapping routines //---------------------------------------------------------------------------- /// Loads a font from file with the specified side. Fonts must be freed using /// the FreeFont routine once finished with. Once the font is loaded you /// can set its style using SetFontStyle. Fonts are then used to draw and /// measure text in your programs. /// /// @lib /// /// @class Font /// @constructor /// @csn initWithFontName:%s andSize:%s function LoadFont(fontName: String; size: LongInt): Font; /// Frees the resources used by the loaded Font. /// /// @lib /// /// @class Font /// @dispose procedure FreeFont(var fontToFree: Font); //---------------------------------------------------------------------------- // Font mapping routines //---------------------------------------------------------------------------- /// Loads and returns a font that can be used to draw text. The supplied /// `filename` is used to locate the font to load. The supplied `name` indicates the /// name to use to refer to this Font in SwinGame. The `Font` can then be /// retrieved by passing this `name` to the `FontNamed` function. /// /// @lib /// /// @class Map /// @constructor /// @csn initWithName:%s forFilename:%s andSize:%s function MapFont(name, filename: String; size: LongInt): Font; /// Determines if SwinGame has a font loaded for the supplied name. /// This checks against all fonts loaded, those loaded without a name /// are assigned the filename as a default. /// /// @lib function HasFont(name: String): Boolean; /// Determines the name that will be used for a font loaded with /// the indicated fontName and size. /// /// @lib function FontNameFor(fontName: String; size: LongInt): String; /// Returns the `Font` that has been loaded with the specified name, /// and font size using `LoadFont`. /// /// @lib FontNamedWithSize function FontNamed(name: String; size: LongInt): Font; overload; /// Returns the `Font` that has been loaded with the specified name, /// see `MapFont`. /// /// @lib function FontNamed(name: String): Font; overload; /// Releases the SwinGame resources associated with the font of the /// specified `name`. /// /// @lib procedure ReleaseFont(name: String); /// Releases all of the fonts that have been loaded. /// /// @lib procedure ReleaseAllFonts(); //---------------------------------------------------------------------------- /// Alters the style of the font. /// /// @lib /// @class Font /// @setter FontStyle procedure FontSetStyle(font: Font; value: FontStyle); /// Returns the style settings for the font. /// /// @lib /// @class Font /// @getter FontStyle function FontFontStyle(font: Font): FontStyle; /// @lib procedure DrawTextOnScreen(theText: String; textColor: Color; theFont: Font; x, y: LongInt); overload; /// @lib DrawTextOnScreenAtPoint procedure DrawTextOnScreen(theText: String; textColor: Color; theFont: Font; const pt: Point2D); overload; /// @lib procedure DrawText(theText: String; textColor: Color; theFont: Font; x, y: Single); overload; /// @lib DrawTextAtPoint procedure DrawText(theText: String; textColor: Color; theFont: Font; const pt: Point2D); overload; {1.1} { procedure DrawUnicodeOnScreen(theText: WideString; textColor: Color; theFont: Font; x, y: LongInt); overload; procedure DrawUnicodeOnScreen(theText: WideString; textColor: Color; theFont: Font; const pt: Point2D); overload; procedure DrawUnicode(theText: WideString; textColor: Color; theFont: Font; x, y: Single); overload; procedure DrawUnicode(theText: WideString; textColor: Color; theFont: Font; const pt: Point2D); overload; } /// @lib procedure DrawTextLinesOnScreen(theText: String; textColor, backColor: Color; theFont: Font; align: FontAlignment; x, y, w, h: LongInt); overload; /// @lib DrawTextLinesInRectOnScreen procedure DrawTextLinesOnScreen(theText: String; textColor, backColor: Color; theFont: Font; align: FontAlignment; const withinRect: Rectangle); overload; /// @lib procedure DrawTextLines(theText: String; textColor, backColor: Color; theFont: Font; align: FontAlignment; x, y: Single; w, h: LongInt); overload; /// @lib DrawTextLinesInRect procedure DrawTextLines(theText: String; textColor, backColor: Color; theFont: Font; align: FontAlignment; const withinRect: Rectangle); overload; {1.1} /// @lib DrawSimpleText procedure DrawText(theText: String; textColor: Color; x, y: Single); overload; /// @lib DrawSimpleTextPt procedure DrawText(theText: String; textColor: Color; const pt: Point2D); overload; /// @lib DrawSimpleTextOnScreen procedure DrawTextOnScreen(theText: String; textColor: Color; x, y: Single); overload; /// @lib DrawSimpleTextOnBitmap procedure DrawText(dest: Bitmap; theText: String; textColor: Color; x, y: Single); overload; /// @lib DrawTextOnBitmap procedure DrawText(dest: Bitmap; theText: String; textColor: Color; theFont: Font; x, y: LongInt); overload; /// @lib DrawTextLinesOnBitmap procedure DrawTextLines(dest: Bitmap; theText: String; textColor, backColor: Color; theFont: Font; align: FontAlignment; x, y, w, h: LongInt); overload; /// @lib DrawTextOnBitmapAtPoint procedure DrawText(dest: Bitmap; theText: String; textColor: Color; theFont: Font; const pt: Point2D); overload; /// @lib DrawTextLinesInRectOnBitmap procedure DrawTextLines(dest: Bitmap; theText: String; textColor, backColor: Color; theFont: Font; align: FontAlignment; const withinRect: Rectangle); overload; /// @lib /// @class Font /// @method TextWidth function TextWidth(theFont: Font; theText: String): LongInt; overload; /// @lib /// @class Font /// @method TextHeight function TextHeight(theFont: Font; theText: String): LongInt; overload; { function TextWidth(theText: WideString; theFont: Font): LongInt; overload; function TextHeight(theText: WideString; theFont: Font): LongInt; overload; } /// @lib procedure DrawFramerate(x, y: LongInt; font: Font); overload; /// @lib DrawFrameRateWithSimpleFont procedure DrawFramerate(x, y: LongInt); overload; /// Returns the font alignment for the passed in character (l = left. r = right, c = center). /// /// @lib function TextAlignmentFrom(str: String): FontAlignment; //============================================================================= implementation uses SysUtils, Classes, stringhash, // libsrc sgCore, sgGeometry, sgGraphics, sgCamera, sgShared, sgResources, sgImages, SDL, SDL_TTF, SDL_gfx; //============================================================================= const EOL = LineEnding; // from sgShared var _Fonts: TStringHash; //---------------------------------------------------------------------------- function LoadFont(fontName: String; size: LongInt): Font; begin result := MapFont(FontNameFor(fontName, size), fontName, size); end; procedure FreeFont(var fontToFree: Font); begin if Assigned(fontToFree) then begin {$IFDEF TRACE} Trace('Resources', 'IN', 'FreeFont', 'After calling free notifier'); {$ENDIF} try {$IFDEF TRACE} Trace('Resources', 'IN', 'FreeFont', 'Before calling close font'); {$ENDIF} TTF_CloseFont(fontToFree); CallFreeNotifier(fontToFree); fontToFree := nil; {$IFDEF TRACE} Trace('Resources', 'IN', 'FreeFont', 'At end of free font'); {$ENDIF} except RaiseException('Unable to free the specified font'); exit; end; end; end; //---------------------------------------------------------------------------- function MapFont(name, filename: String; size: LongInt): Font; var obj: tResourceContainer; fnt: Font; function _DoLoadFont(fontName: String; size: LongInt): Font; var filename: String; begin filename := fontName; if not FileExists(filename) then begin filename := PathToResource(filename, FontResource); if not FileExists(filename) then begin RaiseException('Unable to locate font ' + fontName); exit; end; end; result := TTF_OpenFont(PChar(filename), size); if result = nil then begin RaiseException('LoadFont failed: ' + TTF_GetError()); exit; end; end; begin if _Fonts.containsKey(name) then begin result := FontNamed(name); exit; end; fnt := _DoLoadFont(filename, size); obj := tResourceContainer.Create(fnt); if not _Fonts.setValue(name, obj) then raise Exception.create('Error loaded Font resource twice, ' + name); result := fnt; end; function HasFont(name: String): Boolean; begin result := _Fonts.containsKey(name); end; function FontNameFor(fontName: String; size: LongInt): String; begin result := fontName + '|' + IntToStr(size); end; function FontNamed(name: String; size: LongInt): Font; begin result := FontNamed(FontNameFor(name, size)); end; function FontNamed(name: String): Font; var tmp : TObject; begin tmp := _Fonts.values[name]; if assigned(tmp) then result := Font(tResourceContainer(tmp).Resource) else result := nil; end; procedure ReleaseFont(name: String); var fnt: Font; begin fnt := FontNamed(name); if (assigned(fnt)) then begin _Fonts.remove(name).free(); FreeFont(fnt); end; end; procedure ReleaseAllFonts(); begin ReleaseAll(_Fonts, @ReleaseFont); end; //---------------------------------------------------------------------------- /// Sets the style of the passed in font. This is time consuming, so load /// fonts multiple times and set the style for each if needed. /// /// @param font: The font to set the style of /// @param style: The new style for the font, values can be read together /// /// Side Effects: /// - The font's style is changed procedure FontSetStyle(font: Font; value: FontStyle); begin if not Assigned(font) then begin RaiseException('No font supplied'); exit; end; TTF_SetFontStyle(font, LongInt(value)); end; function FontFontStyle(font: Font): FontStyle; begin if not Assigned(font) then begin RaiseException('No font supplied'); exit; end; result := FontStyle(TTF_GetFontStyle(font)); end; function IsSet(toCheck, checkFor: FontAlignment): Boolean; overload; begin result := (LongInt(toCheck) and LongInt(checkFor)) = LongInt(checkFor); end; /// This function prints "str" with font "font" and color "clrFg" /// * onto a rectangle of color "clrBg". /// * It does not pad the text. procedure PrintStrings(dest: PSDL_Surface; font: Font; str: String; rc: PSDL_Rect; clrFg, clrBg:Color; flags:FontAlignment); var sText: Bitmap; temp: PSDL_Surface; lineSkip, width, height: LongInt; lines: Array of String; subStr: String; n, w, h, i: LongInt; rect: TSDL_Rect; colorFG: TSDL_Color; bgTransparent: Boolean; begin if Length(str) = 0 then exit; if dest = nil then begin RaiseException('Error Printing Strings: There was no surface.'); exit; end; colorFG := ToSDLColor(clrFg); bgTransparent := TransparencyOf(clrBg) < 255; // If there's nothing to draw, return NULL if (Length(str) = 0) or (font = nil) then exit; // This is the surface that everything is printed to. lineSkip := TTF_FontLineSkip( font ); width := rc^.w; height := 10; SetLength(lines, 1); // Break the String into its lines: n := -1; i := 0; while n <> 0 do begin // Get until either "\n" or "\0": n := Pos(eol, str); //Copy all except EOL if n = 0 then subStr := str else if n = 1 then subStr := ' ' else subStr := Copy(str, 1, n - 1); if Length(subStr) < 1 then subStr := ' '; //Remove the line from the original string if n <> 0 then begin str := Copy( str, n + Length(eol), Length(str)); //excess not copied... end; i := i + 1; SetLength(lines, i); lines[i - 1] := subStr; w := 0; // Get the size of the rendered text. if Length(subStr) > 0 then TTF_SizeText(font, PChar(subStr), w, height); if w > width then width := w; end; if (width = 0) or (height = 0) then exit; // Length(lines) = Number of Lines. // we assume that height is the same for all lines. height := (Length(lines) - 1) * lineSkip + height; sText := CreateBitmap(width, height); ClearSurface(sText, clrBg); // Actually render the text: for i := 0 to High(lines) do begin // The rendered text: if length(lines[i]) = 0 then continue; temp := TTF_RenderText_Blended(font, PChar(lines[i]), colorFG); //temp := TTF_RenderUNICODE_Blended(font, PUint16(lines[i]), colorFG); // Put it on the surface: if IsSet(flags, AlignLeft) or (not (IsSet(flags, AlignCenter) or IsSet(flags, AlignRight))) then begin // If it's specifically LEFT or none of the others: rect := NewSDLRect(0,i*lineSkip,0,0); end else if IsSet(flags, AlignCenter) then begin w := 0; h := 0; TTF_SizeText(font, PChar(lines[i]), w, h); rect := NewSDLRect(width div 2 - w div 2, i * lineSkip, 0, 0) end else if IsSet(flags, AlignRight) then begin // Get w and h from the size of the text... w := 0; h := 0; TTF_SizeText(font, PChar(lines[i]), w, h); rect := NewSDLRect(rc^.w - w, i * lineSkip, 0, 0); end else begin RaiseException('Invalid font alignment'); exit; end; // Render the current line. Ignore alpha in this draw if bgTransparent then SDL_SetAlpha(temp, 0, SDL_ALPHA_TRANSPARENT); SDL_BlitSurface(temp, nil, sText^.surface, @rect); // Clean up: SDL_FreeSurface(temp); end; // Draw the text on top of that: rect.x := 0; rect.y := 0; rect.w := rc^.w; rect.h := rc^.h; if (not bgTransparent) then SDL_SetAlpha(sText^.surface, 0, SDL_ALPHA_TRANSPARENT); SDL_BlitSurface(sText^.surface, @rect, dest, rc ); FreeBitmap(sText); end; /// This function prints "str" with font "font" and color "clrFg" /// * onto a rectangle of color "clrBg". /// * It does not pad the text. procedure PrintWideStrings(dest: PSDL_Surface; font: Font; str: WideString; rc: PSDL_Rect; clrFg, clrBg:Color; flags:FontAlignment); var sText: Bitmap; temp: PSDL_Surface; lineSkip, width, height: LongInt; lines: Array of String; subStr: String; n, w, h, i: LongInt; rect: TSDL_Rect; colorFG: TSDL_Color; bgTransparent: Boolean; begin if dest = nil then begin RaiseException('Error Printing Strings: There was no surface.'); exit; end; colorFG := ToSDLColor(clrFg); bgTransparent := TransparencyOf(clrBg) < 255; // If there's nothing to draw, return NULL if (Length(str) = 0) or (font = nil) then exit; // This is the surface that everything is printed to. lineSkip := TTF_FontLineSkip( font ); width := rc^.w; height := 10; SetLength(lines, 1); // Break the String into its lines: n := -1; i := 0; while n <> 0 do begin // Get until either "\n" or "\0": n := Pos(eol, str); //Copy all except EOL if n = 0 then subStr := str else if n = 1 then subStr := ' ' else subStr := Copy(str, 1, n - 1); if Length(subStr) < 1 then subStr := ' '; //Remove the line from the original string if n <> 0 then begin str := Copy( str, n + Length(eol), Length(str)); //excess not copied... end; i := i + 1; SetLength(lines, i); lines[i - 1] := subStr; w := 0; // Get the size of the rendered text. if Length(subStr) > 0 then TTF_SizeUNICODE(font, PUint16(subStr), w, height); //Keep widest rendered text size if w > width then width := w; end; // Length(lines) = Number of Lines. // we assume that height is the same for all lines. height := (Length(lines) - 1) * lineSkip + height; sText := CreateBitmap(width, height); ClearSurface(sText, clrBg); // Actually render the text: for i := 0 to High(lines) do begin if length(lines[i]) = 0 then continue; // The rendered text: //temp := TTF_RenderText_Blended(font, PUint16(lines[i]), colorFG); temp := TTF_RenderUNICODE_Blended(font, PUint16(lines[i]), colorFG); // Put it on the surface: if IsSet(flags, AlignLeft) or (not (IsSet(flags, AlignCenter) or IsSet(flags, AlignRight))) then begin // If it's specifically LEFT or none of the others: rect := NewSDLRect(0,i*lineSkip,0,0); end else if IsSet(flags, AlignCenter) then begin w := 0; h := 0; TTF_SizeUNICODE(font, PUint16(lines[i]), w, h); rect := NewSDLRect(width div 2 - w div 2, i * lineSkip, 0, 0) end else if IsSet(flags, AlignRight) then begin w := 0; h := 0; TTF_SizeUNICODE(font, PUint16(lines[i]), w, h); rect := NewSDLRect(width - w, i * lineSkip, 0, 0); end else begin RaiseException('Invalid font alignment'); exit; end; // Render the current line. Ignore alpha in this draw if bgTransparent then SDL_SetAlpha(temp, 0, SDL_ALPHA_TRANSPARENT); SDL_BlitSurface(temp, nil, sText^.surface, @rect); // Clean up: SDL_FreeSurface(temp); end; // Draw the text on top of that: rect.x := 0; rect.y := 0; rect.w := rc^.w; rect.h := rc^.h; if (not bgTransparent) then SDL_SetAlpha(sText^.surface, 0, SDL_ALPHA_TRANSPARENT); SDL_BlitSurface(sText^.surface, @rect, dest, rc ); FreeBitmap(sText); end; /// Draws texts to the destination bitmap. Drawing text is a slow operation, /// and drawing it to a bitmap, then drawing the bitmap to screen is a /// good idea. Do not use this technique if the text changes frequently. /// /// @param dest: The destination bitmap - not optimised! /// @param theText: The text to be drawn onto the destination /// @param textColor: The color to draw the text /// @param theFont: The font used to draw the text /// @param x,y: The x,y location to draw the text at (top left) /// /// Side Effects: /// - The text is drawn in the specified font, at the indicated location /// in the destination bitmap. procedure DrawText(dest: Bitmap; theText: String; textColor: Color; theFont: Font; x, y: LongInt); overload; var rect: TSDL_Rect; begin if theFont = nil then begin RaiseException('The specified font is nil'); exit; end; if dest = nil then begin RaiseException('Cannot draw text, as no destination was supplied'); exit; end; rect := NewSDLRect(x + 1, y + 1, TextWidth(theFont, theText) + 2, TextHeight(theFont, theText) + 2); PrintStrings(dest^.surface, theFont, theText, @rect, textColor, ColorTransparent, AlignLeft); end; procedure DrawUnicode(dest: Bitmap; theText: WideString; textColor: Color; theFont: Font; x, y: LongInt); overload; var rect: TSDL_Rect; begin if theFont = nil then begin RaiseException('The specified font is nil'); exit; end; if dest = nil then begin RaiseException('Cannot draw text, as no destination was supplied'); exit; end; rect := NewSDLRect(x, y, TextWidth(theFont, theText), TextHeight(theFont, theText)); PrintWideStrings(dest^.surface, theFont, theText, @rect, textColor, ColorTransparent, AlignLeft); end; procedure DrawText(dest: Bitmap; theText: String; textColor: Color; theFont: Font; const pt: Point2D); overload; begin DrawText(dest, theText, textColor, theFont, Round(pt.x), Round(pt.y)); end; procedure DrawUnicode(dest: Bitmap; theText: WideString; textColor: Color; theFont: Font; const pt: Point2D); overload; begin DrawUnicode(dest, theText, textColor, theFont, Round(pt.x), Round(pt.y)); end; /// Draws multiple lines of text to the destination bitmap. This is a very /// slow operation, so if the text is not frequently changing save it to a /// bitmap and draw that bitmap to screen instead. /// /// @param dest: The destination bitmap - not optimised! /// @param theText: The text to be drawn onto the destination /// @param textColor: The color to draw the text /// @param backColor: The color to draw behind the text /// @param theFont: The font used to draw the text /// @param align: The alignment for the text in the region /// @param x,y: The x,y location to draw the text at (top left) /// @param w, h: The width and height of the region to draw inside /// /// Side Effects: /// - The text is drawn in the specified font, at the indicated location /// in the destination bitmap. procedure DrawTextLines(dest: Bitmap; theText: String; textColor, backColor: Color; theFont: Font; align: FontAlignment; x, y, w, h: LongInt); overload; var rect: TSDL_Rect; begin rect := NewSDLRect(x + 1, y + 1, w - 2, h - 2); PrintStrings(dest^.surface, theFont, theText, @rect, textColor, backColor, align); end; procedure DrawTextLines(dest: Bitmap; theText: String; textColor, backColor: Color; theFont: Font; align: FontAlignment; const withinRect: Rectangle); overload; begin DrawTextLines(dest, theText, textColor, backColor, theFont, align, Round(withinRect.x), Round(withinRect.y), withinRect.width, withinRect.height); end; /// Draws multiple lines of text to the screen. This is a very /// slow operation, so if the text is not frequently changing save it to a /// bitmap and draw that bitmap to screen instead. /// /// @param theText: The text to be drawn onto the destination /// @param textColor: The color to draw the text /// @param backColor: The color to draw behind the text /// @param theFont: The font used to draw the text /// @param align: The alignment for the text in the region /// @param x,y: The x,y location to draw the text at (top left) /// @param w, h: The width and height of the region to draw inside /// /// Side Effects: /// - The text is drawn in the specified font, at the indicated location /// on the screen. procedure DrawTextLinesOnScreen(theText: String; textColor, backColor: Color; theFont: Font; align: FontAlignment; x, y, w, h: LongInt); overload; begin DrawTextLines(screen, theText, textColor, backColor, theFont, align, x, y, w, h); end; procedure DrawTextLinesOnScreen(theText: String; textColor, backColor: Color; theFont: Font; align: FontAlignment; const withinRect: Rectangle); overload; begin DrawTextLines(screen, theText, textColor, backColor, theFont, align, Round(withinRect.x), Round(withinRect.y), withinRect.width, withinRect.height); end; procedure DrawTextLines(theText: String; textColor, backColor: Color; theFont: Font; align: FontAlignment; x, y:Single; w, h: LongInt); overload; begin DrawTextLines(screen, theText, textColor, backColor, theFont, align, ToScreenX(x), ToScreenY(y), w, h); end; procedure DrawTextLines(theText: String; textColor, backColor: Color; theFont: Font; align: FontAlignment; const withinRect: Rectangle); overload; begin DrawTextLines(screen, theText, textColor, backColor, theFont, align, ToScreenX(withinRect.x), ToScreenY(withinRect.y), withinRect.width, withinRect.height); end; /// Draws texts to the screen. Drawing text is a slow operation, /// and drawing it to a bitmap, then drawing the bitmap to screen is a /// good idea. Do not use this technique if the text changes frequently. /// /// @param theText: The text to be drawn onto the screen /// @param textColor: The color to draw the text /// @param theFont: The font used to draw the text /// @param x,y: The x,y location to draw the text at (top left) /// /// Side Effects: /// - The text is drawn in the specified font, at the indicated location /// on the screen. procedure DrawTextOnScreen(theText: String; textColor: Color; theFont: Font; x, y: LongInt); begin DrawText(screen, theText, textColor, theFont, x, y); end; procedure DrawTextOnScreen(theText: String; textColor: Color; theFont: Font; const pt: Point2D); overload; begin DrawText(screen, theText, textColor, theFont, Round(pt.x), Round(pt.y)); end; procedure DrawUnicodeOnScreen(theText: WideString; textColor: Color; theFont: Font; x, y: LongInt); overload; begin DrawUnicode(screen, theText, textColor, theFont, x, y); end; procedure DrawUnicodeOnScreen(theText: WideString; textColor: Color; theFont: Font; const pt: Point2D); overload; begin DrawUnicode(screen, theText, textColor, theFont, Round(pt.x), Round(pt.y)); end; procedure DrawText(theText: String; textColor: Color; theFont: Font; x, y: Single); begin DrawText(screen, theText, textColor, theFont, ToScreenX(x), ToScreenY(y)); end; procedure DrawText(theText: String; textColor: Color; theFont: Font; const pt: Point2D); overload; begin DrawText(screen, theText, textColor, theFont, ToScreenX(pt.x), ToScreenY(pt.y)); end; procedure DrawUnicode(theText: WideString; textColor: Color; theFont: Font; x, y: Single); overload; begin DrawUnicode(screen, theText, textColor, theFont, ToScreenX(x), ToScreenY(y)); end; procedure DrawUnicode(theText: WideString; textColor: Color; theFont: Font; const pt: Point2D); overload; begin DrawUnicode(screen, theText, textColor, theFont, ToScreenX(pt.x), ToScreenY(pt.y)); end; /// Calculates the width of a string when drawn with a given font. /// /// @param theText: The text to measure /// @param theFont: The font used to draw the text /// @returns The width of the drawing in pixels function TextWidth(theFont: Font; theText: String): LongInt; overload; var y: LongInt; //SizeText returns both... store and ignore y begin if not Assigned(theFont) then begin RaiseException('No font supplied'); exit; end; try y := 0; result := 0; if length(theText) = 0 then result := 0 else TTF_SizeText(theFont, PChar(theText), result, y); except begin RaiseException('Unable to get the text width'); exit; end; end; end; function TextWidth(theText: WideString; theFont: Font): LongInt; overload; var y: LongInt; //SizeText returns both... store and ignore y begin if not Assigned(theFont) then begin RaiseException('No font supplied'); exit; end; try y := 0; result := 0; if length(theText) = 0 then result := 0 else TTF_SizeUNICODE(theFont, PUInt16(theText), result, y); except begin RaiseException('Unable to get the text width'); exit; end; end; end; /// Calculates the height of a string when drawn with a given font. /// /// @param theText: The text to measure /// @param theFont: The font used to draw the text /// @returns The height of the drawing in pixels function TextHeight(theFont: Font; theText: String): LongInt; overload; var w: LongInt; //SizeText returns both... store and ignore w begin if not Assigned(theFont) then begin RaiseException('No font supplied'); exit; end; try w := 0; result := 0; TTF_SizeText(theFont, PChar(theText), w, result); except begin RaiseException('Unable to get the text height'); exit; end; end; end; function TextHeight(theText: WideString; theFont: Font): LongInt; overload; var w: LongInt; //SizeText returns both... store and ignore w begin if not Assigned(theFont) then begin RaiseException('No font supplied'); exit; end; try w := 0; result := 0; TTF_SizeUNICODE(theFont, PUInt16(theText), w, result); except begin RaiseException('Unable to get the text height'); exit; end; end; end; /// Draws the frame rate using the specified font at the indicated x, y. /// Draws the FPS (min, max) current average /// /// @param x,y: The x, y location to draw to /// @param font: The font used to draw the framerate /// /// Side Effects: /// - Framerate is drawn to the screen procedure DrawFramerate(x, y: LongInt; font: Font); overload; var textColor : Color; average, highest, lowest : String; begin //Draw framerates CalculateFramerate(average, highest, lowest, textColor); if not Assigned(font) then DrawTextOnScreen('FPS: (' + highest + ', ' + lowest + ') ' + average, textColor, x + 2, y + 2) else DrawTextOnScreen('FPS: (' + highest + ', ' + lowest + ') ' + average, textColor, font, x + 2, y + 2); end; procedure DrawFramerate(x, y: LongInt); overload; begin DrawFramerate(x, y, nil); end; procedure DrawText(theText: String; textColor: Color; x, y: Single); overload; begin DrawText(screen, theText, textColor, ToScreenX(x), ToScreenY(y)); end; procedure DrawText(theText: String; textColor: Color; const pt: Point2D); begin DrawText(theText, textColor, pt.x, pt.y); end; procedure DrawTextOnScreen(theText: String; textColor: Color; x, y: Single); overload; begin DrawText(screen, theText, textColor, x, y); end; procedure DrawText(dest: Bitmap; theText: String; textColor: Color; x, y: Single); overload; begin stringColor(dest^.surface, Round(x), Round(y), PChar(theText), ToGFXColor(textColor)); end; function TextAlignmentFrom(str: String): FontAlignment; var ch: Char; begin str := trim(str); if length(str) > 0 then ch := str[1] else ch := 'l'; case ch of 'c', 'C': result := AlignCenter; 'r', 'R': result := AlignRight; else result := AlignLeft; end; end; //============================================================================= //============================================================================= initialization begin InitialiseSwinGame(); _Fonts := TStringHash.Create(False, 1024); if TTF_Init() = -1 then begin begin RaiseException('Error opening font library. ' + string(TTF_GetError)); exit; end; end; end; //============================================================================= finalization begin TTF_Quit(); end; end.
// SYNTAX TEST "Packages/Pascal/Pascal.sublime-syntax" // double slash comment // <- punctuation.whitespace.comment.leading.pascal // <- punctuation.definition.comment.pascal // ^^^^^^^^^^^^^^^^^^^^ comment.line.double-slash.pascal.two -- double dash comment // <- punctuation.whitespace.comment.leading.pascal // <- punctuation.definition.comment.pascal // ^^^^^^^^^^^^^^^^^^^ comment.line.double-dash.pascal.one // comment procedure foo; // ^ meta.function.pascal keyword.declaration.function begin // comment end; // <- keyword.control.pascal -- comment procedure bar; // ^ meta.function.pascal keyword.declaration.function begin -- comment end; // <- keyword.control.pascal
unit l3MetafileHeader; // Модуль: "w:\common\components\rtl\Garant\L3\l3MetafileHeader.pas" // Стереотип: "UtilityPack" // Элемент модели: "l3MetafileHeader" MUID: (552616EE02DF) {$Include w:\common\components\rtl\Garant\L3\l3Define.inc} interface uses l3IntfUses , Windows ; const c_WMFKey = Integer($9AC6CDD7); type Pl3MetafileHeader = ^Tl3MetafileHeader; Tl3MetafileHeader = packed record Key: LongInt; Handle: SmallInt; Box: TSmallRect; Inch: Word; Reserved: LongInt; CheckSum: Word; end;//Tl3MetafileHeader function l3IsValidMetafileHeader(const aWMFHeader: Tl3MetafileHeader): Boolean; function l3ComputeAldusChecksum(var theWMF: Tl3MetafileHeader): Word; implementation uses l3ImplUses //#UC START# *552616EE02DFimpl_uses* //#UC END# *552616EE02DFimpl_uses* ; function l3IsValidMetafileHeader(const aWMFHeader: Tl3MetafileHeader): Boolean; //#UC START# *55262EC601CF_552616EE02DF_var* var l_WH : Tl3MetafileHeader; //#UC END# *55262EC601CF_552616EE02DF_var* begin //#UC START# *55262EC601CF_552616EE02DF_impl* l_WH := aWMFHeader; Result := (aWMFHeader.Key = c_WMFKEY) and (l3ComputeAldusChecksum(l_WH) = aWMFHeader.CheckSum); //#UC END# *55262EC601CF_552616EE02DF_impl* end;//l3IsValidMetafileHeader function l3ComputeAldusChecksum(var theWMF: Tl3MetafileHeader): Word; //#UC START# *55262F470207_552616EE02DF_var* type PWord = ^Word; var pW: PWord; pEnd: PWord; //#UC END# *55262F470207_552616EE02DF_var* begin //#UC START# *55262F470207_552616EE02DF_impl* Result := 0; pW := @theWMF; pEnd := @theWMF.CheckSum; while Longint(pW) < Longint(pEnd) do begin Result := Result xor pW^; Inc(Longint(pW), SizeOf(Word)); end; //#UC END# *55262F470207_552616EE02DF_impl* end;//l3ComputeAldusChecksum end.
unit fmWorkBench; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.WebBrowser, FMX.StdCtrls, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo, FMX.TabControl, FMX.Edit; type TForm1 = class(TForm) TabControl1: TTabControl; TabItem1: TTabItem; TabItem2: TTabItem; mInput: TMemo; mOutput: TMemo; Memo3: TMemo; Memo4: TMemo; Button4: TButton; Button6: TButton; Label1: TLabel; Label2: TLabel; btBeautify: TButton; btMinify: TButton; gbButtons: TGroupBox; btToWriter: TButton; btToDelphi: TButton; lbUseBuilders: TCheckBox; procedure btBeautifyClick(Sender: TObject); procedure btMinifyClick(Sender: TObject); procedure Button4Click(Sender: TObject); procedure Button6Click(Sender: TObject); procedure btToDelphiClick(Sender: TObject); procedure btToWriterClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; implementation uses System.JSON.Types, System.IOUtils, System.DateUtils, Converters, Writers; {$R *.fmx} { TForm1 } procedure TForm1.btBeautifyClick(Sender: TObject); begin try mOutput.Text := TConverters.JsonReformat(mInput.Text, True); except on E: EJsonException do mOutput.Text := E.Message; end; end; procedure TForm1.Button4Click(Sender: TObject); begin try Memo3.Text := TConverters.Json2BsonString(Memo4.Text); except on E: EJsonException do Memo3.Text := E.Message; end; end; procedure TForm1.btMinifyClick(Sender: TObject); begin try mOutput.Text := TConverters.JsonReformat(mInput.Text, False); except on E: EJsonException do mOutput.Text := E.Message; end; end; procedure TForm1.btToDelphiClick(Sender: TObject); begin try mOutput.Text := TConverters.Json2DelphiCode(mInput.Text) except on E: EJsonException do mOutput.Text := E.Message; end; end; procedure TForm1.btToWriterClick(Sender: TObject); var LCode: string; begin try if lbUseBuilders.IsChecked then begin // LCode := ' LCode := TConverters.Json2JsonBuilderCode(mInput.Text, 'Builder'); end else begin LCode := TConverters.Json2JsonWriterCode(mInput.Text, 'Writer'); end; mOutput.Text := LCode; except on E: EJsonException do mOutput.Text := E.Message; end; end; procedure TForm1.Button6Click(Sender: TObject); begin try Memo4.Text := TConverters.BsonString2Json(Memo3.Text); except on E: EJsonException do Memo4.Text := E.Message; end; end; end.
// // Created by the DataSnap proxy generator. // 10/10/2019 00:58:50 // unit ClientClassesUnit1; interface uses System.JSON, Datasnap.DSProxyRest, Datasnap.DSClientRest, Data.DBXCommon, Data.DBXClient, Data.DBXDataSnap, Data.DBXJSON, Datasnap.DSProxy, System.Classes, System.SysUtils, Data.DB, Data.SqlExpr, Data.DBXDBReaders, Data.DBXCDSReaders, Data.FireDACJSONReflect, Data.DBXJSONReflect; type IDSRestCachedTFDJSONDataSets = interface; TServerMethods1Client = class(TDSAdminRestClient) private FEchoStringCommand: TDSRestCommand; FReverseStringCommand: TDSRestCommand; FupdateClienteCommand: TDSRestCommand; FClienteCommand: TDSRestCommand; FClienteCommand_Cache: TDSRestCommand; public constructor Create(ARestConnection: TDSRestConnection); overload; constructor Create(ARestConnection: TDSRestConnection; AInstanceOwner: Boolean); overload; destructor Destroy; override; function EchoString(Value: string; const ARequestFilter: string = ''): string; function ReverseString(Value: string; const ARequestFilter: string = ''): string; procedure updateCliente(ADeltaList: TFDJSONDeltas); function Cliente(const ARequestFilter: string = ''): TFDJSONDataSets; function Cliente_Cache(const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets; end; IDSRestCachedTFDJSONDataSets = interface(IDSRestCachedObject<TFDJSONDataSets>) end; TDSRestCachedTFDJSONDataSets = class(TDSRestCachedObject<TFDJSONDataSets>, IDSRestCachedTFDJSONDataSets, IDSRestCachedCommand) end; const TServerMethods1_EchoString: array [0..1] of TDSRestParameterMetaData = ( (Name: 'Value'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'string') ); TServerMethods1_ReverseString: array [0..1] of TDSRestParameterMetaData = ( (Name: 'Value'; Direction: 1; DBXType: 26; TypeName: 'string'), (Name: ''; Direction: 4; DBXType: 26; TypeName: 'string') ); TServerMethods1_updateCliente: array [0..0] of TDSRestParameterMetaData = ( (Name: 'ADeltaList'; Direction: 1; DBXType: 37; TypeName: 'TFDJSONDeltas') ); TServerMethods1_Cliente: array [0..0] of TDSRestParameterMetaData = ( (Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets') ); TServerMethods1_Cliente_Cache: array [0..0] of TDSRestParameterMetaData = ( (Name: ''; Direction: 4; DBXType: 26; TypeName: 'String') ); implementation function TServerMethods1Client.EchoString(Value: string; const ARequestFilter: string): string; begin if FEchoStringCommand = nil then begin FEchoStringCommand := FConnection.CreateCommand; FEchoStringCommand.RequestType := 'GET'; FEchoStringCommand.Text := 'TServerMethods1.EchoString'; FEchoStringCommand.Prepare(TServerMethods1_EchoString); end; FEchoStringCommand.Parameters[0].Value.SetWideString(Value); FEchoStringCommand.Execute(ARequestFilter); Result := FEchoStringCommand.Parameters[1].Value.GetWideString; end; function TServerMethods1Client.ReverseString(Value: string; const ARequestFilter: string): string; begin if FReverseStringCommand = nil then begin FReverseStringCommand := FConnection.CreateCommand; FReverseStringCommand.RequestType := 'GET'; FReverseStringCommand.Text := 'TServerMethods1.ReverseString'; FReverseStringCommand.Prepare(TServerMethods1_ReverseString); end; FReverseStringCommand.Parameters[0].Value.SetWideString(Value); FReverseStringCommand.Execute(ARequestFilter); Result := FReverseStringCommand.Parameters[1].Value.GetWideString; end; procedure TServerMethods1Client.updateCliente(ADeltaList: TFDJSONDeltas); begin if FupdateClienteCommand = nil then begin FupdateClienteCommand := FConnection.CreateCommand; FupdateClienteCommand.RequestType := 'POST'; FupdateClienteCommand.Text := 'TServerMethods1."updateCliente"'; FupdateClienteCommand.Prepare(TServerMethods1_updateCliente); end; if not Assigned(ADeltaList) then FupdateClienteCommand.Parameters[0].Value.SetNull else begin FMarshal := TDSRestCommand(FupdateClienteCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler; try FupdateClienteCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(ADeltaList), True); if FInstanceOwner then ADeltaList.Free finally FreeAndNil(FMarshal) end end; FupdateClienteCommand.Execute; end; function TServerMethods1Client.Cliente(const ARequestFilter: string): TFDJSONDataSets; begin if FClienteCommand = nil then begin FClienteCommand := FConnection.CreateCommand; FClienteCommand.RequestType := 'GET'; FClienteCommand.Text := 'TServerMethods1.Cliente'; FClienteCommand.Prepare(TServerMethods1_Cliente); end; FClienteCommand.Execute(ARequestFilter); if not FClienteCommand.Parameters[0].Value.IsNull then begin FUnMarshal := TDSRestCommand(FClienteCommand.Parameters[0].ConnectionHandler).GetJSONUnMarshaler; try Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FClienteCommand.Parameters[0].Value.GetJSONValue(True))); if FInstanceOwner then FClienteCommand.FreeOnExecute(Result); finally FreeAndNil(FUnMarshal) end end else Result := nil; end; function TServerMethods1Client.Cliente_Cache(const ARequestFilter: string): IDSRestCachedTFDJSONDataSets; begin if FClienteCommand_Cache = nil then begin FClienteCommand_Cache := FConnection.CreateCommand; FClienteCommand_Cache.RequestType := 'GET'; FClienteCommand_Cache.Text := 'TServerMethods1.Cliente'; FClienteCommand_Cache.Prepare(TServerMethods1_Cliente_Cache); end; FClienteCommand_Cache.ExecuteCache(ARequestFilter); Result := TDSRestCachedTFDJSONDataSets.Create(FClienteCommand_Cache.Parameters[0].Value.GetString); end; constructor TServerMethods1Client.Create(ARestConnection: TDSRestConnection); begin inherited Create(ARestConnection); end; constructor TServerMethods1Client.Create(ARestConnection: TDSRestConnection; AInstanceOwner: Boolean); begin inherited Create(ARestConnection, AInstanceOwner); end; destructor TServerMethods1Client.Destroy; begin FEchoStringCommand.DisposeOf; FReverseStringCommand.DisposeOf; FupdateClienteCommand.DisposeOf; FClienteCommand.DisposeOf; FClienteCommand_Cache.DisposeOf; inherited; end; end.
unit Benjamim.Signature; interface uses {$IF DEFINED(FPC)} Classes, SysUtils, TypInfo, {$ELSE} System.Classes, System.TypInfo, System.NetEncoding, System.Hash, System.SysUtils, {$ENDIF} Benjamim.Utils, Benjamim.Signature.Interfaces, Benjamim.Interfaces; type TSignature = class(TInterfacedObject, iSignature) class function New(const aJWT: iJWT): iSignature; constructor Create(const aJWT: iJWT); destructor Destroy; override; strict private FJWT: iJWT; procedure loadAlgorithm(const aHeader: string); function Sign(const aData: string): string; overload; public function Sign: string; overload; function Verify: boolean; end; implementation { TSignature } class function TSignature.New(const aJWT: iJWT): iSignature; begin Result := Self.Create(aJWT); end; constructor TSignature.Create(const aJWT: iJWT); begin FJWT := aJWT; end; destructor TSignature.Destroy; begin FJWT := nil; inherited; end; function TSignature.Sign(const aData: string): string; begin {$IF DEFINED(FPC)} { TODO -oAll -cLazarus : Implementar } {$ELSE} if FJWT.PasswordEncoded then Exit((TNetEncoding.Base64.EncodeBytesToString(THashSHA2.GetHMACAsBytes( TEncoding.UTF8.GetBytes(aData), TNetEncoding.Base64.DecodeStringToBytes(FJWT.Password), FJWT.Header.Algorithm.AsJwtAlgorithm.AsAlgorithm ))).ClearLineBreak.FixBase64); Result := (TNetEncoding.Base64.EncodeBytesToString(THashSHA2.GetHMACAsBytes( TEncoding.UTF8.GetBytes(aData), FJWT.Password, FJWT.Header.Algorithm.AsJwtAlgorithm.AsAlgorithm) )).ClearLineBreak.FixBase64; {$ENDIF} end; procedure TSignature.loadAlgorithm(const aHeader: string); begin if SameStr(aHeader, 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9') then begin FJWT.Header.Algorithm(TJwtAlgorithm.HS256); Exit; end; if SameStr(aHeader, 'eyJhbGciOiJIUzM4NCIsInR5cCI6IkpXVCJ9') then begin FJWT.Header.Algorithm(TJwtAlgorithm.HS384); Exit; end; if SameStr(aHeader, 'eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9') then begin FJWT.Header.Algorithm(TJwtAlgorithm.HS512); Exit; end; FJWT.Header.Algorithm(TJwtAlgorithm.HS256); end; { Signature - Verify } function TSignature.Verify: boolean; const INDEX_HEADER = 0; INDEX_PAYLOAD = 1; INDEX_SIGNATURE = 2; begin try with TStringList.Create do try Clear; Delimiter := DotSep[1]; StrictDelimiter := true; DelimitedText := FJWT.Token; loadAlgorithm(Strings[INDEX_HEADER]); Exit(SameStr(Strings[INDEX_SIGNATURE], Sign(Strings[INDEX_HEADER] + DotSep + Strings[INDEX_PAYLOAD]))); finally Free; end; except on E: Exception do end; Result := false; end; { Signature - Sign } function TSignature.Sign: string; begin Result := FJWT.Header.AsJson(true) + DotSep + FJWT.Payload.AsJson(true); Result := Result + DotSep + Sign(Result); end; end.
{ *********************************************************************************** } { * CryptoLib Library * } { * Copyright (c) 2018 - 20XX Ugochukwu Mmaduekwe * } { * Github Repository <https://github.com/Xor-el> * } { * Distributed under the MIT software license, see the accompanying file LICENSE * } { * or visit http://www.opensource.org/licenses/mit-license.php. * } { * Acknowledgements: * } { * * } { * Thanks to Sphere 10 Software (http://www.sphere10.com/) for sponsoring * } { * development of this library * } { * ******************************************************************************* * } (* &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&& *) unit ClpSecP384R1Point; {$I ..\..\..\..\Include\CryptoLib.inc} interface uses ClpNat, ClpNat384, ClpECPoint, ClpSecP384R1Field, ClpISecP384R1Point, ClpISecP384R1FieldElement, ClpIECFieldElement, ClpIECInterface, ClpCryptoLibTypes; resourcestring SOneOfECFieldElementIsNil = 'Exactly One of the Field Elements is Nil'; type TSecP384R1Point = class sealed(TAbstractFpPoint, ISecP384R1Point) strict protected function Detach(): IECPoint; override; public /// <summary> /// Create a point which encodes without point compression. /// </summary> /// <param name="curve"> /// the curve to use /// </param> /// <param name="x"> /// affine x co-ordinate /// </param> /// <param name="y"> /// affine y co-ordinate /// </param> constructor Create(const curve: IECCurve; const x, y: IECFieldElement); overload; deprecated 'Use ECCurve.createPoint to construct points'; /// <summary> /// Create a point that encodes with or without point compresion. /// </summary> /// <param name="curve"> /// the curve to use /// </param> /// <param name="x"> /// affine x co-ordinate /// </param> /// <param name="y"> /// affine y co-ordinate /// </param> /// <param name="withCompression"> /// if true encode with point compression /// </param> constructor Create(const curve: IECCurve; const x, y: IECFieldElement; withCompression: Boolean); overload; deprecated 'Per-point compression property will be removed, see GetEncoded(boolean)'; constructor Create(const curve: IECCurve; const x, y: IECFieldElement; const zs: TCryptoLibGenericArray<IECFieldElement>; withCompression: Boolean); overload; function Add(const b: IECPoint): IECPoint; override; function Negate(): IECPoint; override; function Twice(): IECPoint; override; function TwicePlus(const b: IECPoint): IECPoint; override; function ThreeTimes(): IECPoint; override; end; implementation uses // included here to avoid circular dependency :) ClpSecP384R1FieldElement; { TSecP384R1Point } constructor TSecP384R1Point.Create(const curve: IECCurve; const x, y: IECFieldElement); begin Create(curve, x, y, false); end; constructor TSecP384R1Point.Create(const curve: IECCurve; const x, y: IECFieldElement; withCompression: Boolean); begin Inherited Create(curve, x, y, withCompression); if ((x = Nil) <> (y = Nil)) then begin raise EArgumentCryptoLibException.CreateRes(@SOneOfECFieldElementIsNil); end; end; constructor TSecP384R1Point.Create(const curve: IECCurve; const x, y: IECFieldElement; const zs: TCryptoLibGenericArray<IECFieldElement>; withCompression: Boolean); begin Inherited Create(curve, x, y, zs, withCompression); end; function TSecP384R1Point.Add(const b: IECPoint): IECPoint; var Lcurve: IECCurve; X1, Y1, X2, Y2, Z1, Z2, X3, Y3, Z3: ISecP384R1FieldElement; c: UInt32; tt1, tt2, t3, t4, U2, S2, U1, S1, H, R, HSquared, G, V: TCryptoLibUInt32Array; Z1IsOne, Z2IsOne: Boolean; zs: TCryptoLibGenericArray<IECFieldElement>; begin if (IsInfinity) then begin result := b; Exit; end; if (b.IsInfinity) then begin result := Self as IECPoint; Exit; end; if ((Self as IECPoint) = b) then begin result := Twice(); Exit; end; Lcurve := curve; X1 := RawXCoord as ISecP384R1FieldElement; Y1 := RawYCoord as ISecP384R1FieldElement; X2 := b.RawXCoord as ISecP384R1FieldElement; Y2 := b.RawYCoord as ISecP384R1FieldElement; Z1 := RawZCoords[0] as ISecP384R1FieldElement; Z2 := b.RawZCoords[0] as ISecP384R1FieldElement; tt1 := TNat.Create(24); tt2 := TNat.Create(24); t3 := TNat.Create(12); t4 := TNat.Create(12); Z1IsOne := Z1.IsOne; if (Z1IsOne) then begin U2 := X2.x; S2 := Y2.x; end else begin S2 := t3; TSecP384R1Field.Square(Z1.x, S2); U2 := tt2; TSecP384R1Field.Multiply(S2, X2.x, U2); TSecP384R1Field.Multiply(S2, Z1.x, S2); TSecP384R1Field.Multiply(S2, Y2.x, S2); end; Z2IsOne := Z2.IsOne; if (Z2IsOne) then begin U1 := X1.x; S1 := Y1.x; end else begin S1 := t4; TSecP384R1Field.Square(Z2.x, S1); U1 := tt1; TSecP384R1Field.Multiply(S1, X1.x, U1); TSecP384R1Field.Multiply(S1, Z2.x, S1); TSecP384R1Field.Multiply(S1, Y1.x, S1); end; H := TNat.Create(12); TSecP384R1Field.Subtract(U1, U2, H); R := TNat.Create(12); TSecP384R1Field.Subtract(S1, S2, R); // Check if b = Self or b = -Self if (TNat.IsZero(12, H)) then begin if (TNat.IsZero(12, R)) then begin // Self = b, i.e. Self must be doubled result := Twice(); Exit; end; // Self = -b, i.e. the result is the point at infinity result := Lcurve.Infinity; Exit; end; HSquared := t3; TSecP384R1Field.Square(H, HSquared); G := TNat.Create(12); TSecP384R1Field.Multiply(HSquared, H, G); V := t3; TSecP384R1Field.Multiply(HSquared, U1, V); TSecP384R1Field.Negate(G, G); TNat384.Mul(S1, G, tt1); c := TNat.AddBothTo(12, V, V, G); TSecP384R1Field.Reduce32(c, G); X3 := TSecP384R1FieldElement.Create(t4); TSecP384R1Field.Square(R, X3.x); TSecP384R1Field.Subtract(X3.x, G, X3.x); Y3 := TSecP384R1FieldElement.Create(G); TSecP384R1Field.Subtract(V, X3.x, Y3.x); TNat384.Mul(Y3.x, R, tt2); TSecP384R1Field.AddExt(tt1, tt2, tt1); TSecP384R1Field.Reduce(tt1, Y3.x); Z3 := TSecP384R1FieldElement.Create(H); if (not(Z1IsOne)) then begin TSecP384R1Field.Multiply(Z3.x, Z1.x, Z3.x); end; if (not(Z2IsOne)) then begin TSecP384R1Field.Multiply(Z3.x, Z2.x, Z3.x); end; zs := TCryptoLibGenericArray<IECFieldElement>.Create(Z3); result := TSecP384R1Point.Create(Lcurve, X3, Y3, zs, IsCompressed) as IECPoint; end; function TSecP384R1Point.Detach: IECPoint; begin result := TSecP384R1Point.Create(Nil, AffineXCoord, AffineYCoord) as IECPoint; end; function TSecP384R1Point.Negate: IECPoint; begin if (IsInfinity) then begin result := Self as IECPoint; Exit; end; result := TSecP384R1Point.Create(curve, RawXCoord, RawYCoord.Negate(), RawZCoords, IsCompressed) as IECPoint; end; function TSecP384R1Point.ThreeTimes: IECPoint; begin if ((IsInfinity) or (RawYCoord.IsZero)) then begin result := Self as IECPoint; Exit; end; // NOTE: Be careful about recursions between TwicePlus and ThreeTimes result := Twice().Add(Self as IECPoint); end; function TSecP384R1Point.Twice: IECPoint; var Lcurve: IECCurve; Y1, X1, Z1, X3, Y3, Z3: ISecP384R1FieldElement; c: UInt32; Y1Squared, Z1Squared, T, M, S, t1, t2: TCryptoLibUInt32Array; Z1IsOne: Boolean; begin if (IsInfinity) then begin result := Self as IECPoint; Exit; end; Lcurve := curve; Y1 := RawYCoord as ISecP384R1FieldElement; if (Y1.IsZero) then begin result := Lcurve.Infinity; Exit; end; X1 := RawXCoord as ISecP384R1FieldElement; Z1 := RawZCoords[0] as ISecP384R1FieldElement; t1 := TNat.Create(12); t2 := TNat.Create(12); Y1Squared := TNat.Create(12); TSecP384R1Field.Square(Y1.x, Y1Squared); T := TNat.Create(12); TSecP384R1Field.Square(Y1Squared, T); Z1IsOne := Z1.IsOne; Z1Squared := Z1.x; if (not(Z1IsOne)) then begin Z1Squared := t2; TSecP384R1Field.Square(Z1.x, Z1Squared); end; TSecP384R1Field.Subtract(X1.x, Z1Squared, t1); M := t2; TSecP384R1Field.Add(X1.x, Z1Squared, M); TSecP384R1Field.Multiply(M, t1, M); c := TNat.AddBothTo(12, M, M, M); TSecP384R1Field.Reduce32(c, M); S := Y1Squared; TSecP384R1Field.Multiply(Y1Squared, X1.x, S); c := TNat.ShiftUpBits(12, S, 2, 0); TSecP384R1Field.Reduce32(c, S); c := TNat.ShiftUpBits(12, T, 3, 0, t1); TSecP384R1Field.Reduce32(c, t1); X3 := TSecP384R1FieldElement.Create(T); TSecP384R1Field.Square(M, X3.x); TSecP384R1Field.Subtract(X3.x, S, X3.x); TSecP384R1Field.Subtract(X3.x, S, X3.x); Y3 := TSecP384R1FieldElement.Create(S); TSecP384R1Field.Subtract(S, X3.x, Y3.x); TSecP384R1Field.Multiply(Y3.x, M, Y3.x); TSecP384R1Field.Subtract(Y3.x, t1, Y3.x); Z3 := TSecP384R1FieldElement.Create(M); TSecP384R1Field.Twice(Y1.x, Z3.x); if (not(Z1IsOne)) then begin TSecP384R1Field.Multiply(Z3.x, Z1.x, Z3.x); end; result := TSecP384R1Point.Create(Lcurve, X3, Y3, TCryptoLibGenericArray<IECFieldElement>.Create(Z3), IsCompressed) as IECPoint; end; function TSecP384R1Point.TwicePlus(const b: IECPoint): IECPoint; var Y1: IECFieldElement; begin if ((Self as IECPoint) = b) then begin result := ThreeTimes(); Exit; end; if (IsInfinity) then begin result := b; Exit; end; if (b.IsInfinity) then begin result := Twice(); Exit; end; Y1 := RawYCoord; if (Y1.IsZero) then begin result := b; Exit; end; result := Twice().Add(b); end; end.
unit clRestricoes; interface uses clConexao; type TRestricoes = Class(TObject) private function getAgente: Integer; function getCodigo: Integer; function getEntregador: Integer; function getValor: Double; procedure setAgente(const Value: Integer); procedure setCodigo(const Value: Integer); procedure setEntregador(const Value: Integer); procedure setValor(const Value: Double); function getPago: Double; procedure setPago(const Value: Double); function getDebitar: Double; procedure setDebitar(const Value: Double); constructor Create; destructor Destroy; protected _codigo: Integer; _valor: Double; _pago: Double; _agente: Integer; _entregador: Integer; _debitar: Double; _conexao: TConexao; public property Codigo: Integer read getCodigo write setCodigo; property Valor: Double read getValor write setValor; property Agente: Integer read getAgente write setAgente; property Entregador: Integer read getEntregador write setEntregador; property Pago: Double read getPago write setPago; property Debitar: Double read getDebitar write setDebitar; procedure MaxCod; function Validar(): Boolean; function Delete(filtro: String): Boolean; function getObject(id, filtro: String): Boolean; function Insert(): Boolean; function Update(): Boolean; function getField(campo, coluna: String): String; function getObjects(): Boolean; function RetornaDebito(iEntregador: Integer): Double; end; const TABLENAME = 'TBRESTRICOES'; implementation { TRestricoes } uses SysUtils, Dialogs, udm, clUtil, ZDataset, ZAbstractRODataset, DB, Windows; constructor TRestricoes.Create; begin _conexao := TConexao.Create; if (not _conexao.VerifyConnZEOS(0)) then begin MessageDlg('Erro ao estabelecer conexão ao banco de dados (' + Self.ClassName + ') !', mtError, [mbCancel], 0); end; end; destructor TRestricoes.Destroy; begin _conexao.Free; end; function TRestricoes.getAgente: Integer; begin Result := _agente; end; function TRestricoes.getCodigo: Integer; begin Result := _codigo; end; function TRestricoes.getEntregador: Integer; begin Result := _entregador; end; function TRestricoes.getValor: Double; begin Result := _valor; end; procedure TRestricoes.MaxCod; begin Try with dm.QryGetObject do begin Close; SQL.Clear; SQL.Text := 'SELECT MAX(COD_RESTRICAO) AS CODIGO FROM ' + TABLENAME; dm.ZConn.PingServer; Open; if not(IsEmpty) then First; end; Self.Codigo := (dm.QryGetObject.FieldByName('CODIGO').AsInteger) + 1; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TRestricoes.Validar(): Boolean; begin try Result := False; if Self.Agente = 0 then begin MessageDlg('Informe o Agente!', mtWarning, [mbOK], 0); Exit; end; if Self.Valor = 0 then begin if MessageDlg('Confirma Restrição com o valor igual a zero?', mtConfirmation, [mbYes, mbNo], 0) = IDNO then begin Exit; end; end; if Self.Debitar > Self.Valor then begin MessageDlg ('Valor a Debitar não pode ser maior que o valor da Restrição Pendente!', mtWarning, [mbOK], 0); Exit; end; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TRestricoes.Delete(filtro: String): Boolean; begin try Result := False; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Add('DELETE FROM ' + TABLENAME); if filtro = 'CODIGO' then begin SQL.Add('WHERE COD_RESTRICAO = :CODIGO'); ParamByName('CODIGO').AsInteger := Self.Codigo; end else if filtro = 'AGENTE' then begin SQL.Add('WHERE COD_AGENTE = :AGENTE'); ParamByName('AGENTE').AsInteger := Self.Agente; end else if filtro = 'ENTREGADOR' then begin SQL.Add('WHERE COD_ENTREGADOR = :ENTREGADOR'); ParamByName('ENTREGADOR').AsInteger := Self.Entregador; end; dm.ZConn.PingServer; ExecSQL; end; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TRestricoes.getObject(id, filtro: String): Boolean; begin Try Result := False; if TUtil.Empty(id) then Exit; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); if filtro = 'CODIGO' then begin SQL.Add('WHERE COD_RESTRICAO = :CODIGO'); ParamByName('CODIGO').AsInteger := StrToInt(id); end else if filtro = 'AGENTE' then begin SQL.Add('WHERE COD_AGENTE = :AGENTE AND COD_ENTREGADOR = :ENTREGADOR'); ParamByName('AGENTE').AsInteger := StrToInt(id); ParamByName('ENTREGADOR').AsInteger := StrToInt(id); end else if filtro = 'ENTREGADOR' then begin SQL.Add('WHERE COD_ENTREGADOR = :ENTREGADOR'); ParamByName('ENTREGADOR').AsInteger := StrToInt(id); end; dm.ZConn.PingServer; Open; if not(IsEmpty) then begin First; if RecordCount = 1 then begin Self.Codigo := FieldByName('COD_RESTRICAO').AsInteger; Self.Valor := FieldByName('VAL_RESTRICAO').AsFloat; Self.Agente := FieldByName('COD_AGENTE').AsInteger; Self.Entregador := FieldByName('COD_ENTREGADOR').AsInteger; Self.Pago := FieldByName('VAL_PAGO').AsFloat; Self.Debitar := FieldByName('VAL_DEBITAR').AsFloat; Close; SQL.Clear; end end else begin Close; SQL.Clear; Exit; end; end; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TRestricoes.Insert(): Boolean; begin Try Result := False; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Text := 'INSERT INTO ' + TABLENAME + '(' + 'COD_RESTRICAO, ' + 'VAL_RESTRICAO, ' + 'COD_AGENTE, ' + 'COD_ENTREGADOR, ' + 'VAL_PAGO, ' + 'VAL_DEBITAR) ' + 'VALUES (' + ':CODIGO, ' + ':VALOR, ' + ':AGENTE, ' + ':ENTREGADOR, ' + ':PAGO, ' + ':DEBITAR)'; MaxCod; ParamByName('CODIGO').AsInteger := Self.Codigo; ParamByName('VALOR').AsFloat := Self.Valor; ParamByName('AGENTE').AsInteger := Self.Agente; ParamByName('ENTREGADOR').AsInteger := Self.Entregador; ParamByName('PAGO').AsFloat := Self.Pago; ParamByName('DEBITAR').AsFloat := Self.Debitar; dm.ZConn.PingServer; ExecSQL; end; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TRestricoes.Update(): Boolean; begin try Result := False; with dm.QryCRUD do begin Close; SQL.Clear; SQL.Text := 'UPDATE ' + TABLENAME + ' SET ' + 'VAL_RESTRICAO = :VALOR, ' + 'COD_AGENTE = :AGENTE, ' + 'COD_ENTREGADOR = :ENTREGADOR, ' + 'VAL_PAGO = :PAGO, ' + 'VAL_DEBITAR = :DEBITAR ' + 'WHERE ' + 'COD_RESTRICAO = :CODIGO'; ParamByName('CODIGO').AsInteger := Self.Codigo; ParamByName('VALOR').AsFloat := Self.Valor; ParamByName('AGENTE').AsInteger := Self.Agente; ParamByName('ENTREGADOR').AsInteger := Self.Entregador; ParamByName('PAGO').AsFloat := Self.Pago; ParamByName('DEBITAR').AsFloat := Self.Debitar; dm.ZConn.PingServer; ExecSQL; end; dm.QryCRUD.Close; dm.QryCRUD.SQL.Clear; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TRestricoes.getField(campo, coluna: String): String; begin Try Result := ''; with dm.QryGetObject do begin Close; SQL.Clear; SQL.Text := 'SELECT ' + campo + ' FROM ' + TABLENAME; if coluna = 'CODIGO' then begin SQL.Add(' WHERE COD_RESTRICAO =:CODIGO '); ParamByName('CODIGO').AsInteger := Self.Codigo; end else if coluna = 'VALOR' then begin SQL.Add(' WHERE VAL_RESTRICAO =:VALOR '); ParamByName('VALOR').AsFloat := Self.Valor; end else if coluna = 'AGENTE' then begin SQL.Add(' WHERE COD_AGENTE =:AGENTE '); ParamByName('AGENTE').AsInteger := Self.Agente; end else if coluna = 'ENTREGADOR' then begin SQL.Add(' WHERE COD_ENTREGADOR = :ENTREGADOR '); ParamByName('ENTREGADOR').AsInteger := Self.Entregador; end; dm.ZConn.PingServer; Open; if not IsEmpty then First; end; if dm.QryGetObject.RecordCount > 0 then Result := dm.QryGetObject.FieldByName(campo).AsString; dm.QryGetObject.Close; dm.QryGetObject.SQL.Clear; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TRestricoes.getObjects(): Boolean; begin Try Result := False; with dm.qryGeral do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); dm.ZConn.PingServer; Open; if not IsEmpty then begin First; end else begin Close; SQL.Clear; Exit; end; end; Result := True; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; function TRestricoes.RetornaDebito(iEntregador: Integer): Double; begin Try Result := 0; with dm.qryCalculo do begin Close; SQL.Clear; SQL.Add('SELECT * FROM ' + TABLENAME); SQL.Add('WHERE COD_ENTREGADOR = :ENTREGADOR'); ParamByName('ENTREGADOR').AsInteger := iEntregador; dm.ZConn.PingServer; Open; if not(IsEmpty) then begin First; Result := FieldByName('VAL_DEBITAR').AsFloat; Close; SQL.Clear; Exit; end; end; Except on E: Exception do ShowMessage('Classe: ' + E.ClassName + chr(13) + 'Mensagem: ' + E.Message); end; end; procedure TRestricoes.setAgente(const Value: Integer); begin _agente := Value; end; procedure TRestricoes.setCodigo(const Value: Integer); begin _codigo := Value; end; procedure TRestricoes.setEntregador(const Value: Integer); begin _entregador := Value; end; procedure TRestricoes.setValor(const Value: Double); begin _valor := Value; end; function TRestricoes.getPago: Double; begin Result := _pago; end; procedure TRestricoes.setPago(const Value: Double); begin _pago := Value; end; function TRestricoes.getDebitar: Double; begin Result := _debitar; end; procedure TRestricoes.setDebitar(const Value: Double); begin _debitar := Value; end; end.
unit SpellDemoUnit; // TSpellChecker demo // Simple rich-text format editor with spelling check capability // Author: Alexander Obukhov // // see comments in the listing to understand some // TSpellChecker methods and properties interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ComCtrls, Spellers, Menus, StdCtrls, ToolWin, RXCtrls, ClipBrd, RichEdit, Langs, RxCombos; type TSpellDemoForm = class(TForm) MainToolBar: TToolBar; RichEdit: TRichEdit; StatusBar: TStatusBar; MainMenu: TMainMenu; Speller: TSpellChecker; NewBtn: TToolButton; OpenBtn: TToolButton; SaveBtn: TToolButton; ToolButton4: TToolButton; CutBtn: TToolButton; CopyBtn: TToolButton; PasteBtn: TToolButton; ToolButton8: TToolButton; FindBtn: TToolButton; ReplaceBtn: TToolButton; ToolButton11: TToolButton; SpellBtn: TToolButton; Images: TImageList; UndoBtn: TToolButton; ToolButton14: TToolButton; FileMI: TMenuItem; EditMI: TMenuItem; AboutMI: TMenuItem; NewMI: TMenuItem; OpenMI: TMenuItem; SaveMI: TMenuItem; N1: TMenuItem; SaveAsMI: TMenuItem; N2: TMenuItem; ExitMI: TMenuItem; CutMI: TMenuItem; CopyMI: TMenuItem; PasteMI: TMenuItem; N3: TMenuItem; FindMI: TMenuItem; ReplaceMI: TMenuItem; LanguageMI: TMenuItem; N4: TMenuItem; SpellMI: TMenuItem; ExitBtn: TToolButton; ToolButton2: TToolButton; OpenDialog: TOpenDialog; SaveDialog: TSaveDialog; ToolButton3: TToolButton; PrintBtn: TToolButton; N5: TMenuItem; PrintMI: TMenuItem; CoolBar: TCoolBar; FmtToolBar: TToolBar; FontSize: TComboBox; ToolButton6: TToolButton; BoldBtn: TToolButton; ToolButton9: TToolButton; ItalicBtn: TToolButton; ToolButton10: TToolButton; ColorCombo: TColorComboBox; UndrlBtn: TToolButton; UndoMI: TMenuItem; N6: TMenuItem; SelectAllMI: TMenuItem; N7: TMenuItem; FindDialog: TFindDialog; ReplaceDialog: TReplaceDialog; PrintSetupMI: TMenuItem; PrinterSetupDialog: TPrinterSetupDialog; FontCombo: TComboBox; VariantsMenu: TPopupMenu; ToolButton1: TToolButton; LeftBtn: TToolButton; CenterBtn: TToolButton; RightBtn: TToolButton; ToolButton13: TToolButton; BulletsBtn: TToolButton; procedure NewMIClick(Sender: TObject); procedure SelectAllMIClick(Sender: TObject); procedure CutMIClick(Sender: TObject); procedure CopyMIClick(Sender: TObject); procedure PasteMIClick(Sender: TObject); procedure FindMIClick(Sender: TObject); procedure ReplaceMIClick(Sender: TObject); procedure SaveMIClick(Sender: TObject); procedure SaveAsMIClick(Sender: TObject); procedure FindDialogFind(Sender: TObject); procedure ReplaceDialogReplace(Sender: TObject); procedure UndoMIClick(Sender: TObject); procedure ExitMIClick(Sender: TObject); procedure LangMIClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure PrintMIClick(Sender: TObject); procedure RichEditChange(Sender: TObject); procedure RichEditSelectionChange(Sender: TObject); procedure OpenMIClick(Sender: TObject); procedure PrintSetupMIClick(Sender: TObject); procedure FontSizeKeyPress(Sender: TObject; var Key: Char); procedure FontComboChange(Sender: TObject); procedure BoldBtnClick(Sender: TObject); procedure ItalicBtnClick(Sender: TObject); procedure UndrlBtnClick(Sender: TObject); procedure ColorComboChange(Sender: TObject); procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean); procedure FontSizeKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure FontSizeChange(Sender: TObject); procedure FontSizeDropDown(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure VariantsMenuPopup(Sender: TObject); procedure RichEditMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure SpellMIClick(Sender: TObject); procedure VariantMIClick(Sender: TObject); procedure LeftBtnClick(Sender: TObject); procedure CenterBtnClick(Sender: TObject); procedure RightBtnClick(Sender: TObject); procedure BulletsBtnClick(Sender: TObject); procedure AboutMIClick(Sender: TObject); procedure FormShow(Sender: TObject); private { Private declarations } FChanged: Boolean; FFileName: String; FIsNew: Boolean; WasDropped: Boolean; procedure UpdateButtons; procedure ExecSave; procedure ExecSaveAs; procedure ExecLoad; procedure ExecNew; procedure CheckForSave; procedure SetChanged(Value: Boolean); procedure SetFileName(Value: String); property IsChanged: Boolean read FChanged write SetChanged; property FileName: String read FFileName write SetFileName; property IsNew: Boolean read FIsNew write FIsNew; public { Public declarations } end; var SpellDemoForm: TSpellDemoForm; implementation uses AboutUnit; {$R *.DFM} const Counter: Integer = 0; procedure TSpellDemoForm.UpdateButtons; begin CopyBtn.Enabled:= RichEdit.SelLength>0; CutBtn.Enabled:= RichEdit.SelLength>0; FindBtn.Enabled:= RichEdit.Lines.Count>0; ReplaceBtn.Enabled:= RichEdit.Lines.Count>0; PasteBtn.Enabled:= Clipboard.HasFormat(CF_Text); UndoBtn.Enabled:= Boolean(SendMessage(RichEdit.Handle, EM_CANUNDO, 0, 0)); CopyMI.Enabled:= CopyBtn.Enabled; CutMI.Enabled:= CutBtn.Enabled; FindMI.Enabled:= FindBtn.Enabled; ReplaceMI.Enabled:= ReplaceBtn.Enabled; PasteMI.Enabled:= PasteBtn.Enabled; UndoMI.Enabled:= UndoBtn.Enabled; end; procedure TSpellDemoForm.ExecSave; begin if IsNew then ExecSaveAs else begin RichEdit.Lines.SaveToFile(FileName); IsChanged:= False; end; end; procedure TSpellDemoForm.ExecSaveAs; begin SaveDialog.FileName:= FileName; if SaveDialog.Execute then begin RichEdit.Lines.SaveToFile(FileName); IsNew:= False; IsChanged:= False; end; end; procedure TSpellDemoForm.ExecLoad; begin CheckForSave; OpenDialog.FileName:= ''; if OpenDialog.Execute then begin FileName:= OpenDialog.FileName; RichEdit.Lines.LoadFromFile(FileName); IsNew:= False; IsChanged:= False; RichEditSelectionChange(Self); end; end; procedure TSpellDemoForm.ExecNew; begin CheckForSave; Inc(Counter); FileName:= 'Document'+IntToStr(Counter)+'.rtf'; RichEdit.Clear; RichEditSelectionChange(Self); IsNew:= True; IsChanged:= False; end; procedure TSpellDemoForm.CheckForSave; var Res: Integer; begin if not IsChanged then Exit; Res:= MessageBox(Handle, 'File is modified. Save before closing?', 'Warning', mb_YesNoCancel+mb_IconQuestion); if Res=id_Cancel then Abort; if Res=id_Yes then ExecSave; end; procedure TSpellDemoForm.SetChanged(Value: Boolean); begin FChanged:= Value; if Value then StatusBar.SimpleText:= 'Modified' else StatusBar.SimpleText:= ''; end; procedure TSpellDemoForm.SetFileName(Value: String); begin FFileName:= Value; Caption:= 'TSpellChecker demo - '+Value; end; procedure TSpellDemoForm.AboutMIClick(Sender: TObject); begin AboutForm.ShowModal; end; procedure TSpellDemoForm.FormShow(Sender: TObject); begin AboutForm.ShowModal; end; procedure TSpellDemoForm.NewMIClick(Sender: TObject); begin RichEdit.Clear; end; procedure TSpellDemoForm.SelectAllMIClick(Sender: TObject); begin RichEdit.SelectAll; UpdateButtons; end; procedure TSpellDemoForm.CutMIClick(Sender: TObject); begin RichEdit.CutToClipboard; IsChanged:= True; UpdateButtons; end; procedure TSpellDemoForm.CopyMIClick(Sender: TObject); begin RichEdit.CopyToClipboard; UpdateButtons; end; procedure TSpellDemoForm.PasteMIClick(Sender: TObject); begin RichEdit.PasteFromClipboard; IsChanged:= True; UpdateButtons; end; procedure TSpellDemoForm.FindMIClick(Sender: TObject); begin FindDialog.Execute; end; procedure TSpellDemoForm.ReplaceMIClick(Sender: TObject); begin ReplaceDialog.Execute; end; procedure TSpellDemoForm.SaveMIClick(Sender: TObject); begin ExecSave; end; procedure TSpellDemoForm.SaveAsMIClick(Sender: TObject); begin ExecSaveAs; end; procedure TSpellDemoForm.FindDialogFind(Sender: TObject); var SearchStart: Integer; FS: TFindTextExA; Flags: Integer; Buf: array[0..255]of Char; begin with TFindDialog(Sender) do begin if (frFindNext in Options) then SearchStart:= RichEdit.SelStart+RichEdit.SelLength else SearchStart:= RichEdit.SelStart; FS.chrg.cpMin:= SearchStart; FS.chrg.cpMax:= -1; StrPCopy(Buf, FindText); FS.lpstrText:= Buf; if (frMatchCase in Options) then Flags:= FT_MATCHCASE else Flags:= 0; if (frWholeWord in Options) then Flags:= Flags or FT_WHOLEWORD; if (SendMessage(RichEdit.Handle, EM_FINDTEXTEX, Flags, Integer(@FS))>0) then begin RichEdit.SelStart := FS.chrgText.cpMin; RichEdit.SelLength := FS.chrgText.cpMax - FS.chrgText.cpMin; UpdateButtons; end else MessageBox(Handle, PChar(Format('Text «%s» not found', [FindText])), 'Message', mb_Ok+mb_IconInformation); end; end; procedure TSpellDemoForm.ReplaceDialogReplace(Sender: TObject); var SearchStart: Integer; ReplCount: Integer; FS: TFindTextExA; Flags: Integer; Buf: array[0..255]of Char; begin with TReplaceDialog(Sender) do begin if (frReplaceAll in Options) then begin ReplCount:= 0; FS.chrg.cpMin:= RichEdit.SelStart; FS.chrg.cpMax:= -1; StrPCopy(Buf, FindText); FS.lpstrText:= Buf; if (frMatchCase in Options) then Flags:= FT_MATCHCASE else Flags:= 0; if (frWholeWord in Options) then Flags:= Flags or FT_WHOLEWORD; while (SendMessage(RichEdit.Handle, EM_FINDTEXTEX, Flags, Integer(@FS))>-1) do begin RichEdit.SelStart := FS.chrgText.cpMin; RichEdit.SelLength := FS.chrgText.cpMax - FS.chrgText.cpMin; RichEdit.SelText:= ReplaceText; UpdateButtons; Inc(ReplCount); FS.chrg.cpMin:= RichEdit.SelStart+Length(ReplaceText); end; MessageBox(Handle, PChar(Format('%d replaces were made', [ReplCount])), 'Message', mb_Ok+mb_IconInformation); end else begin if (frFindNext in Options) then SearchStart:= RichEdit.SelStart+RichEdit.SelLength else SearchStart:= RichEdit.SelStart; FS.chrg.cpMin:= SearchStart; FS.chrg.cpMax:= -1; StrPCopy(Buf, FindText); FS.lpstrText:= Buf; if (frMatchCase in Options) then Flags:= FT_MATCHCASE else Flags:= 0; if (frWholeWord in Options) then Flags:= Flags or FT_WHOLEWORD; if (SendMessage(RichEdit.Handle, EM_FINDTEXTEX, Flags, Integer(@FS))>-1) then begin RichEdit.SelStart := FS.chrgText.cpMin; RichEdit.SelLength := FS.chrgText.cpMax - FS.chrgText.cpMin; RichEdit.SelText:= ReplaceText; UpdateButtons; end else MessageBox(Handle, PChar(Format('Text «%s» not found', [FindText])), 'Message', mb_Ok+mb_IconInformation); end; end; end; procedure TSpellDemoForm.UndoMIClick(Sender: TObject); begin SendMessage(RichEdit.Handle, EM_UNDO, 0, 0); SendMessage(RichEdit.Handle, EM_EMPTYUNDOBUFFER, 0, 0); UpdateButtons; end; procedure TSpellDemoForm.ExitMIClick(Sender: TObject); begin Close; end; procedure TSpellDemoForm.FormCreate(Sender: TObject); var Langs: TStringList; MI: TMenuItem; I: Integer; begin WasDropped:= False; FontCombo.Items.Assign(Screen.Fonts); FontCombo.ItemIndex:= FontCombo.Items.IndexOf('Arial'); Langs:= TStringList.Create; //Get list of installed spell-checkers GetSpellLanguages(Langs, loLocalized); Langs.Sort; // Fills Language menu with names of installed spell-checkers for I:= 0 to Langs.Count-1 do begin MI:= TMenuItem.Create(LanguageMI); // Takes name of spell-checker MI.Caption:= Langs[I]; // Takes spell-checker language MI.Tag:= Integer(Langs.Objects[I]); MI.GroupIndex:= 1; MI.RadioItem:= True; MI.Checked:= MI.Tag=langEnglishUS; MI.OnClick:= LangMIClick; LanguageMI.Add(MI); end; Langs.Free; ExecNew; UpdateButtons; end; procedure TSpellDemoForm.PrintMIClick(Sender: TObject); begin RichEdit.Print(Caption); end; procedure TSpellDemoForm.RichEditChange(Sender: TObject); begin IsChanged:= True; UpdateButtons; end; procedure TSpellDemoForm.RichEditSelectionChange(Sender: TObject); var L: TLanguage; S: String; begin L:= GetThreadLocale; S:= IntToStr(L); UpdateButtons; with RichEdit.SelAttributes do begin FontCombo.ItemIndex:= FontCombo.Items.IndexOf(Name); FontSize.Text:= IntToStr(Size); BoldBtn.Down:= fsBold in Style; ItalicBtn.Down:= fsItalic in Style; UndrlBtn.Down:= fsUnderline in Style; ColorCombo.Selected:= Color; end; with RichEdit.Paragraph do begin BulletsBtn.Down:= Numbering=nsBullet; LeftBtn.Down:= Alignment=taLeftJustify; CenterBtn.Down:= Alignment=taCenter; RightBtn.Down:= Alignment=taRightJustify; end; end; procedure TSpellDemoForm.OpenMIClick(Sender: TObject); begin ExecLoad; end; procedure TSpellDemoForm.PrintSetupMIClick(Sender: TObject); begin PrinterSetupDialog.Execute; end; procedure TSpellDemoForm.FontSizeKeyPress(Sender: TObject; var Key: Char); begin if not (Key in [#1..#31, '0'..'9']) then Key:= #0; end; procedure TSpellDemoForm.FontComboChange(Sender: TObject); begin RichEdit.SelAttributes.Name:= FontCombo.Text; ActiveControl:= RichEdit; end; procedure TSpellDemoForm.BoldBtnClick(Sender: TObject); begin if BoldBtn.Down then RichEdit.SelAttributes.Style:= RichEdit.SelAttributes.Style+[fsBold] else RichEdit.SelAttributes.Style:= RichEdit.SelAttributes.Style-[fsBold]; end; procedure TSpellDemoForm.ItalicBtnClick(Sender: TObject); begin if ItalicBtn.Down then RichEdit.SelAttributes.Style:= RichEdit.SelAttributes.Style+[fsItalic] else RichEdit.SelAttributes.Style:= RichEdit.SelAttributes.Style-[fsItalic]; end; procedure TSpellDemoForm.UndrlBtnClick(Sender: TObject); begin if UndrlBtn.Down then RichEdit.SelAttributes.Style:= RichEdit.SelAttributes.Style+[fsUnderline] else RichEdit.SelAttributes.Style:= RichEdit.SelAttributes.Style-[fsUnderline]; end; procedure TSpellDemoForm.ColorComboChange(Sender: TObject); begin RichEdit.SelAttributes.Color:= ColorCombo.Selected; ActiveControl:= RichEdit; end; procedure TSpellDemoForm.FormCloseQuery(Sender: TObject; var CanClose: Boolean); begin CheckForSave; end; procedure TSpellDemoForm.FontSizeKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); begin if Key=vk_Return then begin RichEdit.SelAttributes.Size:= StrToInt(FontSize.Text); ActiveControl:= RichEdit; end; end; procedure TSpellDemoForm.FontSizeChange(Sender: TObject); begin if WasDropped then begin RichEdit.SelAttributes.Size:= StrToInt(FontSize.Text); ActiveControl:= RichEdit; WasDropped:= False; end; end; procedure TSpellDemoForm.FontSizeDropDown(Sender: TObject); begin WasDropped:= True; end; procedure TSpellDemoForm.LeftBtnClick(Sender: TObject); begin RichEdit.Paragraph.Alignment:= taLeftJustify; end; procedure TSpellDemoForm.CenterBtnClick(Sender: TObject); begin RichEdit.Paragraph.Alignment:= taCenter; end; procedure TSpellDemoForm.RightBtnClick(Sender: TObject); begin RichEdit.Paragraph.Alignment:= taRightJustify; end; procedure TSpellDemoForm.BulletsBtnClick(Sender: TObject); begin if BulletsBtn.Down then RichEdit.Paragraph.Numbering:= nsBullet else RichEdit.Paragraph.Numbering:= nsNone; end; procedure TSpellDemoForm.FormDestroy(Sender: TObject); begin // Closes speller if Speller.Active then Speller.Close; end; // Changes speller language procedure TSpellDemoForm.LangMIClick(Sender: TObject); var MI: TMenuItem; begin MI:= Sender as TMenuItem; MI.Checked:= True; // To change language speller must be closed if Speller.Active then Speller.Close; // Sets new language from selected menu item Speller.Language:= MI.Tag; end; procedure TSpellDemoForm.VariantsMenuPopup(Sender: TObject); var I: Integer; Variants: TStringList; MI: TMenuItem; begin for I:= VariantsMenu.Items.Count-1 downto 0 do VariantsMenu.Items.Delete(I); // To make some work speller must be opened if not Speller.Active then Speller.Open; // Checks selected word with current language // If word is unknown then populates VariantsMenu with alternatives if not Speller.IsKnownWord(RichEdit.SelText) then begin MI:= TMenuItem.Create(VariantsMenu); MI.Caption:= 'Spelling'; MI.ShortCut:= TextToShortCut('F7'); MI.OnClick:= SpellMIClick; VariantsMenu.Items.Add(MI); Variants:= TStringList.Create; //Get list of alternatives into Variants Speller.GetVariants(RichEdit.SelText, Variants); if Variants.Count>0 then begin MI:= TMenuItem.Create(VariantsMenu); MI.Caption:= '-'; VariantsMenu.Items.Add(MI); end; for I:= 0 to Variants.Count-1 do begin MI:= TMenuItem.Create(VariantsMenu); MI.Caption:= Variants[I]; MI.OnClick:= VariantMIClick; VariantsMenu.Items.Add(MI); end; Variants.Free; end; end; procedure TSpellDemoForm.RichEditMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin // When right-clicking selects word under mouse cursor if Button=mbRight then SendMessage(RichEdit.Handle, WM_LBUTTONDBLCLK, MK_LBUTTON, Y shl 16 +X); end; procedure TSpellDemoForm.SpellMIClick(Sender: TObject); begin // To make some work speller must be opened if not Speller.Active then Speller.Open; // Executes interactive spell checking Speller.CheckMemo(RichEdit); end; procedure TSpellDemoForm.VariantMIClick(Sender: TObject); begin // Replaces selected word with alterntive from popup menu RichEdit.SelText:= (Sender as TMenuItem).Caption; end; end.
{ Subroutine SST_R_SYO_DECLARE * * Process DECLARE syntax. } module sst_r_syo_declare; define sst_r_syo_declare; %include 'sst_r_syo.ins.pas'; procedure sst_r_syo_declare; {process DECLARE syntax} const max_msg_parms = 1; {max parameters we can pass to a message} var tag: sys_int_machine_t; {tag from syntax tree} str_h, str2_h: syo_string_t; {handles to strings from input file} syname: string_var32_t; {name of syntax symbol being declared} prname: string_var32_t; {name of procedure to run syntax} token: string_var16_t; {scratch string for number conversion} hpos: string_hash_pos_t; {hash table position handle} found: boolean; {TRUE if name found in hash table} flags: sst_symflag_t; {flags for SST subroutine name symbol} name_p: string_var_p_t; {pointer to name in hash table entry} data_p: symbol_data_p_t; {pointer to user data in hash table entry} arg_p: sst_proc_arg_p_t; {pointer to info about subroutine argument} dt_p: sst_dtype_p_t; {scratch pointer to data type descriptor} msg_parm: {parameter references for messages} array[1..max_msg_parms] of sys_parm_msg_t; stat: sys_err_t; label opt_tag, done_opt_tags; begin syname.max := sizeof(syname.str); {init local var strings} prname.max := sizeof(prname.str); token.max := sizeof(token.str); syo_level_down; {down into DECLARE syntax} syo_get_tag_msg ( {get symbol name tag} tag, str_h, 'sst_syo_read', 'syerr_declare', nil, 0); if tag <> 1 then syo_error_tag_unexp (tag, str_h); syo_get_tag_string (str_h, syname); {get name of symbol being declared} { * Init to defaults before processing options. } prname.len := 0; {subroutine name not explicitly set} flags := []; {syntax subroutine will be local to this file} { * Back here to get each optional tag. } opt_tag: syo_get_tag_msg ( {get tag for next option, if any} tag, str2_h, 'sst_syo_read', 'syerr_declare', nil, 0); case tag of 1: begin {tag is for subroutine name} syo_get_tag_string (str2_h, prname); flags := flags + [sst_symflag_global_k]; {subroutine will be globally visible} end; 2: begin {tag is EXTERNAL option} flags := flags + [sst_symflag_extern_k]; {subroutine not defined here} end; syo_tag_end_k: begin {done processing all the optional tags} if prname.len = 0 then begin {need to make subroutine name ?} string_copy (prefix, prname); {init subroutine name with prefix} prname.len := min(prname.len, prname.max - 6); {leave room for suffix} string_appendn (prname, '_sy', 3); string_f_int_max_base ( {make subroutine sequence number string} token, {output string} seq_subr, {input number} 10, {base} 3, {field width} [string_fi_leadz_k, string_fi_unsig_k], {write leading zeros, no sign} stat); syo_error_abort (stat, str2_h, 'sst_syo_read', 'seq_subr_err', nil, 0); string_append (prname, token); {make full subroutine name} seq_subr := seq_subr + 1; {update sequence number for next time} string_downcase (prname); {default subroutine names are lower case} end; goto done_opt_tags; {all done processing tags} end; otherwise syo_error_tag_unexp (tag, str2_h); end; {end of optional tag type cases} goto opt_tag; {back for next optional tag} done_opt_tags: {done processing optional tags} syo_level_up; {back up from DECLARE syntax} string_upcase (syname); {SYN file symbols are case-insensitive} { * All done reading the input stream for this SYMBOL command. * The SYN file symbol name is in SYNAME, and the subroutine name is * in PRNAME. } %debug; writeln ('Declaring "', syname.str:syname.len, %debug; '", subroutine "', prname.str:prname.len, '"'); string_hash_pos_lookup ( {get hash table position for new name} table_sym, syname, hpos, found); if found then begin {this symbol already declared ?} sys_msg_parm_vstr (msg_parm[1], syname); syo_error (str_h, 'sst_syo_read', 'symbol_already_used', msg_parm, 1); end; string_hash_ent_add ( {add new symbol to the SYN symbol table} hpos, {handle to hash table position} name_p, {points to name in hash table entry} data_p); {points to data area in hash table entry} sst_symbol_new_name ( {add subroutine name to SST symbol table} prname, data_p^.sym_p, stat); syo_error_abort (stat, str_h, '', '', nil, 0); data_p^.name_p := name_p; {save pointer to hash entry name} data_p^.call_p := nil; {init list of called syntaxes to empty} sst_scope_new; {create private scope for new subroutine} sst_scope_p^.symbol_p := data_p^.sym_p; sst_mem_alloc_scope (sizeof(arg_p^), arg_p); {alloc memory for subr arg descriptor} { * Fill in descriptor for subroutine name symbol. } sst_dtype_new (dt_p); {create PROC data type descriptor} dt_p^.dtype := sst_dtype_proc_k; dt_p^.proc_p := addr(data_p^.sym_p^.proc); data_p^.sym_p^.symtype := sst_symtype_proc_k; {fill in SST symbol descriptor} data_p^.sym_p^.flags := flags; data_p^.sym_p^.proc.sym_p := data_p^.sym_p; data_p^.sym_p^.proc.dtype_func_p := nil; data_p^.sym_p^.proc.n_args := 1; data_p^.sym_p^.proc.flags := []; data_p^.sym_p^.proc.first_arg_p := arg_p; data_p^.sym_p^.proc_scope_p := sst_scope_p; data_p^.sym_p^.proc_dtype_p := dt_p; data_p^.sym_p^.proc_funcvar_p := nil; { * Fill in descriptor for MFLAG subroutine argument. } arg_p^.next_p := nil; sst_symbol_new_name ( {create symbol for subroutine argument} string_v('mflag'(0)), arg_p^.sym_p, stat); syo_error_abort (stat, str_h, '', '', nil, 0); arg_p^.name_p := nil; arg_p^.exp_p := nil; arg_p^.dtype_p := sym_mflag_t_p^.dtype_dtype_p; arg_p^.pass := sst_pass_ref_k; arg_p^.rwflag_int := [sst_rwflag_read_k, sst_rwflag_write_k]; arg_p^.rwflag_ext := [sst_rwflag_write_k]; arg_p^.univ := false; { * Fill in symbol descriptor for MFLAG dummy variable. } arg_p^.sym_p^.symtype := sst_symtype_var_k; arg_p^.sym_p^.flags := [sst_symflag_def_k]; arg_p^.sym_p^.var_dtype_p := arg_p^.dtype_p; arg_p^.sym_p^.var_val_p := nil; arg_p^.sym_p^.var_arg_p := arg_p; arg_p^.sym_p^.var_proc_p := addr(data_p^.sym_p^.proc); arg_p^.sym_p^.var_com_p := nil; arg_p^.sym_p^.var_next_p := nil; sst_scope_old; {pop back from subroutine's scope} end;
unit HGM.BlurGaussian; interface uses Windows, Graphics, SysUtils; type PRGBTriple = ^TRGBTriple; TRGBTriple = packed record R:Byte; G:Byte; B:Byte; end; PRow = ^TRow; TRow = array[0..1000000] of TRGBTriple; PPRows = ^TPRows; TPRows = array[0..1000000] of PRow; const MaxKernelSize = 100; type TKernelSize = 1..MaxKernelSize; TKernel = record Size:TKernelSize; Weights:array[-MaxKernelSize..MaxKernelSize] of Single; end; procedure GBlur(BMP:TBitmap; Radius:Double); implementation function TrimValue(Lower, Upper, Value:Integer):Integer; overload; begin if (Value <= Upper) and (Value >= Lower) then Result:=Value else if Value > Upper then Result:=Upper else Result:=Lower; end; function TrimValue(Lower, Upper:Integer; Value:Double):Integer; overload; begin if (Value < Upper) and (Value >= Lower) then Result:=Trunc(Value) else if Value > Upper then Result:=Upper else Result:=Lower; end; procedure GBlur(BMP:TBitmap; Radius:Double); var Row, Col:Integer; Rows:PPRows; K:TKernel; ACol:PRow; P:PRow; procedure BlurRow(var Row:array of TRGBTriple; K:TKernel; P:PRow); var j, n:Integer; tr, tg, tb:Double; w:Double; begin for j:=0 to High(Row) do begin tb:=0; tg:=0; tr:=0; for n:= -K.Size to K.Size do begin w:=K.Weights[n]; with Row[TrimValue(0, High(Row), j - n)] do begin tb:=tb + w * b; tg:=tg + w * g; tr:=tr + w * r; end; end; with P[j] do begin b:=TrimValue(0, 255, tb); g:=TrimValue(0, 255, tg); r:=TrimValue(0, 255, tr); end; end; Move(P[0], Row[0], (High(Row) + 1) * Sizeof(TRGBTriple)); end; procedure MakeGaussianKernel(var K:TKernel; Radius:Double; MaxData, DataGranularity:Double); var j:Integer; temp, delta:Double; KernelSize:TKernelSize; begin for j:=Low(K.Weights) to High(K.Weights) do begin temp:=j / radius; K.Weights[j]:=exp(-temp * temp / 2); end; temp:=0; for j:=Low(K.Weights) to High(K.Weights) do temp:=temp + K.Weights[j]; for j:=Low(K.Weights) to High(K.Weights) do K.Weights[j]:=K.Weights[j] / temp; KernelSize:=MaxKernelSize; delta:=DataGranularity / (2 * MaxData); temp:=0; while (temp < delta) and (KernelSize > 1) do begin temp:=temp + 2 * K.Weights[KernelSize]; Dec(KernelSize); end; K.Size:=KernelSize; temp:=0; for j:= -K.Size to K.Size do temp:=temp + K.Weights[j]; for j:= -K.Size to K.Size do K.Weights[j]:=K.Weights[j] / temp; end; begin if (BMP.HandleType <> bmDIB) or (BMP.PixelFormat <> pf24Bit) then begin raise Exception.Create('Необходимо 24-битное изображение'); end; MakeGaussianKernel(K, Radius, 255, 1); GetMem(Rows, BMP.Height * SizeOf(PRow)); GetMem(ACol, BMP.Height * SizeOf(TRGBTriple)); for Row:=0 to BMP.Height - 1 do Rows[Row]:=BMP.Scanline[Row]; P:=AllocMem(BMP.Width * SizeOf(TRGBTriple)); for Row:=0 to BMP.Height - 1 do BlurRow(Slice(Rows[Row]^, BMP.Width), K, P); ReAllocMem(P, BMP.Height * SizeOf(TRGBTriple)); for Col:=0 to BMP.Width - 1 do begin for Row:=0 to BMP.Height - 1 do ACol[Row]:=Rows[Row][Col]; BlurRow(Slice(ACol^, BMP.Height), K, P); for Row:=0 to BMP.Height - 1 do Rows[Row][Col]:=ACol[Row]; end; FreeMem(Rows); FreeMem(ACol); ReAllocMem(P, 0); end; end.
unit FrmMain; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls; type TMainForm = class(TForm) lblButtonPressed: TLabel; procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } procedure CMDialogKey(var msg: TCMDialogKey); message CM_DIALOGKEY; public { Public declarations } end; var MainForm: TMainForm; implementation {$R *.dfm} //to allow VK_TAB etc keycode to be shown / used in onkeydown procedure TMainForm.CMDialogKey(var msg: TCMDialogKey); begin msg.Result := 0; end; procedure TMainForm.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var RealKey: Word; begin if Application.Terminated then Exit; RealKey := Key; if RealKey = VK_SHIFT then if GetKeyState(VK_LSHIFT) < 0 then RealKey := VK_LSHIFT else if GetKeyState(VK_RSHIFT) < 0 then RealKey := VK_RSHIFT; if RealKey = VK_CONTROL then if GetKeyState(VK_LCONTROL) < 0 then RealKey := VK_LCONTROL else if GetKeyState(VK_RCONTROL) < 0 then RealKey := VK_RCONTROL; if RealKey = VK_MENU then if GetKeyState(VK_LMENU) < 0 then RealKey := VK_LMENU else if GetKeyState(VK_RMENU) < 0 then RealKey := VK_RMENU; lblButtonPressed.Caption := 'Last Key Pressed: ' + IntToStr(RealKey); end; end.
{ $Project$ $Workfile$ $Revision$ $DateUTC$ $Id$ This file is part of the Indy (Internet Direct) project, and is offered under the dual-licensing agreement described on the Indy website. (http://www.indyproject.org/) Copyright: (c) 1993-2005, Chad Z. Hower and the Indy Pit Crew. All rights reserved. } { $Log$ } { Rev 1.18 2/8/05 5:24:48 PM RLebeau Updated Disconnect() to not wait for the listening thread to terminate until after the inherited Disconnect() is called, so that the socket is actually disconnected and the thread can terminate properly. Rev 1.17 2/1/05 12:38:30 AM RLebeau Removed unused CommandHandlersEnabled property Rev 1.16 6/11/2004 8:48:16 AM DSiders Added "Do not Localize" comments. Rev 1.15 5/18/04 9:12:26 AM RLebeau Bug fix for SetExceptionReply() property setter Rev 1.14 5/16/04 5:18:04 PM RLebeau Added setter method to ExceptionReply property Rev 1.13 5/10/2004 6:10:38 PM DSiders Removed unused member var FCommandHandlersInitialized. Rev 1.12 2004.03.06 1:33:00 PM czhower -Change to disconnect -Addition of DisconnectNotifyPeer -WriteHeader now write bufers Rev 1.11 2004.03.01 5:12:24 PM czhower -Bug fix for shutdown of servers when connections still existed (AV) -Implicit HELP support in CMDserver -Several command handler bugs -Additional command handler functionality. Rev 1.10 2004.02.03 4:17:10 PM czhower For unit name changes. Rev 1.9 2004.01.20 10:03:22 PM czhower InitComponent Rev 1.8 1/4/04 8:46:16 PM RLebeau Added OnBeforeCommandHandler and OnAfterCommandHandler events Rev 1.7 11/4/2003 10:25:40 PM DSiders Removed duplicate FReplyClass member in TIdCmdTCPClient (See TIdTCPConnection). Rev 1.6 10/21/2003 10:54:20 AM JPMugaas Fix for new API change. Rev 1.5 2003.10.18 9:33:24 PM czhower Boatload of bug fixes to command handlers. Rev 1.4 2003.10.02 10:16:26 AM czhower .Net Rev 1.3 2003.09.19 11:54:26 AM czhower -Completed more features necessary for servers -Fixed some bugs Rev 1.2 7/9/2003 10:55:24 PM BGooijen Restored all features Rev 1.1 7/9/2003 04:36:06 PM JPMugaas You now can override the TIdReply with your own type. This should illiminate some warnings about some serious issues. TIdReply is ONLY a base class with virtual methods. Rev 1.0 7/7/2003 7:06:40 PM SPerry Component that uses command handlers Rev 1.0 7/6/2003 4:47:26 PM SPerry Units that use Command handlers } unit IdCmdTCPClient; { Original author: Sergio Perry Description: TCP client that uses CommandHandlers } interface {$I IdCompilerDefines.inc} uses IdContext, IdException, IdGlobal, IdReply, IdResourceStringsCore, IdThread, IdTCPClient, IdCommandHandlers; type TIdCmdTCPClient = class; { Events } TIdCmdTCPClientAfterCommandHandlerEvent = procedure(ASender: TIdCmdTCPClient; AContext: TIdContext) of object; TIdCmdTCPClientBeforeCommandHandlerEvent = procedure(ASender: TIdCmdTCPClient; var AData: string; AContext: TIdContext) of object; { Listening Thread } TIdCmdClientContext = class(TIdContext) protected FClient: TIdCmdTCPClient; public property Client: TIdCmdTCPClient read FClient; end; TIdCmdTCPClientListeningThread = class(TIdThread) protected FContext: TIdCmdClientContext; FClient: TIdCmdTCPClient; FRecvData: String; // procedure Run; override; public constructor Create(AClient: TIdCmdTCPClient); reintroduce; destructor Destroy; override; // property Client: TIdCmdTCPClient read FClient; property RecvData: String read FRecvData write FRecvData; end; { TIdCmdTCPClient } TIdCmdTCPClient = class(TIdTCPClient) protected FExceptionReply: TIdReply; FListeningThread: TIdCmdTCPClientListeningThread; FCommandHandlers: TIdCommandHandlers; FOnAfterCommandHandler: TIdCmdTCPClientAfterCommandHandlerEvent; FOnBeforeCommandHandler: TIdCmdTCPClientBeforeCommandHandlerEvent; // procedure DoAfterCommandHandler(ASender: TIdCommandHandlers; AContext: TIdContext); procedure DoBeforeCommandHandler(ASender: TIdCommandHandlers; var AData: string; AContext: TIdContext); procedure DoReplyUnknownCommand(AContext: TIdContext; ALine: string); virtual; function GetCmdHandlerClass: TIdCommandHandlerClass; virtual; procedure InitComponent; override; procedure SetCommandHandlers(AValue: TIdCommandHandlers); procedure SetExceptionReply(AValue: TIdReply); public procedure Connect; override; destructor Destroy; override; procedure Disconnect(ANotifyPeer: Boolean); override; published property CommandHandlers: TIdCommandHandlers read FCommandHandlers write SetCommandHandlers; property ExceptionReply: TIdReply read FExceptionReply write SetExceptionReply; // property OnAfterCommandHandler: TIdCmdTCPClientAfterCommandHandlerEvent read FOnAfterCommandHandler write FOnAfterCommandHandler; property OnBeforeCommandHandler: TIdCmdTCPClientBeforeCommandHandlerEvent read FOnBeforeCommandHandler write FOnBeforeCommandHandler; end; EIdCmdTCPClientError = class(EIdException); EIdCmdTCPClientConnectError = class(EIdCmdTCPClientError); implementation uses IdReplyRFC, SysUtils; type TIdCmdClientContextAccess = class(TIdCmdClientContext) end; { Listening Thread } constructor TIdCmdTCPClientListeningThread.Create(AClient: TIdCmdTCPClient); begin FClient := AClient; FContext := TIdCmdClientContext.Create(AClient, nil, nil); FContext.FClient := AClient; TIdCmdClientContextAccess(FContext).FOwnsConnection := False; // inherited Create(False); end; destructor TIdCmdTCPClientListeningThread.Destroy; begin inherited Destroy; FreeAndNil(FContext); end; procedure TIdCmdTCPClientListeningThread.Run; begin FRecvData := FClient.IOHandler.ReadLn; if not FClient.CommandHandlers.HandleCommand(FContext, FRecvData) then begin FClient.DoReplyUnknownCommand(FContext, FRecvData); end; //Synchronize(?); if not Terminated then begin FClient.IOHandler.CheckForDisconnect; end; end; { TIdCmdTCPClient } destructor TIdCmdTCPClient.Destroy; begin Disconnect; FreeAndNil(FExceptionReply); FreeAndNil(FCommandHandlers); inherited Destroy; end; procedure TIdCmdTCPClient.Connect; begin inherited Connect; // try FListeningThread := TIdCmdTCPClientListeningThread.Create(Self); except Disconnect(True); raise EIdCmdTCPClientConnectError.Create(RSNoCreateListeningThread); // translate end; end; procedure TIdCmdTCPClient.Disconnect(ANotifyPeer: Boolean); begin if Assigned(FListeningThread) then begin FListeningThread.Terminate; end; try inherited Disconnect(ANotifyPeer); finally if Assigned(FListeningThread) and not IsCurrentThread(FListeningThread) then begin FListeningThread.WaitFor; FreeAndNil(FListeningThread); end; end; end; procedure TIdCmdTCPClient.DoAfterCommandHandler(ASender: TIdCommandHandlers; AContext: TIdContext); begin if Assigned(OnAfterCommandHandler) then begin OnAfterCommandHandler(Self, AContext); end; end; procedure TIdCmdTCPClient.DoBeforeCommandHandler(ASender: TIdCommandHandlers; var AData: string; AContext: TIdContext); begin if Assigned(OnBeforeCommandHandler) then begin OnBeforeCommandHandler(Self, AData, AContext); end; end; procedure TIdCmdTCPClient.DoReplyUnknownCommand(AContext: TIdContext; ALine: string); begin end; function TIdCmdTCPClient.GetCmdHandlerClass: TIdCommandHandlerClass; begin Result := TIdCommandHandler; end; procedure TIdCmdTCPClient.InitComponent; var LHandlerClass: TIdCommandHandlerClass; begin inherited InitComponent; FExceptionReply := FReplyClass.Create(nil); ExceptionReply.SetReply(500, 'Unknown Internal Error'); {do not localize} LHandlerClass := GetCmdHandlerClass; FCommandHandlers := TIdCommandHandlers.Create(Self, FReplyClass, nil, ExceptionReply, LHandlerClass); FCommandHandlers.OnAfterCommandHandler := DoAfterCommandHandler; FCommandHandlers.OnBeforeCommandHandler := DoBeforeCommandHandler; end; procedure TIdCmdTCPClient.SetCommandHandlers(AValue: TIdCommandHandlers); begin FCommandHandlers.Assign(AValue); end; procedure TIdCmdTCPClient.SetExceptionReply(AValue: TIdReply); begin FExceptionReply.Assign(AValue); end; end.
unit ElHeaderDemoMain; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, ElImgFrm, ElBtnEdit, ElPopBtn, StdCtrls, ElACtrls, ElSpin, ElBtnCtl, ElVCLUtils, ElCheckCtl, ElGroupBox, ElHeader, ExtCtrls, ElPanel, ElImgLst, ElCheckItemGrp, ElXPThemedControl, ImgList, ElEdits; type TElHeaderDemoMainForm = class(TForm) ElHeaderImageForm: TElImageForm; ElHeaderSectionsGroupBox: TElGroupBox; Label2: TLabel; Label3: TLabel; Label4: TLabel; ElHeaderSectionSpinEdit: TElSpinEdit; ElHeaderAddButton: TElPopupButton; ElHeaderDeleteButton: TElPopupButton; ElHeaderTextButtonEdit: TElButtonEdit; ElHeaderHintButtonEdit: TElButtonEdit; ElHeaderCanClickCB: TElCheckBox; ElHeaderGeneralGroupbox: TElGroupBox; ElHeaderFlatCB: TElCheckBox; ElHeaderDraggableSectionsCB: TElCheckBox; ElHeaderMoveOnDragCB: TElCheckBox; ElHeaderUseImageFormCB: TElCheckBox; ElHeaderWrapCaptionsCB: TElCheckBox; ElHeaderResizeOnDragCB: TElCheckBox; sampleElHeader: TElHeader; ElHeaderCanResizeCB: TElCheckBox; ElHeaderSectionMinWidthSpinEdit: TElSpinEdit; Label1: TLabel; Label5: TLabel; ElHeaderSectionMaxWidthSpinEdit: TElSpinEdit; ElHeaderAutoSizeCB: TElCheckBox; ElHeaderTextAlignRG: TElRadioGroup; ElHeaderImageAlignRG: TElRadioGroup; Label6: TLabel; ElHeaderSectionImageIndexSpinEdit: TElSpinEdit; ElHeaderSectionVisibleCB: TElCheckBox; ElHeaderSectionSortSignRG: TElRadioGroup; HeaderImages: TElImageList; procedure ElHeaderAddButtonClick(Sender: TObject); procedure ElHeaderCanClickCBClick(Sender: TObject); procedure ElHeaderDraggableSectionsCBClick(Sender: TObject); procedure ElHeaderFlatCBClick(Sender: TObject); procedure ElHeaderMoveOnDragCBClick(Sender: TObject); procedure ElHeaderSectionSpinEditChange(Sender: TObject); procedure ElHeaderUseImageFormCBClick(Sender: TObject); procedure ElHeaderResizeOnDragCBClick(Sender: TObject); procedure ElHeaderWrapCaptionsCBClick(Sender: TObject); procedure ElHeaderTextButtonEditButtonClick(Sender: TObject); procedure ElHeaderHintButtonEditButtonClick(Sender: TObject); procedure ElHeaderDeleteButtonClick(Sender: TObject); procedure FormActivate(Sender: TObject); procedure ElHeaderSectionMinWidthSpinEditChange(Sender: TObject); procedure ElHeaderSectionMaxWidthSpinEditChange(Sender: TObject); procedure ElHeaderAutoSizeCBClick(Sender: TObject); procedure ElHeaderSectionVisibleCBClick(Sender: TObject); procedure ElHeaderSectionImageIndexSpinEditChange(Sender: TObject); procedure ElHeaderTextAlignRGClick(Sender: TObject); procedure ElHeaderImageAlignRGClick(Sender: TObject); procedure ElHeaderSectionSortSignRGClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var ElHeaderDemoMainForm: TElHeaderDemoMainForm; implementation {$R *.DFM} procedure TElHeaderDemoMainForm.ElHeaderAddButtonClick(Sender: TObject); begin sampleElHeader.Sections.AddSection; ElHeaderSectionSpinEdit.MaxValue := sampleElHeader.Sections.Count - 1; ElHeaderSectionSpinEditChange(Self); end; procedure TElHeaderDemoMainForm.ElHeaderCanClickCBClick(Sender: TObject); begin sampleElHeader.Sections[ElHeaderSectionSpinEdit.Value].AllowClick := ElHeaderCanClickCB.Checked; end; procedure TElHeaderDemoMainForm.ElHeaderDraggableSectionsCBClick(Sender: TObject); begin sampleElHeader.AllowDrag := ElHeaderDraggableSectionsCB.Checked; end; procedure TElHeaderDemoMainForm.ElHeaderFlatCBClick(Sender: TObject); begin SampleElHeader.Flat := ElHeaderFlatCB.Checked; end; procedure TElHeaderDemoMainForm.ElHeaderMoveOnDragCBClick(Sender: TObject); begin sampleElHeader.MoveOnDrag := ElHEaderMoveOnDragCB.Checked; end; procedure TElHeaderDemoMainForm.ElHeaderSectionSpinEditChange(Sender: TObject); begin ElHeaderTextButtonEdit.Text := sampleElHeader.Sections[ElHeaderSectionSpinEdit.Value].Text; ElHeaderHintButtonEdit.Text := sampleElHeader.Sections[ElHeaderSectionSpinEdit.Value].Hint; ElHeaderCanClickCB.Checked := sampleElHeader.Sections[ElHeaderSectionSpinEdit.Value].AllowClick; ElHeaderAutoSizeCB.Checked := sampleElHeader.Sections[ElHeaderSectionSpinEdit.Value].AutoSize; ElHeaderCanResizeCB.Checked := sampleElHeader.Sections[ElHeaderSectionSpinEdit.Value].Resizable; ElHeaderSectionMinWidthSpinEdit.Value := sampleElHeader.Sections[ElHeaderSectionSpinEdit.Value].MinWidth; ElHeaderSectionMaxWidthSpinEdit.Value := sampleElHeader.Sections[ElHeaderSectionSpinEdit.Value].MaxWidth; ElHeaderSectionImageIndexSpinEdit.Value := sampleElHeader.Sections[ElHeaderSectionSpinEdit.Value].ImageIndex; ElHeaderTextAlignRG.ItemIndex := Integer(sampleElHeader.Sections[ElHeaderSectionSpinEdit.Value].Alignment); ElHeaderImageAlignRG.ItemIndex := Integer(sampleElHeader.Sections[ElHeaderSectionSpinEdit.Value].PictureAlign); ElHeaderSectionSortSignRG.ItemIndex := Integer(sampleElHeader.Sections[ElHeaderSectionSpinEdit.Value].SortMode); end; procedure TElHeaderDemoMainForm.ElHeaderUseImageFormCBClick(Sender: TObject); begin if ElHeaderUseImageFormCB.Checked then begin ElHeaderImageForm.BackgroundType := bgtTileBitmap; end else begin ElHeaderImageForm.BackgroundType := bgtColorFill; end; end; procedure TElHeaderDemoMainForm.ElHeaderResizeOnDragCBClick( Sender: TObject); begin sampleElHeader.ResizeOnDrag := ElHeaderResizeOnDragCB.Checked; end; procedure TElHeaderDemoMainForm.ElHeaderWrapCaptionsCBClick( Sender: TObject); begin sampleElHeader.WrapCaptions := ElHeaderWrapCaptionsCB.Checked; end; procedure TElHeaderDemoMainForm.ElHeaderTextButtonEditButtonClick( Sender: TObject); begin sampleElHeader.Sections[ElHeaderSectionSpinEdit.Value].Text := ElHEaderTextButtonEdit.Text; end; procedure TElHeaderDemoMainForm.ElHeaderHintButtonEditButtonClick( Sender: TObject); begin sampleElHeader.Sections[ElHeaderSectionSpinEdit.Value].Hint := ElHeaderHintButtonEdit.Text; end; procedure TElHeaderDemoMainForm.ElHeaderDeleteButtonClick(Sender: TObject); begin if sampleElHeader.Sections.Count > 1 then begin sampleElHeader.Sections.DeleteSection(sampleElHeader.Sections[ElHeaderSectionSpinEdit.Value]); ElHeaderSectionSpinEdit.MaxValue := sampleElHeader.Sections.Count - 1; ElHeaderDeleteButton.Enabled := sampleElHeader.Sections.Count > 0; ElHeaderSectionSpinEditChange(Self); end; end; procedure TElHeaderDemoMainForm.FormActivate(Sender: TObject); begin ElHeaderSectionSpinEditChange(Self); end; procedure TElHeaderDemoMainForm.ElHeaderSectionMinWidthSpinEditChange( Sender: TObject); begin sampleElHeader.Sections[ElHeaderSectionSpinEdit.Value].MinWidth := ElHeaderSectionMinWidthSpinEdit.Value; end; procedure TElHeaderDemoMainForm.ElHeaderSectionMaxWidthSpinEditChange( Sender: TObject); begin sampleElHeader.Sections[ElHeaderSectionSpinEdit.Value].MaxWidth := ElHeaderSectionMaxWidthSpinEdit.Value; end; procedure TElHeaderDemoMainForm.ElHeaderAutoSizeCBClick(Sender: TObject); begin sampleElHeader.Sections[ElHeaderSectionSpinEdit.Value].AutoSize := ElHeaderAutoSizeCB.Checked; end; procedure TElHeaderDemoMainForm.ElHeaderSectionVisibleCBClick( Sender: TObject); begin sampleElHeader.Sections[ElHeaderSectionSpinEdit.Value].Visible := ElHeaderSectionVisibleCB.Checked; end; procedure TElHeaderDemoMainForm.ElHeaderSectionImageIndexSpinEditChange( Sender: TObject); begin sampleElHeader.Sections[ElHeaderSectionSpinEdit.Value].ImageIndex := ElHeaderSectionImageIndexSpinEdit.Value; end; procedure TElHeaderDemoMainForm.ElHeaderTextAlignRGClick(Sender: TObject); begin sampleElHeader.Sections[ElHeaderSectionSpinEdit.Value].Alignment := TElSAlignment(ElHeaderTextAlignRG.ItemIndex); end; procedure TElHeaderDemoMainForm.ElHeaderImageAlignRGClick(Sender: TObject); begin sampleElHeader.Sections[ElHeaderSectionSpinEdit.Value].PictureAlign := TElSAlignment(ElHeaderImageAlignRG.ItemIndex); end; procedure TElHeaderDemoMainForm.ElHeaderSectionSortSignRGClick( Sender: TObject); begin sampleElHeader.Sections[ElHeaderSectionSpinEdit.Value].SortMode := TElSSortMode(ElHeaderSectionSortSignRG.ItemIndex); end; end.
unit tfwScriptDebugger; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, afwTextControlPrim, afwTextControl, vtPanel, vtSizeablePanel, OvcBase, afwControlPrim, afwBaseControl, afwControl, nevControl, evCustomEditorWindowPrim, evEditorWindow, evCustomEditorWindowModelPart, evMultiSelectEditorWindow, evCustomEditorModelPart, evCustomEditor, evEditorWithOperations, evCustomMemo, evMemo, tfwScriptingInterfaces, tb97GraphicControl, TB97Ctls, evButton, l3CardinalList, l3Interfaces, afwInputControl, vtLister, ExtCtrls, l3WinControlCanvas, evCustomEditorWindow, vtPanelPrim ; type TtfwScriptDebugger_Form = class(TForm, ItfwScriptCaller) edScript: TevMemo; pnFooter: TvtSizeablePanel; pnHeader: TvtSizeablePanel; edOutput: TevMemo; btRun: TevButton; btClear: TevButton; lstStack : TvtLister; pnStack: TvtSizeablePanel; tmStack: TTimer; procedure btRunClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure btClearClick(Sender: TObject); procedure lstStackGetStrItem(Sender: TObject; Index: Integer; var ItemString: Il3CString); procedure tmStackTimer(Sender: TObject); procedure FormDestroy(Sender: TObject); private f_Starts : Tl3CardinalList; {* Начальные точки замеров} f_TextForm : TCustomForm; { Private declarations } procedure Check(aCondition: Boolean; const aMessage : AnsiString = ''); {* Проверяет инвариант } procedure Print(const aStr: Tl3WString); overload; procedure Print(const aStr: Il3CString); overload; function ResolveIncludedFilePath(const aFile: AnsiString): AnsiString; function ResolveOutputFilePath(const aFile: AnsiString): AnsiString; function ResolveInputFilePath(const aFile: AnsiString): AnsiString; function SystemDictionary: IStream; procedure CheckPictureOnly; procedure CheckWithEtalon(const aFileName: AnsiString; aHeaderBegin: AnsiChar); procedure CheckOutputWithInput(const aIn: AnsiString; const aOut: AnsiString; aHeaderBegin: AnsiChar; aEtalonNeedsComputerName: Boolean; aEtalonCanHaveDiff: Boolean; const anExtraFileName: AnsiString; aNeedsCheck: Boolean); overload; procedure CheckOutputWithInput(const aSt: AnsiString; aHeaderBegin: AnsiChar = #0; const anExtraFileName: AnsiString = ''; aNeedsCheck: Boolean = true); overload; //function PrepareForm(aClass: TClass): TCustomForm; procedure CheckPrintEtalon(const aLogName: AnsiString; const aOutputName: AnsiString); function ShouldStop: Boolean; procedure CheckTimeout(aNow: Cardinal; aTimeout: Cardinal); function StartTimer: Longword; function StopTimer(const aSt: AnsiString = ''; const aSubName: AnsiString = ''; aNeedTimeToLog: Boolean = true): Longword; function KPage: AnsiString; procedure ToLog(const aSt: AnsiString); function CompileOnly: Boolean; function GetIsWritingToK: Boolean; function GetIsFakeCVS: Boolean; function GetCVSPath: AnsiString; procedure TimeToLog(aTime: Cardinal; const aSt: AnsiString; const aSubName: AnsiString); {* Выводит замер времени в лог } function GetEtalonSuffix: AnsiString; procedure ScriptDone(const aCtx: TtfwContext); procedure ScriptWillRun(const aCtx: TtfwContext); protected procedure DontRaiseIfEtalonCreated; function GetTestSetFolderName: AnsiString; public { Public declarations } procedure LoadScriptFromFile(aFileName: AnsiString); procedure RunScript; end; var g_DebuggerForm: TtfwScriptDebugger_Form; implementation {$R *.dfm} uses vcmInsiderTest, tfwScriptEngine, l3String, afwAnswer, {$IfNDef NoVCM} vcmForm, vcmBase, {$EndIf NoVCM} k2Reader, {$IF not Defined(Nemesis) and not Defined(Archi) and not Defined(EverestLite)} //AutoTestFormFactory, {$IFEND} //_afwFacade, l3Base, l3Filer, evTxtRd, TypInfo, kwMain, l3BatchService, l3KeyboardLayoutService ; procedure TtfwScriptDebugger_Form.Check(aCondition: Boolean; const aMessage : AnsiString = ''); {* Проверяет инвариант } begin if (aMessage = '') then Assert(aCondition) else Assert(aCondition, aMessage); end; procedure TtfwScriptDebugger_Form.Print(const aStr: Tl3WString); begin edOutput.GotoBottom; edOutput.InsertBuf(aStr); edOutput.InsertBuf(l3PCharLen(#13#10)); end; procedure TtfwScriptDebugger_Form.Print(const aStr: Il3CString); begin Print(l3PCharLen(aStr)); end; function TtfwScriptDebugger_Form.ResolveIncludedFilePath(const aFile: AnsiString): AnsiString; begin Result := TvcmInsiderTest.DoResolveIncludedFilePath(aFile); end; function TtfwScriptDebugger_Form.ResolveOutputFilePath(const aFile: AnsiString): AnsiString; begin Result := TvcmInsiderTest.DoResolveOutputFilePath(aFile); end; function TtfwScriptDebugger_Form.ResolveInputFilePath(const aFile: AnsiString): AnsiString; begin Result := TvcmInsiderTest.DoResolveInputFilePath(aFile); end; function TtfwScriptDebugger_Form.SystemDictionary: IStream; begin Result := nil; end; procedure TtfwScriptDebugger_Form.CheckWithEtalon(const aFileName: AnsiString; aHeaderBegin: AnsiChar); begin // - ничего не делаем end; procedure TtfwScriptDebugger_Form.CheckOutputWithInput(const aIn: AnsiString; const aOut: AnsiString; aHeaderBegin: AnsiChar; aEtalonNeedsComputerName: Boolean; aEtalonCanHaveDiff: Boolean; const anExtraFileName: AnsiString; aNeedsCheck: Boolean); //overload; begin Assert(false); end; procedure TtfwScriptDebugger_Form.CheckOutputWithInput(const aSt: AnsiString; aHeaderBegin: AnsiChar = #0; const anExtraFileName: AnsiString = ''; aNeedsCheck: Boolean = true); //overload; begin Assert(false); end; procedure TtfwScriptDebugger_Form.btRunClick(Sender: TObject); begin Tl3KeyboardLayoutService.Instance.TryActivateKeyboardLayout; Assert(not Tl3BatchService.Instance.IsBatchMode); {$IF not Defined(Archi) and not Defined(EverestLite)} {$IfNDef NoVCM} vcmDispatcher.FormDispatcher.CurrentMainForm.VCLWinControl.SetFocus; {$EndIf NoVCM} {$IFEND} Tl3BatchService.Instance.EnterBatchMode; try try TtfwScriptEngine.Script(edScript.Text, Self); except on E : Exception do begin try Print(l3PCharLen(E.Message)); except end;//try..except l3System.Exception2Log(E); end;//E : Exception end;//try..finally finally Tl3BatchService.Instance.LeaveBatchMode; end;//try..finally end; procedure TtfwScriptDebugger_Form.FormCreate(Sender: TObject); begin edScript.TextSource.New; edScript.NeedReplaceQuotes := false; edScript.AutoSelect := false; edOutput.TextSource.New; edOutput.AutoSelect := false; end; procedure TtfwScriptDebugger_Form.btClearClick(Sender: TObject); begin edOutput.TextSource.New; end; procedure TtfwScriptDebugger_Form.lstStackGetStrItem(Sender: TObject; Index: Integer; var ItemString: Il3CString); begin ItemString := l3CStr('<' + IntToStr(Index) + '>'); if (g_ScriptEngine <> nil) then if (g_ScriptEngine.ValueStack <> nil) then with g_ScriptEngine.ValueStack do begin if (Index < Count) then try ItemString := Items[Count - Index - 1].AsPrintable; except ItemString := l3CStr('Видимо битая ссылка на объект'); end;//try..except (* with Items[Count - Index - 1] do begin Case rType of tfw_svtVoid: ItemString := l3CStr('<void>'); tfw_svtInt: ItemString := l3CStr(IntToStr(rInteger)); tfw_svtBool: ItemString := l3CStr(BoolToStr(AsBoolean, true)); tfw_svtStr: ItemString := AsString; tfw_svtObj: try if (AsObject Is TComponent) then ItemString := l3CStr('Class: ' + TComponent(AsObject).Name + ' : ' +AsObject.ClassName) else ItemString := l3CStr('Class: ' + AsObject.ClassName); except ItemString := l3CStr('Видимо битая ссылка на объект'); end;//try..except else ItemString := l3CStr(GetEnumName(TypeInfo(TtfwStackValueType), Ord(rType))); end;//Case rType end;//with Items[Count - Index - 1]*) end;//with g_ScriptEngine.ValueStack end; procedure TtfwScriptDebugger_Form.tmStackTimer(Sender: TObject); var l_Cnt : Integer; begin l_Cnt := 0; if (g_ScriptEngine <> nil) then if (g_ScriptEngine.ValueStack <> nil) then l_Cnt := g_ScriptEngine.ValueStack.Count; lstStack.Total := l_Cnt; end; (*function TtfwScriptDebugger_Form.PrepareForm(aClass: TClass): TCustomForm; begin Assert(false); end;*) procedure TtfwScriptDebugger_Form.FormDestroy(Sender: TObject); begin l3Free(f_TextForm); l3Free(f_Starts); end; procedure TtfwScriptDebugger_Form.CheckPrintEtalon(const aLogName: AnsiString; const aOutputName: AnsiString); begin Assert(False); end; procedure TtfwScriptDebugger_Form.CheckTimeout(aNow, aTimeout: Cardinal); begin Assert(False); end; function TtfwScriptDebugger_Form.ShouldStop: Boolean; begin Assert(False); end; function TtfwScriptDebugger_Form.StartTimer: Longword; begin if (f_Starts = nil) then f_Starts := Tl3CardinalList.Make; Result := GetTickCount; f_Starts.Add(Result); end; function TtfwScriptDebugger_Form.StopTimer(const aSt, aSubName: AnsiString; aNeedTimeToLog: Boolean): Longword; begin Assert(f_Starts <> nil); Assert(f_Starts.Count > 0); Result := GetTickCount - f_Starts.Last; f_Starts.Delete(f_Starts.Hi); if aNeedTimeToLog then TimeToLog(Result, aSt, aSubName); end; function TtfwScriptDebugger_Form.KPage: AnsiString; begin Assert(False); end; procedure TtfwScriptDebugger_Form.ToLog(const aSt: AnsiString); begin (* if Assigned(f_ToLog) then f_ToLog(aSt) else*) l3System.Msg2Log(ClassName + '.Debugger: ' + aSt); end; function TtfwScriptDebugger_Form.CompileOnly: Boolean; begin Result := false; end; function TtfwScriptDebugger_Form.GetCVSPath: AnsiString; begin Assert(False); Result := ''; end; function TtfwScriptDebugger_Form.GetIsFakeCVS: Boolean; begin Assert(False); Result := False; end; function TtfwScriptDebugger_Form.GetIsWritingToK: Boolean; begin Assert(False); Result := False; end; procedure TtfwScriptDebugger_Form.DontRaiseIfEtalonCreated; begin Assert(False); end; procedure TtfwScriptDebugger_Form.LoadScriptFromFile(aFileName: AnsiString); var l_Reader : Tk2CustomFileReader; l_DosFiler : TevDosFiler; begin l_DosFiler := TevDosFiler.Create; try l_Reader := TevTextParser.Create(nil); try l_DosFiler.FileName := aFileName; (l_Reader as TevTextParser).PlainText := True; l_Reader.Filer := l_DosFiler; edScript.TextSource.Load(l_Reader); finally l3Free(l_Reader); end; finally l3Free(l_DosFiler); end; end; procedure TtfwScriptDebugger_Form.RunScript; begin btRun.Click; end; procedure TtfwScriptDebugger_Form.TimeToLog(aTime: Cardinal; const aSt, aSubName: AnsiString); var l_S : AnsiString; begin (* if Assigned(f_TimeToLog) then begin l_S := ClassName + '.' + FTestName; if (aSt <> '') then l_S := l_S + '.' + aSt; f_TimeToLog(aTime, l_S, aSubName); end//Assigned(f_TimeToLog) else*) begin l_S := 'time ' + IntToStr(aTime) + ' ms'; if (aSubName <> '') then l_S := aSubName + ' ' + l_S; if (aSt <> '') then l_S := aSt + ' done: ' + l_S; ToLog(l_S); end;//Assigned(f_TimeToLog) end; function TtfwScriptDebugger_Form.GetTestSetFolderName: AnsiString; begin Result := 'TestSet'; end; function TtfwScriptDebugger_Form.GetEtalonSuffix: AnsiString; begin Result := '.etalon'; end; procedure TtfwScriptDebugger_Form.ScriptDone(const aCtx: TtfwContext); begin end; procedure TtfwScriptDebugger_Form.ScriptWillRun(const aCtx: TtfwContext); begin end; procedure TtfwScriptDebugger_Form.CheckPictureOnly; begin end; end.
unit Unit1; {$mode objfpc}{$H+} {* * PascalCoin Layer-2 Example * Copyright (c) 2020 by Preben Bjorn Biermann Madsen * Distributed under the MIT software license * * This is a very simple example to show how to * send or receive data in the Pascal network * using JSON-RPC calls to the build in server. * * All operations are saved in the blockchain * * See PIP-0033: DATA operation RPC implementation * https://www.pascalcoin.org/development/pips/pip-0033 * * See also JSON RPC API Specification & Guideline * https://github.com/PascalCoinDev/PascalCoin/wiki/JSON-RPC-API *} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, fphttpclient; // <--- Add this native http client to uses type { TForm1 } TForm1 = class(TForm) Button1: TButton; Button2: TButton; Memo1: TMemo; procedure Button1Click(Sender: TObject); procedure Button2Click(Sender: TObject); private public end; var Form1: TForm1; implementation {$R *.lfm} { TForm1 } // method: senddata // send call to Pascal JSON-RPC Server using HTTP Post // params: sender: account #, target: account #, payload: hex string // See PIP-0033 for all possible params and more info // run Pascal Wallet or Daemon with RPC server enabled // set port to 4003(mainnet) or 4103 or 4203 (testnet) // set sender to an account you own procedure TForm1.Button1Click(Sender: TObject); var client: TFPHTTPClient; respons: String; begin client := TFPHTTPClient.Create(nil); try try // remember to set port, sender and target respons := client.SimpleFormPost('http://localhost:4003/', '{"jsonrpc":"2.0","method":"senddata","params":{"sender":"000000", "target":"000000", "payload":"0123456789ABCDEF"},"id":123}'); memo1.Text := respons; except on E: exception do ShowMessage(E.Message); end; finally client.Free; end; end; // method: finddataoperations // send call to Pascal JSON-RPC Server using HTTP Post // params: target: account # // See PIP-0030 for all possible params and more info // the call returns by default the 100 latest operations // run Pascal Wallet or Daemon with RPC server enabled // set port to 4003(mainnet) or 4103 or 4203 (testnet) // set target to an account you own procedure TForm1.Button2Click(Sender: TObject); var client: TFPHTTPClient; respons: String; begin client := TFPHTTPClient.Create(nil); try try // remember to set port and target respons := client.SimpleFormPost('http://localhost:4003/', '{"jsonrpc":"2.0","method":"finddataoperations","params":{"target":"000000"},"id":123}'); memo1.Text := respons; // do something - her we just write to the memo except on E: exception do ShowMessage(E.Message); end; finally client.Free; end; end; end.
unit atSharedBuffer; {* Класс для создания буфера памяти, общего для нескольких процессов на одной машине. } // Модуль: "w:\quality\test\garant6x\AdapterTest\CoreObjects\atSharedBuffer.pas" // Стереотип: "SimpleClass" // Элемент модели: "TatSharedBuffer" MUID: (491D776401B4) interface uses l3IntfUses , l3_Base , Windows ; type TatSharedBuffer = class(Tl3_Base) {* Класс для создания буфера памяти, общего для нескольких процессов на одной машине. } private f_FileMapping: THandle; f_MappingAddress: Pointer; f_Size: LongWord; {* Размер буфера. } protected function pm_GetValue: Pointer; virtual; procedure Cleanup; override; {* Функция очистки полей объекта. } public constructor Create(const aName: AnsiString; aSize: LongWord); reintroduce; public property Value: Pointer read pm_GetValue; {* Указатель на буфер. } property Size: LongWord read f_Size; {* Размер буфера. } end;//TatSharedBuffer implementation uses l3ImplUses , SysUtils //#UC START# *491D776401B4impl_uses* //#UC END# *491D776401B4impl_uses* ; function TatSharedBuffer.pm_GetValue: Pointer; //#UC START# *491D881000F6_491D776401B4get_var* //#UC END# *491D881000F6_491D776401B4get_var* begin //#UC START# *491D881000F6_491D776401B4get_impl* Result := f_MappingAddress; //#UC END# *491D881000F6_491D776401B4get_impl* end;//TatSharedBuffer.pm_GetValue constructor TatSharedBuffer.Create(const aName: AnsiString; aSize: LongWord); //#UC START# *491D78AD03E4_491D776401B4_var* var isNewMapping : boolean; //#UC END# *491D78AD03E4_491D776401B4_var* begin //#UC START# *491D78AD03E4_491D776401B4_impl* inherited Create; f_Size := aSize; // создаем отображение в файл подкачки f_FileMapping := CreateFileMapping( $FFFFFFFF, nil, PAGE_READWRITE OR SEC_COMMIT, 0, f_Size, PAnsiChar('{5D573166-D8D3-4419-97CE-83DDF40C9831}_' + aName) ); isNewMapping := (GetLastError() = 0); // если бы уже существовало, то GetLastError возвратил бы ERROR_ALREADY_EXISTS if (f_FileMapping = 0) then Raise Exception.Create('Вызов CreateFileMapping не удался!'); // теперь мапим в адресное пространство f_MappingAddress := MapViewOfFile(f_FileMapping, FILE_MAP_ALL_ACCESS, 0, 0, f_Size); if (f_MappingAddress = nil) then Raise Exception.Create('Вызов MapViewOfFile не удался!'); if isNewMapping then FillChar(f_MappingAddress^, f_Size, 0); //#UC END# *491D78AD03E4_491D776401B4_impl* end;//TatSharedBuffer.Create procedure TatSharedBuffer.Cleanup; {* Функция очистки полей объекта. } //#UC START# *479731C50290_491D776401B4_var* //#UC END# *479731C50290_491D776401B4_var* begin //#UC START# *479731C50290_491D776401B4_impl* UnmapViewOfFile(f_MappingAddress); CloseHandle(f_FileMapping); inherited; //#UC END# *479731C50290_491D776401B4_impl* end;//TatSharedBuffer.Cleanup end.
unit TrackedItemFrame; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Buttons, ExtCtrls, Grids, AdvGrid, FFSAdvStringGrid, DBISAMTb, FFSUtils, ImgList, NotesDialog, Menus, LMDControl, LMDBaseControl, LMDBaseGraphicControl, LMDBaseLabel, LMDCustomSimpleLabel, LMDSimpleLabel, ActnList, LMDCustomButton, LMDButton, htmlabel, ShellAPI, sFrameAdapter, sButton, sCheckBox, sLabel, sPanel, AdvUtil, System.Actions, System.ImageList, AdvObj, BaseGrid; type TTrackedItemFram = class(TFrame) Panel2: TsPanel; cbxItemHist: TsCheckBox; titmgrid: TFFSAdvStringGrid; ImageList1: TImageList; dlgTitmNotes: TNotesDialog; PopupMenu1: TPopupMenu; AddItem1: TMenuItem; EditItem1: TMenuItem; DeleteItem1: TMenuItem; ItemNotes1: TMenuItem; Documents1: TMenuItem; Label1: TsLabel; alTracked: TActionList; actAddItem: TAction; actEditItem: TAction; actDeleteItem: TAction; actItemNotes: TAction; actItemDocs: TAction; btnDelete: TsButton; btnNotes: TsButton; btnEdit: TsButton; btnAdd: TsButton; btnDocs: TsButton; sfrmdptr1: TsFrameAdapter; procedure cbxItemHistClick(Sender: TObject); procedure titmGridDblClick(Sender: TObject); procedure titmgridGetCellColor(Sender: TObject; ARow, ACol: Integer; AState: TGridDrawState; ABrush: TBrush; AFont: TFont); procedure titmgridRowChanging(Sender: TObject; OldRow, NewRow: Integer; var Allow: Boolean); procedure titmgridRecordEdit(Sender: TObject); procedure actAddItemExecute(Sender: TObject); procedure actEditItemExecute(Sender: TObject); procedure actDeleteItemExecute(Sender: TObject); procedure actItemNotesExecute(Sender: TObject); procedure actItemDocsExecute(Sender: TObject); procedure titmgridRecordDelete(Sender: TObject); procedure titmgridRecordInsert(Sender: TObject); procedure titmgridGetAlignment(Sender: TObject; ARow, ACol: Integer; var AAlignment: TAlignment); procedure titmgridMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); procedure titmgridMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); private FItemCount: integer; FEnabled: boolean; procedure RefreshButtons(ARow: integer); procedure SetEnabled(Value: Boolean); override; private FCifFlag, FLoanNumber : string; FCollCode : string; FCollNum : integer; FTrakCode : string; FSubNum : integer; procedure GoToTitm; { Private declarations } public { Public declarations } FrameBusy : boolean; procedure SetFormOptions; procedure SetLCIF(ACifFlag, ALoanNumber:string); procedure SetCCC(ACollCode:string;ACollNum:integer); procedure RefreshGrid(DoFocus,KeepPos:boolean); property ItemCount:integer read FItemCount; property Enabled : boolean read FEnabled write SetEnabled; end; implementation uses datamod, TrackedItem, titmdoc, TicklerTypes, TicklerGlobals; {$R *.DFM} const ColNoteFlag = 1; ColDocFlag = 2; ColHist = 3; ColCat = 4; ColDesc = 6; ColRef = 7; ColExpireDate = 8; ColExpFlag = 9; ColNoticeDate = 10; ColDocId = 13; ColAgentId = 22; procedure TTrackedItemFram.cbxItemHistClick(Sender: TObject); begin RefreshGrid(true,true); end; procedure TTrackedItemFram.RefreshGrid(DoFocus,KeepPos:boolean); var LeadTime : integer; ExpDate : TDateTime; LastRow : integer; trakList : TStringList; begin FrameBusy := true; trakList := TStringList.create; try if not CurrentLend.DeficiencyEnabled then titmGrid.HideColumn(16); daapi.TitmGetList(CurrentLend.Number, FCifFlag, FLoanNumber, FCollNum, cbxItemHist.checked, trakList); titmGrid.BeginUpdate; titmGrid.LoadFromCSVStringList(trakList); LastRow := titmGrid.Row; FItemCount := trakList.count; titmGrid.EndUpdate; actItemDocs.Visible := CurrentLend.DocImagingEnabled; if (DoFocus) and (titmGrid.CanFocus) then titmGrid.SetFocus; if ItemCount > 0 then titmGrid.AddImageIdx(0,1,0,haCenter,vaCenter); if KeepPos then begin if LastRow < titmGrid.RowCount then titmGrid.Row := LastRow else titmGrid.Row := titmGrid.RowCount - 1; end; finally FrameBusy := false; TrakList.free; titmgrid.FitLastColumn; RefreshButtons(titmGrid.Row); end; end; function ExtractCat(s:string):string; var x,p : integer; begin p := 0; for x := length(s) downto 1 do if s[x] = '-' then begin p := x; break; end; result := copy(s,1,p-1); end; function ExtractSub(s:string):integer; var x,p : integer; begin p := 0; for x := length(s) downto 1 do if s[x] = '-' then begin p := x; break; end; result := strtointdef(copy(s,p+1,length(s)-p),0); end; procedure TTrackedItemFram.titmGridDblClick(Sender: TObject); begin actEditItem.Execute; end; procedure TTrackedItemFram.SetLCIF(ACifFlag, ALoanNumber: string); begin titmgrid.UnhideColumnsAll; if not currentlend.DocImagingEnabled then titmgrid.HideColumn(2); if not currentlend.DocIDEnabled then titmgrid.HideColumn(13); if not currentlend.UTLEnabled then begin titmgrid.HideColumn(14); titmgrid.HideColumn(15); end; if not currentlend.EscrowEnabled then begin titmgrid.HideColumn(17); titmgrid.HideColumn(18); titmgrid.HideColumn(19); titmgrid.HideColumn(20); titmgrid.HideColumn(21); end; if not currentLend.AgentEnabled then titmgrid.HideColumn(ColAgentId); // column 22 FCifFlag := ACifFlag; FLoanNumber := ALoanNumber; RefreshGrid(false,true); cbxItemHist.Enabled := instr(ACifFlag, 'YN'); end; procedure TTrackedItemFram.GoToTitm; begin FTrakCode := padnumeric(trim(ExtractCat(titmGrid.cells[ColCat, titmGrid.Row])),8); FSubNum := ExtractSub(titmGrid.cells[ColCat, titmGrid.Row]); end; procedure TTrackedItemFram.titmgridGetCellColor(Sender: TObject; ARow, ACol: Integer; AState: TGridDrawState; ABrush: TBrush; AFont: TFont); var histflag : string[1]; begin if ARow < titmGrid.FixedRows then exit; histflag := titmGrid.Cells[colHist, ARow]; if pos('h', histflag) > 0 then AFont.Color := clBlue else begin case ACol of colNoteFlag : if titmGrid.Cells[colNoteFlag, ARow] = 'N' then ABrush.Color := clYellow else ABrush.Color := clWindow; colDocFlag : if titmGrid.Cells[colDocFlag, ARow] = 'D' then ABrush.Color := clYellow else ABrush.Color := clWindow; colHist : if histflag = 'H' then ABrush.Color := clYellow else ABrush.Color := clWindow; colExpFlag : if trim(titmGrid.Cells[colExpFlag, ARow]) > '' then ABrush.Color := clYellow else ABrush.Color := clWindow; colNoticeDate : if trim(titmGrid.Cells[colNoticeDate, ARow]) > '' then ABrush.Color := clYellow else ABrush.Color := clWindow; end; // if (ABrush.Color = clYellow) and (ARow = titmGrid.Row) then AFont.Color := clBlack; end; if gdSelected in AState then begin ABrush.Color := titmGrid.SelectionColor; AFont.Color := titmGrid.SelectionTextColor; end; end; procedure TTrackedItemFram.titmgridRowChanging(Sender: TObject; OldRow, NewRow: Integer; var Allow: Boolean); begin RefreshButtons(NewRow); end; procedure TTrackedItemFram.RefreshButtons(ARow:integer); var hist: boolean; x : integer; begin for x := 1 to titmGrid.Rowcount - 1 do titmGrid.RemoveImageIdx(0,x); titmGrid.AddImageIdx(0,ARow,0,haCenter,vaCenter); // buttons hist := false; if ItemCount > 0 then hist := titmGrid.cells[colHist, ARow] = 'h'; if FEnabled then begin actAddItem.Enabled := (IsACif(FCifFlag) and UsrRights(tpCIFTitmAdd)) or (IsALoan(FCifFlag) and UsrRights(tpLoanTitmAdd)); actEditItem.Enabled := ((IsACif(FCifFlag) and UsrRights(tpCIFTitmModify)) or (IsALoan(FCifFlag) and UsrRights(tpLoanTitmModify))) and (not hist) and (ItemCount > 0); actDeleteItem.Enabled := ((IsACif(FCifFlag) and UsrRights(tpCifTitmDelete)) or (IsALoan(FCifFlag) and UsrRights(tpLoanTitmDelete))) and (not hist) and (ItemCount > 0); actItemNotes.Enabled := ((IsACif(FCifFlag) and (UsrRights(tpCifTitmNoteAppend) or UsrRights(tpCifTitmNoteFull) or UsrRights(tpCifTitmDocView) )) or (IsALoan(FCifFlag) and (UsrRights(tpLoanTitmNoteAppend) or UsrRights(tpLoanTitmNoteFull) or UsrRights(tpLoanTitmDocView) ))) and (not hist) and (ItemCount > 0); actItemDocs.Enabled := ((IsACif(FCifFlag) and UsrRights(tpCifTitmDocView)) or (IsALoan(FCifFlag) and UsrRights(tpLoanTitmDocView))) and (not hist) and (ItemCount > 0); end else begin actAddItem.Enabled := FALSE; actEditItem.Enabled := FALSE; actDeleteItem.Enabled := FALSE; actItemNotes.Enabled := FALSE; actItemDocs.Enabled := FALSE; end; // btnAdd.Enabled := actAddItem.Enabled; // btnEdit.Enabled := actEditItem.Enabled; // btnDelete.Enabled := actDeleteItem.Enabled; // btnNotes.Enabled := actItemNotes.Enabled; // btnDocs.Enabled := actItemDocs.Enabled; end; procedure TTrackedItemFram.titmgridRecordEdit(Sender: TObject); begin actEditItem.Execute; end; procedure TTrackedItemFram.actAddItemExecute(Sender: TObject); begin if (FCifFlag = FlagCif) and (not UsrRights(tpCifTitmAdd)) then MsgInsufficient; if (FCifFlag = FlagLoan) and (not UsrRights(tpLoanTitmAdd)) then MsgInsufficient; AddTrackedItem(FCifFlag, FLoanNumber, FCollNum); RefreshGrid(true,false); end; procedure TTrackedItemFram.actEditItemExecute(Sender: TObject); begin if FrameBusy then exit; if (FCifFlag = FlagCif) and (not UsrRights(tpCifTitmModify)) then MsgInsufficient; if (FCifFlag = FlagLoan) and (not UsrRights(tpLoanTitmModify)) then MsgInsufficient; GoToTitm; if empty(FTrakCode) then exit; EditTrackedItem(FCifFlag, FLoanNumber, FCollNum, FTrakCode, FSubNum); RefreshGrid(true,true); end; procedure TTrackedItemFram.actDeleteItemExecute(Sender: TObject); var count : integer; x,y : integer; req : boolean; P : PChar; grdCollCode : string; list1,list2,list3 : TStringList; i: integer; addallxpldg: boolean; tmploans: String; begin if FrameBusy then exit; if (FCifFlag = FlagCif) and (not UsrRights(tpCifTitmDelete)) then MsgInsufficient; if (FCifFlag = FlagLoan) and (not UsrRights(tpLoanTitmDelete)) then MsgInsufficient; GoToTitm; if empty(FTrakCode) then exit; // count the number of items in this category count := 0; FTrakCode := PadNumeric(FTrakCode,8); for x := 1 to titmGrid.Rowcount - 1 do begin y := LastDelimiter('-',titmGrid.cells[colCat, x]) - 1 ; if y = -1 then y := 8; grdCollCode := copy(titmGrid.cells[colCat, x], 1, y); grdCollCode := PadNumeric(grdCollcode,8); if grdCollcode = FTrakcode then inc(count); end; // check to see if it is a required item if it is the only one req := false; if (count = 1) and (trim(FCollCode) > '') then begin // it is the only one and there is a coll code req := daapi.CitmRequiredItem(CurrentLend.Number, FCollCode, FTrakCode); end; // if it is required then it cannot be deleted if req then begin if FCifFlag = 'N' then TrMsgInformation('You cannot delete this item because it is a required item for collateral code: ' + FCollCode) else TrMsgInformation('You cannot delete this item because it is a required item for customer code: ' + FCollCode); end else begin if TrMsgConfirmation('Are you sure you wish to delete this tracked item?') = IDYES then begin //Get all cross-pledged loans (all levels) by calling recursive function getAllXPldgs list1 := TStringList.Create; list2 := TStringList.Create; getAllXPldgs(CurrentLend.Number,FLoanNumber,inttostr(FCollNum),list1,list2); //Check if current tracked item already exists in any of the cross-pledged loans. //If it exists, then check if same titm exists in any of the loans. //If it does, then show a message asking if these loans should be modified tmploans := ''; for i := 0 to list1.Count-1 do begin list3 := TStringList.Create; list3.CommaText := list1[i]; if daapi.TitmItemExists(CurrentLend.Number, FCifFlag, list3[0], strtoint(iif(length(trim(list3[1]))=0,'0',list3[1])), FTrakCode, FSubNum) then begin if trim(list3[0]) = trim(FLoanNumber) then else tmploans := tmploans + iif(length(tmploans)>0,',','') + trim(list3[0]); end; end; //Ask for permission to add titm recs in all cross-pledged loans addallxpldg := false; if length(tmploans) > 0 then begin if MessageDlg('This tracked item also exists in cross-pledged loans ' + tmploans + '. Delete this tracked item in all these loans?', mtConfirmation, [mbYes, mbNo], 0) = mrYes then addallxpldg := true else addallxpldg := false; end; //Now delete titms - first delete titm of currently open loan record. daapi.TitmDelete(CurrentLend.Number, FCifFlag, FLoanNumber, FCollNum, FTrakCode, FSubNum); //Next delete titms in all cross-pledged loans ONLY if user has selected Yes //to delete titms in all cross-pledged loans above. if addallxpldg = true then begin for i := 0 to list1.Count-1 do begin list3 := TStringList.Create; list3.CommaText := list1[i]; if ( (list3[0] = FLoanNumber) and (strtoint(iif(length(trim(list3[1]))=0,'0',list3[1])) = FCollNum) ) then else daapi.TitmDelete(CurrentLend.Number, FCifFlag, list3[0], strtoint(iif(length(trim(list3[1]))=0,'0',list3[1])), FTrakCode, FSubNum); end; end; end; end; RefreshGrid(true,true); end; procedure TTrackedItemFram.actItemNotesExecute(Sender: TObject); var template : string; begin if FrameBusy then exit; if (FCifFlag = FlagCif) and (not (UsrRights(tpCifTitmNoteAppend) or UsrRights(tpCifTitmNoteFull))) then MsgInsufficient; if (FCifFlag = FlagLoan) and (not (UsrRights(tpLoanTitmNoteAppend) or UsrRights(tpLoanTitmNoteFull))) then MsgInsufficient; GoToTitm; if empty(FTrakCode) then exit; dlgTitmNotes.ShowCaptions := false; dlgTitmNotes.Clear; dlgTitmNotes.Notes := daapi.titmGetNotes(CurrentLend.Number, FCifFlag, FLoanNumber, FCollNum, FTrakCode, FSubNum); dlgTitmNotes.DlgCaption := 'Notes for Tracked Item: ' + trim(FTrakCode) + '-' + inttostr(FSubNum); // Template Check. template := daapi.TrakGetTemplate(CurrentLend.Number, FTrakCode); if Template = EmptyStr then dlgTitmNotes.NewNote := CurrentUser.PUserName + ' ' + trim(DateTimeStamp) + ' ' else if dlgTitmNotes.Notes = EmptyStr then dlgTitmNotes.NewNote := Template; // dlgTitmNotes.NoteOption := nopReadOnly; if IsALoan(FCifFlag) then begin if UsrRights(tpLoanTitmNoteAppend) then dlgTitmNotes.NoteOption := nopReadWrite; if UsrRights(tpLoanTitmNoteFull) then dlgTitmNotes.NoteOption := nopWriteAll; end else begin if UsrRights(tpCifTitmNoteAppend) then dlgTitmNotes.NoteOption := nopReadWrite; if UsrRights(tpCifTitmNoteFull) then dlgTitmNotes.NoteOption := nopWriteAll; end; dlgTitmNotes.WantReturns := true; if (Template > EmptyStr) and (dlgTitmNotes.NoteOption > nopReadOnly) then begin dlgTitmNotes.NoteOption := nopTemplate; dlgTitmNotes.WantReturns := false; end; if dlgTitmNotes.Execute then daapi.TitmUpdateNote(CurrentLend.Number, FCifFlag, FLoanNumber, FCollNum, FTrakCode, FSubNum, dlgTitmNotes.Notes); RefreshGrid(true,true); template := EmptyStr; end; procedure TTrackedItemFram.actItemDocsExecute(Sender: TObject); var Titmdoc : TfrmTitmDoc; crow : integer; temp : string; begin if not FrameBusy then begin if empty(TicklerSetup.ImageUrl) then begin ShowMessage('There is no external Document Image Url.'); exit; end; if empty(titmGrid.Cells[ColDocId,titmGrid.Row]) then begin ShowMessage('There is no Document to view.'); exit; end; // temp := format(Trim(TicklerSetup.ImageUrl),[titmGrid.Cells[ColDocId,titmGrid.Row]]); temp := Trim(TicklerSetup.ImageUrl) + titmGrid.Cells[ColDocId,titmGrid.Row]; shellexecute(0,'open',pchar(temp),nil,nil,SW_SHOWNORMAL) end; // ah 07.26.02 change to external // if ItemCount = 0 then exit; // crow := titmGrid.Row; // TitmDoc := TfrmTitmDoc.Create(self); // TitmDoc.CifFlag := FCifFlag; // TitmDoc.LoanNum := FLoanNumber; // TitmDoc.category := ExtractCat(titmGrid.cells[colCat,crow]); // TitmDoc.subNum := ExtractSub(titmGrid.cells[colCat,crow]); // TitmDoc.catdesc := titmGrid.cells[colCat+1,crow]; // TitmDoc.lbTitm.Caption := titmGrid.cells[colCat,crow] + ': ' + titmGrid.Cells[colCat+1,crow]; // TitmDoc.lbDescRef.Caption := titmGrid.cells[colDesc,crow] + '/' + titmGrid.cells[colRef,crow]; // TitmDoc.lbExpire.Caption := titmGrid.cells[colExpireDate, crow]; // TitmDoc.ShowModal; // TitmDoc.Free; // RefreshGrid(true,true); end; procedure TTrackedItemFram.titmgridRecordDelete(Sender: TObject); begin actDeleteItem.Execute; end; procedure TTrackedItemFram.titmgridRecordInsert(Sender: TObject); begin actAddItem.Execute; end; procedure TTrackedItemFram.SetCCC(ACollCode: string; ACollNum: integer); begin FCollCode := ACollCode; FCollNum := ACollNum; end; procedure TTrackedItemFram.SetFormOptions; begin { btnAdd.Visible := UsrRights(tpLoanTitmAdd); btnEdit.Visible := UsrRights(tpLoanTitmModify); btnDelete.Visible := UsrRights(tpLoanTitmDelete); btnNotes.Visible := UsrRights(tpLoanTitmNoteAppend) or UsrRights(tpLoanTitmNoteFull); btnDocs.Visible := UsrRights(tpLoanTitmDocView) or UsrRights(tpLoanTitmDocAdd) or UsrRights(tpLoanTitmDocModify) or UsrRights(tpLoanTitmDocDelete); } end; procedure TTrackedItemFram.SetEnabled(Value: Boolean); begin FEnabled := Value; RefreshButtons(titmGrid.Row); end; procedure TTrackedItemFram.titmgridGetAlignment(Sender: TObject; ARow, ACol: Integer; var AAlignment: TAlignment); begin if ((ACol = 18) or (ACol = 20)) and (ARow > 0) then begin AAlignment := taRightJustify; end; end; procedure TTrackedItemFram.titmgridMouseWheelDown(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); begin titmgrid.SetFocus; end; procedure TTrackedItemFram.titmgridMouseWheelUp(Sender: TObject; Shift: TShiftState; MousePos: TPoint; var Handled: Boolean); begin titmgrid.SetFocus; end; end.
{ DBAExplorer - Oracle Admin Management Tool Copyright (C) 2008 Alpaslan KILICKAYA This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. } unit frmIndexProperties; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, frmBaseForm, OraBarConn, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxDataStorage, cxEdit, DB, cxDBData, cxMemo, cxRichEdit, cxSplitter, dxStatusBar, cxGridLevel, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid, cxLabel, cxContainer, cxTextEdit, dxBar, jpeg, cxPC, StdCtrls, ExtCtrls, GenelDM, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, cxDropDownEdit, cxImageComboBox, cxGroupBox, cxRadioGroup, cxMaskEdit, cxCheckBox, MemDS, DBAccess, Ora, VirtualTable, OraIndex; type TIndexPropertiesFrm = class(TBaseform) Panel1: TPanel; imgToolBar: TImage; lblDescription: TLabel; pcIndexProperties: TcxPageControl; tsPartitions: TcxTabSheet; tsProperties: TcxTabSheet; dxBarDockControl4: TdxBarDockControl; tsViewScripts: TcxTabSheet; dxBarManager1: TdxBarManager; bbtnCreateIndex: TdxBarButton; bbtnDropIndex: TdxBarButton; bbtnAlterIndex: TdxBarButton; bbtnAnalyzeIndex: TdxBarButton; bbtnRebuildIndex: TdxBarButton; bbtnCoalesceIndex: TdxBarButton; bbtnRefreshIndex: TdxBarButton; pcTableIndex: TcxPageControl; cxTabSheet1: TcxTabSheet; Label3: TLabel; Label43: TLabel; Label37: TLabel; Label44: TLabel; lblPartition: TLabel; cgroupParalel: TcxGroupBox; Label22: TLabel; Label23: TLabel; cbParalel: TcxCheckBox; edtParalelDegree: TcxMaskEdit; edtParalelInstances: TcxMaskEdit; edtIndexName: TcxTextEdit; edtIndexType: TcxTextEdit; rgroupIndexType: TcxRadioGroup; rgroupKeyCompression: TcxRadioGroup; edtKeyCompressionColumns: TcxMaskEdit; cbLogging: TcxImageComboBox; cxTabSheet2: TcxTabSheet; Label28: TLabel; Label33: TLabel; Label34: TLabel; Label35: TLabel; Label36: TLabel; cxGroupBox7: TcxGroupBox; Label24: TLabel; Label25: TLabel; Label26: TLabel; Label27: TLabel; Label29: TLabel; Label30: TLabel; Label31: TLabel; Label32: TLabel; edtInitialExtend: TcxMaskEdit; edtNextExtend: TcxMaskEdit; edtMinExtents: TcxMaskEdit; edtMaxExtents: TcxMaskEdit; edtPctIncrease: TcxMaskEdit; edtFreeList: TcxMaskEdit; edtFreeGroup: TcxMaskEdit; cbBufferPool: TcxImageComboBox; edtPercentFree: TcxMaskEdit; edtPercentUsed: TcxMaskEdit; edtInitialTrans: TcxMaskEdit; edtMaxTrans: TcxMaskEdit; lcTablespace: TcxLookupComboBox; cxSplitter1: TcxSplitter; GridIndex: TcxGrid; GridIndexDBTableView: TcxGridDBTableView; GridIndexDBTableViewColumn1: TcxGridDBColumn; GridIndexDBTableViewColumn2: TcxGridDBColumn; GridIndexDBTableViewColumn3: TcxGridDBColumn; GridIndexDBTableViewColumn4: TcxGridDBColumn; GridIndexDBTableViewColumn5: TcxGridDBColumn; GridIndexDBTableViewColumn6: TcxGridDBColumn; cxGridLevel1: TcxGridLevel; dsIndexes: TDataSource; vIndexes: TVirtualTable; vIndexColumns: TVirtualTable; dsIndexColumns: TDataSource; redtDDL: TcxRichEdit; vtIndexPartitions: TVirtualTable; dsIndexPartitions: TDataSource; GridPartitiones: TcxGrid; GridPartitionesDBTableView1: TcxGridDBTableView; GridPartitionesDBTableView1Column1: TcxGridDBColumn; GridPartitionesDBTableView1Column2: TcxGridDBColumn; GridPartitionesDBTableView1Column3: TcxGridDBColumn; GridPartitionesDBTableView1Column4: TcxGridDBColumn; GridPartitionesDBTableView1Column5: TcxGridDBColumn; GridPartitionesDBTableView1Column6: TcxGridDBColumn; GridPartitionesDBTableView1Column7: TcxGridDBColumn; GridPartitionesDBTableView1Column8: TcxGridDBColumn; GridPartitionesDBTableView1Column9: TcxGridDBColumn; GridPartitionesDBTableView1Column10: TcxGridDBColumn; GridPartitionesLevel1: TcxGridLevel; procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure bbtnCreateIndexClick(Sender: TObject); procedure bbtnAlterIndexClick(Sender: TObject); procedure bbtnDropIndexClick(Sender: TObject); procedure bbtnAnalyzeIndexClick(Sender: TObject); procedure bbtnRebuildIndexClick(Sender: TObject); procedure bbtnCoalesceIndexClick(Sender: TObject); procedure bbtnRefreshIndexClick(Sender: TObject); private { Private declarations } FOraSession: TOraSession; FIndexName, FOwnerName : string; TableIndex : TTableIndex; procedure GetIndex; procedure GetIndexDetail; public { Public declarations } procedure Init(ObjName, OwnerName: string); override; end; var IndexPropertiesFrm: TIndexPropertiesFrm; implementation {$R *.dfm} uses frmSchemaBrowser, Util, OraStorage, frmTableIndexes, frmTableEvents, frmSchemaPublicEvent, VisualOptions; procedure TIndexPropertiesFrm.Init(ObjName, OwnerName: string); begin inherited Show; top := 0; left := 0; DMGenel.ChangeLanguage(self); ChangeVisualGUI(self); FIndexName := ObjName; FOwnerName := OwnerName; FOraSession := TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).OraSession; GetIndex; end; procedure TIndexPropertiesFrm.FormClose(Sender: TObject; var Action: TCloseAction); begin if TableIndex <> nil then FreeAndNil(TableIndex); end; {*******************************************************************************} { I N D E X } {*******************************************************************************} procedure TIndexPropertiesFrm.GetIndex; begin if TableIndex <> nil then FreeAndNil(TableIndex); TableIndex := TTableIndex.Create; TableIndex.IndexName := FIndexName; TableIndex.IndexSchema := FOwnerName; TableIndex.OraSession := FOraSession; TableIndex.SetDDL; lblDescription.Caption := TableIndex.IndexStatus; vIndexes.close; vIndexes.Assign(TableIndex.DSIndex); vIndexes.open; vIndexColumns.close; vIndexColumns.Assign(TableIndex.DSIndexColumns); vIndexColumns.open; vtIndexPartitions.close; vtIndexPartitions.Assign(TableIndex.DSIndexPartitions); vtIndexPartitions.open; GetIndexDetail; end; procedure TIndexPropertiesFrm.GetIndexDetail; begin redtDDL.Text := ''; if FIndexName = '' then exit; if TableIndex = nil then exit; redtDDL.Text := TableIndex.GetDDL; CodeColors(self, 'Default', redtDDL, false); edtIndexName.Text := TableIndex.IndexName; edtIndexType.Text := 'NORMAL'; if TableIndex.Bitmap then edtIndexType.Text := 'BITMAP'; if TableIndex.Functions then edtIndexType.Text := 'FUNCTION-BASED NORMAL'; cbLogging.ItemIndex := Integer(TableIndex.LoggingType); if TableIndex.IndexType = Uniqe then rgroupIndexType.ItemIndex := 0 else rgroupIndexType.ItemIndex := 1; if TableIndex.Compress then rgroupKeyCompression.ItemIndex := 0 else rgroupKeyCompression.ItemIndex := 1; edtKeyCompressionColumns.Text := IntToStr(TableIndex.CompressColumns); cbParalel.Checked := TableIndex.Paralel; edtParalelDegree.Text := IntToStr(TableIndex.ParalelDegree); edtParalelInstances.Text := IntToStr(TableIndex.ParalelInstances); lblPartition.Visible := TableIndex.PartitionClause <> pcNonPartition ; if TableIndex.PartitionClause <> pcNonPartition then lblPartition.Caption := 'This table has '+ IntToStr(TableIndex.IndexPartitionLists.Count) +' '+DBIndexPartitionType[TableIndex.IndexPartitionType] +' partitions'; with TableIndex.PhsicalAttributes do begin edtPercentFree.Text := PercentFree; edtPercentUsed.Text := PercentUsed; edtInitialTrans.Text := InitialTrans; edtMaxTrans.Text := MaxExtent; lcTablespace.Text := Tablespace; edtInitialExtend.Text := InitialExtent; edtNextExtend.Text := NextExtent; edtMinExtents.Text := MinExtent; edtMaxExtents.Text := MaxExtent; edtPctIncrease.Text := PctIncrease; cbBufferPool.ItemIndex := Integer(BufferPool); edtFreeList.Text := FreeLists; edtFreeGroup.Text := FreeGroups; end; end; procedure TIndexPropertiesFrm.bbtnCreateIndexClick(Sender: TObject); var FTableIndex : TTableIndex; begin inherited; FTableIndex := TTableIndex.Create; FTableIndex.IndexName := ''; FTableIndex.IndexSchema := FOwnerName; FTableIndex.TableName := ''; FTableIndex.TableSchema := FOwnerName; FTableIndex.OraSession := FOraSession; if TableIndexesFrm.Init(FTableIndex) then TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).RefreshNode(dbIndexes); end; procedure TIndexPropertiesFrm.bbtnAlterIndexClick(Sender: TObject); begin inherited; if FIndexName = '' then exit; if TableIndex = nil then exit; if TableIndexesFrm.Init(TableIndex) then GetIndex; end; procedure TIndexPropertiesFrm.bbtnDropIndexClick(Sender: TObject); begin inherited; if FIndexName = '' then exit; if TableIndex = nil then exit; if SchemaPublicEventFrm.Init(TableIndex, oeDrop) then TSchemaBrowserFrm(Application.MainForm.ActiveMDIChild).RefreshNode(dbIndexes); end; procedure TIndexPropertiesFrm.bbtnAnalyzeIndexClick(Sender: TObject); begin inherited; if FIndexName = '' then exit; if TableIndex = nil then exit; if TableEventsfrm.Init(TableIndex, oeAnalyze) then GetIndex; end; procedure TIndexPropertiesFrm.bbtnRebuildIndexClick(Sender: TObject); begin inherited; if FIndexName = '' then exit; if TableIndex = nil then exit; if SchemaPublicEventFrm.Init(TableIndex, oeRebuild) then GetIndex; end; procedure TIndexPropertiesFrm.bbtnCoalesceIndexClick(Sender: TObject); begin inherited; if FIndexName = '' then exit; if TableIndex = nil then exit; if SchemaPublicEventFrm.Init(TableIndex, oeCoalesce) then GetIndex; end; procedure TIndexPropertiesFrm.bbtnRefreshIndexClick(Sender: TObject); begin GetIndex; end; end.
unit calculator; interface uses Classes, SyncObjs, fvm.Combinations, Generics.Collections; procedure FindCombinationsIncludingAllOf(ResultList, SourceList, IncludeList: TCombinationList); procedure FindRandomCombinations(ResultList, SourceList: TCombinationList; Count: integer); function CalculateHighestSubCountOf(Combo1, Combo2: TCombination; MaxPlaces: cardinal = MaxInt): integer; implementation uses SysUtils, Generics.Defaults; type TComboCombo = record Used : boolean; Main : TCombinationRec; Subs : array[0..19] of TCombinationRec; end; TComboComboArray = array[0..0] of TComboCombo; PComboComboArray = ^TComboComboArray; type TCalculatorThread = class(TThread) public Subs : TArray<TCombination>; Combo : TCombination; Found : boolean; procedure Execute; override; end; TCalculator = class private Threads : TList<TCalculatorThread>; Src : PComboComboArray; SrcLength : cardinal; SrcIndex : cardinal; Subs : TArray<TCombination>; SubsIndex : cardinal; SubsRequired : cardinal; SubsInSrcCount : cardinal; procedure CreateSrcArray(SourceList: TCombinationList; SubNumPlaces: cardinal); procedure CreateSubArray(SubList: TCombinationList); function FindUnique(UniqueSubsRequired: integer): TCombination; public Results: TCombinationList; constructor Create; destructor Destroy; override; procedure Calculate(SourceList, SubsList: TCombinationList); end; procedure FindCombinationsIncludingAllOf(ResultList, SourceList, IncludeList: TCombinationList); var calc : TCalculator; begin calc := TCalculator.Create; try calc.Calculate(SourceList, IncludeList); ResultList.Assign(calc.Results); finally calc.Free; end; end; procedure FindRandomCombinations(ResultList, SourceList: TCombinationList; Count: integer); var src : TCombinationList; i, idx : integer; combo : TCombination; begin ResultList.Clear; src := TCombinationList.Create; try src.Assign(SourceList); for i := 0 to Count-1 do begin idx := Random(src.Count); combo := src.Items[idx]; src.Delete(idx); ResultList.Add(combo); end; finally src.Free; end; end; function CalculateHighestSubCountOf(Combo1, Combo2: TCombination; MaxPlaces: cardinal): integer; var r1, r2 : TCombinationRec; l1, l2 : TCombinationList; places : cardinal; i, j : integer; found : boolean; maxplc : cardinal; procedure CombosNow(List: TCombinationList; const Combination: TCombinationRec); var counter, counter2 : integer; rn : TCombinationRec; begin List.Clear; CalculateCombinations(places, r1.NumPlaces, List); for counter := 0 to List.Count-1 do begin rn.Blob := List.Items[counter]; for counter2 := 0 to places-1 do rn.Data[counter2] := Combination.Data[rn.Data[counter2]-1]; List.Items[counter] := rn.Blob; end; end; begin Result := 0; l1 := TCombinationList.Create; l2 := TCombinationList.Create; r1.Blob := Combo1; r2.Blob := Combo2; maxplc := r1.NumPlaces; if MaxPlaces < maxplc then maxplc := MaxPlaces; for places := maxplc downto 1 do begin CombosNow(l1, r1); CombosNow(l2, r2); found := FALSE; for i := 0 to l1.Count-1 do for j := 0 to l2.Count-1 do begin if l1.Items[i] = l2.Items[j] then begin Result := places; found := TRUE; Break; end; end; if found then Break; end; l1.Free; l2.Free; end; { TCalculatorThread } procedure TCalculatorThread.Execute; begin {} end; { TCalculator } procedure TCalculator.Calculate(SourceList, SubsList: TCombinationList); var combo: TCombination; begin Results.Clear; if not Assigned(SourceList) or not Assigned(SubsList) then Exit; CreateSrcArray(SourceList, SubsList.NumPlaces); if not Assigned(Src) then Exit; CreateSubArray(SubsList); if Length(Subs) = 0 then begin FreeMem(Src); Src := nil; Exit; end; SrcIndex := 0; SubsIndex := 0; SubsRequired := SubsInSrcCount; repeat combo := FindUnique(SubsRequired); if combo = 0 then begin dec(subsrequired); srcindex := 0; end else Results.Add(combo); until (SubsRequired = 0) or (SubsIndex >= Length(Subs)); FreeMem(Src); Src := nil; SrcLength := 0; SetLength(Subs, 0); end; constructor TCalculator.Create; begin inherited; Threads := TList<TCalculatorThread>.Create; Results := TCombinationList.Create; end; procedure TCalculator.CreateSrcArray(SourceList: TCombinationList; SubNumPlaces: cardinal); var i, j, k : integer; clist : TCombinationList; r : TCombinationRec; begin SubsInSrcCount := 0; GetMem(Src, SizeOf(TComboCombo) * SourceList.Count); SrcLength := SourceList.Count; clist := TCombinationList.Create; try CalculateCombinations(SubNumPlaces, SourceList.NumPlaces, clist); if clist.Count > 20 then begin FreeMem(Src); Src := nil; SrcLength := 0; Exit; end; SubsInSrcCount := clist.Count; for i := 0 to SourceList.Count-1 do with Src^[i] do begin Used := FALSE; Main.Blob := SourceList.Items[i]; for j := 0 to clist.Count-1 do begin r.Blob := clist.Items[j]; Subs[j].MaxValue := SourceList.MaxValue; Subs[j].NumPlaces := SubNumPlaces; for k := 0 to SubNumPlaces-1 do Subs[j].Data[k] := Main.Data[r.Data[k]-1]; end; end; finally clist.Free; end; end; procedure TCalculator.CreateSubArray(SubList: TCombinationList); var i: integer; begin Subs := TArray<TCombination>.Create(); SetLength(Subs, SubList.Count); for i := 0 to Length(Subs)-1 do Subs[i] := 0; end; destructor TCalculator.Destroy; begin SetLength(Subs, 0); FreeMem(Src); Results.Free; Threads.Free; inherited; end; function TCalculator.FindUnique(UniqueSubsRequired: integer): TCombination; var i, j, k, startidx : cardinal; subplaces : cardinal; sub : TCombination; remaining : integer; foundidxs : array of boolean; begin Result := 0; SetLength(foundidxs, SubsInSrcCount); startidx := SrcIndex; for i := startidx to SrcLength-1 do begin inc(SrcIndex); if Src^[i].Used then Continue; remaining := SubsInSrcCount; for j := 0 to SubsInSrcCount-1 do begin sub := Src^[i].Subs[j].Blob; foundidxs[j] := FALSE; for k := 0 to Length(Subs)-1 do begin if Subs[k] = sub then begin foundidxs[j] := TRUE; Break; end else if Subs[k] = 0 then Break; end; if foundidxs[j] then begin dec(remaining); if remaining < UniqueSubsRequired then Break; end; end; if remaining >= UniqueSubsRequired then begin for j := 0 to SubsInSrcCount-1 do if not foundidxs[j] then begin Subs[SubsIndex] := Src^[i].Subs[j].Blob; inc(SubsIndex); end; Src^[i].Used := TRUE; Result := Src^[i].Main.Blob; Break; end; end; end; end.
unit frPipePrinter; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls; type TframPipePrinter = class(TFrame) edtPipe: TEdit; Label1: TLabel; cmbxPrinter: TComboBox; Label2: TLabel; btnDelete: TButton; lblPrinted: TLabel; tmrPrinted: TTimer; procedure tmrPrintedTimer(Sender: TObject); private FSectionName: string; FPrintCount: Integer; function GetOutputPrinter: string; function GetPipeName: string; procedure SetOutputPrinter(const Value: string); procedure SetPipeName(const Value: string); procedure SetPrintCount(const Value: Integer); public procedure AfterConstruction;override; destructor Destroy; override; property SectionName : string read FSectionName write FSectionName; property PipeName : string read GetPipeName write SetPipeName; property OutputPrinter: string read GetOutputPrinter write SetOutputPrinter; property PrintCount: Integer read FPrintCount write SetPrintCount; end; implementation uses Printers; {$R *.dfm} { TframPipePrinter } procedure TframPipePrinter.AfterConstruction; begin inherited; edtPipe.Text := 'printpipe1'; //load available printers cmbxPrinter.Items.Text := Printer.Printers.Text; end; destructor TframPipePrinter.Destroy; begin inherited; end; function TframPipePrinter.GetOutputPrinter: string; begin Result := cmbxPrinter.Text; end; function TframPipePrinter.GetPipeName: string; begin Result := edtPipe.Text; end; procedure TframPipePrinter.SetOutputPrinter(const Value: string); begin cmbxPrinter.ItemIndex := cmbxPrinter.Items.IndexOf(Value); end; procedure TframPipePrinter.SetPipeName(const Value: string); begin edtPipe.Text := Value; end; procedure TframPipePrinter.SetPrintCount(const Value: Integer); begin FPrintCount := Value; lblPrinted.Caption := Format('Printed: %d',[Value]); if Value > 0 then begin Self.Color := clLime; tmrPrinted.Enabled := True; end; end; procedure TframPipePrinter.tmrPrintedTimer(Sender: TObject); begin tmrPrinted.Enabled := False; Self.Color := clBtnFace; end; end.
unit DBDateTimePicker; interface uses System.SysUtils, System.Classes, Vcl.Controls, Vcl.ComCtrls, Data.DB, Vcl.DBCtrls, Vcl.Forms, Winapi.Messages; type TDBDateTimePicker = class(TDateTimePicker) private FDataLink: TFieldDataLink; function GetDataSource: TDataSource; procedure SetDataField(const Value: string); procedure SetDataSource(const Value: TDataSource); function GetDataField: string; procedure DataChange(Sender: TObject); { Private declarations } protected {Protected declarations } procedure UpdateData(Sender: TObject); procedure CMExit(var Message: TCMExit); message CM_EXIT; public { Public declarations } constructor Create(AOwner: TComponent); override; procedure Change(); override; published { Published declarations } property DataSource: TDataSource read GetDataSource write SetDataSource; property DataField: string read GetDataField write SetDataField; end; procedure Register; implementation procedure Register; begin RegisterComponents('componenteOW', [TDBDateTimePicker]); end; { TDBDateTimePicker } procedure TDBDateTimePicker.Change; begin if not(FDataLink.Edit) then FDataLink.Edit; FDataLink.Modified; inherited; end; procedure TDBDateTimePicker.CMExit(var Message: TCMExit); begin inherited; try FDataLink.UpdateRecord; except on Exception do SetFocus; end; end; constructor TDBDateTimePicker.Create(AOwner: TComponent); begin inherited; FDataLink := TFieldDataLink.Create; FDataLink.OnDataChange := DataChange; FDataLink.OnUpdateData := UpdateData; end; procedure TDBDateTimePicker.DataChange(Sender: TObject); begin if (Assigned(FDataLink.DataSource)) and (Assigned(FDataLink.Field)) then Self.Date := FDataLink.Field.AsDateTime; end; function TDBDateTimePicker.GetDataField: string; begin Result := FDataLink.FieldName; end; function TDBDateTimePicker.GetDataSource: TDataSource; begin Result := FDataLink.DataSource; end; procedure TDBDateTimePicker.SetDataField(const Value: string); begin FDataLink.FieldName := Value; end; procedure TDBDateTimePicker.SetDataSource(const Value: TDataSource); begin FDataLink.DataSource := Value; end; procedure TDBDateTimePicker.UpdateData(Sender: TObject); begin if (Assigned(FDataLink.DataSource)) and (Assigned(FDataLink.Field)) then FDataLink.Field.AsDateTime := Self.Date; end; end.
unit ShutDownKeywordsPack; {* Набор слов словаря для доступа к экземплярам контролов формы ShutDown } // Модуль: "w:\garant6x\implementation\Garant\GbaNemesis\View\PrimCommon\ShutDownKeywordsPack.pas" // Стереотип: "ScriptKeywordsPack" // Элемент модели: "ShutDownKeywordsPack" MUID: (7FB5E199E37C) {$Include w:\garant6x\implementation\Garant\nsDefine.inc} interface {$If NOT Defined(NoScripts)} uses l3IntfUses {$If NOT Defined(NoVCL)} , ExtCtrls {$IfEnd} // NOT Defined(NoVCL) , vtPanel , vtLabel , vtButton ; {$IfEnd} // NOT Defined(NoScripts) implementation {$If NOT Defined(NoScripts)} uses l3ImplUses , ShutDown_Form , tfwControlString {$If NOT Defined(NoVCL)} , kwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) , tfwScriptingInterfaces , tfwPropertyLike , TypInfo , tfwTypeInfo , TtfwClassRef_Proxy , SysUtils , TtfwTypeRegistrator_Proxy , tfwScriptingTypes ; type Tkw_Form_ShutDown = {final} class(TtfwControlString) {* Слово словаря для идентификатора формы ShutDown ---- *Пример использования*: [code] 'aControl' форма::ShutDown TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_Form_ShutDown Tkw_ShutDown_Component_ShutdownTimer = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола ShutdownTimer ---- *Пример использования*: [code] компонент::ShutdownTimer TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ShutDown_Component_ShutdownTimer Tkw_ShutDown_Control_vtPanel1 = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола vtPanel1 ---- *Пример использования*: [code] контрол::vtPanel1 TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ShutDown_Control_vtPanel1 Tkw_ShutDown_Control_vtPanel1_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола vtPanel1 ---- *Пример использования*: [code] контрол::vtPanel1:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ShutDown_Control_vtPanel1_Push Tkw_ShutDown_Control_LeftPanel = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола LeftPanel ---- *Пример использования*: [code] контрол::LeftPanel TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ShutDown_Control_LeftPanel Tkw_ShutDown_Control_LeftPanel_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола LeftPanel ---- *Пример использования*: [code] контрол::LeftPanel:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ShutDown_Control_LeftPanel_Push Tkw_ShutDown_Control_Image = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола Image ---- *Пример использования*: [code] контрол::Image TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ShutDown_Control_Image Tkw_ShutDown_Control_Image_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола Image ---- *Пример использования*: [code] контрол::Image:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ShutDown_Control_Image_Push Tkw_ShutDown_Control_CenterPanel = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола CenterPanel ---- *Пример использования*: [code] контрол::CenterPanel TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ShutDown_Control_CenterPanel Tkw_ShutDown_Control_CenterPanel_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола CenterPanel ---- *Пример использования*: [code] контрол::CenterPanel:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ShutDown_Control_CenterPanel_Push Tkw_ShutDown_Control_TopSpacerPanel = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола TopSpacerPanel ---- *Пример использования*: [code] контрол::TopSpacerPanel TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ShutDown_Control_TopSpacerPanel Tkw_ShutDown_Control_TopSpacerPanel_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола TopSpacerPanel ---- *Пример использования*: [code] контрол::TopSpacerPanel:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ShutDown_Control_TopSpacerPanel_Push Tkw_ShutDown_Control_WarningText = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола WarningText ---- *Пример использования*: [code] контрол::WarningText TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ShutDown_Control_WarningText Tkw_ShutDown_Control_WarningText_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола WarningText ---- *Пример использования*: [code] контрол::WarningText:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ShutDown_Control_WarningText_Push Tkw_ShutDown_Control_RightSpacerPanel = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола RightSpacerPanel ---- *Пример использования*: [code] контрол::RightSpacerPanel TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ShutDown_Control_RightSpacerPanel Tkw_ShutDown_Control_RightSpacerPanel_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола RightSpacerPanel ---- *Пример использования*: [code] контрол::RightSpacerPanel:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ShutDown_Control_RightSpacerPanel_Push Tkw_ShutDown_Control_pnlBottom = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола pnlBottom ---- *Пример использования*: [code] контрол::pnlBottom TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ShutDown_Control_pnlBottom Tkw_ShutDown_Control_pnlBottom_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола pnlBottom ---- *Пример использования*: [code] контрол::pnlBottom:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ShutDown_Control_pnlBottom_Push Tkw_ShutDown_Control_CloseButton = {final} class(TtfwControlString) {* Слово словаря для идентификатора контрола CloseButton ---- *Пример использования*: [code] контрол::CloseButton TryFocus ASSERT [code] } protected function GetString: AnsiString; override; class procedure RegisterInEngine; override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ShutDown_Control_CloseButton Tkw_ShutDown_Control_CloseButton_Push = {final} class({$If NOT Defined(NoVCL)} TkwBynameControlPush {$IfEnd} // NOT Defined(NoVCL) ) {* Слово словаря для контрола CloseButton ---- *Пример использования*: [code] контрол::CloseButton:push pop:control:SetFocus ASSERT [code] } protected procedure DoDoIt(const aCtx: TtfwContext); override; class function GetWordNameForRegister: AnsiString; override; end;//Tkw_ShutDown_Control_CloseButton_Push TkwShutDownFormShutdownTimer = {final} class(TtfwPropertyLike) {* Слово скрипта .TShutDownForm.ShutdownTimer } private function ShutdownTimer(const aCtx: TtfwContext; aShutDownForm: TShutDownForm): TTimer; {* Реализация слова скрипта .TShutDownForm.ShutdownTimer } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwShutDownFormShutdownTimer TkwShutDownFormVtPanel1 = {final} class(TtfwPropertyLike) {* Слово скрипта .TShutDownForm.vtPanel1 } private function vtPanel1(const aCtx: TtfwContext; aShutDownForm: TShutDownForm): TvtPanel; {* Реализация слова скрипта .TShutDownForm.vtPanel1 } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwShutDownFormVtPanel1 TkwShutDownFormLeftPanel = {final} class(TtfwPropertyLike) {* Слово скрипта .TShutDownForm.LeftPanel } private function LeftPanel(const aCtx: TtfwContext; aShutDownForm: TShutDownForm): TvtPanel; {* Реализация слова скрипта .TShutDownForm.LeftPanel } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwShutDownFormLeftPanel TkwShutDownFormImage = {final} class(TtfwPropertyLike) {* Слово скрипта .TShutDownForm.Image } private function Image(const aCtx: TtfwContext; aShutDownForm: TShutDownForm): TImage; {* Реализация слова скрипта .TShutDownForm.Image } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwShutDownFormImage TkwShutDownFormCenterPanel = {final} class(TtfwPropertyLike) {* Слово скрипта .TShutDownForm.CenterPanel } private function CenterPanel(const aCtx: TtfwContext; aShutDownForm: TShutDownForm): TvtPanel; {* Реализация слова скрипта .TShutDownForm.CenterPanel } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwShutDownFormCenterPanel TkwShutDownFormTopSpacerPanel = {final} class(TtfwPropertyLike) {* Слово скрипта .TShutDownForm.TopSpacerPanel } private function TopSpacerPanel(const aCtx: TtfwContext; aShutDownForm: TShutDownForm): TvtPanel; {* Реализация слова скрипта .TShutDownForm.TopSpacerPanel } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwShutDownFormTopSpacerPanel TkwShutDownFormWarningText = {final} class(TtfwPropertyLike) {* Слово скрипта .TShutDownForm.WarningText } private function WarningText(const aCtx: TtfwContext; aShutDownForm: TShutDownForm): TvtLabel; {* Реализация слова скрипта .TShutDownForm.WarningText } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwShutDownFormWarningText TkwShutDownFormRightSpacerPanel = {final} class(TtfwPropertyLike) {* Слово скрипта .TShutDownForm.RightSpacerPanel } private function RightSpacerPanel(const aCtx: TtfwContext; aShutDownForm: TShutDownForm): TvtPanel; {* Реализация слова скрипта .TShutDownForm.RightSpacerPanel } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwShutDownFormRightSpacerPanel TkwShutDownFormPnlBottom = {final} class(TtfwPropertyLike) {* Слово скрипта .TShutDownForm.pnlBottom } private function pnlBottom(const aCtx: TtfwContext; aShutDownForm: TShutDownForm): TvtPanel; {* Реализация слова скрипта .TShutDownForm.pnlBottom } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwShutDownFormPnlBottom TkwShutDownFormCloseButton = {final} class(TtfwPropertyLike) {* Слово скрипта .TShutDownForm.CloseButton } private function CloseButton(const aCtx: TtfwContext; aShutDownForm: TShutDownForm): TvtButton; {* Реализация слова скрипта .TShutDownForm.CloseButton } protected class function GetWordNameForRegister: AnsiString; override; procedure DoDoIt(const aCtx: TtfwContext); override; public function GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; override; function GetAllParamsCount(const aCtx: TtfwContext): Integer; override; function ParamsTypes: PTypeInfoArray; override; procedure SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); override; end;//TkwShutDownFormCloseButton function Tkw_Form_ShutDown.GetString: AnsiString; begin Result := 'ShutDownForm'; end;//Tkw_Form_ShutDown.GetString class function Tkw_Form_ShutDown.GetWordNameForRegister: AnsiString; begin Result := 'форма::ShutDown'; end;//Tkw_Form_ShutDown.GetWordNameForRegister function Tkw_ShutDown_Component_ShutdownTimer.GetString: AnsiString; begin Result := 'ShutdownTimer'; end;//Tkw_ShutDown_Component_ShutdownTimer.GetString class procedure Tkw_ShutDown_Component_ShutdownTimer.RegisterInEngine; begin inherited; TtfwClassRef.Register(TTimer); end;//Tkw_ShutDown_Component_ShutdownTimer.RegisterInEngine class function Tkw_ShutDown_Component_ShutdownTimer.GetWordNameForRegister: AnsiString; begin Result := 'компонент::ShutdownTimer'; end;//Tkw_ShutDown_Component_ShutdownTimer.GetWordNameForRegister function Tkw_ShutDown_Control_vtPanel1.GetString: AnsiString; begin Result := 'vtPanel1'; end;//Tkw_ShutDown_Control_vtPanel1.GetString class procedure Tkw_ShutDown_Control_vtPanel1.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtPanel); end;//Tkw_ShutDown_Control_vtPanel1.RegisterInEngine class function Tkw_ShutDown_Control_vtPanel1.GetWordNameForRegister: AnsiString; begin Result := 'контрол::vtPanel1'; end;//Tkw_ShutDown_Control_vtPanel1.GetWordNameForRegister procedure Tkw_ShutDown_Control_vtPanel1_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('vtPanel1'); inherited; end;//Tkw_ShutDown_Control_vtPanel1_Push.DoDoIt class function Tkw_ShutDown_Control_vtPanel1_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::vtPanel1:push'; end;//Tkw_ShutDown_Control_vtPanel1_Push.GetWordNameForRegister function Tkw_ShutDown_Control_LeftPanel.GetString: AnsiString; begin Result := 'LeftPanel'; end;//Tkw_ShutDown_Control_LeftPanel.GetString class procedure Tkw_ShutDown_Control_LeftPanel.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtPanel); end;//Tkw_ShutDown_Control_LeftPanel.RegisterInEngine class function Tkw_ShutDown_Control_LeftPanel.GetWordNameForRegister: AnsiString; begin Result := 'контрол::LeftPanel'; end;//Tkw_ShutDown_Control_LeftPanel.GetWordNameForRegister procedure Tkw_ShutDown_Control_LeftPanel_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('LeftPanel'); inherited; end;//Tkw_ShutDown_Control_LeftPanel_Push.DoDoIt class function Tkw_ShutDown_Control_LeftPanel_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::LeftPanel:push'; end;//Tkw_ShutDown_Control_LeftPanel_Push.GetWordNameForRegister function Tkw_ShutDown_Control_Image.GetString: AnsiString; begin Result := 'Image'; end;//Tkw_ShutDown_Control_Image.GetString class procedure Tkw_ShutDown_Control_Image.RegisterInEngine; begin inherited; TtfwClassRef.Register(TImage); end;//Tkw_ShutDown_Control_Image.RegisterInEngine class function Tkw_ShutDown_Control_Image.GetWordNameForRegister: AnsiString; begin Result := 'контрол::Image'; end;//Tkw_ShutDown_Control_Image.GetWordNameForRegister procedure Tkw_ShutDown_Control_Image_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('Image'); inherited; end;//Tkw_ShutDown_Control_Image_Push.DoDoIt class function Tkw_ShutDown_Control_Image_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::Image:push'; end;//Tkw_ShutDown_Control_Image_Push.GetWordNameForRegister function Tkw_ShutDown_Control_CenterPanel.GetString: AnsiString; begin Result := 'CenterPanel'; end;//Tkw_ShutDown_Control_CenterPanel.GetString class procedure Tkw_ShutDown_Control_CenterPanel.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtPanel); end;//Tkw_ShutDown_Control_CenterPanel.RegisterInEngine class function Tkw_ShutDown_Control_CenterPanel.GetWordNameForRegister: AnsiString; begin Result := 'контрол::CenterPanel'; end;//Tkw_ShutDown_Control_CenterPanel.GetWordNameForRegister procedure Tkw_ShutDown_Control_CenterPanel_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('CenterPanel'); inherited; end;//Tkw_ShutDown_Control_CenterPanel_Push.DoDoIt class function Tkw_ShutDown_Control_CenterPanel_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::CenterPanel:push'; end;//Tkw_ShutDown_Control_CenterPanel_Push.GetWordNameForRegister function Tkw_ShutDown_Control_TopSpacerPanel.GetString: AnsiString; begin Result := 'TopSpacerPanel'; end;//Tkw_ShutDown_Control_TopSpacerPanel.GetString class procedure Tkw_ShutDown_Control_TopSpacerPanel.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtPanel); end;//Tkw_ShutDown_Control_TopSpacerPanel.RegisterInEngine class function Tkw_ShutDown_Control_TopSpacerPanel.GetWordNameForRegister: AnsiString; begin Result := 'контрол::TopSpacerPanel'; end;//Tkw_ShutDown_Control_TopSpacerPanel.GetWordNameForRegister procedure Tkw_ShutDown_Control_TopSpacerPanel_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('TopSpacerPanel'); inherited; end;//Tkw_ShutDown_Control_TopSpacerPanel_Push.DoDoIt class function Tkw_ShutDown_Control_TopSpacerPanel_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::TopSpacerPanel:push'; end;//Tkw_ShutDown_Control_TopSpacerPanel_Push.GetWordNameForRegister function Tkw_ShutDown_Control_WarningText.GetString: AnsiString; begin Result := 'WarningText'; end;//Tkw_ShutDown_Control_WarningText.GetString class procedure Tkw_ShutDown_Control_WarningText.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtLabel); end;//Tkw_ShutDown_Control_WarningText.RegisterInEngine class function Tkw_ShutDown_Control_WarningText.GetWordNameForRegister: AnsiString; begin Result := 'контрол::WarningText'; end;//Tkw_ShutDown_Control_WarningText.GetWordNameForRegister procedure Tkw_ShutDown_Control_WarningText_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('WarningText'); inherited; end;//Tkw_ShutDown_Control_WarningText_Push.DoDoIt class function Tkw_ShutDown_Control_WarningText_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::WarningText:push'; end;//Tkw_ShutDown_Control_WarningText_Push.GetWordNameForRegister function Tkw_ShutDown_Control_RightSpacerPanel.GetString: AnsiString; begin Result := 'RightSpacerPanel'; end;//Tkw_ShutDown_Control_RightSpacerPanel.GetString class procedure Tkw_ShutDown_Control_RightSpacerPanel.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtPanel); end;//Tkw_ShutDown_Control_RightSpacerPanel.RegisterInEngine class function Tkw_ShutDown_Control_RightSpacerPanel.GetWordNameForRegister: AnsiString; begin Result := 'контрол::RightSpacerPanel'; end;//Tkw_ShutDown_Control_RightSpacerPanel.GetWordNameForRegister procedure Tkw_ShutDown_Control_RightSpacerPanel_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('RightSpacerPanel'); inherited; end;//Tkw_ShutDown_Control_RightSpacerPanel_Push.DoDoIt class function Tkw_ShutDown_Control_RightSpacerPanel_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::RightSpacerPanel:push'; end;//Tkw_ShutDown_Control_RightSpacerPanel_Push.GetWordNameForRegister function Tkw_ShutDown_Control_pnlBottom.GetString: AnsiString; begin Result := 'pnlBottom'; end;//Tkw_ShutDown_Control_pnlBottom.GetString class procedure Tkw_ShutDown_Control_pnlBottom.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtPanel); end;//Tkw_ShutDown_Control_pnlBottom.RegisterInEngine class function Tkw_ShutDown_Control_pnlBottom.GetWordNameForRegister: AnsiString; begin Result := 'контрол::pnlBottom'; end;//Tkw_ShutDown_Control_pnlBottom.GetWordNameForRegister procedure Tkw_ShutDown_Control_pnlBottom_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('pnlBottom'); inherited; end;//Tkw_ShutDown_Control_pnlBottom_Push.DoDoIt class function Tkw_ShutDown_Control_pnlBottom_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::pnlBottom:push'; end;//Tkw_ShutDown_Control_pnlBottom_Push.GetWordNameForRegister function Tkw_ShutDown_Control_CloseButton.GetString: AnsiString; begin Result := 'CloseButton'; end;//Tkw_ShutDown_Control_CloseButton.GetString class procedure Tkw_ShutDown_Control_CloseButton.RegisterInEngine; begin inherited; TtfwClassRef.Register(TvtButton); end;//Tkw_ShutDown_Control_CloseButton.RegisterInEngine class function Tkw_ShutDown_Control_CloseButton.GetWordNameForRegister: AnsiString; begin Result := 'контрол::CloseButton'; end;//Tkw_ShutDown_Control_CloseButton.GetWordNameForRegister procedure Tkw_ShutDown_Control_CloseButton_Push.DoDoIt(const aCtx: TtfwContext); begin aCtx.rEngine.PushString('CloseButton'); inherited; end;//Tkw_ShutDown_Control_CloseButton_Push.DoDoIt class function Tkw_ShutDown_Control_CloseButton_Push.GetWordNameForRegister: AnsiString; begin Result := 'контрол::CloseButton:push'; end;//Tkw_ShutDown_Control_CloseButton_Push.GetWordNameForRegister function TkwShutDownFormShutdownTimer.ShutdownTimer(const aCtx: TtfwContext; aShutDownForm: TShutDownForm): TTimer; {* Реализация слова скрипта .TShutDownForm.ShutdownTimer } begin Result := aShutDownForm.ShutdownTimer; end;//TkwShutDownFormShutdownTimer.ShutdownTimer class function TkwShutDownFormShutdownTimer.GetWordNameForRegister: AnsiString; begin Result := '.TShutDownForm.ShutdownTimer'; end;//TkwShutDownFormShutdownTimer.GetWordNameForRegister function TkwShutDownFormShutdownTimer.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TTimer); end;//TkwShutDownFormShutdownTimer.GetResultTypeInfo function TkwShutDownFormShutdownTimer.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwShutDownFormShutdownTimer.GetAllParamsCount function TkwShutDownFormShutdownTimer.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TShutDownForm)]); end;//TkwShutDownFormShutdownTimer.ParamsTypes procedure TkwShutDownFormShutdownTimer.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству ShutdownTimer', aCtx); end;//TkwShutDownFormShutdownTimer.SetValuePrim procedure TkwShutDownFormShutdownTimer.DoDoIt(const aCtx: TtfwContext); var l_aShutDownForm: TShutDownForm; begin try l_aShutDownForm := TShutDownForm(aCtx.rEngine.PopObjAs(TShutDownForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aShutDownForm: TShutDownForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(ShutdownTimer(aCtx, l_aShutDownForm)); end;//TkwShutDownFormShutdownTimer.DoDoIt function TkwShutDownFormVtPanel1.vtPanel1(const aCtx: TtfwContext; aShutDownForm: TShutDownForm): TvtPanel; {* Реализация слова скрипта .TShutDownForm.vtPanel1 } begin Result := aShutDownForm.vtPanel1; end;//TkwShutDownFormVtPanel1.vtPanel1 class function TkwShutDownFormVtPanel1.GetWordNameForRegister: AnsiString; begin Result := '.TShutDownForm.vtPanel1'; end;//TkwShutDownFormVtPanel1.GetWordNameForRegister function TkwShutDownFormVtPanel1.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtPanel); end;//TkwShutDownFormVtPanel1.GetResultTypeInfo function TkwShutDownFormVtPanel1.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwShutDownFormVtPanel1.GetAllParamsCount function TkwShutDownFormVtPanel1.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TShutDownForm)]); end;//TkwShutDownFormVtPanel1.ParamsTypes procedure TkwShutDownFormVtPanel1.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству vtPanel1', aCtx); end;//TkwShutDownFormVtPanel1.SetValuePrim procedure TkwShutDownFormVtPanel1.DoDoIt(const aCtx: TtfwContext); var l_aShutDownForm: TShutDownForm; begin try l_aShutDownForm := TShutDownForm(aCtx.rEngine.PopObjAs(TShutDownForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aShutDownForm: TShutDownForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(vtPanel1(aCtx, l_aShutDownForm)); end;//TkwShutDownFormVtPanel1.DoDoIt function TkwShutDownFormLeftPanel.LeftPanel(const aCtx: TtfwContext; aShutDownForm: TShutDownForm): TvtPanel; {* Реализация слова скрипта .TShutDownForm.LeftPanel } begin Result := aShutDownForm.LeftPanel; end;//TkwShutDownFormLeftPanel.LeftPanel class function TkwShutDownFormLeftPanel.GetWordNameForRegister: AnsiString; begin Result := '.TShutDownForm.LeftPanel'; end;//TkwShutDownFormLeftPanel.GetWordNameForRegister function TkwShutDownFormLeftPanel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtPanel); end;//TkwShutDownFormLeftPanel.GetResultTypeInfo function TkwShutDownFormLeftPanel.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwShutDownFormLeftPanel.GetAllParamsCount function TkwShutDownFormLeftPanel.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TShutDownForm)]); end;//TkwShutDownFormLeftPanel.ParamsTypes procedure TkwShutDownFormLeftPanel.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству LeftPanel', aCtx); end;//TkwShutDownFormLeftPanel.SetValuePrim procedure TkwShutDownFormLeftPanel.DoDoIt(const aCtx: TtfwContext); var l_aShutDownForm: TShutDownForm; begin try l_aShutDownForm := TShutDownForm(aCtx.rEngine.PopObjAs(TShutDownForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aShutDownForm: TShutDownForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(LeftPanel(aCtx, l_aShutDownForm)); end;//TkwShutDownFormLeftPanel.DoDoIt function TkwShutDownFormImage.Image(const aCtx: TtfwContext; aShutDownForm: TShutDownForm): TImage; {* Реализация слова скрипта .TShutDownForm.Image } begin Result := aShutDownForm.Image; end;//TkwShutDownFormImage.Image class function TkwShutDownFormImage.GetWordNameForRegister: AnsiString; begin Result := '.TShutDownForm.Image'; end;//TkwShutDownFormImage.GetWordNameForRegister function TkwShutDownFormImage.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TImage); end;//TkwShutDownFormImage.GetResultTypeInfo function TkwShutDownFormImage.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwShutDownFormImage.GetAllParamsCount function TkwShutDownFormImage.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TShutDownForm)]); end;//TkwShutDownFormImage.ParamsTypes procedure TkwShutDownFormImage.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству Image', aCtx); end;//TkwShutDownFormImage.SetValuePrim procedure TkwShutDownFormImage.DoDoIt(const aCtx: TtfwContext); var l_aShutDownForm: TShutDownForm; begin try l_aShutDownForm := TShutDownForm(aCtx.rEngine.PopObjAs(TShutDownForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aShutDownForm: TShutDownForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(Image(aCtx, l_aShutDownForm)); end;//TkwShutDownFormImage.DoDoIt function TkwShutDownFormCenterPanel.CenterPanel(const aCtx: TtfwContext; aShutDownForm: TShutDownForm): TvtPanel; {* Реализация слова скрипта .TShutDownForm.CenterPanel } begin Result := aShutDownForm.CenterPanel; end;//TkwShutDownFormCenterPanel.CenterPanel class function TkwShutDownFormCenterPanel.GetWordNameForRegister: AnsiString; begin Result := '.TShutDownForm.CenterPanel'; end;//TkwShutDownFormCenterPanel.GetWordNameForRegister function TkwShutDownFormCenterPanel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtPanel); end;//TkwShutDownFormCenterPanel.GetResultTypeInfo function TkwShutDownFormCenterPanel.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwShutDownFormCenterPanel.GetAllParamsCount function TkwShutDownFormCenterPanel.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TShutDownForm)]); end;//TkwShutDownFormCenterPanel.ParamsTypes procedure TkwShutDownFormCenterPanel.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству CenterPanel', aCtx); end;//TkwShutDownFormCenterPanel.SetValuePrim procedure TkwShutDownFormCenterPanel.DoDoIt(const aCtx: TtfwContext); var l_aShutDownForm: TShutDownForm; begin try l_aShutDownForm := TShutDownForm(aCtx.rEngine.PopObjAs(TShutDownForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aShutDownForm: TShutDownForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(CenterPanel(aCtx, l_aShutDownForm)); end;//TkwShutDownFormCenterPanel.DoDoIt function TkwShutDownFormTopSpacerPanel.TopSpacerPanel(const aCtx: TtfwContext; aShutDownForm: TShutDownForm): TvtPanel; {* Реализация слова скрипта .TShutDownForm.TopSpacerPanel } begin Result := aShutDownForm.TopSpacerPanel; end;//TkwShutDownFormTopSpacerPanel.TopSpacerPanel class function TkwShutDownFormTopSpacerPanel.GetWordNameForRegister: AnsiString; begin Result := '.TShutDownForm.TopSpacerPanel'; end;//TkwShutDownFormTopSpacerPanel.GetWordNameForRegister function TkwShutDownFormTopSpacerPanel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtPanel); end;//TkwShutDownFormTopSpacerPanel.GetResultTypeInfo function TkwShutDownFormTopSpacerPanel.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwShutDownFormTopSpacerPanel.GetAllParamsCount function TkwShutDownFormTopSpacerPanel.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TShutDownForm)]); end;//TkwShutDownFormTopSpacerPanel.ParamsTypes procedure TkwShutDownFormTopSpacerPanel.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству TopSpacerPanel', aCtx); end;//TkwShutDownFormTopSpacerPanel.SetValuePrim procedure TkwShutDownFormTopSpacerPanel.DoDoIt(const aCtx: TtfwContext); var l_aShutDownForm: TShutDownForm; begin try l_aShutDownForm := TShutDownForm(aCtx.rEngine.PopObjAs(TShutDownForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aShutDownForm: TShutDownForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(TopSpacerPanel(aCtx, l_aShutDownForm)); end;//TkwShutDownFormTopSpacerPanel.DoDoIt function TkwShutDownFormWarningText.WarningText(const aCtx: TtfwContext; aShutDownForm: TShutDownForm): TvtLabel; {* Реализация слова скрипта .TShutDownForm.WarningText } begin Result := aShutDownForm.WarningText; end;//TkwShutDownFormWarningText.WarningText class function TkwShutDownFormWarningText.GetWordNameForRegister: AnsiString; begin Result := '.TShutDownForm.WarningText'; end;//TkwShutDownFormWarningText.GetWordNameForRegister function TkwShutDownFormWarningText.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtLabel); end;//TkwShutDownFormWarningText.GetResultTypeInfo function TkwShutDownFormWarningText.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwShutDownFormWarningText.GetAllParamsCount function TkwShutDownFormWarningText.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TShutDownForm)]); end;//TkwShutDownFormWarningText.ParamsTypes procedure TkwShutDownFormWarningText.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству WarningText', aCtx); end;//TkwShutDownFormWarningText.SetValuePrim procedure TkwShutDownFormWarningText.DoDoIt(const aCtx: TtfwContext); var l_aShutDownForm: TShutDownForm; begin try l_aShutDownForm := TShutDownForm(aCtx.rEngine.PopObjAs(TShutDownForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aShutDownForm: TShutDownForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(WarningText(aCtx, l_aShutDownForm)); end;//TkwShutDownFormWarningText.DoDoIt function TkwShutDownFormRightSpacerPanel.RightSpacerPanel(const aCtx: TtfwContext; aShutDownForm: TShutDownForm): TvtPanel; {* Реализация слова скрипта .TShutDownForm.RightSpacerPanel } begin Result := aShutDownForm.RightSpacerPanel; end;//TkwShutDownFormRightSpacerPanel.RightSpacerPanel class function TkwShutDownFormRightSpacerPanel.GetWordNameForRegister: AnsiString; begin Result := '.TShutDownForm.RightSpacerPanel'; end;//TkwShutDownFormRightSpacerPanel.GetWordNameForRegister function TkwShutDownFormRightSpacerPanel.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtPanel); end;//TkwShutDownFormRightSpacerPanel.GetResultTypeInfo function TkwShutDownFormRightSpacerPanel.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwShutDownFormRightSpacerPanel.GetAllParamsCount function TkwShutDownFormRightSpacerPanel.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TShutDownForm)]); end;//TkwShutDownFormRightSpacerPanel.ParamsTypes procedure TkwShutDownFormRightSpacerPanel.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству RightSpacerPanel', aCtx); end;//TkwShutDownFormRightSpacerPanel.SetValuePrim procedure TkwShutDownFormRightSpacerPanel.DoDoIt(const aCtx: TtfwContext); var l_aShutDownForm: TShutDownForm; begin try l_aShutDownForm := TShutDownForm(aCtx.rEngine.PopObjAs(TShutDownForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aShutDownForm: TShutDownForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(RightSpacerPanel(aCtx, l_aShutDownForm)); end;//TkwShutDownFormRightSpacerPanel.DoDoIt function TkwShutDownFormPnlBottom.pnlBottom(const aCtx: TtfwContext; aShutDownForm: TShutDownForm): TvtPanel; {* Реализация слова скрипта .TShutDownForm.pnlBottom } begin Result := aShutDownForm.pnlBottom; end;//TkwShutDownFormPnlBottom.pnlBottom class function TkwShutDownFormPnlBottom.GetWordNameForRegister: AnsiString; begin Result := '.TShutDownForm.pnlBottom'; end;//TkwShutDownFormPnlBottom.GetWordNameForRegister function TkwShutDownFormPnlBottom.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtPanel); end;//TkwShutDownFormPnlBottom.GetResultTypeInfo function TkwShutDownFormPnlBottom.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwShutDownFormPnlBottom.GetAllParamsCount function TkwShutDownFormPnlBottom.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TShutDownForm)]); end;//TkwShutDownFormPnlBottom.ParamsTypes procedure TkwShutDownFormPnlBottom.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству pnlBottom', aCtx); end;//TkwShutDownFormPnlBottom.SetValuePrim procedure TkwShutDownFormPnlBottom.DoDoIt(const aCtx: TtfwContext); var l_aShutDownForm: TShutDownForm; begin try l_aShutDownForm := TShutDownForm(aCtx.rEngine.PopObjAs(TShutDownForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aShutDownForm: TShutDownForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(pnlBottom(aCtx, l_aShutDownForm)); end;//TkwShutDownFormPnlBottom.DoDoIt function TkwShutDownFormCloseButton.CloseButton(const aCtx: TtfwContext; aShutDownForm: TShutDownForm): TvtButton; {* Реализация слова скрипта .TShutDownForm.CloseButton } begin Result := aShutDownForm.CloseButton; end;//TkwShutDownFormCloseButton.CloseButton class function TkwShutDownFormCloseButton.GetWordNameForRegister: AnsiString; begin Result := '.TShutDownForm.CloseButton'; end;//TkwShutDownFormCloseButton.GetWordNameForRegister function TkwShutDownFormCloseButton.GetResultTypeInfo(const aCtx: TtfwContext): PTypeInfo; begin Result := TypeInfo(TvtButton); end;//TkwShutDownFormCloseButton.GetResultTypeInfo function TkwShutDownFormCloseButton.GetAllParamsCount(const aCtx: TtfwContext): Integer; begin Result := 1; end;//TkwShutDownFormCloseButton.GetAllParamsCount function TkwShutDownFormCloseButton.ParamsTypes: PTypeInfoArray; begin Result := OpenTypesToTypes([TypeInfo(TShutDownForm)]); end;//TkwShutDownFormCloseButton.ParamsTypes procedure TkwShutDownFormCloseButton.SetValuePrim(const aValue: TtfwStackValue; const aCtx: TtfwContext); begin RunnerError('Нельзя присваивать значение readonly свойству CloseButton', aCtx); end;//TkwShutDownFormCloseButton.SetValuePrim procedure TkwShutDownFormCloseButton.DoDoIt(const aCtx: TtfwContext); var l_aShutDownForm: TShutDownForm; begin try l_aShutDownForm := TShutDownForm(aCtx.rEngine.PopObjAs(TShutDownForm)); except on E: Exception do begin RunnerError('Ошибка при получении параметра aShutDownForm: TShutDownForm : ' + E.Message, aCtx); Exit; end;//on E: Exception end;//try..except aCtx.rEngine.PushObj(CloseButton(aCtx, l_aShutDownForm)); end;//TkwShutDownFormCloseButton.DoDoIt initialization Tkw_Form_ShutDown.RegisterInEngine; {* Регистрация Tkw_Form_ShutDown } Tkw_ShutDown_Component_ShutdownTimer.RegisterInEngine; {* Регистрация Tkw_ShutDown_Component_ShutdownTimer } Tkw_ShutDown_Control_vtPanel1.RegisterInEngine; {* Регистрация Tkw_ShutDown_Control_vtPanel1 } Tkw_ShutDown_Control_vtPanel1_Push.RegisterInEngine; {* Регистрация Tkw_ShutDown_Control_vtPanel1_Push } Tkw_ShutDown_Control_LeftPanel.RegisterInEngine; {* Регистрация Tkw_ShutDown_Control_LeftPanel } Tkw_ShutDown_Control_LeftPanel_Push.RegisterInEngine; {* Регистрация Tkw_ShutDown_Control_LeftPanel_Push } Tkw_ShutDown_Control_Image.RegisterInEngine; {* Регистрация Tkw_ShutDown_Control_Image } Tkw_ShutDown_Control_Image_Push.RegisterInEngine; {* Регистрация Tkw_ShutDown_Control_Image_Push } Tkw_ShutDown_Control_CenterPanel.RegisterInEngine; {* Регистрация Tkw_ShutDown_Control_CenterPanel } Tkw_ShutDown_Control_CenterPanel_Push.RegisterInEngine; {* Регистрация Tkw_ShutDown_Control_CenterPanel_Push } Tkw_ShutDown_Control_TopSpacerPanel.RegisterInEngine; {* Регистрация Tkw_ShutDown_Control_TopSpacerPanel } Tkw_ShutDown_Control_TopSpacerPanel_Push.RegisterInEngine; {* Регистрация Tkw_ShutDown_Control_TopSpacerPanel_Push } Tkw_ShutDown_Control_WarningText.RegisterInEngine; {* Регистрация Tkw_ShutDown_Control_WarningText } Tkw_ShutDown_Control_WarningText_Push.RegisterInEngine; {* Регистрация Tkw_ShutDown_Control_WarningText_Push } Tkw_ShutDown_Control_RightSpacerPanel.RegisterInEngine; {* Регистрация Tkw_ShutDown_Control_RightSpacerPanel } Tkw_ShutDown_Control_RightSpacerPanel_Push.RegisterInEngine; {* Регистрация Tkw_ShutDown_Control_RightSpacerPanel_Push } Tkw_ShutDown_Control_pnlBottom.RegisterInEngine; {* Регистрация Tkw_ShutDown_Control_pnlBottom } Tkw_ShutDown_Control_pnlBottom_Push.RegisterInEngine; {* Регистрация Tkw_ShutDown_Control_pnlBottom_Push } Tkw_ShutDown_Control_CloseButton.RegisterInEngine; {* Регистрация Tkw_ShutDown_Control_CloseButton } Tkw_ShutDown_Control_CloseButton_Push.RegisterInEngine; {* Регистрация Tkw_ShutDown_Control_CloseButton_Push } TkwShutDownFormShutdownTimer.RegisterInEngine; {* Регистрация ShutDownForm_ShutdownTimer } TkwShutDownFormVtPanel1.RegisterInEngine; {* Регистрация ShutDownForm_vtPanel1 } TkwShutDownFormLeftPanel.RegisterInEngine; {* Регистрация ShutDownForm_LeftPanel } TkwShutDownFormImage.RegisterInEngine; {* Регистрация ShutDownForm_Image } TkwShutDownFormCenterPanel.RegisterInEngine; {* Регистрация ShutDownForm_CenterPanel } TkwShutDownFormTopSpacerPanel.RegisterInEngine; {* Регистрация ShutDownForm_TopSpacerPanel } TkwShutDownFormWarningText.RegisterInEngine; {* Регистрация ShutDownForm_WarningText } TkwShutDownFormRightSpacerPanel.RegisterInEngine; {* Регистрация ShutDownForm_RightSpacerPanel } TkwShutDownFormPnlBottom.RegisterInEngine; {* Регистрация ShutDownForm_pnlBottom } TkwShutDownFormCloseButton.RegisterInEngine; {* Регистрация ShutDownForm_CloseButton } TtfwTypeRegistrator.RegisterType(TypeInfo(TShutDownForm)); {* Регистрация типа TShutDownForm } TtfwTypeRegistrator.RegisterType(TypeInfo(TTimer)); {* Регистрация типа TTimer } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtPanel)); {* Регистрация типа TvtPanel } TtfwTypeRegistrator.RegisterType(TypeInfo(TImage)); {* Регистрация типа TImage } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtLabel)); {* Регистрация типа TvtLabel } TtfwTypeRegistrator.RegisterType(TypeInfo(TvtButton)); {* Регистрация типа TvtButton } {$IfEnd} // NOT Defined(NoScripts) end.
program TESTSIN2 ( OUTPUT ) ; (**********************************************************************) (*$A+ *) (**********************************************************************) var X : REAL ; function F1 ( X : REAL ) : REAL ; begin (* F1 *) F1 := X * X end (* F1 *) ; function F2 ( X : REAL ) : REAL ; begin (* F2 *) F2 := SIN ( X ) end (* F2 *) ; function F3 ( X : REAL ) : REAL ; begin (* F3 *) F3 := SQRT ( X ) end (* F3 *) ; procedure F4 ( X1 : REAL ; X2 : REAL ; function F ( Y : REAL ) : REAL ) ; var X : REAL ; begin (* F4 *) X := X1 ; while X <= X2 do begin WRITELN ( 'funktion f: ' , X : 10 : 2 , F ( X ) : 10 : 2 ) ; X := ROUNDX ( X + 0.1 , - 1 ) ; end (* while *) end (* F4 *) ; begin (* HAUPTPROGRAMM *) WRITELN ( 'schleife mit f1-aufrufen' ) ; X := 1.0 ; while X <= 4.0 do begin WRITELN ( 'funktion f: ' , X : 10 : 2 , F1 ( X ) : 10 : 5 ) ; X := ROUNDX ( X + 0.1 , - 1 ) ; end (* while *) ; WRITELN ( 'schleife mit sinus-aufrufen' ) ; X := 1.0 ; while X <= 4.0 do begin WRITELN ( 'funktion f: ' , X : 10 : 2 , F2 ( X ) : 10 : 5 ) ; X := ROUNDX ( X + 0.1 , - 1 ) ; end (* while *) ; WRITELN ( 'schleife mit sqrt-aufrufen' ) ; X := 1.0 ; while X <= 4.0 do begin WRITELN ( 'funktion f: ' , X : 10 : 2 , F3 ( X ) : 10 : 5 ) ; X := ROUNDX ( X + 0.1 , - 1 ) ; end (* while *) ; WRITELN ( 'variabler aufruf (F4)' ) ; F4 ( 1.0 , 4.0 , F1 ) ; F4 ( 1.0 , 4.0 , F2 ) ; F4 ( 1.0 , 4.0 , F3 ) ; end (* HAUPTPROGRAMM *) .
unit PercentBar; interface uses SysUtils, Windows, Messages, Classes, Graphics, Controls, Forms, Dialogs, ExtCtrls, StdCtrls; const SensitiveRadius = 2; const InitRepeatPause = 500; { pause before repeat timer (ms) } RepeatPause = 100; { pause before hint window displays (ms)} type THorJustify = (hjCenter, hjClose); TVerJustify = (vjTop, vjCenter, vjBottom); TTextFormat = (tfNone, tfNumber, tfPercent); TKind = (kdCuantitative, kdCualitative); TWinControlClass = class of TWinControl; type TBltBitmap = class(TBitmap) procedure MakeLike(ATemplate: TBitmap); end; TTimeState = set of (tbFocusRect, tbAllowTimer); type TPercentBar = class(TGraphicControl) private FAvailableArea: word; FBackColor: TColor; FBorderStyle: TBorderStyle; FCurValue: Longint; FForeColor: TColor; FIncrement: integer; FLastCoord: integer; FLimitsVerJustify: TVerJustify; FLimitsHorJustify: THorJustify; FLimitsFont: TFont; FLimitsWidth: integer; FKind: TKind; FMaxValue: Longint; FMinValue: Longint; FProgressFont: TFont; FProgressJustify: TVerJustify; FShowMaxValue: TTextFormat; FShowMinValue: TTextFormat; FShowProgress: TTextFormat; FRepeatTimer: TTimer; FTimeState: TTimeState; FValuesList: TStrings; FEndForeBar: integer; FTypeLimits: boolean; MouseX: integer; MovingBar: boolean; RightLimitFormat: TTextFormat; LeftLimitFormat: TTextFormat; FLeftVBoxOpen: boolean; FRightVBoxOpen: boolean; ValuesBox: TWinControl; BoxClass: TWinControlClass; Acknowlege: boolean; FLimitsChangeable: boolean; function GetStartBackBar: integer; function GetEndBackBar: integer; function GetStartForeBar: integer; function GetEndForeBar: integer; function GetStartSecondHeader: integer; function GetMaxBarWidth: integer; function GetBackBarWidth: integer; function GetBarWidth: integer; function GetPercentDone: Longint; function GetProgress(const X: integer): Longint; function GetValuesList: TStrings; function GetText(const Number: Longint; const TheFormat: TTextFormat): string; procedure RunListBox(const X: integer; const Value: Longint); procedure UpDateVBox(const Val: Longint; const UpDate: boolean); procedure PaintBackground(AnImage: TBitmap); procedure PaintAsText(AnImage: TBitmap); procedure PaintAsBar(AnImage: TBitmap; PaintRect: TRect); procedure PaintHeaders(Image: TBitmap); procedure PutProgress(Image: TBitmap); procedure PutLimits(Image: TBitmap; const Left,Top,Width,Height: integer; const Number: Longint; TheFormat: TTextFormat); procedure PaintBorder(Image: TBitMap); procedure SetBorderStyle(Value: TBorderStyle); procedure SetForeColor(Value: TColor); procedure SetBackColor(Value: TColor); procedure SetMinValue(const Value: Longint); procedure SetMaxValue(const Value: Longint); procedure SetProgress(const Value: Longint); procedure SetLimitsHorJustify(Value: THorJustify); procedure SetLimitsVerJustify(Value: TVerJustify); procedure SetLimitsFont(Value: TFont); procedure SetShowMaxValue(Value: TTextFormat); procedure SetShowMinValue(Value: TTextFormat); procedure SetShowProgress(Value: TTextFormat); procedure SetProgressFont(Value: TFont); procedure SetProgressJustify(Value: TVerJustify); procedure SetLimitsWidth(const Value: integer); procedure SetValuesList(Value: TStrings); procedure SetKind(Value: TKind); procedure SetEndForeBar(const Value: integer); procedure SetLastCoord(const Value: integer); procedure SetTypeLimits(const Value: boolean); procedure SetRightVBoxOpen(const Value: boolean); procedure SetLeftVBoxOpen(const Value: boolean); procedure KeyPressVBox(Sender: TObject; var Key: Char); procedure TimerExpired(Sender: TObject); procedure RefreshFont(Sender: TObject); procedure ClickVBoxValue(Sender: TObject); procedure Exit(Sender: TObject); property LeftVBoxOpen: boolean read FLeftVBoxOpen write SetLeftVBoxOpen; property RightVBoxOpen: boolean read FRightVBoxOpen write SetRightVBoxOpen; property StartBackBar: integer read GetStartBackBar; property EndBackBar: integer read GetEndBackBar; property StartForeBar: integer read GetStartForeBar; property EndForeBar: integer read FEndForeBar write SetEndForeBar stored true; //GetEndForeBar; property StartSecondHeader: integer read GetStartSecondHeader; property MaxBarWidth: integer read GetMaxBarWidth; {Relative to StartForeBar} property BackBarWidth: integer read GetBackBarWidth; property BarWidth: integer read GetBarWidth; property LastCoord: integer read FLastCoord write SetLastCoord stored true; property AvailableArea: word read FAvailableArea write FAvailableArea; protected procedure Paint; 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 DblClick; override; procedure Click; override; procedure Loaded; override; procedure AddProgress(const Value: Longint); property PercentDone: Longint read GetPercentDone; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property TimeState: TTimeState read FTimeState write FTimeState; published property Align; property BackColor: TColor read FBackColor write SetBackColor default clWhite; property BorderStyle: TBorderStyle read FBorderStyle write SetBorderStyle default bsSingle; property Color; property Enabled; property ForeColor: TColor read FForeColor write SetForeColor default clBlack; property Increment: integer read FIncrement write FIncrement; property MinValue: Longint read FMinValue write SetMinValue default 0; property MaxValue: Longint read FMaxValue write SetMaxValue default 100; property LimitsFont: TFont read FLimitsFont write SetLimitsFont; property LimitsChangeable: boolean read FLimitsChangeable write FLimitsChangeable; property LimitsHorJustify: THorJustify read FLimitsHorJustify write SetLimitsHorJustify; property LimitsVerJustify: TVerJustify read FLimitsVerJustify write SetLimitsVerJustify; property LimitsWidth: integer read FLimitsWidth write SetLimitsWidth; property Kind: TKind read FKind write SetKind; property ParentColor; property ParentFont; property ParentShowHint; property Progress: Longint read FCurValue write SetProgress; property ProgressFont: TFont read FProgressFont write SetProgressFont; property ProgressJustify: TVerJustify read FProgressJustify write SetProgressJustify; property ShowHint; property ShowMaxValue: TTextFormat read FShowMaxValue write SetShowMaxValue; property ShowMinValue: TTextFormat read FShowMinValue write SetShowMinValue; property ShowProgress: TTextFormat read FShowProgress write SetShowProgress; property TypeLimits: boolean read FTypeLimits write SetTypeLimits; property ValuesList: TStrings read GetValuesList write SetValuesList; property Visible; end; procedure Register; implementation procedure TBltBitmap.MakeLike(ATemplate: TBitmap); begin Width := ATemplate.Width; Height := ATemplate.Height; Canvas.Brush.Color := clWindowFrame; Canvas.Brush.Style := bsSolid; Canvas.FillRect(Rect(0, 0, Width, Height)); end; function SolveForX(Y, Z: Longint): Integer; begin SolveForX := Trunc( Z * (Y * 0.01) ); end; function SolveForY(X, Z: Longint): Integer; begin if Z = 0 then Result := 0 else Result := Trunc( (X * 100) / Z ); end; function TPercentBar.GetProgress(const X: integer): Longint; begin Result := MinValue + Trunc(((FMaxValue - FMinValue)*(X-StartForeBar))/MaxBarWidth); end; function TPercentBar.GetPercentDone: Longint; begin GetPercentDone := SolveForY(FCurValue - FMinValue, FMaxValue - FMinValue); end; {TPercentBar} constructor TPercentBar.Create(AOwner: TComponent); begin inherited Create(AOwner); if FTypeLimits then BoxClass := TComboBox else BoxClass := TListBox; ValuesBox := BoxClass.Create(Self); ControlStyle := ControlStyle + [csFramed, csOpaque]; { default values } FMinValue := 0; FMaxValue := 100; FLimitsChangeable := False; FLimitsWidth := 40; FCurValue := 0; Acknowlege := false; FShowMinValue := tfNumber; FShowMaxValue := tfNumber; RightLimitFormat := FShowMaxValue; LeftLimitFormat := FShowMinValue; FShowProgress := tfPercent; FBorderStyle := bsSingle; FForeColor := clBtnFace; FBackColor := clWhite; FLimitsVerJustify := vjCenter; FLimitsHorJustify := hjCenter; FKind := kdCuantitative; FProgressJustify := vjCenter; FEndForeBar := StartForeBar; FLastCoord := StartForeBar; MovingBar := false; Width := 200; Height := 20; FIncrement := 2; TimeState := [tbAllowTimer]; AvailableArea := 80; LeftVBoxOpen := false; RightVBoxOpen := false; // Creation and initialization of Fonts FLimitsFont := TFont.Create; FLimitsFont.Assign(Font); FLimitsFont.OnChange := RefreshFont; FLimitsFont.Size := 8; FProgressFont := TFont.Create; FProgressFont.Assign(Font); FProgressFont.OnChange := RefreshFont; FProgressFont.Size := 8; FValuesList := TStringList.Create; end; destructor TPercentBar.Destroy; begin FLimitsFont.Free; FProgressFont.Free; FValuesList.Free; FRepeatTimer.Free; inherited Destroy; end; procedure TPercentBar.Loaded; begin inherited Loaded; if FKind = kdCualitative then begin FMinValue := 0; FMaxValue := FValuesList.Count - 1; end; FLastCoord := FEndForeBar; end; procedure TPercentBar.Paint; var TheImage: TBitmap; OverlayImage: TBltBitmap; PaintRect: TRect; begin with Canvas do begin TheImage := TBitmap.Create; try TheImage.Height := Height; TheImage.Width := Width; PaintBackground(TheImage); PaintRect := Rect(StartBackBar,0,EndBackBar+1, ClientHeight); if FBorderStyle = bsSingle then InflateRect(PaintRect, 0, -1); OverlayImage := TBltBitmap.Create; try OverlayImage.MakeLike(TheImage); PaintBackground(OverlayImage); PaintAsBar(OverlayImage, PaintRect); TheImage.Canvas.CopyMode := cmSrcInvert; TheImage.Canvas.Draw(0, 0, OverlayImage); TheImage.Canvas.CopyMode := cmSrcCopy; PaintHeaders(TheImage); if FBorderStyle = bsSingle then PaintBorder(TheImage); PaintAsText(TheImage); finally OverlayImage.Free; end; Canvas.CopyMode := cmSrcCopy; Canvas.Draw(0, 0, TheImage); finally TheImage.Destroy; end; end; end; procedure TPercentBar.PaintAsBar(AnImage: TBitmap; PaintRect: TRect); var H: Integer; begin with PaintRect do H := PaintRect.Bottom - PaintRect.Top + 1; with AnImage.Canvas do begin Brush.Color := BackColor; FillRect(PaintRect); Pen.Color := ForeColor; Pen.Width := 1; Brush.Color := ForeColor; FillRect(Rect(StartForeBar, 0, EndForeBar, H)); with PaintRect do begin Pen.Color := clBtnShadow; // Bevel Outer MoveTo(Right-1,Top); LineTo(Left,Top); LineTo(Left,Bottom-1); Pen.Color := clBtnHighlight; MoveTo(Left,Bottom-1); LineTo(Right-1,Bottom-1); LineTo(Right-1,Top); if EndForeBar > StartForeBar then begin Pen.Color := clBtnShadow; // Bevel Inner MoveTo(Left+1,Bottom-2); LineTo(EndForeBar, Bottom-2); LineTo(EndForeBar, Top+1); Pen.Color := clBtnHighlight; MoveTo(EndForeBar,Top+1); LineTo(Left+1,Top+1); LineTo(Left+1,Bottom-2); end; end; end; end; procedure TPercentBar.PaintBackground(AnImage: TBitmap); var ARect: TRect; begin with AnImage.Canvas do begin CopyMode := cmBlackness; ARect := Rect(0, 0, Width, Height); CopyRect(ARect, Animage.Canvas, ARect); CopyMode := cmSrcCopy; end; end; procedure TPercentBar.PaintAsText(AnImage: TBitmap); begin if ShowMinValue <> tfNone then PutLimits(AnImage,0,0,LimitsWidth,ClientHeight,MinValue, ShowMinValue); if ShowMaxValue <> tfNone then PutLimits(AnImage,StartSecondHeader,0,LimitsWidth,ClientHeight,MaxValue, ShowMaxValue); if ShowProgress <> tfNone then PutProgress(AnImage); end; procedure TPercentBar.PutProgress(Image: TBitmap); var X,Y: integer; S: string; const margin = 4; begin S := GetText(Progress,ShowProgress); with Image.Canvas do begin Font := ProgressFont; case ProgressJustify of vjTop: Y := 3; vjCenter: Y := (Height - TextHeight(S)) div 2; else // vjBottom Y := Height - TextHeight(S)-3; end; { if TextWidth(S) + margin < BarWidth then begin Brush.Color := ForeColor; X := EndForeBar - TextWidth(S) - margin; end else begin Brush.Color := BackColor; X := EndForeBar + margin; end; } if TextWidth(S) + margin < MaxBarWidth - BarWidth then begin Brush.Color := BackColor; X := EndForeBar + margin; end else begin Brush.Color := ForeColor; X := EndForeBar - TextWidth(S) - margin; end; TextOut(X,Y,S); end; end; procedure TPercentBar.PutLimits(Image: TBitmap; const Left,Top,Width,Height: integer; const Number: Longint; TheFormat: TTextFormat); var S: string; X,Y: integer; dY,dX: integer; begin with Image.Canvas do begin Font := LimitsFont; S := GetText(Number,TheFormat); case LimitsVerJustify of vjTop: dY := 1; vjCenter: dY := (Height - TextHeight(S)) div 2; else // vjBottom: dY := Height - TextHeight(S)-1; end; if LimitsHorJustify = hjCenter then dX := (Width - TextWidth(S)) div 2 else if Left = 0 then dX := LimitsWidth - TextWidth(S + 'A') else dX := TextWidth('A'); X := Left + dX; Y := Top + dY; TextOut(X,Y,S); end; end; procedure TPercentBar.PaintHeaders(Image: TBitmap); begin with Image.Canvas do begin Brush.Color := Color; Pen.Width := 1; FillRect(Rect(0, 0, LimitsWidth, ClientHeight)); FillRect(Rect(StartSecondHeader, 0, ClientWidth, ClientHeight)); end; end; procedure TPercentBar.PaintBorder(Image: TBitMap); begin with Image.Canvas do begin Pen.Color := clBtnHighlight; MoveTo(0,ClientHeight-1); LineTo(0,0); LineTo(ClientWidth-1,0); Pen.Color := clBtnShadow; LineTo(ClientWidth-1,ClientHeight-1); LineTo(0,ClientHeight-1); end; end; procedure TPercentBar.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if ((X > StartBackBar) and LeftVBoxOpen) or ((X < EndBackBar) and RightVBoxOpen) then begin RightVBoxOpen := false; LeftVBoxOpen := false; Acknowlege := true; end else if Button = mbLeft then if (X > EndForeBar - SensitiveRadius) and (X <= EndForeBar + SensitiveRadius) then MovingBar:= True else if tbAllowTimer in FTimeState then begin if FRepeatTimer = nil then FRepeatTimer := TTimer.Create(Self); FRepeatTimer.OnTimer := TimerExpired; FRepeatTimer.Interval := InitRepeatPause; FRepeatTimer.Enabled := True; end; inherited; end; procedure TPercentBar.MouseMove(Shift: TShiftState; X, Y: Integer); begin MouseX := X; if MovingBar then if (X > - AvailableArea) and (X < Width + AvailableArea) and (Y > - AvailableArea) and (Y < Height + AvailableArea) then begin EndForeBar := X; Progress := GetProgress(X); end else begin EndForeBar := LastCoord; Progress := GetProgress(EndForeBar); end else begin if (X > EndForeBar - Sensitiveradius) and (X <= EndForeBar + SensitiveRadius) and not (LeftVBoxOpen or RightVBoxOpen) then Cursor := crSizeWE else Cursor := crDefault; end; inherited; end; procedure TPercentBar.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin if (X > -AvailableArea) and (X < Width + AvailableArea) and (Y > 0) and (Y < Height) then LastCoord := EndForeBar else begin EndForeBar := LastCoord; Progress := GetProgress(EndForeBar); end; if MovingBar then begin MovingBar := false; Cursor := crDefault; end; if FRepeatTimer <> nil then FRepeatTimer.Enabled := False; inherited; end; procedure TPercentBar.SetBorderStyle(Value: TBorderStyle); begin if Value <> FBorderStyle then begin FBorderStyle := Value; Invalidate; end; end; procedure TPercentBar.SetForeColor(Value: TColor); begin if Value <> FForeColor then begin FForeColor := Value; Invalidate; end; end; procedure TPercentBar.SetBackColor(Value: TColor); begin if Value <> FBackColor then begin FBackColor := Value; Invalidate; end; end; procedure TPercentBar.SetMinValue(const Value: Longint); begin if (Value <> FMinValue) and (Value < FMaxValue) then begin if (Kind = kdCualitative) and (Value < 0) then FMinValue := 0 else FMinValue := Value; if FCurValue < FMinValue then FCurValue := FMinValue; FEndForeBar := GetEndForeBar; Invalidate; end; end; procedure TPercentBar.SetMaxValue(const Value: Longint); begin if (Value <> FMaxValue) and (Value > FMinValue) then begin if (Kind = kdCualitative) and (Value >= FValuesList.Count) then FMaxValue := pred(FValuesList.Count) else FMaxValue := Value; if FCurValue > FMaxValue then FCurValue := FMaxValue; FEndForeBar := GetEndForeBar; Invalidate; end; end; procedure TPercentBar.SetLastCoord(const Value: integer); begin if Value <> FLastCoord then begin FLastCoord := Value; Invalidate; end; end; procedure TPercentBar.SetProgress(const Value: Longint); var ActValue: Longint; begin if Value > FMaxValue then ActValue := FMaxValue else if Value < MinValue then ActValue := FMinValue else ActValue := Value; if FCurValue <> ActValue then begin FCurValue := ActValue; if (csDesigning in ComponentState) or (csLoading in ComponentState) or not MovingBar then EndForeBar := GetEndForebar; end; Invalidate; end; procedure TPercentBar.SetLimitsHorJustify(Value: THorJustify); begin if Value <> FLimitsHorJustify then begin FLimitsHorJustify := Value; Invalidate; end; end; procedure TPercentBar.SetLimitsVerJustify(Value: TVerJustify); begin if Value <> FLimitsVerJustify then begin FLimitsVerJustify := Value; Invalidate; end; end; procedure TPercentBar.SetLimitsFont(Value: TFont); begin if Value <> FLimitsFont then begin FLimitsFont.Assign(Value); Invalidate; end; end; procedure TPercentBar.SetProgressJustify(Value: TVerJustify); begin if Value <> FProgressJustify then begin FProgressJustify := Value; Invalidate; end; end; procedure TPercentBar.SetShowMaxValue(Value: TTextFormat); begin if Value <> FShowMaxValue then begin FShowMaxValue := Value; Invalidate; end; end; procedure TPercentBar.SetShowMinValue(Value: TTextFormat); begin if Value <> FShowMinValue then begin FShowMinValue := Value; Invalidate; end; end; procedure TPercentBar.SetShowProgress(Value: TTextFormat); begin if Value <> FShowProgress then begin FShowProgress := Value; Invalidate; end; end; procedure TPercentBar.SetLimitsWidth(const Value: integer); begin if Value <> FLimitsWidth then begin FLimitsWidth := Value; EndForeBar := GetEndForeBar; Invalidate; end; end; procedure TPercentBar.SetProgressFont(Value: TFont); begin if Value <> FProgressFont then begin FProgressFont := Value; Invalidate; end; end; procedure TPercentBar.AddProgress(const Value: Longint); begin Progress := FCurValue + Value; EndForeBar := GetEndForeBar; if ((Value > 0) and (EndForeBar > MouseX)) or ((Value < 0) and (EndForeBar < MouseX)) then begin EndForeBar := MouseX; Progress := GetProgress(EndForeBar); end; Invalidate; end; function TPercentBar.GetStartBackBar: integer; begin Result := LimitsWidth; end; function TPercentBar.GetEndBackBar: integer; begin Result := Width - LimitsWidth - 1; end; function TPercentBar.GetStartForeBar: integer; begin Result := LimitsWidth + 1; end; function TPercentBar.GetEndForeBar: integer; begin Result := SolveForX(PercentDone, pred(MaxBarWidth)); if Result > pred(MaxBarWidth) then Result := pred(MaxBarWidth); Result := Result + StartForeBar; end; function TPercentBar.GetStartSecondHeader: integer; begin Result := Width - LimitsWidth; end; function TPercentBar.GetMaxBarWidth: integer; begin Result := BackBarWidth - 2; end; function TPercentBar.GetBackBarWidth: integer; begin Result := Width - 2*LimitsWidth; end; function TPercentBar.GetBarWidth: integer; begin Result := EndForeBar - StartBackBar; if Result < 0 then Result := 0; end; procedure TPercentBar.RefreshFont(Sender: TObject); begin Invalidate; end; function TPercentBar.GetText(const Number: Longint; const TheFormat: TTextFormat): string; begin if Kind = kdCualitative then Result := FValuesList.Strings[Number] else if TheFormat = tfNumber then Result := Format(' %d ', [Number]) else Result := Format(' %d%% ', [Number]); end; function TPercentBar.GetValuesList: TStrings; begin Result := FValuesList; end; procedure TPercentBar.SetValuesList(Value: TStrings); begin if Value.Count >= 2 then FValuesList.Assign(Value); // Sino Error: No puede haber menos de dos // posibles valores extremos Invalidate; end; procedure TPercentBar.SetRightVBoxOpen(const Value: boolean); begin if Value <> FRightVBoxOpen then begin FRightVBoxOpen := Value; if FRightVBoxOpen then begin LeftVBoxOpen := false; RightLimitFormat := ShowMaxValue; ShowMaxValue := tfNone; RunListBox(StartSecondHeader, FMaxValue); end else begin ShowMaxValue := RightLimitFormat; if ValuesBox is TComboBox then (ValuesBox as TComboBox).Visible := false else (ValuesBox as TListBox).Visible := false; end; end; end; procedure TPercentBar.SetLeftVBoxOpen(const Value: boolean); begin if Value <> FLeftVBoxOpen then begin FLeftVBoxOpen := Value; if FLeftVBoxOpen then begin RightVBoxOpen := false; LeftLimitFormat := ShowMinValue; ShowMinValue := tfNone; RunListBox(1, FMinValue); end else begin ShowMinValue := LeftLimitFormat; if ValuesBox is TComboBox then (ValuesBox as TComboBox).Visible := false else (ValuesBox as TListBox).Visible := false; end; end; end; procedure TPercentBar.SetEndForeBar(const Value: integer); begin if Value < StartForeBar then FEndForeBar := StartForeBar else if Value >= StartForeBar + MaxBarWidth then FEndForeBar := StartForeBar + MaxBarWidth - 1 else FEndForeBar := Value; end; procedure TPercentBar.SetTypeLimits(const Value: boolean); begin if Value <> FTypeLimits then begin ValuesBox.Free; FTypeLimits := Value; if FTypeLimits then BoxClass := TComboBox else BoxClass := TListBox; ValuesBox := BoxClass.Create(Self); end; end; procedure TPercentBar.SetKind(Value: TKind); begin if Value <> FKind then begin if Value = kdCualitative then begin MinValue := 0; MaxValue := FValuesList.Count - 1; Increment := 1; TypeLimits := false; end else begin Increment := 2; TypeLimits := true; end; FKind := Value; Invalidate; end; end; procedure TPercentBar.UpDateVBox(const Val: Longint; const UpDate: boolean); begin if LeftVBoxOpen then begin if UpDate then MinValue := val; LeftVBoxOpen := false; end else begin if UpDate then MaxValue := val; RightVBoxOpen := false; end; end; procedure TPercentBar.KeyPressVBox(Sender: TObject; var Key: Char); var value: Longint; code: integer; begin if Key = #13 then begin val((ValuesBox as TComboBox).Text, value, code); if ((ValuesBox as TComboBox).Text <> '') and (code = 0) then UpDateVBox(value, true) else UpDateVBox(0,false); end; end; procedure TPercentBar.ClickVBoxValue(Sender: TObject); var value: Longint; code: integer; begin if Kind = kdCualitative then UpDateVBox((ValuesBox as TListBox).ItemIndex, true) else if ValuesBox is TComboBox then with ValuesBox as TComboBox do begin if ItemIndex <> - 1 then begin value := StrToInt(Items[ItemIndex]); UpDateVBox(value, true); end else begin val(Items[ItemIndex], value, code); if code = 0 then UpDateVBox(value, true) else UpDateVBox(0, false); end; visible := false; end else with ValuesBox as TListBox do begin if ItemIndex <> - 1 then begin value := StrToInt(Items[ItemIndex]); UpDateVBox(value, true); end else begin val(Items[ItemIndex], value, code); if code = 0 then UpDateVBox(value, true) else UpDateVBox(0, false); end; visible := false; end; end; procedure TPercentBar.RunListBox(const X: integer; const Value: Longint); begin if ValuesBox.Parent = nil then // Creation and initialization of ValuesBox begin if ValuesBox is TComboBox then with (ValuesBox as TComboBox) do begin Parent := Self.Parent; Visible := false; OnClick := ClickVBoxValue; OnExit := Exit; OnKeyPress := KeyPressVBox; Font := LimitsFont; end else with (ValuesBox as TListBox) do begin Parent := Self.Parent; Visible := false; Font := LimitsFont; OnClick := ClickVBoxValue; OnExit := Exit; end; with ValuesBox do begin Width := LimitsWidth; Height := 50; end; end; if ValuesBox is TComboBox then with ValuesBox as TComboBox do begin Text := IntToStr(Value); Items.Assign(ValuesList); end else (ValuesBox as TListBox).Items.Assign(ValuesList); with ValuesBox do begin Left := Self.Left + X + LimitsWidth div 4; Top := Self.Top + Self.Height div 3; end; if ValuesBox is TComboBox then (ValuesBox as TComboBox).Visible := true else (ValuesBox as TListBox).Visible := true; ValuesBox.SetFocus; end; procedure TPercentBar.Exit(Sender: TObject); begin if RightVBoxOpen then RightVBoxOpen := false; if LeftVBoxOpen then LeftVBoxOpen := false; end; procedure TPercentBar.DblClick; begin if LimitsChangeable then if (MouseX >= StartSecondHeader) and not RightVBoxOpen //and not MovingBar then RightVBoxOpen := true else if (MouseX < StartBackBar) and not LeftVBoxOpen //and not MovingBar then LeftVBoxOpen := true; inherited; end; procedure TPercentBar.Click; begin if Acknowlege then Acknowlege := false else if EndForeBar + 1 < MouseX then AddProgress(Increment) else if EndForeBar - 1 > MouseX then AddProgress(- Increment); inherited; end; procedure TPercentBar.TimerExpired(Sender: TObject); begin FRepeatTimer.Interval := RepeatPause; if MouseCapture then begin try Click; except FRepeatTimer.Enabled := False; raise; end; end; end; procedure Register; begin RegisterComponents('Merchise', [TPercentBar]); end; end.