text stringlengths 14 6.51M |
|---|
unit uTCad_Produto;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, uTBaseDados, db, uT_Constante, utcad_cor, bpf_geral, utcad_marca, utcad_tamanho, uTCad_Unidade;
type
{ TCad_Produto }
TView_Produto = class(TBaseView)
private
FMarca : TCad_Marca;
FTamanho : TCad_Tamanho;
FCor : TCad_Cor;
FUnidade : TCad_Unidade;
public
FK_MARCA : Integer;
FK_TAMANHO : Integer;
FK_UNIDADE : Integer;
FK_COR : INTEGER;
REFERENCIA : String;
DESCRICAO : String;
CODIGO_BARRAS : String;
OBSERVACAO : String;
CUSTO : Extended;
DATA_CADASTRO : TDateTime;
property Marca : TCad_Marca read FMarca write FMarca;
property Tamanho : TCad_Tamanho read FTamanho write FTamanho;
property Cor : TCad_Cor read FCor write FCor;
property Unidade : TCad_Unidade read FUnidade write FUnidade;
end;
TCad_Produto = class(TBaseBusiness)
private
FView: TView_Produto;
procedure GetSQLInsert;
procedure GetSQLUpdate;
procedure Carregar;
public
procedure Inserir ; override;
procedure Editar ; override;
procedure Excluir ; override;
procedure Gravar ; override;
procedure SendToDb; override;
procedure Cancelar; override;
procedure LoadFromDb(pID : Integer); override;
procedure LimparEntidade; override;
property View : TView_Produto read FView write FView;
constructor Create;
destructor Destroy;
end;
implementation
{ TCad_Produto }
procedure TCad_Produto.GetSQLInsert;
begin
with FView do
begin
FView.SQL_Insert:= 'INSERT INTO PRODUTO (ID, FK_MARCA, FK_TAMANHO, FK_UNIDADE, FK_COR, REFERENCIA, DESCRICAO, CODIGO_BARRAS, OBSERVACAO, CUSTO, DATA_CADASTRO)'
+#13+' VALUES ('
+#13+'' + IntToStr(ID) +','
+#13+'' + IntToStr(FK_MARCA) +','
+#13+'' + IntToStr(FK_TAMANHO) +','
+#13+'' + IntToStr(FK_UNIDADE) +','
+#13+'' + IntToStr(FK_COR) +','
+#13+'' + QuotedStr(REFERENCIA) +','
+#13+'' + QuotedStr(DESCRICAO) +','
+#13+'' + QuotedStr(CODIGO_BARRAS) +','
+#13+'' + QuotedStr(OBSERVACAO) +','
+#13+'' + TPF_String.GetFloat(FloatToStr(CUSTO)) +','
+#13+'' + QuotedStr(FormatDateTime('mm/dd/yyyy',DATA_CADASTRO))
+#13+');'
end;
end;
procedure TCad_Produto.GetSQLUpdate;
begin
with FView do
begin
SQL_Update:= 'UPDATE PRODUTO SET '
+#13+'FK_MARCA = ' + IntToStr(FK_MARCA) +','
+#13+'FK_TAMANHO = ' + IntToStr(FK_TAMANHO) +','
+#13+'FK_UNIDADE = ' + IntToStr(FK_UNIDADE) +','
+#13+'FK_COR = ' + IntToStr(FK_COR) +','
+#13+'REFERENCIA = ' + QuotedStr(REFERENCIA) +','
+#13+'DESCRICAO = ' + QuotedStr(DESCRICAO) +','
+#13+'CODIGO_BARRAS = ' + QuotedStr(CODIGO_BARRAS) +','
+#13+'OBSERVACAO = ' + QuotedStr(OBSERVACAO) +','
+#13+'CUSTO = ' + TPF_String.GetFloat(FloatToStr(CUSTO)) + ','
+#13+' WHERE ID = ' + IntToStr(FView.ID);
end;
end;
procedure TCad_Produto.Carregar;
begin
with FView do
begin
Marca .LoadFromDb(FK_MARCA);
Tamanho .LoadFromDb(FK_TAMANHO);
Cor .LoadFromDb(FK_COR);
Unidade .LoadFromDb(FK_UNIDADE);
end;
;
end;
procedure TCad_Produto.Inserir;
begin
LimparEntidade;
FView.State:= TObSt_Inserting;
FView.ID:= TBaseDados.GetNextID(FView.Generator);
FView.DATA_CADASTRO:= Now;
end;
procedure TCad_Produto.Editar;
begin
inherited Editar;
FView.State:= TObSt_Editing;
end;
procedure TCad_Produto.Excluir;
begin
FView.SQL_Delete:='DELETE FROM PRODUTO WHERE ID = ' + IntToStr(FView.ID);
TBaseDados.ExecQuery(FView.SQL_Delete);
LimparEntidade;
end;
procedure TCad_Produto.Gravar;
begin
case FView.State of
TObSt_Inserting : GetSQLInsert;
TObSt_Editing : GetSQLUpdate;
end;
end;
procedure TCad_Produto.SendToDb;
begin
try
case FView.State of
TObSt_Inserting : TBaseDados.ExecQuery(FView.SQL_Insert);
TObSt_Editing : TBaseDados.ExecQuery(FView.SQL_Update);
end;
finally
FView.State:= TObSt_Browse;
end;
end;
procedure TCad_Produto.Cancelar;
begin
FView.State:= TObSt_Browse;
LimparEntidade;
end;
procedure TCad_Produto.LoadFromDb(pID: Integer);
begin
Query := TBaseDados.GetNewAbsQuery;
Query.SQL.Clear;
Query.SQL.Text:= 'SELECT * FROM PRODUTO WHERE ID = '+ IntToStr(pID);
Query.Open;
with Query, FView do
begin
ID := FieldByName('id').AsInteger;
FK_MARCA := FieldByName('FK_MARCA').AsInteger;
FK_TAMANHO := FieldByName('FK_TAMANHO').AsInteger;
FK_UNIDADE := FieldByName('FK_UNIDADE').AsInteger;
FK_COR := FieldByName('FK_COR').AsInteger;
REFERENCIA := FieldByName('REFERENCIA').AsString;
DESCRICAO := FieldByName('DESCRICAO').AsString;
CODIGO_BARRAS := FieldByName('CODIGO_BARRAS').AsString;
OBSERVACAO := FieldByName('OBSERVACAO').AsString;
CUSTO := FieldByName('CUSTO').AsFloat;
DATA_CADASTRO := FieldByName('DATA_CADASTRO').AsDateTime;
end;
Carregar;
end;
procedure TCad_Produto.LimparEntidade;
begin
with FView do
begin
ID := 0;
FK_MARCA := 0;
FK_TAMANHO := 0;
FK_UNIDADE := 0;
FK_COR := 0;
REFERENCIA := '';
DESCRICAO := '';
CODIGO_BARRAS := '';
OBSERVACAO := '';
CUSTO := 0;
end;
end;
constructor TCad_Produto.Create;
begin
FView := TView_Produto.Create(nil);
FView.FMarca := TCad_Marca.Create;
FView.FTamanho := TCad_Tamanho.Create;
FView.FCor := TCad_Cor.Create;
FView.FUnidade := TCad_Unidade.Create;
FView.Generator:= 'GEN_PRODUTO_ID';
end;
destructor TCad_Produto.Destroy;
begin
FreeAndnIl(FView);
end;
end.
|
unit MonitorUnit;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.OleServer, AlienRFID2_TLB,
Vcl.StdCtrls, Vcl.Buttons, Vcl.Grids, ActiveX, Vcl.ExtCtrls, StrUtils,
Vcl.Samples.Spin;
type
TMonitorForm = class(TForm)
mReader: TclsReader;
GetTagsButton: TBitBtn;
OptionsGroupBox: TGroupBox;
GroupBox1: TGroupBox;
StringGrid1: TStringGrid;
NotifyMemo: TMemo;
NotifyServer: TCAlienServer;
AlienUtils1: TAlienUtils;
StartMonitorButton: TBitBtn;
MaskCheckBox: TCheckBox;
GroupBox2: TGroupBox;
StringMaskEdit: TEdit;
SetMaskButton: TBitBtn;
Label1: TLabel;
Label2: TLabel;
HexMaskEdit: TEdit;
OffsetMaskSpinEdit: TSpinEdit;
Label3: TLabel;
Panel1: TPanel;
Splitter1: TSplitter;
ProgramTagButton: TBitBtn;
LabelProgram: TLabel;
GroupBox3: TGroupBox;
procedure GetTagsButtonClick(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure StartMonitorButtonClick(Sender: TObject);
procedure NotifyServerServerMessageReceived(ASender: TObject;
const msg: WideString);
procedure NotifyServerServerConnectionEstablished(ASender: TObject;
const guid: WideString);
procedure NotifyServerServerConnectionEnded(ASender: TObject;
const guid: WideString);
procedure NotifyServerServerListeningStarted(Sender: TObject);
procedure NotifyServerServerListeningStopped(Sender: TObject);
procedure NotifyServerServerSocketError(ASender: TObject;
const msg: WideString);
procedure MaskCheckBoxClick(Sender: TObject);
procedure SetMaskButtonClick(Sender: TObject);
procedure HexMaskEditKeyPress(Sender: TObject; var Key: Char);
procedure HexMaskEditChange(Sender: TObject);
procedure StringMaskEditChange(Sender: TObject);
procedure FormResize(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ProgramTagButtonClick(Sender: TObject);
private
{ Private declarations }
tfs:TFormatSettings;
FMonitoring:boolean;
FTagsCount:integer;
procedure WriteLog(OutString: string;Memo1:TMemo=nil);
procedure setMonitoring(const Value: boolean);
procedure setTagsCount(const Value: integer);
property Monitoring:boolean read FMonitoring write setMonitoring;
property TagsCount:integer read FTagsCount write setTagsCount;
public
{ Public declarations }
end;
var
MonitorForm: TMonitorForm;
implementation
{$R *.dfm}
uses ProgrammUnit,CommonUnit;
procedure TMonitorForm.NotifyServerServerConnectionEnded(ASender: TObject;
const guid: WideString);
begin
if ASender=NotifyServer then
begin
GetTagsButtonClick(self);
WriteLOg('End with '+guid,NotifyMemo);
end;
end;
procedure TMonitorForm.NotifyServerServerConnectionEstablished(
ASender: TObject; const guid: WideString);
begin
if ASender=NotifyServer then
WriteLOg('Est with '+guid,NotifyMemo);
end;
procedure TMonitorForm.NotifyServerServerListeningStarted(Sender: TObject);
begin
if Sender=NotifyServer then
WriteLOg('Listening started',NotifyMemo);
end;
procedure TMonitorForm.NotifyServerServerListeningStopped(Sender: TObject);
begin
if Sender=NotifyServer then
WriteLOg('Listening stopped', NotifyMemo);
end;
procedure TMonitorForm.NotifyServerServerMessageReceived(ASender: TObject;
const msg: WideString);
var SafeArray: PSafeArray;
TagInfo:ITagInfo;
TagInfoArray:array of ITagInfo;
iLow,iHigh,i,p:integer;
inString:String;
selTag:String;
selRow:Integer;
begin
// WriteLog('Notify message Received '+msg,NotifyMemo);
inString:=msg;
p:=pos('<',InString);
inString:=trim(copy(InString,p,Length(inString)));
if (inString<>'') and (pos('No Tags',inString)=0) then
begin
mReader.ParseXMLTagList(inString,SafeArray,false);
// mReader.ParseTagList(inString,SafeArray);
if SafeArray<>nil then
begin
SafeArrayGetLBound(SafeArray,1,iLow);
SafeArrayGetUBound(SafeArray,1,iHigh);
tagsCount:=iHigh-iLow+1;
if tagsCount>0 then
begin
SetLength(TagInfoArray,tagsCount);
SelTag:=StringGrid1.cells[0,StringGrid1.Row];
SelRow:=0;
for i:=iLow to iHigh do
begin
SafeArrayGetElement(SafeArray,i,TagInfo);
TagInfoArray[i]:=TagInfo;
StringGrid1.cells[0,i+1]:=TagInfo.TagID;
StringGrid1.cells[1,i+1]:=HexToString(TagInfo.TagID);
StringGrid1.cells[2,i+1]:=TagInfo.DiscoveryTime;
StringGrid1.cells[3,i+1]:=TagInfo.LastSeenTime;
StringGrid1.cells[4,i+1]:=IntToStr(TagInfo.Antenna);
StringGrid1.cells[5,i+1]:=IntToStr(TagInfo.ReadCount);
if TagInfo.TagID=selTag then
SelRow:=i+1;
end;
if SelRow>1 then
StringGrid1.Row:=SelRow;
end
end
else
tagsCount:=0;
end
else
tagsCount:=0;
// WriteLog('Found '+IntToStr(TagsCount)+' tag(s)',NotifyMemo);
StringGrid1.Options:=StringGrid1.Options + [goColSizing] -[goFixedRowClick];
MyGridSize(StringGrid1);
application.ProcessMessages;
end;
procedure TMonitorForm.NotifyServerServerSocketError(ASender: TObject;
const msg: WideString);
begin
WriteLOg('Socket error '+msg);
end;
procedure TMonitorForm.ProgramTagButtonClick(Sender: TObject);
var TagId:String;
lastMonitoring:boolean;
begin
TagId:='';
if StringGrid1.Row>0 then
begin
TagId:=StringGrid1.Cells[0, StringGrid1.Row];
end;
if TagId='' then
begin
showMessage('Please select TAG to programm it');
exit;
end;
if ProgrammForm=nil then
begin
try
ProgrammForm:=TProgrammForm.create(Application);
finally
end;
end;
if ProgrammForm<>nil then
begin
try
lastMonitoring:=Monitoring;
Monitoring:=false;
SetReaderMask(TagId,0,mReader);
ProgrammForm.mReader:=mReader;
ProgrammForm.showmodal;
finally
Monitoring:=lastMonitoring;
SetReaderMask('',0,mReader);
ProgrammForm.free;
ProgrammForm:=nil;
end;
end;
end;
procedure TMonitorForm.SetMaskButtonClick(Sender: TObject);
var Offset:integer;
i,l:integer;
mask,resultMask:string;
begin
Mask:= trim(HexMaskEdit.text);
Offset:=OffsetMaskSpinEdit.Value;
if MaskCheckBox.checked then
SetReaderMask(Mask,OffSet,mReader);
end;
procedure TMonitorForm.FormActivate(Sender: TObject);
begin
Monitoring:=false;
tfs:=tformatSettings.create(LOCALE_SYSTEM_DEFAULT);
StringGrid1.cells[0,0]:='Tag ID';
StringGrid1.cells[1,0]:='String Tag ID';
StringGrid1.cells[2,0]:='Discovery Time';
StringGrid1.cells[3,0]:='Last Seen Time';
StringGrid1.cells[4,0]:='Antenna';
StringGrid1.cells[5,0]:='Read Count';
if mreader.IsConnected then
GetTagsButtonClick(self)
else
TagsCount:=0;
MyGridSize(StringGrid1);
end;
procedure TMonitorForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Monitoring:=false;
end;
procedure TMonitorForm.FormResize(Sender: TObject);
begin
MyGridSize(StringGrid1);
end;
procedure TMonitorForm.GetTagsButtonClick(Sender: TObject);
var inString:string;
result:boolean;
sTagList:TStringList;
i:integer;
SafeArray: PSafeArray;
TagInfo:ITagInfo;
TagInfoArray:array of ITagInfo;
iLow, iHigh : Integer;
selTag:String;
selRow:Integer;
s:String;
begin
WriteLog('Try to Read Tags...');
application.ProcessMessages;
if not mReader.IsConnected then
begin
WriteLog('Reader not connected. Exit');
exit;
end;
mReader.TagListFormat:='Text';
mReader.TagListFormat:='XML';
inString:=mReader.TagList;
if (inString<>'') and (pos('No Tags',inString)=0) then
begin
mReader.ParseXMLTagList(inString,SafeArray,false);
if SafeArray<>nil then
begin
SafeArrayGetLBound(SafeArray,1,iLow);
SafeArrayGetUBound(SafeArray,1,iHigh);
tagsCount:=iHigh-iLow+1;
if tagsCount>0 then
begin
SetLength(TagInfoArray,tagsCount);
SelTag:=StringGrid1.cells[0,StringGrid1.Row];
SelRow:=0;
for i:=iLow to iHigh do
begin
SafeArrayGetElement(SafeArray,i,TagInfo);
TagInfoArray[i]:=TagInfo;
StringGrid1.cells[0,i+1]:=TagInfo.TagID;
StringGrid1.cells[1,i+1]:=HexToString(TagInfo.TagID);
StringGrid1.cells[2,i+1]:=TagInfo.DiscoveryTime;
StringGrid1.cells[3,i+1]:=TagInfo.LastSeenTime;
StringGrid1.cells[4,i+1]:=IntToStr(TagInfo.Antenna);
StringGrid1.cells[5,i+1]:=IntToStr(TagInfo.ReadCount);
if TagInfo.TagID=selTag then
SelRow:=i+1;
end;
if SelRow>1 then
StringGrid1.Row:=SelRow;
end;
end
else
tagsCount:=0;
end
else
tagsCount:=0;
// WriteLog('Found '+IntToStr(TagsCount)+' tag(s)');
StringGrid1.Options:=StringGrid1.Options + [goColSizing] -[goFixedRowClick];
MyGridSize(StringGrid1);
application.ProcessMessages;
end;
procedure TMonitorForm.MaskCheckBoxClick(Sender: TObject);
begin
if Not(TCheckBox(Sender).Checked) then
if mReader.IsConnected then
mReader.Mask:='00';
end;
procedure TMonitorForm.setMonitoring(const Value: boolean);
begin
if Value then
begin
NotifyServer.port:=4000;
if not(mReader.IsConnected) then
mReader.connect;
if mReader.IsConnected then
begin
mReader.NotifyAddress:=NotifyServer.notificationHost;
mReader.AutoMode:= 'On';
mReader.NotifyMode:= 'On';
mReader.NotifyTime:= '0';
mReader.NotifyTrigger:= 'Change';
mReader.NotifyFormat:= 'Text';
mReader.NotifyFormat:= 'XML';
mReader.NotifyHeader:= 'OFF';
mReader.AcquireMode:= 'Inventory';
mReader.TagListMillis:= 'On';
mReader.TagStreamMode:= 'OFF';
mReader.TagStreamFormat:= 'Terse';
mReader.TagStreamFormat:= 'XML';
mReader.TagStreamFormat:= 'Text';
mReader.IOStreamMode:= 'OFF';
mReader.IOStreamFormat:= 'Terse';
end;
NotifyServer.StartListening;
GetTagsButtonClick(self);
end
else
begin
mReader.AutoMode:= 'OFF';
mReader.NotifyMode:= 'OFF';
NotifyServer.StopListening;
if not(mReader.IsConnected) then
mReader.connect;
end;
FMonitoring := NotifyServer.IsListening;
if FMonitoring then
begin
WriteLog('Monitoring started');
StartMonitorButton.Caption:='Stop Monitoring';
end
else
begin
WriteLog('Monitoring stopped');
StartMonitorButton.Caption:='Start Monitoring';
end;
end;
procedure TMonitorForm.setTagsCount(const Value: integer);
begin
if Value=0 then
begin
StringGrid1.RowCount:=2;
StringGrid1.cells[0,1]:='';
StringGrid1.cells[1,1]:='';
StringGrid1.cells[2,1]:='';
StringGrid1.cells[3,1]:='';
StringGrid1.cells[4,1]:='';
StringGrid1.cells[5,1]:='';
end
else
StringGrid1.RowCount:=Value+1;
MyGridSize(StringGrid1);
LabelProgram.Visible:=false;
ProgramTagButton.Enabled:=false;
if (mReader.IsConnected) then
if (Value>0) and (StringGrid1.cells[0,StringGrid1.Row]<>'') then
begin
LabelProgram.Visible:=false;
ProgramTagButton.Enabled:=true;
end
else
begin
LabelProgram.Visible:=true;
ProgramTagButton.Enabled:=false;
end;
Application.ProcessMessages;
FTagsCount := Value;
end;
procedure TMonitorForm.StartMonitorButtonClick(Sender: TObject);
begin
WriteLog('Try to '+TBitBtn(Sender).caption+'...');
Monitoring:=not(Monitoring);
end;
procedure TMonitorForm.WriteLog(OutString:string;Memo1:TMemo=nil);
var i:integer;
begin
if Memo1=nil then Memo1:=self.NotifyMemo;
{ if Memo1.Lines.count>=1024 then
for i:=0 to 127 do
try
memo1.Lines.Delete(0);
finally
end;}
Memo1.Lines.add(DateTimeToStr(now(),tfs)+'->'+OutString);
end;
procedure TMonitorForm.StringMaskEditChange(Sender: TObject);
begin
if ActiveControl=StringMaskEdit then
HexMaskEdit.Text:=StringToHex(StringMaskEdit.text);
end;
procedure TMonitorForm.HexMaskEditChange(Sender: TObject);
begin
if ActiveControl=HexMaskEdit then
StringMaskEdit.Text:=HexToString(HexMaskEdit.text);
end;
procedure TMonitorForm.HexMaskEditKeyPress(Sender: TObject; var Key: Char);
begin
Key:=ValidHexKey(Key);
end;
end.
|
unit Aurelius.Schema.DB2;
{$I Aurelius.Inc}
interface
uses
Aurelius.Drivers.Interfaces,
Aurelius.Schema.AbstractImporter,
Aurelius.Sql.Metadata;
type
TDB2SchemaImporter = class(TAbstractSchemaImporter)
strict protected
procedure GetDatabaseMetadata(Connection: IDBConnection; Database: TDatabaseMetadata); override;
end;
TDB2SchemaRetriever = class(TSchemaRetriever)
strict private
procedure GetTables;
procedure GetColumns;
procedure GetPrimaryKeys;
procedure GetUniqueKeys;
procedure GetForeignKeys;
procedure GetSequences;
procedure GetFieldDefinition(Column: TColumnMetadata; ADataType: string; ASize, AScale: integer);
public
constructor Create(AConnection: IDBConnection; ADatabase: TDatabaseMetadata); override;
procedure RetrieveDatabase; override;
end;
implementation
uses
SysUtils,
Aurelius.Schema.Register;
{ TDB2SchemaImporter }
procedure TDB2SchemaImporter.GetDatabaseMetadata(Connection: IDBConnection;
Database: TDatabaseMetadata);
var
Retriever: TSchemaRetriever;
begin
Retriever := TDB2SchemaRetriever.Create(Connection, Database);
try
Retriever.RetrieveDatabase;
finally
Retriever.Free;
end;
end;
{ TDB2SchemaRetriever }
constructor TDB2SchemaRetriever.Create(AConnection: IDBConnection;
ADatabase: TDatabaseMetadata);
begin
inherited Create(AConnection, ADatabase);
end;
procedure TDB2SchemaRetriever.GetColumns;
begin
RetrieveColumns(
'SELECT TABNAME AS TABLE_NAME, COLNAME AS COLUMN_NAME, '+
'TYPENAME AS DATA_TYPE, LENGTH AS FIELD_SIZE, SCALE AS NUMERIC_SCALE, IDENTITY, '+
'NULLS AS NULLABLE '+
'FROM SYSCAT.COLUMNS '+
'ORDER BY TABNAME, COLNO',
procedure (Column: TColumnMetadata; ResultSet: IDBResultSet)
begin
Column.NotNull := (AsString(ResultSet.GetFieldValue('NULLABLE')) = 'N');
GetFieldDefinition(Column,
AsString(ResultSet.GetFieldValue('DATA_TYPE')),
AsInteger(ResultSet.GetFieldValue('FIELD_SIZE')),
AsInteger(ResultSet.GetFieldValue('NUMERIC_SCALE'))
);
Column.AutoGenerated := (AsString(ResultSet.GetFieldValue('IDENTITY')) = 'Y');
end
);
end;
procedure TDB2SchemaRetriever.GetFieldDefinition(Column: TColumnMetadata;
ADataType: string; ASize, AScale: integer);
const
vSizeTypes: array[0..3] of string =
('character', 'varchar', 'vargraphic', 'graphic');
vPrecisionTypes: array[0..1] of string =
('decimal', 'numeric');
function FindType(ATypes: array of string): boolean;
var
I: integer;
begin
for I := Low(ATypes) to high(ATypes) do
if SameText(ADataType, ATypes[I]) then
Exit(true);
Result := False;
end;
begin
Column.DataType := ADataType;
if FindType(vSizeTypes) then
Column.Length := ASize
else
if FindType(vPrecisionTypes) then
begin
Column.Precision := ASize;
Column.Scale := AScale;
end;
ADataType := Lowercase(ADataType);
if ADataType = 'character' then
Column.DataType := 'CHAR'
else
if ADataType = 'decimal' then
Column.DataType := 'NUMERIC'
else
if ADataType = 'double' then
Column.DataType := 'DOUBLE PRECISION';
end;
procedure TDB2SchemaRetriever.GetForeignKeys;
begin
RetrieveForeignKeys(
'SELECT TC.TABNAME AS FK_TABLE_NAME, TC.CONSTNAME AS CONSTRAINT_NAME, KC.COLNAME AS FK_COLUMN_NAME, '+
'TC.REFTABNAME AS PK_TABLE_NAME, KP.COLNAME AS PK_COLUMN_NAME '+
'FROM SYSCAT.REFERENCES TC, SYSCAT.KEYCOLUSE KC, SYSCAT.KEYCOLUSE KP '+
'WHERE TC.TABSCHEMA = KC.TABSCHEMA AND TC.TABNAME = KC.TABNAME AND TC.CONSTNAME = KC.CONSTNAME '+
'AND TC.REFTABSCHEMA = KP.TABSCHEMA AND TC.REFTABNAME = KP.TABNAME AND TC.REFKEYNAME = KP.CONSTNAME '+
'AND KC.COLSEQ = KP.COLSEQ '+
'ORDER BY TC.TABNAME, TC.CONSTNAME, KC.COLSEQ'
);
end;
procedure TDB2SchemaRetriever.GetPrimaryKeys;
begin
RetrievePrimaryKeys(
'SELECT TC.TABNAME AS TABLE_NAME, TC.CONSTNAME AS CONSTRAINT_NAME, KC.COLNAME AS COLUMN_NAME '+
'FROM SYSCAT.TABCONST TC, SYSCAT.KEYCOLUSE KC ' +
'WHERE TC.TABSCHEMA = KC.TABSCHEMA AND TC.TABNAME = KC.TABNAME AND TC.CONSTNAME = KC.CONSTNAME '+
'AND TC.TYPE=''P'' '+
'ORDER BY TC.TABNAME, TC.CONSTNAME, KC.COLSEQ'
);
end;
procedure TDB2SchemaRetriever.GetSequences;
begin
RetrieveSequences(
'SELECT SEQNAME AS SEQUENCE_NAME '+
'FROM SYSCAT.SEQUENCES '+
'WHERE OWNER = USER AND NOT SEQSCHEMA LIKE ''SYS%'' '+
'AND SEQTYPE = ''S'' '+
'ORDER BY SEQNAME'
);
end;
procedure TDB2SchemaRetriever.GetTables;
begin
RetrieveTables(
'SELECT TABNAME AS TABLE_NAME '+
'FROM SYSCAT.TABLES '+
'WHERE TYPE = ''T'' AND OWNER = USER '+
'AND NOT TABSCHEMA LIKE ''SYS%'' '+
'ORDER BY TABNAME'
);
end;
procedure TDB2SchemaRetriever.GetUniqueKeys;
begin
RetrieveUniqueKeys(
'SELECT TC.TABNAME AS TABLE_NAME, TC.CONSTNAME AS CONSTRAINT_NAME, KC.COLNAME AS COLUMN_NAME '+
'FROM SYSCAT.TABCONST TC, SYSCAT.KEYCOLUSE KC ' +
'WHERE TC.TABSCHEMA = KC.TABSCHEMA AND TC.TABNAME = KC.TABNAME AND TC.CONSTNAME = KC.CONSTNAME '+
'AND TC.TYPE=''U'' '+
'ORDER BY TC.TABNAME, TC.CONSTNAME, KC.COLSEQ'
);
end;
procedure TDB2SchemaRetriever.RetrieveDatabase;
begin
Database.Clear;
GetTables;
GetColumns;
GetPrimaryKeys;
GetUniqueKeys;
GetForeignKeys;
GetSequences;
end;
initialization
TSchemaImporterRegister.GetInstance.RegisterImporter('DB2', TDB2SchemaImporter.Create);
end.
|
unit FreeOTFEfrmOptions;
// Description:
// By Sarah Dean
// Email: sdean12@sdean12.org
// WWW: http://www.FreeOTFE.org/
//
// -----------------------------------------------------------------------------
//
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComCtrls,
CommonSettings, FreeOTFEfmeOptions_SystemTray, FreeOTFEfmeOptions_Hotkeys,
FreeOTFEfmeOptions_General,
FreeOTFEfmeOptions_AutoRun,
OTFEFreeOTFE_U, ExtCtrls, SDUForms, SDUStdCtrls, CommonfmeOptions_Base,
FreeOTFEfmeOptions_Base, CommonfrmOptions, CommonfmeOptions_PKCS11,
FreeOTFEfmeOptions_Advanced;
type
TfrmOptions_FreeOTFE = class(TfrmOptions)
tsGeneral: TTabSheet;
tsHotkeys: TTabSheet;
tcSystemTray: TTabSheet;
tsAutorun: TTabSheet;
tsAdvanced: TTabSheet;
fmeOptions_FreeOTFEGeneral1: TfmeOptions_FreeOTFEGeneral;
fmeOptions_Hotkeys1: TfmeOptions_Hotkeys;
fmeOptions_SystemTray1: TfmeOptions_SystemTray;
fmeOptions_FreeOTFEAdvanced1: TfmeOptions_FreeOTFEAdvanced;
fmeOptions_Autorun1: TfmeOptions_Autorun;
ckLaunchAtStartup: TSDUCheckBox;
ckLaunchMinimisedAtStartup: TSDUCheckBox;
procedure FormCreate(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure ckLaunchAtStartupClick(Sender: TObject);
protected
FOrigLaunchAtStartup: boolean;
FOrigLaunchMinimisedAtStartup: boolean;
procedure EnableDisableControls(); override;
procedure AllTabs_InitAndReadSettings(config: TSettings); override;
function DoOKClicked(): boolean; override;
public
function OTFEFreeOTFE(): TOTFEFreeOTFE;
procedure ChangeLanguage(langCode: string); override;
end;
implementation
{$R *.DFM}
uses
Math,
ShlObj, // Required for CSIDL_PROGRAMS
OTFEFreeOTFEBase_U,
FreeOTFESettings,
SDUi18n,
SDUGeneral,
SDUDialogs;
{$IFDEF _NEVER_DEFINED}
// This is just a dummy const to fool dxGetText when extracting message
// information
// This const is never used; it's #ifdef'd out - SDUCRLF in the code refers to
// picks up SDUGeneral.SDUCRLF
const
SDUCRLF = ''#13#10;
{$ENDIF}
procedure TfrmOptions_FreeOTFE.ChangeLanguage(langCode: string);
var
tmpConfig: TFreeOTFESettings;
begin
tmpConfig := TFreeOTFESettings.Create();
try
tmpConfig.Assign(Settings);
AllTabs_WriteSettings(tmpConfig);
SDUSetLanguage(langCode);
try
SDURetranslateComponent(self);
except
on E:Exception do
begin
SDUTranslateComponent(self);
end;
end;
AllTabs_InitAndReadSettings(tmpConfig);
finally
tmpConfig.Free();
end;
// Call EnableDisableControls() as this re-jigs the "Save above settings to:"
// label
EnableDisableControls();
end;
procedure TfrmOptions_FreeOTFE.ckLaunchAtStartupClick(Sender: TObject);
begin
inherited;
EnableDisableControls();
end;
procedure TfrmOptions_FreeOTFE.FormCreate(Sender: TObject);
begin
inherited;
// Set active page to the first one
pcOptions.ActivePage := tsGeneral;
end;
procedure TfrmOptions_FreeOTFE.FormShow(Sender: TObject);
begin
inherited;
FOrigLaunchAtStartup := SDUDoesShortcutExist(
SDU_CSIDL_STARTUP,
Application.Title
);
ckLaunchAtStartup.checked := FOrigLaunchAtStartup;
FOrigLaunchMinimisedAtStartup := FALSE;
if FOrigLaunchAtStartup then
begin
FOrigLaunchMinimisedAtStartup := (SDUGetShortCutRunWindowState(
SDU_CSIDL_STARTUP,
Application.Title
) = wsMinimized);
end;
ckLaunchMinimisedAtStartup.checked := FOrigLaunchMinimisedAtStartup;
// Push the "Advanced" tab to the far end; even after the "PKCS#11" tab
tsAdvanced.PageIndex := (pcOptions.PageCount - 1);
end;
function TfrmOptions_FreeOTFE.OTFEFreeOTFE(): TOTFEFreeOTFE;
begin
Result := TOTFEFreeOTFE(OTFEFreeOTFEBase);
end;
procedure TfrmOptions_FreeOTFE.EnableDisableControls();
begin
inherited;
SDUEnableControl(ckLaunchMinimisedAtStartup, ckLaunchAtStartup.checked);
if not(ckLaunchMinimisedAtStartup.Enabled) then
begin
ckLaunchMinimisedAtStartup.checked := FALSE;
end;
end;
procedure TfrmOptions_FreeOTFE.AllTabs_InitAndReadSettings(config: TSettings);
var
ckboxIndent: integer;
maxCBoxWidth: integer;
begin
inherited;
ckLaunchAtStartup.Caption := SDUParamSubstitute(
_('Start %1 at system startup'),
[Application.Title]
);
ckboxIndent := ckLaunchMinimisedAtStartup.left - ckLaunchAtStartup.left;
maxCBoxWidth := max(ckAssociateFiles.width, ckLaunchAtStartup.width);
ckAssociateFiles.Left := ((self.Width - maxCBoxWidth) div 2);
ckLaunchAtStartup.Left := ckAssociateFiles.Left;
ckLaunchMinimisedAtStartup.left := ckLaunchAtStartup.left + ckboxIndent;
EnableDisableControls();
end;
function TfrmOptions_FreeOTFE.DoOKClicked(): boolean;
var
allOK: boolean;
useRunWindowState: TWindowState;
begin
allOK := inherited DoOKClicked();
if allOK then
begin
if (
(ckLaunchAtStartup.checked <> FOrigLaunchAtStartup) or
(ckLaunchMinimisedAtStartup.checked <> FOrigLaunchMinimisedAtStartup)
) then
begin
// Purge any existing shortcut...
SDUDeleteShortcut(
SDU_CSIDL_STARTUP,
Application.Title
);
// ...and recreate if necessary
if ckLaunchAtStartup.checked then
begin
useRunWindowState := wsNormal;
if ckLaunchMinimisedAtStartup.checked then
begin
useRunWindowState := wsMinimized;
end;
SDUCreateShortcut(
SDU_CSIDL_STARTUP,
Application.Title,
ParamStr(0),
'',
'',
// ShortcutKey: TShortCut; - not yet implemented
useRunWindowState,
''
);
end;
FOrigAssociateFiles := ckAssociateFiles.checked;
end;
end;
Result := allOK;
end;
END.
|
unit SQLMonitorUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, MaximizedUnit, IBSQLMonitor, StdCtrls, ExtCtrls,
IB;
type
TSQLMonitor = class(TMaximizedForm)
Panel1: TPanel;
chbOnOff: TCheckBox;
chbStayOnTop: TCheckBox;
Button1: TButton;
memoText: TMemo;
Button2: TButton;
SaveDialog: TSaveDialog;
IBSQLMonitor: TIBSQLMonitor;
GroupBox1: TGroupBox;
chbFetch: TCheckBox;
chbPrepare: TCheckBox;
chbTransaction: TCheckBox;
procedure chbOnOffClick(Sender: TObject);
procedure chbStayOnTopClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure IBSQLMonitorSQL(EventText: String; EventTime: TDateTime);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure chbFetchClick(Sender: TObject);
procedure chbPrepareClick(Sender: TObject);
procedure chbTransactionClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
class procedure Open;
end;
var
SQLMonitor: TSQLMonitor;
implementation
uses Dm_u;
{$R *.dfm}
procedure TSQLMonitor.chbOnOffClick(Sender: TObject);
begin
inherited;
IBSQLMonitor.Enabled := chbOnOff.Checked;
if chbOnOff.Checked then begin
DM.DB.TraceFlags:=[tfQExecute];
if chbFetch.checked then DM.DB.TraceFlags:=DM.DB.TraceFlags + [tfQFetch];
if chbPrepare.checked then DM.DB.TraceFlags:=DM.DB.TraceFlags + [tfQPrepare];
if chbTransaction.checked then DM.DB.TraceFlags:=DM.DB.TraceFlags + [tfTransact];
end
else begin
DM.DB.TraceFlags:=[];
end;
IBSQLMonitor.Enabled:=chbOnOff.Checked;
end;
procedure TSQLMonitor.chbStayOnTopClick(Sender: TObject);
begin
inherited;
if chbStayOnTop.Checked then
FormStyle := fsStayOnTop
else
FormStyle := fsNormal;
end;
class procedure TSQLMonitor.Open;
begin
if not Assigned(SQLMonitor) then
SQLMonitor := TSQLMonitor.Create(Application);
SQLMonitor.Show;
end;
procedure TSQLMonitor.FormClose(Sender: TObject; var Action: TCloseAction);
begin
inherited;
Action := caFree;
end;
procedure TSQLMonitor.FormDestroy(Sender: TObject);
begin
inherited;
SQLMonitor := nil;
end;
procedure TSQLMonitor.IBSQLMonitorSQL(EventText: String;
EventTime: TDateTime);
var s:string;
begin
inherited;
memoText.Lines.Add('');
s:=EventText;
delete(s,1,pos(']',s)+2);
memoText.Lines.Add(FormatDateTime('HH:mm:ss', Eventtime)+' '+s);
//memoText.Update;
end;
procedure TSQLMonitor.Button1Click(Sender: TObject);
begin
inherited;
memotext.clear;
end;
procedure TSQLMonitor.Button2Click(Sender: TObject);
begin
inherited;
if savedialog.Execute = true then
begin
MemoText.lines.SaveToFile(savedialog.filename);
end;
end;
procedure TSQLMonitor.chbFetchClick(Sender: TObject);
begin
inherited;
chbOnOffclick(nil);
end;
procedure TSQLMonitor.chbPrepareClick(Sender: TObject);
begin
inherited;
chbOnOffclick(nil);
end;
procedure TSQLMonitor.chbTransactionClick(Sender: TObject);
begin
inherited;
chbOnOffclick(nil);
end;
end.
|
unit untLocalDatabaseHelper;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, sqlite3conn, sqldb, db;
type
{ LocalConnectionHelper }
LocalConnectionHelper=class
private
conLocal:TSQLite3Connection;
trsLocal:TSQLTransaction;
public
constructor LocalConnectionHelper(LocalDatabasePath:string);
procedure ExecuteNonQuery(QueryString:string);
function ExcuteQurery(QueryString:string):TDataSet;
function ExecuteScalar(QueryString:string):string;
end;
implementation
{ LocalConnectionHelper }
constructor LocalConnectionHelper.LocalConnectionHelper(
LocalDatabasePath: string);
begin
conLocal.DatabaseName:=LocalDatabasePath;
trsLocal.DataBase:=conLocal;
conLocal.Transaction:=trsLocal;
conLocal.Open;
end;
function LocalConnectionHelper.ExcuteQurery(QueryString: string): TDataSet;
var
qryResult:TSQLQuery;
dtbResult:TDataSource;
dstResult:TDataSet;
i:integer;
begin
qryResult.SQL.Clear;
qryResult.SQL.Add(QueryString);
dtbResult.DataSet:=qryResult;
qryResult.DataBase:=conLocal;
qryResult.Transaction:=trsLocal;
trsLocal.DataBase:=conLocal;
trsLocal.Active:=true;
qryResult.ExecSQL;
dstResult:=dtbResult.DataSet;
for i:=0 to dtbResult.DataSet.FieldCount-1 do
begin
dstResult.Fields.Add(dtbResult.DataSet.Fields[i]);
end;
while(not dtbResult.DataSet.EOF) do
begin
for i:=0 to dtbResult.DataSet.FieldCount-1 do
begin
dstResult.Fields[i].AsVariant:=dtbResult.DataSet.Fields[i].AsVariant;
end;
dtbResult.DataSet.Next;
end;
Result:=dstResult;
trsLocal.Commit;
trsLocal.Active:=false;
qryResult.Free;
end;
function LocalConnectionHelper.ExecuteScalar(QueryString: string): string;
var
qryResult:TSQLQuery;
begin
qryResult.SQL.Clear;
qryResult.SQL.Add(QueryString);
qryResult.DataBase:=conLocal;
qryResult.Transaction:=trsLocal;
trsLocal.DataBase:=conLocal;
trsLocal.Active:=true;
qryResult.ExecSQL;
trsLocal.Commit;
Result:=qryResult.Fields[0].AsString;
trsLocal.Active:=false;
qryResult.Free;
end;
procedure LocalConnectionHelper.ExecuteNonQuery(QueryString: string);
var
qryResult:TSQLQuery;
begin
qryResult.SQL.Clear;
qryResult.SQL.Add(QueryString);
qryResult.DataBase:=conLocal;
qryResult.Transaction:=trsLocal;
trsLocal.DataBase:=conLocal;
trsLocal.Active:=true;
qryResult.ExecSQL;
trsLocal.Commit;
trsLocal.Active:=false;
qryResult.Free;
end;
end.
|
//-----------------------------------------------------------------------------
//
// Copyright 1982-2001 Pervasive Software Inc. All Rights Reserved
//
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
// BTRCONST.PAS
// This is the Pascal constants unit for Btrieve 6.x under MS Windows
// and DOS. Include this file in the USES clause of your application.
// For examples, see:
// MS Windows: btrsampw.pas
// DOS: btrsampd.pas
// Delphi: btrsam16.pas, btrsam32.pas
//-----------------------------------------------------------------------------
unit BtrConst;
interface
const
//
// Size Constants
//
ACS_SIZE = 265; // alternate collating sequence size
ACS_FILLER_SIZE = 260;
ACS_BYTE_MAP_SIZE = 256;
ACS_NAME_SIZE = 8;
ISR_TABLE_NAME_SIZE = 16;
ISR_FILLER_SIZE = 248;
BLOB_HEADER_LEN = $0014; // record chunk offset
MAX_DATABUF_SIZE = 57000;
MIN_PAGE = 512;
MAX_PAGE = 4096;
MAX_KEY_SIZE = 255;
MAX_KEY_SEG = 119;
OWNER_NAME_SIZE = 8+1; // 8 characters + binary 0
POS_BLOCK_SIZE = 128;
PHYSICAL_POS_BUF_LEN = 4; // data buf size for Get Position
MAX_FIXED_RECORD_LEN = 4088; // maximum fixed record length
MAX_STATBUF_SIZE = 33455; // B_STAT maximum data buffer size
MAX_FILE_NAME_LENGTH = 64;
//
// 'Chunk' API Constatnts
//
GET_SIGNATURE_INDEX = $00000004;
GET_NUM_CHUNKS_INDEX = $00000008;
GET_CHUNK_OFFSET_INDEX = 12;
GET_CHUNK_LEN_INDEX = 16;
GET_USER_DATA_PTR_INDEX = 20;
UPDATE_SIGNATURE_INDEX = $00000000;
UPDATE_NUM_CHUNKS_INDEX = $00000004;
UPDATE_CHUNK_OFFSET_INDEX = $00000008;
UPDATE_CHUNK_LEN_INDEX = $00000012;
UPDATE_USER_DATA_PTR_INDEX = $00000016;
RECTANGLE_DIRECT_SIGN = $80000002;
RECTANGLE_INDIRECT_SIGN = $80000003;
APPEND_TO_BLOB = $20000000;
GET_DRTC_XTRACTOR_KEY = $FFFFFFFE;
NEXT_IN_BLOB = $40000000;
XTRACTR_INDIRECT_SIGN = $80000001;
XTRACTR_DIRECT_SIGN = $80000000;
TRUNC_SIGN = $80000004;
PARTS_OF_KEY = $00800000;
TRUNC_AFTER_UPDATE = $00400000;
CHUNK_NOBIAS_MASK = (NEXT_IN_BLOB or APPEND_TO_BLOB or PARTS_OF_KEY or TRUNC_AFTER_UPDATE) xor $FFFFFFFF;
CHUNK_NO_INTERNAL_CURRENCY = $0001;
MUST_READ_DATA_PAGE = $0002;
NO_INTERNAL_CURRENCY = 0;
//
// Operation Codes
//
B_OPEN = 0;
B_CLOSE = 1;
B_INSERT = 2;
B_UPDATE = 3;
B_DELETE = 4;
B_GET_EQUAL = 5;
B_GET_NEXT = 6;
B_GET_PREVIOUS = 7;
B_GET_GT = 8;
B_GET_GE = 9;
B_GET_LT = 10;
B_GET_LE = 11;
B_GET_FIRST = 12;
B_GET_LAST = 13;
B_CREATE = 14;
B_STAT = 15;
B_EXTEND = 16;
B_SET_DIR = 17;
B_GET_DIR = 18;
B_BEGIN_TRAN = 19;
B_END_TRAN = 20;
B_ABORT_TRAN = 21;
B_GET_POSITION = 22;
B_GET_DIRECT = 23;
B_STEP_NEXT = 24;
B_STOP = 25;
B_VERSION = 26;
B_UNLOCK = 27;
B_RESET = 28;
B_SET_OWNER = 29;
B_CLEAR_OWNER = 30;
B_BUILD_INDEX = 31;
B_DROP_INDEX = 32;
B_STEP_FIRST = 33;
B_STEP_LAST = 34;
B_STEP_PREVIOUS = 35;
B_GET_NEXT_EXTENDED = 36;
B_GET_PREV_EXTENDED = 37;
B_STEP_NEXT_EXT = 38;
B_STEP_PREVIOUS_EXT = 39;
B_EXT_INSERT = 40;
B_MISC_DATA = 41;
B_CONTINUOUS = 42;
B_SEEK_PERCENT = 44;
B_GET_PERCENT = 45;
B_CHUNK_UPDATE = 53;
B_EXTENDED_STAT = 65;
//
// Operation Bias Codes
//
S_WAIT_LOCK = 100;
S_NOWAIT_LOCK = 200; // function code bias for lock
M_WAIT_LOCK = 300; // function code bias for multiple loop lock
M_NOWAIT_LOCK = 400; // function code bias for multiple lock
WAIT_T = 119; // begin transaction with wait (same as 19)
NOWAIT_T = 219; // begin transaction with nowait
WAIT3_T = 319; // begin transaction with wait (same as 19)
NOWAIT4_T = 419; // begin transaction with nowait
CCURR_T_BIAS = 1000; // function code bias for consurrent trans
NOWRITE_WAIT = 500; // function code bias when ins/del/upd should
//
// Key Number Bias Codes & Special Key Codes
// The hexadecimal values below are unsigned values
//
KEY_BIAS = 50;
DROP_BUT_NO_RENUMBER = $80; // key num bias for Drop
// Preserves key #s
CREATE_SUPPLEMENTAL_AS_THIS_KEY_NUM = $80; // key bias for Create SI
CREATE_NEW_FILE = $FF;
DONT_CREATE_WITH_TTS = $FE;
CREATE_NEW_FILE_NO_TTS = $FD;
IGNORE_KEY = $FFFF; // ignore the key number
//
// Btrieve File Open Modes
// The hexadecimal values below are unsigned values
//
NORMAL = $00; // normal mode
ACCELERATED = $FF; // accelerated mode
EXCLUSIVE = $FC; // exclusive mode
MINUSONE = $FF; // byte value for -1
READONLY = $FE; // read only mode
//
// Btrieve Return Codes
//
B_NO_ERROR = 0;
B_INVALID_FUNCTION = 1;
B_IO_ERROR = 2;
B_FILE_NOT_OPEN = 3;
B_KEY_VALUE_NOT_FOUND = 4;
B_DUPLICATE_KEY_VALUE = 5;
B_INVALID_KEYNUMBER = 6;
B_DIFFERENT_KEYNUMBER = 7;
B_POSITION_NOT_SET = 8;
B_END_OF_FILE = 9;
B_MODIFIABLE_KEYVALUE_ERROR = 10;
B_FILENAME_BAD = 11;
B_FILE_NOT_FOUND = 12;
B_EXTENDED_FILE_ERROR = 13;
B_PREIMAGE_OPEN_ERROR = 14;
B_PREIMAGE_IO_ERROR = 15;
B_EXPANSION_ERROR = 16;
B_CLOSE_ERROR = 17;
B_DISKFULL = 18;
B_UNRECOVERABLE_ERROR = 19;
B_RECORD_MANAGER_INACTIVE = 20;
B_KEYBUFFER_TOO_SHORT = 21;
B_DATALENGTH_ERROR = 22;
B_POSITIONBLOCK_LENGTH = 23;
B_PAGE_SIZE_ERROR = 24;
B_CREATE_IO_ERROR = 25;
B_NUMBER_OF_KEYS = 26;
B_INVALID_KEY_POSITION = 27;
B_INVALID_RECORD_LENGTH = 28;
B_INVALID_KEYLENGTH = 29;
B_NOT_A_BTRIEVE_FILE = 30;
B_FILE_ALREADY_EXTENDED = 31;
B_EXTEND_IO_ERROR = 32;
B_BTR_CANNOT_UNLOAD = 33;
B_INVALID_EXTENSION_NAME = 34;
B_DIRECTORY_ERROR = 35;
B_TRANSACTION_ERROR = 36;
B_TRANSACTION_IS_ACTIVE = 37;
B_TRANSACTION_FILE_IO_ERROR = 38;
B_END_TRANSACTION_ERROR = 39;
B_TRANSACTION_MAX_FILES = 40;
B_OPERATION_NOT_ALLOWED = 41;
B_INCOMPLETE_ACCEL_ACCESS = 42;
B_INVALID_RECORD_ADDRESS = 43;
B_NULL_KEYPATH = 44;
B_INCONSISTENT_KEY_FLAGS = 45;
B_ACCESS_TO_FILE_DENIED = 46;
B_MAXIMUM_OPEN_FILES = 47;
B_INVALID_ALT_SEQUENCE_DEF = 48;
B_KEY_TYPE_ERROR = 49;
B_OWNER_ALREADY_SET = 50;
B_INVALID_OWNER = 51;
B_ERROR_WRITING_CACHE = 52;
B_INVALID_INTERFACE = 53;
B_VARIABLE_PAGE_ERROR = 54;
B_AUTOINCREMENT_ERROR = 55;
B_INCOMPLETE_INDEX = 56;
B_EXPANED_MEM_ERROR = 57;
B_COMPRESS_BUFFER_TOO_SHORT = 58;
B_FILE_ALREADY_EXISTS = 59;
B_REJECT_COUNT_REACHED = 60;
B_SMALL_EX_GET_BUFFER_ERROR = 61;
B_INVALID_GET_EXPRESSION = 62;
B_INVALID_EXT_INSERT_BUFF = 63;
B_OPTIMIZE_LIMIT_REACHED = 64;
B_INVALID_EXTRACTOR = 65;
B_RI_TOO_MANY_DATABASES = 66;
B_RIDDF_CANNOT_OPEN = 67;
B_RI_CASCADE_TOO_DEEP = 68;
B_RI_CASCADE_ERROR = 69;
B_RI_VIOLATION = 71;
B_RI_REFERENCED_FILE_CANNOT_OPEN = 72;
B_RI_OUT_OF_SYNC = 73;
B_END_CHANGED_TO_ABORT = 74;
B_RI_CONFLICT = 76;
B_CANT_LOOP_IN_SERVER = 77;
B_DEAD_LOCK = 78;
B_PROGRAMMING_ERROR = 79;
B_CONFLICT = 80;
B_LOCKERROR = 81;
B_LOST_POSITION = 82;
B_READ_OUTSIDE_TRANSACTION = 83;
B_RECORD_INUSE = 84;
B_FILE_INUSE = 85;
B_FILE_TABLE_FULL = 86;
B_NOHANDLES_AVAILABLE = 87;
B_INCOMPATIBLE_MODE_ERROR = 88;
B_DEVICE_TABLE_FULL = 90;
B_SERVER_ERROR = 91;
B_TRANSACTION_TABLE_FULL = 92;
B_INCOMPATIBLE_LOCK_TYPE = 93;
B_PERMISSION_ERROR = 94;
B_SESSION_NO_LONGER_VALID = 95;
B_COMMUNICATIONS_ERROR = 96;
B_DATA_MESSAGE_TOO_SMALL = 97;
B_INTERNAL_TRANSACTION_ERROR = 98;
B_REQUESTER_CANT_ACCESS_RUNTIME = 99;
B_NO_CACHE_BUFFERS_AVAIL = 100;
B_NO_OS_MEMORY_AVAIL = 101;
B_NO_STACK_AVAIL = 102;
B_CHUNK_OFFSET_TOO_LONG = 103;
B_LOCALE_ERROR = 104;
B_CANNOT_CREATE_WITH_BAT = 105;
B_CHUNK_CANNOT_GET_NEXT = 106;
B_CHUNK_INCOMPATIBLE_FILE = 107;
B_TRANSACTION_TOO_COMPLEX = 109;
B_ARCH_BLOG_OPEN_ERROR = 110;
B_ARCH_FILE_NOT_LOGGED = 111;
B_ARCH_FILE_IN_USE = 112;
B_ARCH_LOGFILE_NOT_FOUND = 113;
B_ARCH_LOGFILE_INVALID = 114;
B_ARCH_DUMPFILE_ACCESS_ERROR = 115;
B_NO_SYSTEM_LOCKS_AVAILABLE = 130;
B_FILE_FULL = 132;
B_MORE_THAN_5_CONCURRENT_USERS = 133;
B_ISR_READ_ERROR = 134; // Old definition
B_ISR_NOT_FOUND = 134; // New definition
B_ISR_FORMAT_INVALID = 135; // No Longer returned
B_ACS_NOT_FOUND = 136;
B_CANNOT_CONVERT_RP = 137;
B_INVALID_NULL_INDICATOR = 138;
B_INVALID_KEY_OPTION = 139;
B_INCOMPATIBLE_CLOSE = 140;
B_INVALID_USERNAME = 141;
B_INVALID_DATABASE = 142;
B_NO_SSQL_RIGHTS = 143;
B_ALREADY_LOGGED_IN = 144;
B_NO_DATABASE_SERVICES = 145;
B_DUPLICATE_SYSTEM_KEY = 146;
B_LOG_SEGMENT_MISSING = 147;
B_ROLL_FORWARD_ERROR = 148;
B_SYSTEM_KEY_INTERNAL = 149;
B_DBS_INTERNAL_ERROR = 150;
B_NESTING_DEPTH_ERROR = 151;
B_INVALID_PARAMETER_TO_MKDE = 160;
B_USER_COUNT_LIMIT_EXCEEDED = 161;
// Windows Client Return codes
B_LOCK_PARM_OUTOFRANGE = 1001;
B_MEM_ALLOCATION_ERR = 1002;
B_MEM_PARM_TOO_SMALL = 1003;
B_PAGE_SIZE_PARM_OUTOFRANGE = 1004;
B_INVALID_PREIMAGE_PARM = 1005;
B_PREIMAGE_BUF_PARM_OUTOFRANGE = 1006;
B_FILES_PARM_OUTOFRANGE = 1007;
B_INVALID_INIT_PARM = 1008;
B_INVALID_TRANS_PARM = 1009;
B_ERROR_ACC_TRANS_CONTROL_FILE = 1010;
B_COMPRESSION_BUF_PARM_OUTOFRANGE = 1011;
B_INV_N_OPTION = 1012;
B_TASK_LIST_FULL = 1013;
B_STOP_WARNING = 1014;
B_POINTER_PARM_INVALID = 1015;
B_ALREADY_INITIALIZED = 1016;
B_REQ_CANT_FIND_RES_DLL = 1017;
B_ALREADY_INSIDE_BTR_FUNCTION = 1018;
B_CALLBACK_ABORT = 1019;
B_INTF_COMM_ERROR = 1020;
B_FAILED_TO_INITIALIZE = 1021;
// Btrieve requester status codes
B_INSUFFICIENT_MEM_ALLOC = 2001;
B_INVALID_OPTION = 2002;
B_NO_LOCAL_ACCESS_ALLOWED = 2003;
B_SPX_NOT_INSTALLED = 2004;
B_INCORRECT_SPX_VERSION = 2005;
B_NO_AVAIL_SPX_CONNECTION = 2006;
B_INVALID_PTR_PARM = 2007;
B_CANT_CONNECT_TO_615 = 2008;
B_CANT_LOAD_MKDE_ROUTER = 2009;
B_UT_THUNK_NOT_LOADED = 2010;
B_NO_RESOURCE_DLL = 2011;
B_OS_ERROR = 2012;
// MKDE Router status codes
B_MK_ROUTER_MEM_ERROR = 3000;
B_MK_NO_LOCAL_ACCESS_ALLOWED = 3001;
B_MK_NO_RESOURCE_DLL = 3002;
B_MK_INCOMPAT_COMPONENT = 3003;
B_MK_TIMEOUT_ERROR = 3004;
B_MK_OS_ERROR = 3005;
B_MK_INVALID_SESSION = 3006;
B_MK_SERVER_NOT_FOUND = 3007;
B_MK_INVALID_CONFIG = 3008;
B_MK_NETAPI_NOT_LOADED = 3009;
B_MK_NWAPI_NOT_LOADED = 3010;
B_MK_THUNK_NOT_LOADED = 3011;
B_MK_LOCAL_NOT_LOADED = 3012;
B_MK_PNSL_NOT_LOADED = 3013;
B_MK_CANT_FIND_ENGINE = 3014;
B_MK_INIT_ERROR = 3015;
B_MK_INTERNAL_ERROR = 3016;
B_MK_LOCAL_MKDE_DATABUF_TOO_SMALL = 3017;
B_MK_CLOSED_ERROR = 3018;
B_MK_SEMAPHORE_ERROR = 3019;
B_MK_LOADING_ERROR = 3020;
B_MK_BAD_SRB_FORMAT = 3021;
B_MK_DATABUF_LEN_TOO_LARGE = 3022;
B_MK_TASK_TABLE_FULL = 3023;
B_MK_INVALID_OP_ON_REMOTE = 3034;
// PNSL status codes
B_NL_FAILURE = 3101;
B_NL_NOT_INITIALIZED = 3102;
B_NL_NAME_NOT_FOUND = 3103;
B_NL_PERMISSION_ERROR = 3104;
B_NL_NO_AVAILABLE_TRANSPORT = 3105;
B_NL_CONNECTION_FAILURE = 3106;
B_NL_OUT_OF_MEMORY = 3107;
B_NL_INVALID_SESSION = 3108;
B_NL_MORE_DATA = 3109;
B_NL_NOT_CONNECTED = 3110;
B_NL_SEND_FAILURE = 3111;
B_NL_RECEIVE_FAILURE = 3112;
B_NL_INVALID_SERVER_TYPE = 3113;
B_NL_SRT_FULL = 3114;
B_NL_TRANSPORT_FAILURE = 3115;
B_NL_RCV_DATA_OVERFLOW = 3116;
B_NL_CST_FULL = 3117;
B_NL_INVALID_ADDRESS_FAMILY = 3118;
B_NL_NO_AUTH_CONTEXT_AVAILABLE = 3119;
B_NL_INVALID_AUTH_TYPE = 3120;
B_NL_INVALID_AUTH_OBJECT = 3121;
B_NL_AUTH_LEN_TOO_SMALL = 3122;
//
// File flag definitions
// The hexadecimal values below are unsigned values.
//
VAR_RECS = $0001;
BLANK_TRUNC = $0002;
PRE_ALLOC = $0004;
DATA_COMP = $0008;
KEY_ONLY = $0010;
BALANCED_KEYS = $0020;
FREE_10 = $0040;
FREE_20 = $0080;
FREE_30 = FREE_10 or FREE_20;
DUP_PTRS = $0100;
INCLUDE_SYSTEM_DATA = $0200;
SPECIFY_KEY_NUMS = $0400;
VATS_SUPPORT = $0800;
NO_INCLUDE_SYSTEM_DATA = $1200;
//
// Key Flag Definitions
// The hexadecimal values below are unsigned values
//
KFLG_DUP = $0001; // Duplicates allowed mask
KFLG_MODX = $0002; // Modifiable key mask
KFLG_BIN = $0004; // Binary or extended key type mask
KFLG_NUL = $0008; // Null key mask
KFLG_SEG = $0010; // Segmented key mask
KFLG_ALT = $0020; // Alternate collating sequence mask
KFLG_NUMBERED_ACS = $0420; // Use numbered ACS in File
KFLG_NAMED_ACS = $0C20; // Use named ACS in File
KFLG_DESC_KEY = $0040; // Key stored descending mask
KFLG_REPEAT_DUPS_KEY = $0080; // Dupes handled w/ unique suffix
KFLG_EXTTYPE_KEY = $0100; // Extended key types are specified
KFLG_MANUAL_KEY = $0200; // Manual key which can be optionally null
// (then key is not inc. in B-tree)
KFLG_NOCASE_KEY = $0400; // Case insensitive key
KFLG_KEYONLY_FILE = $4000; // key only type file
KFLG_PENDING_KEY = $8000; // Set during a create or drop index
KFLG_ALLOWABLE_KFLAG_PRE6 = $037F; // before ver 6.0, no nocase.
//
// Extended Key Types
//
STRING_TYPE = 0;
INTEGER_TYPE = 1;
IEEE_TYPE = 2;
DATE_TYPE = 3;
TIME_TYPE = 4;
DECIMAL_TYPE = 5;
MONEY_TYPE = 6;
LOGICAL_TYPE = 7;
NUMERIC_TYPE = 8;
BFLOAT_TYPE = 9;
LSTRING_TYPE = 10;
ZSTRING_TYPE = 11;
UNSIGNED_BINARY_TYPE = 14;
AUTOINCREMENT_TYPE = 15;
STS = 17;
NUMERIC_SA = 18;
CURRENCY_TYPE = 19;
TIMESTAMP_TYPE = 20;
WSTRING_TYPE = 25;
WZSTRING_TYPE = 26;
//
// ACS Signature Types
//
ALT_ID = $AC;
COUNTRY_CODE_PAGE_ID = $AD;
ISR_ID = $AE;
implementation
end.
|
{*******************************************************}
{ }
{ HCView V1.1 作者:荆通 }
{ }
{ 本代码遵循BSD协议,你可以加入QQ群 649023932 }
{ 来获取更多的技术交流 2018-5-4 }
{ }
{ 文本文字样式实现单元 }
{ }
{*******************************************************}
unit HCTextStyle;
interface
uses
Windows, Classes, Graphics, SysUtils;
type
THCFontStyle = (tsBold, tsItalic, tsUnderline, tsStrikeOut, tsSuperscript,
tsSubscript);
THCFontStyles = set of THCFontStyle;
THCTextStyle = class(TPersistent)
private const
DefaultFontSize: Single = 10.5; // 五号
DefaultFontFamily = '宋体';
MaxFontSize: Single = 512;
strict private
FSize: Single;
FFamily: TFontName;
FFontStyles: THCFontStyles;
FColor: TColor; // 字体颜色
FBackColor: TColor;
protected
procedure SetFamily(const Value: TFontName);
procedure SetSize(const Value: Single);
procedure SetFontStyles(const Value: THCFontStyles);
public
CheckSaveUsed: Boolean;
TempNo: Integer;
constructor Create;
destructor Destroy; override;
function IsSizeStored: Boolean;
function IsFamilyStored: Boolean;
procedure ApplyStyle(const ACanvas: TCanvas; const AScale: Single = 1);
function EqualsEx(const ASource: THCTextStyle): Boolean;
procedure AssignEx(const ASource: THCTextStyle);
procedure SaveToStream(const AStream: TStream);
procedure LoadFromStream(const AStream: TStream; const AFileVersion: Word);
published
property Family: TFontName read FFamily write SetFamily stored IsFamilyStored;
property Size: Single read FSize write SetSize stored IsSizeStored nodefault;
property FontStyles: THCFontStyles read FFontStyles write SetFontStyles default [];
property Color: TColor read FColor write FColor default clBlack;
property BackColor: TColor read FBackColor write FBackColor default clWhite;
end;
implementation
{ THCTextStyle }
procedure THCTextStyle.ApplyStyle(const ACanvas: TCanvas; const AScale: Single = 1);
var
vFont: TFont;
vLogFont: TLogFont;
begin
with ACanvas do
begin
if FBackColor = clNone then
Brush.Style := bsClear
else
begin
Brush.Style := bsSolid;
Brush.Color := FBackColor;
end;
Font.Color := FColor;
Font.Name := FFamily;
Font.Size := Round(FSize);
if tsBold in FFontStyles then
Font.Style := Font.Style + [TFontStyle.fsBold]
else
Font.Style := Font.Style - [TFontStyle.fsBold];
if tsItalic in FFontStyles then
Font.Style := Font.Style + [TFontStyle.fsItalic]
else
Font.Style := Font.Style - [TFontStyle.fsItalic];
if tsUnderline in FFontStyles then
Font.Style := Font.Style + [TFontStyle.fsUnderline]
else
Font.Style := Font.Style - [TFontStyle.fsUnderline];
if tsStrikeOut in FFontStyles then
Font.Style := Font.Style + [TFontStyle.fsStrikeOut]
else
Font.Style := Font.Style - [TFontStyle.fsStrikeOut];
//if AScale <> 1 then
begin
vFont := TFont.Create;
try
vFont.Assign(ACanvas.Font);
GetObject(vFont.Handle, SizeOf(vLogFont), @vLogFont);
if (tsSuperscript in FFontStyles) or (tsSubscript in FFontStyles) then
vLogFont.lfHeight := -Round(FSize / 2 * GetDeviceCaps(ACanvas.Handle, LOGPIXELSY) / 72 / AScale)
else
vLogFont.lfHeight := -Round(FSize * GetDeviceCaps(ACanvas.Handle, LOGPIXELSY) / 72 / AScale);
vFont.Handle := CreateFontIndirect(vLogFont);
ACanvas.Font.Assign(vFont);
finally
vFont.Free;
end;
end;
end;
end;
procedure THCTextStyle.AssignEx(const ASource: THCTextStyle);
begin
Self.FSize := ASource.Size;
Self.FFontStyles := ASource.FontStyles;
Self.FFamily := ASource.Family;
Self.FColor := ASource.Color;
Self.FBackColor := ASource.BackColor;
end;
constructor THCTextStyle.Create;
begin
FSize := DefaultFontSize;
FFamily := DefaultFontFamily;
FFontStyles := [];
FColor := clBlack;
FBackColor := clNone;
end;
destructor THCTextStyle.Destroy;
begin
inherited;
end;
function THCTextStyle.EqualsEx(const ASource: THCTextStyle): Boolean;
begin
Result :=
(Self.FSize = ASource.Size)
and (Self.FFontStyles = ASource.FontStyles)
and (Self.FFamily = ASource.Family)
and (Self.FColor = ASource.Color)
and (Self.FBackColor = ASource.BackColor);
end;
function THCTextStyle.IsFamilyStored: Boolean;
begin
Result := FFamily <> DefaultFontFamily;
end;
function THCTextStyle.IsSizeStored: Boolean;
begin
Result := FSize = DefaultFontSize;
end;
procedure THCTextStyle.LoadFromStream(const AStream: TStream; const AFileVersion: Word);
var
vOldSize: Integer;
vSize: Word;
vBuffer: TBytes;
begin
if AFileVersion < 12 then
begin
AStream.ReadBuffer(vOldSize, SizeOf(vOldSize)); // 字号
FSize := vOldSize;
end
else
AStream.ReadBuffer(FSize, SizeOf(FSize)); // 字号
// 字体
AStream.ReadBuffer(vSize, SizeOf(vSize));
if vSize > 0 then
begin
SetLength(vBuffer, vSize);
AStream.Read(vBuffer[0], vSize);
FFamily := StringOf(vBuffer);
end;
AStream.ReadBuffer(FFontStyles, SizeOf(FFontStyles));
AStream.ReadBuffer(FColor, SizeOf(FColor));
AStream.ReadBuffer(FBackColor, SizeOf(FBackColor));
end;
procedure THCTextStyle.SaveToStream(const AStream: TStream);
var
vBuffer: TBytes;
vSize: Word;
begin
AStream.WriteBuffer(FSize, SizeOf(FSize));
vBuffer := BytesOf(FFamily);
vSize := System.Length(vBuffer);
AStream.WriteBuffer(vSize, SizeOf(vSize));
if vSize > 0 then
AStream.WriteBuffer(vBuffer[0], vSize);
AStream.WriteBuffer(FFontStyles, SizeOf(FFontStyles));
AStream.WriteBuffer(FColor, SizeOf(FColor));
AStream.WriteBuffer(FBackColor, SizeOf(FBackColor));
end;
procedure THCTextStyle.SetFamily(const Value: TFontName);
begin
if FFamily <> Value then
FFamily := Value;
end;
procedure THCTextStyle.SetSize(const Value: Single);
begin
if FSize <> Value then
FSize := Value;
end;
procedure THCTextStyle.SetFontStyles(const Value: THCFontStyles);
begin
if FFontStyles <> Value then
FFontStyles := Value;
end;
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs,
StdCtrls;
type
{ TForm1 }
TForm1 = class(TForm)
Memo1: TMemo;
procedure FormCreate(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
Form1: TForm1;
implementation
uses
synsock, blcksock, synautil,
Contnrs;
{$R *.lfm}
type
{ TTCPHttpDaemon }
TTCPHttpDaemon = class(TThread)
private
Sock: TTCPBlockSocket;
ThreadList: TObjectList;
public
constructor Create;
destructor Destroy; override;
procedure Execute; override;
end;
{ TTCPHttpThread }
TTCPHttpThread = class(TThread)
private
Sock: TTCPBlockSocket;
Headers: TStringList;
InputData, OutputData: TMemoryStream;
LogData: string;
function ProcessHttpRequest(Request, URI: string): integer;
procedure AddLog;
public
DoneFlag: boolean;
constructor Create(hSock: TSocket);
destructor Destroy; override;
procedure Execute; override;
end;
var
Daemon: TTCPHttpDaemon;
{ TForm1 }
procedure TForm1.FormCreate(Sender: TObject);
begin
Memo1.Align := alClient;
Memo1.Lines.Clear;
end;
{ TTCPHttpDaemon }
constructor TTCPHttpDaemon.Create;
begin
Sock := TTCPBlockSocket.Create;
Sock.Family := SF_IP4;
ThreadList := TObjectList.Create(False);
FreeOnTerminate := False;
Priority := tpNormal;
inherited Create(False);
end;
destructor TTCPHttpDaemon.Destroy;
var
thd: TTCPHttpThread;
i: integer;
begin
for i := 0 to ThreadList.Count - 1 do
begin
thd := TTCPHttpThread(ThreadList[i]);
thd.Sock.AbortSocket;
thd.Terminate;
thd.WaitFor;
FreeAndNil(thd);
end;
ThreadList.Free;
Sock.Free;
inherited Destroy;
end;
procedure TTCPHttpDaemon.Execute;
var
hSock: TSocket;
th: TTCPHttpThread;
i: integer;
begin
try
Sock.CreateSocket;
Sock.SetLinger(True, 10000);
Sock.Bind('0.0.0.0', '80');
Sock.Listen;
while not Terminated do
begin
if Sock.CanRead(1000) then
begin
hSock := Sock.Accept;
if Sock.LastError = 0 then
begin
i := 0;
while i < ThreadList.Count do
begin
// Garbage collection
th := TTCPHttpThread(ThreadList[i]);
if th.DoneFlag then
begin
th.Free;
ThreadList.Delete(i);
end
else
Inc(i);
end;
ThreadList.Add(TTCPHttpThread.Create(hSock));
end;
end;
end;
finally
end;
end;
{ TTCPHttpThrd }
constructor TTCPHttpThread.Create(hSock: TSocket);
begin
Sock := TTCPBlockSocket.Create;
Sock.Family := SF_IP4;
Sock.Socket := hSock;
FreeOnTerminate := False;
Priority := tpNormal;
inherited Create(False);
end;
destructor TTCPHttpThread.Destroy;
begin
Sock.Free;
inherited Destroy;
end;
procedure TTCPHttpThread.Execute;
var
timeout: integer;
s: string;
method, uri, protocol: string;
size: integer;
x, n: integer;
resultcode: integer;
Close: boolean;
begin
Headers := TStringList.Create;
InputData := TMemoryStream.Create;
OutputData := TMemoryStream.Create;
DoneFlag := False;
try
timeout := 120000;
while not Terminated and (Sock.LastError = 0) do
begin
// read request line
s := Sock.RecvString(timeout);
if Sock.LastError <> 0 then
Exit;
if s = '' then
Exit;
LogData := Format('%s:%d Connected. (ID=%d)',
[Sock.GetRemoteSinIP, Sock.GetRemoteSinPort, Self.FThreadID]);
Synchronize(@AddLog);
method := fetch(s, ' ');
if (s = '') or (method = '') then
Exit;
uri := fetch(s, ' ');
if uri = '' then
Exit;
protocol := fetch(s, ' ');
headers.Clear;
size := -1;
Close := False;
//read request headers
if protocol <> '' then
begin
if pos('HTTP/', protocol) <> 1 then
Exit;
if pos('HTTP/1.1', protocol) <> 1 then
Close := True;
repeat
s := sock.RecvString(Timeout);
if sock.lasterror <> 0 then
Exit;
if s <> '' then
Headers.add(s);
if Pos('CONTENT-LENGTH:', Uppercase(s)) = 1 then
Size := StrToIntDef(SeparateRight(s, ' '), -1);
if Pos('CONNECTION: CLOSE', Uppercase(s)) = 1 then
Close := True;
until s = '';
end;
//recv document...
InputData.Clear;
if size >= 0 then
begin
InputData.SetSize(Size);
x := Sock.RecvBufferEx(InputData.Memory, Size, Timeout);
InputData.SetSize(x);
if sock.lasterror <> 0 then
Exit;
end;
OutputData.Clear;
ResultCode := ProcessHttpRequest(method, uri);
sock.SendString(protocol + ' ' + IntToStr(ResultCode) + CRLF);
if protocol <> '' then
begin
headers.Add('Content-length: ' + IntToStr(OutputData.Size));
if Close then
headers.Add('Connection: close');
headers.Add('Date: ' + Rfc822DateTime(now));
headers.Add('Server: Synapse HTTP server demo');
headers.Add('');
for n := 0 to headers.Count - 1 do
sock.sendstring(headers[n] + CRLF);
end;
if Sock.LastError <> 0 then
Exit;
Sock.SendBuffer(OutputData.Memory, OutputData.Size);
if Close then
Break;
end;
finally
Headers.Free;
InputData.Free;
OutputData.Free;
DoneFlag := True;
end;
end;
function TTCPHttpThread.ProcessHttpRequest(Request, URI: string): integer;
var
l: TStringList;
begin
//sample of precessing HTTP request:
// InputData is uploaded document, headers is stringlist with request headers.
// Request is type of request and URI is URI of request
// OutputData is document with reply, headers is stringlist with reply headers.
// Result is result code
Result := 504;
if request = 'GET' then
begin
headers.Clear;
headers.Add('Content-type: Text/Html');
l := TStringList.Create;
try
l.Add('<html>');
l.Add('<head></head>');
l.Add('<body>');
l.Add('Request Uri: ' + uri);
l.Add('<br>');
l.Add('This document is generated by Synapse HTTP server demo!');
l.Add('</body>');
l.Add('</html>');
l.SaveToStream(OutputData);
finally
l.Free;
end;
Result := 200;
end;
end;
procedure TTCPHttpThread.AddLog;
begin
if Assigned(Form1) then
begin
Form1.Memo1.Lines.BeginUpdate;
try
Form1.Memo1.Lines.Add(LogData);
finally
Form1.Memo1.Lines.EndUpdate;
end;
end;
LogData := '';
end;
procedure _Init;
begin
Daemon := TTCPHttpDaemon.Create;
end;
procedure _Fin;
begin
if Assigned(Daemon) then
begin
Daemon.Terminate;
Daemon.WaitFor;
FreeAndNil(Daemon);
end;
end;
initialization
_Init;
finalization
_Fin;
end.
|
// **************************************************************************************************
//
// unit Vcl.Styles.NSIS
// https://github.com/RRUZ/vcl-styles-plugins
//
// The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License");
// you may not use this file except in compliance with the License. You may obtain a copy of the
// License at http://www.mozilla.org/MPL/
//
// Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF
// ANY KIND, either express or implied. See the License for the specific language governing rights
// and limitations under the License.
//
// The Original Code is NSISVCLStyles.dpr
//
// The Initial Developer of the Original Code is Rodrigo Ruz V.
//
// Portions created by Rodrigo Ruz V. are Copyright (C) 2013-2021 Rodrigo Ruz V.
//
// All Rights Reserved.
//
// **************************************************************************************************
unit Vcl.Styles.NSIS;
interface
{$DEFINE HookFileDialogs}
uses
System.Types,
System.SysUtils,
System.Classes,
System.Generics.Collections,
WinApi.Windows,
WinApi.Messages,
Vcl.Styles,
Vcl.Themes,
Vcl.StdCtrls,
Vcl.Graphics,
Vcl.Styles.Utils.SysStyleHook,
Vcl.Styles.Utils.Forms,
Vcl.Styles.Utils.StdCtrls;
type
TTransparentStaticNSIS = class(TSysStaticStyleHook)
private
protected
procedure Paint(Canvas: TCanvas); override;
procedure WndProc(var Message: TMessage); override;
procedure PaintBackground(Canvas: TCanvas); override;
public
constructor Create(AHandle: THandle); override;
Destructor Destroy; override;
end;
/// <summary> Dialog Style hook to add image and/or color support for the background and non client area
/// </summary>
TSysDialogStyleHookBackground = class(TSysDialogStyleHook)
strict private
type
TSettings = class
strict private
FColor: TColor;
FImageLocation: string;
FBitmap: TBitmap;
FUseColor: Boolean;
FUseImage: Boolean;
FEnabled: Boolean;
FUseAlpha: Boolean;
FAlphaValue: Byte;
procedure SetColor(const Value: TColor);
procedure SetImageLocation(const Value: string);
procedure SetUseColor(const Value: Boolean);
procedure SetUseImage(const Value: Boolean);
public
property UseImage: Boolean read FUseImage write SetUseImage;
property UseColor: Boolean read FUseColor write SetUseColor;
property Color: TColor read FColor write SetColor;
property ImageLocation: string read FImageLocation write SetImageLocation;
property Bitmap: TBitmap read FBitmap;
property Enabled: Boolean read FEnabled write FEnabled;
property UseAlpha: Boolean read FUseAlpha write FUseAlpha;
property AlphaValue: Byte read FAlphaValue write FAlphaValue;
constructor Create;
destructor Destroy; override;
end;
class var FNCSettings: TSettings;
class var FBackGroundSettings: TSettings;
class var FMergeImages: Boolean;
class Var FSharedBitMap: TBitmap;
class var FSharedImageLocation: string;
class procedure SetSharedImageLocation(const Value: string); static;
protected
procedure PaintNC(Canvas: TCanvas); override;
procedure PaintBackground(Canvas: TCanvas); override;
class constructor Create;
class destructor Destroy;
public
constructor Create(AHandle: THandle); override;
class property SharedImageLocation: string read FSharedImageLocation
write SetSharedImageLocation;
class property SharedBitMap: TBitmap read FSharedBitMap write FSharedBitMap;
class property MergeImages: Boolean read FMergeImages write FMergeImages;
class property NCSettings: TSettings read FNCSettings;
class property BackGroundSettings: TSettings read FBackGroundSettings;
end;
TSysDialogStyleHookNC = class(TSysDialogStyleHook)
protected
procedure WndProc(var Message: TMessage); override;
public
constructor Create(AHandle: THandle); override;
end;
TNSISTreeViewStyleHook = class (TMouseTrackSysControlStyleHook)
protected
procedure UpdateColors; override;
procedure WndProc(var Message: TMessage); override;
function GetBorderSize: TRect; override;
public
constructor Create(AHandle: THandle); override;
end;
var
NSIS_IgnoredControls: TList<HWND>;
implementation
uses
Winapi.CommCtrl,
DDetours,
Winapi.CommDlg,
Vcl.Styles.Utils.Graphics,
Vcl.Styles.Utils.SysControls, uLogExcept;
type
TThemedNSISControls = class
private
class var
FHook_WH_CALLWNDPROC: HHook;
protected
class function HookActionCallBackWndProc(nCode: Integer; wParam: wParam;
lParam: lParam): LRESULT; stdcall; static;
procedure InstallHook;
procedure RemoveHook;
public
constructor Create; overload;
destructor Destroy; override;
end;
var
NSISControlsList: TObjectDictionary<HWND, TSysStyleHook>;
ClassesList: TStrings; //use a TStrings to avoid the use of generics
ThemedNSISControls: TThemedNSISControls;
//
procedure Addlog(const Msg: string);
begin
//TFile.AppendAllText('C:\Test\log.txt', Format('%s %s %s', [FormatDateTime('hh:nn:ss.zzz', Now), Msg, sLineBreak]));
end;
constructor TNSISTreeViewStyleHook.Create(AHandle: THandle);
begin
inherited;
OverrideEraseBkgnd:=True;
OverridePaintNC := True;
OverrideFont := True;
HookedDirectly := True;
end;
procedure TNSISTreeViewStyleHook.UpdateColors;
begin
//TLogFile.Add('TFolderTreeViewStyleHook.UpdateColors');
inherited;
if OverrideEraseBkgnd then
Color := StyleServices.GetStyleColor(scTreeView)
else
Color := clWhite;
if OverrideFont then
FontColor := StyleServices.GetSystemColor(clWindowText)
else
FontColor := clWindowText;
end;
procedure TNSISTreeViewStyleHook.WndProc(var Message: TMessage);
begin
case Message.Msg of
WM_ERASEBKGND:
begin
UpdateColors;
if (Longint(TreeView_GetBkColor(Handle))<>ColorToRGB(Color)) then
TreeView_SetBkColor(Handle, ColorToRGB(Color));
if (Longint(TreeView_GetTextColor(Handle))<>ColorToRGB(FontColor)) then
TreeView_SetTextColor(Handle, ColorToRGB(FontColor));
//Message.Result := CallDefaultProc(Message);
//Exit;
end;
end;
inherited;
end;
function TNSISTreeViewStyleHook.GetBorderSize: TRect;
begin
if SysControl.HasBorder then
Result := Rect(2, 2, 2, 2);
end;
{ TTransparentStaticNSIS }
constructor TTransparentStaticNSIS.Create(AHandle: THandle);
begin
inherited;
OverrideEraseBkgnd := True;
OverrideFont := False;
// if (SysControl.ExStyle and WS_EX_TRANSPARENT <> WS_EX_TRANSPARENT) then
// SysControl.ExStyle := SysControl.ExStyle or WS_EX_TRANSPARENT;
end;
destructor TTransparentStaticNSIS.Destroy;
begin
inherited;
end;
procedure TTransparentStaticNSIS.Paint(Canvas: TCanvas);
const
Alignments: array [TAlignment] of Word = (DT_LEFT, DT_RIGHT, DT_CENTER);
States: array [Boolean] of TThemedTextLabel = (ttlTextLabelDisabled,
ttlTextLabelNormal);
var
LDetails: TThemedElementDetails;
LRect: TRect;
begin
LRect := SysControl.ClientRect;
LDetails := StyleServices.GetElementDetails(tbCheckBoxUncheckedNormal);
StyleServices.DrawParentBackground(Handle, Canvas.Handle, LDetails, False);
Canvas.Brush.Style := bsClear;
LDetails := StyleServices.GetElementDetails(States[SysControl.Enabled]);
DrawText(Canvas.Handle, LDetails, SysControl.Text, LRect, TextFormat);
end;
procedure TTransparentStaticNSIS.PaintBackground(Canvas: TCanvas);
//var
// Details: TThemedElementDetails;
begin
// if StyleServices.Available then
// begin
// Details.Element := teButton;
// if StyleServices.HasTransparentParts(Details) then
// StyleServices.DrawParentBackground(Handle, Canvas.Handle, Details, False);
// end;
end;
procedure TTransparentStaticNSIS.WndProc(var Message: TMessage);
begin
inherited;
case Message.Msg of
CM_CTLCOLORSTATIC:
begin
// SetTextColor(Message.wParam, ColorToRGB(FontColor));
SetBkMode(Message.wParam, TRANSPARENT);
// StyleServices.DrawParentBackground(Handle, Message.wParam, nil, False);
Message.Result := GetStockObject(NULL_BRUSH);
Exit;
end;
else
inherited;
end;
end;
{ TSysDialogStyleHookBackground }
class constructor TSysDialogStyleHookBackground.Create;
begin
FMergeImages := False;
FSharedBitMap := TBitmap.Create;
FNCSettings := TSysDialogStyleHookBackground.TSettings.Create;
FBackGroundSettings := TSysDialogStyleHookBackground.TSettings.Create;
end;
constructor TSysDialogStyleHookBackground.Create(AHandle: THandle);
begin
inherited;
end;
class destructor TSysDialogStyleHookBackground.Destroy;
begin
FreeAndNil(FSharedBitMap);
FreeAndNil(FNCSettings);
FreeAndNil(FBackGroundSettings);
end;
procedure TSysDialogStyleHookBackground.PaintBackground(Canvas: TCanvas);
var
LRect: TRect;
RBitmap: TRect;
L, H: Integer;
begin
// if the option is not enabled use the default inherited PaintBackground method
if not BackGroundSettings.Enabled then
inherited
else
begin
// Addlog('pass');
// get he bounds of the control (form)
LRect := Rect(0, 0, SysControl.ClientWidth, SysControl.ClientHeight);
// use a custom color for the background?
if BackGroundSettings.UseColor then
begin
Canvas.Brush.Color := BackGroundSettings.Color;
Canvas.FillRect(LRect);
end
else
// use a bitmap
begin
// check the size of the bitmap against the control bounds to detrine how the bitmap is drawn
if not FMergeImages and ((BackGroundSettings.Bitmap.Width < LRect.Width)
or (BackGroundSettings.Bitmap.Height < LRect.Height)) then
begin
Canvas.Brush.Bitmap := BackGroundSettings.Bitmap;
Canvas.FillRect(LRect);
end
else
begin
// check if the the background bitmap must be merged with non client area bitmap
if not FMergeImages then
Canvas.CopyRect(LRect, BackGroundSettings.Bitmap.Canvas, LRect)
else
begin
RBitmap := LRect;
H := GetBorderSize.Top;
L := GetBorderSize.Left;
RBitmap.SetLocation(L, H);
// Canvas.CopyRect(LRect,BackGroundSettings.Bitmap.Canvas,RBitmap);
Canvas.CopyRect(LRect, FSharedBitMap.Canvas, RBitmap);
end;
end;
end;
end;
end;
procedure TSysDialogStyleHookBackground.PaintNC(Canvas: TCanvas);
begin
inherited
end;
class procedure TSysDialogStyleHookBackground.SetSharedImageLocation
(const Value: string);
var
Picture: TPicture;
begin
FSharedImageLocation := Value;
if FileExists(Value) then
begin
Picture := TPicture.Create;
try
Picture.LoadFromFile(Value);
FSharedBitMap.Width := Picture.Width;
FSharedBitMap.Height := Picture.Height;
FSharedBitMap.Canvas.Draw(0, 0, Picture.Graphic);
finally
Picture.Free;
end;
end;
end;
{ TSysDialogStyleHookBackground.TSettings }
constructor TSysDialogStyleHookBackground.TSettings.Create;
begin
inherited;
FUseAlpha := False;
FAlphaValue := 200;
FEnabled := False;
FBitmap := TBitmap.Create;
ImageLocation := '';
UseImage := False;
end;
destructor TSysDialogStyleHookBackground.TSettings.Destroy;
begin
FBitmap.Free;
inherited;
end;
procedure TSysDialogStyleHookBackground.TSettings.SetColor(const Value: TColor);
begin
if Value <> FColor then
FColor := Value;
end;
procedure TSysDialogStyleHookBackground.TSettings.SetImageLocation
(const Value: string);
var
Picture: TPicture;
begin
FImageLocation := Value;
if FileExists(Value) then
begin
Picture := TPicture.Create;
try
Picture.LoadFromFile(Value);
FBitmap.Width := Picture.Width;
FBitmap.Height := Picture.Height;
FBitmap.Canvas.Draw(0, 0, Picture.Graphic);
finally
Picture.Free;
end;
end;
end;
procedure TSysDialogStyleHookBackground.TSettings.SetUseColor
(const Value: Boolean);
begin
FUseColor := Value;
FUseImage := not Value;
end;
procedure TSysDialogStyleHookBackground.TSettings.SetUseImage
(const Value: Boolean);
begin
FUseImage := Value;
FUseColor := not Value;
end;
{ TSysDialogStyleHookNC }
constructor TSysDialogStyleHookNC.Create(AHandle: THandle);
begin
inherited;
OverridePaintNC := False;
end;
procedure TSysDialogStyleHookNC.WndProc(var Message: TMessage);
begin
inherited;
end;
function FindWinFromRoot(Root: HWND; ClassName: PChar): HWND;
var
Next, Child: HWND;
S: String;
begin
Result := 0;
Next := GetWindow(Root, GW_CHILD or GW_HWNDFIRST);
while (Next > 0) do
begin
S := GetWindowClassName(Next);
//Addlog(S);
if SameText(S, String(ClassName)) then
Exit(Next);
Next := GetWindow(Next, GW_HWNDNEXT);
Child := GetWindow(Next, GW_CHILD or GW_HWNDFIRST);
if Child > 0 then
Result := FindWinFromRoot(Next, ClassName);
if Result > 0 then
Exit;
end;
end;
function WindowIsDirectUIHWND(hwndParent: HWND): Boolean;
begin
Result := FindWinFromRoot(hwndParent, 'DUIViewWndClassName')>0;// (FindWindowEx(hwndParent, 0, 'DUIViewWndClassName', nil) <> 0);
end;
function BeforeNSISHookingControl(Info: PControlInfo): Boolean;
var
LInfo: TControlInfo;
// Root, C: HWND;
begin
{
Return true to allow control hooking !
Return false to prevent control hooking !
}
{ NB: The ClassName is always in lowercase . }
LInfo := Info^;
// Addlog('Cheking '+ LInfo.ClassName);
if SameText('#32770', LInfo.ClassName) then
begin
// Addlog(IntToHex(LInfo.Handle, 8));
// if WindowIsDirectUIHWND( LInfo.Handle) then
// begin
// Addlog('true');
// Exit(False);
//
// end
// else
// Addlog('false');
end
else
begin
// //Root := GetAncestor(LInfo.Parent, GA_ROOT);
// Root:=GetParent(LInfo.Handle);
// //if FindWinFromRoot(Root, 'DUIViewWndClassName') > 0 then
// if FindWindowEx(Root, 0, 'DUIViewWndClassName', nil) <> 0 then
// begin
// Result := False;
// Exit;
// end;
end;
// Result := True;
// Root := GetAncestor(LInfo.Parent, GA_ROOT);
// if FindWinFromRoot(Root, 'DirectUIHWND') > 0 then
// begin
// Result := False;
// Exit;
// end;
//Addlog('BeforeNSISHookingControl '+IntToHex(LInfo.Handle, 8));
Result := NSIS_IgnoredControls.IndexOf(LInfo.Handle) < 0;
// if not Result then
// Addlog(IntToHex(LInfo.Handle, 8));
end;
procedure HookNotificationNSIS(Action: TSysHookAction; Info: PControlInfo);
var
LInfo: TControlInfo;
begin
LInfo := Info^;
if Action = cRemoved then
if NSIS_IgnoredControls.IndexOf(LInfo.Handle) >= 0 then
NSIS_IgnoredControls.Remove(LInfo.Handle);
end;
{ TThemedNppControls }
constructor TThemedNSISControls.Create;
begin
inherited;
FHook_WH_CALLWNDPROC := 0;
InstallHook;
NSISControlsList := TObjectDictionary<HWND, TSysStyleHook>.Create([doOwnsValues]);
ClassesList := TStringList.Create;
end;
destructor TThemedNSISControls.Destroy;
begin
RemoveHook;
NSISControlsList.Free;
ClassesList.Free;
inherited;
end;
class function TThemedNSISControls.HookActionCallBackWndProc(nCode: Integer;
wParam: wParam; lParam: lParam): LRESULT;
var
sClassName: string;
begin
Result := CallNextHookEx(FHook_WH_CALLWNDPROC, nCode, wParam, lParam);
if (nCode < 0) then
Exit;
if (StyleServices.Enabled) and not (StyleServices.IsSystemStyle) then
begin
// GetClassName(PCWPStruct(lParam)^.hwnd, C, 256);
// if SameText(C,'#32770') then
// begin
// Addlog(Format('Handle %x ',[PCWPStruct(lParam)^.hwnd]));
// Addlog('GetClassName ' + C);
// end;
if ClassesList.IndexOfName(IntToStr(PCWPStruct(lParam)^.hwnd))=-1 then
begin
sClassName:=GetWindowClassName(PCWPStruct(lParam)^.hwnd);
//Addlog('GetClassName ' + C);
ClassesList.Add(Format('%d=%s',[PCWPStruct(lParam)^.hwnd, sClassName]));
end;
if ClassesList.IndexOfName(IntToStr(PCWPStruct(lParam)^.hwnd))>=0 then
begin
sClassName:=ClassesList.Values[IntToStr(PCWPStruct(lParam)^.hwnd)]; //ClassesList[PCWPStruct(lParam)^.hwnd];
if SameText(sClassName,'#32770') then
begin
if not TSysStyleManager.SysStyleHookList.ContainsKey(PCWPStruct(lParam)^.hwnd) then // avoid double registration
if (PCWPStruct(lParam)^.message=WM_NCCALCSIZE) and not (NSISControlsList.ContainsKey(PCWPStruct(lParam)^.hwnd)) then
NSISControlsList.Add(PCWPStruct(lParam)^.hwnd, TSysDialogStyleHook.Create(PCWPStruct(lParam)^.hwnd));
end
end;
end;
end;
procedure TThemedNSISControls.InstallHook;
begin
FHook_WH_CALLWNDPROC := SetWindowsHookEx(WH_CALLWNDPROC, @TThemedNSISControls.HookActionCallBackWndProc, 0, GetCurrentThreadId);
end;
procedure TThemedNSISControls.RemoveHook;
begin
if FHook_WH_CALLWNDPROC <> 0 then
UnhookWindowsHookEx(FHook_WH_CALLWNDPROC);
end;
Procedure Done;
begin
if Assigned(ThemedNSISControls) then
begin
ThemedNSISControls.Free;
ThemedNSISControls:=nil;
end;
end;
{$IFDEF HookFileDialogs}
const
commdlg32 = 'comdlg32.dll';
var
TrampolineGetOpenFileNameW: function (var OpenFile: TOpenFilenameW): Bool; stdcall;
TrampolineGetOpenFileNameA: function (var OpenFile: TOpenFilenameA): Bool; stdcall;
TrampolineGetSaveFileNameW: function (var OpenFile: TOpenFilenameW): Bool; stdcall;
TrampolineGetSaveFileNameA: function (var OpenFile: TOpenFilenameA): Bool; stdcall;
function DialogHook(Wnd: HWnd; Msg: UINT; WParam: WPARAM; LParam: LPARAM): UINT_PTR; stdcall;
begin
Exit(0);
end;
function DetourGetOpenFileNameW(var OpenFile: TOpenFilename): Bool; stdcall;
begin
//Addlog('DetourGetOpenFileNameW');
OpenFile.lpfnHook := @DialogHook;
OpenFile.Flags := OpenFile.Flags or OFN_ENABLEHOOK or OFN_EXPLORER;
Exit(TrampolineGetOpenFileNameW(OpenFile));
end;
function DetourGetOpenFileNameA(var OpenFile: TOpenFilenameA): Bool; stdcall;
begin
//Addlog('DetourGetOpenFileNameA');
OpenFile.lpfnHook := @DialogHook;
OpenFile.Flags := OpenFile.Flags or OFN_ENABLEHOOK or OFN_EXPLORER;
Exit(TrampolineGetOpenFileNameA(OpenFile));
end;
function DetourGetSaveFileNameW(var OpenFile: TOpenFilename): Bool; stdcall;
begin
//Addlog('DetourGetSaveFileNameW');
OpenFile.lpfnHook := @DialogHook;
OpenFile.Flags := OpenFile.Flags or OFN_ENABLEHOOK or OFN_EXPLORER;
Exit(TrampolineGetSaveFileNameW(OpenFile));
end;
function DetourGetSaveFileNameA(var OpenFile: TOpenFilenameA): Bool; stdcall;
begin
//Addlog('DetourGetSaveFileNameA');
OpenFile.lpfnHook := @DialogHook;
OpenFile.Flags := OpenFile.Flags or OFN_ENABLEHOOK or OFN_EXPLORER;
Exit(TrampolineGetSaveFileNameA(OpenFile));
end;
procedure HookFileDialogs;
begin
//Addlog('HookFileDialogs');
@TrampolineGetOpenFileNameW := InterceptCreate(commdlg32, 'GetOpenFileNameW', @DetourGetOpenFileNameW, True);
@TrampolineGetOpenFileNameA := InterceptCreate(commdlg32, 'GetOpenFileNameA', @DetourGetOpenFileNameA, True);
@TrampolineGetSaveFileNameW := InterceptCreate(commdlg32, 'GetSaveFileNameW', @DetourGetSaveFileNameW, True);
@TrampolineGetSaveFileNameA := InterceptCreate(commdlg32, 'GetSaveFileNameA', @DetourGetSaveFileNameA, True);
end;
procedure UnHookFileDialogs;
begin
//Addlog('UnHookFileDialogs');
InterceptRemove(@TrampolineGetOpenFileNameW);
InterceptRemove(@TrampolineGetOpenFileNameA);
InterceptRemove(@TrampolineGetSaveFileNameW);
InterceptRemove(@TrampolineGetSaveFileNameA);
end;
{$ENDIF}
var
Trampoline_LoadBitmapA: function (hInstance: HINST; lpBitmapName: PAnsiChar): HBITMAP; stdcall;
function Detour_LoadBitmapA(hInstance: HINST; lpBitmapName: PAnsiChar): HBITMAP; stdcall;
var
LBitMap: TBitmap;
LRect: TRect;
LSize: TSize;
begin
if IS_INTRESOURCE(PChar(lpBitmapName)) then
case Integer(lpBitmapName) of
110: begin
LBitMap:=TBitmap.Create;
try
//LBitmap.Handle := Result;
LBitMap.SetSize(16 * 6, 16);
LBitMap.PixelFormat := pf8bit;
StyleServices.GetElementSize(LBitMap.Canvas.Handle, StyleServices.GetElementDetails(tbCheckBoxUncheckedNormal), TElementSize.esMinimum, LSize);
if (LSize.Width>=16) or (LSize.Height>=16) then
LBitMap.Canvas.Brush.Color:= StyleServices.GetSystemColor(clWindow)
else
LBitMap.Canvas.Brush.Color:=clFuchsia;
//LBitMap.TransparentColor := clFuchsia;
LRect := Rect(0, 0, LBitMap.Width, LBitMap.Height);
LBitMap.Canvas.FillRect(LRect);
LRect := Rect(0, 1, 16, 15);
OffsetRect(LRect, 16, 0);
DrawStyleElement(LBitMap.Canvas.Handle, StyleServices.GetElementDetails(tbCheckBoxUncheckedNormal), LRect);
OffsetRect(LRect, 16, 0);
DrawStyleElement(LBitMap.Canvas.Handle, StyleServices.GetElementDetails(tbCheckBoxCheckedNormal), LRect);
OffsetRect(LRect, 16, 0);
DrawStyleElement(LBitMap.Canvas.Handle, StyleServices.GetElementDetails(tbCheckBoxCheckedDisabled), LRect);
OffsetRect(LRect, 16, 0);
DrawStyleElement(LBitMap.Canvas.Handle, StyleServices.GetElementDetails(tbCheckBoxUncheckedDisabled), LRect);
OffsetRect(LRect, 16, 0);
DrawStyleElement(LBitMap.Canvas.Handle, StyleServices.GetElementDetails(tbCheckBoxCheckedDisabled), LRect);
//LBitMap.SaveToFile(Format('C:\Dephi\github\vcl-styles-plugins\NSIS plugin\Scripts\Modern UI\check_%dx%d.bmp', [LSize.Width, LSize.Height]));
Exit(LBitMap.Handle);
finally
LBitmap.ReleaseHandle;
LBitMap.Free;
end;
end;
end;
Result:= Trampoline_LoadBitmapA(hInstance, lpBitmapName);
end;
initialization
{$IFDEF HookFileDialogs}
HookFileDialogs;
{$ENDIF}
NSIS_IgnoredControls := TList<HWND>.Create;
TSysStyleManager.OnBeforeHookingControl := @BeforeNSISHookingControl;
TSysStyleManager.OnHookNotification := @HookNotificationNSIS;
ThemedNSISControls:=nil;
if StyleServices.Available then
ThemedNSISControls := TThemedNSISControls.Create;
@Trampoline_LoadBitmapA := InterceptCreate(user32, 'LoadBitmapA', @Detour_LoadBitmapA);
finalization
{$IFDEF HookFileDialogs}
UnHookFileDialogs;
{$ENDIF}
Done;
NSIS_IgnoredControls.Free;
InterceptRemove(@Trampoline_LoadBitmapA);
end.
|
(**
* $Id: dco.transport.ConnectionImpl.pas 840 2014-05-24 06:04:58Z QXu $
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either
* express or implied. See the License for the specific language governing rights and limitations under the License.
*)
unit dco.transport.ConnectionImpl;
interface
uses
dco.transport.Connection,
dco.transport.Pdu,
dco.transport.Transport;
type
/// <summary>This class implements a tranport connection.</summary>
TConnectionImpl = class(TInterfacedObject, IConnection)
private
FTransport: ITransport;
FLocalUri: string;
FRemoteUri: string;
function CreatePdu(const Message_: string): TPdu;
public
constructor Create(const Transport: ITransport; const LocalUri: string; const RemoteUri: string);
destructor Destroy; override;
/// <summary>Returns the uri of the connection.</summary>
function GetId: string;
/// <summary>Sends an outbound message and waits for it is actually sent out.</summary>
function WriteEnsured(const Message_: string): Boolean;
/// <summary>Sends an outbound message and waits for it is actually sent out.</summary>
procedure Write(const Message_: string);
///
procedure HandleRead(const Message_: string);
end;
implementation
constructor TConnectionImpl.Create(const Transport: ITransport; const LocalUri: string; const RemoteUri: string);
begin
assert(Transport <> nil);
assert(LocalUri <> '');
assert(RemoteUri <> '');
assert(RemoteUri <> LocalUri);
inherited Create;
FTransport := Transport;
FLocalUri := LocalUri;
FRemoteUri := RemoteUri;
end;
destructor TConnectionImpl.Destroy;
begin
FTransport := nil;
inherited;
end;
function TConnectionImpl.CreatePdu(const Message_: string): TPdu;
begin
Result := TPdu.Create(FRemoteUri, FLocalUri, Message_);
end;
function TConnectionImpl.GetId: string;
begin
Result := FLocalUri;
end;
function TConnectionImpl.WriteEnsured(const Message_: string): Boolean;
var
Pdu: TPdu;
begin
Pdu := CreatePdu(Message_);
Result := FTransport.WriteEnsured(Pdu);
end;
procedure TConnectionImpl.Write(const Message_: string);
var
Pdu: TPdu;
begin
Pdu := CreatePdu(Message_);
FTransport.Write(Pdu);
end;
procedure TConnectionImpl.HandleRead(const Message_: string);
begin
// TODO:
end;
end.
|
(*======================================================================*
| unitObjectCache |
| |
| Object caching & association classes: |
| |
| TObjectCache Implements a flexible cache of objects |
| TClassAssociations Associates pairs of classes |
| TClassStringAssociations Associates a string/class pairs |
| TObjectProcessor Process a list of objects in a |
| background thread. |
| |
| The contents of this file are subject to the Mozilla Public License |
| Version 1.1 (the "License"); you may not use this file except in |
| compliance with the License. You may obtain a copy of the License |
| at http://www.mozilla.org/MPL/ |
| |
| Software distributed under the License is distributed on an "AS IS" |
| basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See |
| the License for the specific language governing rights and |
| limitations under the License. |
| |
| Copyright © Colin Wilson 2003 All Rights Reserved
| |
| Version Date By Description |
| ------- ---------- ---- ------------------------------------------|
| 1.0 10/12/2003 CPWW Original |
*======================================================================*)
unit unitObjectCache;
interface
uses Windows, Classes, SysUtils, ConTnrs, SyncObjs, Types;
type
TObjectCacheProc = procedure (obj : TObject; idx, param : Integer; var continue : boolean) of object;
//---------------------------------------------------------------
TObjectCache = class
private
fOrigCapacity : Integer;
fObjects : TObjectList;
function GetOwnsObjects: boolean;
procedure SetOwnsObjects(const Value: boolean);
function GetCapacity: Integer;
procedure SetCapacity(const Value: Integer);
function GetCount: Integer;
protected
function CanRemove (AObject : TObject) : boolean; virtual;
function Matches (ObjA, ObjB : TObject) : boolean; virtual;
public
constructor Create (ACapacity : Integer; OwnsObjects : boolean);
destructor Destroy; override;
function IndexOfObject (AObject : TObject) : Integer;
procedure Add (AObject : TObject); virtual;
procedure Clear;
function ForEach (proc : TObjectCacheProc; param : Integer) : TObject;
function ForEachIdx (proc : TObjectCacheProc; param : Integer) : Integer;
procedure BringToFrontObject (idx : Integer);
function ObjectAt (idx : Integer) : TObject;
procedure Remove (AObject : TObject);
function Extract (AObject : TObject) : TObject;
procedure Push (AObject : TObject);
function Pop : TObject;
property OwnsObjects : boolean read GetOwnsObjects write SetOwnsObjects;
property Capacity : Integer read GetCapacity write SetCapacity;
property Count : Integer read GetCount;
end;
//---------------------------------------------------------------
TClassAssociation = class
private
fClassA, fClassB : TClass;
public
constructor Create (AClassA, AClassB : TClass);
property ClassA : TClass read fClassA;
property ClassB : TClass read fClassB;
end;
//---------------------------------------------------------------
TClassAssociations = class
private
fAssociations : TObjectList;
function GetCount: Integer;
function GetAssociation(idx: Integer): TClassAssociation;
function GetIndexOf(classA, classB: TClass): Integer;
function GetIndexOfClassA(classA: TClass): Integer;
function GetIndexOfClassB(classB: TClass): Integer;
protected
property Association [idx : Integer] : TClassAssociation read GetAssociation;
property Count : Integer read GetCount;
property IndexOf [classA, classB : TClass] : Integer read GetIndexOf;
property IndexOfClassA [classA : TClass] : Integer read GetIndexOfClassA;
property IndexOfClassB [classB : TClass] : Integer read GetIndexOfClassB;
public
constructor Create;
destructor Destroy; override;
procedure Associate (classA, classB : TClass);
procedure DisAssociate (classA, classB : TClass);
function FindClassBFor (classA : TClass) : TClass;
function FindClassAFor (classB : TClass) : TClass;
end;
//---------------------------------------------------------------
TClassStringAssociations = class
private
fAssociations : TStringList;
function GetIndexOf(const st: string; cls: TClass): Integer;
function GetCount: Integer;
function GetString(idx: Integer): string;
function GetClass(idx: Integer): TClass;
protected
property IndexOf [const st : string; cls : TClass] : Integer read GetIndexOf;
public
constructor Create;
destructor Destroy; override;
procedure Associate (const st : string; cls : TClass);
procedure DisAssociate (const st : string; cls : TClass);
function FindStringFor (cls : TClass) : string;
function FindClassFor (const st : string) : TClass;
property Count : Integer read GetCount;
property Strings [idx : Integer] : string read GetString;
property Classes [idx : Integer] : TClass read GetClass;
end;
TObjectProcessorState = (opsIdle, opsBusy);
//---------------------------------------------------------------
TObjectProcessor = class (TThread)
private
fSync : TCriticalSection;
fSignal : TEvent;
fObjects : TObjectList;
fState : TObjectProcessorState;
procedure SetOwnsObjects(const Value: boolean);
function GetOwnsObjects: boolean;
function GetCount: Integer;
protected
procedure Execute; override;
procedure Reset (obj : TObject); virtual;
procedure Process (obj : TObject); virtual;
procedure ObjectsProcessed; virtual;
public
constructor Create;
destructor Destroy; override;
procedure Clear;
procedure Terminate;
procedure AddObjectToQueue (obj : TObject);
property OwnsObjects : boolean read GetOwnsObjects write SetOwnsObjects;
property State : TObjectProcessorState read fState;
property Count : Integer read GetCount;
end;
TLog = class
private
fLock : TCriticalSection;
fStrings : TStrings;
fLocked : boolean;
fInLock : boolean;
fCapacity: Integer;
procedure Init;
procedure Lock;
procedure LimitCapacity;
function GetStrings(idx: Integer): string;
procedure SetCapacity(const Value: Integer);
public
destructor Destroy; override;
function LockGetCount : Integer;
procedure Add (const st : string);
procedure Clear;
procedure Unlock;
property Capacity : Integer read fCapacity write SetCapacity;
property Strings [idx : Integer] : string read GetStrings;
end;
implementation
{ TObjectCache }
(*----------------------------------------------------------------------*
| TObjectCache.Add |
| |
| Add an object to the cache. |
| |
| Note that the cache capacity will automatically be increased if |
| it is full, and no objects can be removed (see the CanRemove method) |
| |
| Parameters: |
| AObject: TObject The object to add |
*----------------------------------------------------------------------*)
procedure TObjectCache.Add(AObject: TObject);
var
idx, c : Integer;
b : boolean;
begin
idx := IndexOfObject (AObject);
if idx = 0 then // Already in the cache at the front
begin
if OwnsObjects then
AObject.Free;
Exit
end;
if idx = -1 then
begin // Not already in cache. Add it.
b := False;
c := fObjects.Count;
while c >= fOrigCapacity do
begin // There's not room. Remove old objects (if we're allowed)
repeat // Try to get back to the original capacity if it's been
Dec (c); // exceeded.
if CanRemove (fObjects [c]) then
begin
fObjects.Delete(c);
b := True
end
until b or (c = 0);
end;
if b then // Shrink the cache if it's bulged.
if fObjects.Capacity > fOrigCapacity then
if fObjects.Count < fOrigCapacity then
fObjects.Capacity := fOrigCapacity;
if fObjects.Capacity = fObjects.Count then // Bulge the cache
fObjects.Capacity := fObjects.Capacity + 1;
fObjects.Insert (0, AObject)
end
else // The object was already in the cache. So bring it to
begin // the front
BringToFrontObject (idx);
if OwnsObjects then
AObject.Free
end
end;
(*----------------------------------------------------------------------*
| procedure TObjectCache.BringToFrontObject |
| |
| Bring object 'idx' to the front of the cache. |
| |
| Parameters: |
| idx: Integer // Index of the object to bring to the front. |
*----------------------------------------------------------------------*)
procedure TObjectCache.BringToFrontObject(idx: Integer);
var
b : boolean;
obj : TObject;
begin
if (idx > 0) then
begin
obj := fObjects [idx];
b := OwnsObjects;
OwnsObjects := False; // Temporarily turn off 'owns objects' so we
try // can delete and reinsert safely.
fObjects.Delete (idx);
fObjects.Insert (0, obj)
finally
OwnsObjects := b
end
end
end;
(*----------------------------------------------------------------------*
| TObjectCache.CanRemove |
| |
| Override this to prevent objects from being removed from the cache |
| - maybe because another reference to the object still exists. |
| |
| Parameters: |
| AObject: TObject The object to test |
| |
| The function returns True if the object can be safely removed. |
*----------------------------------------------------------------------*)
function TObjectCache.CanRemove(AObject: TObject) : boolean;
begin
result := True
end;
(*----------------------------------------------------------------------*
| procedure TObjectCache.Clear |
| |
| Clear the cache - or as much of it as can safely be cleared. |
*----------------------------------------------------------------------*)
procedure TObjectCache.Clear;
var
i : Integer;
begin
i := 0;
while i < fObjects.Count do
if CanRemove (fObjects [i]) then
fObjects.Delete(i)
else
Inc (i)
end;
(*----------------------------------------------------------------------*
| constructor TObjectCache.Create |
*----------------------------------------------------------------------*)
constructor TObjectCache.Create(ACapacity : Integer; OwnsObjects : boolean);
begin
fObjects := TObjectList.Create (OwnsObjects);
fOrigCapacity := ACapacity;
fObjects.Capacity := ACapacity;
end;
(*----------------------------------------------------------------------*
| destructor TObjectCache.Destroy |
*----------------------------------------------------------------------*)
destructor TObjectCache.Destroy;
begin
fObjects.Free;
inherited;
end;
(*----------------------------------------------------------------------*
| function TObjectCache.Extract |
| |
| Extract an object from the cache. |
| |
| Parameters: |
| AObject: TObject The object to extract |
| |
| The function returns the extracted object. nb. Even if OwnsObjects |
| true, the object is *not* deleted |
*----------------------------------------------------------------------*)
function TObjectCache.Extract(AObject: TObject) : TObject;
begin
result := fObjects.Extract(AObject)
end;
(*----------------------------------------------------------------------*
| function TObjectCache.ForEach |
| |
| Call 'proc' for each object in the cache |
| |
| Parameters: |
| proc: TObjectCacheProc procedure to call |
| param : Integer User parameter to pass to the procedure |
| |
| The function returns the object that caused 'proc' to return with |
| 'continue=False'. You can use this eg. to search the cache. |
*----------------------------------------------------------------------*)
function TObjectCache.ForEach(proc: TObjectCacheProc; param : Integer) : TObject;
var
i : Integer;
continue : boolean;
begin
i := 0;
continue := True;
while continue and (i < fObjects.Count) do
begin
proc (fObjects [i], i, param, continue);
if continue then
Inc (i)
end;
if not continue then
result := fObjects [i]
else
result := Nil
end;
(*----------------------------------------------------------------------*
| function TObjectCache.ForEachIdx |
| |
| Call 'proc' for each object in the cache. nb. this differs from |
| ForEach only in the return value. |
| |
| Parameters: |
| proc: TObjectCacheProc procedure to call |
| param : Integer User parameter to pass to the procedure |
| |
| The function returns the index of the object that caused 'proc' |
| to return with 'continue=False'. You can use this eg. to search the |
| cache. |
*----------------------------------------------------------------------*)
function TObjectCache.ForEachIdx(proc: TObjectCacheProc;
param: Integer): Integer;
var
i : Integer;
continue : boolean;
begin
i := 0;
continue := True;
while continue and (i < fObjects.Count) do
begin
proc (fObjects [i], i, param, continue);
if continue then
Inc (i)
end;
if not continue then
result := i
else
result := -1
end;
(*----------------------------------------------------------------------*
| function TObjectCache.GetCapacity |
| |
| Return the (preferred) capacity of the cache. |
*----------------------------------------------------------------------*)
function TObjectCache.GetCapacity: Integer;
begin
result := fOrigCapacity
end;
(*----------------------------------------------------------------------*
| function TObjectCache.GetCount |
| |
| Returns the number of cached objects |
*----------------------------------------------------------------------*)
function TObjectCache.GetCount: Integer;
begin
result := fObjects.Count;
end;
(*----------------------------------------------------------------------*
| function TObjectCache.GetOwnsObjects |
| |
| Returns the 'OwnsObjects' state of the cache. |
*----------------------------------------------------------------------*)
function TObjectCache.GetOwnsObjects: boolean;
begin
result := fObjects.OwnsObjects;
end;
(*----------------------------------------------------------------------*
| function TObjectCache.IndexOfObject |
| |
| Returns the index of an object in the cache |
*----------------------------------------------------------------------*)
function TObjectCache.IndexOfObject(AObject: TObject): Integer;
var
i, c : Integer;
begin
result := -1;
c := fObjects.Count;
for i := 0 to c - 1 do
if Matches (fObjects [i], AObject) then
begin
result := i;
break
end;
end;
(*----------------------------------------------------------------------*
| function TObjectCache.Matches |
| |
| Return 'True' if ObjA matches ObB. Override this to provide more |
| complicated matching of objects. |
*----------------------------------------------------------------------*)
function TObjectCache.Matches(ObjA, ObjB: TObject): boolean;
begin
result := ObjA = ObjB;
end;
(*----------------------------------------------------------------------*
| function TObjectCache.ObjectAt |
| |
| Return the idx'th object in the cache |
*----------------------------------------------------------------------*)
function TObjectCache.ObjectAt(idx: Integer): TObject;
begin
result := fObjects [idx]
end;
(*----------------------------------------------------------------------*
| procedure TObjectCache.Remove |
| |
| Remove an object from the cache. nb. Even if OwnsObjects is True |
| the object isn't deleted. |
*----------------------------------------------------------------------*)
function TObjectCache.Pop: TObject;
begin
if Count > 0 then
begin
result := fObjects [0];
Extract (result)
end
else
result := Nil
end;
(*----------------------------------------------------------------------*
| TObjectCache.Push |
| |
| Alias for 'Add' - see above. |
*----------------------------------------------------------------------*)
procedure TObjectCache.Push(AObject: TObject);
begin
Add (AObject);
end;
(*----------------------------------------------------------------------*
| procedure TObjectCache.Remove |
| |
| Remove an object from the cache |
*----------------------------------------------------------------------*)
procedure TObjectCache.Remove(AObject: TObject);
begin
if (fObjects.Count > 0) and CanRemove (AObject) then
fObjects.Remove(AObject)
end;
(*----------------------------------------------------------------------*
| prcoedure TObjectCache.SetCapacity |
| |
| Set the (preferred) capacity of the cache |
*----------------------------------------------------------------------*)
procedure TObjectCache.SetCapacity(const Value: Integer);
begin
if Value <> fOrigCapacity then
begin
while fObjects.Count > Value do
fObjects.Delete(fObjects.Count - 1);
fObjects.Capacity := Value;
fOrigCapacity := Value
end
end;
(*----------------------------------------------------------------------*
| procedure TObjectCache.SetOwnsObjects |
| |
| If 'OwnsObjects' is true, the object cache assumes responsibility |
| for deleting objects added to it (with Add or Push). Whenever |
| objects are removed from the cache, either with 'Remove' or because |
| the cache overflowed, the get deleted (freed). |
*----------------------------------------------------------------------*)
procedure TObjectCache.SetOwnsObjects(const Value: boolean);
begin
fObjects.OwnsObjects := Value
end;
{ TClassAssociations }
// TClassAssociations allows you to associate a class with another class.
// eg. you could associate a TGraphicsForm with TGraphic, etc.
//
// TClassAssociations support inheritance, so as TIcon derives from
// TGraphic, then TGraphicsForm will be returned for TIcon - unless a
// separate TIconForm is registered for TIcon.
(*----------------------------------------------------------------------*
| TClassAssociations.Associate |
| |
| Associate ClassA with ClassB |
| |
| Parameters: |
| classA, classB: TClass The classes to associate |
*----------------------------------------------------------------------*)
procedure TClassAssociations.Associate(classA, classB: TClass);
var
i : Integer;
begin
i := IndexOf [classA, classB];
if i = -1 then
fAssociations.Insert(0, TClassAssociation.Create(classA, classB));
end;
(*----------------------------------------------------------------------*
| constructor TClassAssociations.Create |
*----------------------------------------------------------------------*)
constructor TClassAssociations.Create;
begin
fAssociations := TObjectList.Create;
end;
(*----------------------------------------------------------------------*
| destructor TClassAssociations.Destroy |
*----------------------------------------------------------------------*)
destructor TClassAssociations.Destroy;
begin
fAssociations.Free;
inherited;
end;
(*----------------------------------------------------------------------*
| procedure TClassAssociations.DisAssociate |
| |
| Remove the association between classA and classB |
*----------------------------------------------------------------------*)
procedure TClassAssociations.DisAssociate(classA, classB: TClass);
var
idx : Integer;
begin
idx := IndexOf [classA, classB];
if idx >= 0 then
fAssociations.Delete(idx);
end;
(*----------------------------------------------------------------------*
| TClassAssociations.FindClassAFor |
| |
| eg. FindClassAFor (TGraphicsForm) will return TGraphic. Note that |
| this way round there is no inheritance. There's either an |
| association or there's not. |
| |
| Parameters: |
| classB: TClass The ClassB to find. |
| |
| The function returns the classA that matches classB |
*----------------------------------------------------------------------*)
function TClassAssociations.FindClassAFor(classB: TClass): TClass;
var
idx : Integer;
begin
idx := IndexOfClassB [classB];
if idx >= 0 then
result := Association [idx].ClassA
else
result := Nil
end;
(*----------------------------------------------------------------------*
| function TClassAssociations.FindClassBFor |
| |
| eg. FindClassAFor (TGraphic) will return TGraphicForm. |
| |
| nb. this supports inheritance, so as TIcon derives from TGraphic, |
| TGraphicsForm will be returned for TIcon - unless a separate |
| TIconForm is registered for TIcon. |
| |
| Parameters: |
| classA: TClass The ClassA to find |
| |
| The function returns the classB that matches classA. If no match is |
| found, classA's Ancestor classes are searched too. |
*----------------------------------------------------------------------*)
function TClassAssociations.FindClassBFor(classA: TClass): TClass;
var
idx : Integer;
begin
idx := IndexOfClassA [classA];
if idx >= 0 then
result := Association [idx].ClassB
else
result := Nil
end;
(*----------------------------------------------------------------------*
| function TClassAssociations.GetAssociation |
| |
| 'Get' method for Association property |
*----------------------------------------------------------------------*)
function TClassAssociations.GetAssociation(
idx: Integer): TClassAssociation;
begin
result := TClassAssociation (fAssociations [idx]);
end;
(*----------------------------------------------------------------------*
| function TClassAssociations.GetCount |
| |
| 'Get' method for Count property |
*----------------------------------------------------------------------*)
function TClassAssociations.GetCount: Integer;
begin
result := fAssociations.Count;
end;
function TClassAssociations.GetIndexOf(classA, classB: TClass): Integer;
var
i : Integer;
ass : TClassAssociation;
begin
result := -1;
for i := 0 to Count - 1 do
begin
ass := Association [i];
if (ass.ClassA = classA) and (ass.ClassB = classB) then
begin
result := i;
break
end
end
end;
function TClassAssociations.GetIndexOfClassA(classA: TClass): Integer;
var
i : Integer;
ass : TClassAssociation;
begin
result := -1;
while (result = -1) and Assigned (classA) do
begin
for i := 0 to Count - 1 do
begin
ass := Association [i];
if ass.ClassA = classA then
begin
result := i;
break
end
end;
if result = -1 then
classA := classA.ClassParent
end
end;
function TClassAssociations.GetIndexOfClassB(classB: TClass): Integer;
var
i : Integer;
ass : TClassAssociation;
begin
result := -1;
for i := 0 to Count - 1 do
begin
ass := Association [i];
if ass.ClassB = classB then
begin
result := i;
break
end
end
end;
{ TClassAssociation }
constructor TClassAssociation.Create(AClassA, AClassB: TClass);
begin
fClassA := AClassA;
fClassB := AClassB
end;
{ TClassStringAssociations }
procedure TClassStringAssociations.Associate(const st: string; cls: TClass);
var
i : Integer;
begin
i := IndexOf [st, cls];
if i = -1 then
fAssociations.InsertObject (0, st, TObject (cls))
end;
constructor TClassStringAssociations.Create;
begin
fAssociations := TStringList.Create;
end;
destructor TClassStringAssociations.Destroy;
begin
fAssociations.Free;
inherited;
end;
procedure TClassStringAssociations.DisAssociate(const st: string;
cls: TClass);
var
idx : Integer;
begin
idx := IndexOf [st, cls];
if idx >= 0 then
fAssociations.Delete(idx);
end;
function TClassStringAssociations.FindClassFor(const st: string): TClass;
var
idx : Integer;
begin
idx := fAssociations.IndexOf (st);
if idx >= 0 then
result := TClass (fAssociations.Objects [idx])
else
result := Nil
end;
function TClassStringAssociations.FindStringFor(cls: TClass): string;
var
i : Integer;
begin
result := '';
for i := 0 to Count - 1 do
if TClass (fAssociations.Objects [i]) = cls then
begin
result := fAssociations [i];
break
end
end;
function TClassStringAssociations.GetClass(idx: Integer): TClass;
begin
result := TClass (fAssociations.Objects [idx])
end;
function TClassStringAssociations.GetCount: Integer;
begin
result := fAssociations.Count
end;
function TClassStringAssociations.GetIndexOf(const st: string;
cls: TClass): Integer;
var
i : Integer;
begin
result := -1;
for i := 0 to Count - 1 do
if (fAssociations.Objects [i] = TObject (cls)) and SameText (st, fAssociations [i]) then
begin
result := i;
break
end
end;
function TClassStringAssociations.GetString(idx: Integer): string;
begin
result := fAssociations [idx];
end;
{ TObjectProcessor }
procedure TObjectProcessor.AddObjectToQueue(obj: TObject);
begin
fSync.Enter;
try
fObjects.Add(obj);
if fState = opsIdle then
fSignal.SetEvent;
finally
fSync.Leave
end
end;
procedure TObjectProcessor.Clear;
var
i : Integer;
begin
fSync.Enter;
try
for i := 0 to fObjects.Count - 1 do
Reset (fObjects [i]);
fObjects.Clear;
finally
fSync.Leave
end
end;
constructor TObjectProcessor.Create;
begin
fSync := TCriticalSection.Create;
fSignal := TEvent.Create (Nil, false, false, '');
fObjects := TObjectList.Create;
fObjects.OwnsObjects := False;
inherited Create (false);
end;
destructor TObjectProcessor.Destroy;
begin
fSync.Free;
fSignal.Free;
inherited;
end;
procedure TObjectProcessor.Execute;
begin
while not Terminated do
begin
try
if fObjects.Count = 0 then
fSignal.WaitFor(INFINITE);
fState := opsBusy;
try
while not Terminated and (fObjects.Count > 0) do
begin
fSync.Enter;
try
if fObjects.Count > 0 then
begin
Process (fObjects [0]);
fObjects.Delete(0)
end
finally
fSync.Leave
end;
end;
if not Terminated then
ObjectsProcessed;
finally
fState := opsIdle
end
except
try
Clear
except
end
end
end
end;
function TObjectProcessor.GetCount: Integer;
begin
result := fObjects.Count
end;
function TObjectProcessor.GetOwnsObjects: boolean;
begin
result := fObjects.OwnsObjects
end;
procedure TObjectProcessor.ObjectsProcessed;
begin
// Stub - called when a batch of objects has been processed
end;
procedure TObjectProcessor.Process(obj: TObject);
begin
// Stub - called to process each object
end;
procedure TObjectProcessor.Reset(obj: TObject);
begin
// Stub - called when un-processed objects are removed from the queue (by Clear)
end;
procedure TObjectProcessor.SetOwnsObjects(const Value: boolean);
begin
fObjects.OwnsObjects := Value
end;
procedure TObjectProcessor.Terminate;
begin
Clear;
inherited Terminate;
fSignal.SetEvent;
WaitFor
end;
{ TLog }
procedure TLog.Add(const st: string);
begin
Lock;
try
fStrings.Add(st);
LimitCapacity
finally
Unlock
end
end;
procedure TLog.Clear;
begin
Lock;
try
fStrings.Clear
finally
Unlock
end
end;
destructor TLog.Destroy;
begin
fLock.Free;
fStrings.Free;
inherited;
end;
function TLog.GetStrings(idx: Integer): string;
begin
if not fLocked then
raise Exception.Create ('Must call LockGetCount');
result := fStrings [idx];
end;
procedure TLog.Init;
begin
if not Assigned (fStrings) then
fStrings := TStringList.Create;
if not Assigned (fLock) then
fLock := TCriticalSection.Create;
end;
procedure TLog.LimitCapacity;
var
needLock : boolean;
begin
if fCapacity < 1 then
Exit;
needLock := not fInLock;
if needLock then
Lock;
try
while fStrings.Count > fCapacity do
fStrings.Delete(0);
finally
if needLock then
Unlock
end
end;
procedure TLog.Lock;
begin
Init;
fLock.Enter;
fInLock := True;
end;
function TLog.LockGetCount: Integer;
begin
Lock;
fLocked := True;
result := fStrings.Count
end;
procedure TLog.SetCapacity(const Value: Integer);
begin
if Value <> fCapacity then
begin
fCapacity := Value;
LimitCapacity
end
end;
procedure TLog.Unlock;
begin
fLock.Leave;
fLocked := False;
fInLock := False;
end;
end.
|
unit Vector3bComparatorTest;
{$mode objfpc}{$H+}
{$CODEALIGN LOCALMIN=16}
interface
uses
Classes, SysUtils, fpcunit, testregistry, BaseTestCase,
native, BZVectorMath;
type
{ TVector3bComparatorTest }
TVector3bComparatorTest = class(TByteVectorBaseTestCase)
published
procedure TestCompare;
procedure TestCompareFalse;
procedure TestOpAdd;
procedure TestOpAddByte;
procedure TestOpSub;
procedure TestOpSubByte;
procedure TestOpMul;
procedure TestOpMulByte;
procedure TestOpMulSingle;
procedure TestOpDiv;
procedure TestOpDivByte;
procedure TestOpEquality;
procedure TestOpNotEquals;
procedure TestOpAnd;
procedure TestOpAndByte;
procedure TestOpOr;
procedure TestOpOrByte;
procedure TestOpXor;
procedure TestOpXorByte;
procedure TestSwizzle;
end;
implementation
procedure TVector3bComparatorTest.TestCompare;
begin
AssertTrue('Test Values do not match'+nbt1.ToString+' --> '+abt1.ToString, Compare(nbt1,abt1));
end;
procedure TVector3bComparatorTest.TestCompareFalse;
begin
AssertFalse('Test Values should not match'+nbt1.ToString+' --> '+abt2.ToString, Compare(nbt1,abt2));
end;
procedure TVector3bComparatorTest.TestOpAdd;
begin
nbt3 := nbt1 + nbt2;
abt3 := abt1 + abt2;
AssertTrue('Vector + Vector no match'+nbt3.ToString+' --> '+abt3.ToString, Compare(nbt3,abt3));
end;
procedure TVector3bComparatorTest.TestOpAddByte;
begin
nbt3 := nbt1 + b1;
abt3 := abt1 + b1;
AssertTrue('Vector + Byte no match'+nbt3.ToString+' --> '+abt3.ToString, Compare(nbt3,abt3));
end;
procedure TVector3bComparatorTest.TestOpSub;
begin
nbt3 := nbt1 - nbt2;
abt3 := abt1 - abt2;
AssertTrue('Vector - Vector no match'+nbt3.ToString+' --> '+abt3.ToString, Compare(nbt3,abt3));
end;
procedure TVector3bComparatorTest.TestOpSubByte;
begin
nbt3 := nbt1 - b1;
abt3 := abt1 - b1;
AssertTrue('Vector - Byte no match'+nbt3.ToString+' --> '+abt3.ToString, Compare(nbt3,abt3));
end;
procedure TVector3bComparatorTest.TestOpMul;
begin
nbt3 := nbt1 * nbt2;
abt3 := abt1 * abt2;
AssertTrue('Vector * Vector no match'+nbt3.ToString+' --> '+abt3.ToString, Compare(nbt3,abt3));
end;
procedure TVector3bComparatorTest.TestOpMulByte;
begin
nbt3 := nbt1 * b1;
abt3 := abt1 * b1;
AssertTrue('Vector * Byte no match'+nbt3.ToString+' --> '+abt3.ToString, Compare(nbt3,abt3));
end;
procedure TVector3bComparatorTest.TestOpMulSingle;
begin
nbt3 := nbt1 * fs1;
abt3 := abt1 * fs1;
AssertTrue('Vector * Single no match'+nbt3.ToString+' --> '+abt3.ToString, Compare(nbt3,abt3));
end;
procedure TVector3bComparatorTest.TestOpDiv;
begin
nbt3 := nbt1 Div nbt2;
abt3 := abt1 Div abt2;
AssertTrue('Vector Div Vector no match'+nbt3.ToString+' --> '+abt3.ToString, Compare(nbt3,abt3));
end;
procedure TVector3bComparatorTest.TestOpDivByte;
begin
nbt3 := nbt1 Div b1;
abt3 := abt1 Div b1;
AssertTrue('Vector Div Byte no match'+nbt3.ToString+' --> '+abt3.ToString, Compare(nbt3,abt3));
end;
procedure TVector3bComparatorTest.TestOpEquality;
begin
nb := nbt1 = nbt1;
ab := abt1 = abt1;
AssertTrue('Vector = do not match'+nb.ToString+' --> '+ab.ToString, (nb = ab));
nb := nbt1 = nbt2;
ab := abt1 = abt2;
AssertTrue('Vector = should not match'+nb.ToString+' --> '+ab.ToString, (nb = ab));
end;
procedure TVector3bComparatorTest.TestOpNotEquals;
begin
nb := nbt1 = nbt1;
ab := abt1 = abt1;
AssertTrue('Vector <> do not match'+nb.ToString+' --> '+ab.ToString, (nb = ab));
nb := nbt1 = nbt2;
ab := abt1 = abt2;
AssertTrue('Vector <> should not match'+nb.ToString+' --> '+ab.ToString, (nb = ab));
end;
procedure TVector3bComparatorTest.TestOpAnd;
begin
nbt3 := nbt1 and nbt2;
abt3 := abt1 and abt2;
AssertTrue('Vector And Vector no match'+nbt3.ToString+' --> '+abt3.ToString, Compare(nbt3,abt3));
end;
procedure TVector3bComparatorTest.TestOpAndByte;
begin
nbt3 := nbt1 and b5;
abt3 := abt1 and b5;
AssertTrue('Vector And Byte no match'+nbt3.ToString+' --> '+abt3.ToString, Compare(nbt3,abt3));
end;
procedure TVector3bComparatorTest.TestOpOr;
begin
nbt3 := nbt1 or nbt2;
abt3 := abt1 or abt2;
AssertTrue('Vector Or Vector no match'+nbt3.ToString+' --> '+abt3.ToString, Compare(nbt3,abt3));
end;
procedure TVector3bComparatorTest.TestOpOrByte;
begin
nbt3 := nbt1 or b1;
abt3 := abt1 or b1;
AssertTrue('Vector Or Byte no match'+nbt3.ToString+' --> '+abt3.ToString, Compare(nbt3,abt3));
end;
procedure TVector3bComparatorTest.TestOpXor;
begin
nbt3 := nbt1 xor nbt2;
abt3 := abt1 xor abt2;
AssertTrue('Vector Xor Vector no match'+nbt3.ToString+' --> '+abt3.ToString, Compare(nbt3,abt3));
end;
procedure TVector3bComparatorTest.TestOpXorByte;
begin
nbt3 := nbt1 xor b1;
abt3 := abt1 xor b1;
AssertTrue('Vector Xor Byte no match'+nbt3.ToString+' --> '+abt3.ToString, Compare(nbt3,abt3));
end;
procedure TVector3bComparatorTest.TestSwizzle;
begin
nbt3 := nbt1.Swizzle(swBRG);
abt3 := abt1.Swizzle(swBRG);
AssertTrue('Vector Swizzle no match'+nbt3.ToString+' --> '+abt3.ToString, Compare(nbt3,abt3));
end;
initialization
RegisterTest(REPORT_GROUP_VECTOR3B, TVector3bComparatorTest);
end.
|
unit forControlImage;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, ComCtrls, ExtCtrls, LibGfl;
//function IntToPixelFormat(ImagePixelFormat: Integer): TPixelFormat;
{function OpenImage (filename: String): TBitmap;
procedure CloneImage (Original: PGFL_BITMAP);
procedure UndoImage (Original: PGFL_BITMAP);
procedure RedoImage (Original: PGFL_BITMAP);
function RePaintOriginal (Original: PGFL_BITMAP): TBitmap;
function CloneBMP (gfl_bmp: PGFL_BITMAP): TBitmap;
function SaveImageInMem (ImageHandle: Pointer): TBitmap;
function gfl2bmp (gfl_bmp: PGFL_BITMAP): TBitmap;
var GflFilterString : String;
WidthImage, HeightImage: Integer;
OriginalBMP, ClonBitmap, UndoBitmap, RedoBitmap: PGFL_BITMAP;
}
implementation
{
function OpenImage (filename: String): TBitmap;
var
finfo: TGFL_FILE_INFORMATION;
lp: TGFL_LOAD_PARAMS;
gfl_bmp: PGFL_BITMAP;
e: GFL_ERROR;
bmp: TBitmap;
x, y, k: Integer;
LineSrc: Pointer;
LineDest: Pointer;
//LineIn: PLine1;
LineOut: PByteArray;
Mask1: Byte;
Mask: Byte;
pal: PLogPalette;
i, ImagePixelFormat: Integer;
Arect: TRect;
begin
gflEnableLZW(GFL_TRUE);
gflGetDefaultLoadParams(lp);
lp.ColorModel := GFL_BGR;
//lp.ColorModel := GFL_BGRA;
//lp.Flags := GFL_LOAD_FORCE_COLOR_MODEL;
e := gflLoadBitmap(PChar(filename), gfl_bmp, lp, finfo);
//ERROR
if (e <> gfl_no_error) then begin
MessageDlg('File not readable: ' + string(gflGetErrorString(e)), mtError, [mbOK], 0);
exit;
end;
if (gfl_bmp.Btype = GFL_BINARY) then begin
ImagePixelFormat := 1;
end else begin
ImagePixelFormat := gfl_bmp.BytesPerPixel * 8;
end;
if not (ImagePixelFormat in [1, 4, 8, 24, 32]) then begin
MessageDlg('Only 1, 4, 8, 24 or 32 BitsPerPixel are supported in this demo !', mtError, [mbOK], 0);
gflFreeBitmap(gfl_bmp);
exit;
end;
// Create Delphi Bitmap. If paletted, minimize memory by setting size after pixel format
bmp := TBitmap.Create;
//bmp.PixelFormat := IntToPixelFormat(ImagePixelFormat);
bmp.Width := gfl_bmp.Width;
bmp.Height := gfl_bmp.Height;
WidthImage := gfl_bmp.Width;
HeightImage := gfl_bmp.Height;
//NewPalette := 0;
OriginalBMP := gflCloneBitmap(gfl_bmp);
//gflBrightness(OriginalBMP, nil, 100);
case bmp.PixelFormat of
pf1bit: begin end;
pf4Bit: begin end;
pf8Bit: begin end;
pf24Bit, pf32Bit:
begin
for y := 0 to gfl_bmp.Height - 1 do begin
// get Pointer to Scanlines
lineSrc := Pointer(Integer(gfl_bmp.data) + (y * gfl_bmp.BytesPerLine));
lineDest := bmp.Scanline[y];
// copy Pixel Data
move(lineSrc^, lineDest^, gfl_bmp.BytesPerLine);
end;
Result := bmp;
end;
end; {case pixelformat}
//end;
{
function SaveImage (filename: String): TBitmap;
var
finfo: TGFL_FILE_INFORMATION;
lp: TGFL_LOAD_PARAMS;
gfl_bmp: PGFL_BITMAP;
e: GFL_ERROR;
bmp: TBitmap;
x, y, k: Integer;
LineSrc: Pointer;
LineDest: Pointer;
//LineIn: PLine1;
LineOut: PByteArray;
Mask1: Byte;
Mask: Byte;
pal: PLogPalette;
i, ImagePixelFormat: Integer;
Arect: TRect;
begin
gflEnableLZW(GFL_TRUE);
gflGetDefaultLoadParams(lp);
lp.ColorModel := GFL_BGR;
//lp.ColorModel := GFL_BGRA;
//lp.Flags := GFL_LOAD_FORCE_COLOR_MODEL;
e := gflLoadBitmap(PChar(filename), gfl_bmp, lp, finfo);
//ERROR
if (e <> gfl_no_error) then begin
MessageDlg('File not readable: ' + string(gflGetErrorString(e)), mtError, [mbOK], 0);
exit;
end;
if (gfl_bmp.Btype = GFL_BINARY) then begin
ImagePixelFormat := 1;
end else begin
ImagePixelFormat := gfl_bmp.BytesPerPixel * 8;
end;
if not (ImagePixelFormat in [1, 4, 8, 24, 32]) then begin
MessageDlg('Only 1, 4, 8, 24 or 32 BitsPerPixel are supported in this demo !', mtError, [mbOK], 0);
gflFreeBitmap(gfl_bmp);
exit;
end;
// Create Delphi Bitmap. If paletted, minimize memory by setting size after pixel format
bmp := TBitmap.Create;
bmp.PixelFormat := IntToPixelFormat(ImagePixelFormat);
bmp.Width := gfl_bmp.Width;
bmp.Height := gfl_bmp.Height;
WidthImage := gfl_bmp.Width;
HeightImage := gfl_bmp.Height;
//NewPalette := 0;
OriginalBMP := gflCloneBitmap(gfl_bmp);
//gflBrightness(OriginalBMP, nil, 100);
case bmp.PixelFormat of
pf1bit: begin end;
pf4Bit: begin end;
pf8Bit: begin end;
pf24Bit, pf32Bit:
begin
for y := 0 to gfl_bmp.Height - 1 do begin
// get Pointer to Scanlines
lineSrc := Pointer(Integer(gfl_bmp.data) + (y * gfl_bmp.BytesPerLine));
lineDest := bmp.Scanline[y];
// copy Pixel Data
move(lineSrc^, lineDest^, gfl_bmp.BytesPerLine);
end;
Result := bmp;
end;
end;
end;
procedure CloneImage (Original: PGFL_BITMAP);
begin
ClonBitmap := gflCloneBitmap(Original);
end;
procedure UndoImage (Original: PGFL_BITMAP);
begin
UndoBitmap := gflCloneBitmap(Original);
end;
}
// Это не обязательно, можно обойтись только Undo
{procedure RedoImage (Original: PGFL_BITMAP);
begin
RedoBitmap := gflCloneBitmap(Original);
RedoBitmap.Width := Original.Width;
RedoBitmap.Height := Original.Height;
end;
function RePaintOriginal (Original: PGFL_BITMAP): TBitmap;
var
bmp: TBitmap;
y, ImagePixelFormat: Integer;
LineSrc: Pointer;
LineDest: Pointer;
begin
if (Original.Btype = GFL_BINARY) then begin
ImagePixelFormat := 1;
end else begin
ImagePixelFormat := Original.BytesPerPixel * 8;
end;
if not (ImagePixelFormat in [1, 4, 8, 24, 32]) then begin
MessageDlg('Only 1, 4, 8, 24 or 32 BitsPerPixel are supported in this demo !', mtError, [mbOK], 0);
gflFreeBitmap(Original);
exit;
end;
bmp := TBitmap.Create;
//bmp.PixelFormat := IntToPixelFormat(ImagePixelFormat);
bmp.Width := Original.Width;
bmp.Height := Original.Height;
case bmp.PixelFormat of
pf1bit: begin end;
pf4Bit: begin end;
pf8Bit: begin end;
pf24Bit, pf32Bit:
begin
for y := 0 to Original.Height - 1 do begin
lineSrc := Pointer(Integer(Original.data) + (y * Original.BytesPerLine));
lineDest := bmp.Scanline[y];
move(lineSrc^, lineDest^, Original.BytesPerLine);
end;
Result := bmp;
end;
end;
end;
function CloneBMP (gfl_bmp: PGFL_BITMAP): TBitmap;
var
bmp: TBitmap;
y, ImagePixelFormat: Integer;
LineSrc: Pointer;
LineDest: Pointer;
begin
if (gfl_bmp.Btype = GFL_BINARY) then begin
ImagePixelFormat := 1;
end else begin
ImagePixelFormat := gfl_bmp.BytesPerPixel * 8;
end;
if not (ImagePixelFormat in [1, 4, 8, 24, 32]) then begin
MessageDlg('Only 1, 4, 8, 24 or 32 BitsPerPixel are supported in this demo !', mtError, [mbOK], 0);
//gflFreeBitmap(gfl_bmp);
exit;
end;
bmp := TBitmap.Create;
bmp.PixelFormat := IntToPixelFormat(ImagePixelFormat);
bmp.Width := gfl_bmp.Width;
bmp.Height := gfl_bmp.Height;
case bmp.PixelFormat of
pf1bit: begin end;
pf4Bit: begin end;
pf8Bit: begin end;
pf24Bit, pf32Bit:
begin
for y := 0 to gfl_bmp.Height - 1 do begin
// get Pointer to Scanlines
lineSrc := Pointer(Integer(gfl_bmp.data) + (y * gfl_bmp.BytesPerLine));
lineDest := bmp.Scanline[y];
// copy Pixel Data
move(lineSrc^, lineDest^, gfl_bmp.BytesPerLine);
end;
Result := bmp;
end;
end;
end;
function SaveImageInMem (ImageHandle: Pointer): TBitmap;
var
finfo: TGFL_FILE_INFORMATION;
lp: TGFL_LOAD_PARAMS;
gfl_bmp: PGFL_BITMAP;
e: GFL_ERROR;
bmp: TBitmap;
x, y, k: Integer;
LineSrc: Pointer;
LineDest: Pointer;
//LineIn: PLine1;
LineOut: PByteArray;
Mask1: Byte;
Mask: Byte;
pal: PLogPalette;
i, ImagePixelFormat: Integer;
Arect: TRect;
begin
gflEnableLZW(GFL_TRUE);
gflGetDefaultLoadParams(lp);
lp.ColorModel := GFL_BGR;
//lp.ColorModel := GFL_BGRA;
//lp.Flags := GFL_LOAD_FORCE_COLOR_MODEL;
e := gflLoadBitmapFromHandle(ImageHandle, gfl_bmp, lp, finfo);
//ERROR
if (e <> gfl_no_error) then begin
MessageDlg('File not readable: ' + string(gflGetErrorString(e)), mtError, [mbOK], 0);
exit;
end;
if (gfl_bmp.Btype = GFL_BINARY) then begin
ImagePixelFormat := 1;
end else begin
ImagePixelFormat := gfl_bmp.BytesPerPixel * 8;
end;
if not (ImagePixelFormat in [1, 4, 8, 24, 32]) then begin
MessageDlg('Only 1, 4, 8, 24 or 32 BitsPerPixel are supported in this demo !', mtError, [mbOK], 0);
gflFreeBitmap(gfl_bmp);
exit;
end;
// Create Delphi Bitmap. If paletted, minimize memory by setting size after pixel format
bmp := TBitmap.Create;
bmp.PixelFormat := IntToPixelFormat(ImagePixelFormat);
bmp.Width := gfl_bmp.Width;
bmp.Height := gfl_bmp.Height;
WidthImage := gfl_bmp.Width;
HeightImage := gfl_bmp.Height;
//NewPalette := 0;
case bmp.PixelFormat of
pf1bit: begin end;
pf4Bit: begin end;
pf8Bit: begin end;
pf24Bit, pf32Bit:
begin
for y := 0 to gfl_bmp.Height - 1 do begin
// get Pointer to Scanlines
lineSrc := Pointer(Integer(gfl_bmp.data) + (y * gfl_bmp.BytesPerLine));
lineDest := bmp.Scanline[y];
// copy Pixel Data
move(lineSrc^, lineDest^, gfl_bmp.BytesPerLine);
end;
Result := bmp;
end;
end; {case pixelformat} {
end;
function gfl2bmp (gfl_bmp: PGFL_BITMAP): TBitmap;
var
bmp: TBitmap;
y, ImagePixelFormat: Integer;
LineSrc: Pointer;
LineDest: Pointer;
begin
if (gfl_bmp.Btype = GFL_BINARY) then begin
ImagePixelFormat := 1;
end else begin
ImagePixelFormat := gfl_bmp.BytesPerPixel * 8;
end;
if not (ImagePixelFormat in [1, 4, 8, 24, 32]) then begin
MessageDlg('Only 1, 4, 8, 24 or 32 BitsPerPixel are supported in this demo !', mtError, [mbOK], 0);
gflFreeBitmap(gfl_bmp);
exit;
end;
bmp := TBitmap.Create;
bmp.PixelFormat := IntToPixelFormat(ImagePixelFormat);
bmp.Width := gfl_bmp.Width;
bmp.Height := gfl_bmp.Height;
case bmp.PixelFormat of
pf1bit: begin end;
pf4Bit: begin end;
pf8Bit: begin end;
pf24Bit, pf32Bit:
begin
for y := 0 to gfl_bmp.Height - 1 do begin
lineSrc := Pointer(Integer(gfl_bmp.data) + (y * gfl_bmp.BytesPerLine));
lineDest := bmp.Scanline[y];
move(lineSrc^, lineDest^, gfl_bmp.BytesPerLine);
end;
Result := bmp;
end;
end;
end;
}
end.
|
unit aOPCTCPSource;
interface
uses
SysUtils, Classes,
DateUtils, SyncObjs,
aCustomOPCSource, aOPCSource,
IdTCPClient, IdGlobal, IdException, IdExceptionCore
, IdIOHandler, IdIOHandlerSocket, IdSSLOpenSSL
, aDCIntercept
, IdCompressionIntercept
, uDCObjects, uUserMessage, uOPCTCPConnection
, aCustomOPCTCPSource
;
type
TaOPCTCPSource = class(TaCustomOPCTCPSource)
private
// работа с TCP клиентом
function ReadLnCompress: string;
function ReadInteger: integer;
procedure ReadStreamCompress(aStream: TStream; aSize: Int64 = -1);
procedure WriteStream(AStream: TStream);
procedure WriteStreamCompress(AStream: TStream);
function GetPrepValues: string;
//function GetDS: char;
procedure LoadFS;
protected
procedure SetCompressionLevel(const Value: integer); override;
procedure TryConnect; override;
procedure Authorize(aUser: string; aPassword: string); override;
public
constructor Create(aOwner: TComponent); override;
destructor Destroy; override;
function SendModBus(aSystemType: integer; aRequest: string;
aRetByteCount: integer; aTimeOut: integer): string; override;
function SendModBusEx(aConnectionName: string; aRequest: string;
aRetByteCount: integer; aTimeOut: integer): string; override;
//function GetSensorProperties(id: string): TSensorProperties; override; // ?
function GetSensorPropertiesEx(id: string): string; override; // +
function SetSensorPropertiesEx(id: string; sl: TStrings): string; override; // +
function GetValue(PhysID: string; aAsText: Boolean = False): string; override;
function GetUsers: string; override;
function Login(const aUserName, aPassword: string): Boolean; override;
// +
function GetUserPermission(const aUser, aPassword, aObject: String): String; override; // +
function GetClientList: string; override; // +
function GetThreadList: string; override; // +
function GetThreadProp(aThreadName: string): string; override;
function SetThreadState(ConnectionName: string; NewState: boolean): string; override; // +
function SetThreadLock(ConnectionName: string; NewState: boolean): string; override; // +
function GetSensorsReadError: string; override;
function ExecSql(Sql: string): string; override;
function LoadLookup(aName: string; var aTimeStamp: TDateTime): string; override; // +
function DelSensorValue(PhysID: string; Moment: TDateTime): string; override;
function SetSensorValue(PhysID, Value: string; Moment: TDateTime = 0): string; override; // +
function GetSensorValue(PhysID: String; var ErrorCode: integer; var ErrorString: String;
var Moment: TDateTime): string; override;
function GetSensorsValues(PhysIDs: String): string; override; // +
function GetSensorValueOnMoment(PhysID: String; var Moment: TDateTime): string; override; // +
function GetSensorsValueOnMoment(PhysIDs: String; Moment: TDateTime): string; override; // +
function GetPermissions(PhysIDs: string): string; override;
procedure FillSensorsValuesStream(var aValuesStream: TMemoryStream); override; // +
procedure FillHistory(Stream: TStream; SensorID: string; // +
Date1: TDateTime; Date2: TDateTime = 0;
aDataKindSet: TDataKindSet = [dkValue];
aCalcLeftVal: Boolean = True; aCalcRightVal: Boolean = True); override;
procedure FillNameSpaceStrings(aNameSpace: TStrings; aRootID: string = ''; aLevelCount: Integer = 0;
aKinds: TDCObjectKindSet = []); override;
function GetNameSpace(aObjectID: string = ''; aLevelCount: Integer = 0): boolean; override; // +
function CalcVolume(aSensorID: integer; aDate1, aDate2: TDateTime): extended; override;
function GetTimes(aSensorID: Integer; aDate1, aDate2: TDateTime): string; override;
function GetStatistic(aSensorID: string; aDate1, aDate2: TDateTime): string; override;
procedure GetFile(aFileName: string; aStream: TStream); override; // +
procedure UploadFile(aFileName: string; aDestDir: string = ''); override; // +
procedure ChangePassword(aUser, aOldPassword, aNewPassword: string); override; // +
procedure DisconnectUser(aUserGUID: string); override;
procedure SendUserMessage(aUserGUID: string; aMessage: string); override; // +
function GetMessage: TUserMessage; override; // +
end;
implementation
uses
StrUtils, IdTCPConnection,
aOPCLog, aOPCconsts, aOPCUtils,
DC.StrUtils;
{ TaOPCTCPSource }
constructor TaOPCTCPSource.Create(aOwner: TComponent);
begin
inherited Create(aOwner);
ProtocolVersion := 1;
//UpdateMode := umStreamPacket;
end;
function TaOPCTCPSource.DelSensorValue(PhysID: string; Moment: TDateTime): string;
begin
Result := '';
LockConnection;
try
try
DoConnect;
SendCommandFmt('DeleteValue %s;%s', [PhysID, FloatToStr(Moment, OpcFS)]);
Result := ReadLn;
except
on e: EIdException do
if ProcessTCPException(e) then
raise;
end;
finally
UnlockConnection;
end;
end;
destructor TaOPCTCPSource.Destroy;
begin
inherited;
end;
procedure TaOPCTCPSource.DisconnectUser(aUserGUID: string);
begin
{ TODO : TaOPCTCPSource.DisconnectUser is not implemented }
end;
function TaOPCTCPSource.ExecSql(Sql: string): string;
var
I: Integer;
LineCount: integer;
begin
Result := '';
LockConnection;
try
try
DoConnect;
SendCommand('ExecSql ' + Sql);
LineCount := ReadInteger;
for I := 0 to LineCount - 1 do // Iterate
Result := Result + ReadLn + #13#10;
except
on e: EIdException do
if ProcessTCPException(e) then
raise;
end;
finally
UnlockConnection;
end;
end;
//function TaOPCTCPSource.GetDS: char;
//var
// Str: string;
//begin
// Result := FormatSettings.DecimalSeparator;
// LockConnection;
// try
// try
// DoConnect;
// SendCommand('GetDecimalSeparator');
// Str := ReadLn;
// Result := str[1];
// except
// on e: EIdException do
// ProcessTCPException(e);
// end;
// finally
// UnlockConnection;
// end;
//end;
procedure TaOPCTCPSource.GetFile(aFileName: string; aStream: TStream);
var
Size: integer;
begin
LockConnection;
try
Assert(Assigned(aStream), 'Не создан поток');
// if not then
// Exception.Create('Не создан поток');
try
DoConnect;
SendCommand('GetFile '+aFileName);
Size := StrToInt(ExtractParamsFromAnswer(ReadLn, 1));
ReadStreamCompress(aStream, Size);
except
on e: EIdException do
ProcessTCPException(e);
end;
finally
UnlockConnection;
end;
end;
function TaOPCTCPSource.GetPermissions(PhysIDs: string): string;
var
aByteCount: integer;
aStatus: string;
begin
Result := '';
LockConnection;
try
try
DoConnect;
SendCommand('GetPermissions ' + PhysIDs);
aStatus := ReadLn;
// CheckAnswer(aStatus);
if aStatus = sError then
raise EOPCTCPCommandException.Create(ReadLn)
else if aStatus <> sOk then
raise EOPCTCPUnknownAnswerException.Create('Нестандартый ответ на команду');
ReadLn; // количество строк данных
aByteCount := StrToInt(ReadLn); // количество байт данных
// читаем данные
Result := ReadString(aByteCount);
except
on e: EIdException do
if ProcessTCPException(e) then
raise;
end;
finally
UnLockConnection;
end;
end;
function TaOPCTCPSource.GetPrepValues: string;
var
aPosition, aCount: integer;
aSize: integer;
aUnswer: string;
begin
// функция вызаывается после команды подготовки некоторых данных
// (об ошибках чтения, о списке потоков на сервере и т.д)
// в случае большого количества данных,
// функция выполняет выбокру в несколько этапов
// возвращает данные, которые сервер сформировал
// читаем ответ на запрос (типа Get...)
aUnswer := ReadLn;
// в ответе должен быть результат выполнения команды
// и размер софрмированных данных
aSize := StrToInt(ExtractParamsFromAnswer(aUnswer));
if aSize < Connection.IOHandler.MaxLineLength then
begin
// прочитать всю строку
SendCommand('GetPrepValues');
Result := ReadLnCompress;
end
else
begin
Result := '';
aPosition := 1;
// прочитать строку частями по TCPClient.MaxLineLength - 1 байт
aCount := Connection.IOHandler.MaxLineLength - 1;
while aPosition <= aSize do
begin
SendCommand(Format('GetPrepValues %d;%d', [aPosition, aCount]));
Result := Result + ReadLnCompress;
aPosition := aPosition + aCount;
// если это последний кусочек, то у него особый размер
if (aPosition + aCount) > aSize then
aCount := aSize - aPosition + 1;
end;
end;
end;
{
function TaOPCTCPSource.GetSensorProperties(id: string): TSensorProperties;
var
Unswer: string;
begin
LockConnection;
try
try
DoConnect;
SendCommand('GetSensorProperties ' + id);
Unswer := ReadLn;
if LowerCase(Unswer) <> 'ok' then
raise Exception.CreateFmt('Ошибка при получении свойств датчика %s: %s',
[id, Unswer]);
with Result do
begin
Name := ReadLn; // наименование датчика
NameEn := ReadLn; // наименование датчика (латиницей)
FullName := ReadLn; // полное наименование датчика
ThreadName := ReadLn; // имя потока сбора данных
EquipmentPath := ReadLn; // адрес контроллера
Path := ReadLn; // адрес датчика (тега,сигнала)
Id := ReadLn; // идентификатор датчика на сервере
UnitName := ReadLn; // единица измерения
DisplayFormat := ReadLn; // формат представления показаний
CorrectM := ReadLn; // коэффициент умножения
Correct := ReadLn; // константа добавления
Delta := ReadLn; // мёртвая зона (интервал тишины)
Precision := ReadLn; // точность (знаков после запятой)
UpdateInterval := ReadLn; // интервал обновления
MinReadInterval := ReadLn;
// минимальный интервал между чтением показаний
Vn := ReadLn; // номинальная скорость изменения показаний
RefTableName := ReadLn; // ссылка на справочник расшифровки значений
RefAutoFill := ReadLn; // режим автоматического заполнения справочника
UpdateDBInterval := ReadLn; // интервал записи в БД
FuncName := ReadLn; // наименование функции вычисления значения датчика
end;
except
on e: EIdException do
if ProcessTCPException(e) then
raise;
end;
finally
UnlockConnection;
end;
end;
}
function TaOPCTCPSource.GetSensorPropertiesEx(id: string): string;
var
Unswer: string;
sl: TStringList;
begin
Result := '';
LockConnection;
try
try
DoConnect;
SendCommand('GetSensorPropertiesEx ' + id);
Unswer := ReadLn;
if LowerCase(Unswer) <> 'ok' then
raise Exception.CreateFmt('Ошибка при получении свойств датчика %s: %s',
[id, Unswer]);
sl := TStringList.Create;
try
Connection.IOHandler.ReadStrings(sl);
Result := sl.Text;
finally
sl.Free;
end;
except
on e: EIdException do
if ProcessTCPException(e) then
raise;
end;
finally
UnlockConnection;
end;
end;
function TaOPCTCPSource.GetUserPermission(const aUser, aPassword, aObject: String): String;
begin
LockConnection;
try
try
DoConnect;
SendCommandFmt('GetPermission %s;%s;%s', [aUser, aPassword, aObject]);
Result := ExtractParamsFromAnswer(ReadLn);
Authorize(aUser, aPassword);
LoadFS; // 23.09.2011
except
on e: EIdException do
if ProcessTCPException(e) then
raise;
end;
finally
UnlockConnection;
end;
end;
function TaOPCTCPSource.GetUsers: string;
var
i, LineCount: integer;
begin
Result := '';
LockConnection;
try
try
DoConnect;
SendCommand('GetUsers');
LineCount := ReadInteger;
for I := 0 to LineCount - 1 do
Result := Result + ReadLn + #13#10;
except
on e: EIdException do
if ProcessTCPException(e) then
raise;
end;
finally
UnlockConnection;
end;
end;
function TaOPCTCPSource.GetValue(PhysID: string; aAsText: Boolean = False): string;
var
p: integer;
Str: string;
Delimiter: string;
begin
Result := '';
LockConnection;
try
try
DoConnect;
SendCommand('GetValue ' + PhysID);
Str := ReadLn;
//Connection.IOHandler.WriteLn('GetValue ' + PhysID);
//Str := Connection.IOHandler.ReadLn(LF, TimeOut);
// if Connection.IOHandler.ReadLnTimedOut then
// begin
// Result := 'Превышен интервал ожидания ответа';
// Exit;
// end;
Delimiter := LeftStr(Str, 1);
Str := RightStr(Str, length(Str) - 1);
p := Pos(Delimiter, str);
Result := LeftStr(Str, p - 1);
except
on e: EIdException do
ProcessTCPException(e);
end;
finally
UnlockConnection;
end;
end;
procedure TaOPCTCPSource.LoadFS;
var
sl: TStringList;
s: string;
begin
//csTCPCommand.Acquire;
sl := TStringList.Create;
try
try
DoConnect;
SendCommand('GetFS');
s := ReadLn;
//Connection.{$IFDEF INDY100}IOHandler.{$ENDIF}WriteLn('GetFS');
//s := Connection.{$IFDEF INDY100}IOHandler.{$ENDIF}ReadLn(LF, TimeOut);
sl.CommaText := s;
SlToFormatSettings(sl);
except
on e: EIdException do
ProcessTCPException(e);
end;
finally
sl.Free;
//csTCPCommand.Release;
end;
end;
procedure TaOPCTCPSource.SetCompressionLevel(const Value: integer);
begin
if CompressionLevel = Value then
exit;
inherited SetCompressionLevel(Value);
if Connected then
begin
Authorize(User, Password);
LoadFS; // 23.09.2011
end;
end;
function TaOPCTCPSource.SetSensorPropertiesEx(id: string; sl: TStrings): string;
begin
Result := '';
LockConnection;
try
try
DoConnect;
SendCommandFmt('SetSensorPropertiesEx %s', [id]);
Result := ReadLn;
CheckAnswer(Result);
// if AnsiSameText(Result,'ok') then
// begin
Connection.IOHandler.Write(sl, true);
Result := ReadLn;
// end;
except
on e: EIdException do
if ProcessTCPException(e) then
raise;
end;
finally
UnlockConnection;
end;
end;
function TaOPCTCPSource.SetSensorValue(PhysID, Value: string;
Moment: TDateTime): string;
begin
Result := '';
LockConnection;
try
try
DoConnect;
SendCommandFmt('SetValue %s;%s;%s', [PhysID, Value, FloatToStr(Moment, OpcFS)]);
Result := ReadLn;
except
on e: EIdException do
if ProcessTCPException(e) then
raise;
end;
finally
UnlockConnection;
end;
end;
function TaOPCTCPSource.GetSensorValue(PhysID: String;
var ErrorCode: integer; var ErrorString: String;
var Moment: TDateTime): string;
var
p: integer;
Str: string;
Delimiter: string;
begin
LockConnection;
try
try
DoConnect;
SendCommand('GetValue ' + PhysID);
Str := ReadLn;
except
on e: EIdException do
if ProcessTCPException(e) then
raise;
end;
Delimiter := LeftStr(Str, 1);
Str := RightStr(Str, length(Str) - 1);
// Value (Result)
p := Pos(Delimiter, str);
Result := LeftStr(Str, p - 1);
Str := RightStr(Str, length(Str) - p);
// ErrorCode
if ProtocolVersion > 0 then
begin
p := Pos(Delimiter, str);
ErrorCode := StrToIntDef(LeftStr(Str, p - 1), 0);
Str := RightStr(Str, length(Str) - p);
end;
// ErrorString
p := Pos(Delimiter, str);
ErrorString := LeftStr(Str, p - 1);
Str := RightStr(Str, length(Str) - p);
if ProtocolVersion = 0 then
begin
if ErrorString <> '' then
ErrorCode := -2
else
ErrorCode := 0;
end;
// Moment
Moment := StrToDateTime(Str, OpcFS);
finally
UnlockConnection;
end;
end;
function TaOPCTCPSource.GetClientList: string;
var
i, LineCount: integer;
s: String;
begin
Result := '';
LockConnection;
try
try
DoConnect;
if ServerVer > 0 then
SendCommand('GetClientList1')
else
SendCommand('GetClientList');
LineCount := ReadInteger;
for I := 0 to LineCount - 1 do
begin
s := ReadLn;
//OPCLog.WriteToLog(s);
Result := Result + s + #13#10;
end;
except
on e: EIdException do
if ProcessTCPException(e) then
raise;
end;
finally
UnlockConnection;
end;
end;
function TaOPCTCPSource.CalcVolume(aSensorID: integer; aDate1,
aDate2: TDateTime): extended;
begin
Result := 0;
LockConnection;
try
try
DoConnect;
SendCommandFmt('CalcVolume %d;%s;%s',
[aSensorID, DateTimeToStr(aDate1, OpcFS), DateTimeToStr(aDate2, OpcFS)]);
Result := StrToFloat(ReadLn, OpcFS);
except
on e: EIdException do
if ProcessTCPException(e) then
raise;
end;
finally
UnlockConnection;
end;
end;
procedure TaOPCTCPSource.ChangePassword(aUser, aOldPassword,
aNewPassword: string);
var
Str: string;
begin
LockConnection;
try
try
DoConnect;
SendCommandFmt('ChangePassword %s;%s;%s', [aUser, aOldPassword, aNewPassword]);
Str := ReadLn;
if not AnsiSameText(Str, sOk) then
raise Exception.Create('Не удалось изменить пароль.');
except
on e: EIdException do
if ProcessTCPException(e) then
raise;
end;
finally
UnlockConnection;
end;
end;
function TaOPCTCPSource.GetSensorValueOnMoment(PhysID: String;
var Moment: TDateTime): string;
var
p: integer;
Str: string;
begin
LockConnection;
try
try
DoConnect;
SendCommandFmt('GetValueOnMoment %s;%s', [PhysID, DateTimeToStr(Moment, OpcFS)]);
Str := ReadLn;
except
on e: EIdException do
if ProcessTCPException(e) then
raise;
end;
Str := ExtractParamsFromAnswer(Str, 2);
p := Pos(cParamsDelimiter, str);
Result := LeftStr(Str, p - 1);
Str := RightStr(Str, length(Str) - p);
Moment := StrToDateTime(Str, OpcFS);
finally
UnlockConnection;
end;
end;
function TaOPCTCPSource.GetStatistic(aSensorID: string; aDate1, aDate2: TDateTime): string;
begin
{ TODO : TaOPCTCPSource.GetStatistic is not implemented }
Result := '';
end;
function TaOPCTCPSource.GetThreadList: string;
begin
LockConnection;
try
try
DoConnect;
SendCommand('PrepThreadList');
Result := GetPrepValues;
except
on e: EIdException do
if ProcessTCPException(e) then
raise;
end;
finally
UnlockConnection;
end;
end;
function TaOPCTCPSource.GetThreadProp(aThreadName: string): string;
begin
{ TODO : TaOPCTCPSource.GetThreadProp is not implemented }
Result := '';
end;
function TaOPCTCPSource.GetTimes(aSensorID: Integer; aDate1, aDate2: TDateTime): string;
begin
{ TODO : TaOPCTCPSource.GetTimes is not implemented }
Result := '';
end;
function TaOPCTCPSource.SetThreadLock(ConnectionName: string; NewState: boolean): string;
begin
LockConnection;
try
try
DoConnect;
SendCommandFmt('SetThreadLock %s;%s', [ConnectionName, BoolToStr(NewState)]);
Result := ReadLn;
except
on e: EIdException do
if ProcessTCPException(e) then
raise;
end;
finally
UnlockConnection;
end;
end;
function TaOPCTCPSource.SetThreadState(ConnectionName: string; NewState:
boolean): string;
begin
LockConnection;
try
try
DoConnect;
SendCommandFmt('SetThreadState %s;%s', [ConnectionName, BoolToStr(NewState)]);
Result := ReadLn;
except
on e: EIdException do
if ProcessTCPException(e) then
raise;
end;
finally
UnlockConnection;
end;
end;
procedure TaOPCTCPSource.TryConnect;
begin
inherited TryConnect;
Intercept.CompressionLevel := 0;
Authorize(User, Password);
LoadFS;
end;
procedure TaOPCTCPSource.UploadFile(aFileName: string; aDestDir: string = '');
var
//Answer: string;
//Size: integer;
Stream: TFileStream;
begin
LockConnection;
try
Stream := TFileStream.Create(aFileName, fmOpenRead or fmShareDenyNone);
try
try
DoConnect;
SendCommand(Format('UploadFile %s;%d', [aFileName, Stream.Size]));
ExtractParamsFromAnswer(ReadLn);
WriteStreamCompress(Stream);
except
on e: EIdException do
ProcessTCPException(e);
end;
finally
Stream.Free;
end;
finally
UnlockConnection;
end;
end;
procedure TaOPCTCPSource.WriteStream(AStream: TStream);
begin
Connection.IOHandler.Write(aStream);
end;
procedure TaOPCTCPSource.WriteStreamCompress(AStream: TStream);
begin
Connection.Intercept := Intercept;
try
WriteStream(AStream);
finally
Connection.Intercept := nil;
end;
end;
function TaOPCTCPSource.GetSensorsReadError: string;
var
aPosition, aCount: integer;
aSize: integer;
aUnswer: string;
// tc1: cardinal;
begin
LockConnection;
try
try
DoConnect;
SendCommand('PrepSensorsReadError');
aUnswer := ReadLn;
aSize := StrToInt(ExtractParamsFromAnswer(aUnswer));
if aSize < Connection.IOHandler.MaxLineLength then
begin
// прочитать всю строку показаний
SendCommand('GetPrepSensorsReadError');
Result := ReadLnCompress;
end
else
begin
Result := '';
aPosition := 1;
// прочитать строку частями по TCPClient.MaxLineLength - 1 байт
aCount := Connection.IOHandler.MaxLineLength - 1;
while aPosition <= aSize do
begin
SendCommand(Format('GetPrepSensorsReadError %d;%d', [aPosition,
aCount]));
Result := Result + ReadLnCompress;
aPosition := aPosition + aCount;
// если это последний кусочек, то у него особый размер
if (aPosition + aCount) > aSize then
aCount := aSize - aPosition + 1;
end;
end;
except
on e: EIdException do
if ProcessTCPException(e) then
raise;
end;
finally
UnlockConnection;
end;
end;
function TaOPCTCPSource.GetSensorsValueOnMoment(PhysIDs: String; Moment: TDateTime): string;
var
p: integer;
Str: string;
begin
LockConnection;
try
try
DoConnect;
SendCommandFmt('GetValuesOnMoment %s;%s', [DateTimeToStr(DateToServer(Moment), OpcFS), PhysIDs]);
Result := ExtractParamsFromAnswer(ReadLn);
except
on e: EIdException do
if ProcessTCPException(e) then
raise;
end;
finally
UnLockConnection;
end;
end;
function TaOPCTCPSource.GetSensorsValues(PhysIDs: String): string;
var
aPosition, aCount: integer;
aSize: integer;
aUnswer: string;
// tc1: cardinal;
begin
LockConnection;
try
try
DoConnect;
// tc1 := GetTickCount;
SendCommand('PrepValues ' + PhysIDs);
aUnswer := ReadLn;
aSize := StrToInt(ExtractParamsFromAnswer(aUnswer));
if aSize < Connection.IOHandler.MaxLineLength then
begin
// прочитать всю строку показаний
SendCommand('GetPrepValues');
Result := ReadLnCompress;
end
else
begin
Result := '';
aPosition := 1;
// прочитать строку частями по TCPClient.MaxLineLength - 1 байт
aCount := Connection.IOHandler.MaxLineLength - 1;
while aPosition <= aSize do
begin
SendCommand(Format('GetPrepValues %d;%d', [aPosition, aCount]));
Result := Result + ReadLnCompress;
aPosition := aPosition + aCount;
// если это последний кусочек, то у него особый размер
if (aPosition + aCount) > aSize then
aCount := aSize - aPosition + 1;
end;
end;
// OPCLog.WriteToLogFmt('TaOPCTCPSource.GetSensorsValues : ReadLnCompress = %d(%d)',
// [GetTickCount - tc1, aSize]);
except
on e: EIdException do
if ProcessTCPException(e) then
raise;
end;
finally
UnlockConnection;
end;
end;
procedure TaOPCTCPSource.FillHistory(Stream: TStream; SensorID: string; Date1,
Date2: TDateTime; aDataKindSet: TDataKindSet;
aCalcLeftVal: Boolean; aCalcRightVal: Boolean);
var
aStreamSizeParam: string;
//tc1: cardinal;
begin
if SensorID = '' then
exit;
LockConnection;
try
try
if not Assigned(Stream) then
Exception.Create('Не создан поток');
DoConnect;
//tc1 := GetTickCount;
SendCommand('PrepHistory ' +
SensorID + ';' +
DateTimeToStr(Date1, OpcFS) + ';' +
DateTimeToStr(Date2, OpcFS) + ';' +
BoolToStr(dkState in aDataKindSet) + ';' +
BoolToStr(dkValue in aDataKindSet) + ';' +
BoolToStr(dkUser in aDataKindSet) + ';' +
BoolToStr(aCalcLeftVal) + ';' +
BoolToStr(aCalcRightVal)
);
aStreamSizeParam := ExtractParamsFromAnswer(ReadLn, 1);
SendCommand('GetPrepHistory ' + aStreamSizeParam);
ReadStreamCompress(Stream, StrToInt(aStreamSizeParam));
//OPCLog.WriteToLogFmt('TaOPCTCPSource.GetSensorJurnal : %d мс (%d Byte)',
// [GetTickCount - tc1, Stream.Size]);
Stream.Position := 0;
except
on e: EIdException do
if ProcessTCPException(e) then
raise;
end;
finally
UnlockConnection;
end;
end;
procedure TaOPCTCPSource.FillNameSpaceStrings(aNameSpace: TStrings; aRootID: string; aLevelCount: Integer;
aKinds: TDCObjectKindSet);
var
Stream: TMemoryStream;
//dt: TDateTime;
Res: string;
//dtStr: string;
begin
Assert(Assigned(aNameSpace));
aNameSpace.Clear;
LockConnection;
try
try
DoConnect;
SendCommandFmt('GetNameSpace ObjectID=%s;TimeStamp=%s;LevelCount=%d', [aRootID, '0', aLevelCount]);
Connection.Intercept := Intercept;
try
//dt := StrToDateTimeDef(ReadLn, 0, OpcFS);
ReadLn; // читаем дату
Res := ReadLn;
if Res <> 'Stream' then
Exit;
Stream := TMemoryStream.Create;
try
ReadStream(Stream);
Stream.Position := 0;
aNameSpace.LoadFromStream(Stream);
finally
FreeAndNil(Stream);
end;
finally
Connection.Intercept := nil;
end;
except
on e: EIdException do
if ProcessTCPException(e) then
raise;
end;
finally
UnlockConnection;
end;
end;
procedure TaOPCTCPSource.FillSensorsValuesStream(var aValuesStream:
TMemoryStream);
var
i: integer;
Stream: TMemoryStream;
PhysID: integer;
aByteCount: integer;
// tc1: cardinal;
begin
LockConnection;
try
try
DoConnect;
// tc1 := GetTickCount;
if FDataLinkGroupsChanged then
begin
Stream := TMemoryStream.Create;
try
for i := 0 to DataLinkGroups.Count - 1 do
begin
PhysID := StrToIntDef(TOPCDataLinkGroup(DataLinkGroups.Items[i]).PhysID, 0);
Stream.Write(PhysID, SizeOf(PhysID));
end;
Stream.Position := 0;
SendCommandFmt('PrepStreamValues %d', [DataLinkGroups.Count]);
WriteStream(Stream);
//WriteStreamCompress(Stream);
// отметим, что мы передали серверу новые адреса запрашиваемых датчиков
FDataLinkGroupsChanged := false;
finally
Stream.Free;
end;
end
else
SendCommand('PrepStreamValues');
aByteCount := StrToInt(ExtractParamsFromAnswer(ReadLn));
SendCommand('GetPrepStreamValues');
aValuesStream.Clear;
ReadStreamCompress(aValuesStream, aByteCount);
aValuesStream.Position := 0;
// OPCLog.WriteToLogFmt('TaOPCTCPSource.FillSensorsValuesStream : ReadStream = %d(%d)',
// [GetTickCount - tc1,aValuesStream.Size]);
// что-то пошло не так (сервер перегрузился...)
// установим признак необходимости передать серверу новые адреса
if DataLinkGroups.Count * SizeOf(TDCSensorDataRec) <> aValuesStream.Size then
FDataLinkGroupsChanged := true;
except
on e: EIdException do
if ProcessTCPException(e) then
raise;
end;
finally
UnlockConnection;
end;
end;
function TaOPCTCPSource.GetNameSpace(aObjectID: string; aLevelCount: Integer): boolean;
var
Stream: TMemoryStream;
dt: TDateTime;
Res: string;
dtStr: string;
begin
Result := false;
LockConnection;
try
try
DoConnect;
if (aObjectID <> FNameSpaceParentID) or
not (FileExists(GetNameSpaceFileName)) then
FNameSpaceTimeStamp := 0;
dtStr := FloatToStr(FNameSpaceTimeStamp, OpcFS);
SendCommandFmt('GetNameSpace ObjectID=%s;TimeStamp=%s;LevelCount=%d', [aObjectID, dtStr, aLevelCount]);
Connection.Intercept := Intercept;
try
dt := StrToDateTimeDef(ReadLn, 0, OpcFS);
if (SecondsBetween(dt, FNameSpaceTimeStamp) <= 1) then
exit;
Res := ReadLn;
if Res <> 'Stream' then
Exit;
Stream := TMemoryStream.Create;
try
ReadStream(Stream);
Stream.Position := 0;
FNameSpaceCash.LoadFromStream(Stream);
FNameSpaceTimeStamp := dt;
FNameSpaceParentID := aObjectID;
Result := true;
finally
FreeAndNil(Stream);
end;
finally
Connection.Intercept := nil;
end;
except
on e: EIdException do
if ProcessTCPException(e) then
raise;
end;
finally
UnlockConnection;
end;
end;
function TaOPCTCPSource.LoadLookup(aName: string;
var aTimeStamp: TDateTime): string;
var
i: Integer;
LineCount: integer;
dtStr: string;
dt: TDateTime;
answer: string;
begin
Result := '';
LockConnection;
try
try
DoConnect;
SendCommandFmt('GetLookupTimeStamp %s', [aName]);
dtStr := ReadLn;
dt := StrToDateTimeDef(dtStr, 0, OpcFS);
if Abs(dt - aTimeStamp) > 1 / 24 / 60 / 60 then // > 1 секунды
begin
aTimeStamp := dt;
SendCommandFmt('GetLookup %s', [aName]);
Connection.Intercept := Intercept;
try
answer := ReadLn;
if answer <> aName then
raise Exception.Create(answer);
LineCount := ReadInteger;
for I := 0 to LineCount - 1 do
Result := Result + ReadLn + #13#10;
finally
Connection.Intercept := nil;
end;
end;
except
on e: EIdException do
if ProcessTCPException(e) then
raise;
end;
finally
UnlockConnection;
end;
end;
function TaOPCTCPSource.Login(const aUserName, aPassword: string): Boolean;
begin
Result := GetUserPermission(aUserName, aPassword, '') <> '';
end;
function TaOPCTCPSource.ReadInteger: integer;
begin
Result := Connection.IOHandler.ReadInt32;
end;
function TaOPCTCPSource.ReadLnCompress: string;
begin
Connection.Intercept := Intercept;
try
Result := ReadLn;
finally
Connection.Intercept := nil;
end;
end;
procedure TaOPCTCPSource.ReadStreamCompress(aStream: TStream; aSize: Int64 = -1);
begin
Connection.Intercept := Intercept;
try
Connection.IOHandler.ReadStream(aStream, aSize);
finally
Connection.Intercept := nil;
end;
end;
function TaOPCTCPSource.GetMessage: TUserMessage;
var
aMessageStr: string;
aMessageLength: integer;
begin
Result := nil;
// сервера 0 версии не поддерживают обмен сообщениями
if ServerVer = 0 then
Exit;
LockConnection;
try
try
DoConnect;
SendCommand('GetMessage');
aMessageLength := StrToInt(ExtractParamsFromAnswer(ReadLn, 1));
if aMessageLength = 0 then
Exit;
aMessageStr := Connection.IOHandler.ReadString(aMessageLength);
Result := TUserMessage.Create(aMessageStr);
except
on e: EIdException do
if ProcessTCPException(e) then
raise;
end;
finally
UnLockConnection;
end;
end;
procedure TaOPCTCPSource.Authorize(aUser: string; aPassword: string);
begin
SendCommandFmt(
'AuthorizeUser User=%s;Password=%s;Description=%s;%d;%s;%s;%d;%d;%d',
[aUser, aPassword, Description, 1, //ProtocolVersion,
GetLocalUserName, GetComputerName,
CompressionLevel, Connection.IOHandler.MaxLineLength, Ord(EnableMessage)]);
Intercept.CompressionLevel := CompressionLevel;
if OPCLog.AutoFillOnAuthorize then
begin
OPCLog.LoginName := GetLocalUserName;
OPCLog.UserName := aUser;
OPCLog.ComputerName := GetComputerName;
OPCLog.IPAdress := Connection.Socket.Binding.IP;
end;
end;
function TaOPCTCPSource.SendModBus(aSystemType: integer; aRequest: string;
aRetByteCount, aTimeOut: integer): string;
begin
Result := '';
LockConnection;
try
try
DoConnect;
SendCommandFmt('SendModBus %d;%s;%d;%d', [aSystemType, aRequest, aRetByteCount, aTimeOut]);
Result := ReadLn;
except
on e: EIdException do
if ProcessTCPException(e) then
raise;
end;
finally
UnlockConnection;
end;
end;
function TaOPCTCPSource.SendModBusEx(aConnectionName, aRequest: string;
aRetByteCount, aTimeOut: integer): string;
begin
Result := '';
LockConnection;
try
try
DoConnect;
SendCommandFmt('SendModBus %s;%s;%d;%d', [aConnectionName, aRequest, aRetByteCount, aTimeOut]);
Result := ReadLn;
except
on e: EIdException do
if ProcessTCPException(e) then
raise;
end;
finally
UnlockConnection;
end;
end;
procedure TaOPCTCPSource.SendUserMessage(aUserGUID, aMessage: string);
begin
// сервера 0 версии не поддерживают обмен сообщениями
if ServerVer = 0 then
Exit;
LockConnection;
try
try
DoConnect;
SendCommandFmt('SendMessage %s;%s', [aUserGUID, ConvertBinToStr(aMessage)]);
CheckAnswer(ReadLn);
except
on e: EIdException do
ProcessTCPException(e);
end;
finally
UnLockConnection;
end;
end;
end.
|
unit
main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Winapi.ShellApi, System.IOUtils,
Vcl.Buttons, Vcl.ExtDlgs, Vcl.Grids;
type
TForm1 = class(TForm)
Memo1: TMemo;
lblFolder: TLabel;
SpeedButton1: TSpeedButton;
SaveTextFileDialog1: TSaveTextFileDialog;
Label1: TLabel;
procedure SpeedButton1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
{ Private declarations }
folderPath : string;
procedure WMDROPFILES(var msg : TWMDropFiles) ; message WM_DROPFILES;
procedure CreateWnd; override;
procedure DestroyWnd; override;
procedure GetListOfFiles(aFolder : string; var fl : TStringList);
function ChecklineCount(fl : TStringList): Boolean;
function SuggestFileName(aFolder : string): string;
public
{ Public declarations }
end;
const
MemoCapacity = 22;
var
Form1: TForm1;
implementation
{$R *.dfm}
function TForm1.ChecklineCount(fl: TStringList): Boolean;
begin
if fl.Count >= MemoCapacity then
result := true;
end;
procedure TForm1.CreateWnd;
begin
inherited;
DragAcceptFiles(Handle, True);
end;
procedure TForm1.DestroyWnd;
begin
DragAcceptFiles(Handle, false);
inherited;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
SaveTextFileDialog1.Filter := 'Text files (*.txt)|*.TXT|Any file (*.*)|*.*';
end;
procedure TForm1.GetListOfFiles(aFolder : string; var fl: TStringList);
var
sr : TSearchRec;
begin
fl := TStringList.Create;
try
if FindFirst( aFolder + '\' + '*.*', faDirectory, sr) < 0 then
Exit
else
repeat
if ((sr.Attr and faDirectory <> 0) AND (sr.Name <> '.') AND (sr.Name <> '..')) then
begin
fl.Add(sr.Name) ;
end;
until FindNext(sr) <> 0;
finally
FindClose(sr) ;
end;
end;
procedure TForm1.SpeedButton1Click(Sender: TObject);
var
fileName : string;
begin
SaveTextFileDialog1.FileName := SuggestFileName(folderPath);
if SaveTextFileDialog1.Execute then
begin
fileName := SaveTextFileDialog1.FileName;
// + '.' + SaveTextFileDialog1.FilterIndex;
//ShowMessage(fileName);
// Memo1.Lines.SaveToFile(SaveTextFileDialog1.FileName );
Memo1.Lines.SaveToFile(filename);
end;
//Edit1.Text := SaveTextFileDialog1.Encodings[SaveTextFileDialog1.EncodingIndex];
end;
function TForm1.SuggestFileName(aFolder: string): string;
var
tmp : string;
begin
tmp := aFolder.Substring(aFolder.IndexOf('\') + 1);
result := tmp.Replace('\','_');
end;
procedure TForm1.WMDROPFILES(var msg: TWMDropFiles);
var
i, fileCount: integer;
fileName: array[0..MAX_PATH] of char;
folderList : TStringList;
tmp : string;
begin
SpeedButton1.Visible := false;
fileCount:=DragQueryFile(msg.Drop, $FFFFFFFF, fileName, MAX_PATH);
if fileCount = 1 then
begin
for i := 0 to fileCount - 1 do
begin
DragQueryFile(msg.Drop, i, fileName, MAX_PATH);
end;
DragFinish(msg.Drop);
if TDirectory.Exists(fileName) then
begin
tmp := fileName;
lblFolder.Caption := tmp;
folderPath := tmp;
GetListOfFiles(folderPath, folderList);
// ShowMessage(SuggestFileName(fileName));
if ChecklineCount(folderList) then
Memo1.ScrollBars := ssVertical;
Memo1.Lines := folderList;
Memo1.Visible := true;
SpeedButton1.Visible := true;
end;
end;
end;
end.
|
{
Shows a list of FormIDs < 800h from selected references
}
unit userscript;
var
sl: TStringList;
function Initialize: integer;
begin
sl := TStringList.Create;
end;
function Process(e: IInterface): integer;
var
s: string;
formid: integer;
begin
s := Signature(e);
if (s <> 'REFR') and (s <> 'ACHR') and (s <> 'PHZD') and (s <> 'PGRD') then
Exit;
formid := GetElementNativeValues(e, 'NAME');
if (formid = 0 ) or (formid > $800) then
Exit;
s := IntToHex(formid, 8) + ';' + GetElementEditValues(e, 'NAME');
if sl.IndexOf(s) = -1 then
sl.Add(s);
end;
function Finalize: integer;
begin
sl.Sort;
AddMessage(sl.Text);
sl.Free;
end;
end. |
unit ServerList;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, cxGraphics, cxControls,
cxLookAndFeels,
cxLookAndFeelPainters, cxContainer, cxEdit, cxCustomData, cxStyles, cxTL,
cxTextEdit, cxTLdxBarBuiltInMenu, cxInplaceContainer, cxGroupBox, Vcl.Menus,
Vcl.StdCtrls, cxButtons, Generics.Collections, Intfs, cxSpinEdit,
System.ImageList, Vcl.ImgList;
type
TSrvList = class(TForm)
cxServerList: TcxGroupBox;
cxServers: TcxTreeList;
cxServerName: TcxTreeListColumn;
cxPort: TcxTreeListColumn;
cxOK: TcxButton;
cxCancel: TcxButton;
cxMenu: TcxImageList;
SrvPopUp: TPopupMenu;
nAddServer: TMenuItem;
nRemoveServer: TMenuItem;
procedure nAddServerClick(Sender: TObject);
procedure nRemoveServerClick(Sender: TObject);
procedure cxOKClick(Sender: TObject);
public
constructor Create(AOwner : TComponent; AServers : TList<TServerData>); reintroduce;
strict private
FServers : TList<TServerData>;
procedure PopulateServerList();
procedure InvalidateServerList();
procedure SaveServerList();
end;
implementation
{$R *.dfm}
{ TSrvList }
constructor TSrvList.Create(AOwner: TComponent; AServers: TList<TServerData>);
begin
inherited Create(AOwner);
FServers := AServers;
PopulateServerList();
end;
procedure TSrvList.cxOKClick(Sender: TObject);
begin
InvalidateServerList();
SaveServerList();
ModalResult := mrOK;
end;
procedure TSrvList.InvalidateServerList;
var
i : Integer;
srv : TServerData;
begin
FServers.Clear();
for i:=0 to cxServers.Count-1 do begin
srv := Default(TServerData);
if VarIsNull(cxServers.Items[i].Values[0]) then
continue;
srv.FAddress := cxServers.Items[i].Values[0];
if not VarIsNumeric(cxServers.Items[i].Values[1]) then
continue;
srv.FPort := cxServers.Items[i].Values[1];
if srv.FPort = 0 then
Continue;
FServers.Add(srv);
end;
end;
procedure TSrvList.nAddServerClick(Sender: TObject);
begin
cxServers.Root.AddChild();
end;
procedure TSrvList.nRemoveServerClick(Sender: TObject);
begin
if cxServers.SelectionCount = 0 then
Exit;
cxServers.Selections[0].Delete();
end;
procedure TSrvList.PopulateServerList;
var
srv : TServerData;
node : TcxTreeListNode;
begin
for srv in FServers do begin
node := cxServers.Root.AddChild();
node.Values[0] := srv.FAddress;
node.Values[1] := srv.FPort;
end;
end;
procedure TSrvList.SaveServerList;
var
sl : TStringList;
srv : TServerData;
begin
sl := TStringList.Create();
try
for srv in FServers do
sl.Add(Format('%s:%d', [srv.FAddress, srv.FPort]));
try
sl.SaveToFile('servers.ini');
except
end;
finally
sl.Free();
end;
end;
end.
|
{
ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi
Copyright (c) 2016, Isaque Pinheiro
All rights reserved.
GNU Lesser General Public License
Versão 3, 29 de junho de 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
A todos é permitido copiar e distribuir cópias deste documento de
licença, mas mudá-lo não é permitido.
Esta versão da GNU Lesser General Public License incorpora
os termos e condições da versão 3 da GNU General Public License
Licença, complementado pelas permissões adicionais listadas no
arquivo LICENSE na pasta principal.
}
{ @abstract(ORMBr Framework.)
@created(20 Jul 2016)
@author(Isaque Pinheiro <isaquepsp@gmail.com>)
@abstract(Website : http://www.ormbr.com.br)
@abstract(Telagram : https://t.me/ormbr)
}
unit ormbr.objects.manager.abstract;
interface
uses
Rtti,
Generics.Collections,
// ORMBr
dbebr.factory.interfaces,
dbcbr.mapping.explorer,
dbcbr.mapping.classes;
type
TObjectManagerAbstract<M: class, constructor> = class abstract
protected
// Instancia a class que mapea todas as class do tipo Entity
function FindSQLInternal(const ASQL: String): TObjectList<M>; virtual; abstract;
procedure ExecuteOneToOne(AObject: TObject; AProperty: TRttiProperty;
AAssociation: TAssociationMapping); virtual; abstract;
procedure ExecuteOneToMany(AObject: TObject; AProperty: TRttiProperty;
AAssociation: TAssociationMapping); virtual; abstract;
public
constructor Create(const AOwner: TObject; const AConnection: IDBConnection;
const APageSize: Integer); virtual;
procedure InsertInternal(const AObject: M); virtual; abstract;
procedure UpdateInternal(const AObject: TObject;
const AModifiedFields: TDictionary<string, string>); virtual; abstract;
procedure DeleteInternal(const AObject: M); virtual; abstract;
function SelectInternalWhere(const AWhere: string;
const AOrderBy: string): string; virtual; abstract;
function SelectInternalAll: IDBResultSet; virtual; abstract;
function SelectInternalID(const AID: Variant): IDBResultSet; virtual; abstract;
function SelectInternal(const ASQL: String): IDBResultSet; virtual; abstract;
function SelectInternalAssociation(const AObject: TObject): String; virtual; abstract;
function GetDMLCommand: string; virtual; abstract;
function Find: TObjectList<M>; overload; virtual; abstract;
function Find(const AID: Variant): M; overload; virtual; abstract;
function FindWhere(const AWhere: string;
const AOrderBy: string = ''): TObjectList<M>; virtual; abstract;
function ExistSequence: Boolean; virtual; abstract;
function NextPacket: IDBResultSet; overload; virtual; abstract;
function NextPacket(const APageSize,
APageNext: Integer): IDBResultSet; overload; virtual; abstract;
function NextPacket(const AWhere, AOrderBy: String;
const APageSize, APageNext: Integer): IDBResultSet; overload; virtual; abstract;
function NextPacketList: TObjectList<M>; overload; virtual; abstract;
function NextPacketList(const APageSize,
APageNext: Integer): TObjectList<M>; overload; virtual; abstract;
function NextPacketList(const AWhere, AOrderBy: String;
const APageSize, APageNext: Integer): TObjectList<M>; overload; virtual; abstract;
procedure NextPacketList(const AObjectList: TObjectList<M>;
const APageSize, APageNext: Integer); overload; virtual; abstract;
procedure NextPacketList(const AObjectList: TObjectList<M>;
const AWhere, AOrderBy: String;
const APageSize, APageNext: Integer); overload; virtual; abstract;
procedure LoadLazy(const AOwner, AObject: TObject); virtual; abstract;
end;
implementation
{ TObjectManagerAbstract<M> }
constructor TObjectManagerAbstract<M>.Create(const AOwner: TObject;
const AConnection: IDBConnection; const APageSize: Integer);
begin
// Popula todas classes modelos na lista
TMappingExplorer.GetRepositoryMapping;
end;
end.
|
////////////////////////////////////////////////////////////////////////////////
// Board.pas
// MTB simulator library.
// MTB board configuration form implemetation.
// (c) Jan Horacek (jan.horacek@kmz-brno.cz),
// Michal Petrilak (engineercz@gmail.com)
////////////////////////////////////////////////////////////////////////////////
{
LICENSE:
Copyright 2015-2017 Michal Petrilak, Jan Horacek
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
}
{
DESCRIPTION:
Configuration form of one MTB board.
}
unit Board;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TF_Board = class(TForm)
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
CB_Type: TComboBox;
E_Name: TEdit;
L_adresa: TLabel;
B_Apply: TButton;
B_Storno: TButton;
Label4: TLabel;
E_FW: TEdit;
RG_Exists: TRadioGroup;
RG_Failure: TRadioGroup;
procedure B_StornoClick(Sender: TObject);
procedure B_ApplyClick(Sender: TObject);
private
public
OpenIndex:Integer;
procedure OpenForm(Module:Integer);
end;
var
F_Board: TF_Board;
implementation
uses fConfig, LibraryEvents, Errors;
{$R *.dfm}
procedure TF_Board.B_ApplyClick(Sender: TObject);
begin
if (Self.CB_Type.ItemIndex = -1) then
begin
MessageBox(F_Board.Handle,'Vyberte typ MTB desky !','Nelze uložit',MB_OK OR MB_ICONWARNING);
Exit;
end;
if ((not Modules[OpenIndex].failure) and (Self.RG_Failure.ItemIndex = 1)) then
begin
// module is failing
Modules[OpenIndex].failure := true;
if (Assigned(LibEvents.OnError.event)) then
LibEvents.OnError.event(Self, LibEvents.OnError.data, MTB_MODULE_FAIL, OpenIndex, 'Modul nekomunikuje');
if (Assigned(LibEvents.OnOutputChanged.event)) then
begin
LibEvents.OnOutputChanged.event(FormConfig, LibEvents.OnOutputChanged.data, OpenIndex);
LibEvents.OnInputChanged.event(FormConfig, LibEvents.OnOutputChanged.data, OpenIndex);
end;
end;
if (((Modules[OpenIndex].failure) and (Self.RG_Failure.ItemIndex = 0)) or
((FormConfig.Status = TSimulatorStatus.running) and (not Modules[OpenIndex].exists) and (Self.RG_Exists.ItemIndex = 1))) then
begin
// module is restored
Modules[OpenIndex].failure := false;
if (Assigned(LibEvents.OnError.event)) then
LibEvents.OnError.event(Self, LibEvents.OnError.data, MTB_MODULE_RESTORED, OpenIndex, 'Modul komunikuje');
if (Assigned(LibEvents.OnOutputChanged.event)) then
begin
LibEvents.OnOutputChanged.event(FormConfig, LibEvents.OnOutputChanged.data, OpenIndex);
LibEvents.OnInputChanged.event(FormConfig, LibEvents.OnOutputChanged.data, OpenIndex);
end;
end;
Modules[OpenIndex].name := Self.E_Name.Text;
case (Self.CB_Type.ItemIndex) of
0 : Modules[OpenIndex].typ := idMTB_UNI_ID;
1 : Modules[OpenIndex].typ := idMTB_UNIOUT_ID;
2 : Modules[OpenIndex].typ := idMTB_TTL_ID;
3 : Modules[OpenIndex].typ := idMTB_TTLOUT_ID;
4 : Modules[OpenIndex].typ := idMTB_REGP_ID;
5 : Modules[OpenIndex].typ := idMTB_POT_ID;
end;
Modules[OpenIndex].fw := Self.E_FW.Text;
case (Self.RG_Exists.ItemIndex) of
0:Modules[OpenIndex].exists := false;
1:Modules[OpenIndex].exists := true;
end;//case
Self.Close()
end;//procedure
procedure TF_Board.OpenForm(Module: Integer);
begin
Self.L_adresa.Caption := IntToStr(Module);
Self.OpenIndex := Module;
Self.E_Name.Text := Modules[OpenIndex].name;
Self.E_FW.Text := Modules[OpenIndex].fw;
case (Modules[OpenIndex].exists) of
false:Self.RG_Exists.ItemIndex := 0;
true :Self.RG_Exists.ItemIndex := 1;
end;//case
case (Modules[OpenIndex].failure) of
false:Self.RG_Failure.ItemIndex := 0;
true :Self.RG_Failure.ItemIndex := 1;
end;//case
Self.RG_Exists.Enabled := (FormConfig.Status <> TSimulatorStatus.running) or (not Modules[OpenIndex].exists);
Self.RG_Failure.Enabled := (FormConfig.Status = TSimulatorStatus.running) and (Modules[OpenIndex].exists);
case (Modules[OpenIndex].typ) of
idMTB_UNI_ID : Self.CB_Type.ItemIndex := 0;
idMTB_UNIOUT_ID : Self.CB_Type.ItemIndex := 1;
idMTB_TTL_ID : Self.CB_Type.ItemIndex := 2;
idMTB_TTLOUT_ID : Self.CB_Type.ItemIndex := 3;
idMTB_REGP_ID : Self.CB_Type.ItemIndex := 4;
idMTB_POT_ID : Self.CB_Type.ItemIndex := 5;
end;
Self.Caption := 'Editovat desku '+IntToStr(Module);
Self.Show();
end;//procedure
procedure TF_Board.B_StornoClick(Sender: TObject);
begin
Self.Close();
end;//procedure
initialization
finalization
FreeAndNil(F_Board);
end.//unit
|
unit uMainFormORM;
interface
uses
Windows,
Messages,
SysUtils,
Variants,
Classes,
Graphics,
Controls,
Forms,
Dialogs,
DB,
Grids,
DBGrids,
StdCtrls,
Mask,
DBClient,
DBCtrls,
ExtCtrls,
/// orm factory
ormbr.factory.interfaces,
/// orm injection dependency
ormbr.container.dataset.interfaces,
ormbr.container.fdmemtable,
ormbr.factory.firedac,
ormbr.types.database,
ormbr.dml.generator.sqlite,
/// orm model
ormbr.model.client,
FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf,
FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys,
FireDAC.VCLUI.Wait, FireDAC.Comp.Client, FireDAC.Stan.Intf,
FireDAC.Phys.SQLite, FireDAC.Phys.SQLiteDef, FireDAC.Stan.ExprFuncs,
FireDAC.Comp.UI, FireDAC.DApt, FireDAC.Stan.Param, FireDAC.DatS,
FireDAC.DApt.Intf, FireDAC.Comp.DataSet, FireDAC.Phys.MySQL,
FireDAC.Phys.MySQLDef;
type
TForm3 = class(TForm)
DBGrid1: TDBGrid;
DBNavigator1: TDBNavigator;
Button2: TButton;
DataSource3: TDataSource;
Label3: TLabel;
DBEdit3: TDBEdit;
Label4: TLabel;
DBEdit4: TDBEdit;
FDConnection1: TFDConnection;
FDPhysSQLiteDriverLink1: TFDPhysSQLiteDriverLink;
FDGUIxWaitCursor1: TFDGUIxWaitCursor;
FDClient: TFDMemTable;
Button1: TButton;
procedure FormCreate(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
private
{ Private declarations }
oConn: IDBConnection;
oContainerClient: IContainerDataSet<Tclient>;
public
{ Public declarations }
end;
var
Form3: TForm3;
implementation
uses
StrUtils;
{$R *.dfm}
procedure TForm3.Button1Click(Sender: TObject);
var
LClient: Tclient;
begin
LClient := oContainerClient.Current;
LClient.client_name := 'Mudar campo "Nome" pelo objeto';
oContainerClient.Save(LClient);
end;
procedure TForm3.Button2Click(Sender: TObject);
begin
oConn.StartTransaction;
oContainerClient.ApplyUpdates(0);
oConn.Commit;
end;
procedure TForm3.FormCreate(Sender: TObject);
begin
// Instância da class de conexão via FireDAC
oConn := TFactoryFireDAC.Create(FDConnection1, dnSQLite);
// Client
oContainerClient := TContainerFDMemTable<Tclient>.Create(oConn, FDClient);
oContainerClient.Open;
end;
end.
|
unit sPanel;
{$I sDefs.inc}
{.$DEFINE LOGGED}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, sCommonData, sConst
{$IFDEF TNTUNICODE} , TntExtCtrls {$ENDIF};
type
{$IFDEF TNTUNICODE}
TsPanel = class(TTntPanel)
{$ELSE}
TsPanel = class(TPanel)
{$ENDIF}
{$IFNDEF NOTFORHELP}
private
FCommonData: TsCommonData;
FOnPaint: TPaintEvent;
FOnMouseLeave: TNotifyEvent;
FOnMouseEnter: TNotifyEvent;
FOldBevel : TPanelBevel;
public
constructor Create(AOwner:TComponent); override;
destructor Destroy; override;
procedure AfterConstruction; override;
procedure Loaded; override;
procedure Paint; override;
procedure OurPaint(DC : HDC = 0; SendUpdated : boolean = True); virtual;
procedure PrepareCache;
procedure WndProc (var Message: TMessage); override;
procedure WriteText(R : TRect; aCanvas : TCanvas = nil; aDC : hdc = 0); virtual;
procedure PaintWindow(DC: HDC); override;
published
{$ENDIF} // NOTFORHELP
property SkinData : TsCommonData read FCommonData write FCommonData;
property OnPaint : TPaintEvent read FOnPaint write FOnPaint;
property OnMouseEnter: TNotifyEvent read FOnMouseEnter write FOnMouseEnter;
property OnMouseLeave: TNotifyEvent read FOnMouseLeave write FOnMouseLeave;
end;
TsDragBar = class(TsPanel)
{$IFNDEF NOTFORHELP}
private
FDraggedControl : TControl;
procedure WMActivateApp(var Message: TWMActivateApp); message WM_ACTIVATEAPP;
protected
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
public
procedure ReadState(Reader: TReader); override;
constructor Create (AOwner: TComponent); override;
procedure WndProc (var Message: TMessage); override;
published
property Alignment;
property Align default alTop;
property Color default clActiveCaption;
{$ENDIF} // NOTFORHELP
property DraggedControl : TControl read FDraggedControl write FDraggedControl;
end;
{$IFNDEF NOTFORHELP}
TsContainer = class(TsPanel)
end;
TsGrip = class(TsPanel)
public
Transparent : boolean;
LinkedControl : TWinControl;
constructor Create (AOwner: TComponent); override;
procedure Paint; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
end;
TsColInfo = record
Index : integer;
Color : TColor;
R : TRect;
Selected : boolean;
end;
TsColorsPanel = class(TsPanel)
private
FColors: TStrings;
FItemIndex: integer;
FItemWidth: integer;
FItemHeight: integer;
FItemMargin: integer;
FColCount: integer;
FRowCount: integer;
FOnChange: TNotifyEvent;
procedure SetColors(const Value: TStrings);
procedure SetItemIndex(const Value: integer);
procedure SetItemHeight(const Value: integer);
procedure SetItemWidth(const Value: integer);
procedure SetItemMargin(const Value: integer);
procedure SetColCount(const Value: integer);
procedure SetRowCount(const Value: integer);
public
OldSelected : integer;
ColorsArray : array of TsColInfo;
constructor Create (AOwner: TComponent); override;
destructor Destroy; override;
procedure GenerateColors;
procedure AfterConstruction; override;
procedure Loaded; override;
procedure OurPaint(DC : HDC = 0; SendUpdated : boolean = True); override;
procedure PaintColors(const DC: hdc);
function Count : integer;
function GetItemByCoord(p : TPoint) : integer;
procedure WndProc (var Message: TMessage); override;
procedure MouseDown (Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
function ColorValue : TColor;
published
property ColCount : integer read FColCount write SetColCount default 5;
property Colors : TStrings read FColors write SetColors;
property ItemIndex : integer read FItemIndex write SetItemIndex default -1;
property ItemHeight : integer read FItemHeight write SetItemHeight default 21;
property ItemWidth : integer read FItemWidth write SetItemWidth default 21;
property ItemMargin : integer read FItemMargin write SetItemMargin default 6;
property Height default 60;
property RowCount : integer read FRowCount write SetRowCount default 2;
property Width default 140;
property OnChange : TNotifyEvent read FOnChange write FOnChange;
end;
TsStdColorsPanel = class(TsColorsPanel)
end;
{$ENDIF} // NOTFORHELP
implementation
uses sMessages, sGraphUtils, sVCLUtils, sMaskData, sStyleSimply, sSkinManager, sBorders,
acntUtils{$IFDEF LOGGED}, sDebugMsgs{$ENDIF}, sAlphaGraph, sSkinProps;
{ TsPanel }
procedure TsPanel.AfterConstruction;
begin
inherited;
FCommonData.Loaded;
end;
constructor TsPanel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FCommonData := TsCommonData.Create(Self, True);
FCommonData.COC := COC_TsPanel;
end;
destructor TsPanel.Destroy;
begin
if Assigned(FCommonData) then FreeAndNil(FCommonData);
inherited Destroy;
end;
procedure TsPanel.Loaded;
begin
inherited;
FCommonData.Loaded;
FOldBevel := BevelOuter;
end;
procedure TsPanel.OurPaint;
var
b : boolean;
SavedDC, NewDC : HDC;
R : TRect;
i : integer;
ParentBG : TacBGInfo;
C : TColor;
TmpCanvas : TCanvas;
begin
if Showing and Assigned(FCommonData) and FCommonData.Skinned {and not acGraphPainting }then begin
if DC <> 0 then NewDC := DC else NewDC := Canvas.Handle;
if IsCached(FCommonData) and not SkinData.CustomColor or (Self is TsColorsPanel) or InAnimationProcess then begin
FCommonData.FUpdating := FCommonData.Updating;
if not FCommonData.FUpdating then begin
// If transparent and parent is resized
b := FCommonData.HalfVisible or FCommonData.BGChanged;
if SkinData.RepaintIfMoved then begin
FCommonData.HalfVisible := (WidthOf(R) <> Width) or (HeightOf(R) <> Height)
end
else FCommonData.HalfVisible := False;
if b and not FCommonData.UrgentPainting then PrepareCache;
CopyWinControlCache(Self, FCommonData, Rect(0, 0, 0, 0), Rect(0, 0, Width, Height), NewDC, False);
sVCLUtils.PaintControls(NewDC, Self, b and SkinData.RepaintIfMoved, Point(0, 0));
end;
end
else begin
FCommonData.Updating := False;
i := SkinBorderMaxWidth(FCommonData);
R := Rect(0, 0, Width, Height);
SavedDC := SaveDC(NewDC);
ExcludeControls(NewDC, Self, actGraphic, 0, 0);
ParentBG.PleaseDraw := False;
if not SkinData.CustomColor then GetBGInfo(@ParentBG, Self.Parent) else begin
ParentBG.Color := ColorToRGB(Color);
ParentBG.BgType := btFill;
end;
if FCommonData.FCacheBmp.Empty then begin
FCommonData.FCacheBmp.Width := 1;
FCommonData.FCacheBmp.Height := 1;
end;
if (FCommonData.SkinManager.gd[FCommonData.SkinIndex].Transparency = 100) and (ParentBG.BgType = btCache) then begin
FCommonData.FUpdating := FCommonData.Updating;
if not FCommonData.FUpdating then begin
if i = 0 then begin
BitBlt(NewDC, 0, 0, Width, Height, ParentBG.Bmp.Canvas.Handle, ParentBG.Offset.X, ParentBG.Offset.Y, SRCCOPY);
end
else begin
if FCommonData.FCacheBmp = nil then FCommonData.FCacheBmp := CreateBmp32(Width, Height);
R := PaintBorderFast(NewDC, R, i, FCommonData, 0);
if FCommonData.SkinManager.gd[FCommonData.SkinIndex].Transparency = 100 then FillDC(NewDC, R, ParentBG.Color) else FillDC(NewDC, R, GetBGColor(SkinData, 0));
if i > 0 then BitBltBorder(NewDC, 0, 0, Width, Height, FCommonData.FCacheBmp.Canvas.Handle, 0, 0, i);
BitBlt(NewDC, i, i, Width - 2 * i, Height - 2 * i, ParentBG.Bmp.Canvas.Handle, ParentBG.Offset.X + i, ParentBG.Offset.Y + i, SRCCOPY);
end;
end;
end
else begin
case FCommonData.SkinManager.gd[FCommonData.SkinIndex].Transparency of
0 : C := iffi(FCommonData.CustomColor, Color, FCommonData.SkinManager.gd[FCommonData.SkinIndex].Color);
100 : C := ParentBG.Color;
else C := MixColors(ParentBG.Color, iffi(FCommonData.CustomColor, Color, FCommonData.SkinManager.gd[FCommonData.SkinIndex].Color), FCommonData.SkinManager.gd[FCommonData.SkinIndex].Transparency / 100);
end;
if i = 0 then FillDC(DC, R, C) else begin
if FCommonData.FCacheBmp = nil then FCommonData.FCacheBmp := CreateBmp32(Width, Height);
R := PaintBorderFast(NewDC, R, i, FCommonData, 0);
FillDC(NewDC, R, C);
if i > 0 then BitBltBorder(NewDC, 0, 0, Width, Height, FCommonData.FCacheBmp.Canvas.Handle, 0, 0, i);
end;
end;
R := ClientRect;
i := BorderWidth + integer(BevelInner <> bvNone) * BevelWidth + integer(BevelOuter <> bvNone) * BevelWidth;
InflateRect(R, -i, -i);
if DC = 0 then TmpCanvas := Canvas else begin
TmpCanvas := TCanvas.Create;
TmpCanvas.Handle := DC;
TmpCanvas.Font.Assign(Font);
TmpCanvas.Brush.Style := bsClear;
end;
WriteText(R, TmpCanvas);
if Assigned(FOnPaint) then FOnPaint(Self, TmpCanvas);
if DC <> 0 then FreeAndNil(TmpCanvas);
FCommonData.BGChanged := False;
RestoreDC(NewDC, SavedDC);
sVCLUtils.PaintControls(NewDC, Self, True, Point(0, 0));
// if FCommonData.FCacheBmp <> nil then FreeAndNil(FCommonData.FCacheBmp);
end;
if SendUpdated and not (csPaintCopy in ControlState) then SetParentUpdated(Self);
end;
end;
procedure TsPanel.Paint;
begin
inherited;
if Showing and Assigned(FOnPaint) then FOnPaint(Self, Canvas)
end;
procedure TsPanel.PaintWindow(DC: HDC);
begin
if not (csPaintCopy in ControlState) or not SkinData.Skinned then begin
inherited;
end;
OurPaint(DC);
end;
procedure TsPanel.PrepareCache;
var
w : integer;
R : TRect;
begin
if IsCached(FCommonData) or InAnimationProcess or (Self is TsColorsPanel) then begin
InitCacheBmp(SkinData);
PaintSkinControl(FCommonData, Parent, True, 0, Rect(0, 0, Width, Height), Point(Left, Top), FCommonData.FCacheBMP, True);
R := ClientRect;
w := BorderWidth + integer(BevelInner <> bvNone) * BevelWidth + integer(BevelOuter <> bvNone) * BevelWidth;
InflateRect(R, -w, -w);
WriteText(R, FCommonData.FCacheBmp.Canvas);
if Assigned(FOnPaint) then FOnPaint(Self, FCommonData.FCacheBmp.Canvas);
FCommonData.BGChanged := False;
end;
end;
procedure TsPanel.WndProc(var Message: TMessage);
var
SaveIndex: Integer;
DC: HDC;
PS: TPaintStruct;
begin
{$IFDEF LOGGED}
AddToLog(Message);
{$ENDIF}
if Message.Msg = SM_ALPHACMD
then case Message.WParamHi of
AC_CTRLHANDLED : begin Message.Result := 1; Exit end;
AC_GETAPPLICATION : begin Message.Result := longint(Application); Exit end;
AC_REMOVESKIN : begin
ControlStyle := ControlStyle - [csOpaque];
if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) then begin
CommonWndProc(Message, FCommonData);
Invalidate;
end;
AlphaBroadCast(Self, Message);
exit
end;
AC_SETNEWSKIN : begin
ControlStyle := ControlStyle - [csOpaque];
AlphaBroadCast(Self, Message);
if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) then begin
CommonWndProc(Message, FCommonData);
end;
exit
end;
AC_REFRESH : begin
if (LongWord(Message.LParam) = LongWord(SkinData.SkinManager)) then begin
CommonWndProc(Message, FCommonData);
if HandleAllocated and not (csLoading in ComponentState) and Visible then begin
InvalidateRect(Handle, nil, True);
RedrawWindow(Handle, nil, 0, RDW_FRAME or RDW_INVALIDATE or RDW_UPDATENOW or RDW_ERASE);
end;
AlphaBroadCast(Self, Message);
end
else AlphaBroadCast(Self, Message);
exit
end;
AC_GETBG : if (SkinData.SkinManager <> nil) and SkinData.SkinManager.IsValidSkinIndex(SkinData.SkinIndex) then begin
{ if (SkinData.BGChanged or SkinData.HalfVisible) and not SkinData.Updating then begin
if not ((SkinData.SkinManager.gd[SkinData.SkinIndex].Transparency = 100) and (not SkinData.SkinManager.IsValidImgIndex(SkinData.BorderIndex) or (SkinData.SkinManager.ma[SkinData.BorderIndex].DrawMode and BDM_ACTIVEONLY = BDM_ACTIVEONLY)))
then begin
// if IsWindowVisible(Handle) then
PrepareCache;
end;
end;}
InitBGInfo(FCommonData, PacBGInfo(Message.LParam), 0);
if (WidthOf(ClientRect) <> Width) and (PacBGInfo(Message.LParam)^.BgType = btCache) and not PacBGInfo(Message.LParam)^.PleaseDraw then begin
inc(PacBGInfo(Message.LParam)^.Offset.X, BorderWidth + BevelWidth * (integer(BevelInner <> bvNone) + integer(BevelOuter <> bvNone)));
inc(PacBGInfo(Message.LParam)^.Offset.Y, BorderWidth + BevelWidth * (integer(BevelInner <> bvNone) + integer(BevelOuter <> bvNone)));
end;
Exit;
end;
end;
if not ControlIsReady(Self) or not FCommonData.Skinned then begin
case Message.Msg of
WM_PRINT : if Assigned(OnPaint) then begin
OnPaint(Self, Canvas);
if TWMPaint(Message).DC <> 0
then BitBlt(TWMPaint(Message).DC, 0, 0, Width, Height, Canvas.Handle, 0, 0, SRCCOPY);
end;
WM_ERASEBKGND : begin
if not Assigned(FOnPaint) then inherited;
end
else inherited;
end;
end
else begin
if Message.Msg = SM_ALPHACMD then case Message.WParamHi of
AC_ENDPARENTUPDATE : begin
if FCommonData.FUpdating then begin
FCommonData.FUpdating := False;
FCommonData.FUpdating := FCommonData.Updating;
if not FCommonData.FUpdating
then RedrawWindow(Handle, nil, 0, RDW_INVALIDATE or RDW_ERASE or RDW_FRAME or RDW_UPDATENOW);
end;
SetParentUpdated(Self);
Exit;
end;
AC_PREPARING : begin
Message.Result := integer(FCommonData.Updating or FCommonData.FCacheBmp.Empty);
Exit;
end
else if CommonMessage(Message, FCommonData) then Exit;
end
else begin
case Message.Msg of
WM_PRINT : begin
FCommonData.FUpdating := False;
if ControlIsReady(Self) then begin
if not (IsCached(FCommonData) or (Self is TsColorsPanel)) and not Assigned(FCommonData.FCacheBMP) then FCommonData.FCacheBMP := CreateBmp32(0, 0);
DC := TWMPaint(Message).DC;
PrepareCache;
OurPaint(DC, False);
end;
Exit;
end;
WM_PAINT : if Visible or (csDesigning in ComponentState) then begin
DC := BeginPaint(Handle, PS);
FCommonData.FUpdating := FCommonData.Updating;
if IsCached(SkinData) and not FCommonData.FUpdating then begin
if TWMPAINT(Message).DC = 0 then DC := GetDC(Handle) else DC := TWMPAINT(Message).DC;
try
SaveIndex := SaveDC(DC);
ControlState := ControlState + [csCustomPaint];
Canvas.Lock;
try
Canvas.Handle := DC;
try
TControlCanvas(Canvas).UpdateTextFlags;
OurPaint(DC);
finally
Canvas.Handle := 0;
end;
finally
Canvas.Unlock;
end;
RestoreDC(DC, SaveIndex);
finally
ControlState := ControlState - [csCustomPaint];
if TWMPaint(Message).DC = 0 then ReleaseDC(Handle, DC);
end;
end
else {$IFDEF DELPHI7UP}if not ParentBackground then{$ENDIF} begin // If BG is not redrawn automatically
OurPaint(DC) // Repainting of graphic controls
end;
EndPaint(Handle, PS);
Message.Result := 0;
Exit;
end;
CM_TEXTCHANGED : begin
if Parent <> nil then FCommonData.Invalidate;
Exit;
end;
WM_ERASEBKGND : begin
if (Message.WParam <> Message.LParam {PerformEraseBackground, TntSpeedButtons}) then begin
FCommonData.FUpdating := FCommonData.Updating;
if not IsCached(SkinData) and not FCommonData.FUpdating then OurPaint(TWMPaint(Message).DC); // TODO : drawing of graphic controls must be added also
Message.Result := 1;
end
else if (Message.WParam <> 0) then begin // From PaintTo
if FCommonData.BGChanged then PrepareCache;
if not FCommonData.BGChanged then begin
if IsCached(FCommonData)
then BitBlt(TWMPaint(Message).DC, 0, 0, Width, Height, FCommonData.FCacheBmp.Canvas.Handle, 0, 0, SRCCOPY)
else FillDC(TWMPaint(Message).DC, Rect(0, 0, Width, Height), GetControlColor(Handle));
end;
Message.Result := 1;
end;
Exit;
end;
{CM_SHOWINGCHANGED, }CM_VISIBLECHANGED : begin
FCommonData.BGChanged := True;
FCommonData.FUpdating := False;
inherited;
Exit;
end;
CM_INVALIDATE : begin
if FOldBevel <> BevelOuter then begin
case FOldBevel of
bvRaised : begin
if FCommonData.SkinSection = s_Panel then begin
case BevelOuter of
bvNone : FCommonData.SkinSection := s_CheckBox;
bvLowered : FCommonData.SkinSection := s_PanelLow;
end;
end;
end;
bvLowered : begin
if FCommonData.SkinSection = s_PanelLow then begin
case BevelOuter of
bvNone : FCommonData.SkinSection := s_CheckBox;
bvRaised : FCommonData.SkinSection := s_Panel;
end;
end;
end;
bvNone : begin
if FCommonData.SkinSection = s_CheckBox then begin
case BevelOuter of
bvRaised : FCommonData.SkinSection := s_Panel;
bvLowered : FCommonData.SkinSection := s_PanelLow;
end;
end;
end;
end;
FOldBevel := BevelOuter;
end;
end;
CM_COLORCHANGED : if SkinData.CustomColor then SkinData.BGChanged := True;
WM_KILLFOCUS, WM_SETFOCUS: begin inherited; exit end;
WM_WINDOWPOSCHANGING : if SkinData.SkinManager.gd[SkinData.SkinIndex].Transparency <> 0 then FCommonData.BGChanged := True;
WM_SIZE : FCommonData.BGChanged := True;
end;
CommonWndProc(Message, FCommonData);
inherited;
case Message.Msg of
CM_ENABLEDCHANGED : FCommonData.Invalidate;
WM_SETFONT : begin
if Caption <> '' then begin
FCommonData.BGChanged := True;
Repaint;
end;
end;
end;
end;
end;
case Message.Msg of
CM_MOUSEENTER : if Assigned(FOnMouseEnter) then FOnMouseEnter(Self);
CM_MOUSELEAVE : if Assigned(FOnMouseLeave) then FOnMouseLeave(Self);
end;
end;
procedure TsPanel.WriteText(R: TRect; aCanvas : TCanvas = nil; aDC : hdc = 0);
var
C : TCanvas;
TmpRect : TRect;
Flags : Cardinal;
begin
{$IFDEF D2009}
if not ShowCaption then Exit;
{$ENDIF}
if (aCanvas = nil) then begin
if aDC <> 0 then begin
C := TCanvas.Create;
C.Handle := aDC;
end
else Exit;
end
else C := aCanvas;
TmpRect := R;
Flags := GetStringFlags(Self, alignment) or DT_WORDBREAK;
C.Font.Assign(Font);
acDrawText(C.Handle, Caption, TmpRect, Flags or DT_CALCRECT);
R.Top := (HeightOf(R) - HeightOf(TmpRect, True)) div 2 + BorderWidth;
R.Bottom := R.Top + HeightOf(TmpRect, True);
acWriteTextEx(C, PacChar(Caption), Enabled, R, Flags, FCommonData, False);
if (aCanvas = nil) and (C <> nil) then FreeAndNil(C);
end;
{ TsDragBar }
constructor TsDragBar.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
SkinData.COC := COC_TsDragBar;
Caption := ' ';
Align := alTop;
Height := 20;
Font.Color := clCaptionText;
Font.Style := [fsBold];
Color := clActiveCaption;
Cursor := crHandPoint;
{$IFDEF DELPHI7UP}
ParentBackGround := False;
{$ENDIF}
end;
procedure TsDragBar.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
inherited MouseDown(Button, Shift, x, y);
if (Button = mbLeft) and (FDraggedControl <> nil) then begin
ReleaseCapture;
FDraggedControl.Perform(WM_SYSCOMMAND, SC_DRAGMOVE, 0);
if Assigned(OnClick) then OnClick(Self);
if Assigned(OnMouseUp) then OnMouseUp(Self, Button, Shift, X, Y);
end
end;
procedure TsDragBar.ReadState(Reader: TReader);
begin
if (Reader.Parent <> nil) and (DraggedControl = nil) then DraggedControl := GetParentForm(TControl(Reader.Parent));
inherited ReadState(Reader);
end;
procedure TsDragBar.WMActivateApp(var Message: TWMActivateApp);
begin
if Message.Active then Font.Color := clActiveCaption else Font.Color := clInActiveCaption;
end;
procedure TsDragBar.WndProc(var Message: TMessage);
begin
inherited;
if Message.Msg = SM_ALPHACMD
then case Message.WParamHi of
AC_REMOVESKIN : begin
Color := clActiveCaption;
{$IFDEF DELPHI7UP}
ParentBackGround := False;
{$ENDIF}
end;
end;
end;
{ TsGrip }
constructor TsGrip.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Caption := ' ';
SkinData.SkinSection := 'CHECKBOX';
Align := alNone;
Height := 20;
Width := 20;
end;
procedure TsGrip.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
inherited;
end;
procedure TsGrip.Paint;
var
CI : TCacheInfo;
BG : TacBGInfo;
begin
if not ControlIsReady(Self) then Exit;
SkinData.BGChanged := False;
CI.Ready := False;
if Transparent and (LinkedControl <> nil) then begin
BG.PleaseDraw := False;
GetBGInfo(@BG, LinkedControl);
CI := BGInfoToCI(@BG);
end;
if CI.Ready then begin
BitBlt(Canvas.Handle, 0, 0, Width, Height, CI.Bmp.Canvas.Handle, CI.Bmp.Width - Width + CI.X, CI.Bmp.Height - Height + CI.Y, SRCCOPY);
end
else FillDC(Canvas.Handle, Rect(0, 0, Width, Height), CI.FillColor);
end;
{ TsColorsPanel }
procedure TsColorsPanel.AfterConstruction;
begin
inherited;
GenerateColors;
end;
function TsColorsPanel.ColorValue: TColor;
begin
if FItemIndex = -1 then Result := clWhite else Result := ColorsArray[FItemIndex].Color;
end;
function TsColorsPanel.Count: integer;
begin
Result := FColors.Count;
end;
constructor TsColorsPanel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Caption := ' ';
FColors := TStringList.Create;
FItemIndex := -1;
ItemHeight := 21;
ItemWidth := 21;
FColCount := 5;
FRowCount := 2;
FItemMargin := 6;
Height := 60;
Width := 140;
end;
destructor TsColorsPanel.Destroy;
begin
FreeAndNil(FColors);
inherited Destroy;
end;
procedure TsColorsPanel.GenerateColors;
var
i, x, y : integer;
s : string;
begin
SetLength(ColorsArray, 0);
i := 0;
for y := 0 to RowCount - 1 do for x := 0 to ColCount - 1 do begin
SetLength(ColorsArray, i + 1);
if i < FColors.Count then begin
s := ExtractWord(1, FColors[i], [#13, #10, ' ']);
ColorsArray[i].Color := SwapInteger(HexToInt(s));
end
else begin
ColorsArray[i].Color := SwapInteger(ColorToRgb(clWhite));
FColors.Add('FFFFFF');
end;
ColorsArray[i].Index := i;
ColorsArray[i].Selected := i = FItemIndex;
ColorsArray[i].R.Left := ItemMargin + x * (ItemWidth + ItemMargin);
ColorsArray[i].R.Top := ItemMargin + y * (ItemHeight + ItemMargin);
ColorsArray[i].R.Right := ColorsArray[i].R.Left + ItemWidth;
ColorsArray[i].R.Bottom := ColorsArray[i].R.Top + ItemHeight;
inc(i);
end;
end;
function TsColorsPanel.GetItemByCoord(p : TPoint): integer;
var
i : integer;
R : TRect;
begin
Result := - 1;
for i := 0 to Count - 1 do begin
R := ColorsArray[i].R;
InflateRect(R, ItemMargin, ItemMargin);
if PtInRect(R, p) then begin
Result := i;
Exit;
end
end;
end;
procedure TsColorsPanel.Loaded;
begin
inherited;
GenerateColors;
end;
procedure TsColorsPanel.MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
inherited;
SetFocus;
ItemIndex := GetItemByCoord(Point(x, y));
end;
procedure TsColorsPanel.OurPaint;
var
b : boolean;
R : TRect;
NewDC : hdc;
Brush : TBrush;
begin
if DC <> 0 then NewDC := DC else NewDC := Canvas.Handle;
if (csDestroying in ComponentState) or (csCreating in Parent.ControlState) or not Assigned(FCommonData) then Exit;
if FCommonData.Skinned then begin
FCommonData.Updating := FCommonData.Updating;
if not FCommonData.Updating then begin
InitCacheBmp(SkinData);
// If transparent and in a form resizing
b := True or FCommonData.BGChanged or FCommonData.HalfVisible or GetBoolMsg(Parent, AC_GETHALFVISIBLE);
FCommonData.HalfVisible := not (PtInRect(Parent.ClientRect, Point(Left, Top)) and
PtInRect(Parent.ClientRect, Point(Left + Width, Top + Height)));
if b and not FCommonData.UrgentPainting then begin
PaintItem(FCommonData, GetParentCache(FCommonData), False, 0, Rect(0, 0, width, Height), Point(Left, Top), FCommonData.FCacheBMP, False);
WriteText(ClientRect);
FCommonData.BGChanged := False;
if not Assigned(FOnPaint)
then PaintColors(FCommonData.FCacheBmp.Canvas.Handle);
end;
if Assigned(FOnPaint)
then FOnPaint(Self, FCommonData.FCacheBmp.Canvas);
CopyWinControlCache(Self, FCommonData, Rect(0, 0, 0, 0), Rect(0, 0, Width, Height), NewDC, True);
sVCLUtils.PaintControls(NewDC, Self, b, Point(0, 0));
if SendUpdated then SetParentUpdated(Self);
end;
end
else begin
inherited;
Perform(WM_NCPAINT, 0, 0);
if not Assigned(FOnPaint) then PaintColors(NewDC);
end;
// Selected item
if (FItemIndex <> -1) and not Assigned(FOnPaint) then begin
R := ColorsArray[FItemIndex].R;
Brush := TBrush.Create;
Brush.Style := bsSolid;
Brush.Color := clWhite;
InflateRect(R, 1, 1);
FrameRect(NewDC, R, Brush.Handle);
InflateRect(R, 1, 1);
Brush.Color := 0;
FrameRect(NewDC, R, Brush.Handle);
if Focused then begin
Brush.Color := clWhite;
InflateRect(R, 2, 2);
DrawFocusRect(NewDC, R);
end;
FreeAndNil(Brush);
end;
end;
procedure TsColorsPanel.PaintColors(const DC: hdc);
var
i : integer;
begin
for i := 0 to Count - 1 do FillDC(DC, ColorsArray[i].R, ColorsArray[i].Color);
end;
procedure TsColorsPanel.SetColCount(const Value: integer);
begin
if FColCount <> Value then begin
FColCount := Value;
GenerateColors;
SkinData.Invalidate;
end;
end;
procedure TsColorsPanel.SetColors(const Value: TStrings);
begin
FColors.Assign(Value);
GenerateColors;
SkinData.Invalidate;
end;
procedure TsColorsPanel.SetItemHeight(const Value: integer);
begin
if FItemHeight <> Value then begin
FItemHeight := Value;
GenerateColors;
SkinData.Invalidate;
end;
end;
procedure TsColorsPanel.SetItemIndex(const Value: integer);
begin
if FItemIndex > Count - 1 then FItemIndex := - 1;
if FItemIndex <> Value then begin
if FItemIndex <> -1 then ColorsArray[FItemIndex].Selected := False;
OldSelected := FItemIndex;
FItemIndex := Value;
if FItemIndex <> -1 then ColorsArray[FItemIndex].Selected := True;
if Assigned(FOnChange) then FOnChange(Self);
Repaint;
end;
end;
procedure TsColorsPanel.SetItemMargin(const Value: integer);
begin
if FItemMargin <> Value then begin
FItemMargin := Value;
GenerateColors;
SkinData.Invalidate;
end;
end;
procedure TsColorsPanel.SetItemWidth(const Value: integer);
begin
if FItemWidth <> Value then begin
FItemWidth := Value;
GenerateColors;
SkinData.Invalidate;
end;
end;
procedure TsColorsPanel.SetRowCount(const Value: integer);
begin
if FRowCount <> Value then begin
FRowCount := Value;
GenerateColors;
SkinData.Invalidate;
end;
end;
procedure TsColorsPanel.WndProc(var Message: TMessage);
begin
inherited;
case Message.Msg of
WM_SETFOCUS, WM_KILLFOCUS : begin
if FItemIndex <> -1 then Repaint;
end;
end;
end;
end.
|
unit LibUnit;
interface
function TiraPontos(varTexto: string): string;
implementation
function TiraPontos(varTexto: string): string;
var
I: Integer;
varResultado: string;
begin
varResultado := '';
for I := 1 to length(varTexto) do
begin
if not (varTexto[I] in ['!','?','.','-',',',';','/','\','|','@','$','&','%','(',')','[',']','{','}','=','+','_','*']) then
begin
varResultado := varResultado + varTexto[I];
end;
end;
Result := varResultado;
end;
end.
|
//////////////////////////////////////////////////////////
// Desenvolvedor: Humberto Sales de Oliveira //
// Email: humbertoliveira@hotmail.com //
// humbertosales@midassistemas.com.br //
// humberto_s_o@yahoo.com.br //
// Objetivo: //
// 1)Conectar software atraves da Intranet //
// usando os componentes ZEOS //
// //
// licensa: free //
// //
// *Auterações, modificações serão bem vindos //
// Créditos: //
// //
//////////////////////////////////////////////////////////
unit zcon;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils,conecta,db,ZDataset,ZConnection;
Type
{ TZCon }
TZCon = Class(TBaseConector)
Private
FCon : TZConnection;
Fconectado : Boolean;
Public
Constructor create(Configuracao : TPathBanco); overload;
Destructor destroy;override;
Function CriarQuery : TBaseQuery; Override;
Function CriarDataSource : TDataSource; virtual; Abstract;
procedure open; Override;
procedure close; Override;
published
property Conectado : boolean read FConectado default false;
end;
{ TZQry }
TZQry = Class(TBaseQuery)
Private
FQuery : TZQuery;
FDataSource : TDataSource;
Public
Constructor create;
Destructor Destroy;
procedure Open; override;
procedure close; override;
procedure execsql; override;
function dataset : TDataSet; override;
function sql : TStrings; override;
Function fields : Tfields; override;
function params : TParams; override;
function ParambyName(Const AparamName : String): TParam; override;
function IsEmpty : Boolean; override;
procedure CriarDataSource; override;
Function DataSource : TDataSource; override;
Published
Property query : TZQuery read FQuery;
end;
implementation
{ TZQry }
constructor TZQry.create;
begin
FQuery := TZQuery.Create(nil);
CriarDataSource;
end;
destructor TZQry.Destroy;
begin
FreeAndNil(FDataSource);
FreeAndNil(FQuery);
inherited destroy;
end;
procedure TZQry.Open;
begin
FQuery.Open;
end;
procedure TZQry.close;
begin
FQuery.Close;
end;
procedure TZQry.execsql;
begin
FQuery.ExecSQL;
end;
function TZQry.dataset: TDataSet;
begin
Result := FQuery;
end;
function TZQry.sql: TStrings;
begin
Result := FQuery.Sql;
end;
function TZQry.fields: Tfields;
begin
Result := Fquery.Fields;
end;
function TZQry.params: TParams;
begin
Result := FQuery.Params;
end;
function TZQry.ParambyName(const AparamName: String): TParam;
begin
Result := FQuery.ParamByName(AparamName);
end;
function TZQry.IsEmpty: Boolean;
begin
Result := FQuery.IsEmpty;
end;
procedure TZQry.CriarDataSource;
begin
fDataSource := TDataSource.Create(Nil);
DataSource.DataSet := FQuery;
end;
function TZQry.DataSource: TDataSource;
begin
Result := fDataSource;
end;
{ TZCon }
constructor TZCon.create(Configuracao: TPathBanco);
begin
Try
Fcon := TZConnection.Create(nil);
With Fcon,Configuracao do
begin
Hostname := IP;
DataBase := Banco;
Port := StrToInt(Porta);
User := Usuario;
Password := Senha;
Protocol := TipoBanco;
Open;
end;
Except
Raise Exception.Create('Houve um erro ao inserir as configurações no arquivo "PathBanco.txt" para o componente ZConnection.' + #13 + 'Corrija as configurações e tente novamente!');
end;
end;
destructor TZCon.destroy;
begin
FreeAndNil(FCon);
end;
function TZCon.CriarQuery: TBaseQuery;
Var
Qry : TZQry;
begin
Qry := TZQry.create;
Qry.FQuery.Connection := FCon;
Result := Qry
end;
procedure TZCon.open;
begin
Fcon.Connected:= true;
FConectado := true;
end;
procedure TZCon.close;
begin
Fcon.Connected:= false;
FConectado := False;
end;
end.
|
unit AsyncIO.Filesystem;
interface
uses
AsyncIO;
type
FileAccess = (faRead, faWrite, faReadWrite);
FileCreationDisposition = (fcCreateNew, fcCreateAlways, fcOpenExisting, fcOpenAlways, fcTruncateExisting);
FileShareMode = (fsNone, fsDelete, fsRead, fsWrite, fsReadWrite);
function NewAsyncFileStream(const Service: IOService;
const Filename: string;
const CreationDisposition: FileCreationDisposition;
const Access: FileAccess;
const ShareMode: FileShareMode): AsyncFileStream;
implementation
uses
AsyncIO.Filesystem.Detail;
function NewAsyncFileStream(const Service: IOService;
const Filename: string;
const CreationDisposition: FileCreationDisposition;
const Access: FileAccess;
const ShareMode: FileShareMode): AsyncFileStream;
begin
result := AsyncFileStreamImpl.Create(
Service, Filename, CreationDisposition, Access, ShareMode
);
end;
end.
|
// ----------------------------------------------------------------------------
// Unit : PxCrt32.pas - a part of PxLib
// Author : Matthias Hryniszak
// Date :
// Version : 1.0
// Description : Utilities for console handling (previously found in the
// Crt.pas in Borland Pascal).
// Changes log : 2004-12-xx - initial version
// 2005-05-03 - compatibility issues with freepascal solved.
// ToDo : Testing, comments in code.
// ----------------------------------------------------------------------------
unit PxCrt32;
{$I PxDefines.inc}
interface
uses
Windows, Messages, SysUtils;
{$IFDEF WIN32}
const
Black = 0;
Blue = 1;
Green = 2;
Cyan = 3;
Red = 4;
Magenta = 5;
Brown = 6;
LightGray = 7;
DarkGray = 8;
LightBlue = 9;
LightGreen = 10;
LightCyan = 11;
LightRed = 12;
LightMagenta = 13;
Yellow = 14;
White = 15;
function WhereX: Integer;
function WhereY: Integer;
procedure ClrEol;
procedure ClrScr;
procedure InsLine;
procedure DelLine;
procedure GotoXY(const X, Y: Integer);
procedure HighVideo;
procedure LowVideo;
procedure NormVideo;
procedure TextBackground(const Color: Word);
procedure TextColor(const Color: Word);
procedure TextAttribut(const Color, Background: Word);
procedure Delay(const Miliseconds: Integer);
function KeyPressed: Boolean;
function ReadKey: Char;
procedure Sound;
procedure NoSound;
procedure ConsoleEnd;
procedure FlushInputBuffer;
function Pipe: Boolean;
var
hConsoleInput : THandle;
hConsoleOutput: THandle;
hConsoleError : THandle;
WindMin : TCoord;
WindMax : TCoord;
ViewMax : TCoord;
TextAttr : Word;
LastMode : Word;
SoundFrequenz : Integer;
SoundDuration : Integer;
{$ENDIF WIN32}
implementation
{$IFDEF WIN32}
var
StartAttr: Word;
OldCP : Integer;
CrtPipe : Boolean;
German : Boolean;
procedure ClrEol;
var
Coords: TCoord;
Len, NW: LongWord;
CBI: TConsoleScreenBufferInfo;
begin
GetConsoleScreenBufferInfo(hConsoleOutput, CBI);
Len := CBI.dwsize.X - CBI.dwCursorPosition.X;
Coords.X := CBI.dwCursorPosition.X;
Coords.Y := CBI.dwCursorPosition.Y;
FillConsoleOutputAttribute(hConsoleOutput, TextAttr,len, Coords, NW);
FillConsoleOutputCharacter(hConsoleOutput, #32, len, Coords, NW);
end;
procedure ClrScr;
var
Coords: TCoord;
NW: LongWord;
CBI: TConsoleScreenBufferInfo;
begin
GetConsoleScreenBufferInfo(hConsoleOutput, CBI);
Coords.X := 0;
Coords.Y := 0;
FillConsoleOutputAttribute(hConsoleOutput, TextAttr, CBI.dwsize.X * CBI.dwsize.Y, Coords, NW);
FillConsoleOutputCharacter(hConsoleOutput,#32, CBI.dwsize.X * CBI.dwsize.Y, Coords, NW);
SetConsoleCursorPosition(hConsoleOutput, Coords);
end;
function WhereX: Integer;
var
CBI: TConsoleScreenBufferInfo;
begin
GetConsoleScreenBufferInfo(hConsoleOutput, CBI);
Result := TCoord(CBI.dwCursorPosition).X + 1
end;
function WhereY: Integer;
var
CBI: TConsoleScreenBufferInfo;
begin
GetConsoleScreenBufferInfo(hConsoleOutput, CBI);
Result := TCoord(CBI.dwCursorPosition).Y + 1
end;
procedure GotoXY(const X, Y: Integer);
var
Coord: TCoord;
begin
Coord.X := X - 1;
Coord.X := Y - 1;
setConsoleCursorPosition(hConsoleOutput, Coord);
end;
procedure InsLine;
var
CBI: TConsoleScreenBufferInfo;
SSR: TSmallRect;
{$IFDEF FPC}
SCR: TSmallRect;
{$ENDIF}
Coord: TCoord;
CI: TCharInfo;
NW: LongWord;
begin
GetConsoleScreenBufferInfo(hConsoleOutput, CBI);
Coord := CBI.dwCursorPosition;
SSR.Left := 0;
SSR.Top := Coord.Y;
SSR.Right := CBI.srWindow.Right;
SSR.Bottom := CBI.srWindow.Bottom;
CI.AsciiChar := #32;
CI.Attributes := CBI.wAttributes;
Coord.X := 0;
Coord.Y := Coord.Y + 1;
{$IFDEF FPC}
FillChar(SCR, SizeOf(SCR), 0);
ScrollConsoleScreenBuffer(hConsoleOutput, SSR, SCR, Coord, CI);
{$ENDIF}
{$IFDEF DELPHI}
ScrollConsoleScreenBuffer(hConsoleOutput, SSR, nil, Coord, CI);
{$ENDIF}
Coord.Y := Coord.Y-1;
FillConsoleOutputAttribute(hConsoleOutput, TextAttr, CBI.dwsize.X * CBI.dwsize.Y, Coord, NW);
end;
procedure DelLine;
var
CBI: TConsoleScreenBufferInfo;
SSR: TSmallRect;
{$IFDEF FPC}
SCR: TSmallRect;
{$ENDIF}
Coord: TCoord;
CI: TCharInfo;
NW: LongWord;
begin
GetConsoleScreenBufferInfo(hConsoleOutput, CBI);
Coord := CBI.dwCursorPosition;
SSR.Left := 0;
SSR.Top := Coord.Y + 1;
SSR.Right := CBI.srWindow.Right;
SSR.Bottom := CBI.srWindow.Bottom;
CI.AsciiChar := #32;
CI.Attributes := CBI.wAttributes;
Coord.X := 0;
Coord.Y := Coord.Y;
{$IFDEF FPC}
FillChar(SCR, SizeOf(SCR), 0);
ScrollConsoleScreenBuffer(hConsoleOutput, SSR, SCR, Coord, CI);
{$ENDIF}
{$IFDEF DELPHI}
ScrollConsoleScreenBuffer(hConsoleOutput, SSR, nil, Coord, CI);
{$ENDIF}
FillConsoleOutputAttribute(hConsoleOutput, TextAttr, CBI.dwsize.X * CBI.dwsize.Y, Coord, NW);
end;
procedure TextBackground(const Color: Word);
begin
LastMode := TextAttr;
TextAttr := (Color shl $04) or (TextAttr and $0F);
SetConsoleTextAttribute(hConsoleOutput, TextAttr);
end;
procedure TextColor(const Color: Word);
begin
LastMode := TextAttr;
TextAttr := (Color and $0F) or (TextAttr and $F0);
SetConsoleTextAttribute(hConsoleOutput, TextAttr);
end;
procedure TextAttribut(const Color, Background: Word);
begin
LastMode := TextAttr;
TextAttr := (Color and $0F) or (Background shl $04);
SetConsoleTextAttribute(hConsoleOutput, TextAttr);
end;
procedure HighVideo;
begin
LastMode := TextAttr;
TextAttr := TextAttr or $08;
SetConsoleTextAttribute(hConsoleOutput, TextAttr);
end;
procedure LowVideo;
begin
LastMode := TextAttr;
TextAttr := TextAttr and $F7;
SetConsoleTextAttribute(hConsoleOutput, TextAttr);
end;
procedure NormVideo;
begin
LastMode := TextAttr;
TextAttr := StartAttr;
SetConsoleTextAttribute(hConsoleOutput, TextAttr);
end;
procedure FlushInputBuffer;
begin
FlushConsoleInputBuffer(hConsoleInput)
end;
function KeyPressed: Boolean;
var
NumberOfEvents: LongWord;
begin
GetNumberOfConsoleInputEvents(hConsoleInput, NumberOfEvents);
Result := NumberOfEvents > 0;
end;
function ReadKey: Char;
var
NumRead: LongWord;
InputRec: TInputRecord;
begin
while not ReadConsoleInput(hConsoleInput, InputRec, 1, NumRead) or (InputRec.EventType <> KEY_EVENT) do;
{$IFDEF FPC}
Result := InputRec.Event.KeyEvent.AsciiChar;
{$ENDIF}
{$IFDEF DELPHI}
Result := InputRec.KeyEvent.AsciiChar;
{$ENDIF}
end;
procedure Delay(const Miliseconds: Integer);
begin
Sleep(Miliseconds);
end;
procedure Sound;
begin
Windows.Beep(SoundFrequenz, SoundDuration);
end;
procedure NoSound;
begin
Windows.Beep(SoundFrequenz, 0);
end;
procedure ConsoleEnd;
begin
if IsConsole and not CrtPipe then
begin
if WhereX > 1 then Writeln;
TextColor(Green);
SetFocus(GetCurrentProcess);
Write('Press any key!');
NormVideo;
FlushInputBuffer;
ReadKey;
FlushInputBuffer;
end;
end;
function Pipe: Boolean;
begin
Result := CrtPipe;
end;
procedure Init;
var
CBI: TConsoleScreenBufferInfo;
Coords : TCoord;
begin
SetActiveWindow(0);
hConsoleInput := GetStdHandle(STD_INPUT_HANDLE);
hConsoleOutput := GetStdHandle(STD_OUTPUT_HANDLE);
hConsoleError := GetStdHandle(STD_ERROR_HANDLE);
if GetConsoleScreenBufferInfo(hConsoleOutput, CBI) then
begin
TextAttr := CBI.wAttributes;
StartAttr := CBI.wAttributes;
lastmode := CBI.wAttributes;
Coords.X := CBI.srWindow.Left + 1;
Coords.Y := CBI.srWindow.Top + 1;
WindMin := Coords;
ViewMax := CBI.dwsize;
Coords.X := CBI.srWindow.Right + 1;
Coords.Y := CBI.srWindow.Bottom + 1;
WindMax := Coords;
crtpipe := False;
end
else CrtPipe := True;
SoundFrequenz := 1000;
SoundDuration := -1;
OldCP := GetConsoleOutputCP;
SetConsoleOutputCP(1252);
German := $07 = (LoWord(GetUserDefaultLangID) and $03FF);
end;
initialization
Init;
finalization
SetConsoleoutputCP(OldCP);
{$ENDIF WIN32}
end.
|
// Simple hash table unit. The key value is always a string, while each
// entry can contain a string and/or an integer.
// By Ingemar 2012.
// Some thoughts while developing:
// What should I add beyond the obvious?
// Dynamic resizing on overflow! OK!
// Multiple type support? Integer + strings (could be anything - pointer?) OK!
// Seems pretty OK...
unit HashTableUnit;
interface
type
HashRec = record
hashTableKeys: array of AnsiString; // Keys
hashTableValues: array of Longint; // Values
hashTableStringValues: array of AnsiString; // String values
hashMembers: Longint; // Number of occupied spaces
failureValue: Integer; failureString: AnsiString; // Values to return if lookup fails
end;
// function HashGetIndex(fileName: AnsiString; hashLength: Longint): Longint;
procedure HashInitTable(var h: HashRec; failureValue: Integer; failureString: AnsiString; hashLength: Longint);overload;
procedure HashInitTable(var h: HashRec; failureValue: Integer; failureString: AnsiString);overload;
procedure HashInitTable(var h: HashRec);overload;
//procedure HashExpandTable(var h: HashRec);
procedure HashAddEntry(var h: HashRec; keyValue: AnsiString; intValue: Longint; stringValue: AnsiString); overload;
procedure HashAddEntry(var h: HashRec; keyValue: AnsiString; intValue: Longint); overload;
procedure HashAddEntry(var h: HashRec; keyValue: AnsiString; stringValue: AnsiString); overload;
procedure HashLookUp(var h: HashRec; keyValue: AnsiString; var intValue: Longint; var stringValue: AnsiString);
function HashLookUpInteger(var h: HashRec; keyValue: AnsiString): Longint;
function HashLookUpString(var h: HashRec; keyValue: AnsiString): AnsiString;
procedure HashDeleteEntry(var h: HashRec; keyValue: AnsiString);
procedure PrintHashTable(var h: HashRec);
implementation
const
kHashLength = 1024;
function HashGetIndex(key: AnsiString; hashLength: Longint): Longint;
var
i, index: Longint;
begin
index := 0;
// Generate hash index
for i := 1 to Length(key) do
begin
index := index * 2 + Ord(key[i]);
end;
// WriteLn('Start index before mod for ', key, ', ', index);
index := abs(index) mod hashLength;
// WriteLn('Start index for ', key, ' is ', index);
HashGetIndex := index;
end;
procedure HashInitTable(var h: HashRec; failureValue: Integer; failureString: AnsiString; hashLength: Longint);overload;
var
i: Longint;
begin
h.hashMembers := 0;
SetLength(h.hashTableKeys, hashLength);
SetLength(h.hashTableValues, hashLength);
SetLength(h.hashTableStringValues, hashLength);
for i := 0 to High(h.hashTableKeys) do
begin
h.hashTableKeys[i] := ''; // Empty key = free space
h.hashTableValues[i] := 0;
h.hashTableStringValues[i] := '';
end;
h.failureValue := failureValue;
h.failureString := failureString;
end;
procedure HashInitTable(var h: HashRec; failureValue: Integer; failureString: AnsiString);overload;
begin
HashInitTable(h, failureValue, failureString, kHashLength);
end;
procedure HashInitTable(var h: HashRec);overload;
begin
HashInitTable(h, 0, '', kHashLength);
end;
procedure HashExpandTable(var h: HashRec);
var
i, l: Longint;
h2: HashRec; // Temp table
begin
// Clear h2 but with double length
l := Length(h.hashTableKeys);
WriteLn('Expanding table to ', l*2);
SetLength(h2.hashTableKeys, l * 2);
SetLength(h2.hashTableValues, l * 2);
SetLength(h2.hashTableStringValues, l * 2);
for i := 0 to High(h2.hashTableKeys) do
begin
h2.hashTableKeys[i] := ''; // Empty key = free space
h2.hashTableValues[i] := 0;
h2.hashTableStringValues[i] := '';
end;
h2.hashMembers := 0;
// Take all entries in h and put in h2
for i := 0 to High(h.hashTableKeys) do
begin
if Length(h.hashTableKeys[i]) > 0 then
begin
HashAddEntry(h2, h.hashTableKeys[i], h.hashTableValues[i], h.hashTableStringValues[i]);
end;
end;
// Copy h2 to h. Is it this easy?
h := h2;
end;
procedure HashAddEntry(var h: HashRec; keyValue: AnsiString; intValue: Longint; stringValue: AnsiString); overload;
var
index: Longint;
begin
index := HashGetIndex(keyValue, Length(h.hashTableKeys));
if h.hashMembers > Length(h.hashTableKeys) div 2 then
HashExpandTable(h);
while true do
begin
if (Length(h.hashTableKeys[index]) = 0) or (h.hashTableKeys[index] = keyValue) then {Ledig plats eller fanns redan, skall uppdateras}
begin
h.hashTableKeys[index] := keyValue;
h.hashTableValues[index] := intValue;
h.hashTableStringValues[index] := stringValue;
h.hashMembers := h.hashMembers + 1;
Exit;
end;
index := (index + 1) mod Length(h.hashTableKeys); // and kHashLength;
end;
end;
procedure HashAddEntry(var h: HashRec; keyValue: AnsiString; intValue: Longint); overload;
var
i: Longint;
begin
HashAddEntry(h, keyValue, intValue, '');
// TEST
i := HashLookUpInteger(h, keyValue);
if intValue <> i then
begin
WriteLn(keyValue, ' entered ', intValue, ' and got back ', i);
WriteLn('***** ERROR!!! *****');
end;
end;
procedure HashAddEntry(var h: HashRec; keyValue: AnsiString; stringValue: AnsiString); overload;
begin
HashAddEntry(h, keyValue, 0, stringValue);
end;
procedure HashLookUp(var h: HashRec; keyValue: AnsiString; var intValue: Longint; var stringValue: AnsiString);
var
index: Longint;
begin
index := HashGetIndex(keyValue, Length(h.hashTableKeys));
// This should not happen but it does:
if (index < 0) or (index >= Length(h.hashTableKeys)) then
begin
WriteLn('ERROR: index = ', index, ' length = ', Length(h.hashTableKeys), ' for key value ', keyValue);
intValue := h.failureValue;
stringValue := h.failureString;
Exit;
end;
while true do
begin
if Length(h.hashTableKeys[index]) = 0 then {Ledig plats - fanns inte}
begin
// return kOtherToken; {Fanns inte i listan innan!}
intValue := h.failureValue;
stringValue := h.failureString;
Exit;
end;
if h.hashTableKeys[index] = keyValue then
begin
// return h.hashTableValues[index];
intValue := h.hashTableValues[index];
stringValue := h.hashTableStringValues[index];
Exit;
end;
index := (index + 1) mod Length(h.hashTableKeys); // kHashLength;
// eller and med Length(h.hashTableKeys)-1 fšr lite bŠttre fart?
end;
end;
function HashLookUpInteger(var h: HashRec; keyValue: AnsiString): Longint;
var
intValue: Longint;
stringValue: AnsiString;
begin
HashLookUp(h, keyValue, intValue, stringValue);
HashLookUpInteger := intValue;
end;
function HashLookUpString(var h: HashRec; keyValue: AnsiString): AnsiString;
var
intValue: Longint;
stringValue: AnsiString;
begin
HashLookUp(h, keyValue, intValue, stringValue);
HashLookUpString := stringValue;
end;
procedure HashDeleteEntry(var h: HashRec; keyValue: AnsiString);
// May be nontrivial if someone has skipped the space
// Loop through all following entries until we find a space,
// test these against position of new space?
var
index: Longint;
// deletedIndex: Longint;
tmpKeyValue: AnsiString;
tmpIntValue: Longint;
tmpStringValue: AnsiString;
begin
index := HashGetIndex(keyValue, Length(h.hashTableKeys));
if h.hashMembers > Length(h.hashTableKeys) div 2 then
HashExpandTable(h);
while true do
begin
if h.hashTableKeys[index] = keyValue then
begin
// deletedIndex := index;
h.hashTableKeys[index] := '';
h.hashTableValues[index] := 0;
h.hashTableStringValues[index] := '';
h.hashMembers := h.hashMembers - 1;
break;
end;
index := (index + 1) mod Length(h.hashTableKeys);
end;
// Sšk framŒt till nŠsta lediga. Finns nŒgon i den sekvensen som hellre vill ha den nu lediga?
// MEN tar vi bort den upprepar sig problemet!
// Enkel lšsning? Delete pŒ alla i sekvens efter och lŠgg in dem igen? Rekursivt borde vŠl funka?
index := (index + 1) mod Length(h.hashTableKeys);
while true do
begin
if Length(h.hashTableKeys[index]) = 0 then {Ledig plats}
Exit;
begin
tmpKeyValue := h.hashTableKeys[index];
tmpIntValue := h.hashTableValues[index];
tmpStringValue := h.hashTableStringValues[index];
HashDeleteEntry(h, tmpKeyValue);
HashAddEntry(h, tmpKeyValue, tmpIntValue, tmpStringValue);
end;
index := (index + 1) mod Length(h.hashTableKeys);
end;
end;
procedure PrintHashTable(var h: HashRec);
var
i: Longint;
begin
for i := 0 to High(h.hashTableKeys) do
begin
if Length(h.hashTableKeys[i]) = 0 then
WriteLn('-')
else
WriteLn(h.hashTableKeys[i], ': ', h.hashTableValues[i]:1, ', "', h.hashTableStringValues[i], '"')
end;
end;
end.
|
unit Core.BaseInterfaces;
interface
uses
Spring.Collections
, Spring.DesignPatterns
, Rtti
;
type
IGameObserver = interface
['{12747FB2-8809-464D-A8C0-278DEF88F8CF}']
procedure Update(const AData: TValue);
end;
IGameObservable = interface (IObservable<IGameObserver>)
['{A001A725-CBCF-4952-B1CB-A860B244A4E9}']
procedure UpdateView(const AGameData: TValue);
end;
IGameLink<T> = interface
['{993631F9-E46D-4D6A-A067-E7E38E7BAC60}']
function UpdateLink: TValue;
end;
IGameConfig = interface
['{2C5CFA02-6ED1-4DF5-AE83-EE2D2D0A91FB}']
function GetMaxFrameCount: Integer;
function GetLastFrameMaxRollCount: Integer;
function GetNonLastFrameMaxRollCount: Integer;
function GetMaxPinCountPerRoll: Integer;
property MaxFrameCount: Integer read GetMaxFrameCount;
property NonLastFrameMaxRollCount: Integer read GetNonLastFrameMaxRollCount;
property LastFrameMaxRollCount: Integer read GetLastFrameMaxRollCount;
property MaxPinCountPerRoll: Integer read GetMaxPinCountPerRoll;
end;
IGameLinkedList<T> = interface(ILinkedList<T>)
['{7CC38B03-DCC0-49BD-864C-FE14384DD72A}']
end;
IGameDataProcessor<K, V> = interface
['{474FB646-5BEF-4C0A-A7D0-956813A74EFF}']
//clear the dictionary
procedure Clear;
//dictionary item count
function GetCount: Integer;
//get the queue item count i.e. dictionary value at this key level
function GetCountAtKey(const AKey: K): Integer;
//push an entry in queue i.e. dictionary value at this key level
procedure AddItemAtKey(const AKey: K; const AValue: V);
//pop an entry from the queue i.e. dictionary value at this key level
function ExtractItemAtKey(const AKey: K): V;
//extract the entry i.e. queue from the dictionary
function Extract(const AKey: K): IGameLinkedList<V>;
//process all links i.e. queue from the dictionary
procedure ProcessData( AKey: K; AInitialParam: TValue );
property Count: Integer read GetCount;
property CountAtKey[const AKey: K]: Integer read GetCountAtKey;
end;
implementation
end.
|
unit NewsCategoryEditForm;
interface
uses
Forms, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, DB,
cxDBData, TB2Item, Classes, ActnList, TB2Dock, TB2Toolbar,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGridLevel,
cxClasses, cxControls, cxGridCustomView, Controls, cxGrid, ComCtrls;
type
TCategoryEditForm = class(TForm)
cxGridDBTableView1: TcxGridDBTableView;
cxGridLevel1: TcxGridLevel;
cxGrid: TcxGrid;
title: TcxGridDBColumn;
TBDock1: TTBDock;
TBToolbar1: TTBToolbar;
ActionList: TActionList;
Ins: TAction;
Del: TAction;
MoveUp: TAction;
MoveDown: TAction;
Edit: TAction;
TBItem1: TTBItem;
TBItem2: TTBItem;
TBItem3: TTBItem;
TBItem4: TTBItem;
TBSeparatorItem1: TTBSeparatorItem;
TBItem5: TTBItem;
StatusBar1: TStatusBar;
name: TcxGridDBColumn;
procedure InsExecute(Sender: TObject);
procedure EditExecute(Sender: TObject);
procedure DelExecute(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
function GetCategoryEditForm: Integer;
implementation
uses NewsDM, NewsMainForm, Windows;
{$R *.dfm}
function GetCategoryEditForm: Integer;
var
Form: TCategoryEditForm;
begin
Form := TCategoryEditForm.Create(Application);
try
Result := Form.ShowModal;
finally
Form.Free;
end;
end;
procedure TCategoryEditForm.InsExecute(Sender: TObject);
begin
DM.Categories.Append;
end;
procedure TCategoryEditForm.EditExecute(Sender: TObject);
begin
DM.Categories.Edit;
end;
procedure TCategoryEditForm.DelExecute(Sender: TObject);
begin
if MessageBox(Handle, 'Вы точно уверены что хотите удалить ?',
PChar(Caption), MB_ICONQUESTION + MB_OKCANCEL + MB_DEFBUTTON2) = IDOK then
DM.Categories.Delete;
end;
end.
|
{ *******************************************************************************
Title: T2TiPDV
Description: DataModule
The MIT License
Copyright: Copyright (C) 2015 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije
@version 1.0
******************************************************************************* }
unit UDataModuleConexao;
interface
uses
System.SysUtils, System.Classes, Data.DB, Data.SqlExpr, Forms,
Data.DBXMySQL;
type
TFDataModuleConexao = class(TDataModule)
Conexao: TSQLConnection;
procedure DataModuleCreate(Sender: TObject);
private
{ Private declarations }
var Banco: String;
procedure ConfigurarConexao(var pConexao: TSQLConnection; pBD: String);
public
{ Public declarations }
procedure Conectar(BD: String);
procedure Desconectar;
function getConexao: TSQLConnection;
function getBanco: String;
end;
var
FDataModuleConexao: TFDataModuleConexao;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
procedure TFDataModuleConexao.DataModuleCreate(Sender: TObject);
begin
Conectar('MySQL');
end;
procedure TFDataModuleConexao.Conectar(BD: String);
begin
Desconectar;
ConfigurarConexao(Conexao, BD);
Conexao.KeepConnection := True;
Conexao.AutoClone := False;
Conexao.Connected := True;
Banco := BD;
end;
procedure TFDataModuleConexao.Desconectar;
begin
Conexao.Connected := False;
end;
function TFDataModuleConexao.getBanco: String;
begin
Result := Banco;
end;
function TFDataModuleConexao.getConexao: TSQLConnection;
begin
Result := Conexao;
end;
procedure TFDataModuleConexao.ConfigurarConexao(var pConexao: TSQLConnection; pBD: String);
var
Arquivo: String;
Parametros: TStrings;
begin
if pBD = 'Oracle' then
begin
//carrega o arquivo de parametros (neste caso o do MySQL)
Arquivo := ExtractFilePath(Application.ExeName) + 'Oracle_DBExpress_conn.txt';
Conexao.DriverName := 'Oracle';
Conexao.ConnectionName := 'OracleConnection';
Conexao.GetDriverFunc := 'getSQLDriverORACLE';
Conexao.LibraryName := 'dbxora.dll';
Conexao.VendorLib := 'oci.dll';
end
else
if pBD = 'MSSQL' then
begin
//carrega o arquivo de parametros (neste caso o do MySQL)
Arquivo := ExtractFilePath(Application.ExeName) + 'MSSQL_DBExpress_conn.txt';
Conexao.DriverName := 'MSSQL';
Conexao.ConnectionName := 'MSSQLCONNECTION';
Conexao.GetDriverFunc := 'getSQLDriverMSSQL';
Conexao.LibraryName := 'dbxmss.dll';
Conexao.VendorLib := 'oledb';
end
else
if pBD = 'Firebird' then
begin
//carrega o arquivo de parametros (neste caso o do MySQL)
Arquivo := ExtractFilePath(Application.ExeName) + 'Firebird_DBExpress_conn.txt';
Conexao.DriverName := 'Firebird';
Conexao.ConnectionName := 'FBConnection';
Conexao.GetDriverFunc := 'getSQLDriverINTERBASE';
Conexao.LibraryName := 'dbxfb.dll';
Conexao.VendorLib := 'fbclient.dll';
end
else
if pBD = 'Interbase' then
begin
//carrega o arquivo de parametros (neste caso o do MySQL)
Arquivo := ExtractFilePath(Application.ExeName) + 'Interbase_DBExpress_conn.txt';
Conexao.DriverName := 'Interbase';
Conexao.ConnectionName := 'IBConnection';
Conexao.GetDriverFunc := 'getSQLDriverINTERBASE';
Conexao.LibraryName := 'dbxint.dll';
Conexao.VendorLib := 'gds32.dll';
end
else
if pBD = 'MySQL' then
begin
//carrega o arquivo de parametros (neste caso o do MySQL)
Arquivo := ExtractFilePath(Application.ExeName) + 'MySQL_DBExpress_conn.txt';
Conexao.DriverName := 'MySQL';
Conexao.ConnectionName := 'MySQLConnection';
Conexao.GetDriverFunc := 'getSQLDriverMYSQL';
Conexao.LibraryName := 'dbxmys.dll';
Conexao.VendorLib := 'libmysql.dll';
end
else
if pBD = 'DB2' then
begin
//carrega o arquivo de parametros (neste caso o do MySQL)
Arquivo := ExtractFilePath(Application.ExeName) + 'DB2_DBExpress_conn.txt';
Conexao.DriverName := 'Db2';
Conexao.ConnectionName := 'DB2Connection';
Conexao.GetDriverFunc := 'getSQLDriverDB2';
Conexao.LibraryName := 'dbxdb2.dll';
Conexao.VendorLib := 'db2cli.dll';
end
else
if pBD = 'Postgres' then
begin
//carrega o arquivo de parametros (neste caso o do Postgres)
Arquivo := ExtractFilePath(Application.ExeName) + 'Postgres_DBExpress_conn.txt';
Conexao.DriverName := 'DevartPostgreSQL';
Conexao.ConnectionName := 'PostgreConnection';
Conexao.GetDriverFunc := 'getSQLDriverPostgreSQL';
Conexao.LibraryName := 'dbexppgsql40.dll';
Conexao.VendorLib := 'not used';
end;
//variável para carregar os parametros do banco
Parametros := TStringList.Create;
try
Parametros.LoadFromFile(Arquivo);
Conexao.Params.Text := Parametros.Text;
finally
Parametros.Free;
end;
Conexao.LoginPrompt := False;
end;
end.
|
unit frmsnapshothandlerUnit;
{$mode delphi}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls,
StdCtrls, Menus, math, NewKernelHandler, FPImage, FPCanvas, FPImgCanv, FPReadPNG, FPWritePNG, betterControls ;
resourcestring
rsSHView = 'View';
rsSHDissectMemoryOfSelectedSnapshot = 'Dissect memory of selected snapshot';
rsSHDissectAndCompareMemoryOfSelectedSnapshots = 'Dissect and compare memory of selected snapshots';
rsSHCompare = 'Compare';
rsSHFunctions = ' Function(s): ';
rsSHTheStructuresListIsBroken = 'The structures list is broken';
rsSHNewWindow = '<New window>';
rsSHLockAndAddToStructureDissect = 'Lock and add to structure dissect';
rsSHSelectTheStructureDissectWindowYouWishToAddThisRegionTo = 'Select the structure dissect window you wish to add this region to';
type
{ TfrmSnapshotHandler }
//let's experiment with generics this time
TSnapshot=class(tobject)
private
public
filename: string;
dxversion: integer;
picturesize: integer;
pic: TBitmap;
stackbase: qword;
stacksize: integer;
stack: PByteArray;
constantbuffersize: integer;
constantbuffer: PByteArray;
functionnamesize: integer;
functionname: pchar;
//graphical:
selected: boolean;
xpos: integer;
width: integer;
destructor destroy; override;
end;
TSnapshotList = Tlist;
TfrmSnapshotHandler = class(TForm)
btnCompare: TButton;
shImageList: TImageList;
lblCompare: TLabel;
MainMenu1: TMainMenu;
MenuItem1: TMenuItem;
MenuItem2: TMenuItem;
miConfig: TMenuItem;
MenuItem4: TMenuItem;
MenuItem8: TMenuItem;
OpenDialog1: TOpenDialog;
PaintBox1: TPaintBox;
Panel1: TPanel;
Panel2: TPanel;
rbStack: TRadioButton;
rbCB: TRadioButton;
ScrollBar1: TScrollBar;
procedure btnCompareClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure MenuItem8Click(Sender: TObject);
procedure miConfigClick(Sender: TObject);
procedure MenuItem4Click(Sender: TObject);
procedure PaintBox1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure PaintBox1Paint(Sender: TObject);
procedure Panel1Click(Sender: TObject);
procedure ScrollBar1Change(Sender: TObject);
private
{ private declarations }
snapshots: TSnapshotList;
public
{ public declarations }
procedure loadsnapshots(list: TStrings);
procedure clearlist;
end;
var
frmSnapshotHandler: TfrmSnapshotHandler;
implementation
{$R *.lfm}
uses mainunit, frmSaveSnapshotsUnit, d3dhookUnit, frmD3DHookSnapshotConfigUnit,
StructuresFrm2, frmSelectionlistunit, frmStackViewUnit;
destructor TSnapshot.destroy;
begin
if pic<>nil then
freeandnil(pic);
if constantbuffer<>nil then
FreeMemAndNil(constantbuffer);
if stack<>nil then
FreeMemAndNil(stack);
if functionname<>nil then
FreeMemAndNil(functionname);
inherited destroy;
end;
procedure TfrmSnapshotHandler.clearlist;
var i: integer;
begin
for i:=0 to snapshots.count-1 do
TSnapshot(snapshots[i]).free;
snapshots.Clear;
paintbox1.Repaint;
end;
procedure TfrmSnapshotHandler.loadsnapshots(list: TStrings);
var
s: TSnapshot;
i: integer;
f: TFileStream;
posAfterpicture: integer;
fpi: TFPMemoryImage;
fpr: TFPReaderPNG;
fpw: TFPWriterPNG;
c: TFPCustomCanvas;
pictureformat: integer;
begin
for i:=0 to list.count-1 do
begin
s:=TSnapshot.create;
s.filename:=list[i];
f:=tfilestream.Create(s.filename, fmOpenRead);
try
f.readbuffer(s.dxversion, sizeof(s.dxversion));
f.readbuffer(pictureformat, sizeof(pictureformat));
f.ReadBuffer(s.picturesize, sizeof(s.picturesize));
posAfterpicture:=f.position+s.picturesize;
s.pic:=tbitmap.create;
if pictureformat=0 then
begin
s.pic.LoadFromStream(f, s.picturesize);
end
else
if pictureformat=3 then
begin
fpi:=TFPMemoryImage.Create(0,0);
fpr:=TFPReaderPNG.create;
fpi.LoadFromStream(f, fpr);
c:=TFPImageCanvas.create(fpi);
s.pic.Width:=fpi.Width;
s.pic.Height:=fpi.Height;
TFPCustomCanvas(s.pic.Canvas).CopyRect(0,0, c, rect(0,0,fpi.width, fpi.height));
c.free;
fpr.free;
fpi.free;
end;
f.position:=posAfterpicture;
f.readbuffer(s.stackbase, sizeof(s.stackbase));
f.readbuffer(s.stacksize, sizeof(s.stacksize));
if s.stacksize>0 then
begin
getmem(s.stack, s.stacksize);
f.readbuffer(s.stack^, s.stacksize);
end
else
s.stack:=nil;
f.readbuffer(s.constantbuffersize, sizeof(s.constantbuffersize));
if s.constantbuffersize>0 then
begin
getmem(s.constantbuffer, s.constantbuffersize);
f.ReadBuffer(s.constantbuffer^, s.constantbuffersize);
end
else
s.constantbuffer:=nil;
f.readbuffer(s.functionnamesize, sizeof(s.functionnamesize));
if s.functionnamesize>0 then
begin
getmem(s.functionname, s.functionnamesize+1);
f.ReadBuffer(s.functionname^, s.functionnamesize);
s.functionname[s.functionnamesize]:=#0;
end
else
s.functionname:=nil;
finally
f.free;
end;
snapshots.add(s);
end;
scrollbar1.Max:=snapshots.count;
paintbox1.Repaint;
end;
procedure TfrmSnapshotHandler.ScrollBar1Change(Sender: TObject);
begin
end;
procedure TfrmSnapshotHandler.MenuItem4Click(Sender: TObject);
begin
if opendialog1.Execute then
loadsnapshots(opendialog1.Files);
end;
procedure TfrmSnapshotHandler.PaintBox1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var i: integer;
selcount: integer;
functionnames: tstringlist;
fn: string;
begin
selcount:=0;
functionnames:=tstringlist.create;
functionnames.Duplicates:=dupIgnore;
for i:=scrollbar1.Position to snapshots.count-1 do
if InRange(x, TSnapshot(snapshots[i]).xpos, TSnapshot(snapshots[i]).xpos+TSnapshot(snapshots[i]).width) then
TSnapshot(snapshots[i]).selected:=not TSnapshot(snapshots[i]).selected;
for i:=0 to snapshots.count-1 do
begin
if TSnapshot(snapshots[i]).selected then
begin
if TSnapshot(snapshots[i]).functionname<>nil then
begin
if functionnames.IndexOf(TSnapshot(snapshots[i]).functionname)=-1 then //for some reason dupIgnore isn't used
functionnames.Add(TSnapshot(snapshots[i]).functionname);
end;
inc(selcount);
end;
end;
PaintBox1.repaint;
lblCompare.Enabled:=selcount>0;
rbStack.enabled:=selcount>0;
rbCB.enabled:=selcount>0;
btnCompare.enabled:=selcount>0;
if selcount=0 then
begin
lblCompare.caption:='';
btnCompare.caption:=rsSHView;
end
else
if selcount=1 then
begin
lblCompare.caption:=rsSHDissectMemoryOfSelectedSnapshot;
btnCompare.caption:=rsSHView;
end
else
if selcount>1 then
begin
lblCompare.caption:=rsSHDissectAndCompareMemoryOfSelectedSnapshots;
btnCompare.caption:=rsSHCompare;
end;
fn:='';
for i:=0 to functionnames.count-1 do
fn :=fn+functionnames[i]+' ';
lblCompare.caption:=lblCompare.Caption+rsSHFunctions+fn;
functionnames.free;
end;
procedure TfrmSnapshotHandler.PaintBox1Paint(Sender: TObject);
var
i: integer;
xpos: integer;
aspectratio: single;
currentw: integer;
h: integer;
begin
paintbox1.canvas.Clear;
xpos:=0;
h:=paintbox1.Height;
for i:=0 to snapshots.count-1 do
begin
aspectratio:=TSnapshot(snapshots[i]).pic.Width/TSnapshot(snapshots[i]).pic.Height;
currentw:=ceil(h*aspectratio);
paintbox1.Canvas.CopyRect(rect(xpos, 0, xpos+currentw, h), TSnapshot(snapshots[i]).pic.Canvas, rect(0,0,TSnapshot(snapshots[i]).pic.width, TSnapshot(snapshots[i]).pic.height));
TSnapshot(snapshots[i]).xpos:=xpos;
TSnapshot(snapshots[i]).width:=currentw;
if TSnapshot(snapshots[i]).selected then
begin
paintbox1.Canvas.Pen.Width:=3;
paintbox1.canvas.pen.Color:=clAqua;
paintbox1.canvas.Brush.Style:=bsClear;
paintbox1.Canvas.Rectangle(rect(xpos, 0, xpos+currentw, h));
paintbox1.canvas.Brush.Style:=bsSolid;
end;
inc(xpos, currentw+1);
if xpos>paintbox1.Width then
exit; //done
end;
end;
procedure TfrmSnapshotHandler.Panel1Click(Sender: TObject);
begin
end;
procedure TfrmSnapshotHandler.FormCreate(Sender: TObject);
begin
snapshots:=TSnapshotList.create;
panel2.DoubleBuffered:=true;
DoubleBuffered:=true;
end;
procedure TfrmSnapshotHandler.MenuItem8Click(Sender: TObject);
begin
clearList;
end;
procedure TfrmSnapshotHandler.btnCompareClick(Sender: TObject);
var
i: integer;
s: tstringlist;
f: TfrmSelectionList;
structurefrm: TfrmStructures2;
new: boolean;
size: integer;
hasselection: boolean;
begin
hasselection:=false;
for i:=0 to snapshots.count-1 do
if TSnapshot(snapshots[i]).selected then
begin
hasSelection:=true;
break;
end;
if hasselection then
begin
//find out which data dissect windows are open
s:=tstringlist.create;
if frmStructures2=nil then
raise exception.create(rsSHTheStructuresListIsBroken);
for i:=0 to frmStructures2.Count-1 do
s.add(TfrmStructures2(frmStructures2[i]).Caption);
s.add(rsSHNewWindow);
f:=TfrmSelectionList.Create(self, s);
f.caption:=rsSHLockAndAddToStructureDissect;
f.label1.Caption:=rsSHSelectTheStructureDissectWindowYouWishToAddThisRegionTo;
if f.showmodal=mrok then
begin
if f.itemindex=-1 then f.itemindex:=0;
if f.itemindex>=frmStructures2.Count then //new window
begin
structurefrm:=tfrmstructures2.create(application);
structurefrm.show;
end
else
structurefrm:=TfrmStructures2(frmStructures2[f.itemindex]);
//add this as a locked address
size:=0;
for i:=0 to snapshots.count-1 do
if TSnapshot(snapshots[i]).selected then
begin
if rbstack.checked then
begin
structurefrm.addLockedAddress(TSnapshot(snapshots[i]).stackbase, TSnapshot(snapshots[i]).stack, TSnapshot(snapshots[i]).stacksize);
size:=max(TSnapshot(snapshots[i]).stacksize, size);
end
else
begin
structurefrm.addLockedAddress(0, TSnapshot(snapshots[i]).constantbuffer, TSnapshot(snapshots[i]).constantbuffersize);
size:=max(TSnapshot(snapshots[i]).constantbuffersize, size);
end;
end;
structurefrm.show;
if structurefrm.mainStruct=nil then //if no structure is selected define it then
structurefrm.DefineNewStructure(size);
end;
end;
end;
procedure TfrmSnapshotHandler.miConfigClick(Sender: TObject);
var frmD3DHookSnapshotConfig: TfrmD3DHookSnapshotConfig;
pf: integer;
begin
{$IFDEF windows}
frmd3dhooksnapshotconfig:=TfrmD3DHookSnapshotConfig.create(self);
try
if frmd3dhooksnapshotconfig.showmodal=mrok then
begin
safed3dhook;
mainform.updated3dgui;
if frmd3dhooksnapshotconfig.rbFormatPNG.Checked then
pf:=3
else
pf:=0;
if d3dhook<>nil then
d3dhook.setSnapshotOptions(frmd3dhooksnapshotconfig.dirSnapshot.Text, frmd3dhooksnapshotconfig.fullsnapshotkey, frmd3dhooksnapshotconfig.smallsnapshotkey, frmd3dhooksnapshotconfig.cbProgressive.checked, frmd3dhooksnapshotconfig.cbClearDepth.checked, frmd3dhooksnapshotconfig.cbAlsoOutputPng.checked, pf);
end;
finally
frmd3dhooksnapshotconfig.free;
end;
{$ENDIF}
end;
{
procedure TfrmSnapshotHandler.initialize(path: string; count: integer);
begin
end;
}
end.
|
{ :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: QuickReport 5.0 for Delphi and C++Builder ::
:: ::
:: QREPORT.PAS - COMPONENT REGISTRATION & PROPERTY EDITORS ::
:: ::
:: Copyright (c) 2007 QBS Software ::
:: All Rights Reserved ::
:: ::
:: web: http://www.quickreport.co.uk ::
:: ::}
{$I QRDEFS.INC}
unit QRNew;
interface
procedure Register;
implementation
uses Windows, ActiveX, SysUtils, Classes, Controls, Forms, ExptIntf, ToolIntf,
VirtIntf, IStreams, DesignIntf, DesignEditors, QuickRpt, QReport, QR5Const;
type
TNewQuickReport = class(TIExpert)
function GetName: string; override;
function GetComment: string; override;
function GetGlyph: HICON; override;
function GetStyle: TExpertStyle; override;
function GetState: TExpertState; override;
function GetIDString: string; override;
function GetAuthor: string; override;
function GetPage: string; override;
function GetMenuText: string; override;
procedure Execute; override;
end;
{ TNewQuickReport }
function TNewQuickReport.GetName: string;
begin
Result := SqrReport;
end;
function TNewQuickReport.GetComment: string;
begin
Result := SqrDesignReport;
end;
function TNewQuickReport.GetGlyph: HICON;
begin
Result := LoadIcon(HInstance, 'QRNEW');
end;
function TNewQuickReport.GetStyle: TExpertStyle;
begin
Result := esForm;
end;
function TNewQuickReport.GetState: TExpertState;
begin
Result := [esEnabled];
end;
function TNewQuickReport.GetIDString: string;
begin
Result := 'QBSS.NewQuickReport'; { <-- do not resource }
end;
function TNewQuickReport.GetAuthor: string;
begin
Result := SqrQuSoft;
end;
function TNewQuickReport.GetPage: string;
begin
Result := SqrNew;
end;
function TNewQuickReport.GetMenuText: string;
begin
Result := '';
end;
const
CRLF = #13#10;
DashLine =
'//----------------------------------------------------------------------------';
QuickReportCppSource =
DashLine + CRLF +
'#include <vcl\vcl.h>' + CRLF +
'#pragma hdrstop' + CRLF +
CRLF +
'#include "%0:s.h"' + CRLF +
DashLine + CRLF +
'#pragma resource "*.dfm"' + CRLF +
'T%1:s *%1:s;' + CRLF +
DashLine + CRLF +
'__fastcall T%1:s::T%1:s(TComponent* Owner)' + CRLF +
' : TQuickRep(Owner)' + CRLF +
'{' + CRLF +
'}' + CRLF +
DashLine;
QuickReportCppHeader =
DashLine + CRLF +
'#ifndef %0:sH' + CRLF +
'#define %0:sH' + CRLF +
DashLine + CRLF +
'#include <vcl\Classes.hpp>' + CRLF +
'#include <vcl\Controls.hpp>' + CRLF +
'#include <vcl\StdCtrls.hpp>' + CRLF +
'#include <vcl\Forms.hpp>' + CRLF +
'#include <vcl\QuickRpt.hpp>' + CRLF +
'#include <vcl\QRCtrls.hpp>' + CRLF +
DashLine + CRLF +
'class T%1:s : public TQuickRep' + CRLF +
'{' + CRLF +
'__published:' + CRLF +
'private:' + CRLF +
'public:' + CRLF +
' __fastcall T%1:s::T%1:s(TComponent* Owner);' + CRLF +
'};' + CRLF +
DashLine + CRLF +
'extern T%1:s *%1:s;' + CRLF +
DashLine + CRLF +
'#endif';
QuickReportUnitSource =
'unit %0:s;'#13#10 +
#13#10 +
'interface'#13#10 +
#13#10 +
'uses Windows, SysUtils, Messages, Classes, Graphics, Controls,'#13#10 +
' StdCtrls, ExtCtrls, Forms, QuickRpt, QRCtrls;'#13#10 +
#13#10 +
'type'#13#10 +
' T%1:s = class(TQuickRep)'#13#10 +
' private'#13#10 +
#13#10 +
' public'#13#10 +
#13#10 +
' end;'#13#10 +
#13#10 +
'var'#13#10 +
' %1:s: T%1:s;'#13#10 +
#13#10 +
'implementation'#13#10 +
#13#10 +
'{$R *.DFM}'#13#10 +
#13#10 +
'end.'#13#10;
QuickReportDfmSource = 'object %s: T%0:s end';
procedure TNewQuickReport.Execute;
var
UnitIdent, Filename: string;
ReportName: string;
CodeStream, HdrStream, DFMStream: IStream;
DFMString, DFMVCLStream: TStream;
InCppBuilder: Boolean;
begin
if not ToolServices.GetNewModuleName(UnitIdent, FileName) then Exit;
ReportName := 'QuickReport' + Copy(UnitIdent, 5, 255);
InCppBuilder := HexDisplayPrefix <> '$';
if InCppBuilder then
begin
HdrStream := TIStreamAdapter.Create(TStringStream.Create(Format(QuickReportCppHeader,
[UnitIdent, ReportName])), soOwned);
CodeStream := TIStreamAdapter.Create(TStringStream.Create(Format(QuickReportCppSource,
[UnitIdent, ReportName])), soOwned);
end else
begin
HdrStream := nil;
CodeStream := TIStreamAdapter.Create(TStringStream.Create(Format(QuickReportUnitSource,
[UnitIdent, ReportName])), soOwned);
end;
DFMString := TStringStream.Create(Format(QuickReportDfmSource, [ReportName]));
try
DFMVCLStream := TMemoryStream.Create;
DFMStream := TIStreamAdapter.Create(DFMVCLStream, soOwned);
ObjectTextToResource(DFMString, DFMVCLStream);
DFMVCLStream.Position := 0;
ToolServices.CreateCppModule(FileName, ReportName, 'TQuickRep', '',
HdrStream, CodeStream, DFMStream, [cmAddToProject, cmShowSource, cmShowForm,
cmUnNamed, cmMarkModified]);
finally
DFMString.Free;
end;
end;
type
TQuickReportCustomModule = class(TCustomModule)
public
function GetAttributes: TCustomModuleAttributes; override;
function ValidateComponentClass(ComponentClass: TComponentClass): Boolean; override;
procedure ValidateComponent(Component: TComponent); override;
procedure ExecuteVerb(Index: Integer); override;
function GetVerb(Index: Integer): string; override;
function GetVerbCount: Integer; override;
end;
function TQuickReportCustomModule.GetAttributes: TCustomModuleAttributes;
begin
Result := [cmaVirtualSize];
end;
function TQuickReportCustomModule.ValidateComponentClass(ComponentClass: TComponentClass): Boolean;
begin
Result := inherited ValidateComponentClass(ComponentClass) and
(not ComponentClass.InheritsFrom(TControl) or
ComponentClass.InheritsFrom(TQRBasePanel) or
ComponentClass.InheritsFrom(TQRPrintable));
end;
procedure TQuickReportCustomModule.ValidateComponent(Component: TComponent);
begin
if (Component = nil) or ((Component is TControl) and not (Component is TQRBasePanel)
and not (Component is TQRPrintable)) then
raise Exception.CreateFmt(SqrCannotAdd, [Component.ClassName]);
end;
procedure TQuickReportCustomModule.ExecuteVerb(Index: Integer);
begin
ExecuteDesignVerb(Index, TQuickRep(Root));
end;
function TQuickReportCustomModule.GetVerb(Index: Integer): string;
begin
Result := GetDesignVerb(Index);
end;
function TQuickReportCustomModule.GetVerbCount: Integer;
begin
Result := GetDesignVerbCount;
end;
procedure Register;
begin
RegisterCustomModule(TQuickRep, TQuickReportCustomModule);
RegisterLibraryExpert(TNewQuickReport.Create);
end;
end.
|
unit WellPoster;
interface
uses PersistentObjects, DBGate, BaseObjects, DB, LicenseZone, Well, Area, PetrolRegion,
Organization, District, Structure, State, Topolist, Profile, Fluid, ReasonChange, Employee,
Straton, TectonicStructure, Version;
type
TWellDynamicParametersDataPoster = class(TImplementedDataPoster)
private
FWellCategories: TWellCategories;
FWellStates: TStates;
FWellProfiles: TProfiles;
FFluidTypes: TFluidTypes;
FStratons: TSimpleStratons;
FVersions: TVersions;
public
property AllCategories: TWellCategories read FWellCategories write FWellCategories;
property AllStates: TStates read FWellStates write FWellStates;
property AllProfiles: TProfiles read FWellProfiles write FWellProfiles;
property AllFluidTypes: TFluidTypes read FFluidTypes write FFluidTypes;
property AllStratons: TSimpleStratons read FStratons write FStratons;
property AllVersions: TVersions read FVersions write FVersions;
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
// для категорий скважин
TWellCategoryDataPoster = class(TImplementedDataPoster)
public
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
// для отношения организации к скважине
TWellOrganizationStatusDataPoster = class(TImplementedDataPoster)
private
FAllStatusOrganization: TOrganizationStatuses;
FAllOrganization: TOrganizations;
procedure SetAllStatusOrganization(const Value: TOrganizationStatuses);
procedure SetAllOrganization(const Value: TOrganizations);
public
property AllStatusOrganization: TOrganizationStatuses read FAllStatusOrganization write SetAllStatusOrganization;
property AllOrganization: TOrganizations read FAllOrganization write SetAllOrganization;
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
// для динамики отношения организации к скважине
// для привязки скважин
TWellBindingDataPoster = class(TImplementedDataPoster)
private
FAllWells: TWells;
FAllAreas: TAreas;
procedure SetAllWells(const Value: TWells);
procedure SetAllAreas(const Value: TAreas);
public
property AllWells: TWells read FAllWells write SetAllWells;
property AllAreas: TAreas read FAllAreas write SetAllAreas;
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function PostToDB(ACollection: TIDObjects; AOwner: TIDObject): integer; overload; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
// для скважин (загружается только номер, площадь и категория)
TSimpleWellDataPoster = class(TImplementedDataPoster)
private
FAllWellStates: TStates;
FAllWellCategories: TWellCategories;
FAllAreas: TSimpleAreas;
procedure SetAllWellStates(const Value: TStates);
procedure SetAllWellCategories(const Value: TWellCategories);
procedure SetAllAreas(const Value: TSimpleAreas);
public
property AllWellStates: TStates read FAllWellStates write SetAllWellStates;
property AllWellCategories: TWellCategories read FAllWellCategories write SetAllWellCategories;
property AllAreas: TSimpleAreas read FAllAreas write SetAllAreas;
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
// для скважин
TWellDataPoster = class(TImplementedDataPoster)
private
FAllWellStates: TStates;
FAllWellCategories: TWellCategories;
FAllAreas: TSimpleAreas;
FAllOrganizations: TOrganizations;
FAllSimpleStratons: TSimpleStratons;
FAllFluidTypesByBalance: TFluidTypes;
FAllFluidTypes: TFluidTypes;
FAllProfiles: TProfiles;
FAllEmployee: TEmployees;
procedure SetAllWellStates(const Value: TStates);
procedure SetAllWellCategories(const Value: TWellCategories);
procedure SetAllAreas(const Value: TSimpleAreas);
procedure SetAllOrganizations(const Value: TOrganizations);
procedure SetAllSimpleStratons(const Value: TSimpleStratons);
procedure SetAllFluidTypes(const Value: TFluidTypes);
procedure SetAllFluidTypesByBalance(const Value: TFluidTypes);
procedure SetAllProfiles(const Value: TProfiles);
procedure SetAllEmployee(const Value: TEmployees);
protected
procedure LocalSort(AObjects: TIDObjects); override;
procedure InternalInitWell(AWell: TWell); virtual;
procedure CommonInternalInitRow(AWell: TWell; ds: TDataSet); virtual;
public
property AllWellStates: TStates read FAllWellStates write SetAllWellStates;
property AllWellCategories: TWellCategories read FAllWellCategories write SetAllWellCategories;
property AllAreas: TSimpleAreas read FAllAreas write SetAllAreas;
property AllOrganizations: TOrganizations read FAllOrganizations write SetAllOrganizations;
property AllSimpleStratons: TSimpleStratons read FAllSimpleStratons write SetAllSimpleStratons;
property AllProfiles: TProfiles read FAllProfiles write SetAllProfiles;
property AllFluidTypes: TFluidTypes read FAllFluidTypes write SetAllFluidTypes;
property AllFluidTypesByBalance: TFluidTypes read FAllFluidTypesByBalance write SetAllFluidTypesByBalance;
property AllEmployee: TEmployees read FAllEmployee write SetAllEmployee;
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
// для принадлежности скважин
TWellPositionDataPoster = class(TImplementedDataPoster)
private
FAllPetrolRegions: TPetrolRegions;
FAllDistricts: TDistricts;
FAllTopolists: TTopographicalLists;
FAllTectonicStructures: TTectonicStructures;
FAllNewPetrolRegions: TNewPetrolRegions;
FAllNewTectonicStructures: TNewTectonicStructures;
procedure SetAllPetrolRegions(const Value: TPetrolRegions);
procedure SetAllDistricts(const Value: TDistricts);
procedure SetAllTopolists(const Value: TTopographicalLists);
procedure SetAllTectonicStructures(const Value: TTectonicStructures);
procedure SetNewAllPetrolRegions(const Value: TNewPetrolRegions);
procedure SetNewAllTectonicStructures(
const Value: TNewTectonicStructures);
public
property AllPetrolRegions: TPetrolRegions read FAllPetrolRegions write SetAllPetrolRegions;
property AllDistricts: TDistricts read FAllDistricts write SetAllDistricts;
property AllTopolists: TTopographicalLists read FAllTopolists write SetAllTopolists;
property AllTectonicStructures: TTectonicStructures read FAllTectonicStructures write SetAllTectonicStructures;
property AllNewTectonicStructures: TNewTectonicStructures read FAllNewTectonicStructures write SetNewAllTectonicStructures;
property AllNewPetrolRegions: TNewPetrolRegions read FAllNewPetrolRegions write SetNewAllPetrolRegions;
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
TWellLicenseZoneDataPoster = class(TImplementedDataPoster)
private
FLicenseZoneVersionObjectSets: TVersionObjectSets;
FAllVersions: TVersions;
public
property AllVersions: TVersions read FAllVersions write FAllVersions;
property LicenseZoneVersionObjectSets: TVersionObjectSets read FLicenseZoneVersionObjectSets write FLicenseZoneVersionObjectSets;
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
TWellStructureDataPoster = class(TImplementedDataPoster)
private
FStructureVersionObjectSets: TVersionObjectSets;
FAllVersions: TVersions;
public
property AllVersions: TVersions read FAllVersions write FAllVersions;
property StructureVersionObjectSets: TVersionObjectSets read FStructureVersionObjectSets write FStructureVersionObjectSets;
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
TWellFieldDataPoster = class(TImplementedDataPoster)
private
FFieldVersionObjectSets: TVersionObjectSets;
FAllVersions: TVersions;
public
property AllVersions: TVersions read FAllVersions write FAllVersions;
property FieldVersionObjectSets: TVersionObjectSets read FFieldVersionObjectSets write FFieldVersionObjectSets;
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
TWellBedDataPoster = class(TImplementedDataPoster)
private
FBedVersionObjectSets: TVersionObjectSets;
FAllVersions: TVersions;
public
property AllVersions: TVersions read FAllVersions write FAllVersions;
property BedVersionObjectSets: TVersionObjectSets read FBedVersionObjectSets write FBedVersionObjectSets;
function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override;
function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override;
constructor Create; override;
end;
implementation
uses Facade, SysUtils, ClientCommon, Variants, Math, DateUtils, Field, Bed;
function SortWells(Item1, Item2: Pointer): Integer;
var w1, w2: TSimpleWell;
iNum1, iNum2: integer;
begin
Result := 0;
w1 := TSimpleWell(Item1);
w2 := TSimpleWell(Item2);
if w1.Name > w2.Name then Result := 1
else if w1.Name < w2.Name then Result := -1
else
begin
iNum1 := ExtractInt(w1.NumberWell);
iNum2 := ExtractInt(w2.NumberWell);
if iNum1 > iNum2 then Result := 1
else if iNum1 < iNum2 then Result := -1
else if iNum1 = iNum2 then
begin
if w1.NumberWell > w2.NumberWell then Result := 1
else if w1.NumberWell < w2.NumberWell then Result := -1
else Result := 0;
end;
end;
end;
{ TWelldDataPoster }
procedure TWellDataPoster.CommonInternalInitRow(AWell: TWell;
ds: TDataSet);
begin
ds.FieldByName('WELL_UIN').AsInteger := AWell.ID;
ds.FieldByName('VCH_WELL_NUM').AsString := AWell.NumberWell;
ds.FieldByName('AREA_ID').AsInteger := AWell.Area.ID;
ds.FieldByName('VCH_WELL_NAME').AsString := AWell.Name;
ds.FieldByName('VCH_PASSPORT_NUM').AsString := Trim(AWell.PassportNumberWell);
if Assigned (AWell.Category) then ds.FieldByName('WELL_CATEGORY_ID').AsInteger := AWell.Category.ID;
if Assigned (AWell.State) then ds.FieldByName('WELL_STATE_ID').AsInteger := AWell.State.ID;
//if Assigned(AWell.Age) then ds.FieldByName('TRUE_AGE_ID').AsInteger := AWell.Age.ID;
end;
constructor TWellDataPoster.Create;
begin
inherited;
Options := [soGetKeyValue];
DataSourceString := 'VW_WELL_COORD';
DataDeletionString := 'TBL_WELL';
DataPostString := 'TBL_WELL';
KeyFieldNames := 'WELL_UIN';
FieldNames := 'WELL_UIN, VCH_WELL_NUM, VCH_PASSPORT_NUM, AREA_ID, WELL_CATEGORY_ID, WELL_STATE_ID, ' +
'PROFILE_ID, TARGET_STRATON_ID, TRUE_STRATON_ID, NUM_TARGET_DEPTH, NUM_TRUE_DEPTH, ' +
'NUM_GENERAL_ALTITUDE, NUM_TARGET_COST, NUM_TRUE_COST, DTM_CONSTRUCTION_STARTED, DTM_CONSTRUCTION_FINISHED, ' +
'DTM_DRILLING_START, DTM_DRILLING_FINISH, DTM_ENTERING_DATE, TARGET_FLUID_TYPE_ID, ' +
'TRUE_FLUID_TYPE_ID, VCH_WELL_NAME, DTM_LAST_MODIFY_DATE, NUM_IS_PROJECT, TARGET_CATEGORY_ID, EMPLOYEE_ID, MODIFIER_ID, NUM_IS_DYNAMICS_EDITED';
AccessoryFieldNames := 'WELL_UIN, VCH_WELL_NUM, VCH_PASSPORT_NUM, AREA_ID, WELL_CATEGORY_ID, WELL_STATE_ID, ' +
'PROFILE_ID, TARGET_STRATON_ID, TRUE_STRATON_ID, NUM_TARGET_DEPTH, NUM_TRUE_DEPTH, ' +
'NUM_GENERAL_ALTITUDE, NUM_TARGET_COST, NUM_TRUE_COST, DTM_CONSTRUCTION_STARTED, DTM_CONSTRUCTION_FINISHED, ' +
'DTM_DRILLING_START, DTM_DRILLING_FINISH, DTM_ENTERING_DATE, TARGET_FLUID_TYPE_ID, ' +
'TRUE_FLUID_TYPE_ID, VCH_WELL_NAME, DTM_LAST_MODIFY_DATE, NUM_IS_PROJECT, TARGET_CATEGORY_ID, EMPLOYEE_ID, MODIFIER_ID, NUM_IS_DYNAMICS_EDITED';
AutoFillDates := false;
Sort := 'VCH_AREA_NAME, VCH_WELL_NUM';
end;
function TWellDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer;
var ds: TCommonServerDataSet;
begin
Assert(DataDeletionString <> '', 'Не задан приемник данных ' + ClassName);
Result := 0;
ds := TMainFacade.GetInstance.DBGates.Add(Self);
try
// находим строку соответствующую ключу
ds.First;
if ds.Locate('WELL_UIN', AObject.ID, []) then
begin
ds.Delete;
end
except
Result := -1;
end;
end;
function TWellDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TWell;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
if Assigned(AObjects) then
begin
while not ds.Eof do
begin
o := AObjects.Add as TWell;
InternalInitWell(o);
ds.Next;
end;
LocalSort(AObjects);
end;
ds.First;
end;
end;
procedure TWellDataPoster.InternalInitWell(AWell: TWell);
var ds: TDataSet;
begin
ds := TMainFacade.GetInstance.DBGates.Add(Self);
//WELL_UIN
AWell.ID := ds.FieldByName('WELL_UIN').AsInteger;
//VCH_WELL_NUM, VCH_PASSPORT_NUM, AREA_ID, VCH_WELL_NAME
if Assigned(FAllAreas) then
AWell.Area := FAllAreas.ItemsByID[ds.FieldByName('AREA_ID').AsInteger] as TSimpleArea;
AWell.Name := trim(ds.FieldByName('VCH_WELL_NAME').AsString);
AWell.PassportNumberWell := trim(ds.FieldByName('VCH_PASSPORT_NUM').AsString);
AWell.NumberWell := trim(ds.FieldByName('VCH_WELL_NUM').AsString);
//DTM_DRILLING_START, DTM_DRILLING_FINISH
AWell.DtDrillingStart := ds.FieldByName('DTM_DRILLING_START').AsDateTime;
AWell.DtDrillingFinish := ds.FieldByName('DTM_DRILLING_FINISH').AsDateTime;
// NUM_TARGET_DEPTH, NUM_TRUE_DEPTH
AWell.TrueDepth := ds.FieldByName('NUM_TRUE_DEPTH').AsFloat;
AWell.TargetDepth := ds.FieldByName('NUM_TARGET_DEPTH').AsFloat;
// NUM_TARGET_COST, NUM_TRUE_COST
AWell.TargetCost := ds.FieldByName('NUM_TARGET_COST').AsFloat;
AWell.TrueCost := ds.FieldByName('NUM_TRUE_COST').AsFloat;
// DTM_LAST_MODIFY_DATE
AWell.LastModifyDate := ds.FieldByName('DTM_LAST_MODIFY_DATE').AsDateTime;
AWell.IsProject := ds.FieldByName('NUM_IS_PROJECT').AsInteger > 0;
// WELL_CATEGORY_ID, WELL_STATE_ID
if Assigned(FAllWellCategories) then
begin
AWell.Category := FAllWellCategories.ItemsByID[ds.FieldByName('WELL_CATEGORY_ID').AsInteger] as TWellCategory;
AWell.TargetCategory := FAllWellCategories.ItemsByID[ds.FieldByName('TARGET_CATEGORY_ID').AsInteger] as TWellCategory;
end;
if Assigned(FAllWellStates) then
AWell.State := FAllWellStates.ItemsByID[ds.FieldByName('WELL_STATE_ID').AsInteger] as TState;
//TARGET_FLUID_TYPE_ID, TRUE_FLUID_TYPE_ID
if Assigned (FAllFluidTypes) then
begin
AWell.FluidType := FAllFluidTypes.ItemsByID[ds.FieldByName('TRUE_FLUID_TYPE_ID').AsInteger] as TFluidType;
AWell.FluidTypeByBalance := FAllFluidTypes.ItemsByID[ds.FieldByName('TARGET_FLUID_TYPE_ID').AsInteger] as TFluidType;
end;
//PROFILE_ID, TARGET_AGE_ID, TRUE_AGE_ID,
if Assigned (FAllProfiles) then
AWell.Profile := FAllProfiles.ItemsByID[ds.FieldByName('PROFILE_ID').AsInteger] as TProfile;
if Assigned(FAllSimpleStratons) then
begin
AWell.TargetStraton := FAllSimpleStratons.ItemsByID[ds.FieldByName('TARGET_STRATON_ID').AsInteger] as TSimpleStraton;
AWell.TrueStraton := FAllSimpleStratons.ItemsByID[ds.FieldByName('TRUE_STRATON_ID').AsInteger] as TSimpleStraton;
end;
// DTM_CONSTRUCTION_STARTED, DTM_CONSTRUCTION_FINISHED
AWell.DtConstructionStart := ds.FieldByName('DTM_CONSTRUCTION_STARTED').AsDateTime;
AWell.DtConstructionFinish := ds.FieldByName('DTM_CONSTRUCTION_FINISHED').AsDateTime;
// EMPLOYEE_ID
if Assigned(FAllEmployee) then
AWell.Employee := FAllEmployee.ItemsByID[ds.FieldByName('EMPLOYEE_ID').AsInteger] as TEmployee;
// AWell.Altitudes;
end;
procedure TWellDataPoster.LocalSort(AObjects: TIDObjects);
begin
inherited;
//AObjects.Sort(SortWells);
end;
function TWellDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var o: TWell;
ds: TCommonServerDataSet;
bEdit: boolean;
begin
Assert(DataPostString <> '', 'Не задан приемник данных ' + ClassName);
Result := 0;
o := AObject as TWell;
Assert(Assigned(o.Area), 'Не задана площадь');
try
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Active then
ds.Open;
//ds.First;
bEdit := false;
if ds.Locate('WELL_UIN', AObject.ID, []) then
begin
ds.Edit;
bEdit := true;
end
else ds.Append;
except
on E: Exception do
begin
raise;
end;
end;
ds.FieldByName('WELL_UIN').Value := o.ID;
ds.FieldByName('VCH_WELL_NUM').Value := trim(o.NumberWell);
ds.FieldByName('AREA_ID').Value := o.Area.ID;
ds.FieldByName('VCH_WELL_NAME').Value := Trim(o.Name);
ds.FieldByName('VCH_PASSPORT_NUM').Value := trim(o.PassportNumberWell);
ds.FieldByName('DTM_LAST_MODIFY_DATE').Value := DateOf(o.LastModifyDate);
ds.FieldByName('NUM_IS_PROJECT').Value := ord(o.IsProject);
if Assigned (o.Category) then
ds.FieldByName('WELL_CATEGORY_ID').Value := o.Category.ID
else
ds.FieldByName('WELL_CATEGORY_ID').Value := null;
if Assigned(o.TargetCategory) then
ds.FieldByName('TARGET_CATEGORY_ID').Value := o.TargetCategory.ID
else
ds.FieldByName('TARGET_CATEGORY_ID').Value := null;
if Assigned (o.State) then
ds.FieldByName('WELL_STATE_ID').Value := o.State.ID
else
ds.FieldByName('WELL_STATE_ID').Value := null;
if Assigned (o.Profile) then
ds.FieldByName('PROFILE_ID').Value := o.Profile.ID
else
ds.FieldByName('PROFILE_ID').Value := null;
if Assigned (o.FluidType) then
ds.FieldByName('TRUE_FLUID_TYPE_ID').Value := o.FluidType.ID
else
ds.FieldByName('TRUE_FLUID_TYPE_ID').Value := null;
if Assigned (o.FluidTypeByBalance) then
ds.FieldByName('TARGET_FLUID_TYPE_ID').Value := o.FluidTypeByBalance.ID
else
ds.FieldByName('TARGET_FLUID_TYPE_ID').Value := null;
ds.FieldByName('NUM_TARGET_COST').AsFloat := o.TargetCost;
ds.FieldByName('NUM_TRUE_COST').AsFloat := o.TrueCost;
ds.FieldByName('DTM_DRILLING_START').Value := DateToStr(o.DtDrillingStart);
ds.FieldByName('DTM_DRILLING_FINISH').Value := DateToStr(o.DtDrillingFinish);
ds.FieldByName('NUM_TRUE_DEPTH').AsFloat := o.TrueDepth;
ds.FieldByName('NUM_TARGET_DEPTH').AsFloat := o.TargetDepth;
if Assigned(o.TargetStraton) then
ds.FieldByName('TARGET_STRATON_ID').Value := o.TargetStraton.ID
else
ds.FieldByName('TARGET_STRATON_ID').Value := null;
if Assigned(o.TrueStraton) then
ds.FieldByName('TRUE_STRATON_ID').Value := o.TrueStraton.ID
else
ds.FieldByName('TRUE_STRATON_ID').Value := null;
ds.FieldByName('DTM_CONSTRUCTION_STARTED').Value := DateToStr(o.DtConstructionStart);
ds.FieldByName('DTM_CONSTRUCTION_FINISHED').Value := DateToStr(o.DtConstructionFinish);
ds.FieldByName('NUM_IS_PROJECT').AsInteger := ord(o.IsProject);
if not bEdit then
ds.FieldByName('EMPLOYEE_ID').AsInteger := TMainFacade.GetInstance.DBGates.EmployeeID;
ds.FieldByName('MODIFIER_ID').AsInteger := TMainFacade.GetInstance.DBGates.EmployeeID;
ds.FieldByName('num_Is_Dynamics_Edited').AsInteger := 0;
ds.Post;
if o.ID = 0 then
begin
o.ID := ds.FieldByName('WELL_UIN').Value;
o.UpdateFilters;
end;
{
Result := inherited PostToDB(AObject, ACollection);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
o := AObject as TDinamicWell;
ds.FieldByName('WELL_UIN').Value := o.ID;
ds.FieldByName('VCH_WELL_NUM').Value := o.NumberWell;
ds.FieldByName('AREA_ID').Value := o.Area.ID;
ds.FieldByName('VCH_WELL_NAME').Value := o.Name;
ds.FieldByName('VCH_PASSPORT_NUM').Value := o.PassportNumberWell;
if Assigned (o.Category) then ds.FieldByName('WELL_CATEGORY_ID').Value := o.Category.ID;
if Assigned (o.State) then ds.FieldByName('WELL_STATE_ID').Value := o.State.ID;
if Assigned (o.Profile) then
ds.FieldByName('PROFILE_ID').Value := o.Profile.ID;
if Assigned (o.FluidType) then
ds.FieldByName('TRUE_FLUID_TYPE_ID').Value := o.FluidType.ID;
if Assigned (o.FluidTypeByBalance) then
ds.FieldByName('TARGET_FLUID_TYPE_ID').Value := o.FluidTypeByBalance.ID;
// if Assigned (o.AbandonReason) then
// ds.FieldByName('ABANDON_REASON_ID').Value := o.AbandonReason.ID;
// ds.FieldByName('DTM_ABANDON_DATE').Value := DateToStr(o.DtLiquidation);
ds.FieldByName('NUM_TARGET_COST').Value := o.TargetCost;
ds.FieldByName('NUM_TRUE_COST').Value := o.TrueCost;
ds.FieldByName('DTM_ENTERING_DATE').Value := DateToStr(o.EnteringDate);
ds.FieldByName('DTM_LAST_MODIFY_DATE').Value := null;//DateToStr(o.LastModifyDate);
ds.FieldByName('DTM_DRILLING_START').Value := DateToStr(o.DtDrillingStart);
ds.FieldByName('DTM_DRILLING_FINISH').Value := DateToStr(o.DtDrillingFinish);
ds.FieldByName('NUM_TRUE_DEPTH').Value := o.TrueDepth;
ds.FieldByName('NUM_TARGET_DEPTH').AsFloat := o.TargetDepth;
ds.FieldByName('EMPLOYEE_ID').Value := TMainFacade.GetInstance.DBGates.EmployeeID;
ds.Post;
if o.ID = 0 then o.ID := ds.FieldByName('WELL_UIN').Value;
{
ds := fc.DBGates.Add(Self);
o := AObject as TDinamicWell;
ds.FieldByName('WELL_UIN').AsInteger := o.ID;
ds.FieldByName('VCH_WELL_NUM').AsString := o.NumberWell;
ds.FieldByName('VCH_PASSPORT_NUM').AsString := o.PassportNumberWell;
ds.FieldByName('AREA_ID').AsInteger := o.Area.ID;
if Assigned (o.Category) then
ds.FieldByName('WELL_CATEGORY_ID').AsInteger := o.Category.ID;
if Assigned (o.State) then
ds.FieldByName('WELL_STATE_ID').AsInteger := o.State.ID;
if Assigned (o.Profile) then
ds.FieldByName('PROFILE_ID').AsInteger := o.Profile.ID;
ds.FieldByName('VCH_WELL_NAME').AsString := o.Name;
{
NUM_ROTOR_ALTITUDE, ' +
NUM_EARTH_ALTITUDE,
NUM_FLOOR_ALTITUDE,
DTM_CONSTRUCTION_STARTED,
DTM_CONSTRUCTION_FINISHED, ' +
NUM_TARGET_DEPTH,
TARGET_FLUID_TYPE_ID,
VCH_WELL_PRODUCTIVITY,
MODIFIER_ID,
MODIFIER_CLIENT_APP_TYPE_ID, ' +
WELL_OWNER_ID,
TARGET_STRATON_ID,
TRUE_STRATON_ID
// альтитуда
property Altitude: double read FAltitude write FAltitude;
// возраст на забое
property Age: string read FAge write FAge;
// принадлежность к организации по лиц. участку
property LicenseZone: TIDObject read FLicenseZone write SetLicenseZone;
// организация
property OwnerOrganization: TOrganization read FOwnerOrganization write FOwnerOrganization;
// организация - берется по лицензии если таковая есть, если нет по организации из базы данных
property RealOwner: TOrganization read GetRealOwner;
// результат бурения
property FluidType: TFluidType read FFluidType write FFluidType;
// целевое назначение
property FluidTypeByBalance: TFluidType read FFluidTypeByBalance write FFluidTypeByBalance;
// источник
property IstFinance: TIDObject read GetIstFinance;
property IstFinances: TIDObjects read FIstFinances write FIstFinances;
//ds.Post;
//if o.ID = 0 then o.ID := ds.FieldByName('WELL_UIN').Value;
}
end;
{ TWellPositionDataPoster }
constructor TWellPositionDataPoster.Create;
begin
inherited;
Options := [soGetKeyValue, soSingleDataSource];
DataSourceString := 'TBL_WELL_POSITION';
KeyFieldNames := 'WELL_UIN';
FieldNames := 'WELL_UIN, TOPOGRAPHICAL_LIST_ID, STRUCT_ID, DISTRICT_ID, PETROL_REGION_ID, NEW_PETROL_REGION_ID, NEW_TSTRUCT_ID';
AccessoryFieldNames := 'WELL_UIN, TOPOGRAPHICAL_LIST_ID, STRUCT_ID, DISTRICT_ID, PETROL_REGION_ID, NEW_PETROL_REGION_ID, NEW_TSTRUCT_ID';
AutoFillDates := false;
Sort := 'WELL_UIN';
end;
function TWellPositionDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer;
begin
Result := 0;
end;
function TWellPositionDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TWellPosition;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
while not ds.Eof do
begin
o := AObjects.Add as TWellPosition;
o.ID := ds.FieldByName('WELL_UIN').AsInteger;
if Assigned (AllTopolists) then
o.Topolist := FAllTopolists.ItemsByID[ds.FieldByName('TOPOGRAPHICAL_LIST_ID').AsInteger] as TTopographicalList;
if Assigned (AllDistricts) then
o.District := FAllDistricts.ItemsByID[ds.FieldByName('DISTRICT_ID').AsInteger] as TDistrict;
if Assigned (AllPetrolRegions) then
o.NGR := FAllPetrolRegions.PlainList.ItemsByID[ds.FieldByName('PETROL_REGION_ID').AsInteger] as TPetrolRegion;
if Assigned (AllNewPetrolRegions) then
o.NewNGR := FAllNewPetrolRegions.PlainList.ItemsByID[ds.FieldByName('NEW_PETROL_REGION_ID').AsInteger] as TNewPetrolRegion;
if Assigned (AllNewTectonicStructures) then
o.NewTectonicStructure := FAllNewTectonicStructures.ItemsByID[ds.FieldByName('NEW_TSTRUCT_ID').AsInteger] as TNewTectonicStructure;
if Assigned (AllTectonicStructures) then
o.TectonicStructure := FAllTectonicStructures.ItemsByID[ds.FieldByName('STRUCT_ID').AsInteger] as TTectonicStructure;
ds.Next;
end;
ds.First;
end;
end;
function TWellPositionDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TDataSet;
o: TWellPosition;
begin
Assert(DataPostString <> '', 'Не задан приемник данных ' + ClassName);
Result := 0;
o := AObject as TWellPosition;
try
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Active then
ds.Open;
if ds.Locate('WELL_UIN', AObject.ID, []) then
ds.Edit
else ds.Append;
except
on E: Exception do
begin
raise;
end;
end;
ds.FieldByName('WELL_UIN').AsInteger := o.Collection.Owner.ID;
if Assigned(o.Topolist) then
ds.FieldByName('TOPOGRAPHICAL_LIST_ID').AsInteger := o.Topolist.ID
else
ds.FieldByName('TOPOGRAPHICAL_LIST_ID').Value := null;
if Assigned(o.District) then
ds.FieldByName('DISTRICT_ID').AsInteger := o.District.ID
else
ds.FieldByName('DISTRICT_ID').Value := null;
if Assigned(o.NGR) then
ds.FieldByName('PETROL_REGION_ID').AsInteger := o.NGR.ID
else
ds.FieldByName('PETROL_REGION_ID').Value := null;
if Assigned(o.TectonicStructure) then
ds.FieldByName('STRUCT_ID').AsInteger := o.TectonicStructure.ID
else
ds.FieldByName('STRUCT_ID').Value := null;
if Assigned(o.NewTectonicStructure) then
ds.FieldByName('NEW_TSTRUCT_ID').AsInteger := o.NewTectonicStructure.ID
else
ds.FieldByName('NEW_TSTRUCT_ID').Value := null;
if Assigned(o.NewNGR) then
ds.FieldByName('NEW_PETROL_REGION_ID').AsInteger := o.NewNGR.ID
else
ds.FieldByName('NEW_PETROL_REGION_ID').Value := null;
ds.Post;
end;
procedure TWellPositionDataPoster.SetAllDistricts(const Value: TDistricts);
begin
if FAllDistricts <> Value then
FAllDistricts := Value;
end;
procedure TWellPositionDataPoster.SetAllTopolists(
const Value: TTopographicalLists);
begin
if FAllTopolists <> Value then
FAllTopolists := Value;
end;
procedure TWellPositionDataPoster.SetAllTectonicStructures(
const Value: TTectonicStructures);
begin
if FAllTectonicStructures <> Value then
FAllTectonicStructures := Value;
end;
procedure TWellPositionDataPoster.SetNewAllPetrolRegions(
const Value: TNewPetrolRegions);
begin
if FAllNewPetrolRegions <> Value then
FAllNewPetrolRegions := Value;
end;
procedure TWellPositionDataPoster.SetNewAllTectonicStructures(
const Value: TNewTectonicStructures);
begin
if FAllNewTectonicStructures <> Value then
FAllNewTectonicStructures := Value;
end;
{ TWellCategoryDataPoster }
constructor TWellCategoryDataPoster.Create;
begin
inherited;
Options := [];
DataSourceString := 'TBL_WELL_CATEGORY_DICT';
DataDeletionString := '';
DataPostString := '';
KeyFieldNames := 'WELL_CATEGORY_ID';
FieldNames := 'WELL_CATEGORY_ID, VCH_CATEGORY_NAME';
AccessoryFieldNames := '';
AutoFillDates := false;
Sort := 'VCH_CATEGORY_NAME';
end;
function TWellCategoryDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer;
begin
Result := 0;
end;
function TWellCategoryDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TWellCategory;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
while not ds.Eof do
begin
o := AObjects.Add as TWellCategory;
o.ID := ds.FieldByName('WELL_CATEGORY_ID').AsInteger;
o.Name := trim(ds.FieldByName('VCH_CATEGORY_NAME').AsString);
ds.Next;
end;
ds.First;
end;
end;
function TWellCategoryDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
begin
Result := 0;
end;
procedure TWellDataPoster.SetAllAreas(const Value: TSimpleAreas);
begin
if FAllAreas <> Value then
FAllAreas := Value;
end;
procedure TWellDataPoster.SetAllEmployee(const Value: TEmployees);
begin
if FAllEmployee <> Value then
FAllEmployee := Value;
end;
procedure TWellDataPoster.SetAllFluidTypes(const Value: TFluidTypes);
begin
if FAllFluidTypes <> Value then
FAllFluidTypes := Value;
end;
procedure TWellDataPoster.SetAllFluidTypesByBalance(
const Value: TFluidTypes);
begin
if FAllFluidTypesByBalance <> Value then
FAllFluidTypesByBalance := Value;
end;
procedure TWellDataPoster.SetAllOrganizations(const Value: TOrganizations);
begin
if FAllOrganizations <> Value then
FAllOrganizations := Value;
end;
procedure TWellDataPoster.SetAllProfiles(const Value: TProfiles);
begin
if FAllProfiles <> Value then
FAllProfiles := Value;
end;
procedure TWellDataPoster.SetAllSimpleStratons(
const Value: TSimpleStratons);
begin
if FAllSimpleStratons <> Value then
FAllSimpleStratons := Value;
end;
procedure TWellDataPoster.SetAllWellCategories(
const Value: TWellCategories);
begin
if FAllWellCategories <> Value then
FAllWellCategories := Value;
end;
procedure TWellDataPoster.SetAllWellStates(const Value: TStates);
begin
if FAllWellStates <> Value then
FAllWellStates := Value;
end;
procedure TWellPositionDataPoster.SetAllPetrolRegions(
const Value: TPetrolRegions);
begin
if FAllPetrolRegions <> Value then
FAllPetrolRegions := Value;
end;
{ TWellBindingDataPoster }
constructor TWellBindingDataPoster.Create;
begin
inherited;
Options := [soSingleDataSource];
DataSourceString := 'TBL_WELL_BINDING';
KeyFieldNames := 'WELL_UIN; AREA_ID; VCH_WELL_NUM';
FieldNames := 'WELL_UIN, AREA_ID, VCH_WELL_NUM';
AccessoryFieldNames := 'WELL_UIN, AREA_ID, VCH_WELL_NUM';
AutoFillDates := false;
Sort := 'WELL_UIN';
end;
function TWellBindingDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer;
begin
Result := 0;
end;
function TWellBindingDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TWellBinding;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
while not ds.Eof do
begin
o := AObjects.Add as TWellBinding;
o.Area := AllAreas.ItemsByID[ds.FieldByName('AREA_ID').AsInteger] as TArea;
o.NumberWell := ds.FieldByName('VCH_WELL_NUM').AsString;
AObjects.Add(o, false, false);
ds.Next;
end;
ds.First;
end;
end;
function TWellBindingDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
begin
Result := 0;
end;
function TWellBindingDataPoster.PostToDB(ACollection: TIDObjects;
AOwner: TIDObject): integer;
var ds: TDataSet;
o: TWell;
os: TWellBindings;
i: integer;
begin
Result := 0;
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Active then ds.Open;
o := AOwner as TWell;
os := ACollection as TWellBindings;
try
while ds.Locate('WELL_UIN', o.ID, []) do
begin
ds.Delete;
ds.First;
end;
except
on E: Exception do
begin
//
end;
end;
for i := 0 to os.Count - 1 do
begin
ds.Append;
while not varIsNull(ds.FieldByName('WELL_UIN').Value) do
ds.Append;
ds.FieldByName('WELL_UIN').Value := o.ID;
ds.FieldByName('AREA_ID').Value := os.Items[i].Area.ID;
ds.FieldByName('VCH_WELL_NUM').Value := os.Items[i].NumberWell;
ds.Post;
end;
end;
procedure TWellBindingDataPoster.SetAllAreas(const Value: TAreas);
begin
if FAllAreas <> Value then
FAllAreas := Value;
end;
procedure TWellBindingDataPoster.SetAllWells(const Value: TWells);
begin
if FAllWells <> Value then
FAllWells := Value;
end;
{ TOrganizationStatusDataPoster }
constructor TWellOrganizationStatusDataPoster.Create;
begin
inherited;
Options := [soSingleDataSource];
DataSourceString := 'TBL_ORG_STATUS';
KeyFieldNames := 'ORG_STATUS_ID; WELL_UIN';
FieldNames := 'ORG_STATUS_ID, WELL_UIN, ORGANIZATION_ID';
AccessoryFieldNames := 'ORG_STATUS_ID, WELL_UIN, ORGANIZATION_ID';
AutoFillDates := false;
end;
function TWellOrganizationStatusDataPoster.DeleteFromDB(
AObject: TIDObject; ACollection: TIDObjects): integer;
begin
Result := 0;
end;
function TWellOrganizationStatusDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TWellOrganizationStatus;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
while not ds.Eof do
begin
o := AObjects.Add as TWellOrganizationStatus;
o.StatusOrganization := AllStatusOrganization.ItemsByID[ds.FieldByName('ORG_STATUS_ID').AsInteger] as TOrganizationStatus;
o.Organization := AllOrganization.ItemsByID[ds.FieldByName('ORGANIZATION_ID').AsInteger] as TOrganization;
ds.Next;
end;
ds.First;
end;
end;
function TWellOrganizationStatusDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TDataSet;
o: TWellOrganizationStatus;
begin
Assert(DataPostString <> '', 'Не задан приемник данных ' + ClassName);
Result := 0;
o := AObject as TWellOrganizationStatus;
try
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Active then
ds.Open;
if ds.Locate('ORG_STATUS_ID; WELL_UIN', varArrayOf([o.StatusOrganization.ID, (o.Collection.Owner as TWell).ID]), []) then
ds.Edit
else ds.Append;
except
on E: Exception do
begin
raise;
end;
end;
ds := TMainFacade.GetInstance.DBGates.Add(Self);
ds.FieldByName('WELL_UIN').AsInteger := (o.Collection.Owner as TWell).ID;
if Assigned (o.StatusOrganization) then
ds.FieldByName('ORG_STATUS_ID').AsInteger := o.StatusOrganization.ID;
if Assigned (o.Organization) then
ds.FieldByName('ORGANIZATION_ID').AsInteger := o.Organization.ID;
ds.Post;
end;
procedure TWellOrganizationStatusDataPoster.SetAllOrganization(
const Value: TOrganizations);
begin
if FAllOrganization <> Value then
FAllOrganization := Value;
end;
procedure TWellOrganizationStatusDataPoster.SetAllStatusOrganization(
const Value: TOrganizationStatuses);
begin
if FAllStatusOrganization <> Value then
FAllStatusOrganization := Value;
end;
{ TSimpleWellDataPoster }
constructor TSimpleWellDataPoster.Create;
begin
inherited;
Options := [soGetKeyValue];
DataSourceString := 'VW_WELL_COORD';
KeyFieldNames := 'WELL_UIN';
AccessoryFieldNames := 'WELL_UIN, VCH_WELL_NUM, VCH_PASSPORT_NUM, AREA_ID, VCH_WELL_NAME, DTM_LAST_MODIFY_DATE, WELL_CATEGORY_ID, WELL_STATE_ID, NUM_IS_PROJECT, TARGET_CATEGORY_ID, NUM_TARGET_DEPTH, NUM_TRUE_DEPTH, DTM_DRILLING_START, DTM_DRILLING_FINISH';
FieldNames := 'WELL_UIN, VCH_WELL_NUM, VCH_PASSPORT_NUM, AREA_ID, VCH_WELL_NAME, DTM_LAST_MODIFY_DATE, WELL_CATEGORY_ID, WELL_STATE_ID, NUM_IS_PROJECT, TARGET_CATEGORY_ID, NUM_TARGET_DEPTH, NUM_TRUE_DEPTH, DTM_DRILLING_START, DTM_DRILLING_FINISH';
AutoFillDates := false;
Sort := 'VCH_AREA_NAME, VCH_WELL_NUM';
end;
function TSimpleWellDataPoster.DeleteFromDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
begin
Result := 0;
end;
function TSimpleWellDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TSimpleWell;
begin
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
while not ds.Eof do
begin
if AObjects.ObjectClass = TSimpleWell then
o := AObjects.Add as TSimpleWell
else o := AObjects.Add as TWell;
//WELL_UIN
o.ID := ds.FieldByName('WELL_UIN').AsInteger;
//VCH_WELL_NUM, VCH_PASSPORT_NUM, AREA_ID, VCH_WELL_NAME
if Assigned(FAllAreas) then
o.Area := FAllAreas.ItemsByID[ds.FieldByName('AREA_ID').AsInteger] as TSimpleArea;
o.Name := trim(ds.FieldByName('VCH_WELL_NAME').AsString);
o.PassportNumberWell := ds.FieldByName('VCH_PASSPORT_NUM').AsString;
o.NumberWell := trim(ds.FieldByName('VCH_WELL_NUM').AsString);
// DTM_LAST_MODIFY_DATE
o.LastModifyDate := ds.FieldByName('DTM_LAST_MODIFY_DATE').AsDateTime;
O.IsProject := ds.FieldByName('NUM_IS_PROJECT').AsInteger > 0;
// WELL_CATEGORY_ID, WELL_STATE_ID
if Assigned(FAllWellCategories) then
begin
o.Category := FAllWellCategories.ItemsByID[ds.FieldByName('WELL_CATEGORY_ID').AsInteger] as TWellCategory;
o.TargetCategory := FAllWellCategories.ItemsByID[ds.FieldByName('TARGET_CATEGORY_ID').AsInteger] as TWellCategory;
end;
if Assigned(FAllWellStates) then
o.State := FAllWellStates.ItemsByID[ds.FieldByName('WELL_STATE_ID').AsInteger] as TState;
o.TrueDepth := ds.FieldByName('NUM_TRUE_DEPTH').AsFloat;
o.TargetDepth := ds.FieldByName('NUM_TARGET_DEPTH').AsFloat;
o.DtDrillingStart := ds.FieldByName('DTM_DRILLING_START').AsDateTime;
o.DtDrillingFinish := ds.FieldByName('DTM_DRILLING_FINISH').AsDateTime;
ds.Next;
end;
ds.First;
end;
end;
function TSimpleWellDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
begin
Result := 0;
end;
procedure TSimpleWellDataPoster.SetAllAreas(const Value: TSimpleAreas);
begin
if FAllAreas <> Value then
FAllAreas := Value;
end;
procedure TSimpleWellDataPoster.SetAllWellCategories(
const Value: TWellCategories);
begin
if FAllWellCategories <> Value then
FAllWellCategories := Value;
end;
procedure TSimpleWellDataPoster.SetAllWellStates(const Value: TStates);
begin
if FAllWellStates <> Value then
FAllWellStates := Value;
end;
{ TWellDynamicParametersDataPoster }
constructor TWellDynamicParametersDataPoster.Create;
begin
inherited;
Options := [soSingleDataSource];
DataSourceString := 'TBL_WELL_DINAMICS';
KeyFieldNames := 'WELL_UIN; VERSION_ID';
FieldNames := 'WELL_UIN, WELL_CATEGORY_ID, WELL_STATE_ID, ' +
'PROFILE_ID, TRUE_STRATON_ID, NUM_TRUE_DEPTH, NUM_TRUE_COST, ' +
'TRUE_FLUID_TYPE_ID, VERSION_ID, EMPLOYEE_ID, DTM_LAST_MODIFY_DATE, NUM_IS_PROJECT, MODIFIER_ID, DTM_ENTERING_DATE, NUM_IS_WELL_EDITED';
AccessoryFieldNames := FieldNames;
AutoFillDates := false;
Sort := 'WELL_UIN, VERSION_ID';
end;
function TWellDynamicParametersDataPoster.DeleteFromDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var o: TWellDynamicParameters;
ds: TCommonServerDataSet;
begin
o := AObject as TWellDynamicParameters;
Assert(DataDeletionString <> '', 'Не задан приемник данных ' + ClassName);
Assert(Assigned(o), 'Не задан сохраняемый объект');
Assert(Assigned(o.Version), 'Не задана версия сохраняемого объекта');
Result := 0;
try
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Active then
ds.Open;
ds.First;
if ds.Locate('WELL_UIN; VERSION_ID', varArrayOf([AObject.ID, o.Version.ID]), []) then
ds.Delete;
except
on E: Exception do
begin
raise;
end;
end;
end;
function TWellDynamicParametersDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TWellDynamicParameters;
begin
Assert(Assigned(AllCategories));
Assert(Assigned(AllProfiles));
Assert(Assigned(AllStates));
Assert(Assigned(AllFluidTypes));
Assert(Assigned(AllStratons));
Assert(Assigned(AllVersions));
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
while not ds.Eof do
begin
o := AObjects.Add as TWellDynamicParameters;
o.WellCategory := AllCategories.ItemsByID[ds.FieldByName('WELL_CATEGORY_ID').AsInteger] as TWellCategory;
o.WellState := AllStates.ItemsById[ds.FieldByName('WELL_STATE_ID').AsInteger] as TState;
o.WellProfile := AllProfiles.ItemsById[ds.FieldByName('PROFILE_ID').AsInteger] as TProfile;
o.TrueDepth := ds.FieldByName('NUM_TRUE_DEPTH').AsFloat;
o.TrueFluidType := AllFluidTypes.ItemsById[ds.FieldByName('TRUE_FLUID_TYPE_ID').AsInteger] as TFluidType;
o.TrueCost := ds.FieldByName('NUM_TRUE_COST').AsFloat;
o.TrueStraton := AllStratons.ItemsById[ds.FieldByName('TRUE_STRATON_ID').AsInteger] as TSimpleStraton;
o.Version := AllVersions.ItemsByID[ds.FieldByName('VERSION_ID').AsInteger] as TVersion;
ds.Next;
end;
ds.First;
end;
end;
function TWellDynamicParametersDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var o: TWellDynamicParameters;
ds: TCommonServerDataSet;
begin
o := AObject as TWellDynamicParameters;
Assert(DataPostString <> '', 'Не задан приемник данных ' + ClassName);
Assert(Assigned(o), 'Не задан сохраняемый объект');
Assert(Assigned(o.Version), 'Не задана версия сохраняемого объекта');
Result := 0;
try
ds := TMainFacade.GetInstance.DBGates.Add(Self);
ds.Close;
ds.Open;
if ds.Locate('WELL_UIN; VERSION_ID', varArrayOf([AObject.Owner.ID, o.Version.ID]), []) then
ds.Edit
else
begin
ds.Append;
ds.FieldByName('EMPLOYEE_ID').Value := TMainFacade.GetInstance.DBGates.EmployeeID;
ds.FieldByName('DTM_ENTERING_DATE').Value := Date;
end;
except
on E: Exception do
begin
raise;
end;
end;
ds.FieldByName('WELL_UIN').Value := o.Owner.ID;
ds.FieldByName('VERSION_ID').Value := o.Version.ID;
if Assigned(o.WellCategory) then
ds.FieldByName('WELL_CATEGORY_ID').Value := o.WellCategory.ID
else
ds.FieldByName('WELL_CATEGORY_ID').Value := null;
if Assigned(o.WellState) then
ds.FieldByName('WELL_STATE_ID').Value := o.WellState.ID
else
ds.FieldByName('WELL_STATE_ID').Value := null;
if Assigned(o.WellProfile) then
ds.FieldByName('PROFILE_ID').Value := o.WellProfile.ID
else
ds.FieldByName('PROFILE_ID').Value := null;
if Assigned(o.TrueStraton) then
ds.FieldByName('TRUE_STRATON_ID').Value := o.TrueStraton.ID
else
ds.FieldByName('TRUE_STRATON_ID').Value := null;
if Assigned(o.TrueFluidType) then
ds.FieldByName('TRUE_FLUID_TYPE_ID').Value := o.TrueFluidType.ID
else
ds.FieldByName('TRUE_FLUID_TYPE_ID').Value := null;
ds.FieldByName('NUM_TRUE_DEPTH').Value := o.TrueDepth;
ds.FieldByName('NUM_TRUE_COST').Value := o.TrueCost;
ds.FieldByName('MODIFIER_ID').Value := TMainFacade.GetInstance.DBGates.EmployeeID;
ds.FieldByName('DTM_LAST_MODIFY_DATE').Value := Date;
ds.FieldByName('NUM_IS_PROJECT').Value := ord(o.IsProject);
ds.FieldByName('NUM_IS_WELL_EDITED').Value := 0;
ds.Post;
end;
{ TWellLicenseZoneDataPoster }
constructor TWellLicenseZoneDataPoster.Create;
begin
inherited;
Options := [soSingleDataSource];
DataSourceString := 'TBL_WELL_LICENSE_ZONE';
KeyFieldNames := 'WELL_UIN; VERSION_ID; LICENSE_ZONE_ID';
FieldNames := 'WELL_UIN, VERSION_ID, LICENSE_ZONE_ID';
AccessoryFieldNames := 'WELL_UIN, VERSION_ID, LICENSE_ZONE_ID';
AutoFillDates := false;
Sort := 'WELL_UIN, VERSION_ID, LICENSE_ZONE_ID';
end;
function TWellLicenseZoneDataPoster.DeleteFromDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TCommonServerDataSet;
o: TWellLicenseZone;
begin
Assert(DataDeletionString <> '', 'Не задан приемник данных ' + ClassName);
Result := 0;
ds := TMainFacade.GetInstance.DBGates.Add(Self);
o := AObject as TWellLicenseZone;
Assert(Assigned(o.Version), 'Не задана версия объекта');
Assert(Assigned(o.LicenseZone), 'На задан лицензионный участок');
try
// находим строку соответствующую ключу
ds.First;
if ds.Locate(KeyFieldNames, varArrayOf([AObject.ID, o.Version.ID, o.LicenseZone.ID]), []) then
ds.Delete;
except
Result := -1;
end;
end;
function TWellLicenseZoneDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TWellLicenseZone;
begin
Assert(Assigned(AllVersions), 'Не заданы версии объектов');
Assert(Assigned(LicenseZoneVersionObjectSets), 'Не задан источник лицензионных участков');
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
while not ds.Eof do
begin
o := AObjects.Add as TWellLicenseZone;
o.ID := ds.FieldByName('WELL_UIN').AsInteger;
o.Version := AllVersions.ItemsByID[ds.FieldByName('VERSION_ID').AsInteger] as TVersion;
o.LicenseZone := LicenseZoneVersionObjectSets.GetObjectSetByVersion(o.Version).Objects.ItemsByID[ds.FieldByName('LICENSE_ZONE_ID').AsInteger] as TSimpleLicenseZone;
ds.Next;
end;
ds.First;
end;
end;
function TWellLicenseZoneDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TDataSet;
o: TWellLicenseZone;
begin
Assert(DataPostString <> '', 'Не задан приемник данных ' + ClassName);
Assert(Assigned(AllVersions), 'Не заданы версии объектов');
Assert(Assigned(LicenseZoneVersionObjectSets), 'Не задан источник лицензионных участков');
Result := 0;
o := AObject as TWellLicenseZone;
Assert(Assigned(o.Version), 'Не задана версия объекта');
Assert(Assigned(o.LicenseZone), 'На задан лицензионный участок');
try
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Active then
ds.Open;
if ds.Locate(KeyFieldNames, varArrayOf([AObject.ID, o.Version.ID, o.LicenseZone.ID]), []) then
ds.Edit
else ds.Append;
except
on E: Exception do
begin
raise;
end;
end;
ds.FieldByName('VERSION_ID').AsInteger := o.Version.ID;
ds.FieldByName('LICENSE_ZONE_ID').AsInteger := o.LicenseZone.ID;
ds.Post;
end;
{ TWellStructureDataPoster }
constructor TWellStructureDataPoster.Create;
begin
inherited;
Options := [soSingleDataSource];
DataSourceString := 'TBL_WELL_STRUCTURE';
KeyFieldNames := 'WELL_UIN; VERSION_ID; STRUCTURE_ID';
FieldNames := 'WELL_UIN, VERSION_ID, STRUCTURE_ID';
AccessoryFieldNames := 'WELL_UIN, VERSION_ID, STRUCTURE_ID';
AutoFillDates := false;
Sort := 'WELL_UIN, VERSION_ID, STRUCTURE_ID';
end;
function TWellStructureDataPoster.DeleteFromDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TCommonServerDataSet;
o: TWellStructure;
begin
Assert(DataDeletionString <> '', 'Не задан приемник данных ' + ClassName);
Result := 0;
ds := TMainFacade.GetInstance.DBGates.Add(Self);
o := AObject as TWellStructure;
Assert(Assigned(o.Version), 'Не задана версия объекта');
Assert(Assigned(o.Structure), 'На задана структура');
try
// находим строку соответствующую ключу
ds.First;
if ds.Locate(KeyFieldNames, varArrayOf([AObject.ID, o.Version.ID, o.Structure.ID]), []) then
ds.Delete;
except
Result := -1;
end;
end;
function TWellStructureDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TWellStructure;
begin
Assert(Assigned(AllVersions), 'Не заданы версии объектов');
Assert(Assigned(StructureVersionObjectSets), 'Не задан источник структур');
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
while not ds.Eof do
begin
o := AObjects.Add as TWellStructure;
o.ID := ds.FieldByName('WELL_UIN').AsInteger;
o.Version := AllVersions.ItemsByID[ds.FieldByName('VERSION_ID').AsInteger] as TVersion;
o.Structure := StructureVersionObjectSets.GetObjectSetByVersion(o.Version).Objects.ItemsByID[ds.FieldByName('STRUCTURE_ID').AsInteger] as TSimpleStructure;
ds.Next;
end;
ds.First;
end;
end;
function TWellStructureDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TDataSet;
o: TWellStructure;
begin
Assert(DataPostString <> '', 'Не задан приемник данных ' + ClassName);
Assert(Assigned(AllVersions), 'Не заданы версии объектов');
Assert(Assigned(StructureVersionObjectSets), 'Не задан источник структур');
Result := 0;
o := AObject as TWellStructure;
Assert(Assigned(o.Version), 'Не задана версия объекта');
Assert(Assigned(o.Structure), 'На задана структура');
try
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Active then
ds.Open;
if ds.Locate(KeyFieldNames, varArrayOf([AObject.ID, o.Version.ID, o.Structure.ID]), []) then
ds.Edit
else ds.Append;
except
on E: Exception do
begin
raise;
end;
end;
ds.FieldByName('VERSION_ID').AsInteger := o.Version.ID;
ds.FieldByName('STRUCTURE_ID').AsInteger := o.Structure.ID;
ds.Post;
end;
{ TWellFieldDataPoster }
constructor TWellFieldDataPoster.Create;
begin
inherited;
Options := [soSingleDataSource];
DataSourceString := 'TBL_WELL_FIELD';
KeyFieldNames := 'WELL_UIN; VERSION_ID; FIELD_ID';
FieldNames := 'WELL_UIN, VERSION_ID, FIELD_ID';
AccessoryFieldNames := 'WELL_UIN, VERSION_ID, FIELD_ID';
AutoFillDates := false;
Sort := 'WELL_UIN, VERSION_ID, FIELD_ID';
end;
function TWellFieldDataPoster.DeleteFromDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TCommonServerDataSet;
o: TWellField;
begin
Assert(DataDeletionString <> '', 'Не задан приемник данных ' + ClassName);
Result := 0;
ds := TMainFacade.GetInstance.DBGates.Add(Self);
o := AObject as TWellField;
Assert(Assigned(o.Version), 'Не задана версия объекта');
Assert(Assigned(o.Field), 'На задано месторождение');
try
// находим строку соответствующую ключу
ds.First;
if ds.Locate(KeyFieldNames, varArrayOf([AObject.ID, o.Version.ID, o.Field.ID]), []) then
ds.Delete;
except
Result := -1;
end;
end;
function TWellFieldDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TWellField;
begin
Assert(Assigned(AllVersions), 'Не заданы версии объектов');
Assert(Assigned(FieldVersionObjectSets), 'Не задан источник месторождений');
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
while not ds.Eof do
begin
o := AObjects.Add as TWellField;
o.ID := ds.FieldByName('WELL_UIN').AsInteger;
o.Version := AllVersions.ItemsByID[ds.FieldByName('VERSION_ID').AsInteger] as TVersion;
o.Field := FieldVersionObjectSets.GetObjectSetByVersion(o.Version).Objects.ItemsByID[ds.FieldByName('FIELD_ID').AsInteger] as TSimpleField;
ds.Next;
end;
ds.First;
end;
end;
function TWellFieldDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TDataSet;
o: TWellField;
begin
Assert(DataPostString <> '', 'Не задан приемник данных ' + ClassName);
Assert(Assigned(AllVersions), 'Не заданы версии объектов');
Assert(Assigned(FieldVersionObjectSets), 'Не задан источник месторождений');
Result := 0;
o := AObject as TWellField;
Assert(Assigned(o.Version), 'Не задана версия объекта');
Assert(Assigned(o.Field), 'На задано месторождение');
try
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Active then
ds.Open;
if ds.Locate(KeyFieldNames, varArrayOf([AObject.ID, o.Version.ID, o.Field.ID]), []) then
ds.Edit
else ds.Append;
except
on E: Exception do
begin
raise;
end;
end;
ds.FieldByName('VERSION_ID').AsInteger := o.Version.ID;
ds.FieldByName('FIELD_ID').AsInteger := o.Field.ID;
ds.Post;
end;
{ TWellBedDataPoster }
constructor TWellBedDataPoster.Create;
begin
inherited;
Options := [soSingleDataSource];
DataSourceString := 'TBL_WELL_BED';
KeyFieldNames := 'WELL_UIN; VERSION_ID; BED_ID';
FieldNames := 'WELL_UIN, VERSION_ID, BED_ID';
AccessoryFieldNames := 'WELL_UIN, VERSION_ID, BED_ID';
AutoFillDates := false;
Sort := 'WELL_UIN, VERSION_ID, BED_ID';
end;
function TWellBedDataPoster.DeleteFromDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TCommonServerDataSet;
o: TWellBed;
begin
Assert(DataDeletionString <> '', 'Не задан приемник данных ' + ClassName);
Result := 0;
ds := TMainFacade.GetInstance.DBGates.Add(Self);
o := AObject as TWellBed;
Assert(Assigned(o.Version), 'Не задана версия объекта');
Assert(Assigned(o.Bed), 'На задана залежь');
try
// находим строку соответствующую ключу
ds.First;
if ds.Locate(KeyFieldNames, varArrayOf([AObject.ID, o.Version.ID, o.Bed.ID]), []) then
ds.Delete;
except
Result := -1;
end;
end;
function TWellBedDataPoster.GetFromDB(AFilter: string;
AObjects: TIdObjects): integer;
var ds: TDataSet;
o: TWellBed;
begin
Assert(Assigned(AllVersions), 'Не заданы версии объектов');
Assert(Assigned(BedVersionObjectSets), 'Не задан источник залежей');
Result := inherited GetFromDB(AFilter, AObjects);
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Eof then
begin
ds.First;
while not ds.Eof do
begin
o := AObjects.Add as TWellBed;
o.ID := ds.FieldByName('WELL_UIN').AsInteger;
o.Version := AllVersions.ItemsByID[ds.FieldByName('VERSION_ID').AsInteger] as TVersion;
o.Bed := BedVersionObjectSets.GetObjectSetByVersion(o.Version).Objects.ItemsByID[ds.FieldByName('BED_ID').AsInteger] as TSimpleBed;
ds.Next;
end;
ds.First;
end;
end;
function TWellBedDataPoster.PostToDB(AObject: TIDObject;
ACollection: TIDObjects): integer;
var ds: TDataSet;
o: TWellBed;
begin
Assert(DataPostString <> '', 'Не задан приемник данных ' + ClassName);
Assert(Assigned(AllVersions), 'Не заданы версии объектов');
Assert(Assigned(BedVersionObjectSets), 'Не задан источник залежей');
Result := 0;
o := AObject as TWellBed;
Assert(Assigned(o.Version), 'Не задана версия объекта');
Assert(Assigned(o.Bed), 'На задана залежь');
try
ds := TMainFacade.GetInstance.DBGates.Add(Self);
if not ds.Active then
ds.Open;
if ds.Locate(KeyFieldNames, varArrayOf([AObject.ID, o.Version.ID, o.Bed.ID]), []) then
ds.Edit
else ds.Append;
except
on E: Exception do
begin
raise;
end;
end;
ds.FieldByName('VERSION_ID').AsInteger := o.Version.ID;
ds.FieldByName('BED_ID').AsInteger := o.Bed.ID;
ds.Post;
end;
end.
|
unit XParticles;
interface
{ This is a cut-down version of Untitled-3D's particle engine, ported to CgLib.
The TParticleSystem class can manage any number of particles of any type. The
TParticle class has abstract methods to handle updating and rendering. The
system uses metaclasses to add particles to a system, so you can mix several
particle types in the same particle system.
This version of the system requires each particle to define its own parameters
in the Reset() method. The full Untitled-3D system adds some functionality
to read parameters from a file stream, so particle classes don't have to be
as specific as they are here (particle classes for this program are defined
in XParticleClasses.pas). For the latest news on Untitled-3D, keep an eye on
http://www.gamedeveloper.org/delphi3d/projects.shtml }
uses
CgTypes;
{$Z4}
type
TParticleSystem = class; // Forward.
TParticle = class
public
// Predefined properties:
Pos: TCGVector;
Owner: TParticleSystem;
// User code:
procedure Reset; virtual; abstract;
procedure Step(time: Single); virtual; abstract;
procedure Render; virtual; abstract;
constructor Create(AOwner: TParticleSystem); virtual;
end;
TParticleType = class of TParticle;
TParticleSystem = class
public
Particles: array of TParticle;
function AddParticles(pType: TParticleType; n: Integer): Integer;
procedure DeleteParticles(start, n: Integer);
procedure Render;
procedure Step(time: Single);
procedure Reset;
destructor Destroy; override;
end;
implementation
constructor TParticle.Create(AOwner: TParticleSystem);
begin
inherited Create;
Owner := AOwner;
end;
{******************************************************************************}
{ TPARTICLESYSTEM }
{******************************************************************************}
function TParticleSystem.AddParticles(pType: TParticleType; n: Integer): Integer;
var
x, i: Integer;
begin
// Add n particles of the given type to the system.
x := Length(Particles);
SetLength(Particles, x + n);
for i := x to x + n - 1 do
begin
Particles[i] := pType.Create(Self);
Particles[i].Reset;
end;
Result := x;
end;
procedure TParticleSystem.DeleteParticles(start, n: Integer);
var
i: Integer;
begin
// Delete some particles.
for i := start to start + n - 1 do
begin
Particles[i].Free;
Particles[i] := Particles[i+n];
end;
SetLength(Particles, Length(Particles) - n);
end;
destructor TParticleSystem.Destroy;
var
i: Integer;
begin
// Delete all particles
for i := 0 to High(Particles) do Particles[i].Free;
inherited Destroy;
end;
procedure TParticleSystem.Render;
var
i: Integer;
begin
for i := 0 to High(Particles) do Particles[i].Render;
end;
procedure TParticleSystem.Reset;
var
i: Integer;
begin
for i := 0 to High(Particles) do Particles[i].Reset;
end;
procedure TParticleSystem.Step(time: Single);
var
i: Integer;
begin
for i := 0 to High(Particles) do Particles[i].Step(time);
end;
end.
|
{-----------------------------------------------------------------------------}
{ }
{ 「Delphi によるシェルプログラミング入門」サンプルプログラム }
{ }
{ 「項目識別子に対する処理」の実装例 }
{ }
{ Copyright 1998 Masahiro Arai }
{ }
{-----------------------------------------------------------------------------}
unit pidl;
interface
uses
Windows, SysUtils, ShellAPI, ShlObj, ActiveX, Classes;
// 項目識別子(リスト)を格納するためのメモリを確保する
function AllocItemID (Size: integer): PItemIDList;
// 項目識別子(リスト)のサイズを求める
function GetItemIDSize(ItemIDList: PItemIDList): integer;
// 項目識別子(リスト)のコピーを作成する
function CopyItemID (ItemIDList: PItemIDList): PItemIDList;
// 項目識別子(リスト)を連結して新しい項目識別子を作成する
function ConcatItemID (ItemIDList1, ItemIDList2: PItemIDList):
PItemIDList;
// 項目識別子リスト中の「次の項目識別子」を見つける
function GetNextItemID(ItemIDList: PItemIDList): PItemIDList;
// 項目識別子(リスト)を表す文字列を取得する
function GetItemIDName(Folder: IShellFolder; ItemID: PItemIDList;
Flags: integer): string;
// 項目識別子(リスト)を表すアイコンのインデックスを取得する
function GetItemIDIcon(ItemIDList: PItemIDList; Flags: integer):
integer;
// 2つの項目識別子を比較する
function CompareItemID(ShellFolder: IShellFolder;
ItemID1, ItemID2: PItemIDList): Integer;
// 項目識別子リストに含まれる項目識別子をリストアップする
// ※リスト内の各要素は、シェルメモリーアロケーターによって解放すること
function DivItemIDList(ItemIDList: PItemIDList): TList;
var
Malloc: IMalloc;
implementation
// 項目識別子(リスト)を格納するためのメモリを確保する
function AllocItemID(Size: integer): PItemIDList;
var
ItemIDList: PItemIDList;
begin
// 項目識別子(リスト)を格納するためのメモリを確保
ItemIDList := Malloc.Alloc(Size);
// 取得したメモリの内容を初期化
if Assigned(ItemIDList) then
FillChar(ItemIDList^, Size, 0);
Result := ItemIDList;
end;
// 項目識別子(リスト)のサイズを求める
function GetItemIDSize(ItemIDList: PItemIDList): integer;
var
Total: integer;
begin
Total := 0;
if Assigned(ItemIDList) then
begin
// 項目識別子を順番に検索する
while (ItemIDList^.mkid.cb > 0) do
begin
inc(Total, ItemIDList^.mkid.cb);
ItemIDList := GetNextItemID(ItemIDList);
end;
// 項目識別子リストの最後に加わるターミネーターの大きさを加算
Total := Total + SizeOf(ItemIDList^.mkid.cb);
end;
Result := Total;
end;
// 項目識別子(リスト)のコピーを作成する
// ※受け取った項目識別子(リスト)は Malloc.Free(ItemID) を用いて
// 破棄しなければならない
function CopyItemID(ItemIDList: PItemIDList): PItemIDList;
var
NewItemID: PItemIDList;
CopySize: integer;
begin
// 「空の項目識別子」はコピーしない
Result := nil;
if not Assigned(ItemIDList) then
Exit;
// 項目識別子リストの大きさを取得
CopySize := GetItemIDSize(ItemIDList);
// メモリを確保
NewItemID := AllocItemID(CopySize);
// 項目識別子リストのコピー
Move(ItemIDList^, NewItemID^, CopySize);
Result := NewItemID;
end;
// 項目識別子(リスト)を連結して新しい項目識別子を作成する
// ※受け取った項目識別子(リスト)は Malloc.Free(ItemID) を用いて
// 破棄しなければならない
function ConcatItemID(ItemIDList1, ItemIDList2: PItemIDList):
PItemIDList;
var
NewItemIDlist: PChar;
ItemSize1, ItemSize2: integer;
begin
// コピーを行うサイズを取得
if Assigned(ItemIDList1) then
// ターミネーターはコピーしない
ItemSize1 := GetItemIDSize(ItemIDList1)
- SizeOf(ItemIDList1^.mkid.cb)
else
Itemsize1 := 0;
ItemSize2 := GetItemIDSize(ItemIDList2);
// 新しい項目識別子リストを格納するメモリの取得
NewItemIDList := PChar(AllocItemID(ItemSize1 + ItemSize2));
// NewItemIDList は以下の処理で加工するので、戻り値を予め設定する。
Result := PItemIDList(NewItemIDList);
// 項目識別子(リスト)のコピー
if Assigned(NewItemIDList) then
begin
if Assigned(ItemIDList1) then
Move(ItemIDList1^, NewItemIDList^, ItemSize1);
// ポインタのオフセットを行う
inc(NewItemIDList, ItemSize1);
Move(ItemIDList2^, NewItemIDList^, ItemSize2);
end;
end;
// 項目識別子(リスト)を表す文字列を取得する
function GetItemIDName(Folder: IShellFolder; ItemID: PItemIDList;
Flags: integer): string;
var
StrRet: TStrRet;
Chars: PChar;
begin
Result := '';
if (NOERROR = Folder.GetDisplayNameOf(ItemID, Flags, StrRet)) then
begin
case StrRet.uType of
STRRET_WSTR:
begin
//PWideChar から string へのコピー
Result := StrRet.pOleStr;
end;
STRRET_OFFSET:
begin
//ポインタのオフセット
Chars := PChar(ItemID);
inc(Chars, StrRet.uOffset);
//PChar から string へのコピー
Result := Chars;
end;
STRRET_CSTR:
//PChar から string へのコピー
Result := StrRet.cStr;
end;
end;
end;
// 項目識別子リスト中の「次の項目識別子」を見つける
function GetNextItemID(ItemIDList: PItemIDList): PItemIDList;
var
NextItemID: PChar;
begin
// inc を用いてオフセットを行うために PChar 型にキャストする
NextItemID := PChar(ItemIDList);
// ポインタのオフセットを行い、次の要素を指す
inc(NextItemID, ItemIDList^.mkid.cb);
if ItemIDList^.mkid.cb = 0 then
Result := nil
else
Result := PItemIDList(NextItemID);
end;
// 項目識別子(リスト)を表すアイコンのインデックスを取得する
function GetItemIDIcon(ItemIDList: PItemIDList; Flags: integer):
integer;
var
SHFileInfo: TSHFileInfo;
begin
SHGetFileInfo(pchar(ItemIDList), 0, SHFileInfo, Sizeof(TSHFileInfo),
SHGFI_PIDL or Flags);
Result := SHFileInfo.iIcon;
end;
// 項目識別子を比較する
function CompareItemID(ShellFolder: IShellFolder;
ItemID1, ItemID2: PItemIDList): Integer;
begin
Result := SHORT($FFFF and ShellFolder.CompareIDs(0, ItemID1, ItemID2));
end;
// 項目識別子リストに含まれる項目識別子をリストアップする
// ※リスト内の各要素は、シェルメモリーアロケーターによって解放すること
function DivItemIDList(ItemIDList: PItemIDList): TList;
var
ItemSize: Integer;
NewItemID: PItemIDList;
begin
Result := TList.Create;
while Assigned(ItemIDList) do
begin
// リスト内の各要素のサイズを取得する
ItemSize := ItemIDList^.mkid.cb;
// 要素がヌルターミネーターであれば処理を終了
if ItemSize = 0 then
Exit;
// 一階層分の項目を抽出する
NewItemID := AllocItemID(ItemSize+SizeOf(ItemIDList^.mkid.cb));
Move(ItemIDList^, NewItemID^, ItemSize);
Result.Add(NewItemID);
// 次の項目を指す
ItemIDList := GetNextItemID(ItemIDList)
end;
end;
initialization
//シェル・メモリ・アロケーターを確保する
SHGetMalloc(Malloc);
finalization
Malloc := nil;
end.
|
unit Spline;
////////////////////////////////////////////////////////////////////////////////
//
// Author: Jaap Baak
// https://github.com/transportmodelling/Utils
//
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
interface
////////////////////////////////////////////////////////////////////////////////
Uses
SysUtils,Math,Polynom;
Type
TSpline = record
private
FNPieces: Integer;
FKnots: array of Float64;
FPolynomials: array of TPolynomial;
public
Class Operator Multiply(a: TSpline; b: TSpline): TSpline;
Constructor Create(Const Knots: array of Float64; Const Polynomials: array of TPolynomial);
Procedure Nullify;
Function Integrate: Float64; overload;
Function Integrate(Const a,b: Float64): Float64; overload;
end;
////////////////////////////////////////////////////////////////////////////////
implementation
////////////////////////////////////////////////////////////////////////////////
Class Operator TSpline.Multiply(a: TSpline; b: TSpline): TSpline;
Var
Index_a,Index_b: Integer;
begin
SetLength(Result.FKnots,a.FNPieces+b.FNPieces+2);
SetLength(Result.FPolynomials,a.FNPieces+b.FNPieces);
if (a.FNPieces > 0) and (b.FNPieces > 0) then
begin
// Set first knot
if a.FKnots[0] < b.FKnots[0] then
begin
Result.FKnots[0] := b.FKnots[0];
Index_a := 1;
Index_b := 1;
while (Index_a <= a.FNPieces) and (a.FKnots[Index_a] <= b.FKnots[0]) do Inc(Index_a);
end else
begin
Result.FKnots[0] := a.FKnots[0];
Index_a := 1;
Index_b := 1;
while (Index_b <= b.FNPieces) and (b.FKnots[Index_b] < a.FKnots[0]) do Inc(Index_b)
end;
// Set subsequent knots
var Count := 0;
while (Index_a <= a.FNPieces) and (Index_b <= b.FNPieces) do
begin
if a.FKnots[Index_a] < b.FKnots[Index_b] then
begin
Inc(Count);
Result.FKnots[Count] := a.FKnots[Index_a];
Result.FPolynomials[count-1] := a.FPolynomials[Index_a-1]*b.FPolynomials[Index_b-1];
Inc(Index_a);
end else
if a.FKnots[Index_a] > b.FKnots[Index_b] then
begin
Inc(Count);
Result.FKnots[Count] := b.FKnots[Index_b];
Result.FPolynomials[count-1] := a.FPolynomials[Index_a-1]*b.FPolynomials[Index_b-1];
Inc(Index_b);
end else
begin
Inc(Count);
Result.FKnots[Count] := a.FKnots[Index_a];
Result.FPolynomials[count-1] := a.FPolynomials[Index_a-1]*b.FPolynomials[Index_b-1];
Inc(Index_a);
Inc(Index_b);
end;
end;
Result.FNPieces := Count;
end else Result.FNPieces := 0;
end;
Constructor TSpline.Create(Const Knots: array of Float64; Const Polynomials: array of TPolynomial);
begin
if Length(Knots) = Length(Polynomials)+1 then
begin
FNPieces := Length(Polynomials);
SetLength(FKnots,FNPieces+1);
SetLength(FPolynomials,FNPieces);
for var Piece := 0 to FNPieces-1 do
begin
FKnots[Piece] := Knots[Piece];
FPolynomials[Piece] := Polynomials[Piece];
end;
FKnots[FNPieces] := Knots[FNPieces];
end else raise Exception.Create('Inconsistent spline constructor arguments');
end;
Procedure TSpline.Nullify;
begin
FNPieces := 0;
end;
Function TSpline.Integrate: Float64;
begin
Result := 0;
for var Piece := 0 to FNPieces-1 do
Result := Result + FPolynomials[Piece].Integrate(FKnots[Piece],FKnots[Piece+1]);
end;
Function TSpline.Integrate(Const a,b: Float64): Float64;
begin
Result := 0;
for var Piece := 0 to FNPieces-1 do
begin
var c := Max(a,FKnots[Piece]);
var d := Min(b,FKnots[Piece+1]);
if d > c then Result := Result + FPolynomials[Piece].Integrate(c,d);
end;
end;
end.
|
{ wakaru
Copyright (c) 2019 mr-highball
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
}
unit wakaru.utils;
{$mode delphi}
interface
uses
Classes,
SysUtils,
wakaru.consts;
(*
provided a range, this method will return the appropriate signal
enumeration it belongs to
*)
function RangeToSignal(Const ARange : TSignalRange) : TSignal;
implementation
function RangeToSignal(const ARange: TSignalRange): TSignal;
begin
//map the input range to the corresponding signal enum
if (ARange >= Low(TAlphaRange)) and (ARange <= High(TAlphaRange)) then
Exit(sgAlpha)
else if (ARange >= Low(TBetaRange)) and (ARange <= High(TBetaRange)) then
Exit(sgBeta)
else if (ARange >= Low(TGammaRange)) and (ARange <= High(TGammaRange)) then
Exit(sgGamma)
else
Exit(sgDelta);
end;
end.
|
Unit AdvTextExtractors;
{
Copyright (c) 2001-2013, Kestral Computing Pty Ltd (http://www.kestral.com.au)
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
}
Interface
Uses
SysUtils, Classes,
StringSupport, MathSupport, EncodeSupport,
AdvExtractors, AdvCharacterSets, AdvStreams, AdvStreamReaders,
AdvStringBuilders;
Type
TAdvTextExtractor = Class(TAdvStreamReader)
Private
FLine : Integer;
FCache : String;
FBuilder : TAdvStringBuilder;
Protected
Function ErrorClass : EAdvExceptionClass; Override;
Procedure CacheAdd(Const sValue : String); Virtual;
Procedure CacheRemove(Const sValue : String); Virtual;
Procedure RaiseError(Const sMethod, sMessage : String); Override;
Public
Constructor Create; Overload; Override;
Destructor Destroy; Override;
Function More : Boolean; Virtual;
Function ConsumeLine : String;
Procedure ProduceString(Const sToken : String);
Procedure ProduceCharacter(Const cToken : Char);
Function ConsumeCharacter : Char; Overload; Virtual;
Function ConsumeString(Const sToken : String) : String;
Function ConsumeCharacter(Const cToken : Char) : Char; Overload;
Function ConsumeCharacterCount(Const iCharacterCount : Integer) : String;
Function ConsumeWhileCharacter(Const cToken : Char) : String;
Function ConsumeWhileCharacterSet(Const aTokenSet : TCharSet) : String; Overload;
Function ConsumeWhileCharacterSet(Const oCharacterSet : TAdvCharacterSet) : String; Overload;
Function ConsumeUntilCharacter(Const cToken : Char) : String;
Function ConsumeUntilCharacterSet(Const aTokenSet : TCharSet) : String;
Function ConsumeUntilString(Const sToken : String) : String; Overload;
Function ConsumeUntilString(Const aStringArray : Array Of String) : String; Overload;
Function ConsumeRestStream : String;
Function MatchString(Const sToken : String) : Boolean;
Function MatchStringArray(Const aTokenSet : Array Of String) : Integer;
Function NextCharacter : Char;
Function CacheLength : Integer;
Function StreamPosition : Int64;
Property Line : Integer Read FLine Write FLine;
End;
EAdvTextExtractor = Class(EAdvExtractor);
EAdvExceptionClass = AdvExtractors.EAdvExceptionClass;
Implementation
Constructor TAdvTextExtractor.Create;
Begin
Inherited;
FBuilder := TAdvStringBuilder.Create;
End;
Destructor TAdvTextExtractor.Destroy;
Begin
FBuilder.Free;
Inherited;
End;
Procedure TAdvTextExtractor.CacheAdd(Const sValue: String);
Begin
Inherited;
Dec(FLine, StringCount(sValue, cEnter));
End;
Procedure TAdvTextExtractor.CacheRemove(Const sValue: String);
Begin
Inherited;
Inc(FLine, StringCount(sValue, cEnter));
End;
Function TAdvTextExtractor.ConsumeLine : String;
Begin
Result := ConsumeUntilCharacterSet(setVertical);
ConsumeWhileCharacterSet(setVertical);
End;
Procedure TAdvTextExtractor.RaiseError(Const sMethod, sMessage: String);
Begin
Inherited RaiseError(sMethod, StringFormat('Line %d: %s', [FLine, sMessage]));
End;
Function TAdvTextExtractor.ErrorClass: EAdvExceptionClass;
Begin
Result := EAdvTextExtractor;
End;
Procedure TAdvTextExtractor.ProduceString(Const sToken : String);
Begin
FCache := sToken + FCache;
CacheAdd(sToken);
End;
Procedure TAdvTextExtractor.ProduceCharacter(Const cToken : Char);
Begin
ProduceString(cToken);
End;
Function TAdvTextExtractor.MatchString(Const sToken: String): Boolean;
Var
iCacheLength : Integer;
iTokenLength : Integer;
iReadSize : Integer;
sNextString : String;
Buffer: SysUtils.TCharArray;
Begin
iTokenLength := Length(sToken);
iCacheLength := Length(FCache);
SetLength(Buffer, iTokenLength - iCacheLength);
iReadSize := Read(Buffer, 0, iTokenLength - iCacheLength);
If iReadSize > 0 Then
Begin
SetLength(Buffer, iReadSize);
SetString(sNextString, pchar(Buffer), Length(Buffer));
FCache := FCache + sNextString;
End;
Result := StringEquals(FCache, sToken, iTokenLength);
End;
Function TAdvTextExtractor.MatchStringArray(Const aTokenSet: Array Of String): Integer;
Begin
Result := High(aTokenSet);
While (Result >= Low(aTokenSet)) And Not MatchString(aTokenSet[Result]) Do
Dec(Result);
End;
Function TAdvTextExtractor.NextCharacter : Char;
var
Buffer: SysUtils.TCharArray;
Begin
If Length(FCache) = 0 Then
Begin
SetLength(Buffer, 1);
if Read(Buffer, 0, 1) = 1 Then
result := Buffer[0]
Else
result := #0;
FCache := Result;
End
Else
Begin
Result := FCache[1];
End;
End;
Function TAdvTextExtractor.ConsumeCharacter : Char;
Begin
Result := NextCharacter;
Delete(FCache, 1, 1);
CacheRemove(Result);
End;
Function TAdvTextExtractor.ConsumeCharacter(Const cToken : Char) : Char;
Function ToCharacter(Const cChar : Char) : String;
Begin
If (cChar >= ' ') And (cChar <= #127) Then
Result := cChar
Else
Result := '$' + inttohex(Word(cChar), 4);
End;
Begin
If Not StringEquals(cToken, NextCharacter) Then
RaiseError('Consume(Char)', StringFormat('Expected token ''%s'' but found token ''%s''', [ToCharacter(cToken), ToCharacter(NextCharacter)]));
Result := ConsumeCharacter;
End;
Function TAdvTextExtractor.ConsumeString(Const sToken : String) : String;
Begin
If Not MatchString(sToken) Then
RaiseError('Consume(String)', StringFormat('Expected token ''%s'' but found token ''%s''', [sToken, Copy(FCache, 1, Length(sToken))]));
Delete(FCache, 1, Length(sToken));
CacheRemove(sToken);
Result := sToken;
End;
Function TAdvTextExtractor.ConsumeCharacterCount(Const iCharacterCount : Integer) : String;
Var
iLoop : Integer;
Begin
SetLength(Result, iCharacterCount);
For iLoop := 1 To iCharacterCount Do
Result[iLoop] := ConsumeCharacter;
End;
Function TAdvTextExtractor.ConsumeUntilCharacterSet(Const aTokenSet: TCharSet): String;
Begin
FBuilder.Clear;
While More And Not CharInSet(NextCharacter, aTokenSet) Do
FBuilder.Append(ConsumeCharacter);
Result := FBuilder.AsString;
End;
Function TAdvTextExtractor.ConsumeUntilString(Const sToken: String): String;
Begin
FBuilder.Clear;
While More And Not MatchString(sToken) Do
FBuilder.Append(ConsumeCharacter);
Result := FBuilder.AsString;
End;
Function TAdvTextExtractor.ConsumeUntilString(Const aStringArray: Array Of String): String;
Begin
FBuilder.Clear;
While More And Not (MatchStringArray(aStringArray) >= 0) Do
FBuilder.Append(ConsumeCharacter);
Result := FBuilder.AsString;
End;
Function TAdvTextExtractor.ConsumeUntilCharacter(Const cToken : Char) : String;
Begin
FBuilder.Clear;
While More And (NextCharacter <> cToken) Do
FBuilder.Append(ConsumeCharacter);
Result := FBuilder.AsString;
End;
Function TAdvTextExtractor.ConsumeRestStream : String;
Begin
FBuilder.Clear;
While More Do
FBuilder.Append(ConsumeCharacter);
Result := FBuilder.AsString;
End;
Function TAdvTextExtractor.ConsumeWhileCharacter(Const cToken : Char) : String;
Begin
FBuilder.Clear;
While More And (NextCharacter = cToken) Do
FBuilder.Append(ConsumeCharacter);
Result := FBuilder.AsString;
End;
Function TAdvTextExtractor.ConsumeWhileCharacterSet(Const aTokenSet : TCharSet) : String;
Begin
FBuilder.Clear;
While More And CharInSet(NextCharacter, aTokenSet) Do
FBuilder.Append(ConsumeCharacter);
Result := FBuilder.AsString;
End;
Function TAdvTextExtractor.ConsumeWhileCharacterSet(Const oCharacterSet: TAdvCharacterSet): String;
Begin
FBuilder.Clear;
While More And oCharacterSet.ContainsValue(NextCharacter) Do
FBuilder.Append(ConsumeCharacter);
Result := FBuilder.AsString;
End;
Function TAdvTextExtractor.CacheLength: Integer;
Begin
Result := Length(FCache);
End;
Function TAdvTextExtractor.StreamPosition: Int64;
Begin
Assert(Invariants('StreamPosition', BaseStream, TAdvAccessStream, 'Stream'));
Result := TAdvAccessStream(BaseStream).Position - CacheLength;
End;
Function TAdvTextExtractor.More : Boolean;
Begin
Result := Not Inherited EndOfStream Or (Length(FCache) > 0);
End;
End.
|
unit expagend;
{$F+,O+,D-}
interface
uses Overlay, expconst, Objects;
const
SizeOfAgenda = 15;
type
AgendaObject = object(TObject)
Stack : array[0..SizeOfAgenda-1] of TupleObject;
TopStack : Integer; { always points at the next insertion point }
NumItems : Integer; { number of items in the agenda }
constructor Init;
destructor Done; virtual;
function Empty: Boolean;
procedure Pop;
procedure Push(Id : String; Val : String);
function GetIdentifier:String;
function GetValue: String;
end; { Agenda }
implementation
constructor AgendaObject.Init;
var
Count : Integer;
begin
TObject.Init;
NumItems := 0;
TopStack := SizeOfAgenda-1;
for Count := 0 to SizeOfAgenda-1 do
Stack[Count].Init;
end;
destructor AgendaObject.Done;
var
Count : Integer;
begin
TObject.Done;
NumItems := 0;
TopStack := SizeOfAgenda-1;
for Count := 0 to SizeOfAgenda-1 do
Stack[Count].Done;
end;
function AgendaObject.Empty: Boolean;
{* Test to see if the agenda is empty *}
begin
if NumItems = 0 then
Empty := True
else
Empty := False;
end; { AgendaEmpty }
procedure AgendaObject.Pop;
{* Remove top item from agenda *}
begin
if ((NumItems > 0) and (NumItems < SizeOfAgenda)) then
begin
Inc(TopStack);
Stack[TopStack].Done;
Dec(NumItems);
end;
end; { Pop }
procedure AgendaObject.Push(Id : String; Val : String);
{* Push given data onto the top of the agenda *}
begin
if NumItems < SizeOfAgenda then
begin
Stack[TopStack].Identifier := Id;
Stack[TopStack].Value := Val;
Dec(TopStack);
Inc(NumItems);
end;
end; { Push }
function AgendaObject.GetIdentifier: String;
{* Return the top identifier without removing it *}
var
Id : String[MaxIdentifierLength];
begin
if ((NumItems > 0) and (NumItems < SizeOfAgenda)) then
Id := Stack[TopStack+1].Identifier;
GetIdentifier := Id;
end; { GetTuple }
function AgendaObject.GetValue: String;
{* Return the top identifier without removing it *}
var
Val : String[MaxValueLength];
begin
if ((NumItems > 0) and (NumItems < SizeOfAgenda)) then
Val := Stack[TopStack+1].Value;
GetValue := Val;
end; { GetTuple }
end. { Agenda } |
unit Scp;
interface
type
HCkTask = Pointer;
HCkScp = Pointer;
HCkSsh = Pointer;
HCkByteData = Pointer;
HCkString = Pointer;
function CkScp_Create: HCkScp; stdcall;
procedure CkScp_Dispose(handle: HCkScp); stdcall;
function CkScp_getAbortCurrent(objHandle: HCkScp): wordbool; stdcall;
procedure CkScp_putAbortCurrent(objHandle: HCkScp; newPropVal: wordbool); stdcall;
procedure CkScp_getDebugLogFilePath(objHandle: HCkScp; outPropVal: HCkString); stdcall;
procedure CkScp_putDebugLogFilePath(objHandle: HCkScp; newPropVal: PWideChar); stdcall;
function CkScp__debugLogFilePath(objHandle: HCkScp): PWideChar; stdcall;
function CkScp_getHeartbeatMs(objHandle: HCkScp): Integer; stdcall;
procedure CkScp_putHeartbeatMs(objHandle: HCkScp; newPropVal: Integer); stdcall;
procedure CkScp_getLastErrorHtml(objHandle: HCkScp; outPropVal: HCkString); stdcall;
function CkScp__lastErrorHtml(objHandle: HCkScp): PWideChar; stdcall;
procedure CkScp_getLastErrorText(objHandle: HCkScp; outPropVal: HCkString); stdcall;
function CkScp__lastErrorText(objHandle: HCkScp): PWideChar; stdcall;
procedure CkScp_getLastErrorXml(objHandle: HCkScp; outPropVal: HCkString); stdcall;
function CkScp__lastErrorXml(objHandle: HCkScp): PWideChar; stdcall;
function CkScp_getLastMethodSuccess(objHandle: HCkScp): wordbool; stdcall;
procedure CkScp_putLastMethodSuccess(objHandle: HCkScp; newPropVal: wordbool); stdcall;
function CkScp_getPercentDoneScale(objHandle: HCkScp): Integer; stdcall;
procedure CkScp_putPercentDoneScale(objHandle: HCkScp; newPropVal: Integer); stdcall;
procedure CkScp_getSyncedFiles(objHandle: HCkScp; outPropVal: HCkString); stdcall;
procedure CkScp_putSyncedFiles(objHandle: HCkScp; newPropVal: PWideChar); stdcall;
function CkScp__syncedFiles(objHandle: HCkScp): PWideChar; stdcall;
procedure CkScp_getSyncMustMatch(objHandle: HCkScp; outPropVal: HCkString); stdcall;
procedure CkScp_putSyncMustMatch(objHandle: HCkScp; newPropVal: PWideChar); stdcall;
function CkScp__syncMustMatch(objHandle: HCkScp): PWideChar; stdcall;
procedure CkScp_getSyncMustMatchDir(objHandle: HCkScp; outPropVal: HCkString); stdcall;
procedure CkScp_putSyncMustMatchDir(objHandle: HCkScp; newPropVal: PWideChar); stdcall;
function CkScp__syncMustMatchDir(objHandle: HCkScp): PWideChar; stdcall;
procedure CkScp_getSyncMustNotMatch(objHandle: HCkScp; outPropVal: HCkString); stdcall;
procedure CkScp_putSyncMustNotMatch(objHandle: HCkScp; newPropVal: PWideChar); stdcall;
function CkScp__syncMustNotMatch(objHandle: HCkScp): PWideChar; stdcall;
procedure CkScp_getSyncMustNotMatchDir(objHandle: HCkScp; outPropVal: HCkString); stdcall;
procedure CkScp_putSyncMustNotMatchDir(objHandle: HCkScp; newPropVal: PWideChar); stdcall;
function CkScp__syncMustNotMatchDir(objHandle: HCkScp): PWideChar; stdcall;
function CkScp_getVerboseLogging(objHandle: HCkScp): wordbool; stdcall;
procedure CkScp_putVerboseLogging(objHandle: HCkScp; newPropVal: wordbool); stdcall;
procedure CkScp_getVersion(objHandle: HCkScp; outPropVal: HCkString); stdcall;
function CkScp__version(objHandle: HCkScp): PWideChar; stdcall;
function CkScp_DownloadBinary(objHandle: HCkScp; remotePath: PWideChar; outData: HCkByteData): wordbool; stdcall;
function CkScp_DownloadBinaryAsync(objHandle: HCkScp; remotePath: PWideChar): HCkTask; stdcall;
function CkScp_DownloadBinaryEncoded(objHandle: HCkScp; remotePath: PWideChar; encoding: PWideChar; outStr: HCkString): wordbool; stdcall;
function CkScp__downloadBinaryEncoded(objHandle: HCkScp; remotePath: PWideChar; encoding: PWideChar): PWideChar; stdcall;
function CkScp_DownloadBinaryEncodedAsync(objHandle: HCkScp; remotePath: PWideChar; encoding: PWideChar): HCkTask; stdcall;
function CkScp_DownloadFile(objHandle: HCkScp; remotePath: PWideChar; localPath: PWideChar): wordbool; stdcall;
function CkScp_DownloadFileAsync(objHandle: HCkScp; remotePath: PWideChar; localPath: PWideChar): HCkTask; stdcall;
function CkScp_DownloadString(objHandle: HCkScp; remotePath: PWideChar; charset: PWideChar; outStr: HCkString): wordbool; stdcall;
function CkScp__downloadString(objHandle: HCkScp; remotePath: PWideChar; charset: PWideChar): PWideChar; stdcall;
function CkScp_DownloadStringAsync(objHandle: HCkScp; remotePath: PWideChar; charset: PWideChar): HCkTask; stdcall;
function CkScp_SaveLastError(objHandle: HCkScp; path: PWideChar): wordbool; stdcall;
function CkScp_SyncTreeDownload(objHandle: HCkScp; remoteRoot: PWideChar; localRoot: PWideChar; mode: Integer; bRecurse: wordbool): wordbool; stdcall;
function CkScp_SyncTreeDownloadAsync(objHandle: HCkScp; remoteRoot: PWideChar; localRoot: PWideChar; mode: Integer; bRecurse: wordbool): HCkTask; stdcall;
function CkScp_SyncTreeUpload(objHandle: HCkScp; localBaseDir: PWideChar; remoteBaseDir: PWideChar; mode: Integer; bRecurse: wordbool): wordbool; stdcall;
function CkScp_SyncTreeUploadAsync(objHandle: HCkScp; localBaseDir: PWideChar; remoteBaseDir: PWideChar; mode: Integer; bRecurse: wordbool): HCkTask; stdcall;
function CkScp_UploadBinary(objHandle: HCkScp; remotePath: PWideChar; binData: HCkByteData): wordbool; stdcall;
function CkScp_UploadBinaryAsync(objHandle: HCkScp; remotePath: PWideChar; binData: HCkByteData): HCkTask; stdcall;
function CkScp_UploadBinaryEncoded(objHandle: HCkScp; remotePath: PWideChar; encodedData: PWideChar; encoding: PWideChar): wordbool; stdcall;
function CkScp_UploadBinaryEncodedAsync(objHandle: HCkScp; remotePath: PWideChar; encodedData: PWideChar; encoding: PWideChar): HCkTask; stdcall;
function CkScp_UploadFile(objHandle: HCkScp; localPath: PWideChar; remotePath: PWideChar): wordbool; stdcall;
function CkScp_UploadFileAsync(objHandle: HCkScp; localPath: PWideChar; remotePath: PWideChar): HCkTask; stdcall;
function CkScp_UploadString(objHandle: HCkScp; remotePath: PWideChar; textData: PWideChar; charset: PWideChar): wordbool; stdcall;
function CkScp_UploadStringAsync(objHandle: HCkScp; remotePath: PWideChar; textData: PWideChar; charset: PWideChar): HCkTask; stdcall;
function CkScp_UseSsh(objHandle: HCkScp; sshConnection: HCkSsh): wordbool; stdcall;
implementation
{$Include chilkatDllPath.inc}
function CkScp_Create; external DLLName;
procedure CkScp_Dispose; external DLLName;
function CkScp_getAbortCurrent; external DLLName;
procedure CkScp_putAbortCurrent; external DLLName;
procedure CkScp_getDebugLogFilePath; external DLLName;
procedure CkScp_putDebugLogFilePath; external DLLName;
function CkScp__debugLogFilePath; external DLLName;
function CkScp_getHeartbeatMs; external DLLName;
procedure CkScp_putHeartbeatMs; external DLLName;
procedure CkScp_getLastErrorHtml; external DLLName;
function CkScp__lastErrorHtml; external DLLName;
procedure CkScp_getLastErrorText; external DLLName;
function CkScp__lastErrorText; external DLLName;
procedure CkScp_getLastErrorXml; external DLLName;
function CkScp__lastErrorXml; external DLLName;
function CkScp_getLastMethodSuccess; external DLLName;
procedure CkScp_putLastMethodSuccess; external DLLName;
function CkScp_getPercentDoneScale; external DLLName;
procedure CkScp_putPercentDoneScale; external DLLName;
procedure CkScp_getSyncedFiles; external DLLName;
procedure CkScp_putSyncedFiles; external DLLName;
function CkScp__syncedFiles; external DLLName;
procedure CkScp_getSyncMustMatch; external DLLName;
procedure CkScp_putSyncMustMatch; external DLLName;
function CkScp__syncMustMatch; external DLLName;
procedure CkScp_getSyncMustMatchDir; external DLLName;
procedure CkScp_putSyncMustMatchDir; external DLLName;
function CkScp__syncMustMatchDir; external DLLName;
procedure CkScp_getSyncMustNotMatch; external DLLName;
procedure CkScp_putSyncMustNotMatch; external DLLName;
function CkScp__syncMustNotMatch; external DLLName;
procedure CkScp_getSyncMustNotMatchDir; external DLLName;
procedure CkScp_putSyncMustNotMatchDir; external DLLName;
function CkScp__syncMustNotMatchDir; external DLLName;
function CkScp_getVerboseLogging; external DLLName;
procedure CkScp_putVerboseLogging; external DLLName;
procedure CkScp_getVersion; external DLLName;
function CkScp__version; external DLLName;
function CkScp_DownloadBinary; external DLLName;
function CkScp_DownloadBinaryAsync; external DLLName;
function CkScp_DownloadBinaryEncoded; external DLLName;
function CkScp__downloadBinaryEncoded; external DLLName;
function CkScp_DownloadBinaryEncodedAsync; external DLLName;
function CkScp_DownloadFile; external DLLName;
function CkScp_DownloadFileAsync; external DLLName;
function CkScp_DownloadString; external DLLName;
function CkScp__downloadString; external DLLName;
function CkScp_DownloadStringAsync; external DLLName;
function CkScp_SaveLastError; external DLLName;
function CkScp_SyncTreeDownload; external DLLName;
function CkScp_SyncTreeDownloadAsync; external DLLName;
function CkScp_SyncTreeUpload; external DLLName;
function CkScp_SyncTreeUploadAsync; external DLLName;
function CkScp_UploadBinary; external DLLName;
function CkScp_UploadBinaryAsync; external DLLName;
function CkScp_UploadBinaryEncoded; external DLLName;
function CkScp_UploadBinaryEncodedAsync; external DLLName;
function CkScp_UploadFile; external DLLName;
function CkScp_UploadFileAsync; external DLLName;
function CkScp_UploadString; external DLLName;
function CkScp_UploadStringAsync; external DLLName;
function CkScp_UseSsh; external DLLName;
end.
|
unit InfraCommonIntf;
interface
{$I InfraCommon.Inc}
uses
Classes,
InfraBase,
InfraConsts;
type
TRetentionPolice = (rpNone, rpClass, rpInstance);
IBaseElement = interface;
IInfraEventService = interface;
IInfraReferenceService = interface;
IInfraPublisher = interface;
IInfraEvent = interface;
IInfraIterator = interface;
ITypeService = interface;
IClassInfo = interface;
IClassInfoList = interface;
IRelationInfo = interface;
// Application Context
IApplicationContext = interface(IInterface)
['{E0C9C9AC-1555-4A14-B576-AEDB09A170AE}']
function GetElement: IBaseElement;
function GetEventService: IInfraEventService;
function GetReferenceService: IInfraReferenceService;
function GetTypeService: ITypeService;
procedure ShutDown;
property Element: IBaseElement read GetElement;
property EventService: IInfraEventService read GetEventService;
property ReferenceService: IInfraReferenceService read GetReferenceService;
property TypeService: ITypeService read GetTypeService;
end;
// Interface Injection
IInjectedItem = interface(IInterface)
['{BABD476C-9F13-45E0-9246-8694A02E0DDA}']
function GetID: TGUID;
function GetInjectedInterface: IInterface;
function GetIsAnnotation: boolean;
procedure SetID(const Value: TGUID);
procedure SetInjectedInterface(const Value: IInterface);
procedure SetIsAnnotation(Value: boolean);
property ID: TGUID read GetID write SetID;
property InjectedInterface: IInterface read GetInjectedInterface
write SetInjectedInterface;
property IsAnnotation: boolean read GetIsAnnotation write SetIsAnnotation;
end;
IAnnotationsIterator = interface(IInterface)
['{927DF9B4-B76D-436C-8108-1C33DE0CC459}']
function CurrentItem: IInjectedItem;
procedure First;
function IsDone: Boolean;
procedure Next;
end;
IInjectedList = interface(IInterface)
['{489622C1-09B1-4138-BBCF-E7428604ADEC}']
function Add(const ID: TGUID; const pObject: IInterface): integer;
function GetCount: Integer;
function GetItem(Index: Integer): IInjectedItem;
function IndexByGUID(const Item: TGUID): Integer;
function NewAnnotationIterator: IAnnotationsIterator;
procedure Clear;
property Count: Integer read GetCount;
property Item[Index: Integer]: IInjectedItem read GetItem; default;
end;
IBaseElement = interface(IInterface)
['{B70BB062-6298-4EF7-9CCB-9BFF732EC0CD}']
{$IFDEF SEE_REFCOUNT}
function GetRefCount: integer;
{$ENDIF}
function Inject(const pID: TGUID; const pItem: IInterface): IInjectedItem;
function GetInjectedList: IInjectedList;
property InjectedList: IInjectedList read GetInjectedList;
end;
IElement = interface(IBaseElement)
['{82045917-1413-4752-ADFB-16A8B26D93B8}']
function GetPublisher: IInfraPublisher;
function GetTypeInfo: IClassInfo;
procedure SetTypeInfo(const Value: IClassInfo);
property Publisher: IInfraPublisher read GetPublisher;
property TypeInfo: IClassInfo read GetTypeInfo write SetTypeInfo;
end;
// Instance
IInfraInstance = interface(IInterface)
['{95987A62-A416-438F-9A58-88F8BB6D5446}']
function GetInstance: TObject;
end;
// Reference
IInfraReferenceKeeper = interface(IInterface)
['{CC81AD6A-B14D-4379-97E4-EA945AB700B1}']
procedure SetReference(var Ref: IInterface; const Value: IInterface);
end;
IInfraReferenceService = interface(IInterface)
['{54987987-573B-4379-B15F-031FCE125412}']
procedure NotifyDestruction(const Sender: IInterface);
procedure SetReference(const Sender: IInterface; var Ref: IInterface;
const Value: IInterface);
end;
IReflect = interface
['{00FF9AF3-26A8-45EB-9103-4E3973F5AC61}']
end;
// Notify
TSubscriberInform = procedure (const Event: IInfraEvent) of object;
TSubscriberFilter = function (const Event: IInfraEvent): Boolean of object;
IInfraPublisher = interface(IElement)
['{8AAAA64F-D54E-4ADC-83B2-F40C25A35605}']
function HasSubscribers(const EventType: TGUID): Boolean;
procedure Publish(const Event: IInfraEvent);
end;
IInfraPublisherList = interface(IBaseElement)
['{3744A0C5-DB23-400F-9861-A075BF49DF21}']
function Add(const Item: IInfraPublisher): Integer;
function First: IInfraPublisher;
function GetCount: Integer;
function GetItem(Index: Integer): IInfraPublisher;
function Last: IInfraPublisher;
procedure SetItem(Index: Integer; const Value: IInfraPublisher);
property Count: Integer read GetCount;
property Items[Index: Integer]: IInfraPublisher read GetItem
write SetItem; default;
end;
ISubscriber = interface(IInterface)
['{ABC1C548-8467-470A-8E1E-9C6ACCCDBE81}']
procedure Inform(const Event: IInfraEvent);
end;
IInfraFilter = interface(IInterface)
['{82CB0372-0BC8-4204-95B3-ED83E88E82F9}']
function Apply(const Event: IInfraEvent): Boolean;
end;
ISubscription = interface(IBaseElement)
['{00154BC2-A64D-45B4-9C3E-4915C39B565B}']
function GetSubscriber: ISubscriber;
procedure Publish(const Event: IInfraEvent);
property Subscriber: ISubscriber read GetSubscriber;
end;
ICallBackSubscription = interface(ISubscription)
['{C1111067-B417-407B-BA25-E01D6F7EC88E}']
function GetFilter: TSubscriberFilter;
function GetInform: TSubscriberInform;
property Filter: TSubscriberFilter read GetFilter;
property Inform: TSubscriberInform read GetInform;
end;
IClassicSubscription = interface(ISubscription)
['{02269AA0-A39B-4C96-B057-7482EE4F3443}']
function GetFilter: IInfraFilter;
function GetSubscriber: ISubscriber;
property Filter: IInfraFilter read GetFilter;
property Subscriber: ISubscriber read GetSubscriber;
end;
ISubscriptionList = interface(IBaseElement)
['{CAFB19B6-91E5-45D7-BCE9-709794C1840E}']
function Add(const Item: ISubscription): Integer;
function First: ISubscription;
function GetItem(AIndex: Integer): ISubscription;
function GetCount: Integer;
function NewIterator: IInfraIterator;
function IndexOf(const Item: ISubscription): Integer;
function Last: ISubscription;
function Remove(const Item: ISubscription): Integer;
procedure Clear;
procedure Delete(Index: Integer);
procedure SetItem(Index: Integer; const Value: ISubscription);
property Count: Integer read GetCount;
property Items[Index: Integer]: ISubscription read GetItem
write SetItem; default;
end;
IInfraEventType = interface(IInterface)
['{C41D07B2-72D7-49CD-8F0F-1B4C52F30935}']
end;
IInfraEvent = interface(IInterface)
['{D2460D4E-8B93-499A-B106-BADCFBC83351}']
function GetSource: IElement;
procedure SetSource(const Value: IElement);
property Source: IElement read GetSource write SetSource;
end;
IInfraEventServiceItem = interface(IBaseElement)
['{54D2EDC8-299F-4055-9438-4B32CBF51D20}']
function GetEventType: TGUID;
function GetPublishers: IInfraPublisherList;
function GetSubscriptions: ISubscriptionList;
property EventType: TGUID read GetEventType;
property Publishers: IInfraPublisherList read GetPublishers;
property Subscriptions: ISubscriptionList read GetSubscriptions;
end;
IInfraEventServiceItems = interface(IInterface)
['{CA4A565C-8ABC-4567-9281-1F6F7E5F93AC}']
function Add(ID: TGUID; Item: IInfraEventServiceItem): TGUID;
function First: IInfraEventServiceItem;
function GetCount: Integer;
function GetItem(Index: TGUID): IInfraEventServiceItem;
function IndexOf(Item: IInfraEventServiceItem): TGUID;
function IndexOfPosition(Index: Integer): TGUID;
function Last: IInfraEventServiceItem;
function Remove(Item: IInfraEventServiceItem): TGUID;
function ValueOfPosition(Index: Integer): IInfraEventServiceItem;
procedure Clear;
procedure Delete(Index: TGUID);
procedure SetItem(Index: TGUID; Item: IInfraEventServiceItem);
property Count: Integer read GetCount;
property Items[Index: TGUID]: IInfraEventServiceItem read GetItem
write SetItem; default;
end;
IInfraEventService = interface(IInterface)
['{553AED4B-820F-4CA5-8732-D30AEFD96751}']
function GetItems: IInfraEventServiceItems;
function GetPublishersForSubscriberIterator(
const Subscriber: ISubscriber): IInfraIterator;
function HasSubscribers(const EventType: TGUID): Boolean;
procedure Publish(const Event: IInfraEvent);
procedure Subscribe(const EventType: TGUID; const Subscriber: ISubscriber;
const Filter: IInfraFilter); overload;
procedure Subscribe(const EventType: TGUID;
const Subscriber: ISubscriber; const Inform: TSubscriberInform;
const PropertyName: string = '';
const Filter: TSubscriberFilter = nil); overload;
procedure UnSubscribe(const EventType: TGUID;
const Subscriber: ISubscriber);
procedure UnSubscribeAll(const Subscriber: ISubscriber);
property Items: IInfraEventServiceItems read GetItems;
end;
// Metadata
TMemberType = (mtConstructor, mtEvent, mtMethod, mtProperty);
TMethodType = (mtJustMethods, mtJustConstructors, mtBoth);
TMemberTypes = Set of TMemberType;
TRelationKind = (rkAssociation, rkAgregation, rkComposition);
TParameterOption = (poConst, poVar, poReturn);
TParameterOptions = set of TParameterOption;
TCallingConvention = (ccRegister, ccPascal, ccCdecl, ccStdcall, ccSafecall);
IMemberInfo = interface;
IMethodInfo = interface;
IPropertyInfo = interface;
IParameterInfo = interface;
IParameterInfoList = interface;
IClassInfoList = interface(IBaseElement)
['{A9E10732-7BED-4FC1-BCD2-556721330485}']
function Add(const Item: IClassInfo): Integer;
function First: IClassInfo;
function GetCount: Integer;
function GetItem(Index: Integer): IClassInfo;
function IndexOf(const Item: IClassInfo): Integer;
function Last: IClassInfo;
function ByGUID(DataType: TGUID): IClassInfo;
function ByClass(ClassType: TInfraBaseObjectClass): IClassInfo;
function ByName(const pName: string): IClassInfo;
procedure Clear;
procedure Delete(Index: Integer);
procedure Insert(Index: Integer; const Item: IClassInfo);
procedure SetItem(Index: Integer; const TypeInfo: IClassInfo);
property Count: Integer read GetCount;
property Items[Index: Integer]: IClassInfo read GetItem
write SetItem; default;
end;
IMemberInfoIterator = interface(IInterface)
['{2365C35D-6226-4BF8-85C5-080F9C0DF377}']
function CurrentItem: IMemberInfo;
procedure First;
function IsDone: Boolean;
procedure Next;
end;
IPropertyInfoIterator = interface(IInterface)
['{5C012700-E499-49AB-98E1-D95E6C85C173}']
function CurrentItem: IPropertyInfo;
procedure First;
function IsDone: Boolean;
procedure Next;
end;
IMethodInfoIterator = interface(IInterface)
['{96F7C367-FB67-416E-90A6-E72EC7D87B05}']
function CurrentItem: IMethodInfo;
function IsDone: Boolean;
procedure First;
procedure Next;
end;
IMemberInfoList = interface(IBaseElement)
['{A8439100-8F79-4693-A30C-04823B557769}']
function Add(const Item: IMemberInfo): Integer;
function First: IMemberInfo;
function GetCount: Integer;
function GetItem(Index: Integer): IMemberInfo;
function IndexOf(const Item: IMemberInfo): Integer;
function Last: IMemberInfo;
procedure Clear;
procedure Delete(Index: Integer);
function NewMemberInfoIterator(
MemberTypes: TMemberTypes): IMemberInfoIterator;
function NewMethodInfoIterator(MethodType: TMethodType): IMethodInfoIterator;
function NewPropertyInfoIterator: IPropertyInfoIterator;
procedure Insert(Index: Integer; const Item: IMemberInfo);
procedure SetItem(Index: Integer; const TypeInfo: IMemberInfo);
property Count: Integer read GetCount;
property Items[Index: Integer]: IMemberInfo read GetItem
write SetItem; default;
end;
IMethodInfoList = interface(IBaseElement)
['{EA1C173B-0079-4F53-819E-851A24C3798E}']
function Add(const Item: IMethodInfo): Integer;
function First: IMethodInfo;
function GetCount: Integer;
function GetItem(Index: Integer): IMethodInfo;
function IndexOf(const Item: IMethodInfo): Integer;
function Last: IMethodInfo;
procedure Clear;
procedure Delete(Index: Integer);
procedure Insert(Index: Integer; const Item: IMethodInfo);
procedure SetItem(Index: Integer; const TypeInfo: IMethodInfo);
property Count: Integer read GetCount;
property Items[Index: Integer]: IMethodInfo read GetItem
write SetItem; default;
end;
IParameterInfoList = interface(IBaseElement)
['{E587DA28-2D36-4C37-AAA3-7817B9F8095E}']
function Add(const Item: IParameterInfo): Integer;
function First: IParameterInfo;
function GetCount: Integer;
function GetItem(Index: Integer): IParameterInfo;
function IndexOf(const Item: IParameterInfo): Integer;
function Last: IParameterInfo;
procedure Clear;
procedure Delete(Index: Integer);
procedure Insert(Index: Integer; const Item: IParameterInfo);
procedure SetItem(Index: Integer; const TypeInfo: IParameterInfo);
property Count: Integer read GetCount;
property Items[Index: Integer]: IParameterInfo read GetItem
write SetItem; default;
end;
IRelationInfoList = interface(IBaseElement)
['{4C0735B1-779C-4E57-8799-89FC9727ED78}']
function Add(const Item: IRelationInfo): Integer;
function First: IRelationInfo;
function GetCount: Integer;
function GetItem(Index: Integer): IRelationInfo;
function IndexOf(const Item: IRelationInfo): Integer;
function Last: IRelationInfo;
procedure Clear;
procedure Delete(Index: Integer);
procedure Insert(Index: Integer; const Item: IRelationInfo);
procedure SetItem(Index: Integer; const TypeInfo: IRelationInfo);
property Count: Integer read GetCount;
property Items[Index: Integer]: IRelationInfo read GetItem
write SetItem; default;
end;
IReflectElement = interface(IElement)
['{CF16B242-DA09-482A-9DB7-DB2DD7330A94}']
function Annotate(const pID: TGUID): IInterface; overload;
function Annotate(const pClassInfo: IClassInfo): IInterface; overload;
function isAnnotationPresent(const pID: TGUID): Boolean;
function GetAnnotation(const pID: TGUID): IInterface;
function GetAnnotations: IAnnotationsIterator;
end;
IClassInfo = interface(IReflectElement)
['{FCD45266-7AE7-4EB3-9F51-4CD22F3C7B4B}']
function AddPropertyInfo(const pName: string; const pType: IClassInfo;
pGetterMethod: Pointer; pSetterMethod: Pointer = nil): IPropertyInfo;
function AddMethodInfo(const pName: string;
const pParametersInfo: IParameterInfoList; pMethod: Pointer;
const pReturnInfo: IClassInfo = nil; pIsConstructor: boolean = False;
pCallConvention: TCallingConvention = ccRegister): IMethodInfo;
function AddConstructorInfo(const pName: string;
const pParametersInfo: IParameterInfoList; pMethod: Pointer;
pCallConvention: TCallingConvention = ccRegister): IMethodInfo;
function FindMembers(MemberTypes: TMemberTypes): IMemberInfoIterator;
function GetClassFamily: TGUID;
function GetConstructors: IMethodInfoIterator; overload;
function GetFullName: string;
function GetTypeID: TGUID;
function GetImplClass: TInfraBaseObjectClass;
function GetMemberInfo(const pName: String): IMemberInfo;
function GetMembers: IMemberInfoIterator;
function GetMethodInfo(const pName: String): IMethodInfo;
function GetMethods: IMethodInfoIterator;
function GetAllMethods: IMethodInfoIterator;
function GetName: string;
function GetOwner: IClassInfo;
function GetProperties: IPropertyInfoIterator;
function GetProperty(const Obj: IElement; const pName: String;
const pClassInfo: IClassInfo = nil): IInterface;
function GetPropertyInfo(const pName: String;
ThrowException: Boolean = False): IPropertyInfo;
function GetSuperClass: IClassInfo;
function GetRetentionPolice: TRetentionPolice;
function IsSubClassOf(const Value: IClassInfo): Boolean;
function GetIsAnnotation: Boolean;
procedure SetRetentionPolice(const Value: TRetentionPolice);
procedure SetClassFamily(const Family: TGUID);
procedure SetTypeID(const Value: TGUID);
procedure SetImplClass(Value: TInfraBaseObjectClass);
procedure SetName(const Value: string);
procedure SetOwner(const Value: IClassInfo);
procedure SetRelation(const pPropertyName: string;
pSrcMultLower, pSrcMultUpper,
pTgtMultLower, pTgtMultUpper: TRelationLimit;
const pTargetInfo: IClassInfo;
const pListInfo: IClassInfo = nil); overload;
procedure SetRelation(const pPropertyInfo: IPropertyInfo;
pSrcMultLower, pSrcMultUpper,
pTgtMultLower, pTgtMultUpper: TRelationLimit;
const pTargetInfo: IClassInfo;
const pListInfo: IClassInfo = nil); overload;
procedure SetSuperClass(const Value: IClassInfo);
property FamilyID: TGUID read GetClassFamily write SetClassFamily;
property FullName: string read GetFullName;
property TypeID: TGUID read GetTypeID write SetTypeID;
property ImplClass: TInfraBaseObjectClass read GetImplClass
write SetImplClass;
property Name: string read GetName write SetName;
property Owner: IClassInfo read GetOwner write SetOwner;
property SuperClass: IClassInfo read GetSuperClass write SetSuperClass;
property RetentionPolice: TRetentionPolice read GetRetentionPolice
write SetRetentionPolice;
property IsAnnotation: Boolean read GetIsAnnotation;
end;
IMemberInfo = interface(IReflectElement)
['{879C1FB0-9FBF-4CAB-A4AC-E3A769C50304}']
function GetDeclaringType: IClassInfo;
function GetFullName: string;
function GetMemberType: TMemberType;
function GetName: string;
procedure SetDeclaringType(const Value: IClassInfo);
procedure SetMemberType(Value: TMemberType);
procedure SetName(const Value: string);
property DeclaringType: IClassInfo read GetDeclaringType write
SetDeclaringType;
property FullName: string read GetFullName;
property MemberType: TMemberType read GetMemberType write SetMemberType;
property Name: string read GetName write SetName;
end;
IPropertyInfo = interface(IMemberInfo)
['{D5063A5A-978F-475B-8CC1-2177F41DB28D}']
function GetGetterInfo: IMethodInfo;
function GetSetterInfo: IMethodInfo;
function GetValue(const pObject: IInterface): IInterface;
procedure SetValue(const pObject, pValue: IInterface);
function GetTypeInfo: IClassInfo;
end;
IMethodInfo = interface(IMemberInfo)
['{F91AA616-6E05-4A0B-AC02-EFE207B32243}']
function AddParam(const pName: string;
pParameterType: IClassInfo; pOptions: TParameterOptions = [poConst];
const pDefaultValue: IInterface = nil): IParameterInfo;
function GetCallingConvention: TCallingConvention;
function GetIsConstructor: Boolean;
function GetIsFunction: Boolean;
function GetMethodPointer: Pointer;
function GetParameters: IParameterInfoList;
function GetReturnType: IClassInfo;
function Invoke(const pObj: IInfraInstance;
const pParameters: IInterfaceList): IInterface; overload;
function Invoke(pObj: TObject;
const pParameters: IInterfaceList): IInterface; overload;
property IsConstructor: Boolean read GetIsConstructor;
property IsFunction: Boolean read GetIsFunction;
property MethodPointer: Pointer read GetMethodPointer;
property Parameters: IParameterInfoList read GetParameters;
property ReturnType: IClassInfo read GetReturnType;
property CallingConvention: TCallingConvention read GetCallingConvention;
end;
IConstructorInfo = interface(IMethodInfo)
['{E3A8CED1-0138-4CAA-BD83-75266DE95C8A}']
end;
IParameterInfo = interface(IBaseElement)
['{13334830-727F-4BB4-85DA-54EFE7673508}']
function GetDefaultValue: IInterface;
function GetIsOptional: boolean;
function GetIsConst: boolean;
function GetIsVar: boolean;
function GetIsReturn: boolean;
function GetName: string;
function GetParameterType: IClassInfo;
function GetPosition: integer;
property DefaultValue: IInterface read GetDefaultValue;
property IsConst: boolean read GetIsConst;
property IsOptional: boolean read GetIsOptional;
property IsReturn: boolean read GetIsReturn;
property IsVar: boolean read GetIsVar;
property Name: string read GetName;
property ParameterType: IClassInfo read GetParameterType;
property Position: integer read GetPosition;
end;
IMultiplicityInfo = interface(IBaseElement)
['{8E7BD210-2649-4F16-B19A-BEFD4CF2BC9F}']
function GetLower: TRelationLimit;
function GetUpper: TRelationLimit;
procedure SetLower(Value: TRelationLimit);
procedure SetUpper(Value: TRelationLimit);
property Lower: TRelationLimit read GetLower write SetLower;
property Upper: TRelationLimit read GetUpper write SetUpper;
end;
IRelationEndInfo = interface(IBaseElement)
['{F10A3702-1303-4FB1-B9F4-AB504866C1C5}']
function GetPropertyInfo: IPropertyInfo;
function GetMultiplicity: IMultiplicityInfo;
function GetOtherEnd: IRelationEndInfo;
procedure SetPropertyInfo(const Value: IPropertyInfo);
property PropertyInfo: IPropertyInfo read GetPropertyInfo
write SetPropertyInfo;
property Multiplicity: IMultiplicityInfo read GetMultiplicity;
property OtherEnd: IRelationEndInfo read GetOtherEnd;
end;
IRelationInfo = interface(IBaseElement)
['{6249107B-0C3F-4246-87C0-C9D92E2106F6}']
function GetDestination: IRelationEndInfo;
function GetContainerInfo: IClassInfo;
function GetSource: IRelationEndInfo;
function GetRelationKind(const Source: IRelationEndInfo): TRelationKind;
function OtherEnd(const RelationEnd: IRelationEndInfo): IRelationEndInfo;
procedure SetContainerInfo(const Value: IClassInfo);
property Destination: IRelationEndInfo read GetDestination;
property ContainerInfo: IClassInfo read GetContainerInfo
write SetContainerInfo;
property Source: IRelationEndInfo read GetSource;
end;
IClassInfoIterator = interface(IInterface)
['{F252D2F0-A40A-4F99-931F-3FD1262FAF67}']
function CurrentItem: IClassInfo; overload;
procedure First;
function IsDone: Boolean;
procedure Next;
end;
IRelationInfoIterator = interface(IInterface)
['{110E3E80-B9FB-479C-A68C-5A9AFA7E54FE}']
function CurrentItem: IRelationInfo;
procedure First;
function IsDone: Boolean;
procedure Next;
end;
ITypeService = interface(IInterface)
['{93190314-B32A-4C57-B28E-478C99DEE0BA}']
function CreateInstance(ClassID: TGUID): IElement; overload;
function CreateInstance(const ClassInfo: IClassInfo): IElement; overload;
function AddAnnotation(const pTypeID: TGUID;
const pTypeName: string; pClassImplementing: TInfraBaseObjectClass;
const pFamilyID: TGUID; const pSuperClassInfo: IClassInfo = nil;
pRetention: TRetentionPolice = rpClass): IClassInfo;
function AddType(const pTypeID: TGUID; const pTypeName: string;
pClassImplementing: TInfraBaseObjectClass; const pFamilyID: TGUID;
const pSuperClassInfo: IClassInfo = nil): IClassInfo;
function GetRelations: IRelationInfoList;
function NewClassInfoIterator: IClassInfoIterator;
function NewRelationsIterator(
const TypeInfo: IClassInfo): IRelationInfoIterator; overload;
function NewRelationsIterator(
const pPropertyInfo: IPropertyInfo): IRelationInfoIterator; overload;
function GetTypes: IClassInfoList;
function GetType(TypeID: TGUID;
ThrowException: Boolean = False): IClassInfo; overload;
function GetType(pClass: TInfraBaseObjectClass;
ThrowException: Boolean = False): IClassInfo; overload;
function GetType(const TypeName: String;
ThrowException: Boolean = False): IClassInfo; overload;
procedure AddRelation(const pPropertyInfo: IPropertyInfo;
pSourceLower, pSourceUpper, pTargetLower, pTargetUpper: TRelationLimit;
const pTarget: IClassInfo;
const pListInfo: IClassInfo = nil); overload;
property Relations: IRelationInfoList read GetRelations;
property Types: IClassInfoList read GetTypes;
end;
// Iterator
IInfraIterator = interface(IInterface)
['{6DC5C8D0-643A-4926-8AC8-0814D36D8566}']
function CurrentItem: IInterface;
procedure First;
function IsDone: Boolean;
procedure Next;
end;
// Basic List
IInfraCustomList = interface(IInterfaceList)
['{C3677798-1424-465F-BC99-EA58AD9A6E72}']
function NewIterator: IInfraIterator;
end;
procedure RegisterApplicationContext(const Context: IApplicationContext);
function ApplicationContext: IApplicationContext;
function EventService: IInfraEventService;
function ReferenceService: IInfraReferenceService;
function TypeService: ITypeService;
const
mtAll = [mtConstructor..mtProperty];
implementation
var
_ApplicationContext: IApplicationContext = nil;
procedure RegisterApplicationContext(const Context: IApplicationContext);
begin
_ApplicationContext := Context;
end;
function ApplicationContext: IApplicationContext;
begin
result := _ApplicationContext;
end;
function EventService: IInfraEventService;
begin
result := ApplicationContext.EventService;
end;
function ReferenceService: IInfraReferenceService;
begin
result := ApplicationContext.ReferenceService;
end;
function TypeService: ITypeService;
begin
result := ApplicationContext.TypeService;
end;
initialization
finalization
if Assigned(_ApplicationContext) then
_ApplicationContext.ShutDown;
end.
|
unit uApache;
interface
uses GnuGettext, uBaseModule, SysUtils, Classes, Windows, ExtCtrls, StdCtrls, Buttons, uNetstatTable, uTools, uProcesses, Messages, uServices;
type
tApacheLogType = (altAccess, altError);
tApache = class(tBaseModule)
OldPIDs, OldPorts: string;
OldPIDCount: integer;
GlobalStatus: string;
procedure ServiceInstall; override;
procedure ServiceUnInstall; override;
procedure Start; override;
procedure Stop; override;
procedure Admin; override;
procedure UpdateStatus; override;
procedure CheckIsService; reintroduce;
procedure EditConfig(ConfigFile: string); reintroduce;
procedure ShowLogs(LogType: tApacheLogType); reintroduce;
procedure AddLog(Log: string; LogType: tLogType = ltDefault); reintroduce;
constructor Create(pbbService: TBitBtn; pStatusPanel: tPanel; pPIDLabel, pPortLabel: tLabel; pStartStopButton, pAdminButton: TBitBtn);
destructor Destroy; override;
end;
implementation
uses uMain;
const
// cServiceName = 'Apache2.2';
cModuleName = 'Apache';
{ tApache }
procedure tApache.AddLog(Log: string; LogType: tLogType = ltDefault);
begin
inherited AddLog(cModuleName, Log, LogType);
end;
procedure tApache.Admin;
var
App, Param: string;
begin
inherited;
if Config.ServicePorts.Apache = 80 then
Param := 'http://localhost/'
else
Param := 'http://localhost:' + IntToStr(Config.ServicePorts.Apache) + '/';
if Config.BrowserApp <> '' then
begin
App := Config.BrowserApp;
ExecuteFile(App, Param, '', SW_SHOW);
AddLog(Format(_('Executing "%s" "%s"'), [App, Param]), ltDebug);
end
else
begin
ExecuteFile(Param, '', '', SW_SHOW);
AddLog(Format(_('Executing "%s"'), [Param]), ltDebug);
end;
end;
procedure tApache.CheckIsService;
var
s: string;
path: string;
begin
inherited CheckIsService(RemoveWhiteSpace(Config.ServiceNames.Apache));
if isService then
begin
s := _('Service installed');
path:=GetServicePath(RemoveWhiteSpace(Config.ServiceNames.Apache));
end
else
s := _('Service not installed');
AddLog(Format(_('Checking for service (name="%s"): %s'), [RemoveWhiteSpace(Config.ServiceNames.Apache), s]), ltDebug);
if (path<>'') then
begin
if (Pos(LowerCase(basedir + 'apache\bin\' + Config.BinaryNames.Apache), LowerCase(path))<>0) then
AddLog(Format(_('Service Path: %s'), [path]), ltDebug)
else
begin
pStatus.Color := cErrorColor;
AddLog(_('Apache Service detected with wrong path'), ltError);
AddLog(_('Change XAMPP Apache settings or'), ltError);
AddLog(_('Uninstall/disable the other service manually first'), ltError);
AddLog(Format(_('Found Path: %s'), [Path]), ltError);
AddLog(Format(_('Expected Path: "%sapache\bin\%s" -k runservice'), [basedir, Config.BinaryNames.Apache]), ltError);
end
end
else
AddLog(_('Service Path: Service Not Installed'), ltDebug);
end;
constructor tApache.Create;
var
PortBlocker: string;
ServerApp, ReqTool: string;
p: integer;
Ports: array [0 .. 1] of integer;
path: string;
// =(Config.ServicePorts.Apache,Config.ServicePorts.ApacheSSL);
begin
inherited;
Ports[0] := Config.ServicePorts.Apache;
Ports[1] := Config.ServicePorts.ApacheSSL;
ModuleName := cModuleName;
OldPIDCount := 0;
GlobalStatus := 'starting';
AddLog(_('Initializing module...'), ltDebug);
ServerApp := basedir + 'apache\bin\' + Config.BinaryNames.Apache;
ReqTool := basedir + 'apache\bin\pv.exe';
AddLog(_('Checking for module existence...'), ltDebug);
if not FileExists(ServerApp) then
begin
pStatus.Color := cErrorColor;
AddLog(_('Problem detected: Apache Not Found!'), ltError);
AddLog(_('Disabling Apache buttons'), ltError);
AddLog(_('Run this program from your XAMPP root directory!'), ltError);
bAdmin.Enabled := False;
bbService.Enabled := False;
bStartStop.Enabled := False;
end;
if not Config.EnableServices.Apache then
begin
AddLog(_('Apache Service is disabled.'), ltDebug);
fmain.bApacheService.Enabled := false;
end;
AddLog(_('Checking for required tools...'), ltDebug);
// if not FileExists(ReqTool) then
// begin
// AddLog(_('Possible problem detected: Required Tool pv.exe Not Found!'), ltError);
// end;
CheckIsService;
path:=GetServicePath(RemoveWhiteSpace(Config.ServiceNames.Apache));
if Config.EnableChecks.CheckDefaultPorts then
begin
AddLog(_('Checking default ports...'), ltDebug);
for p := Low(Ports) to High(Ports) do
begin
PortBlocker := NetStatTable.isPortInUse(Ports[p]);
if (PortBlocker <> '') then
begin
//if (LowerCase(PortBlocker) = LowerCase(ServerApp)) then
AddLog(Format(_('Portblocker Detected: %s'), [PortBlocker]), ltDebug);
AddLog(Format(_('Checking for App: %s'), [ServerApp]), ltDebug);
if isservice then
AddLog(Format(_('Checking for Service: %s'), [path]), ltDebug);
if (pos(LowerCase(ServerApp), LowerCase(PortBlocker))<>0) then
begin
// AddLog(Format(_('"%s" seems to be running on port %d?'),[ServerApp,Ports[p]]),ltError);
AddLog(Format(_('XAMPP Apache is already running on port %d'), [Ports[p]]), ltInfo);
end
else if (pos(LowerCase(PortBlocker), LowerCase(path))<>0) and (isService = True) then
begin
AddLog(Format(_('XAMPP Apache Service is already running on port %d'), [Ports[p]]), ltInfo);
end
else
begin
pStatus.Color := cErrorColor;
AddLog(_('Problem detected!'), ltError);
AddLog(Format(_('Port %d in use by "%s"!'), [Ports[p], PortBlocker]), ltError);
AddLog(_('Apache WILL NOT start without the configured ports free!'), ltError);
AddLog(_('You need to uninstall/disable/reconfigure the blocking application'), ltError);
AddLog(_('or reconfigure Apache to listen on a different port'), ltError);
end;
end;
end;
end;
end;
destructor tApache.Destroy;
begin
inherited;
end;
procedure tApache.EditConfig(ConfigFile: string);
var
App, Param: string;
begin
App := Config.EditorApp;
Param := basedir + ConfigFile;
AddLog(Format(_('Executing %s %s'), [App, Param]), ltDebug);
ExecuteFile(App, Param, '', SW_SHOW);
end;
procedure tApache.ServiceInstall;
var
App, Param: string;
RC: integer;
begin
App := basedir + 'apache\bin\' + Config.BinaryNames.Apache;
Param := '-k install -n "' + RemoveWhiteSpace(Config.ServiceNames.Apache) + '"';
AddLog(_('Installing service...'));
AddLog(Format(_('Executing "%s %s"'), [App, Param]), ltDebug);
RC := RunAsAdmin(App, Param, SW_HIDE);
if RC = 0 then
AddLog(Format(_('Return code: %d'), [RC]), ltDebug)
else
AddLog(Format(_('There may be an error, return code: %d - %s'), [RC, SystemErrorMessage(RC)]), ltError);
end;
procedure tApache.ServiceUnInstall;
var
App, Param: string;
RC: Cardinal;
begin
App := basedir + 'apache\bin\' + Config.BinaryNames.Apache;
Param := '-k uninstall -n "' + RemoveWhiteSpace(Config.ServiceNames.Apache) + '"';
AddLog(_('Uninstalling service...'));
AddLog(Format(_('Executing "%s %s"'), [App, Param]), ltDebug);
RC := RunAsAdmin(App, Param, SW_HIDE);
if RC = 0 then
AddLog(Format(_('Return code: %d'), [RC]), ltDebug)
else
AddLog(Format(_('There may be an error, return code: %d - %s'), [RC, SystemErrorMessage(RC)]), ltError);
end;
procedure tApache.ShowLogs(LogType: tApacheLogType);
var
App, Param: string;
begin
App := Config.EditorApp;
if LogType = altAccess then
Param := basedir + 'apache\logs\access.log';
if LogType = altError then
Param := basedir + 'apache\logs\error.log';
AddLog(Format(_('Executing "%s %s"'), [App, Param]), ltDebug);
ExecuteFile(App, Param, '', SW_SHOW);
end;
procedure tApache.Start;
var
App, ErrMsg: string;
RC: Cardinal;
begin
GlobalStatus := 'starting';
if isService then
begin
AddLog(Format(_('Attempting to start %s service...'), [cModuleName]));
//App := Format('start "%s"', [RemoveWhiteSpace(Config.ServiceNames.Apache)]);
//AddLog(Format(_('Executing "%s"'), ['net ' + App]), ltDebug);
//RC := RunAsAdmin('net', App, SW_HIDE);
RC := StartService(RemoveWhiteSpace(Config.ServiceNames.Apache));
if (RC = 0) or (RC = 1077) then
AddLog(Format(_('Return code: %d'), [RC]), ltDebug)
else
begin
ErrMsg := SysUtils.SysErrorMessage(System.GetLastError);
AddLog(Format(_('There may be an error, return code: %d - %s'), [RC, SystemErrorMessage(RC)]), ltError);
//AddLog(Format(_('%s'), [ErrMsg]), ltError);
if (Pos('SideBySide', SystemErrorMessage(RC)) <> 0)
or (Pos('VC9', SystemErrorMessage(RC)) <> 0)
or (Pos('VC9', ErrMsg) <> 0 )
or (Pos('SideBySide', ErrMsg) <> 0) then
begin
AddLog(_('You appear to be missing the VC9 Runtime Files'), ltError);
AddLog(_('You need to download and install the Microsoft Visual C++ 2008 SP1 (x86) Runtimes'), ltError);
AddLog(_('http://www.microsoft.com/download/en/details.aspx?id=5582'), ltError);
end;
end;
end
else
begin
AddLog(Format(_('Attempting to start %s app...'), [cModuleName]));
App := basedir + 'apache\bin\' + Config.BinaryNames.Apache;
AddLog(Format(_('Executing "%s"'), [App]), ltDebug);
RC := RunProcess(App, SW_HIDE, false);
if RC = 0 then
AddLog(Format(_('Return code: %d'), [RC]), ltDebug)
else
begin
ErrMsg := SysUtils.SysErrorMessage(System.GetLastError);
AddLog(Format(_('There may be an error, return code: %d - %s'), [RC, SystemErrorMessage(RC)]), ltError);
//AddLog(Format(_('%s'), [ErrMsg]), ltError);
if (Pos('SideBySide', SystemErrorMessage(RC)) <> 0)
or (Pos('VC9', SystemErrorMessage(RC)) <> 0)
or (Pos('VC9', ErrMsg) <> 0 )
or (Pos('SideBySide', ErrMsg) <> 0) then
begin
AddLog(_('You appear to be missing the VC9 Runtime Files'), ltError);
AddLog(_('You need to download and install the Microsoft Visual C++ 2008 SP1 (x86) Runtimes'), ltError);
AddLog(_('http://www.microsoft.com/download/en/details.aspx?id=5582'), ltError);
end;
end;
end;
end;
procedure tApache.Stop;
var
i, pPID: integer;
//App, ErrMsg: string;
ErrMsg: string;
RC: Cardinal;
begin
GlobalStatus := 'stopping';
if isService then
begin
AddLog(Format(_('Attempting to stop %s service...'), [cModuleName]));
//App := Format('stop "%s"', [RemoveWhiteSpace(Config.ServiceNames.Apache)]);
//AddLog(Format(_('Executing "%s"'), ['net ' + App]), ltDebug);
//RC := RunAsAdmin('net', App, SW_HIDE);
RC := StopService(RemoveWhiteSpace(Config.ServiceNames.Apache));
if RC = 0 then
AddLog(Format(_('Return code: %d'), [RC]), ltDebug)
else
begin
ErrMsg := SysUtils.SysErrorMessage(System.GetLastError);
AddLog(Format(_('There may be an error, return code: %d - %s'), [RC, SystemErrorMessage(RC)]), ltError);
//AddLog(Format(_('%s'), [ErrMsg]), ltError);
if (Pos('SideBySide', SystemErrorMessage(RC)) <> 0)
or (Pos('VC9', SystemErrorMessage(RC)) <> 0)
or (Pos('VC9', ErrMsg) <> 0 )
or (Pos('SideBySide', ErrMsg) <> 0) then
begin
AddLog(_('You appear to be missing the VC9 Runtime Files'), ltError);
AddLog(_('You need to download and install the Microsoft Visual C++ 2008 SP1 (x86) Runtimes'), ltError);
AddLog(_('http://www.microsoft.com/download/en/details.aspx?id=5582'), ltError);
end;
end;
end
else
begin
if PIDList.Count > 0 then
begin
for i := 0 to PIDList.Count - 1 do
begin
pPID := integer(PIDList[i]);
AddLog(_('Attempting to stop') + ' ' + cModuleName + ' ' + Format('(PID: %d)', [pPID]));
//App := Format(basedir + 'apache\bin\pv.exe -f -k -q -i %d', [pPID]);
//AddLog(Format(_('Executing "%s"'), [App]), ltDebug);
//RC := RunProcess(App, SW_HIDE, false);
if not TerminateProcessByID(pPID) then
begin
AddLog(Format(_('Problem killing PID %d'), [pPID]), ltError);
AddLog(_('Check that you have the proper privileges'), ltError);
end;
// RC := 0;
// if RC = 0 then
// AddLog(Format(_('Return code: %d'), [RC]), ltDebug)
// else
// begin
// ErrMsg := SysUtils.SysErrorMessage(System.GetLastError);
// AddLog(Format(_('There may be an error, return code: %d - %s'), [RC, SystemErrorMessage(RC)]), ltError);
// //AddLog(Format(_('%s'), [ErrMsg]), ltError);
// if (Pos('SideBySide', SystemErrorMessage(RC)) <> 0)
// or (Pos('VC9', SystemErrorMessage(RC)) <> 0)
// or (Pos('VC9', ErrMsg) <> 0 )
// or (Pos('SideBySide', ErrMsg) <> 0) then
// begin
// AddLog(_('You appear to be missing the VC9 Runtime Files'), ltError);
// AddLog(_('You need to download and install the Microsoft Visual C++ 2008 SP1 (x86) Runtimes'), ltError);
// AddLog(_('http://www.microsoft.com/download/en/details.aspx?id=5582'), ltError);
// end;
// end;
end;
end
else
begin
AddLog(_('No PIDs found?!'));
end;
end;
end;
procedure tApache.UpdateStatus;
var
p: integer;
ProcInfo: TProcInfo;
s: string;
Ports: string;
ErrorStatus: integer;
begin
isRunning := false;
PIDList.Clear;
ErrorStatus := 0;
for p := 0 to Processes.ProcessList.Count - 1 do
begin
ProcInfo := Processes.ProcessList[p];
if (pos(Config.BinaryNames.Apache, ProcInfo.Module) = 1) then
begin
//AddLog(Format(_('Process Path: %s'), [ProcInfo.ExePath]), ltDebug);
if (pos(IntToStr(Config.ServicePorts.Apache),NetStatTable.GetPorts4PID(ProcInfo.PID)) <> 0) or
(pos(IntToStr(Config.ServicePorts.ApacheSSL),NetStatTable.GetPorts4PID(ProcInfo.PID)) <> 0) or
(pos(LowerCase(BaseDir), LowerCase(ProcInfo.ExePath)) <> 0) then
begin
isRunning := true;
PIDList.Add(Pointer(ProcInfo.PID));
end;
end;
end;
// Checking processes
s := '';
for p := 0 to PIDList.Count - 1 do
begin
if p = 0 then
s := IntToStr(integer(PIDList[p]))
else
s := s + #13 + IntToStr(integer(PIDList[p]));
end;
if s <> OldPIDs then
begin
lPID.Caption := s;
OldPIDs := s;
end;
// Checking netstats
s := '';
for p := 0 to PIDList.Count - 1 do
begin
Ports := NetStatTable.GetPorts4PID(integer(PIDList[p]));
if Ports <> '' then
//begin
// if s = '' then
s := RemoveDuplicatePorts(Ports);
// else
// s := s + ', ' + Ports;
//end;
end;
if s <> OldPorts then
begin
lPort.Caption := s;
OldPorts := s;
end;
if (byte(isRunning) <> oldIsRunningByte) or (OldPIDCount <> PIDList.Count) then
begin
if (oldIsRunningByte <> 2) and (byte(isRunning) <> oldIsRunningByte) then
begin
if isRunning then
s := _('running')
else
begin
s := _('stopped');
if GlobalStatus = 'starting' then
ErrorStatus := 1;
end;
AddLog(_('Status change detected:') + ' ' + s);
if ErrorStatus = 1 then
begin
pStatus.Color := cErrorColor;
AddLog(_('Error: Apache shutdown unexpectedly.'), ltError);
AddLog(_('This may be due to a blocked port, missing dependencies, '), ltError);
AddLog(_('improper privileges, a crash, or a shutdown by another method.'), ltError);
AddLog(_('Check the "/xampp/apache/logs/error.log" file'), ltError);
AddLog(_('and the Windows Event Viewer for more clues'), ltError);
end;
end;
oldIsRunningByte := byte(isRunning);
if isRunning then
begin
if (PIDList.Count = 2) or ((PIDList.Count = 1) and (isService)) then
begin
pStatus.Color := cRunningColor;
bStartStop.Caption := _('Stop');
bAdmin.Enabled := true;
fMain.ApacheTray.ImageIndex := 15;
fMain.ApacheTrayControl.Caption := _('Stop');
end
else
begin
pStatus.Color := cPartialColor;
bStartStop.Caption := _('Stop');
bAdmin.Enabled := true;
end;
end
else
begin
pStatus.Color := cStoppedColor;
bStartStop.Caption := _('Start');
bAdmin.Enabled := false;
fMain.ApacheTray.ImageIndex := 16;
fMain.ApacheTrayControl.Caption := _('Start');
end;
end;
OldPIDCount := PIDList.Count;
if AutoStart then
begin
AutoStart := false;
if isRunning then
begin
AddLog(_('Autostart aborted: Apache is already running'), ltInfo);
end
else
begin
AddLog(_('Autostart active: starting...'));
Start;
end;
end;
end;
end.
|
unit QuaternionTestCase;
{$mode objfpc}{$H+}
{$CODEALIGN LOCALMIN=16}
interface
uses
Classes, SysUtils, fpcunit, testregistry, BaseTestCase,
native, BZVectorMath;
type
{ TQuaternionTestCase }
TQuaternionTestCase = class(TVectorBaseTestCase)
protected
procedure Setup; override;
public
{$CODEALIGN RECORDMIN=16}
nqt1, nqt2, nqt3 : TNativeBZQuaternion;
aqt1, aqt2, aqt3 : TBZQuaternion;
{$CODEALIGN RECORDMIN=4}
published
procedure TestCompare;
procedure TestCompareFalse;
procedure TestCreateSingles;
procedure TestCreateImagArrayWithReal;
procedure TestCreateTwoUnitAffine;
procedure TestCreateTwoUnitHmg;
procedure TestCreateAngleAxis;
procedure TestCreateEuler;
procedure TestCreateEulerOrder;
procedure TestMulQuaternion;
procedure TestConjugate;
procedure TestOpEquals;
procedure TestOpNotEquals;
procedure TestMagnitude;
procedure TestNormalize;
procedure TestMultiplyAsSecond;
procedure TestSlerpSingle;
procedure TestSlerpSpin;
procedure TestConvertToMatrix;
procedure TestCreateMatrix;
procedure TestTransform;
procedure TestScale;
end;
implementation
{ TQuaternionTestCase }
procedure TQuaternionTestCase.Setup;
begin
inherited Setup;
nqt1.Create(5.850,-15.480,8.512,1.5);
nqt2.Create(1.558,6.512,4.525,1.0);
aqt1.V := nqt1.V;
aqt2.V := nqt2.V;
end;
{%region%====[ TQuaternionTestCase ]============================================}
procedure TQuaternionTestCase.TestCompare;
begin
AssertTrue('Test Values do not match'+nqt1.ToString+' --> '+aqt1.ToString, Compare(nqt1,aqt1));
end;
procedure TQuaternionTestCase.TestCompareFalse;
begin
AssertFalse('Test Values do not match'+nqt1.ToString+' --> '+aqt2.ToString, Compare(nqt1,aqt2));
end;
procedure TQuaternionTestCase.TestCreateSingles;
begin
nqt3.Create(1,2,3,4);
aqt3.Create(1,2,3,4);
AssertTrue('Quaternion.CreateSingles no match'+nqt3.ToString+' --> '+aqt3.ToString, Compare(nqt3,aqt3));
end;
procedure TQuaternionTestCase.TestCreateImagArrayWithReal;
begin
nqt3.Create(3.0,nt1.AsVector3f);
aqt3.Create(3.0,vt1.AsVector3f);
AssertTrue('Quaternion.CreateImagArrayWithReal no match'+nqt3.ToString+' --> '+aqt3.ToString, Compare(nqt3,aqt3,1e-8));
end;
procedure TQuaternionTestCase.TestCreateTwoUnitAffine;
begin
nqt3.Create(nt1.AsVector3f,nt2.AsVector3f);
aqt3.Create(vt1.AsVector3f,vt2.AsVector3f);
AssertTrue('Quaternion.CreateTwoUnitAffine no match'+nqt3.ToString+' --> '+aqt3.ToString, Compare(nqt3,aqt3,1e-6));
end;
procedure TQuaternionTestCase.TestCreateTwoUnitHmg;
begin
nqt3.Create(nt1,nt2);
aqt3.Create(vt1,vt2);
AssertTrue('Quaternion.CreateTwoUnitHmg no match'+nqt3.ToString+' --> '+aqt3.ToString, Compare(nqt3,aqt3,1e-6));
end;
procedure TQuaternionTestCase.TestCreateAngleAxis;
begin
nqt3.Create(90, NativeZVector);
aqt3.Create(90, ZVector);
AssertTrue('Quaternion.CreateAngleAxis no match'+nqt3.ToString+' --> '+aqt3.ToString, Compare(nqt3,aqt3));
end;
procedure TQuaternionTestCase.TestCreateEuler;
begin
nqt3.Create(90, 0, 0);
aqt3.Create(90, 0, 0);
AssertTrue('Quaternion.CreateEuler no match'+nqt3.ToString+' --> '+aqt3.ToString, Compare(nqt3,aqt3));
end;
procedure TQuaternionTestCase.TestCreateEulerOrder;
begin
nqt3.Create(90, 45, -30, eulZXY);
aqt3.Create(90, 45, -30, eulZXY);
AssertTrue('Quaternion.CreateEulerOrder no match'+nqt3.ToString+' --> '+aqt3.ToString, Compare(nqt3,aqt3));
end;
procedure TQuaternionTestCase.TestMulQuaternion;
begin
nqt3 := nqt1 * nqt2;
aqt3 := aqt1 * aqt2;
AssertTrue('Quaternion * Quaternion no match'+nqt3.ToString+' --> '+aqt3.ToString, Compare(nqt3,aqt3));
end;
procedure TQuaternionTestCase.TestConjugate;
begin
nqt3 := nqt1.Conjugate;
aqt3 := aqt1.Conjugate;
AssertTrue('Quaternion.Conjugate no match'+nqt3.ToString+' --> '+aqt3.ToString, Compare(nqt3,aqt3));
end;
procedure TQuaternionTestCase.TestOpEquals;
begin
nb := nqt1 = nqt1;
ab := aqt1 = aqt1;
AssertTrue('Quaternion = does not match '+nb.ToString+' --> '+ab.ToString, (nb = ab));
end;
procedure TQuaternionTestCase.TestOpNotEquals;
begin
nb := nqt1 <> nqt1;
ab := aqt1 <> aqt1;
AssertTrue('Quaternion <> does not match '+nb.ToString+' --> '+ab.ToString, (nb = ab));
end;
procedure TQuaternionTestCase.TestMagnitude;
begin
Fs1 := nqt1.Magnitude;
Fs2 := aqt1.Magnitude;
AssertTrue('Quaternion Magnitude do not match : '+FLoattostrF(fs1,fffixed,3,3)+' --> '+FLoattostrF(fs2,fffixed,3,3), IsEqual(Fs1,Fs2));
end;
procedure TQuaternionTestCase.TestNormalize;
begin
nqt1.Normalize;
aqt1.Normalize;
AssertTrue('Quaternion Normalize no match'+nqt3.ToString+' --> '+aqt3.ToString, Compare(nqt1,aqt1,1e-2));
end;
procedure TQuaternionTestCase.TestMultiplyAsSecond;
begin
nqt3 := nqt1.MultiplyAsSecond(nqt2);
aqt3 := aqt1.MultiplyAsSecond(aqt2);
AssertTrue('Quaternion MultiplyAsSecond no match'+nqt3.ToString+' --> '+aqt3.ToString, Compare(nqt3,aqt3));
end;
procedure TQuaternionTestCase.TestSlerpSingle;
begin
nqt2.Create(90,NativeZVector);
aqt2.Create(90,ZVector);
nqt3 := NativeIdentityQuaternion.Slerp(nqt1,0.5);
aqt3 := IdentityQuaternion.Slerp(aqt1,0.5);
AssertTrue('Quaternion SlerpSingle no match'+nqt3.ToString+' --> '+aqt3.ToString, Compare(nqt3,aqt3,1e-6));
end;
procedure TQuaternionTestCase.TestSlerpSpin;
begin
nqt1.Create(90,NativeZVector);
aqt1.Create(90,ZVector);
nqt3 := NativeIdentityQuaternion.Slerp(nqt1,3,0.5);
aqt3 := IdentityQuaternion.Slerp(aqt1,3,0.5);
AssertTrue('Quaternion SlerpSpin no match'+nqt3.ToString+' --> '+aqt3.ToString, Compare(nqt3,aqt3,1e-6));
end;
procedure TQuaternionTestCase.TestConvertToMatrix;
var
nMat: TNativeBZMatrix;
aMat: TBZMatrix;
begin
nqt1.Create(90,NativeZVector);
aqt1.Create(90,ZVector);
nMat := nqt1.ConvertToMatrix;
aMat := aqt1.ConvertToMatrix;
AssertTrue('Quaternion ConvertToMatrix no match'+nmat.ToString+' --> '+amat.ToString, CompareMatrix(nMat,aMat));
end;
procedure TQuaternionTestCase.TestCreateMatrix;
var
nMat: TNativeBZMatrix;
aMat: TBZMatrix;
begin
nMat.V[0].Create( 0.6479819, 0.7454178, -0.1564345, 0);
nMat.V[1].Create( 0.7312050, -0.5513194, 0.4017290, 0);
nMat.V[2].Create( 0.2132106, -0.3746988, -0.9022982, 0);
nMat.V[3].Create(0,0,0,1);
aMat.V[0].Create( 0.6479819, 0.7454178, -0.1564345, 0);
aMat.V[1].Create( 0.7312050, -0.5513194, 0.4017290, 0);
aMat.V[2].Create( 0.2132106, -0.3746988, -0.9022982, 0);
aMat.V[3].Create(0,0,0,1);
nqt3.Create(nMat);
aqt3.Create(aMat);
AssertTrue('Quaternion CreateMatrix no match'+nqt3.ToString+' --> '+aqt3.ToString, Compare(nqt3,aqt3));
end;
procedure TQuaternionTestCase.TestTransform;
begin
nqt1.Create(90,NativeZVector);
aqt1.Create(90,ZVector);
nt3 := nqt1.Transform(nt1);
vt3 := aqt1.Transform(vt1);
AssertTrue('Quaternion Transform no match'+nt3.ToString+' --> '+vt3.ToString, Compare(nt3,vt3));
end;
procedure TQuaternionTestCase.TestScale;
begin
nqt1.Create(90,NativeZVector); // create a normalised postive rotation in Z
aqt1.Create(90,ZVector); // create a normalised postive rotation in Z
nqt1.Scale(2);
aqt1.Scale(2);
nt3 := nqt1.Transform(nt1);
vt3 := aqt1.Transform(vt1);
end;
{%endregion%}
initialization
RegisterTest(REPORT_GROUP_QUATERION, TQuaternionTestCase);
end.
|
object NewGameForm: TNewGameForm
Left = 192
Top = 107
BorderStyle = bsToolWindow
Caption = 'New Game'
ClientHeight = 119
ClientWidth = 136
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'MS Sans Serif'
Font.Style = []
OldCreateOrder = False
PixelsPerInch = 96
TextHeight = 13
object Label1: TLabel
Left = 8
Top = 0
Width = 87
Height = 13
Caption = 'Enter Game Name'
end
object edName: TEdit
Left = 8
Top = 16
Width = 121
Height = 21
TabOrder = 0
end
object cbCreateNew: TCheckBox
Left = 8
Top = 40
Width = 129
Height = 17
Caption = 'Create New Database'
TabOrder = 1
end
object bnOk: TButton
Left = 8
Top = 88
Width = 57
Height = 25
Caption = 'Create'
Default = True
ModalResult = 1
TabOrder = 2
OnClick = bnOkClick
end
object Button1: TButton
Left = 72
Top = 88
Width = 57
Height = 25
Caption = 'Cancel'
ModalResult = 2
TabOrder = 3
end
object cbSaveOld: TCheckBox
Left = 7
Top = 64
Width = 137
Height = 17
Caption = 'Save old game'
Checked = True
State = cbChecked
TabOrder = 4
end
end
|
unit HJYValidationChecks;
interface
uses Windows, SysUtils, Classes, IniFiles, DateUtils;
type
TTrialVersionCheck = class
private
FSystemPath: string;
FTimeFileA: string; // 保存的第一个时间文件
FTimeFileB: string; // 保存的第二个时间文件
FScyxDateA: TDateTime;
FScyxDateB: TDateTime;
procedure SaveFirstRunFile;
procedure WriteScyxDate(AFileName: string; AValue: TDateTime);
function GetScyxDate(AFileName: string): TDateTime;
function IsFirstRun: Boolean;
public
constructor Create; virtual;
destructor Destroy; override;
function Execute: Boolean;
end;
function TrialVersionCheck: Boolean;
implementation
uses HJYUtils;
function TrialVersionCheck: Boolean;
var
lCheck: TTrialVersionCheck;
begin
lCheck := TTrialVersionCheck.Create;
try
Result := lCheck.Execute;
finally
lCheck.Free;
end;
end;
const
CJXC_VER_SECTION = 'yscmb';
CJXC_VER_IdentName = 'scyx';
CJXC_Trial_DayCount = 45;
{ TTrialVersionCheck }
constructor TTrialVersionCheck.Create;
begin
FSystemPath := SystemPath;
FTimeFileA := FSystemPath + 'jha.dll';
FTimeFileB := FSystemPath + 'wjhb.dll';
end;
function TTrialVersionCheck.IsFirstRun: Boolean;
begin
Result := not FileExists(FTimeFileA) and not FileExists(FTimeFileB);
end;
function TTrialVersionCheck.GetScyxDate(AFileName: string): TDateTime;
var
lIni: TIniFile;
begin
lIni := TIniFile.Create(AFileName);
try
Result := lIni.ReadDate(CJXC_VER_SECTION, CJXC_VER_IdentName, 0);
finally
lIni.Free;
end;
end;
procedure TTrialVersionCheck.WriteScyxDate(AFileName: string;
AValue: TDateTime);
var
lIni: TIniFile;
begin
lIni := TIniFile.Create(AFileName);
try
lIni.WriteDate(CJXC_VER_SECTION, CJXC_VER_IdentName, AValue);
finally
lIni.Free;
end;
end;
procedure TTrialVersionCheck.SaveFirstRunFile;
begin
WriteScyxDate(FTimeFileA, Date);
WriteScyxDate(FTimeFileB, Date);
end;
destructor TTrialVersionCheck.Destroy;
begin
inherited;
end;
function TTrialVersionCheck.Execute: Boolean;
begin
Result := False;
// 如果是首次运行,则需要创建两个文件,并记录当前日期
if IsFirstRun then
begin
SaveFirstRunFile;
Result := True;
Exit;
end;
// 如果两个文件有一个不存在,则需要复制一份
if not FileExists(FTimeFileA) and FileExists(FTimeFileB) then
CopyFile(PWideChar(FTimeFileB), PWideChar(FTimeFileA), False);
if FileExists(FTimeFileA) and not FileExists(FTimeFileB) then
CopyFile(PWideChar(FTimeFileA), PWideChar(FTimeFileB), False);
// 分别获取两个文件记录的日期,如果日期不一致则统一更新为较小的那个日期
FScyxDateA := GetScyxDate(FTimeFileA);
FScyxDateB := GetScyxDate(FTimeFileB);
if FScyxDateA > FScyxDateB then
begin
WriteScyxDate(FTimeFileA, FScyxDateB);
FScyxDateA := FScyxDateB;
end else if FScyxDateA < FScyxDateB then
begin
WriteScyxDate(FTimeFileB, FScyxDateA);
FScyxDateB := FScyxDateA;
end;
// 如果记录的首次运行日期大于当前系统日期,认为已经超出试用期
if FScyxDateA > Date then
Exit;
// 计算首次运行的日期跟当前日期天数差额,如果大于允许的试用期,已经超出试用期
if DaysBetween(FScyxDateA, Date) > CJXC_Trial_DayCount then
Exit;
Result := True;
end;
end.
|
unit uDMVendas;
interface
uses
System.SysUtils, System.Classes, System.Types, System.Variants, uDM, FireDAC.Stan.Intf, FireDAC.Stan.Option,
FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf,
FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB,
Datasnap.DBClient, Datasnap.Provider, FireDAC.Comp.DataSet,
FireDAC.Comp.Client, uConstantes;
type
TDMVendas = class(TDataModule)
qVenda: TFDQuery;
qVendaid_venda: TLargeintField;
qVendaid_caixa: TIntegerField;
qVendaid_cliente: TLargeintField;
qVendaid_deposito: TIntegerField;
qVendaid_empresa: TIntegerField;
qVendaid_moeda: TIntegerField;
qVendaid_usuario: TIntegerField;
qVendaid_anula: TIntegerField;
qVendaid_faturou: TIntegerField;
qVendadata: TSQLTimeStampField;
qVendadataanula: TSQLTimeStampField;
qVendadatafaturou: TSQLTimeStampField;
qVendaobs: TStringField;
qVendacondpag: TStringField;
qVendastatus: TLargeintField;
qVendanumero: TLargeintField;
qVendadocumento: TStringField;
qVendaendereco: TStringField;
qVendacliente: TStringField;
qVendadatafiscal: TSQLTimeStampField;
qVendaid_timbrado: TLargeintField;
qVendaid_vendedor: TIntegerField;
qVendaid_turno: TIntegerField;
qVendacomfatura: TBooleanField;
qVendancontrole: TStringField;
qVendaNomeCliente: TStringField;
qVendaenvia_pacote: TBooleanField;
qVendaexclusivo: TBooleanField;
qVendaexclusivo_usuario: TLargeintField;
qVendaexclusivo_datahora: TSQLTimeStampField;
qVendaid_pontoentrega: TIntegerField;
qVendacambio_rs: TCurrencyField;
qVendacambio_gs: TCurrencyField;
qVendaid_moeda_fatura: TSmallintField;
qVendaorcamento: TBooleanField;
qVendaItem: TFDQuery;
dspVenda: TDataSetProvider;
dsVenda: TDataSource;
cdsVenda: TClientDataSet;
cdsVendaItem: TClientDataSet;
cdsVendaItemTotal: TAggregateField;
dsCdsVenda: TDataSource;
dsCdsVendaItem: TDataSource;
cdsCliente: TClientDataSet;
qCliente: TFDQuery;
dspCliente: TDataSetProvider;
lsProdutoSaldo: TClientDataSet;
lsProdutoSaldoDS: TDataSource;
qProdutoSaldo: TFDQuery;
dspProdutoSaldo: TDataSetProvider;
qProdutoComSaldo: TFDQuery;
dspProdutoComSaldo: TDataSetProvider;
lsProdutoComSaldo: TClientDataSet;
lsProdutoComSaldoDS: TDataSource;
lsUsuarioPorID: TClientDataSet;
qUsuarioPorID: TFDQuery;
dspUsuarioPorID: TDataSetProvider;
qCambio: TFDQuery;
dspCambio: TDataSetProvider;
lsCambio: TClientDataSet;
cdsControle: TClientDataSet;
cdsControlecampo: TStringField;
cdsControlevalor: TLargeintField;
qControle: TFDQuery;
dspControle: TDataSetProvider;
qGenerica: TFDQuery;
dspGenerica: TDataSetProvider;
cdsGenerica: TClientDataSet;
qProdutoSaldoPorID: TFDQuery;
dspProdutoSaldoPorID: TDataSetProvider;
lsProdutoSaldoPorID: TClientDataSet;
lsUsuario: TClientDataSet;
lsUsuarioDS: TDataSource;
qUsuario: TFDQuery;
dspUsuario: TDataSetProvider;
lsCambioreal: TFMTBCDField;
lsCambioguarani: TFMTBCDField;
qVendaItemid_venda_item: TLargeintField;
qVendaItemdata: TSQLTimeStampField;
qVendaItemid_venda: TLargeintField;
qVendaItemid_deposito: TIntegerField;
qVendaItemid_produto: TLargeintField;
qVendaItemid_bloqueio: TLargeintField;
qVendaItemdescricao: TStringField;
qVendaItemqtde: TFMTBCDField;
qVendaItempreco_liquido: TFMTBCDField;
qVendaItemcusto: TFMTBCDField;
qVendaItemcustofob: TFMTBCDField;
qVendaItemiva: TBCDField;
qVendaItemid_usuario_autpreco: TIntegerField;
qVendaItemstatus: TIntegerField;
qVendaItempreco_normal: TFMTBCDField;
qVendaItemdesconto: TFMTBCDField;
qVendaItemivaporcentagem: TBCDField;
qVendaItemtipo: TIntegerField;
qVendaItempreco_moeda: TFMTBCDField;
qVendaItemgasto: TFMTBCDField;
qVendaItemgasto_moeda: TFMTBCDField;
qVendaItemiva_moeda: TFMTBCDField;
qVendaItemcambio: TCurrencyField;
qVendaItemdescontotipo: TSmallintField;
qVendaItemdesconto_normal: TFMTBCDField;
qVendaItemid_vendedor: TLargeintField;
qVendaItemflag_com_saldo: TBooleanField;
cdsVendaid_venda: TLargeintField;
cdsVendaid_caixa: TIntegerField;
cdsVendaid_cliente: TLargeintField;
cdsVendaid_deposito: TIntegerField;
cdsVendaid_empresa: TIntegerField;
cdsVendaid_moeda: TIntegerField;
cdsVendaid_usuario: TIntegerField;
cdsVendaid_anula: TIntegerField;
cdsVendaid_faturou: TIntegerField;
cdsVendadata: TSQLTimeStampField;
cdsVendadataanula: TSQLTimeStampField;
cdsVendadatafaturou: TSQLTimeStampField;
cdsVendaobs: TStringField;
cdsVendacondpag: TStringField;
cdsVendastatus: TLargeintField;
cdsVendanumero: TLargeintField;
cdsVendadocumento: TStringField;
cdsVendaendereco: TStringField;
cdsVendacliente: TStringField;
cdsVendadatafiscal: TSQLTimeStampField;
cdsVendaid_timbrado: TLargeintField;
cdsVendaid_vendedor: TIntegerField;
cdsVendaid_turno: TIntegerField;
cdsVendacomfatura: TBooleanField;
cdsVendancontrole: TStringField;
cdsVendaNomeCliente: TStringField;
cdsVendaenvia_pacote: TBooleanField;
cdsVendaexclusivo: TBooleanField;
cdsVendaexclusivo_usuario: TLargeintField;
cdsVendaexclusivo_datahora: TSQLTimeStampField;
cdsVendaid_pontoentrega: TIntegerField;
cdsVendacambio_rs: TCurrencyField;
cdsVendacambio_gs: TCurrencyField;
cdsVendaid_moeda_fatura: TSmallintField;
cdsVendaorcamento: TBooleanField;
cdsVendaqVendaItem: TDataSetField;
cdsVendaItemid_venda_item: TLargeintField;
cdsVendaItemdata: TSQLTimeStampField;
cdsVendaItemid_venda: TLargeintField;
cdsVendaItemid_deposito: TIntegerField;
cdsVendaItemid_produto: TLargeintField;
cdsVendaItemid_bloqueio: TLargeintField;
cdsVendaItemdescricao: TStringField;
cdsVendaItemqtde: TFMTBCDField;
cdsVendaItempreco_liquido: TFMTBCDField;
cdsVendaItemcusto: TFMTBCDField;
cdsVendaItemcustofob: TFMTBCDField;
cdsVendaItemiva: TBCDField;
cdsVendaItemid_usuario_autpreco: TIntegerField;
cdsVendaItemstatus: TIntegerField;
cdsVendaItempreco_normal: TFMTBCDField;
cdsVendaItemdesconto: TFMTBCDField;
cdsVendaItemivaporcentagem: TBCDField;
cdsVendaItemtipo: TIntegerField;
cdsVendaItempreco_moeda: TFMTBCDField;
cdsVendaItemgasto: TFMTBCDField;
cdsVendaItemgasto_moeda: TFMTBCDField;
cdsVendaItemiva_moeda: TFMTBCDField;
cdsVendaItemcambio: TCurrencyField;
cdsVendaItemdescontotipo: TSmallintField;
cdsVendaItemdesconto_normal: TFMTBCDField;
cdsVendaItemid_vendedor: TLargeintField;
cdsVendaItemflag_com_saldo: TBooleanField;
lsProdutoSaldoid_produto: TLargeintField;
lsProdutoSaldonome: TStringField;
lsProdutoSaldoserial: TStringField;
lsProdutoSaldounidade: TIntegerField;
lsProdutoSaldoClassificacao: TStringField;
lsProdutoSaldoMarca: TStringField;
lsProdutoSaldoPrecio1US: TFMTBCDField;
lsProdutoSaldoPrecio2US: TFMTBCDField;
lsProdutoSaldoPrecio3US: TFMTBCDField;
lsProdutoSaldoatalho1: TStringField;
lsProdutoSaldoatalho2: TStringField;
lsProdutoSaldoatalho3: TStringField;
lsProdutoSaldotipo: TIntegerField;
lsProdutoSaldoiva: TBCDField;
lsProdutoSaldoguarani: TFMTBCDField;
lsProdutoSaldoreal: TFMTBCDField;
lsProdutoSaldoFornecedor: TStringField;
lsProdutoSaldoDeposito: TIntegerField;
lsProdutoSaldoDepositoTipo: TStringField;
lsProdutoSaldoSaldoTotal: TFMTBCDField;
lsProdutoSaldoBloqueado: TFMTBCDField;
lsProdutoSaldoSaldo: TFMTBCDField;
lsProdutoSaldoCustoFOB: TFMTBCDField;
lsProdutoSaldoCustoCif: TFMTBCDField;
lsProdutoSaldoUltimoCIF: TFMTBCDField;
lsProdutoComSaldoid_produto: TLargeintField;
lsProdutoComSaldonome: TStringField;
lsProdutoComSaldoserial: TStringField;
lsProdutoComSaldounidade: TIntegerField;
lsProdutoComSaldoClassificacao: TStringField;
lsProdutoComSaldoMarca: TStringField;
lsProdutoComSaldoPrecio1US: TFMTBCDField;
lsProdutoComSaldoPrecio2US: TFMTBCDField;
lsProdutoComSaldoPrecio3US: TFMTBCDField;
lsProdutoComSaldoatalho1: TStringField;
lsProdutoComSaldoatalho2: TStringField;
lsProdutoComSaldoatalho3: TStringField;
lsProdutoComSaldotipo: TIntegerField;
lsProdutoComSaldoiva: TBCDField;
lsProdutoComSaldoguarani: TFMTBCDField;
lsProdutoComSaldoreal: TFMTBCDField;
lsProdutoComSaldoFornecedor: TStringField;
lsProdutoComSaldoDeposito: TIntegerField;
lsProdutoComSaldoDepositoTipo: TStringField;
lsProdutoComSaldoSaldoTotal: TFMTBCDField;
lsProdutoComSaldoBloqueado: TFMTBCDField;
lsProdutoComSaldoSaldo: TFMTBCDField;
lsProdutoComSaldoCustoFOB: TFMTBCDField;
lsProdutoComSaldoCustoCif: TFMTBCDField;
lsProdutoComSaldoUltimoCIF: TFMTBCDField;
lsProdutoSaldoPorIDid_produto: TLargeintField;
lsProdutoSaldoPorIDnome: TStringField;
lsProdutoSaldoPorIDserial: TStringField;
lsProdutoSaldoPorIDClassificacao: TStringField;
lsProdutoSaldoPorIDMarca: TStringField;
lsProdutoSaldoPorIDPrecio1US: TFMTBCDField;
lsProdutoSaldoPorIDPrecio2US: TFMTBCDField;
lsProdutoSaldoPorIDPrecio3US: TFMTBCDField;
lsProdutoSaldoPorIDatalho1: TStringField;
lsProdutoSaldoPorIDatalho2: TStringField;
lsProdutoSaldoPorIDatalho3: TStringField;
lsProdutoSaldoPorIDtipo: TIntegerField;
lsProdutoSaldoPorIDiva: TBCDField;
lsProdutoSaldoPorIDguarani: TFMTBCDField;
lsProdutoSaldoPorIDreal: TFMTBCDField;
lsProdutoSaldoPorIDFornecedor: TStringField;
lsProdutoSaldoPorIDDeposito: TIntegerField;
lsProdutoSaldoPorIDDepositoTipo: TStringField;
lsProdutoSaldoPorIDSaldoTotal: TFMTBCDField;
lsProdutoSaldoPorIDBloqueado: TFMTBCDField;
lsProdutoSaldoPorIDSaldo: TFMTBCDField;
lsProdutoSaldoPorIDCustoFOB: TFMTBCDField;
lsProdutoSaldoPorIDCustoCif: TFMTBCDField;
lsProdutoSaldoPorIDUltimoCIF: TFMTBCDField;
lsClientePorID: TClientDataSet;
qClientePorID: TFDQuery;
dspClientePorID: TDataSetProvider;
cdsProdutoSaldo: TClientDataSet;
cdsProdutoSaldoid_produto_saldo: TLargeintField;
cdsProdutoSaldoid_produto: TLargeintField;
cdsProdutoSaldoid_deposito: TIntegerField;
cdsProdutoSaldosaldo: TFloatField;
cdsProdutoSaldobloq: TFloatField;
cdsProdutoSaldototalfob: TFloatField;
cdsProdutoSaldototalcif: TFloatField;
cdsProdutoSaldostatus: TSmallintField;
qProdutoMov: TFDQuery;
dspProdutoMov: TDataSetProvider;
cdsProdutoMov: TClientDataSet;
cdsProdutoMovid_produtomov: TLargeintField;
cdsProdutoMovid_operacao: TIntegerField;
cdsProdutoMovid_deposito: TLargeintField;
cdsProdutoMovid_produto: TLargeintField;
cdsProdutoMovid_usuario: TLargeintField;
cdsProdutoMovcontrole: TLargeintField;
cdsProdutoMovqtde: TFloatField;
cdsProdutoMovtipo: TStringField;
cdsProdutoMovcustomedio: TFloatField;
cdsProdutoMovdata: TSQLTimeStampField;
cdsProdutoMovstatus: TSmallintField;
qDataHora: TFDQuery;
qVendaHistorico: TFDQuery;
dspVendaHistorico: TDataSetProvider;
cdsVendaHistorico: TClientDataSet;
qProduto: TFDQuery;
dspProduto: TDataSetProvider;
cdsProduto: TClientDataSet;
procedure dspVendaBeforeUpdateRecord(Sender: TObject; SourceDS: TDataSet;
DeltaDS: TCustomClientDataSet; UpdateKind: TUpdateKind;
var Applied: Boolean);
private
function FindDeltaUpdateTree(Tree: TUpdateTree;
DeltaDS: TCustomClientDataSet): TUpdateTree;
function AtualizaProduto(lOperacao: string; lCodigo: Integer; lqtde: Real;
lDeposito: integer): boolean;
function EstoqueBaixa(vIdProduto, vIdDeposito: integer; vCustoCif,
vCustoFob, vQtde: Real): boolean;
function EstoqueMov(DeltaDS: TCustomClientDataSet): boolean;
function IfNull(const Value, Default: OleVariant): OleVariant;
function fnGetDataHora: TDateTime;
function EstoqueVendaHistorico(DeltaDS: TCustomClientDataset): boolean;
function EstoqueProdutoDataVenta(DeltaDS: TCustomClientDataSet): boolean;
{ Private declarations }
public
{ Public declarations }
gCrud :string;
gID : integer;
gMsgErro : string;
gUltimaPesquisaPorProduto: string;
function retornaID(NomeCampo: String): integer;
function consultaCliente(lCampo, lValor: string): OleVariant;
end;
var
DMVendas: TDMVendas;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
function TDMVendas.fnGetDataHora: TDateTime;
begin
qDataHora.Close;
qDataHora.Open;
result := qDataHora.FieldByName('datahora').AsDateTime;
qDataHora.Close;
end;
function TDMVendas.IfNull( const Value, Default : OleVariant ) : OleVariant;
begin
if Value = NULL then
Result := Default
else
Result := Value;
end;
function TDMVendas.FindDeltaUpdateTree(Tree: TUpdateTree; DeltaDS: TCustomClientDataSet): TUpdateTree;
var
I: Integer;
begin
Result := nil;
if Tree.Delta = DeltaDS then
Result := Tree
else
for I := 0 to Tree.DetailCount - 1 do
begin
Result := FindDeltaUpdateTree(Tree.Details[I], DeltaDS);
if Assigned(Result) then
Break;
end;
end;
function TDMVendas.EstoqueMov(DeltaDS: TCustomClientDataSet): boolean;
var
resultado: boolean;
begin
resultado := false;
qGenerica.close;
qGenerica.SQL.Clear;
qGenerica.SQL.Add('select numero,condpag,id_usuario,id_vendedor from venda where id_venda = :id_venda');
qGenerica.Params.ParamByName('id_venda').AsInteger := DeltaDS.FieldByName('id_venda').OldValue;
qGenerica.Open();
qGenerica.Refresh;
if qGenerica.RecordCount > 0 then
begin
cdsProdutoMov.Close;
cdsProdutoMov.Params.ParamByName('id_produtomov').AsInteger := -1;
cdsProdutoMov.Open;
cdsProdutoMov.Append;
//PAREI AQUI NESTE ID QUE NAO QUERIA GRAVAR.
if IfNull(qGenerica.FieldByName('condpag').asVariant,0) = 0 then
begin
cdsProdutoMov.FieldByName('id_operacao').AsInteger := OP_VENDA_VISTA;
end
else
begin
cdsProdutoMov.FieldByName('id_operacao').AsInteger := OP_VENDA_PRAZO;
end;
cdsProdutoMov.FieldByName('id_deposito').AsInteger := DeltaDS.FieldByName('id_deposito').OldValue;
cdsProdutoMov.FieldByName('id_produto').AsInteger := DeltaDS.FieldByName('id_produto').OldValue;
cdsProdutoMov.FieldByName('id_usuario').AsInteger := qGenerica.FieldByName('id_vendedor').OldValue;
cdsProdutoMov.FieldByName('controle').AsInteger := qGenerica.FieldByName('numero').AsInteger;
cdsProdutoMov.FieldByName('qtde').AsFloat := DeltaDS.FieldByName('qtde').oldValue;
cdsProdutoMov.FieldByName('tipo').asString := 'S';
cdsProdutoMov.FieldByName('customedio').AsFloat := DeltaDS.FieldByName('custo').oldValue;
cdsProdutoMov.FieldByName('data').AsDateTime := fnGetDataHora;
cdsProdutoMov.FieldByName('status').AsInteger := 1;
cdsProdutoMov.Post;
if (cdsProdutoMov.ApplyUpdates(0) = 0) then
begin
resultado := true;
end;
end;
result := resultado;
end;
function TDMVendas.EstoqueBaixa(vIdProduto, vIdDeposito: integer; vCustoCif,
vCustoFob, vQtde: Real): boolean;
var
resultado: boolean;
begin
resultado := false;
cdsProdutoSaldo.Close;
cdsProdutoSaldo.Params.ParamByName('id_produto').AsInteger := vIdProduto;
cdsProdutoSaldo.Params.ParamByName('id_deposito').AsInteger := vIdDeposito;
cdsProdutoSaldo.Open;
cdsProdutoSaldo.Refresh;
//DeltaDS.FieldByName('qtde').OldValue
//DeltaDS.FieldByName('custofob').OldValue
//DeltaDS.FieldByName('custo').OldValue
cdsProdutoSaldo.Edit;
cdsProdutoSaldo.FieldByName('saldo').AsFloat := cdsProdutoSaldo.FieldByName('saldo').AsFloat - vQtde;
cdsProdutoSaldo.FieldbyName('bloq').asFloat := cdsProdutoSaldo.FieldbyName('bloq').asFloat - vQtde;
cdsProdutoSaldo.FieldByName('totalfob').AsFloat := cdsProdutoSaldo.FieldByName('totalfob').AsFloat - ( vQtde * vCustoFOB);
cdsProdutoSaldo.FieldByName('totalcif').AsFloat := cdsProdutoSaldo.FieldByName('totalcif').AsFloat - ( vQtde * vCustoCIF);
cdsProdutoSaldo.Post;
if (cdsProdutoSaldo.ApplyUpdates(0) = 0) then
begin
resultado := true;
end
else
begin
gMsgErro := 'Erro al dar de baja el saldo del producto';
resultado := false;
end;
result := resultado;
end;
function TDMVendas.AtualizaProduto(lOperacao: string; lCodigo: Integer;
lqtde: Real;lDeposito: integer):boolean;
var
saldo,
bloq,
saldoDisponivel: Real;
begin
gMsgErro := '';
saldo := 0;
saldoDisponivel := 0;
cdsProdutoSaldo.Close;
cdsProdutoSaldo.ParamByName('id_produto').AsInteger := lCodigo;
cdsProdutoSaldo.ParamByName('id_deposito').AsInteger := lDeposito;
cdsProdutoSaldo.Open;
if lOperacao = '+' then
begin
saldo := cdsProdutoSaldo.FieldByName('saldo').asFloat;
bloq := cdsProdutoSaldo.FieldByName('bloq').AsFloat;
saldoDisponivel := saldo - bloq;
if saldoDisponivel >= (lqtde) then
begin
cdsProdutoSaldo.Edit;
cdsProdutoSaldo.FieldByName('bloq').asFloat := cdsProdutoSaldo.FieldByName('bloq').asFloat + lqtde;
cdsProdutoSaldo.Post;
if cdsProdutoSaldo.ApplyUpdates(0) = 0 then
begin
gMsgErro := '';
result := true;
end
else
begin
gMsgErro := 'Apply nao funcionou';
result := false;
end;
end
else
begin
gMsgErro := 'Saldo insuficiente';
result := false;
end;
end
else if lOperacao = '-' then
begin
cdsProdutoSaldo.Edit;
cdsProdutoSaldo.FieldByName('bloq').asFloat := cdsProdutoSaldo.FieldByName('bloq').asFloat - lqtde;
cdsProdutoSaldo.Post;
if cdsProdutoSaldo.ApplyUpdates(0) = 0 then
begin
gMsgErro := '';
result := true;
end
else
begin
gMsgErro := 'Apply PARA DESBLOQUEAR PRODUTO NAO FUNCIONOU funcionou';
result := false;
end;
end;
end;
function TDMVendas.EstoqueVendaHistorico(
DeltaDS: TCustomClientDataset): boolean;
var
resultado : boolean;
begin
resultado := false;
qGenerica.close;
qGenerica.SQL.Clear;
qGenerica.SQL.Add('select numero,condpag,id_usuario,id_vendedor,id_cliente,id_moeda from venda where id_venda = :id_venda');
qGenerica.Params.ParamByName('id_venda').AsInteger := DeltaDS.FieldByName('id_venda').OldValue;
qGenerica.Open();
qGenerica.Refresh;
if qGenerica.RecordCount > 0 then
begin
cdsVendaHistorico.Close;
cdsVendaHistorico.Params.ParamByName('id_venda_historico').AsInteger := -1;
cdsVendaHistorico.Open;
cdsVendaHistorico.Append;
cdsVendaHistorico.fieldbyname('id_venda').AsInteger := DeltaDS.FieldByName('id_venda').OldValue;
cdsVendaHistorico.fieldbyname('id_cliente').AsInteger := qGenerica.FieldByName('id_cliente').asInteger;
cdsVendaHistorico.fieldbyname('id_produto').AsInteger := DeltaDS.FieldByName('id_produto').OldValue;
cdsVendaHistorico.fieldbyname('qtde').AsFloat := DeltaDS.FieldByName('qtde').OldValue;
cdsVendaHistorico.fieldbyname('preco').AsFloat := DeltaDS.FieldByName('preco_moeda').oldValue;
cdsVendaHistorico.FieldByName('data').AsDateTime := fnGetDataHora;
cdsVendaHistorico.FieldByName('id_moeda').AsInteger := qGenerica.FieldByName('id_moeda').asInteger;
cdsVendaHistorico.FieldByName('cambio').asFloat := 1;
cdsVendaHistorico.FieldByName('status').AsInteger := 6;
cdsVendaHistorico.Post;
if (cdsVendaHistorico.ApplyUpdates(0) = 0) then
begin
resultado := true;
end;
end;
Result := resultado;
end;
function TDMVendas.EstoqueProdutoDataVenta(
DeltaDS: TCustomClientDataSet): boolean;
var
resultado: boolean;
begin
resultado := false;
cdsProduto.Close;
cdsProduto.Params.ParamByName('id_produto').asInteger := DeltaDS.FieldByName('id_produto').OldValue;
cdsProduto.Open;
if cdsProduto.RecordCount > 0 then
begin
cdsProduto.Edit;
cdsProduto.FieldByName('dt_uv').AsDateTime := fnGetDataHora;
cdsProduto.Post;
if (cdsProduto.ApplyUpdates(0) = 0) then
begin
resultado := true;
end;
end;
Result := resultado;
end;
procedure TDMVendas.dspVendaBeforeUpdateRecord(Sender: TObject;
SourceDS: TDataSet; DeltaDS: TCustomClientDataSet; UpdateKind: TUpdateKind;
var Applied: Boolean);
var
id_produto: integer;
id_deposito: integer;
qtde_new : Real;
qtde_old : Real;
qtde_dif : Real;
qtde_del : Real;
preco_new : Real;
preco_old : Real;
pus1,pus2,pus3: Real;
Status: TField;
envia_pacote: boolean;
estoque_baixa,
estoque_mov,
estoque_his,
estoque_pro: boolean;
Tree, ParentTree: TUpdateTree;
begin
pus1 := 0;
pus2 := 0;
pus3 := 0;
envia_pacote := false;
if SourceDS.Name = 'qVenda' then
begin
if UpdateKind = ukInsert then
begin
DeltaDs.Edit;
DeltaDS.FieldByName('numero').AsInteger := retornaID('numero_venda');
DeltaDS.FieldByName('exclusivo').AsBoolean := true;
DeltaDS.Post;
Applied := false;
end
else if UpdateKind = ukModify then
begin
// //SE A PARTIR DE AGORA TIVER ID_TIMBRADO GERAR FATURA LEGAL.
// if DeltaDS.FieldByName('id_timbrado').NewValue > 0 then
// begin
// if GerarFaturaLegal(DeltaDS) then
// begin
// Applied := false;
// end
// else
// begin
// Applied := True;
// raise Exception.Create('Erro ao gerar fatura:' + gMsgErro );
// end;
//
// end
// else
// begin
// //se nao for pra gerar fatura e passar no cabecalho
// //dar um applied false para gravar os dados
// Applied := false;
// end;
applied := false;
end;
end
else if SourceDS.Name = 'qVendaItem' then
begin
Tree := FindDeltaUpdateTree(TDataSetProvider(Sender).Resolver.UpdateTree, DeltaDS);
if Assigned(Tree) then
begin
ParentTree := Tree.Parent;
// here you can use ParentTree.Source (the dataset) and ParentTree.Delta (the delta)
end;
//DELTADS representa o item corrente
//ELE VAI ENTRAR AQUI EM TRES SITUAÇÕES
//1 - QUANDO ESTIVER NA VENDA E INSERIR UM ITEM
//2 - QUANDO ESTIVER NA VENDA E MODIFICAR UM ITEM
//3 - QUANDO ESTIVER NO CAIXA E MUDAR O STATUS PARA PAGO
if not ParentTree.Delta.FieldByName('orcamento').AsBoolean then
begin
id_produto := DeltaDS.FieldByName('id_produto').oldValue;
if UpdateKind = ukInsert then
begin
//ORIGEM NA VENDA
//ORIGEM NUNCA VAI VIR DO CAIXA
qtde_new := DeltaDS.FieldByName('qtde').NewValue;
id_deposito := DeltaDS.FieldByName('id_deposito').NewValue;
if AtualizaProduto('+',id_produto,qtde_new,id_deposito) then
begin
//AO CONTRARIO
Applied := False;
end
else
begin
raise Exception.Create('Erro: '+gMsgErro);
Applied := True;
end;
end
else if UPdateKind = ukModify then
begin
//VAI ENTRAR AQUI QUANDO HOUVER QUALQUER ALTERAÇÃO NO ITEM
//SEJA DIRETO PELA VENDA
//SEJA NO CAIXA QUANDO RECEBER A NOTA
if (DeltaDS.FieldByname('status').asInteger = 1) or (DeltaDS.FieldByname('status').asInteger = 0) then
begin
qtde_new := DeltaDS.FieldByName('qtde').NewValue;
qtde_old := DeltaDS.FieldByName('qtde').OldValue;
id_deposito := DeltaDS.FieldByName('id_deposito').OldValue;
if (qtde_new <> qtde_old) and (qtde_new <> 0) then
begin
qtde_dif := qtde_new - qtde_old;
if qtde_dif > 0 then
begin
if AtualizaProduto('+',id_produto, qtde_dif,id_deposito) then
begin
//AO CONTRARIO
Applied := False;
end
else
begin
raise Exception.Create('Erro: '+gMsgErro);
Applied := True;
end;
end
else if qtde_dif < 0 then
begin
qtde_dif := qtde_dif * -1;
if AtualizaProduto('-',id_produto, qtde_dif,id_deposito) then
begin
//AO CONTRARIO
Applied := False;
end
else
begin
raise Exception.Create('Erro: '+gMsgErro);
Applied := True;
end;
end;
end;
preco_new := DeltaDS.FieldByName('preco_normal').NewValue;
preco_old := DeltaDS.FieldByName('preco_normal').OldValue;
if (preco_new <> preco_old) and (preco_new > 0) then
begin
//enviar mensagem para o gerente
//consultar se o preço do produto é esse mesmo, se for menor que o preço atual
//do produto, solicitar gerente para autorizaçao
qGenerica.close;
qGenerica.SQL.Clear;
qGenerica.SQL.Add('select id_produto,pus1,pus2,pus3 from produto where id_produto = :codigo ');
qGenerica.Params.ParamByName('codigo').AsInteger := id_produto;
qGenerica.Open();
qGenerica.Refresh;
pus1 := qgenerica.FieldByName('pus1').AsFloat;
pus2 := qGenerica.FieldByName('pus2').AsFloat;
pus3 := qGenerica.FieldByName('pus3').AsFloat;
//se tem cliente cadastrado o limite é definido pelo cadastro do cliente
//VER COM LAERCIO
//se nao cliente , o limite é pus1,pus2,pus3 (se preço é menor que pus1, pede aut)
if preco_new < pus1 then
begin
DeltaDS.FieldByName('status').NewValue := 10;
Applied := false;
// raise Exception.Create('AUTORIZACAODEPRECO');
end
else
begin
end;
end;
end
else
begin
if DeltaDS.FieldByname('status').asInteger = -1 then
begin
//status mudado para "anulado" entao devolver as quantidades para o estoque
//igual quando apaga o item
//ver quantidade
//diminuir a quantidade do estoque
//dar applied false
qtde_del := DeltaDS.FieldByName('qtde').OldValue;
id_deposito := DeltaDS.FieldByName('id_deposito').OldValue;
AtualizaProduto('-',id_produto, qtde_del,id_deposito);
end
else if DeltaDS.FieldByname('status').asInteger = 6 then
begin
//dar baixa do estoque dessa mercadoria
id_deposito := DeltaDS.FieldByName('id_deposito').OldValue;
estoque_baixa := false;
estoque_mov := false;
estoque_his := false;
estoque_pro := false;
estoque_baixa := EstoqueBaixa(id_produto,id_deposito,DeltaDS.FieldByName('custo').oldvalue,DeltaDS.FieldByName('custofob').oldvalue,DeltaDs.Fieldbyname('qtde').oldvalue);
estoque_mov := EstoqueMov(DeltaDS);
estoque_his := EstoqueVendaHistorico(DeltaDS);
estoque_pro := EstoqueProdutoDataVenta(DeltaDS);
//if estoque_baixa and estoque_mov and estoque_his and estoque_pro then
if estoque_baixa and estoque_mov and estoque_his and estoque_pro then
begin
Applied := False;
end
else
begin
Applied := true;
raise Exception.Create('Erro Grave: ' + gMsgErro );
end;
end;
end;
end
else if UPdateKind = ukDelete then
begin
qtde_del := DeltaDS.FieldByName('qtde').NewValue;
id_deposito := DeltaDS.FieldByName('id_deposito').OldValue;
AtualizaProduto('-',id_produto, qtde_del,id_deposito);
end;
end;
end;
end;
function TDMVendas.retornaID(NomeCampo: String): integer;
begin
//QUEM DEVE NUMERAR DEVE SER O SERVIDOR
//QUEM DEVE numero as chaves primarias é os CLIENTes
//ESTA FUNCAO DEVE NUMERAR APENAS CHAVES PRIMARIAS
cdsControle.Close;
cdsControle.Params.ParamByName('nomecampo').AsString := NomeCampo;
cdsControle.Open;
cdsControle.Refresh;
cdsControle.Edit;
cdsControle.fieldbyname('valor').AsInteger := cdsControle.fieldbyname('valor').AsInteger + 1;
cdsControle.Post;
if cdsControle.ApplyUpdates(0) <> 0 then
begin
retornaID(NomeCampo);
end;
result := cdsControle.fieldbyname('valor').AsInteger;
end;
function TDMVendas.consultaCliente(lCampo,lValor:string): OleVariant;
var
sql: ansistring;
begin
sql := 'select CL.id_cliente, CL.nome,CL.tolerancia_dias, CL.endereco,';
sql := sql + ' CL.limitecredito, VN.Vencimento as UltVencimento, ';
sql := sql + ' CL.documento1,CL.documento2, CL.bloq_tolerancia,CL.bloq_tolerancia_autorizado,CL.bloq_limite,CL.bloq_limite_autorizado,';
sql := sql + ' CL.razaosocial,CL.telefone,CL.Celular,CL.condpag,CL.condpag_prazo, CL.nivelpreco, CL.desconto_porcentagem,';
sql := sql + ' DATEDIFF(day,VN.vencimento,getdate()) as TempoVencido, ';
sql := sql + ' sum(CR.valor-(coalesce(CR.valor_pago,0)-coalesce(cr.desconto,0))) as EmAberto,';
sql := sql + ' (case when CL.limitecredito > 0 then (CL.limitecredito - coalesce(sum(CR.valor-(coalesce(CR.valor_pago,0)-coalesce(cr.desconto,0))),0)) else 0 end) as SaldoDisponivel ';
sql := sql + ' from cliente CL ';
sql := sql + ' left join conta_receber CR on (CR.id_cliente = CL.id_cliente) ';
sql := sql + ' left join (select id_cliente, min(data_vencimento) as vencimento from conta_receber group by id_cliente) VN on (VN.id_cliente = CR.id_cliente) ';
sql := sql + ' where CL.'+lcampo+' like '+quotedstr('%'+lValor+'%');
sql := sql + ' group by CL.id_cliente, CL.nome,CL.limitecredito,CL.tolerancia_dias, CL.endereco, CL.documento1,CL.desconto_porcentagem, ';
sql := sql + ' CL.bloq_tolerancia,CL.bloq_tolerancia_autorizado,CL.nivelpreco,CL.bloq_limite,CL.bloq_limite_autorizado,CL.documento2, CL.razaosocial,CL.telefone,CL.Celular,CL.condpag,CL.condpag_prazo,VN.vencimento ';
sql := sql + ' order by CL.nome ';
qGenerica.Close;
qGenerica.SQL.clear;
qGenerica.SQL.Add(sql);
cdsGenerica.close;
cdsGenerica.Open;
cdsGenerica.Refresh;
result := cdsGenerica.Data;
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP Fenix
Description: Controller relacionado à tabela [FIN_CHEQUE_RECEBIDO]
The MIT License
Copyright: Copyright (C) 2020 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (alberteije@gmail.com)
@version 1.0.0
*******************************************************************************}
unit FinChequeRecebidoController;
interface
uses mvcframework, mvcframework.Commons,
System.SysUtils,
MVCFramework.SystemJSONUtils;
type
[MVCDoc('CRUD FinChequeRecebido')]
[MVCPath('/fin-cheque-recebido')]
TFinChequeRecebidoController = class(TMVCController)
public
[MVCDoc('Retorna uma lista de objetos')]
[MVCPath('/($filtro)')]
[MVCHTTPMethod([httpGET])]
procedure ConsultarLista(Context: TWebContext);
[MVCDoc('Retorna um objeto com base no ID')]
[MVCPath('/($id)')]
[MVCHTTPMethod([httpGET])]
procedure ConsultarObjeto(id: Integer);
[MVCDoc('Insere um novo objeto')]
[MVCPath]
[MVCHTTPMethod([httpPOST])]
procedure Inserir(Context: TWebContext);
[MVCDoc('Altera um objeto com base no ID')]
[MVCPath('/($id)')]
[MVCHTTPMethod([httpPUT])]
procedure Alterar(id: Integer);
[MVCDoc('Exclui um objeto com base no ID')]
[MVCPath('/($id)')]
[MVCHTTPMethod([httpDelete])]
procedure Excluir(id: Integer);
end;
implementation
{ TFinChequeRecebidoController }
uses FinChequeRecebidoService, FinChequeRecebido, Commons, Filtro;
procedure TFinChequeRecebidoController.ConsultarLista(Context: TWebContext);
var
FiltroUrl, FilterWhere: string;
FiltroObj: TFiltro;
begin
FiltroUrl := Context.Request.Params['filtro'];
if FiltroUrl <> '' then
begin
ConsultarObjeto(StrToInt(FiltroUrl));
exit;
end;
filterWhere := Context.Request.Params['filter'];
try
if FilterWhere = '' then
begin
Render<TFinChequeRecebido>(TFinChequeRecebidoService.ConsultarLista);
end
else begin
// define o objeto filtro
FiltroObj := TFiltro.Create(FilterWhere);
Render<TFinChequeRecebido>(TFinChequeRecebidoService.ConsultarListaFiltroValor(FiltroObj.Campo, FiltroObj.Valor));
end;
except
on E: EServiceException do
begin
raise EMVCException.Create
('Erro no Servidor [Consultar Lista FinChequeRecebido] - Exceção: ' + E.Message,
E.StackTrace, 0, 500);
end
else
raise;
end;
end;
procedure TFinChequeRecebidoController.ConsultarObjeto(id: Integer);
var
FinChequeRecebido: TFinChequeRecebido;
begin
try
FinChequeRecebido := TFinChequeRecebidoService.ConsultarObjeto(id);
if Assigned(FinChequeRecebido) then
Render(FinChequeRecebido)
else
raise EMVCException.Create
('Registro não localizado [Consultar Objeto FinChequeRecebido]', '', 0, 404);
except
on E: EServiceException do
begin
raise EMVCException.Create
('Erro no Servidor [Consultar Objeto FinChequeRecebido] - Exceção: ' + E.Message,
E.StackTrace, 0, 500);
end
else
raise;
end;
end;
procedure TFinChequeRecebidoController.Inserir(Context: TWebContext);
var
FinChequeRecebido: TFinChequeRecebido;
begin
try
FinChequeRecebido := Context.Request.BodyAs<TFinChequeRecebido>;
except
on E: EServiceException do
begin
raise EMVCException.Create('Objeto inválido [Inserir FinChequeRecebido] - Exceção: ' +
E.Message, E.StackTrace, 0, 400);
end
else
raise;
end;
try
TFinChequeRecebidoService.Inserir(FinChequeRecebido);
Render(TFinChequeRecebidoService.ConsultarObjeto(FinChequeRecebido.Id));
finally
end;
end;
procedure TFinChequeRecebidoController.Alterar(id: Integer);
var
FinChequeRecebido, FinChequeRecebidoDB: TFinChequeRecebido;
begin
try
FinChequeRecebido := Context.Request.BodyAs<TFinChequeRecebido>;
except
on E: EServiceException do
begin
raise EMVCException.Create('Objeto inválido [Alterar FinChequeRecebido] - Exceção: ' +
E.Message, E.StackTrace, 0, 400);
end
else
raise;
end;
if FinChequeRecebido.Id <> id then
raise EMVCException.Create('Objeto inválido [Alterar FinChequeRecebido] - ID do objeto difere do ID da URL.',
'', 0, 400);
FinChequeRecebidoDB := TFinChequeRecebidoService.ConsultarObjeto(FinChequeRecebido.id);
if not Assigned(FinChequeRecebidoDB) then
raise EMVCException.Create('Objeto com ID inválido [Alterar FinChequeRecebido]',
'', 0, 400);
try
if TFinChequeRecebidoService.Alterar(FinChequeRecebido) > 0 then
Render(TFinChequeRecebidoService.ConsultarObjeto(FinChequeRecebido.Id))
else
raise EMVCException.Create('Nenhum registro foi alterado [Alterar FinChequeRecebido]',
'', 0, 500);
finally
FreeAndNil(FinChequeRecebidoDB);
end;
end;
procedure TFinChequeRecebidoController.Excluir(id: Integer);
var
FinChequeRecebido: TFinChequeRecebido;
begin
FinChequeRecebido := TFinChequeRecebidoService.ConsultarObjeto(id);
if not Assigned(FinChequeRecebido) then
raise EMVCException.Create('Objeto com ID inválido [Excluir FinChequeRecebido]',
'', 0, 400);
try
if TFinChequeRecebidoService.Excluir(FinChequeRecebido) > 0 then
Render(200, 'Objeto excluído com sucesso.')
else
raise EMVCException.Create('Nenhum registro foi excluído [Excluir FinChequeRecebido]',
'', 0, 500);
finally
FreeAndNil(FinChequeRecebido)
end;
end;
end.
|
unit acAlphaImageList;
{$I sDefs.inc}
interface
uses
Windows, Classes, SysUtils, Controls, Graphics, CommCtrl, ImgList, ComCtrls, sConst, acPNG, acntUtils;
type
TsImageFormat = (ifPNG, ifICO);
{$IFNDEF NOTFORHELP}
TsAlphaImageList = class;
TsImgListItems = class;
TsImgListItem = class(TCollectionItem)
private
FImageFormat: TsImageFormat;
FPixelFormat: TPixelFormat;
protected
FOwner : TsImgListItems;
procedure DefineProperties(Filer: TFiler); override;
procedure ReadData(Reader: TStream);
procedure WriteData(Writer: TStream);
public
ImgData : TMemoryStream;
procedure Assign(Source: TPersistent); override;
procedure AssignTo(Dest: TPersistent); override;
destructor Destroy; override;
constructor Create(Collection: TCollection); override;
published
property ImageFormat : TsImageFormat read FImageFormat write FImageFormat;
property PixelFormat : TPixelFormat read FPixelFormat write FPixelFormat default pf32bit;
end;
TsImgListItems = class(TCollection)
protected
FOwner: TsAlphaImageList;
function GetItem(Index: Integer): TsImgListItem;
procedure SetItem(Index: Integer; Value: TsImgListItem);
function GetOwner: TPersistent; override;
public
constructor Create(AOwner : TsAlphaImageList);
destructor Destroy; override;
property Items[Index: Integer]: TsImgListItem read GetItem write SetItem; default;
end;
{$ENDIF}
TsAlphaImageList = class(TImageList)
{$IFNDEF NOTFORHELP}
private
FItems: TsImgListItems;
StdListIsGenerated : boolean;
AcChanging : boolean;
procedure SetItems(const Value: TsImgListItems);
protected
procedure CreateImgList;
procedure Change; override;
procedure DoDraw(Index: Integer; Canvas: TCanvas; X, Y: Integer; Style: Cardinal; Enabled: Boolean = True); override;
procedure KillImgList;
function IsDuplicated : boolean;
function TryLoadFromFile(const FileName : acString) : boolean;
{$IFDEF DELPHI7UP}
procedure ReadData(Stream: TStream); override;
procedure WriteData(Stream: TStream); override;
{$ENDIF}
procedure ItemsClear;
public
DoubleData : boolean;
procedure AcBeginUpdate;
procedure AcEndUpdate(DoChange : boolean = True);
procedure AfterConstruction; override;
procedure Assign(Source: TPersistent); override;
procedure AssignTo(Dest: TPersistent); override;
procedure CopyImages(const ImgList : TsAlphaImageList);
constructor Create(AOwner : TComponent); override;
destructor Destroy; override;
procedure GenerateStdList;
function GetBitmap32(Index: Integer; Image: TBitmap): Boolean;
procedure Loaded; override;
procedure LoadFromFile(const FileName : acString);
procedure SetNewDimensions(Value: HImageList);
published
property Items : TsImgListItems read FItems write SetItems;
{$ENDIF}
end;
{$IFNDEF NOTFORHELP}
function GetImageFormat(const FileName : acString; var ImageFormat : TsImageFormat) : boolean;
function DrawAlphaImgList(const ImgList : TCustomImageList; const DestBmp : TBitmap; const Left : integer; const Top : integer;
const ImageIndex : integer; const Blend : integer; const GrayedColor : TColor; State : integer; const NumGlyphs : integer; const Reflected : boolean) : TSize;
procedure DrawAlphaImgListDC(const ImgList : TCustomImageList; const DC : hdc; const Left : integer; const Top : integer;
const ImageIndex : integer; const Blend : integer; const GrayedColor : TColor; const State : integer; const NumGlyphs : integer; const Reflected : boolean);
function HaveMagic(const FileName : string; const Magic: Pointer; const Size : integer): Boolean;
{$ENDIF}
function AddImageFromRes(aInstance: LongWord; ImageList : TsAlphaimageList; const ResName: String; ImageFormat : TsImageFormat): Boolean; // Png must be compiled in resource as RcData
implementation
uses math, ShellAPI, sGraphUtils, Dialogs, Forms, sAlphaGraph;
{ TsAlphaImageList }
function GetBpp : integer;
var
ScreenDC : hdc;
begin
ScreenDC := GetDC(0);
try
Result := GetDeviceCaps(ScreenDC, BITSPIXEL);
finally
ReleaseDC(0, ScreenDC)
end;
end;
function GetImageFormat(const FileName : acString; var ImageFormat : TsImageFormat) : boolean;
const
IcoMagic: array[0..1] of Byte = (0, 0);
var
s : string;
begin
Result := False;
// Check format
if HaveMagic(FileName, @PNGMagic, 8) then begin // Png
ImageFormat := ifPNG;
Result := True;
end
else if HaveMagic(FileName, @IcoMagic, 2) then begin // Ico
s := LowerCase(ExtractFileExt(FileName));
System.Delete(s, 1, 1);
if s = acIcoExt then begin
ImageFormat := ifICO;
Result := True;
end;
end;
end;
function DrawAlphaImgList(const ImgList : TCustomImageList; const DestBmp : TBitmap; const Left : integer; const Top : integer;
const ImageIndex : integer; const Blend : integer; const GrayedColor : TColor; State : integer; const NumGlyphs : integer; const Reflected : boolean) : TSize;
var
Bmp : TBitmap;
w, Count : integer;
R1, R2 : TRect;
begin
if (DestBmp.Width = 0) or not ImgList.HandleAllocated then Exit;
// if ImgList.Width mod ImgList.Height = 0 then Count := ImgList.Width div ImgList.Height else Count := 1;
Count := NumGlyphs;
w := ImgList.Width div Count;
if State >= Count then State := Count - 1;
R1 := Rect(Left, Top, Left + w, Top + ImgList.Height);
R2 := Rect(0, 0, w, ImgList.Height);
Result.cx := w;
Result.cy := ImgList.Height;
OffsetRect(R2, w * State, 0);
if ImgList is TsAlphaImageList then begin
Bmp := CreateBmp32(ImgList.Width, ImgList.Height);
if TsAlphaImageList(ImgList).GetBitmap32(ImageIndex, Bmp) then begin
CopyBmp32(R1, R2, DestBmp, Bmp, EmptyCI, False, GrayedColor, Blend, Reflected)
end;
end
else begin
Bmp := CreateBmp32(ImgList.Width, ImgList.Height);
if True{(Blend = 0) and (GrayedColor = clNone) not supported in standard imagelist std mode v6} then begin
BitBlt(Bmp.Canvas.Handle, R2.Left, R2.Top, WidthOf(R2), HeightOf(R2), DestBmp.Canvas.Handle, R1.Left, R1.Top, SRCCOPY);
ImgList.Draw(Bmp.Canvas, 0, 0, ImageIndex, True);
BitBlt(DestBmp.Canvas.Handle, R1.Left, R1.Top, WidthOf(R2), HeightOf(R2), Bmp.Canvas.Handle, R2.Left, R2.Top, SRCCOPY);
end
else begin
{ if Bmp.PixelFormat = pf32bit then begin
CopyBmp32(R1, R2, DestBmp, Bmp, EmptyCI, False, GrayedColor, Blend);
end
else begin
Bmp.Transparent := True;
Bmp.TransparentColor := clFuchsia;
CopyTransRect(DestBmp, Bmp, R1.Left, R1.Top, R2, clFuchsia, EmptyCI, False);
end; not supported in standard imagelist std mode v6}
end;
end;
if Bmp <> nil then FreeAndNil(Bmp);
end;
procedure DrawAlphaImgListDC(const ImgList : TCustomImageList; const DC : hdc; const Left : integer; const Top : integer;
const ImageIndex : integer; const Blend : integer; const GrayedColor : TColor; const State : integer; const NumGlyphs : integer; const Reflected : boolean);
var
Bmp : TBitmap;
Size : TSize;
begin
Bmp := CreateBmp32(ImgList.Width, ImgList.Height + Integer(Reflected) * ImgList.Height div 2);
BitBlt(Bmp.Canvas.Handle, 0, 0, Bmp.Width, Bmp.Height, DC, Left, Top, SRCCOPY);
Size := DrawAlphaImgList(ImgList, Bmp, 0, 0, ImageIndex, Blend, GrayedColor, State, NumGlyphs, Reflected);
BitBlt(DC, Left, Top, Bmp.Width, Bmp.Height, Bmp.Canvas.Handle, 0, 0, SRCCOPY);
FreeAndNil(Bmp);
end;
function HaveMagic(const FileName : string; const Magic: Pointer; const Size : integer): Boolean;
var
MagicBuf: array[0..7] of Byte;
Stream: TFileStream;
len: integer;
begin
FillChar(MagicBuf, 8, #0);
Stream := TFileStream.Create(FileName, fmOpenRead or fmShareDenyWrite);
try
len := min(Size, SizeOf(MagicBuf));
Result := (Stream.Size - Stream.Position) > len;
if Result then begin
Stream.ReadBuffer(MagicBuf, len);
Result := CompareMem(@MagicBuf, Magic, len);
end;
finally
FreeAndNil(Stream);
end;
end;
function AddImageFromRes(aInstance: LongWord; ImageList : TsAlphaimageList; const ResName: String; ImageFormat : TsImageFormat): Boolean;
var
hIc : HICON;
Png : TPNGGraphic;
rs : TResourceStream;
Ico : hIcon;
begin
Result := False;
if ImageFormat = ifICO then begin
hIc := LoadImage(aInstance, PChar(ResName), IMAGE_ICON, ImageList.Width, ImageList.Height, 0);
if hIc = 0 then Exit;
try
if ImageList_AddIcon(ImageList.Handle, hIc) <> -1 then begin
// (Items.Add as TsImgListItem).ProcessIcon(hIc);
Result := True;
end;
finally
DestroyIcon(hIc);
end;
end
else begin
Png := TPNGGraphic.Create;
rs := TResourceStream.Create(aInstance, ResName, RT_RCDATA);
Png.LoadFromStream(rs);
FreeAndNil(rs);
Ico := MakeIcon32(Png);
Result := ImageList_AddIcon(ImageList.Handle, Ico) <> -1;
DestroyIcon(Ico);
FreeAndNil(Png);
end;
end;
procedure TsAlphaImageList.AfterConstruction;
begin
inherited;
if not (csLoading in ComponentState) then begin
if not HandleAllocated then CreateImgList;
if not StdListIsGenerated then GenerateStdList;
end;
end;
function GetColor(Value: DWORD): TColor;
begin
case Value of
CLR_NONE: Result := clNone;
CLR_DEFAULT: Result := clDefault;
else
Result := TColor(Value);
end;
end;
procedure TsAlphaImageList.Assign(Source: TPersistent);
var
ImageList: TsAlphaImageList;
begin
if Source = nil then KillImgList else if Source is TsAlphaImageList then begin
AcBeginUpdate;
Clear;
ImageList := TsAlphaImageList(Source);
Masked := ImageList.Masked;
ImageType := ImageList.ImageType;
DrawingStyle := ImageList.DrawingStyle;
ShareImages := ImageList.ShareImages;
SetNewDimensions(ImageList.Handle);
KillImgList;
if not HandleAllocated then CreateImgList else ImageList_SetIconSize(Handle, Width, Height);
BkColor := GetColor(ImageList_GetBkColor(ImageList.Handle));
BlendColor := ImageList.BlendColor;
CopyImages(ImageList);
AcEndUpdate(False);
end
else inherited Assign(Source);
end;
procedure TsAlphaImageList.AssignTo(Dest: TPersistent);
var
ImageList: TsAlphaImageList;
begin
if Dest is TsAlphaImageList then begin
ImageList := TsAlphaImageList(Dest);
ImageList.AcBeginUpdate;
ImageList.Masked := Masked;
ImageList.ImageType := ImageType;
ImageList.DrawingStyle := DrawingStyle;
ImageList.ShareImages := ShareImages;
ImageList.BlendColor := BlendColor;
with ImageList do begin
Clear;
ImageList.KillImgList;
SetNewDimensions(Self.Handle);
if not HandleAllocated then CreateImgList else ImageList_SetIconSize(Handle, Width, Height);
BkColor := GetColor(ImageList_GetBkColor(Self.Handle));
ImageList.CopyImages(Self);
end;
ImageList.AcEndUpdate(False);
end
else inherited AssignTo(Dest);
end;
procedure TsAlphaImageList.CopyImages(const ImgList: TsAlphaImageList);
var
i : integer;
Ico : hIcon;
begin
if not HandleAllocated then Exit;
ImageList_SetBkColor(ImgList.Handle, CLR_NONE);
if IsDuplicated then begin
Items.Clear;
for i := 0 to ImgList.Items.Count - 1 do begin
with TsImgListItem(Items.Add) do begin
ImageFormat := ImgList.Items[i].ImageFormat;
PixelFormat := ImgList.Items[i].PixelFormat;
ImgData.LoadFromStream(ImgList.Items[i].ImgData);
end;
end;
GenerateStdList;
end
else begin
Clear;
ImageList_SetBkColor(Handle, CLR_NONE);
for i := 0 to ImgList.Count - 1 do begin
Ico := ImageList_GetIcon(ImgList.Handle, i, ILD_TRANSPARENT);
ImageList_AddIcon(Handle, Ico);
DestroyIcon(Ico);
end;
end;
end;
constructor TsAlphaImageList.Create(AOwner: TComponent);
begin
inherited;
FItems := TsImgListItems.Create(Self);
DoubleData := True;
end;
procedure TsAlphaImageList.CreateImgList;
begin
Handle := ImageList_Create(Width, Height, ILC_COLOR32 or (Integer(Masked) * ILC_MASK), 0, AllocBy);
// ImageList_SetBkColor(Handle, CLR_NONE);
end;
destructor TsAlphaImageList.Destroy;
begin
FreeAndNil(FItems);
inherited;
end;
procedure TsAlphaImageList.DoDraw(Index: Integer; Canvas: TCanvas; X, Y: Integer; Style: Cardinal; Enabled: Boolean);
var
Ico : hIcon;
TmpBmp, Bmp : TBitmap;
begin
if HandleAllocated then begin
if (Items.Count > Index) and (Items[Index].ImageFormat = ifPng) then begin
// Experimental code
Bmp := CreateBmp32(Width, Height);
Bmp.Canvas.Lock;
try
if GetBitmap32(Index, Bmp) then begin
TmpBmp := CreateBmp32(Width, Height);
TmpBmp.Canvas.Lock;
try
BitBlt(TmpBmp.Canvas.Handle, 0, 0, Width, Height, Canvas.Handle, X, Y, SRCCOPY);
CopyBmp32(Rect(0, 0, Width, Height), Rect(0, 0, Width, Height), TmpBmp, Bmp, MakeCacheInfo(TmpBmp), False, clNone, 0, False);
BitBlt(Canvas.Handle, X, Y, Width, Height, TmpBmp.Canvas.Handle, 0, 0, SRCCOPY);
finally
TmpBmp.Canvas.Unlock;
FreeAndNil(TmpBmp);
end;
end;
finally
Bmp.Canvas.Unlock;
FreeAndNil(Bmp);
end;
end
else begin
ImageList_SetBkColor(Handle, CLR_NONE);
Ico := ImageList_GetIcon(Handle, Index, ILD_TRANSPARENT);
if (Ico > 0) then begin
DrawIconEx(Canvas.Handle, X, Y, Ico, Width, Height, 0, 0, DI_NORMAL);
DestroyIcon(Ico);
end;
end;
end;
end;
procedure TsAlphaImageList.GenerateStdList;
var
i : integer;
Png : TPNGGraphic;
Icon : TIcon;
Ico : hIcon;
begin
if not HandleAllocated then Exit;
AcChanging := True;
Clear;
for i := 0 to Items.Count - 1 do begin
case Items[i].ImageFormat of
ifPNG : begin
Png := TPNGGraphic.Create;
Items[i].ImgData.Seek(0, 0);
Png.LoadFromStream(Items[i].ImgData);
{.$IFDEF DELPHI7UP}
if IsNTFamily
then Ico := MakeCompIcon(Png, ColorToRGB(TColor(ImageList_GetBkColor(Handle))))
else
{.$ENDIF}
Ico := MakeIcon32(Png);
ImageList_AddIcon(Handle, Ico);
DestroyIcon(Ico);
FreeAndNil(Png);
end;
ifICO : begin
Icon := TIcon.Create;
Items[i].ImgData.Seek(0, 0);
Icon.LoadFromStream(Items[i].ImgData);
ImageList_AddIcon(Handle, Icon.Handle);
FreeAndNil(Icon);
end;
end;
end;
if Items.Count > 0 then begin
StdListIsGenerated := True;
if not IsDuplicated then Items.Clear;
end;
AcChanging := False;
end;
function TsAlphaImageList.GetBitmap32(Index: Integer; Image: TBitmap): Boolean;
var
iInfo: TIconInfo;
Ico : hIcon;
TmpBmp : TBitmap;
Png : TPNGGraphic;
Color : TsColor;
TransColor : TColor;
S : PRGBAArray;
C : TsColor_;
procedure CorrectPixelFrmt(Bmp : TBitmap);
var
x, y : integer;
aFast32Src : TacFast32;
begin
TransColor := clFuchsia;
for Y := 0 to Bmp.Height - 1 do begin // Check if alphachannel if fully clear
S := Bmp.ScanLine[Y];
for X := 0 to Bmp.Width - 1 do begin
C := S[X];
if C.A <> 0 then begin
TransColor := clNone;
Break;
end;
end;
if TransColor = clNone then Break;
end;
if TransColor = clFuchsia then begin
TransColor := Bmp.Canvas.Pixels[0, Bmp.Height - 1];
aFast32Src := TacFast32.Create;
if aFast32Src.Attach(Bmp) then for X := 0 to Bmp.Width - 1 do for Y := 0 to Bmp.Height - 1 do begin
Color := aFast32Src[X, Y];
if Color.C <> TransColor then begin
Color.A := MaxByte;
aFast32Src[X, Y] := Color;
end;
end;
FreeAndNil(aFast32Src);
end;
end;
begin
Result := False;
if HandleAllocated and (Image <> nil) and (Index >= 0) and (Index < Count) then begin
if IsDuplicated and (Index < Items.Count) and (Items[Index].ImageFormat = ifPNG) and (Items[Index].ImgData.Size > 0) then begin // Using of original image if exists
Png := TPNGGraphic.Create;
Items[Index].ImgData.Seek(0, 0);
Png.LoadFromStream(Items[Index].ImgData);
if (Png.Width <> Width) or (Png.Height <> Height) then begin // If must be scaled
Image.PixelFormat := pf32bit;
Stretch(Png, Image, Image.Width, Image.Height, ftMitchell);
end
else Image.Assign(Png);
if Image.PixelFormat <> pf32bit then begin
Image.PixelFormat := pf32bit;
CorrectPixelFrmt(Image);
end;
FreeAndNil(Png);
Result := True;
end
else begin
Ico := ImageList_GetIcon(Handle, Index, ILD_NORMAL);
if Ico = 0 then Exit;
TmpBmp := CreateBmp32(Image.Width, Image.Height);
if GetIconInfo(Ico, iInfo) then begin
TmpBmp.Handle := iInfo.hbmColor;
TmpBmp.HandleType := bmDIB;
TmpBmp.PixelFormat := pf32bit;
if (Win32MajorVersion < 6) and (GetBpp < 32) then begin // Update alpha channel
CorrectPixelFrmt(TmpBmp);
end;
Image.Assign(TmpBmp);
DeleteObject(iInfo.hbmMask);
Result := True;
end;
FreeAndNil(TmpBmp);
DestroyIcon(Ico);
end;
end;
end;
function TsAlphaImageList.IsDuplicated: boolean;
begin
Result := DoubleData or (csDesigning in ComponentState);
end;
procedure TsAlphaImageList.KillImgList;
begin
if HandleAllocated and not ShareImages then ImageList_Destroy(Handle);
Handle := 0;
Change;
end;
procedure TsAlphaImageList.Loaded;
begin
inherited;
if not HandleAllocated then CreateImgList;
if not StdListIsGenerated then begin
GenerateStdList;
StdListIsGenerated := True; // Set the flag even if iconlist is empty
end;
end;
procedure TsAlphaImageList.LoadFromFile(const FileName: acString);
begin
if not TryLoadFromfile(FileName) then MessageDlg('Cannot load ' + FileName + #13#10 + 'Invalid or unexpected image format.', mtError, [mbOk], 0);
end;
{$IFDEF DELPHI7UP}
procedure TsAlphaImageList.ReadData(Stream: TStream);
begin
// All data is in Items
end;
procedure TsAlphaImageList.WriteData(Stream: TStream);
begin
// All data is in Items
end;
{$ENDIF}
procedure TsAlphaImageList.SetItems(const Value: TsImgListItems);
begin
FItems.Assign(Value);
end;
procedure TsAlphaImageList.SetNewDimensions(Value: HImageList);
var
AHeight, AWidth: Integer;
begin
AWidth := Width;
AHeight := Height;
ImageList_GetIconSize(Value, AWidth, AHeight);
Width := AWidth;
Height := AHeight;
end;
function TsAlphaImageList.TryLoadFromfile(const FileName: acString) : boolean;
var
Ico: HICON;
iInfo : TIconInfo;
Png : TPNGGraphic;
iFormat : TsImageFormat;
Bmp : TBitmap;
X, Y : integer;
BmpLine : PRGBAArray;
begin
Result := False;
Ico := 0;
if not HandleAllocated or not GetImageFormat(FileName, iFormat) then Exit;
if IsDuplicated then begin // If double data used
with TsImgListItem(Items.Add) do begin
ImgData.LoadFromFile(FileName);
ImageFormat := iFormat;
case iFormat of
ifPNG : begin
PixelFormat := pf32bit;
Png := TPNGGraphic.Create;
Png.LoadFromStream(ImgData);
Ico := MakeIcon32(Png);
FreeAndNil(Png);
end;
ifICO : begin
{$IFDEF TNTUNICODE}
Ico := ExtractIconW(hInstance, PacChar(FileName), 0);
{$ELSE}
Ico := ExtractIcon(hInstance, PacChar(FileName), 0);
{$ENDIF}
GetIconInfo(Ico, iInfo);
Bmp := TBitmap.Create;
Bmp.Handle := iInfo.hbmColor;
Bmp.HandleType := bmDIB;
PixelFormat := pf24bit;
if (Bmp.PixelFormat = pf32bit) then begin // Check the alpha channel
for Y := 0 to Bmp.Height - 1 do begin
BmpLine := Bmp.ScanLine[Y];
for X := 0 to Bmp.Width - 1 do if BmpLine[X].A <> 0 then begin
PixelFormat := pf32bit;
Break;
end;
if PixelFormat = pf32bit then Break;
end;
end;
FreeAndNil(Bmp);
DeleteObject(iInfo.hbmColor);
DeleteObject(iInfo.hbmMask);
end;
end;
end;
end
else begin
case iFormat of
ifPNG : begin
Png := TPNGGraphic.Create;
Png.LoadFromFile(FileName);
Ico := MakeIcon32(Png);
FreeAndNil(Png);
end;
ifICO : begin
{$IFDEF TNTUNICODE}
Ico := ExtractIconW(hInstance, PacChar(FileName), 0);
{$ELSE}
Ico := ExtractIcon(hInstance, PacChar(FileName), 0);
{$ENDIF}
end;
end;
end;
if Ico <> 0 then begin
Result := ImageList_AddIcon(Handle, Ico) > -1;
DestroyIcon(Ico);
end;
Change;
end;
procedure TsAlphaImageList.ItemsClear;
var
i : integer;
begin
for i := 0 to Items.Count - 1 do Items[i].ImgData.Clear;
end;
procedure TsAlphaImageList.Change;
var
Ico, NewIco: HICON;
iInfo : TIconInfo;
Bmp : TBitmap;
X, Y : integer;
BmpLine : PRGBAArray;
i, c, h, w : integer;
b : boolean;
begin
if AcChanging then Exit;
if HandleAllocated and not (csLoading in ComponentState) and StdListIsGenerated then begin
if not (IsDuplicated and (Count <= Items.Count)) or (csDesigning in ComponentState) then inherited;
if not (csDesigning in ComponentState) then begin
if IsDuplicated and (Count <= Items.Count) {If icon was not added using AddIcon or other std. way (not stored in Items)} then begin
if (Count < Items.Count) then begin
AcChanging := True;
GenerateStdList;
AcChanging := False;
inherited;
end;
end
else begin
c := ImageList_GetImageCount(Handle) - 1;
if c > -1 then begin
Bmp := TBitmap.Create;
for i := 0 to c do begin
Ico := ImageList_GetIcon(Handle, i, ILD_NORMAL);
GetIconInfo(Ico, iInfo);
DestroyIcon(Ico);
Bmp.Handle := iInfo.hbmColor;
Bmp.HandleType := bmDIB;
b := False;
h := Bmp.Height - 1;
w := Bmp.Width - 1;
Bmp.PixelFormat := pf32bit;
for Y := 0 to h do begin // Check if AlphaChannel is empty
BmpLine := Bmp.ScanLine[Y];
for X := 0 to w do if BmpLine[X].A <> 0 then begin
b := True;
Break;
end;
if b then Break;
end;
if not b then begin
for Y := 0 to h do begin
BmpLine := Bmp.ScanLine[Y];
for X := 0 to w do if BmpLine[X].C <> sFuchsia.C then BmpLine[X].A := $FF;
end;
iInfo.hbmColor := Bmp.Handle;
NewIco := CreateIconIndirect(iInfo);
ImageList_ReplaceIcon(Handle, i, NewIco);
DestroyIcon(NewIco);
end;
DeleteObject(iInfo.hbmColor);
DeleteObject(iInfo.hbmMask);
end;
FreeAndNil(Bmp);
end;
end;
end;
end;
end;
procedure TsAlphaImageList.AcBeginUpdate;
begin
AcChanging := True;
end;
procedure TsAlphaImageList.AcEndUpdate(DoChange : boolean = True);
begin
AcChanging := False;
if DoChange then Change;
end;
{ TsImgListItems }
constructor TsImgListItems.Create(AOwner: TsAlphaImageList);
begin
inherited Create(TsImgListItem);
FOwner := AOwner;
end;
destructor TsImgListItems.Destroy;
begin
inherited Destroy;
FOwner := nil;
end;
function TsImgListItems.GetItem(Index: Integer): TsImgListItem;
begin
Result := TsImgListItem(inherited GetItem(Index));
end;
function TsImgListItems.GetOwner: TPersistent;
begin
Result := FOwner;
end;
procedure TsImgListItems.SetItem(Index: Integer; Value: TsImgListItem);
begin
inherited SetItem(Index, Value);
end;
{ TsImgListItem }
procedure TsImgListItem.Assign(Source: TPersistent);
begin
if Source <> nil then begin
ImageFormat := TsImgListItem(Source).ImageFormat;
PixelFormat := TsImgListItem(Source).PixelFormat;
ImgData.LoadFromStream(TsImgListItem(Source).ImgData);
end
else inherited;
end;
procedure TsImgListItem.AssignTo(Dest: TPersistent);
begin
if Dest <> nil then begin
TsImgListItem(Dest).ImageFormat := ImageFormat;
TsImgListItem(Dest).PixelFormat := PixelFormat;
TsImgListItem(Dest).ImgData.LoadFromStream(ImgData);
end
else inherited;
end;
constructor TsImgListItem.Create(Collection: TCollection);
begin
inherited Create(Collection);
FOwner := TsImgListItems(Collection);
ImgData := TMemoryStream.Create;
FPixelFormat := pf32bit;
end;
procedure TsImgListItem.DefineProperties(Filer: TFiler);
begin
inherited DefineProperties(Filer);
Filer.DefineBinaryProperty('ImgData', ReadData, WriteData, True);
end;
destructor TsImgListItem.Destroy;
begin
FreeAndNil(ImgData);
inherited Destroy;
end;
procedure TsImgListItem.ReadData(Reader: TStream);
begin
ImgData.LoadFromStream(Reader);
end;
procedure TsImgListItem.WriteData(Writer: TStream);
begin
ImgData.SaveToStream(Writer);
end;
end.
|
{$X+,G+,D-,L-,S-,R-}
unit ASPI;
interface
uses Objects, Drivers, Service;
const
{Valid ASPI Command Codes:}
SC_HostInquiry = $00; {Host Adapter Inquiry}
SC_GetDeviceType = $01; {Get Device Type}
SC_ExecuteIO = $02; {Execute SCSI I/O Command}
SC_AbortIO = $03; {Abort SCSI I/O Command}
SC_ResetDevice = $04; {Reset SCSI Device}
SC_SetHostParams = $05; {Set Host Adapter Parameters}
SC_GetDriveInfo = $06; {Get Disk Drive Information}
{ASPI Status Bytes:}
SS_PENDING = $00; {SCSI Request in Progress }
SS_COMP = $01; {SCSI Request Completed Without Error }
SS_ABORTED = $02; {SCSI Request Aborted by Host }
SS_ERR = $04; {SCSI Request Completed With Error }
SS_INVALID_CMD = $80; {Invalid SCSI Request }
SS_INVALID_HA = $81; {Invalid Host Adapter Number }
SS_NO_DEVICE = $82; {SCSI Device Not Installed }
SR_ExtReqAsk = $AA55;
SR_ExtReqOK = $55AA;
Ext_Residual = $02; {Residual byte length reported}
Ext_Wide32 = $04; {Wide SCSI 32-bit Host Adapter}
Ext_Wide16 = $08; {Wide SCSI 16-bit Host Adapter}
Drv_NoInt13Access = 0;
Drv_Int13DOSAccess = 1;
Drv_Int13NoDOSAccess = 2;
SCSI_DevType : Array [0..9] of String[25] =
(
'Disk Drive',
'Tape Drive (Streamer)',
'Printer',
'Processor',
'WORM Drive',
'CD-ROM Drive',
'Scanner',
'Optical Drive',
'Medium Changer',
'Communications Device'
);
type
TSRB = Record
Command : Byte;
Status : Byte;
HostAdapter : Byte;
Request : Byte;
Reserved : Array [1..4] of Byte;
end;
TInquirySRB = Record
Command : Byte; {W:Command Code = 0}
Status : Byte; {R:Command Status. This byte always returns with a non-zero code}
HostAdapter : Byte;
RequestFlags: Byte;
ExtRequest : Word;
BufLength : Word;
HostsCount : Byte;
HID : Byte;
ManagerID : Array [1..16] of Char;
HostID : Array [1..16] of Char;
HostUnique : Array [1..16] of Byte;
Extensions : Word;
end;
TGetDeviceTypeSRB = Record
Command : Byte; {W:Command Code = 0}
Status : Byte; {R:Command Status. This byte always returns with a non-zero code}
HostAdapter : Byte;
RequestFlags: Byte;
Reserved : Array [1..4] of Byte;
TargetID : Byte;
LUN : Byte;
DeviceType : Byte;
end;
TGetDriveInfoSRB = Record
Command : Byte; {W:Command Code = 0}
Status : Byte; {R:Command Status. This byte always returns with a non-zero code}
HostAdapter : Byte;
RequestFlags: Byte;
Reserved : Array [1..4] of Byte;
TargetID : Byte;
LUN : Byte;
DriveFlags : Byte;
Int13Drive : Byte;
PreferHead : Byte;
PreferSect : Byte;
Reserved0 : Byte;
end;
PSCSICollection = ^TSCSICollection;
TSCSICollection = Object(TCollection)
constructor Init;
procedure FreeItem(Item: Pointer); virtual;
end;
var
ASPIEntryPoint : Pointer;
ASPI_Ok : Boolean;
InqSRB : TInquirySRB;
DevTypeSRB : TGetDeviceTypeSRB;
DrvInfoSRB : TGetDriveInfoSRB;
function ASPIInit : Boolean;
procedure ASPICall(SRB : Pointer);
function ASPIHostAdapterInquiry : Boolean;
function ASPIGetDeviceType(Host,Target,LUN : Byte) : Boolean;
function ASPIGetDriveInfo(Host,Target,LUN : Byte) : Boolean;
implementation
{컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴}
function GetASPIHandle : Word; assembler;
const
SCSIMgrName : Array [0..8] of Char = 'SCSIMGR$'#0;
asm
push ds
mov ax,Seg SCSIMgrName
mov ds,ax
mov dx,Offset SCSIMgrName
mov ax,3D00h
int 21h
jnc @1
xor ax,ax
@1:
pop ds
end;
{컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴}
function GetASPIEntryPoint(Handle : Word) : Pointer; assembler;
asm
push ds
mov ax,Seg ASPIEntryPoint
mov ds,ax
mov dx,Offset ASPIEntryPoint
mov ax,4402h
mov cx,4
mov bx,Handle
int 21h
mov si,Offset ASPIEntryPoint
mov ax,[si]
mov dx,[si+2]
pop ds
end;
{컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴}
procedure CloseFile(Handle : Word); assembler;
asm
mov bx,Handle
mov ah,3Eh
int 21h
end;
{컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴}
function ASPIInit : Boolean;
var
Handle : Word;
begin
ASPI_Ok := False; ASPIInit := False;
Handle := GetASPIHandle;
If Handle = 0 Then Exit;
If GetASPIEntryPoint(Handle) = Nil Then Exit;
CloseFile(Handle);
ASPIInit := True; ASPI_Ok := True;
end;
{컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴}
procedure ASPICall(SRB : Pointer); assembler;
asm
mov ax,word ptr SRB+2
push ax {Push SRB's segment}
mov ax,word ptr SRB
push ax {Push SRB's offset}
call ASPIEntryPoint {Call ASPI}
add sp,4 {Restore the stack}
end;
{컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴}
function ASPIHostAdapterInquiry : Boolean;
begin
ASPIHostAdapterInquiry := False;
InqSRB.Command := SC_HostInquiry;
InqSRB.HostAdapter := 0;
InqSRB.RequestFlags := 0;
InqSRB.ExtRequest := SR_ExtReqAsk;
InqSRB.BufLength := 4;
ASPICall(@InqSRB);
ASPIHostAdapterInquiry := InqSRB.Status = SS_COMP;
end;
{컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴}
function ASPIGetDeviceType(Host,Target,LUN : Byte) : Boolean;
begin
ASPIGetDeviceType := False;
DevTypeSRB.Command := SC_GetDeviceType;
DevTypeSRB.HostAdapter := Host;
DevTypeSRB.TargetID := Target;
DevTypeSRB.LUN := LUN;
ASPICall(@DevTypeSRB);
ASPIGetDeviceType := DevTypeSRB.Status = SS_COMP;
end;
{컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴}
function ASPIGetDriveInfo(Host,Target,LUN : Byte) : Boolean;
begin
ASPIGetDriveInfo := False;
DrvInfoSRB.Command := SC_GetDriveInfo;
DrvInfoSRB.HostAdapter := Host;
DrvInfoSRB.TargetID := Target;
DrvInfoSRB.LUN := LUN;
ASPICall(@DrvInfoSRB);
ASPIGetDriveInfo := DrvInfoSRB.Status = SS_COMP;
end;
{컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴
TSCSICollection.'s Methods
컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴}
constructor TSCSICollection.Init;
const
FStr = '%-17s %s';
var
Host, Target, LUN : Byte;
S, HTL, D : String;
FormatRec : Record
HTL : PString;
Device : PString;
end;
begin
inherited Init(8,1);
If not ASPIInit Then Exit;
If not ASPIHostAdapterInquiry Then Exit;
for Host := 0 to InqSRB.HostsCount-1 do
begin
For Target := 0 to 7 do
begin
LUN := 0;
While ASPIGetDeviceType(Host,Target,LUN) and (LUN <=7) and (DevTypeSRB.DeviceType < $7F) do
begin
HTL := IntToStr(Host)+'/'+IntToStr(Target)+'/'+IntToStr(Lun);
If DevTypeSRB.DeviceType in [0..9]
Then D := SCSI_DevType[DevTypeSRB.DeviceType]
Else D := 'Unknown (Type '+ByteToHexStr(DevTypeSRB.DeviceType)+'h)';
FormatRec.HTL := @HTL;
FormatRec.Device := @D;
FormatStr(S, FStr, FormatRec);
Insert(NewStr(S));
Inc(LUN);
end;
end;
end;
end;
{컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴컴}
procedure TSCSICollection.FreeItem(Item: Pointer);
begin
If Item <> Nil then DisposeStr(Item);
end;
begin
end.
|
{ Module of routines for appending things to the end of existing strings.
}
module string_append;
define string_append;
define string_append1;
define string_appendn;
define string_appends;
define string_append_token;
%include 'string2.ins.pas';
{
*********************************************************************
*
* Subroutine STRING_APPEND (S1, S2)
*
* Append string 2 onto the end of string 1. The result is put into
* string 1.
}
procedure string_append ( {append one string onto another}
in out s1: univ string_var_arg_t; {string to append to}
in s2: univ string_var_arg_t); {string that is appended to S1}
var
nchar: sys_int_machine_t; {number of characters to copy}
i, j: sys_int_machine_t; {scratch integers}
begin
j := s1.len; {init end of string 1 pointer}
nchar := s2.len; {init number of chars to copy}
if nchar > s1.max-j then nchar:=s1.max-j; {clip to max room left in s1}
s1.len := j+nchar; {update s1 length}
for i := 1 to nchar do begin {once for each character}
j := j+1; {point to next position in s1}
s1.str[j] := s2.str[i]; {copy one character}
end; {done copying all the characters}
end;
{
*********************************************************************
*
* Subroutine STRING_APPEND1 (S, CHR)
*
* Append the character CHR to the end of string S.
}
procedure string_append1 ( {append one char to end of string}
in out s: univ string_var_arg_t; {string to append to}
in chr: char); {character to append}
val_param;
begin
if s.len >= s.max then return; {no room for another character ?}
s.len := s.len+1; {one more character in string}
s.str[s.len] := chr; {put character at string end}
end;
{
*********************************************************************
*
* Subroutine STRING_APPENDN (S, CHARS, N)
*
* Append N characters to the end of string S. S is a normal
* variable length string. CHARS is just an array of characters.
}
procedure string_appendn ( {append N characters to end of string}
in out s: univ string_var_arg_t; {string to append to}
in chars: univ string; {characters to append to string}
in n: string_index_t); {number of characters to append}
val_param;
var
i, j: sys_int_machine_t; {string indices}
nc: sys_int_machine_t; {number of chars to copy}
begin
nc := s.max-s.len; {init to room left in S}
if nc > n then nc := n; {nc = num of chars to copy}
if nc <= 0 then return; {nothing to append ?}
j := s.len+1; {init S index}
for i := 1 to nc do begin {once for each char to copy}
s.str[j] := chars[i]; {copy one character}
j := j+1; {update put pointer}
end; {back and copy next char}
s.len := s.len+nc {update length of S}
end;
{
*********************************************************************
*
* Subroutine STRING_APPENDS (S, CHARS)
*
* Append the PASCAL STRING in CHARS to the end of the variable length
* string in S. The string in S will only be used up to but no including
* the trailing blanks.
}
procedure string_appends ( {append PASCAL STRING to variable length string}
in out s: univ string_var_arg_t; {string to append to}
in chars: string); {append these chars up to trailing blanks}
var
vstr: string_var80_t; {var string copy of CHARS}
begin
vstr.max := sizeof(vstr.str); {init local var string}
string_vstring (vstr, chars, sizeof(chars)); {make var string from CHARS}
string_append (s, vstr); {append var string to end of S}
end;
{
*********************************************************************
*
* Subroutine STRING_APPEND_TOKEN (STR, TK)
*
* Append the string in TK to the end of STR in such a way that it would
* be parsed as a single token by STRING_TOKEN. STRING_TOKEN would return
* the original contents of TK, regardless of whether TK contained quotes,
* apostrophies, or blanks.
}
procedure string_append_token ( {append single token using STRING_TOKEN rules}
in out str: univ string_var_arg_t; {string to append to}
in tk: univ string_var_arg_t); {string to append as individual token}
val_param;
var
t: string_var8192_t; {tokenized copy of TK}
begin
t.max := sizeof(t.str); {init local var string}
string_token_make (tk, t); {make individual token of TK in T}
if {end of existing string is end of previous token ?}
(str.len > 0) and then
(str.str[str.len] <> ' ')
then begin
string_append1 (str, ' '); {add separator before new token}
end;
string_append (str, t); {append token to end of string}
end;
|
unit uPerfectNumbersTest;
interface
uses
DUnitX.TestFramework;
type
[TestFixture]
PerfectNumbersTest = class(TObject)
public
[Test]
// [Ignore('Comment the "[Ignore]" statement to run the test')]
procedure Can_classify_3_as_deficient;
[Test]
[Ignore]
procedure Can_classify_7_as_deficient;
[Test]
[Ignore]
procedure Can_classify_13_as_deficient;
[Test]
[Ignore]
procedure Can_classify_6_as_perfect;
[Test]
[Ignore]
procedure Can_classify_28_as_perfect;
[Test]
[Ignore]
procedure Can_classify_496_as_perfect;
[Test]
[Ignore]
procedure Can_classify_12_as_abundant;
[Test]
[Ignore]
procedure Can_classify_18_as_abundant;
[Test]
[Ignore]
procedure Can_classify_20_as_abundant;
end;
implementation
uses uPerfectNumbers;
procedure PerfectNumbersTest.Can_classify_3_as_deficient;
begin
Assert.AreEqual(Deficient, PerfectNumber.Classify(3));
end;
procedure PerfectNumbersTest.Can_classify_7_as_deficient;
begin
Assert.AreEqual(Deficient, PerfectNumber.Classify(7));
end;
procedure PerfectNumbersTest.Can_classify_13_as_deficient;
begin
Assert.AreEqual(Deficient, PerfectNumber.Classify(13));
end;
procedure PerfectNumbersTest.Can_classify_6_as_perfect;
begin
Assert.AreEqual(Perfect, PerfectNumber.Classify(6));
end;
procedure PerfectNumbersTest.Can_classify_28_as_perfect;
begin
Assert.AreEqual(Perfect, PerfectNumber.Classify(28));
end;
procedure PerfectNumbersTest.Can_classify_496_as_perfect;
begin
Assert.AreEqual(Perfect, PerfectNumber.Classify(496));
end;
procedure PerfectNumbersTest.Can_classify_12_as_abundant;
begin
Assert.AreEqual(Abundant, PerfectNumber.Classify(12));
end;
procedure PerfectNumbersTest.Can_classify_18_as_abundant;
begin
Assert.AreEqual(Abundant, PerfectNumber.Classify(18));
end;
procedure PerfectNumbersTest.Can_classify_20_as_abundant;
begin
Assert.AreEqual(Abundant, PerfectNumber.Classify(20));
end;
initialization
TDUnitX.RegisterTestFixture(PerfectNumbersTest);
end.
|
unit ufrmDialogShift;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufrmMasterDialog, ExtCtrls,
ComCtrls, StdCtrls, System.Actions, Vcl.ActnList, ufraFooterDialog3Button;
type
TFormMode = (fmAdd, fmEdit);
TfrmDialogShift = class(TfrmMasterDialog)
edtNameShift: TLabeledEdit;
dtpStart: TDateTimePicker;
dtpEnd: TDateTimePicker;
Label1: TLabel;
lbl1: TLabel;
procedure actDeleteExecute(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormDestroy(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure footerDialogMasterbtnSaveClick(Sender: TObject);
private
FIsProcessSuccessfull: boolean;
FFormMode: TFormMode;
FIDShift: Integer;
procedure SetFormMode(const Value: TFormMode);
procedure SetIsProcessSuccessfull(const Value: boolean);
procedure SetIDShift(const Value: Integer);
procedure PrepareAdd;
procedure PrepareEdit;
public
property FormMode: TFormMode read FFormMode write SetFormMode;
property IsProcessSuccessfull: boolean read FIsProcessSuccessfull write SetIsProcessSuccessfull;
property IDShift: Integer read FIDShift write SetIDShift;
end;
var
frmDialogShift: TfrmDialogShift;
implementation
uses ufrmShift, uTSCommonDlg, uRetnoUnit;
{$R *.dfm}
procedure TfrmDialogShift.actDeleteExecute(Sender: TObject);
begin
inherited;
{
if strgGrid.Cells[0,strgGrid.Row] = ' ' then Exit
else
if (CommonDlg.Confirm('Are you sure you wish to delete Shift(Code: '+ strgGrid.Cells[1,strgGrid.Row]+')?') = mrYes) then
begin
with TNewShift.Create(Self) do
begin
try
if LoadByID(strgGrid.Ints[4,strgGrid.Row],masternewunit.id) then
begin
if RemoveFromDB then
begin
cCommitTrans;
CommonDlg.ShowMessage(CONF_DELETE_SUCCESSFULLY);
actRefreshShiftExecute(Self);
end
else
begin
cRollbackTrans;
CommonDlg.ShowMessage(CONF_COULD_NOT_DELETE);
end;
end;
finally
Free;
end;
end;
end; //end confirm
}
end;
procedure TfrmDialogShift.SetFormMode(const Value: TFormMode);
begin
FFormMode := Value;
end;
procedure TfrmDialogShift.SetIsProcessSuccessfull(const Value: boolean);
begin
FIsProcessSuccessfull := Value;
end;
procedure TfrmDialogShift.SetIDShift(const Value: Integer);
begin
FIDShift := Value;
end;
procedure TfrmDialogShift.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action := caFree;
end;
procedure TfrmDialogShift.FormDestroy(Sender: TObject);
begin
inherited;
frmDialogShift := nil;
end;
procedure TfrmDialogShift.PrepareAdd;
begin
edtNameShift.Clear;
end;
procedure TfrmDialogShift.PrepareEdit;
begin
{edtNameShift.Text:= frmShift.strgGrid.Cells[1,frmShift.strgGrid.Row];
dtpStart.DateTime:= StrToDateTime(frmShift.strgGrid.Cells[5,frmShift.strgGrid.Row]);
dtpEnd.DateTime:= StrToDateTime(frmShift.strgGrid.Cells[6,frmShift.strgGrid.Row]);
}
end;
procedure TfrmDialogShift.FormShow(Sender: TObject);
begin
inherited;
if FormMode=fmAdd then
begin
PrepareAdd;
IDShift := -1;
end
else
PrepareEdit;
edtNameShift.SelectAll;
end;
procedure TfrmDialogShift.footerDialogMasterbtnSaveClick(Sender: TObject);
begin
inherited;
{
if not IsValidDateKarenaEOD(dialogunit,cGetServerTime,FMasterIsStore) then
Exit;
if edtNameShift.Text = '' then
begin
CommonDlg.ShowErrorEmpty('SHIFT NAME');
edtNameShift.SetFocus;
Exit;
end;
with TNewShift.Create(Self) do
begin
try
UpdateData(dialogunit,
dtpEnd.DateTime,
IDShift,
edtNameShift.Text,
dtpStart.DateTime);
IsProcessSuccessfull := SaveToDB;
if IsProcessSuccessfull then
begin
cCommitTrans;
//CommonDlg.ShowMessage(CONF_SAVE_SUCCESSFULLY);
end
else
begin
cRollbackTrans;
//CommonDlg.ShowError(CONF_SAVE_FAILED);
end;
finally
Free;
// free resources
end; // try/finally
end;
Close;
}
end;
end.
|
program simpleExample;
var a_ : integer;
begin
a_ := 411;
writeln(a_);
end.
|
unit UlancarContas;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls,
Vcl.WinXCalendars, Vcl.Mask, Vcl.DBCtrls, FireDAC.Stan.Intf,
FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS,
FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt,
Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.ComCtrls, Vcl.Menus,
Vcl.WinXPickers;
type
TFrmLancarContas = class(TForm)
pnlButtons: TPanel;
btnNovo: TButton;
btnAlterar: TButton;
btnCancelar: TButton;
btnSalvar: TButton;
btnExcluir: TButton;
pnlLancamentos: TPanel;
dbedtContaCodigo: TDBEdit;
Label1: TLabel;
Label2: TLabel;
Label4: TLabel;
dbedtValor: TDBEdit;
Label5: TLabel;
dbedtVencimento: TDBEdit;
Label6: TLabel;
dbedtContaDescricao: TDBEdit;
calendarValor: TCalendarView;
lbEmEdicao: TLabel;
procedure calendarValorClick(Sender: TObject);
procedure dbedtContaCodigoExit(Sender: TObject);
procedure btnNovoClick(Sender: TObject);
procedure btnAlterarClick(Sender: TObject);
procedure btnCancelarClick(Sender: TObject);
procedure btnSalvarClick(Sender: TObject);
procedure btnExcluirClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
private
{ Private declarations }
procedure HabilitarCadastro;
procedure DesabilitarCadastro;
public
{ Public declarations }
end;
var
FrmLancarContas: TFrmLancarContas;
implementation
{$R *.dfm}
uses UdmPrincipal, Umetodos, Uprincipal, Ucontas;
procedure TFrmLancarContas.btnAlterarClick(Sender: TObject);
begin
HabilitarCadastro;
dmPrincipal.fdqContasLancadas.Edit;
end;
procedure TFrmLancarContas.btnCancelarClick(Sender: TObject);
begin
DesabilitarCadastro;
dmPrincipal.fdqContasLancadas.Cancel;
end;
procedure TFrmLancarContas.btnExcluirClick(Sender: TObject);
begin
if Application.MessageBox(PChar ('Deseja excluir o registro[' + dmPrincipal.fdqContasLancadasDESCRICAO.AsString + ']'), 'Confirmação', MB_YESNO) = mrYes then
begin
dmPrincipal.fdqContasLancadas.Delete;
dmPrincipal.fdqContasLancadas.Refresh;
end;
end;
procedure TFrmLancarContas.btnNovoClick(Sender: TObject);
begin
HabilitarCadastro;
dmPrincipal.fdqContasLancadas.Append;
end;
procedure TFrmLancarContas.btnSalvarClick(Sender: TObject);
begin
DesabilitarCadastro;
dmPrincipal.fdqContasLancadas.Post;
end;
procedure TFrmLancarContas.calendarValorClick(Sender: TObject);
begin
dbedtVencimento.Text := DateToStr(calendarValor.Date);
end;
procedure TFrmLancarContas.dbedtContaCodigoExit(Sender: TObject);
begin
dbedtContaDescricao.Clear;
if Trim(dbedtContaCodigo.Text) <> '' then
begin
dbedtContaDescricao.Text := Selecionar('Contas', 'Id', dbedtContaCodigo.Text);
if Trim(dbedtContaDescricao.Text) = '' then
dbedtContaCodigo.SetFocus;
end;
end;
procedure TFrmLancarContas.DesabilitarCadastro;
begin
btnNovo.Enabled := True;
btnAlterar.Enabled := True;
btnCancelar.Enabled := False;
btnSalvar.Enabled := False;
btnExcluir.Enabled := True;
pnlLancamentos.Enabled := False;
lbEmEdicao.Visible := False;
btnNovo.SetFocus;
end;
procedure TFrmLancarContas.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
dmPrincipal.fdqContasLancadas.Close;
end;
procedure TFrmLancarContas.FormCreate(Sender: TObject);
begin
dmPrincipal.fdqContasLancadas.Open;
end;
procedure TFrmLancarContas.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if pnlLancamentos.Enabled then
begin
if Key = VK_F2 then
begin
try
Application.CreateForm(TFrmContas, FrmContas);
FrmContas.pnlButtons.Visible := False;
FrmContas.pnlCadastro.Visible := False;
FrmContas.Tag := 'P';
FrmContas.ShowModal;
finally
Self.dbedtContaCodigo.Text := FrmContas.ContaCod.ToString;
Self.dbedtContaDescricao.Text := FrmContas.ContaDescricao;
FrmContas.Free;
end;
end;
end;
end;
procedure TFrmLancarContas.HabilitarCadastro;
begin
btnNovo.Enabled := False;
btnAlterar.Enabled := False;
btnCancelar.Enabled := True;
btnSalvar.Enabled := True;
btnExcluir.Enabled := False;
pnlLancamentos.Enabled := True;
lbEmEdicao.Visible := True;
dbedtContaCodigo.SetFocus;
end;
end.
|
program uno;
const
valorAlto = 999;
type
comision = record
nombre:String;
cod:integer;
monto:real;
end;
archivoComision = file of comision;
procedure leerDato (var arc : archivoComision; var dat:comision);
begin
if (not eof(arc)) then
read(arc,dat)
else
dat.cod := valorAlto;
end;
procedure generarArchivoBinario (var archivo : archivoComision; var texto : Text);
var
unaComision : comision;
begin
reset(texto);
rewrite(archivo);
while (not eof(texto)) do begin
readln(texto, unaComision.cod, unaComision.nombre);
readln(texto, unaComision.monto);
write(archivo, unaComision);
end;
close(archivo);
close(texto);
end;
procedure compactarArchivo (var archivo : archivoComision; var compacto : archivoComision);
var
regDet, regMae : comision;
codActual : integer;
begin
reset(archivo);
rewrite(compacto);
leerDato(archivo,regDet);
while (regDet.cod <> valorAlto) do begin
codActual := regDet.cod;
regMae.monto := 0;
regMae.nombre := regDet.nombre;
while (codActual = regDet.cod) do begin
regMae.monto := regMae.monto + regDet.monto;
leerDato(archivo,regDet);
end;
regMae.cod := codActual;
write(compacto,regMae);
end;
close(archivo);
close(compacto);
end;
{Deberia quedar:
1 Marcelo 2450
2 Angeles 2500
3 Fabian 4600
4 Carlos 5000
5 Lucia 3600
}
procedure listarDatos (var archivo : archivoComision);
var
unaComision : comision;
begin
reset(archivo);
while (not eof(archivo)) do begin
read(archivo,unaComision);
with unaComision do
writeln('Codigo: ',cod,' Nombre: ',nombre,' Monto: ',monto:4:2);
end;
close(archivo);
end;
//Programa Principal
var
archivoComisionTexto : Text;
compacto, archivoBinario : archivoComision;
begin
assign(archivoComisionTexto,'comisiones.txt');
assign(archivoBinario,'archivo_comision');
assign(compacto,'archivo_comisiones_compactos');
generarArchivoBinario(archivoBinario,archivoComisionTexto);
writeln('Archivo binario');
listarDatos(archivoBinario);
compactarArchivo(archivoBinario,compacto);
writeln('Archivo compacto');
listarDatos(compacto);
end.
|
unit UUtilsStrings;
interface
uses
TypInfo;
type
TArrayOfString = Array of String;
function Split(strValue, strDelimiter: String): TArrayOfString;
function Join(const arrValue: TArrayOfString; const strDelimiter: String): String;
function PosIEx(const SubStr, S: string; Offset: Integer = 1): Integer;
function AnsiEncode64(S: AnsiString): AnsiString;
function AnsiDecode64(S: AnsiString): AnsiString;
function RespaceOverviewName(strText: string; blnAddTabs: boolean): string;
procedure StringToSet(Info: PTypeInfo; var SetParam; const Value: AnsiString);
function SetToString(Info: PTypeInfo; const SetParam; Brackets: Boolean): AnsiString;
implementation
uses
Math, SysUtils, UStringLogicalComparer;
function Split(strValue, strDelimiter: String): TArrayOfString;
var
nPos: Integer;
iDelimeterLength: integer;
begin
if (pos(strDelimiter, strValue) = 0) and (Trim(strValue) = '') then begin
SetLength(Result, 1);
Exit;
end;
iDelimeterLength := Length(strDelimiter);
SetLength(Result, 0);
repeat
nPos := Pos(strDelimiter, strValue);
if (nPos > 0) then
begin
SetLength(Result, Length(Result) + 1);
Result[Length(Result) - 1] := Copy(strValue, 1, nPos - 1);
Delete(strValue, 1, nPos+iDelimeterLength -1);
nPos := Pos(strDelimiter, strValue);
end;
until (nPos = 0);
SetLength(Result, Length(Result) + 1);
Result[Length(Result) - 1] := strValue;
end;
function Join(const arrValue: TArrayOfString; const strDelimiter: String): String;
var
i: Integer;
begin
Result := '';
for i := 0 to Length(arrValue) - 1 do
begin
if (i > 0) then
Result := Result + strDelimiter;
Result := Result + arrValue[i];
end;
end;
var
LookUpTable : array of Char;
procedure InitializeLookUpTable;
var
I: Byte;
S1, S2: String;
begin
SetLength(LookUpTable, 256);
for I := 0 to 255 do
begin
S1 := Char(I);
S2 := UpperCase(S1);
LookUpTable[I] := S2[1];
end;
end;
function PosIEx(const SubStr, S: string; Offset: Integer = 1): Integer;
var
I2, SubStrLength, StrLength : Integer;
SubStrFirstCharUpper : Char;
begin
Result := 0;
if (Offset <= 0) then
Exit;
if S <> '' then
StrLength := Length(S)
else
Exit;
if SubStr <> '' then
SubStrLength := Length(SubStr)
else
Exit;
if (SubStrLength <= 0) then
Exit;
if (StrLength <= 0) then
Exit;
if (Integer(Offset) > StrLength) then
Exit;
if SubStrLength > 1 then begin
if (StrLength - Integer(Offset) + 1 < SubStrLength) then //No room for match
Exit;
Result := Offset;
SubStrFirstCharUpper := LookUpTable[Ord(SubStr[1])];
repeat
if SubStrFirstCharUpper = LookUpTable[Ord(S[Result])] then begin
if Result + SubStrLength - 1 > StrLength then begin
Result := 0;
Exit;
end;
I2 := 1;
repeat
if S[Result+I2] <> SubStr[I2+1] then begin
if LookUpTable[Ord(S[Result+I2])] <> LookUpTable[Ord(SubStr[I2+1])] then
Break;
end;
Inc(I2);
if (I2 >= SubStrLength) then
Exit;
until(False);
end;
Inc(Result);
until(Result > StrLength);
Result := 0;
end else begin
SubStrFirstCharUpper := LookUpTable[Ord(SubStr[1])];
Result := Offset;
repeat
if SubStrFirstCharUpper = LookUpTable[Ord(S[Result])] then
Exit;
Inc(Result);
until (Result > StrLength);
Result := 0;
end;
end;
const
Codes64: AnsiString = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/';
function AnsiEncode64(S: AnsiString): AnsiString;
var
i: Integer;
a: Integer;
x: Integer;
b: Integer;
begin
Result := '';
a := 0;
b := 0;
for i := 1 to Length(s) do
begin
x := Ord(s[i]);
b := b * 256 + x;
a := a + 8;
while a >= 6 do
begin
a := a - 6;
x := b div (1 shl a);
b := b mod (1 shl a);
Result := Result + Codes64[x + 1];
end;
end;
if a > 0 then
begin
x := b shl (6 - a);
Result := Result + Codes64[x + 1];
end;
end;
function AnsiDecode64(S: AnsiString): AnsiString;
var
i: Integer;
a: Integer;
x: Integer;
b: Integer;
begin
Result := '';
a := 0;
b := 0;
for i := 1 to Length(s) do
begin
x := Pos(s[i], codes64) - 1;
if x >= 0 then
begin
b := b * 64 + x;
a := a + 6;
if a >= 8 then
begin
a := a - 8;
x := b shr a;
b := b mod (1 shl a);
x := x mod 256;
Result := Result + AnsiChar(x);
end;
end
else
Exit;
end;
end;
function FindLastDelimiter(const Delimiters, S: string; StartIdx: Integer = -1): Integer;
var
Stop: Boolean;
Len: Integer;
begin
Result := 0;
if StartIdx = -1 then begin
StartIdx := Length(S) -1;
end;
Stop := False;
while (not Stop) and (StartIdx > 0) do
if IsDelimiter(Delimiters, S, StartIdx) then
begin
Result := StartIdx;
Stop := True;
end
else
Dec(StartIdx);
end;
function StringReplace(const S, OldPattern, NewPattern: string; FirstIndex: integer;
Flags: TReplaceFlags): string; overload;
//const
// FirstIndex = Low(string);
var
SearchStr, Patt, NewStr: string;
Offset, I, L: Integer;
begin
if FirstIndex > 0 then
begin
if rfIgnoreCase in Flags then
begin
SearchStr := AnsiUpperCase(S);
Patt := AnsiUpperCase(OldPattern);
end else
begin
SearchStr := S;
Patt := OldPattern;
end;
NewStr := S;
Result := '';
if SearchStr.Length <> S.Length then
begin
I := FirstIndex;
L := OldPattern.Length;
while I <= High(S) do
begin
if string.Compare(S, I - FirstIndex, OldPattern, 0, L, True) = 0 then
begin
Result := Result + NewPattern;
Inc(I, L);
if not (rfReplaceAll in Flags) then
begin
Result := Result + S.Substring(I - FirstIndex, MaxInt);
Break;
end;
end
else
begin
Result := Result + S[I];
Inc(I);
end;
end;
end
else
begin
while SearchStr <> '' do
begin
Offset := PosIEx(Patt, SearchStr, FirstIndex);
if Offset = 0 then
begin
Result := Result + NewStr;
Break;
end;
Result := Result + Copy(NewStr, 1, Offset - 1) + NewPattern;
NewStr := Copy(NewStr, Offset + Length(OldPattern), MaxInt);
if not (rfReplaceAll in Flags) then
begin
Result := Result + NewStr;
Break;
end;
SearchStr := Copy(SearchStr, Offset + Length(Patt), MaxInt);
end;
end;
end
else
begin
Result := S;
end;
end;
function RespaceOverviewName(strText: string; blnAddTabs: boolean): string;
var
iPos: integer;
begin
Result := trim(strText);
// first remove all extra spaces
Result := StringReplace(Result, #9, ' ', [rfReplaceAll]);
Result := StringReplace(Result, ' ', ' ', [rfReplaceAll]);
Result := StringReplace(Result, ' :', ':', [rfReplaceAll]);
Result := StringReplace(Result, ': ', ':', [rfReplaceAll]);
Result := StringReplace(Result, ' ,', ',', [rfReplaceAll]);
Result := StringReplace(Result, ', ', ',', [rfReplaceAll]);
Result := StringReplace(Result, ' -', '-', [rfReplaceAll]);
Result := StringReplace(Result, '- ', '-', [rfReplaceAll]);
Result := StringReplace(Result, 'en ', 'en'#8, pos(':', Result), [rfReplaceAll]);
Result := StringReplace(Result, ' en', #8'en', pos(':', Result), [rfReplaceAll]);
if blnAddTabs then begin
iPos := FindLastDelimiter(' ', Result);
if iPos > 0 then begin
if ((iPos + 1) < Length(Result)) and IsDigit(Result[iPos + 1]) then begin
Result[iPos] := #9
end else begin
iPos := FindLastDelimiter(' ', Result, iPos -1);
if ((iPos + 1) < Length(Result)) and IsDigit(Result[iPos + 1]) then begin
Result[iPos] := #9
end;
end;
end;
Result := StringReplace(Result, ':', #9': ', [rfReplaceAll]);
end else
Result := StringReplace(Result, ':', ' : ', [rfReplaceAll]);
Result := StringReplace(Result, 'en'#8, 'en ', pos(':', Result), [rfReplaceAll]);
Result := StringReplace(Result, #8'en', ' en', pos(':', Result), [rfReplaceAll]);
Result := StringReplace(Result, ',', ', ', [rfReplaceAll]);
Result := StringReplace(Result, '-', ' - ', [rfReplaceAll]);
iPos := PosIEx('en', Result, pos(':', Result));
while iPos > 0 do
begin
if IsDigit(Result[iPos -1]) then
begin
insert(' ', Result, iPos);
inc(iPos);
end;
inc(iPos, 2);
if iPos <= Length(Result) then
begin
if IsDigit(Result[iPos]) then
begin
insert(' ', Result, iPos);
inc(iPos);
end;
end;
iPos := PosIEx('en', Result, iPos);
end;
if Length(Result) > 0 then begin
Result[1] := UpCase(Result[1]);
end;
end;
function GetOrdValue(Info: PTypeInfo; const SetParam): Integer;
begin
Result := 0;
case GetTypeData(Info)^.OrdType of
otSByte, otUByte:
Result := Byte(SetParam);
otSWord, otUWord:
Result := Word(SetParam);
otSLong, otULong:
Result := Integer(SetParam);
end;
end;
procedure SetOrdValue(Info: PTypeInfo; var SetParam; Value: Integer);
begin
case GetTypeData(Info)^.OrdType of
otSByte, otUByte:
Byte(SetParam) := Value;
otSWord, otUWord:
Word(SetParam) := Value;
otSLong, otULong:
Integer(SetParam) := Value;
end;
end;
function SetToString(Info: PTypeInfo; const SetParam; Brackets: Boolean): AnsiString;
var
S: TIntegerSet;
TypeInfo: PTypeInfo;
I: Integer;
begin
Result := '';
Integer(S) := GetOrdValue(Info, SetParam);
TypeInfo := GetTypeData(Info)^.CompType^;
for I := 0 to SizeOf(Integer) * 8 - 1 do
if I in S then
begin
if Result <> '' then
Result := Result + ',';
Result := Result + GetEnumName(TypeInfo, I);
end;
if Brackets then
Result := '[' + Result + ']';
end;
procedure StringToSet(Info: PTypeInfo; var SetParam; const Value: AnsiString);
var
P: PAnsiChar;
EnumInfo: PTypeInfo;
EnumName: AnsiString;
EnumValue, SetValue: Longint;
function NextWord(var P: PAnsiChar): AnsiString;
var
I: Integer;
begin
I := 0;
// scan til whitespace
while not (P[I] in [',', ' ', #0,']']) do
Inc(I);
SetString(Result, P, I);
// skip whitespace
while P[I] in [',', ' ',']'] do
Inc(I);
Inc(P, I);
end;
begin
SetOrdValue(Info, SetParam, 0);
if Value = '' then
Exit;
SetValue := 0;
P := PAnsiChar(Value);
// skip leading bracket and whitespace
while P^ in ['[',' '] do
Inc(P);
EnumInfo := GetTypeData(Info)^.CompType^;
EnumName := NextWord(P);
while EnumName <> '' do
begin
EnumValue := GetEnumValue(EnumInfo, EnumName);
if EnumValue < 0 then
begin
SetOrdValue(Info, SetParam, 0);
Exit;
end;
Include(TIntegerSet(SetValue), EnumValue);
EnumName := NextWord(P);
end;
SetOrdValue(Info, SetParam, SetValue);
end;
//Example usage:
//
//var
// A: TAlignSet;
// S: AnsiString;
//begin
// // set to string
// A := [alClient, alLeft, alTop];
// S := SetToString(TypeInfo(TAlignSet), A, True);
// ShowMessage(Format('%s ($%x)', [S, Byte(A)]));
//
// // string to set
// S := '[alNone, alRight, alCustom]';
// StringToSet(TypeInfo(TAlignSet), A, S);
// ShowMessage(Format('%s ($%x)', [SetToString(TypeInfo(TAlignSet), A, True), Byte(A)]));
//end;
initialization
InitializeLookUpTable;
end.
|
{ Module of routines that convert between system window handles and
* strings.
*
* The format of a system window ID string is the same as a system screen
* ID string followed by one more tokens to identify the window on the screen.
* The screen ID string must not be empty, and at least one blank must
* follow it before the window ID string. The reserved window ID token
* names are:
*
* -STDOUT - Indicates the window displaying standard output. This
* is identified by the WINDOWID environment variable, when present.
*
* -ROOT - Indicates the root window on the screen.
*
* Additional options may follow the window ID token. They are:
*
* -DIR - Forces use of this window directly. The application is not
* allowed create a subordinate window, and then draw into that.
*
* -INDIR - The indicated window must not be used directly. The
* application must always create a subordinate window to draw into.
* This flag is mutually exclusive with -DIR. When neither flag
* is specified, the application may use the window directly or indirectly,
* as it deems appropriate.
*
* -NOWM - Indicates that an attempt should be made to prevent the
* window manager from interfering with any newly created windows.
* Most window managers only interfere with windows that are directly
* subordinate to the root window.
*
* -POS x y - Implies -INDIR, and specifies the position of the top
* left corner of the new window with respect to the top left corner
* of the parent window.
*
* -SIZE dx dy - Implies -INDIR, and specifies the size of the new window.
*
* A blank or omitted window name indicates default, which is -STDOUT.
*
* The format of a screen ID string is described in the header comments
* of file STRING_SCREEN.PAS.
}
module string_window;
define string_f_window;
define string_t_window;
%include 'string2.ins.pas';
var
window_stdout: string_var16_t :=
[str := '-STDOUT', len := 7, max := sizeof(window_stdout.str)];
window_root: string_var16_t :=
[str := '-ROOT', len := 5, max := sizeof(window_root.str)];
flag_dir: string_var16_t :=
[str := '-DIR', len := 4, max := sizeof(flag_dir.str)];
flag_indir: string_var16_t :=
[str := '-INDIR', len := 6, max := sizeof(flag_indir.str)];
flag_nowm: string_var16_t :=
[str := '-NOWM', len := 5, max := sizeof(flag_nowm.str)];
flag_pos: string_var16_t :=
[str := '-POS', len := 4, max := sizeof(flag_pos.str)];
flag_size: string_var16_t :=
[str := '-SIZE', len := 5, max := sizeof(flag_size.str)];
flag_name: string_var16_t :=
[str := '-NAME', len := 5, max := sizeof(flag_name.str)];
flag_icname: string_var16_t :=
[str := '-ICNMAE', len := 7, max := sizeof(flag_icname.str)];
{
********************************************
*
* Subroutine STRING_F_WINDOW (S, WINDOW)
*
* Convert the window handle WINDOW to its string representation in S.
}
procedure string_f_window ( {convert system window handle to a string}
in out s: univ string_var_arg_t; {output string}
in window: sys_window_t); {input handle to the window}
val_param;
var
token: string_var32_t; {scratch token for number conversion}
begin
token.max := sizeof(token.str); {init local var string}
string_f_screen (s, window.screen); {init string with screen ID}
string_append1 (s, ' '); {add separator before window ID token}
if sys_winflag_stdout_k in window.flags
then begin {window ID is -STDOUT}
string_append (s, window_stdout);
end
else begin {window ID is actual window number}
if window.window = -1
then begin {root window}
string_append (s, window_root);
end
else begin {explicit window number}
string_f_int (token, window.window); {make window ID string}
string_append (s, token);
end
;
end
;
string_append1 (s, ' ');
if sys_winflag_dir_k in window.flags then begin
string_append (s, flag_dir);
string_append1 (s, ' ');
end;
if sys_winflag_indir_k in window.flags then begin
string_append (s, flag_indir);
string_append1 (s, ' ');
end;
if sys_winflag_nowm_k in window.flags then begin
string_append (s, flag_nowm);
string_append1 (s, ' ');
end;
if sys_winflag_pos_k in window.flags then begin
string_append (s, flag_pos);
string_append1 (s, ' ');
string_f_int (token, window.pos_x);
string_append (s, token);
string_append1 (s, ' ');
string_f_int (token, window.pos_y);
string_append (s, token);
string_append1 (s, ' ');
end;
if sys_winflag_size_k in window.flags then begin
string_append (s, flag_size);
string_append1 (s, ' ');
string_f_int (token, window.size_x);
string_append (s, token);
string_append1 (s, ' ');
string_f_int (token, window.size_y);
string_append (s, token);
string_append1 (s, ' ');
end;
if sys_winflag_name_k in window.flags then begin
string_append (s, flag_name);
string_appendn (s, ' "', 2);
string_append (s, window.name_wind);
string_appendn (s, '" ', 2);
end;
if sys_winflag_icname_k in window.flags then begin
string_append (s, flag_icname);
string_appendn (s, ' "', 2);
string_append (s, window.name_icon);
string_appendn (s, '" ', 2);
end;
end;
{
********************************************
*
* Subroutine STRING_T_WINDOW (S, WINDOW, STAT)
*
* Convert the string representation of a system window handle in S to
* the system window handle WINDOW.
}
procedure string_t_window ( {convert string to system window handle}
in s: univ string_var_arg_t; {input string}
out window: sys_window_t; {returned handle to the window}
out stat: sys_err_t); {completion status code}
type
pstate_k_t = ( {current parse state}
pstate_bef_k, {before screen ID token}
pstate_tok_k, {in screen ID token}
pstate_quote_k); {within quoted string}
var
pick: sys_int_machine_t; {number of token picked from list}
p: string_index_t; {parse index into S}
pstate: pstate_k_t; {current parse state}
qchar: char; {character to end quoted string}
c: char; {current character being parsed}
token: string_leafname_t; {scratch token extracted from S}
label
parse_again, got_screen_token, loop;
begin
token.max := sizeof(token.str); {init local var string}
sys_error_none (stat); {init to no errors}
{
* Extract the screen ID string into TOKEN. P will be left as a valid parse
* index following the screen ID string.
}
token.len := 0; {init screen ID string}
p := 1; {init input string parse index}
if s.len <= 0 then goto got_screen_token; {input string is empty ?}
pstate := pstate_bef_k; {init to curr parse state is start of string}
for p := 1 to s.len do begin {scan to end of screen ID token}
c := s.str[p]; {extract character being parsed}
parse_again: {back here to re-parse with same input char}
case pstate of
pstate_bef_k: begin {we are before start of screen ID token}
if c = ' ' then next; {ignore this trailing blank char}
pstate := pstate_tok_k; {we are now within token}
goto parse_again; {re-process same char with new state}
end;
pstate_tok_k: begin {we are parsing the token outside of a quote}
if c = ' ' then begin {hit blank after screen ID token ?}
goto got_screen_token;
end;
if (c = '''') or (c = '"') then begin {quote character ?}
pstate := pstate_quote_k; {we are now within quoted string}
qchar := c; {save character to exit quote string state}
end;
end;
pstate_quote_k: begin {we are inside a quoted string}
if c = qchar then begin {hit end of quoted string ?}
pstate := pstate_tok_k; {back to regular token state}
end;
end;
end; {end of parse state cases}
if token.len < token.max then begin {room left in TOKEN ?}
token.len := token.len + 1; {one more character for TOKEN}
token.str[token.len] := c; {stuff character into screen ID token}
end;
end; {back and check previous input string char}
got_screen_token: {screen ID string is in TOKEN}
string_t_screen (token, window.screen, stat); {interpret screen ID string}
if sys_error(stat) then return;
{
* Init remainder of window descriptor, then process the window ID tokens.
* These tokens start at index P in string S.
}
window.window := 0;
window.pos_x := 0;
window.pos_y := 0;
window.size_x := 0;
window.size_y := 0;
window.name_wind.max := sizeof(window.name_wind.str);
window.name_wind.len := 0;
window.name_icon.max := sizeof(window.name_icon.str);
window.name_icon.len := 0;
window.flags := [sys_winflag_stdout_k, sys_winflag_indir_k];
loop: {back here each new window ID token}
string_token (s, p, token, stat); {get next token from input string}
if string_eos(stat) then return; {hit end of input string ?}
string_upcase (token); {make upper case for token matching}
string_tkpick80 (token,
'-STDOUT -ROOT -DIR -INDIR -NOWM -POS -SIZE -NAME -ICNAME',
pick);
case pick of
{
* -STDOUT
}
1: begin
window.flags := window.flags + [sys_winflag_stdout_k];
window.flags := window.flags + [sys_winflag_indir_k];
window.flags := window.flags - [sys_winflag_dir_k];
end;
{
* -ROOT
}
2: begin
window.flags := window.flags - [sys_winflag_stdout_k];
window.window := -1;
window.flags := window.flags + [sys_winflag_indir_k];
window.flags := window.flags - [sys_winflag_dir_k];
end;
{
* -DIR
}
3: begin
window.flags := window.flags + [sys_winflag_dir_k];
window.flags := window.flags - [sys_winflag_indir_k];
end;
{
* -INDIR
}
4: begin
window.flags := window.flags + [sys_winflag_indir_k];
window.flags := window.flags - [sys_winflag_dir_k];
end;
{
* -NOWM
}
5: begin
window.flags := window.flags + [sys_winflag_nowm_k];
end;
{
* -POS x y
}
6: begin
window.flags := window.flags + [sys_winflag_indir_k];
window.flags := window.flags - [sys_winflag_dir_k];
window.flags := window.flags + [sys_winflag_pos_k];
string_token_int (s, p, window.pos_x, stat);
if sys_error(stat) then return;
string_token_int (s, p, window.pos_y, stat);
if sys_error(stat) then return;
end;
{
* -SIZE x y
}
7: begin
window.flags := window.flags + [sys_winflag_indir_k];
window.flags := window.flags - [sys_winflag_dir_k];
window.flags := window.flags + [sys_winflag_size_k];
string_token_int (s, p, window.size_x, stat);
if sys_error(stat) then return;
string_token_int (s, p, window.size_y, stat);
if sys_error(stat) then return;
end;
{
* -NAME window_name
}
8: begin
string_token (s, p, window.name_wind, stat);
window.flags := window.flags + [sys_winflag_name_k];
end;
{
* -ICNAME icon_name
}
9: begin
string_token (s, p, window.name_icon, stat);
window.flags := window.flags + [sys_winflag_icname_k];
end;
{
* The token is not one of the special keywords. It must therefore be
* a hard window ID number.
}
otherwise
string_t_int (token, window.window, stat);
if sys_error(stat) then return;
window.flags := window.flags - [sys_winflag_stdout_k];
window.flags := window.flags - [sys_winflag_dir_k];
window.flags := window.flags - [sys_winflag_indir_k];
end;
goto loop; {back and process next input string token}
end;
|
unit LayoutsUnit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, DbGridUnit, DB, DBClient, Grids, DBGridEh, StdCtrls,
DialogUnit, MaximizedUnit;
type
{ TLayoutsForm }
TLayoutsForm = class(TDialogForm)
ButtonPanel: TPanel;
Grid: TDBGridEh;
LayoutsSource: TDataSource;
LayoutsDataSet: TClientDataSet;
LayoutsDataSetORDER: TIntegerField;
LayoutsDataSetNAME: TStringField;
OKBtn: TButton;
CancelBtn: TButton;
UpBtn: TButton;
DownBtn: TButton;
DeleteBtn: TButton;
LayoutsDataSetPOINTER: TIntegerField;
SelectBtn: TButton;
procedure OKBtnClick(Sender: TObject);
procedure CancelBtnClick(Sender: TObject);
procedure UpBtnClick(Sender: TObject);
procedure DownBtnClick(Sender: TObject);
procedure DeleteBtnClick(Sender: TObject);
procedure SelectBtnClick(Sender: TObject);
procedure LayoutsDataSetORDERGetText(Sender: TField; var Text: String;
DisplayText: Boolean);
procedure LayoutsSourceDataChange(Sender: TObject; Field: TField);
procedure GridGetCellParams(Sender: TObject; Column: TColumnEh;
AFont: TFont; var Background: TColor; State: TGridDrawState);
private
FSelectedLayout: Integer;
FLayoutMan: TGridLayoutMan;
procedure Initialize(LayoutMan: TGridLayoutMan; SelectedLayout: Integer);
procedure UpdateLayout;
public
class function EditLayout(LayoutMan: TGridLayoutMan; SelectedLayout: Integer): Integer;
end;
var
LayoutsForm: TLayoutsForm;
implementation
uses
DataUnit;
{$R *.dfm}
{ TLayoutsForm }
class function TLayoutsForm.EditLayout(LayoutMan: TGridLayoutMan; SelectedLayout: Integer): Integer;
var
Form: TLayoutsForm;
begin
Form := TLayoutsForm.Create(nil);
try
Form.Initialize(LayoutMan, SelectedLayout);
if Form.ShowModal = mrOK then
begin
Form.UpdateLayout;
Result := Form.FSelectedLayout;
end else
begin
Result := SelectedLayout;
end;
finally
Form.Free;
end;
end;
procedure TLayoutsForm.Initialize(LayoutMan: TGridLayoutMan; SelectedLayout: Integer);
var
I: Integer;
Layout: TGridLayout;
begin
FLayoutMan := LayoutMan;
FSelectedLayout := SelectedLayout;
LayoutsDataSet.CreateDataSet;
for I := 0 to FLayoutMan.Count - 1 do
begin
Layout := FLayoutMan[I];
LayoutsDataSet.Insert;
LayoutsDataSetORDER.AsInteger := I;
LayoutsDataSetNAME.AsString := Layout.Name;
LayoutsDataSetPOINTER.AsInteger := Integer(Layout);
LayoutsDataSet.Post;
end;
end;
procedure TLayoutsForm.UpdateLayout;
var
N, I: Integer;
Layout: TGridLayout;
begin
N := 0;
LayoutsDataSet.First;
while not LayoutsDataSet.Eof do
begin
Layout := TGridLayout(LayoutsDataSetPOINTER.AsInteger);
FLayoutMan.Move(FLayoutMan.IndexOf(Layout), N);
Layout.Name := LayoutsDataSetNAME.AsString;
Inc(N);
LayoutsDataSet.Next;
end;
for I := FLayoutMan.Count - 1 downto N do FLayoutMan.Delete(I);
end;
procedure TLayoutsForm.OKBtnClick(Sender: TObject);
begin
ModalResult := mrOK;
end;
procedure TLayoutsForm.CancelBtnClick(Sender: TObject);
begin
ModalResult := mrCancel;
end;
procedure TLayoutsForm.UpBtnClick(Sender: TObject);
var
P: Integer;
begin
if FSelectedLayout = LayoutsDataSetORDER.AsInteger then Dec(FSelectedLayout);
P := LayoutsDataSetPOINTER.AsInteger;
LayoutsDataSet.Prior;
LayoutsDataSet.Edit;
LayoutsDataSetORDER.AsInteger := LayoutsDataSetORDER.AsInteger + 1;
LayoutsDataSet.Post;
LayoutsDataSet.Locate('POINTER', P, []);
LayoutsDataSet.Edit;
LayoutsDataSetORDER.AsInteger := LayoutsDataSetORDER.AsInteger - 1;
LayoutsDataSet.Post;
end;
procedure TLayoutsForm.DownBtnClick(Sender: TObject);
var
P: Integer;
begin
if FSelectedLayout = LayoutsDataSetORDER.AsInteger then Inc(FSelectedLayout);
P := LayoutsDataSetPOINTER.AsInteger;
LayoutsDataSet.Next;
LayoutsDataSet.Edit;
LayoutsDataSetORDER.AsInteger := LayoutsDataSetORDER.AsInteger - 1;
LayoutsDataSet.Post;
LayoutsDataSet.Locate('POINTER', P, []);
LayoutsDataSet.Edit;
LayoutsDataSetORDER.AsInteger := LayoutsDataSetORDER.AsInteger + 1;
LayoutsDataSet.Post;
end;
procedure TLayoutsForm.DeleteBtnClick(Sender: TObject);
var
P, Order: Integer;
begin
if FSelectedLayout = LayoutsDataSetORDER.AsInteger then FSelectedLayout := -1;
P := LayoutsDataSetPOINTER.AsInteger;
Order := LayoutsDataSetORDER.AsInteger;
LayoutsDataSet.Delete;
LayoutsDataSet.DisableControls;
try
LayoutsDataSet.First;
while not LayoutsDataSet.Eof do
begin
LayoutsDataSet.Edit;
if LayoutsDataSetORDER.AsInteger > Order then
begin
LayoutsDataSetORDER.AsInteger := LayoutsDataSetORDER.AsInteger - 1;
end;
LayoutsDataSet.Post;
LayoutsDataSet.Next;
end;
LayoutsDataSet.Locate('POINTER', P, []);
finally
LayoutsDataSet.EnableControls;
end;
end;
procedure TLayoutsForm.SelectBtnClick(Sender: TObject);
begin
FSelectedLayout := LayoutsDataSetORDER.AsInteger;
Grid.Invalidate;
end;
procedure TLayoutsForm.LayoutsDataSetORDERGetText(Sender: TField;
var Text: String; DisplayText: Boolean);
begin
Text := IntToStr(LayoutsDataSetORDER.AsInteger + 1);
end;
procedure TLayoutsForm.LayoutsSourceDataChange(Sender: TObject;
Field: TField);
var
LayoutExists: Boolean;
begin
LayoutExists := not LayoutsDataSet.Bof or not LayoutsDataSet.Eof;
UpBtn.Enabled := LayoutsDataSetORDER.AsInteger > 0;
DownBtn.Enabled := LayoutsDataSetORDER.AsInteger < (FLayoutMan.Count - 1);
DeleteBtn.Enabled := LayoutExists;
SelectBtn.Enabled := LayoutExists and (FSelectedLayout <> LayoutsDataSetORDER.AsInteger);
end;
procedure TLayoutsForm.GridGetCellParams(Sender: TObject;
Column: TColumnEh; AFont: TFont; var Background: TColor;
State: TGridDrawState);
begin
if LayoutsDataSetORDER.AsInteger = FSelectedLayout then AFont.Style := AFont.Style + [fsBold];
end;
end.
|
unit UBrowseHistory;
interface
uses UxlList;
type
THistory = class
private
FIDList: TxlIntList;
FPos: integer;
public
constructor Create ();
destructor Destroy (); override;
function GetPrior (): integer;
function GetNext (): integer;
procedure Add (id: integer);
procedure Delete (id: integer);
function HasPrior (): boolean;
function HasNext (): boolean;
end;
implementation
uses UxlCommDlgs, UxlFunctions;
constructor THistory.Create ();
begin
FIDList := TxlIntList.Create;
FPOs := -1;
end;
destructor THistory.Destroy ();
begin
FIDList.Free;
inherited;
end;
function THistory.GetPrior (): integer;
begin
if FPos > FIDList.Low then dec (FPos);
result := FIDList[FPos];
end;
function THistory.GetNext (): integer;
begin
if FPos < FIDList.High then inc (FPos);
result := FIDList[FPos];
end;
procedure THistory.Add (id: integer);
var i, n: integer;
begin
if (not FIDList.PosValid(FPos)) or (id <> FIDList[FPos]) then
begin
n := FIDList.High;
for i := n downto FPOs + 1 do
FIDList.Delete (i);
FIDList.Add (id);
FPos := FIDList.High;
end;
end;
procedure THistory.Delete (id: integer);
var i: integer;
begin
i := FIDList.Find (id);
FIDList.Delete (i);
end;
function THistory.HasPrior (): boolean;
begin
result := FPos > FIDList.Low;
end;
function THistory.HasNext (): boolean;
begin
result := FPos < FIDList.High;
end;
end.
|
{
*
* Copyright (C) 2005-2009 UDW-SOFTWARE <http://udw.altervista.org/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
}
unit RlmForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ExtCtrls, IniFiles;
type
TForm3 = class(TForm)
GroupBox1: TGroupBox;
realmlabel: TLabel;
Save: TBitBtn;
Realmlist: TEdit;
Description: TEdit;
Label1: TLabel;
Site: TEdit;
Label2: TLabel;
procedure SaveClick(Sender: TObject);
procedure RealmlistChange(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
edit:boolean;
end;
var
Form3: TForm3;
implementation
uses Main, Tools, Engine, Config;
{$R *.dfm}
// FUNZIONE DI SUPPORTO
function IndexofRealmlist(realmlist:string;combo:Tcombobox):integer;
var i,res:integer;
trovato:boolean;
begin
i:=0;
res:=-1;
trovato:=false;
while (i<=combo.Items.Count) and not (trovato ) do
begin
if realmlist=copy(combo.Items.Strings[i],1,length(realmlist)) then
begin
trovato:=true;
res:=i;
end;
inc(i);
end;
result:=res;
end;
// FUNZIONI DI INTERFACCIA
procedure TForm3.SaveClick(Sender: TObject);
var esistente:boolean;
index: integer;
temp: RlmInf;
begin
temp.addr:='';
if (Realmlist.text<>'') and (Realmlist.text<>RealmOff) then
begin
temp.addr:=Realmlist.text;
if (Description.Text<>'') or (Site.text<>'') then
temp.addr:=temp.addr+' #'+Description.Text;
if Site.text<>'' then temp.addr:=temp.addr+' &RlmSite='+Site.Text;
HandleRlmSyntax(temp);
esistente:=false;
//index:=IndexofRealmlist(temp.rlm,Form1.Realmlist);
index:=0;
while (index<Form1.Realmlist.Items.Count) and (not esistente) do
begin
if copy(Form1.Realmlist.Items.Strings[index],1,length(temp.rlm))=temp.rlm then
esistente:=true
else
inc(index);
end;
if esistente then
if edit then
begin
form1.Realmlist.Items.Strings[index]:=temp.addr;
Form1.Realmlist.Text:=Temp.addr
end
else
begin
MessageDlg(GetText('RlmErr1Dlg',[]),mtError,[mbOk] ,0); // esiste giÓ
exit;
end
else
begin
Form1.Realmlist.Items.Add(temp.addr);
Form1.Realmlist.Text:=Temp.addr
end;
Form3.Close;
end;
end;
procedure TForm3.RealmlistChange(Sender: TObject);
begin
CheckRealmlistDgt(Realmlist.Text);
end;
procedure TForm3.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Form1.Enabled:=true;
end;
procedure TForm3.FormShow(Sender: TObject);
begin
Form1.Enabled:=false;
end;
end.
|
unit UdmBusinessRule;
interface
uses
System.SysUtils, System.Classes, IdBaseComponent, IdCoder, IdCoder3to4,
IdCoderMIME, Windows;
type
TdmBusinessRule = class(TDataModule)
Base64Decoder : TIdDecoderMIME;
private
{ Private declarations }
(***************************************************************************
Variables de la clase BusinessRule
<<Por favor no modificar>>
***************************************************************************)
(***************************************************************************
Variables específicas de la clase BusinessRule
<<Por favor añadir aquí las variables de clase para la regla de negocio>>
***************************************************************************)
(***************************************************************************
Métodos particulares regla de negocio
<<Por favor añadir aquí los métodos específicos de la regla de negocio>>
***************************************************************************)
public
{ Public declarations }
(***************************************************************************
Métodos públicos de la clase BusinessRule
<<Por favor no añadir ningún método adicional>>
***************************************************************************)
procedure process(AInstructions, AProcessUUID, AConnection, ATxValidation : String);
end;
const
(*****************************************************************************
Constantes Generales de la clase BusinessRule
<<Por favor no modificar>>
*****************************************************************************)
STATUS_CODE = 'status_code';
STATUS_DESC = 'status_desc';
(*****************************************************************************
Constantes Específicas de la Regla de Negocio
<<Por favor añadir aquí las nuevas constantes asociadas a la regla>>
*****************************************************************************)
CARACTER_CONCATENA_QUERY_SQL = '+';
CARACTER_CONCATENA_QUERY_SQ_LITE = '||';
NOMBRE_PLANTILLA = 'plantilla.txt';
NOMBRE_PROCESO = 'TdmBusinessRule.process';
var
dmBusinessRule : TdmBusinessRule;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
uses
UUtilidades,
fServerDataModule,
UdmPersistenceQueryClient,
RegularExpressions,
UdmPrevio;
{$R *.dfm}
{ TdmBusinessRule }
(*******************************************************************************
Método central de la regla de negocio, este es el punto de entrada general para
toda regla de negocio, recibe los siguientes parámetros, asociados a la entidad:
[gci_AlarmWakeUp].[CONFIGURATION_ALARM_WAKE_UP_TBL]
- AInstructions : <<Muy similar a un archivo de configuración>>. Se encarga de
almacenar valores parametrizados para una regla de negocio
específica, corresponse al campo (parametros_inicio)
- AProcessUUID : Identificador único de una regla de negocio, corresponde al
campo (id_transaccion)
- AConnection : Contiene las cadenas de conexión de base de datos, las cuales
se deben añadir en el campo (conexiones)
- ATxValidation : Aplica para aquellas reglas de negocio que deseen utilizar un
validador de parámetros de entrada, se configura en el campo
(validaciones)
*******************************************************************************)
{
Uso del cascaron:
1. En las constantes del ServerDatamodule se debe asignar 'SI' a los
servicios base que se van a utilizar en la RN.
2. Los parametros de inicialización se deben configurar en la entidad
"[gci_conf].[PARAMETROS_CONFIGURACION_TBL]", correspondiente a la base
de datos de cada proyecto.
SERVICE_PORT=21034
CALL_INTEGRATION_HOST=127.0.0.1
CALL_INTEGRATION_TOOLS_PORT=21005
CALL_INTEGRATION_PERSISTENCE_PORT=21012
MONITOR_HOST=127.0.0.1
MONITOR_PORT=50000
JANUA_HOST=127.0.0.1
JANUA_PORT=21020
Se debe tener en cuenta que la iniciliazacion del servicio tiene tres
instancias:
a) Consulta en linea:
Como primera opcion se consultan los parametros de inicializacion al
servicio "xZero", posteriormente el cascaron guarda los parametros
en un archivo local que será utilizado mas adelante en caso de que el
servicio "xZero" no este disponible.
b) Consulta en archivo:
Si el Servicio "xZero" no está disponible los parametros de
inicializacion se toman del archivo guardado como backup.
c) Parametros por defecto:
Si no esta disponible el servicio "xZero" y tampoco existe archivo
de configuracion el cascaron toma los parametros por defecto
mostrados anteriormente.
3. Para renombrar el proyecto se debe ubicar primero en el Project Manager,
luego se realizar click derecho sobre el nombre del ejecutable del servidor
y seleccionar la opcion rename. Al renombrar se debe tener en cuenta:
a) El servicio se debe nombrar:
'x' + Nombre de la base donde estan los parametros de inicializacion +
'_' + Nombre asignado por el desarrollador
Ejemplo: 'xSGCB_Saldos'
a) El servicio se va a llamar igual que el ejecutable.
b) El archivo de configuracion generado tiene el mismo nombre del
ejecutable con extension ".INI"
4. La descripcion de la respuesta (StatusDesc) se devuelve en la variable
"FMensajeError" de esta clase (dmReglaNegocio).
5. La respuesta del servicio se devuelve en la variable
"FMensajeRespuesta" de esta clase (dmReglaNegocio).
6. Metodo a implementar Regla de Negocio:
El metodo a implementar es "Procesar" de esta clase (dmReglaNegocio)..
7. Datos de entrada:
Los datos de entrada vienen en la variable "ADatosEntrada" del
metodo "TdmReglaNegocio.Procesar" de esta clase (dmReglaNegocio).}
procedure TdmBusinessRule.process(AInstructions, AProcessUUID, AConnection, ATxValidation: String);
var
strProceso : String;
strMensajeError : String;
AGUID : String;
xPrevio : TdmPrevio;
strMessage : String;
begin
try
try
AGUID := TUtilidades.getGUID;
strProceso := TUtilidades.base64Decode(AInstructions);
xPrevio := TProcesarMensaje<TdmPrevio>.cadenaAObjeto(strProceso);
TMonitor.sendInfoMessage(AGUID, xPrevio.Fnombre_proceso, NOMBRE_PROCESO, 'Inicio Regla de Negocio.');
xPrevio.fguid := AGUID;
If xPrevio.iniciarProceso(strMessage) Then
xPrevio.procesarArchivo
Else Begin
TMonitor.sendErrorMessage(AGUID, xPrevio.Fnombre_proceso, NOMBRE_PROCESO, strMessage);
End;
// FreeAndNil(xPrevio);
except on e : exception do
TMonitor.sendErrorMessage(AGUID, xPrevio.Fnombre_proceso, NOMBRE_PROCESO, strMensajeError + e.Message);
end;
finally
TMonitor.sendInfoMessage(AGUID, xPrevio.Fnombre_proceso, NOMBRE_PROCESO, 'Fin Regla de Negocio.');
TMonitor.endMonitorProcess(AGUID);
end;
end;
end.
|
unit BancoAgenciaController;
interface
uses mvcframework, mvcframework.Commons,
System.SysUtils,
MVCFramework.SystemJSONUtils;
type
[MVCDoc('CRUD Banco Agencia')]
[MVCPath('/banco-agencia')]
TBancoAgenciaController = class(TMVCController)
public
[MVCDoc('Retorna uma lista de objetos')]
[MVCPath('/($filtro)')]
[MVCHTTPMethod([httpGET])]
procedure ConsultarLista(Context: TWebContext);
[MVCDoc('Retorna um objeto com base no ID')]
[MVCPath('/($id)')]
[MVCHTTPMethod([httpGET])]
procedure ConsultarObjeto(id: Integer);
[MVCDoc('Insere um novo objeto')]
[MVCPath]
[MVCHTTPMethod([httpPOST])]
procedure Inserir(Context: TWebContext);
[MVCDoc('Altera um objeto com base no ID')]
[MVCPath('/($id)')]
[MVCHTTPMethod([httpPUT])]
procedure Alterar(id: Integer);
[MVCDoc('Exclui um objeto com base no ID')]
[MVCPath('/($id)')]
[MVCHTTPMethod([httpDelete])]
procedure Excluir(id: Integer);
end;
implementation
{ TBancoAgenciaController }
uses BancoAgenciaService, BancoAgencia, Commons, Filtro;
procedure TBancoAgenciaController.ConsultarLista(Context: TWebContext);
var
FiltroUrl, FilterWhere: string;
FiltroObj: TFiltro;
begin
FiltroUrl := Context.Request.Params['filtro'];
if FiltroUrl <> '' then
begin
ConsultarObjeto(StrToInt(FiltroUrl));
exit;
end;
filterWhere := Context.Request.Params['filter'];
try
if FilterWhere = '' then
begin
Render<TBancoAgencia>(TBancoAgenciaService.ConsultarLista);
end
else begin
// define o objeto filtro
FiltroObj := TFiltro.Create(FilterWhere);
Render<TBancoAgencia>(TBancoAgenciaService.ConsultarListaFiltroValor(FiltroObj.Campo, FiltroObj.Valor));
end;
except
on E: EServiceException do
begin
raise EMVCException.Create
('Erro no Servidor [Consultar Lista Banco Agencia] - Exceção: ' + E.Message,
E.StackTrace, 0, 500);
end
else
raise;
end;
end;
procedure TBancoAgenciaController.ConsultarObjeto(id: Integer);
var
BancoAgencia: TBancoAgencia;
begin
try
BancoAgencia := TBancoAgenciaService.ConsultarObjeto(id);
if Assigned(BancoAgencia) then
Render(BancoAgencia)
else
raise EMVCException.Create
('Registro não localizado [Consultar Objeto Banco Agencia]', '', 0, 404);
except
on E: EServiceException do
begin
raise EMVCException.Create
('Erro no Servidor [Consultar Objeto Banco Agencia] - Exceção: ' + E.Message,
E.StackTrace, 0, 500);
end
else
raise;
end;
end;
procedure TBancoAgenciaController.Inserir(Context: TWebContext);
var
BancoAgencia: TBancoAgencia;
begin
try
BancoAgencia := Context.Request.BodyAs<TBancoAgencia>;
BancoAgencia.IdBanco := BancoAgencia.Banco.Id;
except
on E: EServiceException do
begin
raise EMVCException.Create('Objeto inválido [Inserir Banco Agencia] - Exceção: ' +
E.Message, E.StackTrace, 0, 400);
end
else
raise;
end;
try
TBancoAgenciaService.Inserir(BancoAgencia);
Render(TBancoAgenciaService.ConsultarObjeto(BancoAgencia.Id));
finally
end;
end;
procedure TBancoAgenciaController.Alterar(id: Integer);
var
BancoAgencia, BancoAgenciaDB: TBancoAgencia;
begin
try
BancoAgencia := Context.Request.BodyAs<TBancoAgencia>;
BancoAgencia.IdBanco := BancoAgencia.Banco.Id;
except
on E: EServiceException do
begin
raise EMVCException.Create('Objeto inválido [Alterar Banco Agencia] - Exceção: ' +
E.Message, E.StackTrace, 0, 400);
end
else
raise;
end;
if BancoAgencia.Id <> id then
raise EMVCException.Create('Objeto inválido [Alterar Banco Agencia] - ID do objeto difere do ID da URL.',
'', 0, 400);
BancoAgenciaDB := TBancoAgenciaService.ConsultarObjeto(BancoAgencia.id);
if not Assigned(BancoAgenciaDB) then
raise EMVCException.Create('Objeto com ID inválido [Alterar Banco Agencia]',
'', 0, 400);
try
if TBancoAgenciaService.Alterar(BancoAgencia) > 0 then
Render(TBancoAgenciaService.ConsultarObjeto(BancoAgencia.Id))
else
raise EMVCException.Create('Nenhum registro foi alterado [Alterar Banco]',
'', 0, 500);
finally
FreeAndNil(BancoAgenciaDB);
end;
end;
procedure TBancoAgenciaController.Excluir(id: Integer);
var
BancoAgencia: TBancoAgencia;
begin
BancoAgencia := TBancoAgenciaService.ConsultarObjeto(id);
if not Assigned(BancoAgencia) then
raise EMVCException.Create('Objeto com ID inválido [Excluir Banco Agencia]',
'', 0, 400);
try
if TBancoAgenciaService.Excluir(BancoAgencia) > 0 then
Render(200, 'Objeto excluído com sucesso.')
else
raise EMVCException.Create('Nenhum registro foi excluído [Excluir Banco Agencia]',
'', 0, 500);
finally
FreeAndNil(BancoAgencia)
end;
end;
end.
|
unit UFrmDebugs;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, SynEdit,
SynEditHighlighter, SynHighlighterGeneral, SynEditCodeFolding,
SynHighlighterJSON, SynHighlighterTeX;
type
TFrmDebugs = class(TForm)
PnlBar: TPanel;
SynEdit: TSynEdit;
SynGeneralSyn: TSynGeneralSyn;
ChBoxWordWrap: TCheckBox;
SynJSONSyn: TSynJSONSyn;
CmBoxSelHighLighter: TComboBox;
lblSelHighLighter: TLabel;
SynTeXSyn1: TSynTeXSyn;
procedure ChBoxWordWrapClick(Sender: TObject);
procedure CmBoxSelHighLighterSelect(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
FMsgCount: Cardinal;
FStMsg: TStrings;
public
procedure AddDbgMessage(DbgMsgStr: String);
{ Public declarations }
end;
var
FrmDebugs: TFrmDebugs;
implementation
{$R *.dfm}
{ TFrmDebugs }
procedure TFrmDebugs.AddDbgMessage(DbgMsgStr: String);
begin
SynEdit.Lines.Add('');
SynEdit.Lines.Add(DateTimeToStr(Date + time) + ' Message ID: ' + UIntToStr(FMsgCount));
FStMsg.Text := DbgMsgStr;
SynEdit.Lines.AddStrings(FStMsg);
Inc(FMsgCount);
end;
procedure TFrmDebugs.ChBoxWordWrapClick(Sender: TObject);
begin
if ChBoxWordWrap.Checked then
SynEdit.WordWrap := true
else
SynEdit.WordWrap := false;
end;
procedure TFrmDebugs.CmBoxSelHighLighterSelect(Sender: TObject);
begin
case CmBoxSelHighLighter.ItemIndex of
0: SynEdit.Highlighter := SynGeneralSyn;
1: SynEdit.Highlighter := SynJSONSyn;
end;
end;
procedure TFrmDebugs.FormClose(Sender: TObject; var Action: TCloseAction);
begin
FStMsg.Free;
end;
procedure TFrmDebugs.FormCreate(Sender: TObject);
begin
FStMsg := TStringList.Create;
CmBoxSelHighLighterSelect(Nil);
ChBoxWordWrapClick(Nil);
end;
end.
|
unit MathMatrices;
{$mode objfpc}{$H+}{$interfaces corba}
interface
uses
Classes, SysUtils, MathBasics;
type
TIMatrix = interface(TIMathObject)
function IsIn(S: TIMathSet):Boolean;
property components[index:Array of Integer]:TIMathObject;default;
end;
TCMatrix = class(TIMatrix)
private
_components: Array of Array of TIMathObject;
function GetComponent(idx: Array of Integer):TIMathObject;
procedure SetComponent(idx: Array of Integer; const component:TIMathObject);
public
function IsIn(S: TIMathSet):Boolean;
property components[index:Array of Integer]:TIMathObject read GetComponent write SetComponent; default;
end;
implementation
function TCMatrix.GetComponent(idx: Array of Integer):TIMathObject;
begin
Result := _components[idx[0], idx[1]];
end;
procedure TCMatrix.SetComponent(idx: Array of Integer; const component:TIMathObject);
begin
_components[idx[0], idx[1]] := component;
end;
function TCMatrix.IsIn(S: TIMathSet):Boolean;
begin
Result := S.Contains(TIMatrix(Self));
end;
end.
|
unit ceregistry;
{
Wrapper to replace the creating and destroying of default level registry objects with a uniform method
}
{$mode delphi}
interface
uses
{$ifdef darwin}
macPort,
{$endif}
Classes, SysUtils, registry;
type
TCEReg=class
private
reg: TRegistry;
openedregistry: boolean;
needsforce: boolean;
triedforce: boolean;
lastforce: qword;
function getRegistry(force: boolean):boolean;
public
procedure writeBool(registryValueName: string; value: boolean);
function readBool(registryValueName:string; def: boolean=false): boolean;
procedure writeInteger(registryValueName: string; value: integer);
function readInteger(registryValueName:string; def: integer=0): integer;
procedure writeString(registryValueName: string; value: string);
function readString(registryValueName:string; def: string=''): string;
procedure writeStrings(registryValueName: string; sl: TStrings);
procedure readStrings(registryValueName: string; sl: TStrings);
end;
var cereg: TCEReg;
implementation
uses mainunit2;
function TCEReg.getRegistry(force: boolean):boolean;
begin
{$ifdef darwin}
//all registry objects access the same object. and that object has the current key set...
if reg<>nil then
reg.OpenKey('\Software\'+strCheatEngine+'\', false);
{$endif}
if not openedregistry then
begin
if triedforce and (gettickcount64<lastforce+2000) then exit(false);
if needsforce and (force=false) then exit(false); //don't bother
if reg=nil then
reg:=tregistry.create;
openedregistry:=reg.OpenKey('\Software\'+strCheatEngine+'\', force);
if (not openedregistry) then
begin
if force then
begin
triedforce:=true;
lastforce:=gettickcount64; //don't bother with trying for a few seconds (perhaps the user will fix it though ...)
end
else
needsforce:=true;
end;
{$ifdef darwin}
macPortFixRegPath;
{$endif}
end;
result:=openedregistry;
end;
procedure TCEReg.writeStrings(registryValueName: string; sl: TStrings);
begin
if getregistry(true) then
begin
try
reg.WriteStringList(registryValueName, sl);
except
end;
end;
end;
procedure TCEReg.readStrings(registryValueName: string; sl: TStrings);
begin
sl.Clear;
if getregistry(false) and (reg.ValueExists(registryValueName)) then
begin
try
reg.ReadStringList(registryValueName, sl);
except
end;
end;
end;
function TCEReg.readBool(registryValueName: string; def: boolean=false): boolean;
begin
result:=def;
if getregistry(false) and (reg.ValueExists(registryValueName)) then
begin
try
result:=reg.ReadBool(registryValueName);
except
end;
end;
end;
procedure TCEReg.writeBool(registryValueName: string; value: boolean);
begin
if getregistry(true) then
begin
try
reg.WriteBool(registryValueName, value);
except
end;
end;
end;
function TCEReg.readInteger(registryValueName: string; def: integer=0): integer;
begin
result:=def;
if getregistry(false) and (reg.ValueExists(registryValueName)) then
result:=reg.ReadInteger(registryValueName);
end;
procedure TCEReg.writeInteger(registryValueName: string; value: integer);
begin
if getregistry(true) then
reg.WriteInteger(registryValueName, value);
end;
function TCEReg.readString(registryValueName: string; def: string=''): string;
begin
result:=def;
if getregistry(false) and (reg.ValueExists(registryValueName)) then
result:=reg.ReadString(registryValueName);
end;
procedure TCEReg.writeString(registryValueName: string; value: string);
begin
if getregistry(true) then
reg.WriteString(registryValueName, value);
end;
initialization
cereg:=TCEReg.Create;
end.
|
unit URepositorioOS;
interface
uses
UOs
, UEquipamento
, UCliente
, UEntidade
, URepositorioDB
, URepositorioCliente
, URepositorioEquipamento
, SqlExpr
;
type
TRepositorioOS = class (TRepositorioDB<TOS>)
private
FRepositorioCliente: TRepositorioCliente;
FRepositorioEquipamento: TRepositorioEquipamento;
public
constructor Create;
destructor Destroy; override;
procedure AtribuiDBParaEntidade (const coOS: TOS); override;
procedure AtribuiEntidadeParaDB (const coOS: TOS;
const coSQLQuery: TSQLQuery); override;
end;
implementation
uses
UDM
, SysUtils
;
{TRepositorioOS}
constructor TRepositorioOS.Create;
begin
inherited Create (TOS, TBL_OS, FLD_ENTIDADE_ID, STR_OS);
FRepositorioCliente := TRepositorioCliente.Create;
FRepositorioEquipamento := TRepositorioEquipamento.Create;
end;
destructor TRepositorioOS.Destroy;
begin
FreeAndNil(FRepositorioCliente);
FreeAndNil(FRepositorioEquipamento);
inherited;
end;
procedure TRepositorioOS.AtribuiDBParaEntidade(const coOS: TOS);
begin
inherited;
with FSQLSelect do
begin
coOS.DATA_ENTRADA := FieldByName(FLD_OS_DATA_ENTRADA).AsDateTime;
coOS.CLIENTE := TCLIENTE(
FRepositorioCliente.Retorna(FieldByName(FLD_OS_ID_CLIENTE).AsInteger));
coOS.EQUIPAMENTO := TEQUIPAMENTO (
FRepositorioEquipamento.Retorna(FieldByName(FLD_OS_ID_EQUIPAMENTO).AsInteger));
end;
end;
procedure TRepositorioOS.AtribuiEntidadeParaDB(const coOS: TOS; const coSQLQuery: TSQLQuery);
begin
inherited;
with coSQLQuery do
begin
ParamByName(FLD_OS_DATA_ENTRADA).AsDateTime := coOS.DATA_ENTRADA;
ParamByName(FLD_OS_ID_CLIENTE).AsInteger := coOS.CLIENTE.ID;
ParamByName(FLD_OS_ID_EQUIPAMENTO).AsInteger := coOS.EQUIPAMENTO.ID;
end;
end;
end.
|
unit projectapi_lib;
{$mode objfpc}{$H+}
interface
uses
LazFileUtils,
Forms, Controls, FileUtil, Dialogs,
ProjectIntf, PackageIntf, LazIDEIntf,
Classes, SysUtils;
resourcestring
rs_ProjectAPI_Name = 'API Application';
rs_ProjectAPI_Description = 'create API application based on FastPlaz';
type
{ TProjectAPIFastPlazDescriptor }
TProjectAPIFastPlazDescriptor = class(TProjectDescriptor)
private
Header: TStringList;
ProjectName: string;
function ScanDirAndCopy(SourceDirectory, TargetDirectory: string): boolean;
function GenerateStructure(TargetDirectory: string;
DefaultBinaryFile: string = ''): boolean;
public
constructor Create; override;
destructor Destroy; override;
function GetLocalizedName: string; override;
function GetLocalizedDescription: string; override;
function InitProject(AProject: TLazProject): TModalResult; override;
function CreateStartFiles(AProject: TLazProject): TModalResult; override;
end;
implementation
uses fastplaz_tools_register, modsimple_lib, projectapi_wzd;
const
CSS_APISTRUCTURE_FAILED = 'Failed create directory structure';
CSS_API_TEMPLATEFOLDER = 'api';
{ TProjectAPIFastPlazDescriptor }
function TProjectAPIFastPlazDescriptor.ScanDirAndCopy(SourceDirectory,
TargetDirectory: string): boolean;
var
Rec: TSearchRec;
R: integer;
lsFileSource, lsFileTarget, lsSubDir: string;
begin
Result := True;
try
R := FindFirst(SourceDirectory, faAnyFile, Rec);
while R = 0 do
begin
if ((Rec.Attr and faDirectory) <> 0) and (Rec.Name <> '.') and
(Rec.Name <> '..') then
begin
lsSubDir := extractfilepath(SourceDirectory) + Rec.Name;
ForceDirectories(TargetDirectory + DirectorySeparator + Rec.Name);
ScanDirAndCopy(lsSubDir + DirectorySeparator + '*', TargetDirectory +
DirectorySeparator + Rec.Name);
end
else
begin
if ((Rec.Name <> '.') and (Rec.Name <> '..')) then
begin
lsFileSource := extractfilepath(SourceDirectory) + Rec.Name;
lsFileTarget := TargetDirectory + DirectorySeparator + Rec.Name;
CopyFile(lsFileSource, lsFileTarget);
end;
end;
R := FindNext(Rec);
end;
finally
FindClose(Rec);
end;
end;
function TProjectAPIFastPlazDescriptor.GenerateStructure(TargetDirectory: string;
DefaultBinaryFile: string): boolean;
var
Pkg: TIDEPackage;
fastplaz_package_dir, s: string;
i: integer;
headerHtaccess : TStringList;
begin
TargetDirectory := IncludeTrailingPathDelimiter(TargetDirectory);
if not ForceDirectoriesUTF8(TargetDirectory) then
begin
ShowMessage(CSS_APISTRUCTURE_FAILED);
exit;
end;
Pkg := PackageEditingInterface.FindPackageWithName('fastplaz_tools');
fastplaz_package_dir := Pkg.DirectoryExpanded;
ScanDirAndCopy(fastplaz_package_dir + DirectorySeparator +
'templates' + DirectorySeparator + CSS_API_TEMPLATEFOLDER +
DirectorySeparator + '*',
TargetDirectory);
// root .htaccess
//s := LazarusIDE.ActiveProject.LazCompilerOptions.TargetFilename;
s := ExtractFileName(TargetDirectory);
if s = '' then
s := 'your_binary_file';
if DefaultBinaryFile <> '' then
s := DefaultBinaryFile;
with TStringList.Create do
begin
LoadFromFile(fastplaz_package_dir + 'templates' + DirectorySeparator +
CSS_API_TEMPLATEFOLDER + DirectorySeparator + '.htaccess');
Text := StringReplace(Text, 'your_binary_file', s, [rfReplaceAll]);
headerHtaccess := TStringList.Create;
headerHtaccess.Text:= '';
for i := 0 to Header.Count-1 do
begin
s := 'SetEnvIf '+Header[i]+' "(.*)" '+Header[i]+'=$1';
headerHtaccess.Add( s);
end;
Text := StringReplace(Text, '#environment', headerHtaccess.Text, [rfReplaceAll]);
headerHtaccess.Free;
try
SaveToFile(TargetDirectory + DirectorySeparator + '.htaccess');
except
end;
Free;
end;
Result := False;
end;
constructor TProjectAPIFastPlazDescriptor.Create;
begin
inherited Create;
Name := 'FFastPlazAPIApplication';
Header := TStringList.Create;
end;
destructor TProjectAPIFastPlazDescriptor.Destroy;
begin
Header.Free;
inherited Destroy;
end;
function TProjectAPIFastPlazDescriptor.GetLocalizedName: string;
begin
//Result:=inherited GetLocalizedName;
Result := rs_ProjectAPI_Name;
end;
function TProjectAPIFastPlazDescriptor.GetLocalizedDescription: string;
begin
//Result:=inherited GetLocalizedDescription;
Result := rs_ProjectAPI_Description;
end;
function TProjectAPIFastPlazDescriptor.InitProject(AProject: TLazProject): TModalResult;
var
Source: TStringList;
MainFile: TLazProjectFile;
projectTitle, targetExecutable: string;
isCreateStructure: boolean;
begin
//Result := inherited InitProject(AProject);
ProjectName := 'fastplazapi';
targetExecutable := '.' + DirectorySeparator + ProjectName + _APP_EXTENSION;
Header.Clear;
with TfProjectAPIWizard.Create(nil) do
begin
edt_WebRootDir.Text := GetUserDir;
if ShowModal <> mrOk then
begin
Result := mrNo;
Free;
Exit;
end;
projectTitle := ucwords(edt_ProjectName.Text);
ProjectName := LowerCase(edt_ProjectName.Text);
ProjectName := StringReplace(ProjectName, ' ', '', [rfReplaceAll]);
ProjectName := StringReplace(ProjectName, '.', '', [rfReplaceAll]);
if edt_WebRootDir.Text <> '' then
begin
if edt_WebRootDir.Text <> GetUserDir then
targetExecutable := IncludeTrailingPathDelimiter(edt_WebRootDir.Text) +
ProjectName + _APP_EXTENSION;
end;
Header.Text := mem_Header.Lines.Text;
isCreateStructure := cbx_GenerateStructure.Checked;
Free;
end;
Result := inherited InitProject(AProject);
MainFile := AProject.CreateProjectFile(ProjectName + '.lpr');
MainFile.IsPartOfProject := True;
AProject.AddFile(MainFile, False);
AProject.MainFileID := 0;
// project source
Source := TStringList.Create;
with Source do
begin
Add('program ' + ProjectName + ';');
Add('');
Add('{$mode objfpc}{$H+}');
Add('');
Add('uses');
Add(' {$IFNDEF Windows}cthreads,{$ENDIF}');
Add(' fpcgi, sysutils, fastplaz_handler, common, ' + LowerCase(ProjectName) + '_controller;');
Add('');
Add('{$R *.res}');
Add('');
Add('begin');
Add(' Application.Title := string( Config.GetValue(_SYSTEM_SITENAME, _APP));');
Add(' Application.Email := string( Config.GetValue(_SYSTEM_WEBMASTER_EMAIL,UTF8Decode(''webmaster@'' + GetEnvironmentVariable(''SERVER_NAME''))));');
Add(' Application.DefaultModuleName := string( Config.GetValue(_SYSTEM_MODULE_DEFAULT, ''main''));');
Add(' Application.ModuleVariable := string( Config.GetValue(_SYSTEM_MODULE_VARIABLE, ''mod''));');
Add(' Application.AllowDefaultModule := True;');
Add(' Application.RedirectOnErrorURL := string( Config.GetValue(_SYSTEM_ERROR_URL, ''/''));');
Add(' Application.RedirectOnError:= Config.GetValue( _SYSTEM_ERROR_REDIRECT, false);');
Add('');
Add(' Application.OnGetModule := @FastPlasAppandler.OnGetModule;');
Add(' Application.PreferModuleName := True;');
Add(' //{$if (fpc_version=3) and (fpc_release>=0) and (fpc_patch>=4)}');
Add(' {$if FPC_FULlVERSION >= 30004}');
Add(' Application.LegacyRouting := True;');
Add(' {$endif}');
Add('');
Add(' Application.Initialize;');
Add(' Application.Run;');
Add('end.');
end;
{$ifdef windows}
AProject.MainFile.SetSourceText(Source.Text, True);
{$else}
AProject.MainFile.SetSourceText(Source.Text);
{$endif}
FreeAndNil(Source);
// package
AProject.AddPackageDependency('fastplaz_runtime');
AProject.AddPackageDependency('LCL');
// compiler options
AProject.Title := projectTitle;
AProject.LazCompilerOptions.UnitOutputDirectory :=
'lib' + DirectorySeparator + '$(TargetCPU)-$(TargetOS)';
AProject.LazCompilerOptions.Win32GraphicApp := False;
AProject.LazCompilerOptions.TargetFilenameApplyConventions := False;
AProject.LazCompilerOptions.TargetFilename := targetExecutable;
//AProject.LazCompilerOptions.CustomConfigFile := True;
AProject.LazCompilerOptions.ConfigFilePath := 'extra.cfg';
AProject.Flags := AProject.Flags - [pfMainUnitHasCreateFormStatements];
// web dir structure
if isCreateStructure then
begin
GenerateStructure(ExtractFilePath(targetExecutable), ProjectName + _APP_EXTENSION);
end;
Result := mrOk;
end;
function TProjectAPIFastPlazDescriptor.CreateStartFiles(AProject:
TLazProject): TModalResult;
var
Pkg: TIDEPackage;
filename: string;
begin
//Result := inherited CreateStartFiles(AProject);
Pkg := PackageEditingInterface.FindPackageWithName('fastplaz_runtime');
FastPlazRuntimeDirectory := Pkg.DirectoryExpanded;
bCreateProject := True;
bExpert := False;
_GlobalProjectName := ProjectName;
LazarusIDE.DoNewEditorFile(TFileRouteDescModule.Create, 'routes.pas', '',
[nfIsPartOfProject, nfOpenInEditor, nfCreateDefaultSrc]);
LazarusIDE.DoNewEditorFile(TFileDescDefaultModule.Create( True),
LowerCase(ProjectName) + '_controller.pas', '',
[nfIsPartOfProject, nfOpenInEditor, nfCreateDefaultSrc]);
// open readme file
filename := FastPlazRuntimeDirectory + '..' + DirectorySeparator +
'docs' + DirectorySeparator + 'README-new api project.txt';
if FileExists(filename) then
begin
LazarusIDE.DoOpenEditorFile(filename, -1, -1, [ofAddToRecent]);
end;
bCreateProject := False;
Result := mrOk;
end;
end.
|
(*
Contient des fonctions mathématiques, basiques et trigonométriques optimisées.
-------------------------------------------------------------------------------------------------------------
@created(24/02/2019)
@author(J.Delauney (BeanzMaster))
Historique : @br
@unorderedList(
@item(Creation : 24/02/2019)
@item(Mise à jour : )
)
-------------------------------------------------------------------------------------------------------------
@bold(Notes :)@br
Quelques liens :
@unorderedList(
@item(http://lab.polygonal.de/2007/07/18/fast-and-accurate-sinecosine-approximation/)
@item(https://en.wikipedia.org/wiki/Fast_inverse_square_root)
@item(https://en.wikipedia.org/wiki/Taylor_series)
@item(https://stackoverflow.com/questions/18662261/fastest-implementation-of-sine-cosine-and-square-root-in-c-doesnt-need-to-b)
@item(https://en.wikipedia.org/wiki/Newton%27s_method)
@item(http://allenchou.net/2014/02/game-math-faster-sine-cosine-with-polynomial-curves/)
@item(http://www.ue.eti.pg.gda.pl/~wrona/lab_dsp/cw04/fun_aprox.pdf)
@item(http://www.netlib.org/cephes/)
@MatLab
@WolFram
)
-------------------------------------------------------------------------------------------------------------
@bold(Dependances) : Aucune
-------------------------------------------------------------------------------------------------------------
@bold(Credits :)@br
@unorderedList(
@item(J.Delauney (BeanzMaster))
)
-------------------------------------------------------------------------------------------------------------
@bold(LICENCE) : MPL / GPL
------------------------------------------------------------------------------------------------------------- *)
unit BZFastMath;
//==============================================================================
{$mode objfpc}{$H+}
{$i ..\bzscene_options.inc}
//==============================================================================
interface
uses
Classes, SysUtils;
//==============================================================================
{ Retourne le Cosinus de x. Précision 4E-8 }
function FastCosLUT(x:Single):Single;
{ Retourne le Sinus de x. Précision 4E-8 }
function FastSinLUT(x:Single):Single;
{ Retourne la tangente de x. Précision 4E-8 }
function FastTanLUT(x:Single):Single;
{ Retourne le Sinus Invers de X }
Function FastSinc(x: Single): Single;
{ Retourne la tangente Inverse de X }
Function FastTan(x:Single):Single;
{ Retourne l'arc tangente de x }
Function FastArcTan(x:Single):Single;
{ Retourne l'arc Tangente de y par x. Approximation, précis à 0.07 rads. }
Function FastArcTan2(y, x: Single): Single;
{ Retourne l'arc Sinus de X }
Function FastArcSine(Const x: Single): Single;
{ Retourne l'arc Cosinus de X }
Function FastArcCosine(const X: Single): Single;
{ Retourne la racine carré inverse de Value }
Function FastInvSqrt(Const Value: Single): Single;
{ Retourne la racine carré de Value }
Function FastSqrt(Const Value: Single): Single;
//Function FastSqrt(Const Value: Double): Double;
{ Retourne le logarithme naturel de X }
Function FastLn(Const X: Single): Single;
{ Retourne l'exponentiel de X }
Function FastExp(x:Single):Single;
{ Retourne le logarithme naturel de X }
Function FastLog(x:Single):Single;
{ Retourne le logarithme naturel de X base 2 }
Function FastLog2(X: Single): Single;
{ Retourne le logarithme naturel de X base 10 }
Function FastLog10(X: Single): Single;
{ Retourne le logarithme exponentiel de X par N }
Function FastLDExp(x: Single; N: Integer): Single;
{ Retourne le logarithme exponentiel de X par N }
Function FastLNXP1(Const x: Single): Single;
{ Retourne la valeur absolue de X }
Function FastAbs(f:single):single;
{ Retourne le négatif de X }
Function FastNeg(f:single):single;
{ Retourne le signe de f. @br
@unorderedlist(
@item(0 si null)
@item(+1 si positif)
@item(-1 si négatif)) }
Function FastSign(f:single):longint;
//function FastPower(i:single;n:integer):single;
{ Retourne la puissance de base par Power }
Function FastPower(Base: Single; Power: Integer): Single;
{ Initalisation pour les tables de Sinus et Cosinus précalculés }
procedure _InitSinCosTanLUT;
{ Libération des tables de Sinus et Cosinus précalculés. Initialisées Par _InitSinCosLUT }
procedure _DoneSinCosTanLUT;
//==============================================================================
implementation
Uses Math;
//==============================================================================
// On defini quelques valeurs internes en vue d'optimiser les calculs pour une utilisation strictement en interne
Const
_cInfinity = 1e1000;
_cPI: double = 3.1415926535897932384626433832795; //3.141592654;
_c2PI: Single = 6.283185307;
_cPIdiv4: Single = 0.785398163;
_c3PIdiv4: Single = 2.35619449;
_cZero: Single = 0.0;
_cOne: Single = 1.0;
_cEpsilon: Single = 1e-10;
_cEulerNumber = 2.71828182846;
//-----[ INCLUDE IMPLEMENTATION ]-----------------------------------------------
{$ifdef USE_ASM}
{$ifdef CPU64}
{$ifdef UNIX}
{$ifdef USE_ASM_AVX}
{$I fastmath_native_imp.inc}
{$I fastmath_unix64_avx_imp.inc}
{$else}
{$I fastmath_native_imp.inc}
{$I fastmath_unix64_sse_imp.inc}
{$endif}
{$else} // windows
{$ifdef USE_ASM_AVX}
{$I fastmath_native_imp.inc}
{$I fastmath_unix64_avx_imp.inc}
{$else}
{$I fastmath_native_imp.inc}
{$I fastmath_win64_sse_imp.inc}
{$endif}
{$endif}
{$else} //cpu32
{$ifdef USE_ASM_AVX}
{$I fastmath_native_imp.inc}
{$I fastmath_intel32_avx_imp.inc}
{$else}
{$I fastmath_native_imp.inc}
{$I fastmath_intel32_sse_imp.inc}
{$endif}
{$endif}
{$else}
{$I fastmath_native_imp.inc}
{$endif}
end.
|
unit trans_3d;
(**)interface(**)
{p3df- used by tiny_lib}
type
p3df=record
x,y,z:real;
end;
Trans_Point3d=object
public
point3d:p3df;
procedure Translate(p:p3df);
procedure Scale(p:p3df);{get ratios sx,sy,sz.. in range 0..size-1 i.e translate by min later}
procedure Rotate_x(Angle:real);
procedure Rotate_y(Angle:real);
procedure Rotate_z(Angle:real);
(* procedure Rotate3d(p1,p2:p3df;angle:real);{rotate around 3d line} *)
end;{object}
(**)Implementation(**)
procedure Trans_Point3d.Translate(p:p3df);
begin
point3d.x:=point3d.x+p.x;
point3d.y:=point3d.y+p.y;
point3d.z:=point3d.z+p.z;
end;
procedure Trans_Point3d.Scale(p:p3df);
begin
point3d.x:=point3d.x*p.x;
point3d.y:=point3d.y*p.y;
point3d.z:=point3d.z*p.z;
end;
procedure Trans_Point3d.Rotate_x(Angle:real);{rotate yz around x anti-clock}
Var
pt:p3df; c,s:real;
begin
pt:=point3d;
c:=cos(Angle);s:=sin(Angle);
{x doesn't change}
point3d.y:=pt.y*c-pt.z*s;
point3d.z:=pt.y*s+pt.z*c;
end;
procedure Trans_Point3d.Rotate_y(Angle:real);
Var
pt:p3df; c,s:real;
begin
pt:=point3d;
c:=cos(Angle);s:=sin(Angle);
point3d.z:=pt.z*c-pt.x*s;
point3d.x:=pt.z*s+pt.x*c;
end;
procedure Trans_Point3d.Rotate_z(Angle:real);
Var
pt:p3df; c,s:real;
begin
pt:=point3d;
c:=cos(Angle);s:=sin(Angle);
point3d.x:=pt.x*c-pt.y*s;
point3d.y:=pt.x*s+pt.y*c;
end;
(* Incorrect...
procedure Trans_Point3d.Rotate3d(p1,p2:p3df;angle:real);{To Do}
var pt,pt2,pt3,rp,rp2,rp3,rp_res:p3df;
d1,d2,s1,c1,s2,c2,s3,c3:real;
begin{angle in radians}
{translate p1-0, p2,point3d}
s3:=sin(angle);c3:=cos(angle);{angle=-pi/2 to pi/2 radians or -2*pi..2*pi}
{normalise angle..how?if >2*pi then divide angle by 2*pi & divide angle by result}
pt.x:=p2.x-p1.x; {this could be done by declaring pt as transformable point}
pt.y:=p2.x-p1.y; {would that cause recurse declaration error}
pt.z:=p2.x-p1.z; {then use parameter passable simple procs}
rp.x:=point3d.x-p1.x; {if some proc recurses only then variables produced in recursion}
rp.y:=point3d.y-p1.y; {hence until recursion in proc using t.point is o.k}
rp.z:=point3d.z-p1.z;{point to rotate}
{later auto send inverse transforms to inverse transformations stack}
{i.e each transform proc has unique id code or use its pointer,match param(for validity check) & send}
{check if line already aligned to z axis.. then skip it}
{i.e if pt has y=0(xz plane) or z=0(xy plane)}
pt2:=pt;pt3:=pt;rp2:=rp;rp3:=rp;{if pt.y=0 then this may be handy}
if ({(pt.x<>0)and}(pt.y<>0)) then{if in yz or xy plane }
begin{align to z now}
{align to plane(zx or yz), then rotate to z axis(around y or x)}
d1:=sqrt(sqr(pt.y)+sqr(pt.z));
{any value should be less than half or one third of sqrt of max val to avoid overflow from this formula}
{length projected on yz plane-pythogras formula-rectangle by 4 same right triangles}
s1:=pt.y/d1;{sine};c1:=pt.z/d1;{cosine} {line angle from yz plane on zx plane}
{rotate around x- to get to zx plane}
pt2.x:=pt.x;{already done}
pt2.y:={pt.y*c1-pt.z*s1}0.0;{0.0- to speed up a little}
pt2.z:={pt.y*s1+pt.z*c1}d1;
rp2.x:=rp.x
rp2.y:=rp.y*c1-rp.z*s1;
rp2.z:=rp.y*s1+rp.z*c1;
{rotate around y to align to z axis- now in zx plane}
d2:=sqrt(sqr(d1)+sqr(pt2.x));{we know pt2.y=0(approx)}
s2:=pt2.x/d2;c2:=pt2.z/d2;{could've only used pt.x,d1 instead of pt2.x,pt2.z}
{c2=d1/d2,s2=pt.x/d2}
pt3.y:=pt2.y; {pt3 not needed-maybe}
pt3.x:={pt2.x*c2-pt2.z*s2}0.0;
pt3.z:={pt2.z*c2+pt2.x*s2}d2; {line aligned to z}
rp3.y:=rp2.y;
rp3.x:=rp2.x*c2-rp2.z*s2;
rp3.z:=rp2.z*c2+rp2.x*s2;
{now line is aligned to z, hence rotate point...}
rp_res.x:=rp3.x*c3-rp3.y*s3;
rp_res.y:=rp3.x*s3+rp3.y*c3;
rp_res.z:=rp3.z
rp3:=rp_res;
{} {could do arctan first, then sin & cos.. but this is better(no division problem) }
{then transform back- except rotate around z part}
rp2.y:=rp3.y;
rp2.x:=rp3.x*c2-rp3.z*(-s2);{uses cos(-a)=cos(a)}
rp2.z:=rp3.z*c2+rp3.x*(-s2);{sin(-a)=-sin(a); a=angle from 0 angle ref}
rp.y:=rp2.y*c1-rp.z*(-s1);
rp.z:=rp2.y*(-s1)+rp2.z*c1;
rp.x:=rp2.x;
{}
end else
if (pt.x<>0) then{if in xy or zx plane} {verify this once}
Begin {align to y axis}
d1:=sqrt(sqr(pt.x)+sqr(pt.y));
s1:=pt.x/d1;{sine};c1:=pt.y/d1;{cosine} {line angle from yz plane on zx plane}
{rotate around z- to get to yz plane}
pt2.z:=pt.z;{already done}
pt2.x:={pt.x*c1-pt.y*s1}0.0;{0.0- to speed up a little}
pt2.y:={pt.x*s1+pt.y*c1}d1;
rp2.z:=rp.z
rp2.x:=rp.x*c1-rp.y*s1;
rp2.y:=rp.x*s1+rp.y*c1;
{rotate around x to align to y axis- now in yz plane}
d2:=sqrt(sqr(d1)+sqr(pt2.z));{we know pt2.x=0(approx)}
s2:=pt2.z/d2;c2:=pt2.y/d2;{could've only used pt.x,d1 instead of pt2.x,pt2.z}
{c2=d1/d2,s2=pt.x/d2}
pt3.x:=pt2.x; {pt3 not needed-maybe}
pt3.z:={pt2.x*c2-pt2.z*s2}0.0;
pt3.y:={pt2.z*c2+pt2.x*s2}d2; {line aligned to z}
rp3.x:=rp2.x;{chk}
rp3.z:=rp2.x*c2-rp2.z*s2;
rp3.y:=rp2.z*c2+rp2.x*s2;
{now line is aligned to z, hence rotate point...}
rp_res.x:=rp3.x*c3-rp3.y*s3;
rp_res.y:=rp3.x*s3+rp3.y*c3;
rp_res.z:=rp3.z
rp3:=rp_res;
{} {could do arctan first, then sin & cos.. but this is better(no division problem) }
{then transform back- except rotate around z part}
rp2.y:=rp3.y;
rp2.x:=rp3.x*c2-rp3.z*(-s2);{uses cos(-a)=cos(a)}
rp2.z:=rp3.z*c2+rp3.x*(-s2);{sin(-a)=-sin(a); a=angle from 0 angle ref}
rp.y:=rp2.y*c1-rp.z*(-s1);
rp.z:=rp2.y*(-s1)+rp2.z*c1;
rp.x:=rp2.x;
{}
end else
Begin
{now line is aligned to z, hence rotate point...}
{rp_res}rp3.x:=rp3.x*c3-rp3.y*s3;
{rp_res}rp3.y:=rp3.x*s3+rp3.y*c3;
rp:=rp3;
{rp3.z:=rp3.z}
end;{if aligned to z}
{Translate back}
point3d.x:=rp.x+p1.x;
point3d.y:=rp.y+p1.y;
point3d.z:=rp.z+p1.z;
end;
*)
end. |
unit UfrmEditSinglePage;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, GR32_Image,
USlide, USourceInfo, Vcl.ExtCtrls;
type
TfrmEditSinglePage = class(TForm, ISlideEditForm)
Label2: TLabel;
Label3: TLabel;
edtOverviewName: TEdit;
ImgViewPicto: TImgView32;
btnSelectPictoNone: TButton;
btnOK: TButton;
btnCancel: TButton;
PageControlContent: TPageControl;
tsText: TTabSheet;
tsMemo: TTabSheet;
tsPicture: TTabSheet;
ImgViewPicture: TImgView32;
mmoContent: TMemo;
edtContent: TEdit;
Shape1: TShape;
procedure ImgViewPictoClick(Sender: TObject);
procedure btnSelectPictoNoneClick(Sender: TObject);
procedure ImgViewPictureClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
FStartSlide: string;
FPictoName: TSourceInfo;
FPictureName: TSourceInfo;
FContentSubdir: string;
{ Private declarations }
protected
function GetSlideAsString: string;
procedure SetSlideAsString(const Value: string);
function Edit: boolean;
public
property SlideAsString: string read GetSlideAsString write SetSlideAsString;
{ Public declarations }
end;
implementation
{$R *.dfm}
uses
GnuGetText, UUtils, USettings, UUtilsStrings, UUtilsForms, USlideTemplate;
{ TfrmEditSinglePage }
procedure TfrmEditSinglePage.btnSelectPictoNoneClick(Sender: TObject);
begin
FPictoName.FileName := '';
ImgViewPicto.Bitmap.Clear;
end;
function TfrmEditSinglePage.Edit: boolean;
begin
Result := ShowModal = mrOk;
end;
procedure TfrmEditSinglePage.FormCreate(Sender: TObject);
begin
TranslateComponent(self);
FPictoName := TSourceInfo.Create;
FPictureName := TSourceInfo.Create;
end;
procedure TfrmEditSinglePage.FormDestroy(Sender: TObject);
begin
FPictureName.Free;
FPictoName.Free;
end;
function TfrmEditSinglePage.GetSlideAsString: string;
var
slide: TSlide;
slideItemContent, slideItemFooter: TSlideItem;
begin
slide := TSlide.Create(FStartSlide);
try
slide.SlideName := slide.SlideTemplateName + ' : ' + edtOverviewName.Text;
slide.OverviewName := edtOverviewName.Text;
slide.PictoName := FPictoName.DeepCopy;
slideItemFooter := slide['footer'];
if Assigned(slideItemFooter) then begin
slideItemFooter.ContentSources.Clear;
slideItemFooter.ContentSources.Add(TSourceInfo.CreateAsString(edtOverviewName.Text));
end;
slideItemContent := slide['content'];
if Assigned(slideItemContent) then begin
slideItemContent.ContentSources.Clear;
case slideItemContent.ContentType of
ctText: slideItemContent.ContentSources.Add(TSourceInfo.CreateAsString(edtContent.Text));
ctTextMemo,
ctSubtitle: slideItemContent.ContentSources.Add(TSourceInfo.CreateAsString(mmoContent.Lines.Text));
ctPicture,
ctPictureFit: slideItemContent.ContentSources.Add(FPictureName.DeepCopy);
end;
end;
Result := slide.AsJSon;
finally
slide.Free;
end;
end;
procedure TfrmEditSinglePage.ImgViewPictoClick(Sender: TObject);
begin
FPictoName := SelectPicto(FPictoName);
ViewPNG(FPictoName.FileName, ImgViewPicto.Bitmap);
end;
procedure TfrmEditSinglePage.ImgViewPictureClick(Sender: TObject);
begin
FPictureName := SelectPicture(FPictureName, FContentSubdir);
ViewPicture(FPictureName.FileName, ImgViewPicture.Bitmap);
end;
procedure TfrmEditSinglePage.SetSlideAsString(const Value: string);
var
slide: TSlide;
slideItemContent, slideItemFooter: TSlideItem;
template: TSlideTemplate;
source: TSourceInfo;
begin
FStartSlide := Value;
slide := TSlide.Create(FStartSlide);
try
slideItemFooter := slide['footer'];
if Assigned(slideItemFooter) then begin
if slideItemFooter.ContentSources.Count > 0 then begin
source := slideItemFooter.ContentSources[0];
edtOverviewName.Text := source.Text;
end;
end;
FContentSubdir := '';
template := GetSlideTemplates.FindByName(slide.SlideTemplateName);
if Assigned(template) then begin
FContentSubdir := template.SelectContentSubDir;
end;
FreeAndNil(FPictoName);
FPictoName := slide.PictoName.DeepCopy;
ViewPNG(FPictoName.FileName, ImgViewPicto.Bitmap);
slideItemContent := slide['content'];
if Assigned(slideItemContent) then begin
if slideItemContent.ContentSources.Count > 0 then begin
source := slideItemContent.ContentSources[0];
case source.SourceType of
sitUnknown: ;
sitString: begin
if slideItemContent.ContentType = ctText then begin
edtContent.text := source.Text;
PageControlContent.ActivePage := tsText;
end else if slideItemContent.ContentType in [ctTextMemo, ctSubtitle] then begin
mmoContent.Lines.Text := source.Text;
PageControlContent.ActivePage := tsMemo;
end;
end;
sitPPT: ;
sitFileName: begin
FreeAndNil(FPictureName);
FPictureName := source.DeepCopy;
ViewPicture(FPictureName.FileName, ImgViewPicture.Bitmap);
PageControlContent.ActivePage := tsPicture;
end;
end;
end;
PageControlContent.Visible := slideItemContent.ContentType in [ctText, ctTextMemo, ctPicture, ctPictureFit, ctSubtitle];
end;
finally
slide.Free;
end;
end;
end.
|
unit uFrmParamSet;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, cxGraphics, cxControls, cxLookAndFeels, cxLookAndFeelPainters,
cxPCdxBarPopupMenu, cxPC, Vcl.ExtCtrls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxSpinEdit
, ManSoy.MsgBox
, uGlobal
, uJsonClass, cxDropDownEdit
;
type
TFrmParamSet = class(TForm)
Panel1: TPanel;
Bevel1: TBevel;
btnSave: TButton;
btnCancel: TButton;
GroupBox2: TGroupBox;
Label4: TLabel;
Label5: TLabel;
edtMaxTaskTimes: TcxSpinEdit;
edtCurMaxTaskCount: TcxSpinEdit;
GroupBox1: TGroupBox;
Label2: TLabel;
chk自动分批: TCheckBox;
chk缺料则暂停: TCheckBox;
edt分仓附加: TcxSpinEdit;
GroupBox3: TGroupBox;
Label1: TLabel;
Label3: TLabel;
edtTaskLink: TcxTextEdit;
edtStateLink: TcxTextEdit;
Label6: TLabel;
edtLogLink: TcxTextEdit;
Label7: TLabel;
edt仓库浮动: TcxSpinEdit;
Label8: TLabel;
edtImgLink: TcxTextEdit;
cbConsoleID: TcxComboBox;
Label9: TLabel;
Label10: TLabel;
edtSetExceptionLink: TcxTextEdit;
Label11: TLabel;
edtGetOrder: TcxTextEdit;
Label12: TLabel;
edtCarryLink: TcxTextEdit;
procedure btnSaveClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
FShowAll: Boolean;
{ Private declarations }
procedure Data2UI;
procedure UI2Data;
public
{ Public declarations }
function SaveParam: Boolean;
end;
var
FrmParamSet: TFrmParamSet;
function OpenParamSet(AOwner: TComponent): Boolean;
implementation
{$R *.dfm}
function OpenParamSet(AOwner: TComponent): Boolean;
var
F: TFrmParamSet;
begin
F := TFrmParamSet.Create(AOwner);
try
Result := F.ShowModal = mrOk;
finally
FreeAndNil(F);
end;
end;
procedure TFrmParamSet.FormCreate(Sender: TObject);
begin
Data2UI;
end;
function TFrmParamSet.SaveParam: Boolean;
var
sCfg: string;
vLst: TStrings;
begin
sCfg := ExtractFilePath(ParamStr(0)) + 'Config\SvrSysCfg.cfg';
vLst := TStringList.Create;
try
vLst.Text := TSerizalizes.AsJson<TConsoleSet>(GConsoleSet);
vLst.SaveToFile(sCfg);
finally
FreeAndNil(vLst);
end;
end;
procedure TFrmParamSet.btnSaveClick(Sender: TObject);
begin
UI2Data;
//----------------------------------------------------
SaveParam;
Self.ModalResult := mrOk;
end;
procedure TFrmParamSet.Data2UI;
begin
//--任务分配
cbConsoleID.Text := GConsoleSet.ConsoleID;
chk缺料则暂停.Checked := GConsoleSet.LackMaterialPause;
chk自动分批.Checked := GConsoleSet.AutoBatch;
edt分仓附加.Value := GConsoleSet.StockAdditional;
edt仓库浮动.Value := GConsoleSet.StockFloating;
//--连接设置
edtTaskLink.Text := GConsoleSet.TaskInterface;
edtStateLink.Text := GConsoleSet.StateInterface;
edtLogLink.Text := GConsoleSet.LogInterface;
edtImgLink.Text := GConsoleSet.ImgInterface;
edtCarryLink.Text := GConsoleSet.CarryInterface;
edtSetExceptionLink.Text := GConsoleSet.SetExceptionInterface;
edtGetOrder.Text := GConsoleSet.GetOrderInterfac;
//--其他设置
edtMaxTaskTimes.Value := GConsoleSet.TaskTimes;
edtCurMaxTaskCount.Value := GConsoleSet.MaxTaskNum;
end;
procedure TFrmParamSet.UI2Data;
begin
//--任务分配
GConsoleSet.ConsoleID := cbConsoleID.Text;
GConsoleSet.LackMaterialPause := chk缺料则暂停.Checked;
GConsoleSet.AutoBatch := chk自动分批.Checked;
GConsoleSet.StockAdditional := edt分仓附加.Value;
GConsoleSet.StockFloating := edt仓库浮动.Value;
//--连接设置
GConsoleSet.TaskInterface := edtTaskLink.Text;
GConsoleSet.StateInterface := edtStateLink.Text;
GConsoleSet.LogInterface := edtLogLink.Text;
GConsoleSet.ImgInterface := edtImgLink.Text;
GConsoleSet.CarryInterface := edtCarryLink.Text;
GConsoleSet.SetExceptionInterface := edtSetExceptionLink.Text;
GConsoleSet.GetOrderInterfac := edtGetOrder.Text;
//--其他设置
GConsoleSet.TaskTimes := edtMaxTaskTimes.Value;
GConsoleSet.MaxTaskNum := edtCurMaxTaskCount.Value;
end;
end.
|
unit frm1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, StdCtrls
, fphttpclient;
type
{ TForm1 }
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Edit1: TEdit;
Memo1: TMemo;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
function FPHTTPClientDownload(URL: string; SaveToFile: boolean=false;
Filename: string=''): string;
public
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
function TForm1.FPHTTPClientDownload(URL: string; SaveToFile: boolean = false; Filename: string = ''): string;
begin
// Result will be:
// - empty ('') when it has failed
// - filename when the file has been downloaded successfully
// - content when the content SaveToFile is set to False
Result := '';
With TFPHttpClient.Create(Nil) do
try
try
if SaveToFile then begin
Get(URL, Filename);
Result := Filename;
end else begin
Result := Get(URL);
end;
except
on E: Exception do
ShowMessage('Error: ' + E.Message);
end;
finally
Free;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
memo1.Text := FPHTTPClientDownload(Edit1.Text);
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
memo1.Text := FPHTTPClientDownload(Edit1.Text, True, 'test.txt');
end;
end.
|
unit AccessAdapterUnit;
interface
uses SysUtils, Data.DB, Data.Win.ADODB,
System.Generics.Collections, AdaptersUnit;
type
AccessAdapter = class(TInterfacedObject, Adapters)
private
caption:string;
ADOConnection:TADOConnection;
function GetAnswerTableName:string;
function GetAnswerTable(answer:string):TList<string>;
function GetCorrectTableName:string;
function GetCorrectTable(correct:string):TDictionary<integer, integer>;
function GetQuestTableName:string;
function GetQuestTable(quest:string):TList<string>;
function getMenu: TList<string>;
procedure setTest(caption:string);
function getQuest:TList<string>;
function getAnswer:TList<string>;
function getCorrect:TDictionary<integer, integer>;
published
constructor create;
end;
implementation
{ AccessAdapter }
constructor AccessAdapter.create;
begin
ADOConnection:=TADOConnection.create(nil);
with (ADOConnection)do
begin
Provider:='Microsoft.ACE.OLEDB.12.0';
Mode:=cmShareDenyNone;
LoginPrompt:=False;
ConnectionString:= 'Provider=Microsoft.ACE.OLEDB.12.0;'+
'Data Source=Phisics.accdb;'+'Persist Security Info=False';
Connected:=true;
end;
end;
function AccessAdapter.getAnswer: TList<string>;
var
ADOQuery:TADOQuery;
answer:string;
begin
answer:=GetAnswerTableName;
result:=GetAnswerTable(answer);
end;
function AccessAdapter.GetAnswerTable(answer:string):TList<string>;
var
ADOQuery:TADOQuery;
begin
result:=TList<string>.create;
ADOQuery:=TADOQuery.Create(nil);
with (ADOQuery) do
begin
Connection:=ADOConnection;
Close;
SQL.Clear;
SQL.Add('SELECT caption FROM ' + answer + ';');
Open;
Active:=True;
end;
while not ADOQuery.Eof do
begin
result.Add(ADOQuery.FieldByName('caption').AsString);
ADOQuery.Next;
end;
ADOQuery.Free;
end;
function AccessAdapter.GetAnswerTableName: string;
var
ADOQuery:TADOQuery;
begin
ADOQuery:=TADOQuery.Create(nil);
with (ADOQuery) do
begin
Connection:=ADOConnection;
Close;
SQL.Clear;
SQL.Add('SELECT answer FROM Main WHERE caption="' + Self.caption + '";');
Open;
Active:=True;
end;
ADOQuery.First;
result:= ADOQuery.FieldByName('answer').AsString;
ADOQuery.Free;
end;
function AccessAdapter.getCorrect: TDictionary<integer, integer>;
var
correct:string;
begin
correct:=GetCorrectTableName;
result:=GetCorrectTable(correct);
end;
function AccessAdapter.GetCorrectTable(correct: string): TDictionary<integer, integer>;
var
ADOQuery:TADOQuery;
begin
result:=TDictionary<integer, integer>.create;
ADOQuery:=TADOQuery.Create(nil);
with (ADOQuery) do
begin
Connection:=ADOConnection;
Close;
SQL.Clear;
SQL.Add('SELECT quest_id, answer_id FROM ' + correct + ';');
Open;
Active:=True;
end;
ADOQuery.First;
while not ADOQuery.Eof do
begin
result.Add(StrToInt(ADOQuery.FieldByName('quest_id').AsString),
StrToInt(ADOQuery.FieldByName('answer_id').AsString));
ADOQuery.Next;
end;
ADOQuery.Free;
end;
function AccessAdapter.GetCorrectTableName: string;
var
ADOQuery:TADOQuery;
begin
ADOQuery:=TADOQuery.Create(nil);
with (ADOQuery) do
begin
Connection:=ADOConnection;
Close;
SQL.Clear;
SQL.Add('SELECT correct FROM Main WHERE caption="' + Self.caption + '";');
Open;
Active:=True;
end;
ADOQuery.First;
result:= ADOQuery.FieldByName('correct').AsString;
end;
function AccessAdapter.getQuest: TList<string>;
var
ADOQuery:TADOQuery;
quest:string;
begin
quest:=GetQuestTableName;
result:=GetQuestTable(quest);
end;
function AccessAdapter.GetQuestTable(quest: string): TList<string>;
var
ADOQuery:TADOQuery;
begin
result:=TList<string>.create;
ADOQuery:=TADOQuery.Create(nil);
with (ADOQuery) do
begin
Connection:=ADOConnection;
Close;
SQL.Clear;
SQL.Add('SELECT caption FROM ' + quest + ';');
Open;
Active:=True;
end;
while not ADOQuery.Eof do
begin
result.Add(ADOQuery.FieldByName('caption').AsString);
ADOQuery.Next;
end;
ADOQuery.Free;
end;
function AccessAdapter.GetQuestTableName: string;
var
ADOQuery:TADOQuery;
begin
ADOQuery:=TADOQuery.Create(nil);
with (ADOQuery) do
begin
Connection:=ADOConnection;
Close;
SQL.Clear;
SQL.Add('SELECT quest FROM Main WHERE caption="' + Self.caption + '";');
Open;
Active:=True;
end;
ADOQuery.First;
result:=ADOQuery.FieldByName('quest').AsString;
end;
procedure AccessAdapter.setTest(caption: string);
begin
self.caption:=caption;
end;
function AccessAdapter.getMenu: TList<string>;
var
ADOQuery:TADOQuery;
begin
result:=TList<string>.create;
ADOQuery:=TADOQuery.Create(nil);
with (ADOQuery) do
begin
Connection:=ADOConnection;
Close;
SQL.Clear;
SQL.Add('SELECT caption FROM main;');
Open;
Active:=True;
end;
ADOQuery.First;
while not ADOQuery.Eof do
begin
result.Add(ADOQuery.FieldByName('caption').AsString);
ADOQuery.Next;
end;
ADOQuery.Free;
end;
end.
|
unit itclib;
{ =================================================================
Instrutech ITC-16/18 Interface Library for original driver
(c) John Dempster, University of Strathclyde, All Rights Reserved
=================================================================
24.01.03 Tested and working with ITC-18
03.02.03 Tested and working with ITC-16
11/2/04 ... ITC_MemoryToDACAndDigitalOut can now wait for ext. trigger
itclib.dll now specifically loaded from program folder
04/04/07 ... Collection of last point in single sweep now assured
16/01/12 ... D/A fifo now filled by ITC_GetADCSamples allowing
record buffer to be increased to MaxADCSamples div 2 (4194304)
27/8/12 ... ITC_WriteDACsAndDigitalPort and ITC_ReadADC now disabled when ADCActive = TRUE
06.11.13 .. A/D input channels can now be mapped to different physical inputs
}
interface
uses WinTypes,Dialogs, SysUtils, WinProcs,mmsystem,math;
procedure ITC_InitialiseBoard ;
procedure ITC_LoadLibrary ;
function ITC_GetDLLAddress(
Handle : Integer ;
const ProcName : string ) : Pointer ;
procedure ITC_ConfigureHardware(
ITCInterfaceType : Integer ;
EmptyFlagIn : Integer ) ;
function ITC_ADCToMemory(
var HostADCBuf : Array of SmallInt ;
nChannels : Integer ;
nSamples : Integer ;
var dt : Double ;
ADCVoltageRange : Single ;
TriggerMode : Integer ;
CircularBuffer : Boolean ;
ADCChannelInputMap : Array of Integer
) : Boolean ;
function ITC_StopADC : Boolean ;
procedure ITC_GetADCSamples (
OutBuf : Pointer ;
var OutBufPointer : Integer
) ;
procedure ITC_CheckSamplingInterval(
var SamplingInterval : Double ;
var Ticks : Cardinal
) ;
function ITC_MemoryToDACAndDigitalOut(
var DACValues : Array of SmallInt ; // D/A output values
NumDACChannels : Integer ; // No. D/A channels
nPoints : Integer ; // No. points per channel
var DigValues : Array of SmallInt ; // Digital port values
DigitalInUse : Boolean ; // Output to digital outs
WaitForExtTrigger : Boolean // Ext. trigger mode
) : Boolean ;
function ITC_GetDACUpdateInterval : double ;
function ITC_StopDAC : Boolean ;
procedure ITC_WriteDACsAndDigitalPort(
var DACVolts : array of Single ;
nChannels : Integer ;
DigValue : Integer
) ;
function ITC_GetLabInterfaceInfo(
var Model : string ; { Laboratory interface model name/number }
var ADCMinSamplingInterval : Double ; { Smallest sampling interval }
var ADCMaxSamplingInterval : Double ; { Largest sampling interval }
var ADCMinValue : Integer ; { Negative limit of binary ADC values }
var ADCMaxValue : Integer ; { Positive limit of binary ADC values }
var ADCVoltageRanges : Array of single ; { A/D voltage range option list }
var NumADCVoltageRanges : Integer ; { No. of options in above list }
var ADCBufferLimit : Integer ; { Max. no. samples in A/D buffer }
var DACMaxVolts : Single ; { Positive limit of bipolar D/A voltage range }
var DACMinUpdateInterval : Double {Min. D/A update interval }
) : Boolean ;
function ITC_GetMaxDACVolts : single ;
function ITC_ReadADC( Channel : Integer ;
ADCVoltageRange : Single ) : SmallInt ;
procedure ITC_GetChannelOffsets(
var Offsets : Array of Integer ;
NumChannels : Integer
) ;
procedure ITC_CloseLaboratoryInterface ;
function TrimChar( Input : Array of ANSIChar ) : string ;
function MinInt( const Buf : array of LongInt ) : LongInt ;
function MaxInt( const Buf : array of LongInt ) : LongInt ;
Procedure ITC_CheckError( Err : Cardinal ; ErrSource : String ) ;
implementation
uses SESLabIO, forms ;
const
FIFOMaxPoints = 16128 ;
ITC16_ID = 0 ;
ITC18_ID = 1 ;
MaxADCChannels = 7 ;
ITC_MINIMUM_TICKS = 5 ;
ITC_MAXIMUM_TICKS = 65535 ;
DIGITAL_INPUT = $02 ; //Digital Input
DIGITAL_OUTPUT = $03 ; //Digital Output
AUX_INPUT = $04 ; //Aux Input
AUX_OUTPUT = $05 ; //Aux Output
ITC_NUMBEROFADCINPUTS = 8 ;
//STUB -> Move this object to the Registry
ITC18_SOFTWARE_SEQUENCE_SIZE = 4096 ;
//STUB ->Verify
ITC16_SOFTWARE_SEQUENCE_SIZE = 1024 ;
ITC18_NUMBEROFCHANNELS = 16 ; //4 + 8 + 2 + 1 + 1
ITC18_NUMBEROFOUTPUTS = 7 ; //4 + 2 + 1
ITC18_NUMBEROFINPUTS = 9 ; //8 + 1
ITC18_NUMBEROFADCINPUTS = 8 ;
ITC18_NUMBEROFDACOUTPUTS = 4 ;
ITC18_NUMBEROFDIGINPUTS = 1 ;
ITC18_NUMBEROFDIGOUTPUTS = 2 ;
ITC18_NUMBEROFAUXINPUTS = 0 ;
ITC18_NUMBEROFAUXOUTPUTS = 1 ;
ITC18_DA_CH_MASK = $3 ; //4 DA Channels
ITC18_DO0_CH = $4 ; //DO0
ITC18_DO1_CH = $5 ; //DO1
ITC18_AUX_CH = $6 ; //AUX
ITC16_NUMBEROFCHANNELS = 14 ; //4 + 8 + 1 + 1
ITC16_NUMBEROFOUTPUTS = 5 ; //4 + 1
ITC16_NUMBEROFINPUTS = 9 ; //8 + 1
ITC16_DO_CH = 4 ;
ITC16_NUMBEROFADCINPUTS = 8 ;
ITC16_NUMBEROFDACOUTPUTS = 4 ;
ITC16_NUMBEROFDIGINPUTS = 1 ;
ITC16_NUMBEROFDIGOUTPUTS = 1 ;
ITC16_NUMBEROFAUXINPUTS = 0 ;
ITC16_NUMBEROFAUXOUTPUTS = 0 ;
//***************************************************************************
//Overflow/Underrun Codes
ITC_READ_OVERFLOW_H = $01 ;
ITC_WRITE_UNDERRUN_H = $02 ;
ITC_READ_OVERFLOW_S = $10 ;
ITC_WRITE_UNDERRUN_S = $20 ;
ITC_STOP_CH_ON_OVERFLOW = $0001 ; //Stop One Channel
ITC_STOP_CH_ON_UNDERRUN = $0002 ;
ITC_STOP_CH_ON_COUNT = $1000 ;
ITC_STOP_PR_ON_COUNT = $2000 ;
ITC_STOP_DR_ON_OVERFLOW = $0100 ; //Stop One Direction
ITC_STOP_DR_ON_UNDERRUN = $0200 ;
ITC_STOP_ALL_ON_OVERFLOW = $1000 ; //Stop System (Hardware STOP)
ITC_STOP_ALL_ON_UNDERRUN = $2000 ;
//***************************************************************************
//Software Keys MSB
PaulKey = $5053 ;
HekaKey = $4845 ;
UicKey = $5543 ;
InstruKey = $4954 ;
AlexKey = $4142 ;
EcellKey = $4142 ;
SampleKey = $5470 ;
TestKey = $4444 ;
TestSuiteKey = $5453 ;
RESET_FIFO_COMMAND = $10000 ;
PRELOAD_FIFO_COMMAND = $20000 ;
LAST_FIFO_COMMAND = $40000 ;
FLUSH_FIFO_COMMAND = $80000 ;
// ITC-16 FIFO sequence codes
// --------------------------
ITC16_INPUT_AD0 = $7 ;
ITC16_INPUT_AD1 = $6 ;
ITC16_INPUT_AD2 = $5 ;
ITC16_INPUT_AD3 = $4 ;
ITC16_INPUT_AD4 = $3 ;
ITC16_INPUT_AD5 = $2 ;
ITC16_INPUT_AD6 = $1 ;
ITC16_INPUT_AD7 = $0 ;
ITC16_INPUT_DIGITAL =$20 ;
ITC16_INPUT_UPDATE = $0 ;
ITC16_TICKINTERVAL = 1E-6 ;
ITC16_OUTPUT_DA0 = $18 ;
ITC16_OUTPUT_DA1 = $10 ;
ITC16_OUTPUT_DA2 = $08 ;
ITC16_OUTPUT_DA3 = $0 ;
ITC16_OUTPUT_DIGITAL = $40 ;
ITC16_OUTPUT_UPDATE = $0 ;
// ITC-18 FIFO sequence codes
// --------------------------
ITC18_INPUT_AD0 = $0000 ;
ITC18_INPUT_AD1 = $0080 ;
ITC18_INPUT_AD2 = $0100 ;
ITC18_INPUT_AD3 = $0180 ;
ITC18_INPUT_AD4 = $0200 ;
ITC18_INPUT_AD5 = $0280 ;
ITC18_INPUT_AD6 = $0300 ;
ITC18_INPUT_AD7 = $0380 ;
ITC18_INPUT_UPDATE = $4000 ;
ITC18_OUTPUT_DA0 = $0000 ;
ITC18_OUTPUT_DA1 = $0800 ;
ITC18_OUTPUT_DA2 = $1000 ;
ITC18_OUTPUT_DA3 = $1800 ;
ITC18_OUTPUT_DIGITAL0 = $2000 ;
ITC18_OUTPUT_DIGITAL1 = $2800 ;
ITC18_OUTPUT_UPDATE = $8000 ;
ITC18_TICKINTERVAL = 1.25E-6 ;
// Error flags
ACQ_SUCCESS = 0 ;
Error_DeviceIsNotSupported = $0001000 ; //1000 0000 0000 0001 0000 0000 0000
Error_UserVersionID = $80001000 ;
Error_KernelVersionID = $81001000 ;
Error_DSPVersionID = $82001000;
Error_TimerIsRunning = $8CD01000 ;
Error_TimerIsDead = $8CD11000 ;
Error_TimerIsWeak = $8CD21000 ;
Error_MemoryAllocation = $80401000 ;
Error_MemoryFree = $80411000 ;
Error_MemoryError = $80421000 ;
Error_MemoryExist = $80431000 ;
Warning_AcqIsRunning = $80601000 ;
Error_TIMEOUT = $80301000 ;
Error_OpenRegistry = $8D101000 ;
Error_WriteRegistry = $8DC01000 ;
Error_ReadRegistry = $8DB01000 ;
Error_ParamRegistry = $8D701000 ;
Error_CloseRegistry = $8D201000 ;
Error_Open = $80101000 ;
Error_Close = $80201000 ;
Error_DeviceIsBusy = $82601000 ;
Error_AreadyOpen = $80111000 ;
Error_NotOpen = $80121000 ;
Error_NotInitialized = $80D01000 ;
Error_Parameter = $80701000 ;
Error_ParameterSize = $80A01000 ;
Error_Config = $89001000 ;
Error_InputMode = $80611000 ;
Error_OutputMode = $80621000 ;
Error_Direction = $80631000 ;
Error_ChannelNumber = $80641000 ;
Error_SamplingRate = $80651000 ;
Error_StartOffset = $80661000 ;
Error_Software = $8FF01000 ;
type
// *** DLL libray function templates ***
// Interface procedures for the Instrutech ITC16.
//
// Copyright (c) 1991, 1996 Instrutech Corporation, Great Neck, NY, USA
//
// Created by SKALAR Instruments, Seattle, WA, USA
// Application interface functions
//
// Functions that return a status return 0 if the function succeeds,
// and a non-zero value if the function fails. The status values
// can be interpreted by ITC16_GetStatusText.
// Set the type of interface in use (ITC_16, ITC_18)
TITC_SetInterfaceType = Function(
InterfaceType : Integer
) : Cardinal ; cdecl ;
// Function ITC16_GetStatusText
//
// Translate a status value to a text string. The translated string
// is written into "text" with maximum length "length" characters.
TITC_GetStatusText = Function (
Device : Pointer ;
Status : Cardinal ;
Text : PANSIChar ;
Length : Cardinal
) : Cardinal ; cdecl ;
// Return the size of the structure that defines the device.
TITC_GetStructureSize = Function : Cardinal ; cdecl ;
// Initialize the device hardware.
TITC_Initialize = Function(
Device : Pointer
) : Cardinal ; cdecl ;
// Open the device driver.
TITC_Open = Function(
Device : Pointer
) : Cardinal ; cdecl ;
// Close the device and free resources associated with it.
TITC_Close = Function(
Device : Pointer
) : Cardinal ; cdecl ;
// Return the size of the FIFO memory, measured in samples.
TITC_GetFIFOSize = Function(
Device : Pointer
) : Cardinal ; cdecl ;
// Set the sampling rate.
TITC_SetSamplingInterval = Function(
Device : Pointer ;
Interval : Cardinal
) : Cardinal ; cdecl ;
// An array of length instructions is written out to the sequence RAM.
// Acquisition must be stopped to write to the sequence RAM.
// length - The number of entries for the sequence memory.
// Set the sampling rate.
TITC_SetSequence = Function(
Device : Pointer ;
SequenceLength : Cardinal ;
var Sequence : Array of Cardinal ) : Cardinal ; cdecl ;
// This routine must be called before acquisition can be performed after power
// up, and after each call to Stop. The FIFOs are reset and enabled.
TITC_InitializeAcquisition = Function(
Device : Pointer
) : Cardinal ; cdecl ;
// Initiate acquisition. Data acquisition will stop on
// A/D FIFO overflow. D/A output will stop on D/A FIFO underflow.
// D/A output will be enabled only if 'output_enable' is non-zero.
// External triggering may be specified with a non-zero value in
// 'external_trigger'. Otherwise acquisition will start immediately.
TITC_Start = Function(
Device : Pointer ;
ExternalTrigger : Cardinal ;
OutPutEnable : Cardinal
) : Cardinal ; cdecl ;
// Return the number of FIFO entries available for writing.
TITC_GetFIFOWriteAvailable = Function(
Device : Pointer ;
var NumAvailable : Cardinal
) : Cardinal ; cdecl ;
// The buffer of(length) entries is written to the ITC16.
// Any value from 1 to the value returned by ITC16_GetFIFOWriteAvailable may
// be used as the length argument.
TITC_WriteFIFO = Function(
Device : Pointer ;
NumEntries : Cardinal ;
OutBuf : Pointer
) : Cardinal ; cdecl ;
// Return the number of acquired samples not yet read out of the FIFO.
// The "overflow" value is set to zero if FIFO overflow has not occurred,
// and a non-zero value if input FIFO overflow has occurred.
TITC_GetFIFOReadAvailable = Function(
Device : Pointer ;
var NumAvailable : Cardinal
) : Cardinal ; cdecl ;
// The buffer is filled with length entries from the ITC16.
// Any value from 1 to the value returned by ITC16_GetFIFOReadAvailable may
// be used as the length argument.
TITC_ReadFIFO = Function(
Device : Pointer ;
NumEntries : Cardinal ;
InBuf : Pointer
) : Cardinal ; cdecl ;
// Return the state of the clipping bit and clear the latch.
TITC_IsClipping = Function(
Device : Pointer ;
var IsClipping : Cardinal
) : Cardinal ; cdecl ;
// The 'overflow' parameter is set to zero if input FIFO overflow has
// not occurred, and non-zero if input FIFO overflow has occurred.
TITC_GetFIFOOverflow = Function(
Device : Pointer ;
var OverFlow : Cardinal
) : Cardinal ; cdecl ;
// End acquisition immediately.
TITC_Stop = Function(
Device : Pointer
) : Cardinal ; cdecl ;
// Return a status value that corresponds to "FIFO Overflow".
TITC_GetStatusOverflow = Function(
Device : Pointer
) : Cardinal ; cdecl ;
// Release the driver.
// Only of use under Microsoft Windows.
TITC_Release = Function(
Device : Pointer
) : Cardinal ; cdecl ;
// Reserve the driver.
// Only of use under Microsoft Windows.
TITC_Reserve = Function(
Device : Pointer ;
var Busy : Cardinal
) : Cardinal ; cdecl ;
TITC_SetRange = Function(
Device : Pointer ;
var ADRange : Array of Cardinal
) : Cardinal ; cdecl ;
var
ITC_SetInterfaceType : TITC_SetInterfaceType ;
ITC_GetStatusText : TITC_GetStatusText ;
ITC_GetStructureSize : TITC_GetStructureSize ;
ITC_Initialize : TITC_Initialize ;
ITC_Open : TITC_Open ;
ITC_Close : TITC_Close ;
ITC_GetFIFOSize :TITC_GetFIFOSize ;
ITC_SetSamplingInterval : TITC_SetSamplingInterval ;
ITC_SetSequence : TITC_SetSequence ;
ITC_InitializeAcquisition : TITC_InitializeAcquisition ;
ITC_Start : TITC_Start ;
ITC_GetFIFOWriteAvailable : TITC_GetFIFOWriteAvailable ;
ITC_WriteFIFO : TITC_WriteFIFO ;
ITC_GetFIFOReadAvailable : TITC_GetFIFOReadAvailable ;
ITC_ReadFIFO : TITC_ReadFIFO ;
ITC_IsClipping : TITC_IsClipping ;
ITC_GetFIFOOverflow :TITC_GetFIFOOverflow ;
ITC_Stop :TITC_Stop ;
ITC_GetStatusOverflow : TITC_GetStatusOverflow ;
ITC_Release : TITC_Release ;
ITC_Reserve : TITC_Reserve ;
ITC_SetRange : TITC_SetRange ;
LibraryHnd : THandle ; // ITCLIB.DLL library file handle
Device : Pointer ; // Pointer to device strutcure
InterfaceType : Cardinal ; // ITC interface type (ITC16/ITC18)
LibraryLoaded : boolean ; // Libraries loaded flag
DeviceInitialised : Boolean ; // Indicates devices has been successfully initialised
//FADCMaxChannel : Integer ; // Upper limit of A/D channel numbers
FADCVoltageRanges : Array[0..15] of Single ; // A/D input voltage range options
FNumADCVoltageRanges : Integer ; // No. of available A/D voltage ranges
//FADCVoltageRangeMax : Single ; // Upper limit of A/D input voltage range
FADCMinValue : Integer ; // Max. A/D integer value
FADCMaxValue : Integer ; // Min. A/D integer value
FADCSamplingInterval : Double ; // A/D sampling interval
FADCMinSamplingInterval : Single ; // Min. A/D sampling interval
FADCMaxSamplingInterval : Single ; // Max. A/D sampling interval
FADCBufferLimit : Integer ; // Upper limit of A/D sample buffer
CyclicADCBuffer : Boolean ; // Continuous cyclic A/D buffer mode flag
EmptyFlag : SmallInt ; // Empty A/D buffer indicator value
FNumADCSamples : Integer ; // No. A/D samples/channel/sweep
FNumADCChannels : Integer ; // No. A/D channels/sweep
FNumSamplesRequired : Integer ;
OutPointer : Integer ; // Pointer to last A/D sample transferred
// (used by ITC_GetADCSamples)
OutPointerSkipCount : Integer ; // No. of points to ignore when FIFO read starts
FDACVoltageRangeMax : Single ; // Upper limit of D/A voltage range
FDACMinValue : Integer ; // Max. D/A integer value
FDACMaxValue : Integer ; // Min. D/A integer value
FNumDACPoints : Integer ;
FNumDACChannels : Integer ;
FDACMinUpdateInterval : Single ;
FTickInterval : Double ; // A/D clock tick resolution (s)
FTicksPerSample : Cardinal ; // Current no. ticks per A/D sample
DACFIFO : PSmallIntArray ; // FIFO output storage buffer
DACPointer : Integer ; // FIFO DAC write pointer
ADCFIFO : PSmallIntArray ; // FIFO input storage buffer
// FIFO sequencer codes in use
INPUT_AD0 : Integer ;
INPUT_AD1 : Integer ;
INPUT_AD2 : Integer ;
INPUT_AD3 : Integer ;
INPUT_AD4 : Integer ;
INPUT_AD5 : Integer ;
INPUT_AD6 : Integer ;
INPUT_AD7 : Integer ;
INPUT_UPDATE : Integer ;
OUTPUT_DA0 : Integer ;
OUTPUT_DA1 : Integer ;
OUTPUT_DA2 : Integer ;
OUTPUT_DA3 : Integer ;
OUTPUT_DIGITAL : Integer ;
OUTPUT_UPDATE : Integer ;
Sequence : Array[0..16] of Cardinal ; // FIFO input/output control sequence
ADCActive : Boolean ; // Indicates A/D conversion in progress
DACActive : Boolean ;
function ITC_GetLabInterfaceInfo(
var Model : string ; { Laboratory interface model name/number }
var ADCMinSamplingInterval : Double ; { Smallest sampling interval }
var ADCMaxSamplingInterval : Double ; { Largest sampling interval }
var ADCMinValue : Integer ; { Negative limit of binary ADC values }
var ADCMaxValue : Integer ; { Positive limit of binary ADC values }
var ADCVoltageRanges : Array of single ; { A/D voltage range option list }
var NumADCVoltageRanges : Integer ; { No. of options in above list }
var ADCBufferLimit : Integer ; { Max. no. samples in A/D buffer }
var DACMaxVolts : Single ; { Positive limit of bipolar D/A voltage range }
var DACMinUpdateInterval : Double {Min. D/A update interval }
) : Boolean ;
{ --------------------------------------------
Get information about the interface hardware
-------------------------------------------- }
var
i : Integer ;
begin
if not DeviceInitialised then ITC_InitialiseBoard ;
if DeviceInitialised then begin
{ Get device model and serial number }
if InterfaceType = ITC16_ID then Model := ' ITC-16 '
else if InterfaceType = ITC18_ID then Model := ' ITC-18 '
else Model := 'Unknown' ;
// Define available A/D voltage range options
for i := 0 to FNumADCVoltageRanges-1 do
ADCVoltageRanges[i] := FADCVoltageRanges[i] ;
NumADCVoltageRanges := FNumADCVoltageRanges ;
// A/D sample value range (16 bits)
ADCMinValue := -32678 ;
ADCMaxValue := -ADCMinValue - 1 ;
FADCMinValue := ADCMinValue ;
FADCMaxValue := ADCMaxValue ;
// Upper limit of bipolar D/A voltage range
DACMaxVolts := 10.25 ;
FDACVoltageRangeMax := 10.25 ;
DACMinUpdateInterval := 2.5E-6 ;
FDACMinUpdateInterval := DACMinUpdateInterval ;
// Min./max. A/D sampling intervals
ADCMinSamplingInterval := 2.5E-6 ;
ADCMaxSamplingInterval := 100.0 ;
FADCMinSamplingInterval := ADCMinSamplingInterval ;
FADCMaxSamplingInterval := ADCMaxSamplingInterval ;
//FADCBufferLimit := High(TSmallIntArray)+1 ;
//FADCBufferLimit := 16128 ;
FADCBufferLimit := MaxADCSamples div 2 ; //Old value 16128 ;
ADCBufferLimit := FADCBufferLimit ;
end ;
Result := DeviceInitialised ;
end ;
procedure ITC_LoadLibrary ;
{ -------------------------------------
Load ITCLIB.DLL library into memory
-------------------------------------}
begin
{ Load ITCLIB interface DLL library }
LibraryHnd := LoadLibrary(
PChar(ExtractFilePath(ParamStr(0)) + 'itclib.dll'));
{ Get addresses of procedures in library }
if LibraryHnd > 0 then begin
@ITC_SetInterfaceType :=ITC_GetDLLAddress(LibraryHnd,'ITC_SetInterfaceType') ;
@ITC_GetStatusText :=ITC_GetDLLAddress(LibraryHnd,'ITC_GetStatusText') ;
@ITC_GetStructureSize :=ITC_GetDLLAddress(LibraryHnd,'ITC_GetStructureSize') ;
@ITC_Initialize :=ITC_GetDLLAddress(LibraryHnd,'ITC_Initialize') ;
@ITC_Open :=ITC_GetDLLAddress(LibraryHnd,'ITC_Open') ;
@ITC_Close :=ITC_GetDLLAddress(LibraryHnd,'ITC_Close') ;
@ITC_GetFIFOSize :=ITC_GetDLLAddress(LibraryHnd,'ITC_GetFIFOSize') ;
@ITC_SetSamplingInterval :=ITC_GetDLLAddress(LibraryHnd,'ITC_SetSamplingInterval') ;
@ITC_SetSequence :=ITC_GetDLLAddress(LibraryHnd,'ITC_SetSequence') ;
@ITC_InitializeAcquisition :=ITC_GetDLLAddress(LibraryHnd,'ITC_InitializeAcquisition') ;
@ITC_GetFIFOWriteAvailable :=ITC_GetDLLAddress(LibraryHnd,'ITC_GetFIFOWriteAvailable') ;
@ITC_WriteFIFO :=ITC_GetDLLAddress(LibraryHnd,'ITC_WriteFIFO') ;
@ITC_GetFIFOReadAvailable :=ITC_GetDLLAddress(LibraryHnd,'ITC_GetFIFOReadAvailable') ;
@ITC_ReadFIFO :=ITC_GetDLLAddress(LibraryHnd,'ITC_ReadFIFO') ;
@ITC_IsClipping :=ITC_GetDLLAddress(LibraryHnd,'ITC_IsClipping') ;
@ITC_Start :=ITC_GetDLLAddress(LibraryHnd,'ITC_Start') ;
@ITC_GetFIFOOverflow :=ITC_GetDLLAddress(LibraryHnd,'ITC_GetFIFOOverflow') ;
@ITC_Stop :=ITC_GetDLLAddress(LibraryHnd,'ITC_Stop') ;
@ITC_GetStatusOverflow :=ITC_GetDLLAddress(LibraryHnd,'ITC_GetStatusOverflow') ;
@ITC_Release :=ITC_GetDLLAddress(LibraryHnd,'ITC_Release') ;
@ITC_Reserve :=ITC_GetDLLAddress(LibraryHnd,'ITC_Reserve') ;
@ITC_SetRange :=ITC_GetDLLAddress(LibraryHnd,'ITC_SetRange') ;
LibraryLoaded := True ;
end
else begin
MessageDlg( ' Instrutech interface library (ITCLIB.DLL) not found', mtWarning, [mbOK], 0 ) ;
LibraryLoaded := False ;
end ;
end ;
function ITC_GetDLLAddress(
Handle : Integer ;
const ProcName : string ) : Pointer ;
// -----------------------------------------
// Get address of procedure within ITCLIB.DLL
// -----------------------------------------
begin
Result := GetProcAddress(Handle,PChar(ProcName)) ;
if Result = Nil then
MessageDlg('ITCLIB.DLL- ' + ProcName + ' not found',mtWarning,[mbOK],0) ;
end ;
function ITC_GetMaxDACVolts : single ;
// -----------------------------------------------------------------
// Return the maximum positive value of the D/A output voltage range
// -----------------------------------------------------------------
begin
Result := FDACVoltageRangeMax ;
end ;
procedure ITC_InitialiseBoard ;
{ -------------------------------------------
Initialise Instrutech interface hardware
-------------------------------------------}
var
Size,Err : Integer ;
begin
DeviceInitialised := False ;
if not LibraryLoaded then ITC_LoadLibrary ;
if LibraryLoaded then begin
// Determine type of ITC interface
if InterfaceType = ITC16_ID then begin
// Load ITC-16 FIFO sequencer codes
INPUT_AD0 := ITC16_INPUT_AD0 ;
INPUT_AD1 := ITC16_INPUT_AD1 ;
INPUT_AD2 := ITC16_INPUT_AD2 ;
INPUT_AD3 := ITC16_INPUT_AD3 ;
INPUT_AD4 := ITC16_INPUT_AD4 ;
INPUT_AD5 := ITC16_INPUT_AD5 ;
INPUT_AD6 := ITC16_INPUT_AD6 ;
INPUT_AD7 := ITC16_INPUT_AD7 ;
INPUT_UPDATE := ITC16_INPUT_UPDATE ;
OUTPUT_DA0 := ITC16_OUTPUT_DA0 ;
OUTPUT_DA1 := ITC16_OUTPUT_DA1 ;
OUTPUT_DA2 := ITC16_OUTPUT_DA2 ;
OUTPUT_DA3 := ITC16_OUTPUT_DA3 ;
OUTPUT_DIGITAL := ITC16_OUTPUT_DIGITAL ;
OUTPUT_UPDATE := ITC16_OUTPUT_UPDATE ;
// Define available A/D voltage range options
FADCVoltageRanges[0] := 10.24 ;
FNumADCVoltageRanges := 1 ;
FTickInterval := ITC16_TICKINTERVAL ;
// No. of invalid samples in FIFO when started
OutPointerSkipCount := -5 ;
end
else begin
// Load ITC-18 FIFO sequencer codes
INPUT_AD0 := ITC18_INPUT_AD0 ;
INPUT_AD1 := ITC18_INPUT_AD1 ;
INPUT_AD2 := ITC18_INPUT_AD2 ;
INPUT_AD3 := ITC18_INPUT_AD3 ;
INPUT_AD4 := ITC18_INPUT_AD4 ;
INPUT_AD5 := ITC18_INPUT_AD5 ;
INPUT_AD6 := ITC18_INPUT_AD6 ;
INPUT_AD7 := ITC18_INPUT_AD7 ;
INPUT_UPDATE := ITC18_INPUT_UPDATE ;
OUTPUT_DA0 := ITC18_OUTPUT_DA0 ;
OUTPUT_DA1 := ITC18_OUTPUT_DA1 ;
OUTPUT_DA2 := ITC18_OUTPUT_DA2 ;
OUTPUT_DA3 := ITC18_OUTPUT_DA3 ;
OUTPUT_DIGITAL := ITC18_OUTPUT_DIGITAL1 ;
OUTPUT_UPDATE := ITC18_OUTPUT_UPDATE ;
// Define available A/D voltage range options
FADCVoltageRanges[0] := 10.24 ;
FADCVoltageRanges[1] := 5.12 ;
FADCVoltageRanges[2] := 2.048 ;
FADCVoltageRanges[3] := 1.024 ;
FNumADCVoltageRanges := 4 ;
FTickInterval := ITC18_TICKINTERVAL ;
// No. of invalid samples in FIFO when started
OutPointerSkipCount := -3 ;
end ;
// Set type of interface
ITC_SetInterfaceType ( InterfaceType ) ;
// Allocate device control structure
Size := ITC_GetStructureSize ;
if Device <> Nil then FreeMem( Device ) ;
GetMem( Device, Size ) ;
// Open device
Err := ITC_Open( Device ) ;
ITC_CheckError( Err, 'ITC_Open' ) ;
if Err <> ACQ_SUCCESS then exit ;
// Initialise interface hardware
Err := ITC_Initialize( Device ) ;
ITC_CheckError( Err, 'ITC_Initialize' ) ;
// Create A/D, D/A and digital O/P buffers
New(ADCFIFO) ;
New(DACFIFO) ;
DeviceInitialised := True ;
end ;
end ;
procedure ITC_ConfigureHardware(
ITCInterfaceType : Integer ;
EmptyFlagIn : Integer ) ;
// -------------------------------------
// Configure library for interface type
// --------------------------------------
begin
InterfaceType := ITCInterfaceType ;
// Initialise board
ITC_InitialiseBoard ;
EmptyFlag := EmptyFlagIn ;
end ;
function ITC_ADCToMemory(
var HostADCBuf : Array of SmallInt ; { A/D sample buffer (OUT) }
nChannels : Integer ; { Number of A/D channels (IN) }
nSamples : Integer ; { Number of A/D samples ( per channel) (IN) }
var dt : Double ; { Sampling interval (s) (IN) }
ADCVoltageRange : Single ; { A/D input voltage range (V) (IN) }
TriggerMode : Integer ; { A/D sweep trigger mode (IN) }
CircularBuffer : Boolean ; { Repeated sampling into buffer (IN) }
ADCChannelInputMap : Array of Integer // Physical A/D input channel map
) : Boolean ; { Returns TRUE indicating A/D started }
{ -----------------------------
Start A/D converter sampling
-----------------------------}
var
i,ch : Integer ;
ExternalTrigger : Integer ;
OutputEnable : Integer ;
Err : Cardinal ;
OK : Boolean ;
ADRange : Array[0..ITC18_NUMBEROFADCINPUTS-1] of Cardinal ;
begin
Result := False ;
if not DeviceInitialised then ITC_InitialiseBoard ;
if not DeviceInitialised then Exit ;
// Stop any acquisition in progress
if ADCActive or DACActive then begin
Err := ITC_Stop( Device ) ;
ITC_CheckError( Err, 'ITC_Stop' ) ;
end ;
// Make sure that dt is an integer number of microsecs
dt := dt / nChannels ;
ITC_CheckSamplingInterval( dt, FTicksPerSample ) ;
dt := dt*nChannels ;
// Copy to internal storage
FNumADCSamples := nSamples ;
FNumADCChannels := nChannels ;
FNumSamplesRequired := nChannels*nSamples ;
FADCSamplingInterval := dt ;
CyclicADCBuffer := CircularBuffer ;
// Set A/D input voltage range for all channels
for i := 0 to FNumADCVoltageRanges do
if ADCVoltageRange = FADCVoltageRanges[i] then begin
for ch := 0 to High(ADRange) do ADRange[ch] := i ;
end ;
Err := ITC_SetRange( Device, ADRange ) ;
ITC_CheckError( Err, 'ITC_SetRange' ) ;
// Set up FIFO acquisition sequence for A/D input channels
for ch := 0 to nChannels-1 do begin
if ADCChannelInputMap[ch] = 0 then Sequence[ch] := INPUT_AD0 ;
if ADCChannelInputMap[ch] = 1 then Sequence[ch] := INPUT_AD1 ;
if ADCChannelInputMap[ch] = 2 then Sequence[ch] := INPUT_AD2 ;
if ADCChannelInputMap[ch] = 3 then Sequence[ch] := INPUT_AD3 ;
if ADCChannelInputMap[ch] = 4 then Sequence[ch] := INPUT_AD4 ;
if ADCChannelInputMap[ch] = 5 then Sequence[ch] := INPUT_AD5 ;
if ADCChannelInputMap[ch] = 6 then Sequence[ch] := INPUT_AD6 ;
if ADCChannelInputMap[ch] = 7 then Sequence[ch] := INPUT_AD7 ;
if ch = (nChannels-1) then Sequence[ch] := Sequence[ch] or INPUT_UPDATE ;
end ;
// Download sequence to interface
Err := ITC_SetSequence( Device, nChannels, Sequence ) ;
ITC_CheckError( Err, 'ITC_SetSequence' ) ;
// Set sampling interval
Err := ITC_SetSamplingInterval( Device, FTicksPerSample ) ;
ITC_CheckError( Err, 'ITC_SetSamplingInterval' ) ;
// Initialise A/D FIFO
Err := ITC_InitializeAcquisition( Device ) ;
ITC_CheckError( Err, 'ITC_InitializeAcquisition' ) ;
// Start A/D sampling
if TriggerMode <> tmWaveGen then begin
// Free Run vs External Trigger of recording seeep
if TriggerMode = tmExtTrigger then ExternalTrigger := 1
else ExternalTrigger := 0 ;
OutputEnable := 0 ;
Err := ITC_Start( Device,
ExternalTrigger,
OutputEnable ) ;
ITC_CheckError( Err, 'ITC_START' ) ;
OK := True ;
end
else OK := True ;
// Initialise A/D buffer output pointer
OutPointer := OutPointerSkipCount ;
ADCActive := OK ;
Result := OK ;
end ;
function ITC_StopADC : Boolean ; { Returns False indicating A/D stopped }
{ -------------------------------
Reset A/D conversion sub-system
-------------------------------}
var
Err : Cardinal ;
begin
Result := False ;
if not DeviceInitialised then ITC_InitialiseBoard ;
if not DeviceInitialised then Exit ;
{ Stop ITC interface (both A/D and D/A) }
Err := ITC_Stop( Device ) ;
ITC_CheckError( Err, 'ITC_Stop' ) ;
ADCActive := False ;
DACActive := False ; // Since A/D and D/A are synchronous D/A stops too
Result := ADCActive ;
end ;
procedure ITC_GetADCSamples(
OutBuf : Pointer ; { Pointer to buffer to receive A/D samples [In] }
var OutBufPointer : Integer { Latest sample pointer [OUT]}
) ;
// -----------------------------------------
// Get A/D samples from ITC interface FIFO
// -----------------------------------------
var
Err,i,OutPointerLimit,NumSamplesToWrite : Integer ;
NumSamples : Cardinal ;
begin
if not ADCActive then Exit ;
// Determine number of samples available in FIFO
ITC_CheckError( ITC_GetFIFOReadAvailable( Device, NumSamples),
'ITC_GetFIFOReadAvailable (ITC_GetADCSamples)') ;
//outputdebugString(PChar(format('%d',[NumSamples]))) ;
// Read A/D samples from FIFO
// (NOTE! It is essential to leave at least one sample
// in the FIFO to avoid terminating A/D sampling)
if NumSamples > 1 then begin
// Interleave samples from A/D FIFO buffers into O/P buffer
if not CyclicADCBuffer then begin
// Single sweep
OutPointerLimit := FNumSamplesRequired - 1 ;
// Ensure FIFO buffer is not emptied if sweep not completed
if (OutPointer + NumSamples) < OutPointerLimit then begin
NumSamples := NumSamples -1 ;
end ;
// Read FIFO
ITC_CheckError( ITC_ReadFIFO( Device, NumSamples, ADCFIFO ),
'ITC_ReadFIFO (ITC_GetADCSamples)') ;
for i := 0 to NumSamples-1 do begin
if (OutPointer >= 0) and (OutPointer <= OutPointerLimit) then
PSmallIntArray(OutBuf)^[OutPointer] := ADCFIFO^[i] ;
Inc(OutPointer) ;
end ;
OutBufPointer := Min(OutPointer,OutPointerLimit) ;
end
else begin
// Ensure FIFO buffer is not emptied (which stops sampling)
NumSamples := NumSamples - 1 ;
// Read FIFO
ITC_CheckError( ITC_ReadFIFO( Device, NumSamples, ADCFIFO ),
'ITC_ReadFIFO (ITC_GetADCSamples)') ;
// Cyclic buffer
for i := 0 to NumSamples-1 do begin
if OutPointer >= 0 then PSmallIntArray(OutBuf)^[OutPointer] := ADCFIFO^[i] ;
Inc(OutPointer) ;
if Outpointer >= FNumSamplesRequired then Outpointer := 0 ;
end ;
OutBufPointer := OutPointer ;
end ;
if (DACPointer > 0) and (DACPointer < FNumSamplesRequired) then begin
NumSamplesToWrite := Min(NumSamples,FNumSamplesRequired-DACPointer) ;
Err := ITC_WriteFIFO( Device, NumSamplesToWrite, @DACFIFO^[DACPointer] ) ;
ITC_CheckError(Err,'ITC_WriteFIFO') ;
DACPointer := DACPointer + NumSamplesToWrite ;
//outputdebugstring(pchar(format('%d %d',[DACPointer,ChannelData.Value])));
end ;
end ;
end ;
procedure ITC_CheckSamplingInterval(
var SamplingInterval : Double ;
var Ticks : Cardinal
) ;
{ ---------------------------------------------------
Convert sampling period from <SamplingInterval> (in s) into
clocks ticks, Returns no. of ticks in "Ticks"
---------------------------------------------------}
begin
Ticks := Round( SamplingInterval / FTickInterval ) ;
Ticks := MaxInt([MinInt([Ticks,ITC_MAXIMUM_TICKS]),ITC_MINIMUM_TICKS]);
SamplingInterval := Ticks*FTickInterval ;
end ;
function ITC_MemoryToDACAndDigitalOut(
var DACValues : Array of SmallInt ;
NumDACChannels : Integer ;
nPoints : Integer ;
var DigValues : Array of SmallInt ;
DigitalInUse : Boolean ;
WaitForExtTrigger : Boolean // Ext. trigger mode
) : Boolean ;
{ --------------------------------------------------------------
Send a voltage waveform stored in DACBuf to the D/A converters
30/11/01 DigFill now set to correct final value to prevent
spurious digital O/P changes between records
--------------------------------------------------------------}
var
i,k,ch,Err,iFIFO : Integer ;
DACChannel : Array[0..15] of Cardinal ;
ADCChannel : Array[0..15] of Cardinal ;
NumOutChannels : Integer ; // No. of DAC + Digital output channels
LastFIFOSample : Integer ; // Last sample index in FIFO
InCh, OutCh : Integer ;
iDAC, iDig : Integer ;
Step,Counter : Single ;
SequenceLength : Cardinal ;
NumSamplesToWrite : Cardinal ;
ExternalTrigger : Cardinal ;
OutputEnable : Cardinal ;
begin
Result := False ;
if not DeviceInitialised then ITC_InitialiseBoard ;
if not DeviceInitialised then Exit ;
{ Stop any acquisition in progress }
ADCActive := ITC_StopADC ;
// Get A/D channel sequence codes
for ch := 0 to FNumADCChannels-1 do ADCChannel[Ch] := Sequence[Ch] ;
// Set up DAC channel O/P sequence codes
for ch := 0 to High(DACChannel) do DACChannel[ch] := OUTPUT_DA0 ;
if NumDACChannels > 1 then DACChannel[1] := OUTPUT_DA1 ;
if NumDACChannels > 2 then DACChannel[2] := OUTPUT_DA2 ;
if NumDACChannels > 3 then DACChannel[3] := OUTPUT_DA3 ;
NumOutChannels := NumDACChannels ;
if DigitalInUse then begin
DACChannel[NumDACChannels] := OUTPUT_DIGITAL ;
NumOutChannels := NumDACChannels + 1 ;
end ;
// Incorporate codes into FIFO control sequence
// (Note. Config and Se0qence already contains data entered by ITC_ADCToMemory)
if FNumADCChannels < NumOutChannels then begin
// No. of output channels exceed input
// -----------------------------------
// Configure sequence memory
SequenceLength := FNumADCChannels*NumOutChannels ;
InCh := 0 ;
OutCh := 0 ;
for k := 0 to SequenceLength-1 do begin
Sequence[k] := ADCChannel[InCh] or DACChannel[OutCh] ;
// D/A channel update
if OutCh = (NumOutChannels-1) then begin
Sequence[k] := Sequence[k] or OUTPUT_UPDATE ;
OutCh := 0 ;
end
else Inc(OutCh) ;
// A/D channel update
if InCh = (FNumADCChannels-1) then begin
Sequence[k] := Sequence[k] or INPUT_UPDATE ;
InCh := 0 ;
end
else Inc(InCh) ;
end ;
// DAC / Dig buffer step interval
Step := NumOutChannels / FNumADCChannels ;
// Copy D/A values into D/A FIFO buffers
iFIFO := 0 ;
Counter := 0.0 ;
LastFIFOSample := FNumADCChannels*FNumADCSamples - 1 ;
While iFIFO <= LastFIFOSample do begin
// Copy D/A values
iDAC := MinInt( [Trunc(Counter),nPoints-1] ) ;
for ch := 0 to NumDACChannels-1 do if iFIFO <= LastFIFOSample then begin
DACFIFO^[iFIFO] := DACValues[iDAC*NumDACChannels+ch] ;
Inc(iFIFO) ;
end ;
// Copy digital values
if DigitalInUse then begin
iDig := MinInt( [Trunc(Counter),nPoints-1]) ;
if iFIFO <= LastFIFOSample then begin
DACFIFO^[iFIFO] := DigValues[iDig] ;
Inc(iFIFO) ;
end ;
end ;
Counter := Counter + Step ;
end ;
end
else begin
// No. of input channels equal or exceed outputs
// ---------------------------------------------
// Configure sequence memory
SequenceLength := FNumADCChannels ;
for ch := 0 to FNumADCChannels-1 do begin
Sequence[ch] := Sequence[ch] or DACChannel[ch] ;
end ;
Sequence[FNumADCChannels-1] := Sequence[FNumADCChannels-1] or OUTPUT_UPDATE ;
// Copy D/A values into D/A FIFO buffers
for i := 0 to FNumADCSamples-1 do begin
iDAC := MinInt( [i, nPoints-1 ] ) ;
iFIFO := i*FNumADCChannels ;
// Copy D/A values
for ch := 0 to FNumADCChannels-1 do begin
if ch < NumOutChannels then
DACFIFO^[iFIFO+ch] := DACValues[iDAC*NumDACChannels+ch]
else DACFIFO^[iFIFO+ch] := DACValues[iDAC*NumDACChannels] ;
end ;
// Copy digital values
if DigitalInUse then begin
DACFIFO^[iFIFO+NumDACChannels] := DigValues[iDAC] ;
end ;
end ;
end ;
// Download sequence to interface
Err := ITC_SetSequence( Device, SequenceLength, Sequence ) ;
ITC_CheckError( Err, 'ITC_SetSequence' ) ;
// Initialise A/D FIFO
Err := ITC_InitializeAcquisition( Device ) ;
ITC_CheckError( Err, 'ITC_InitializeAcquisition' ) ;
// Write D/A samples to FIFO
NumSamplesToWrite := Min(FNumADCSamples*FNumADCChannels,FIFOMaxPoints) ;
Err := ITC_WriteFIFO( Device, NumSamplesToWrite, DACFIFO ) ;
ITC_CheckError(Err,'ITC_WriteFIFO') ;
{Save D/A sweep data }
DACPointer := Min(FNumADCSamples*FNumADCChannels,FIFOMaxPoints) ;
FNumDACPoints := nPoints ;
FNumDACChannels := NumDACChannels ;
// Set sampling interval
Err := ITC_SetSamplingInterval( Device, FTicksPerSample ) ;
ITC_CheckError( Err, 'ITC_SetSamplingInterval' ) ;
// Start combined A/D & D/A sweep
if WaitForExtTrigger then ExternalTrigger := 1
else ExternalTrigger := 0 ;
OutputEnable := 1 ; // Enable D/A output on interface
Err := ITC_Start( Device,
ExternalTrigger,
OutputEnable ) ;
ITC_CheckError( Err, 'ITC_Start' ) ;
DACActive := True ;
ADCActive := True ;
Result := DACActive ;
end ;
function ITC_GetDACUpdateInterval : double ;
{ -----------------------
Get D/A update interval
-----------------------}
begin
Result := FADCSamplingInterval ;
{ NOTE. DAC update interval is constrained to be the same
as A/D sampling interval (set by ITC_ADCtoMemory. }
end ;
function ITC_StopDAC : Boolean ;
{ ---------------------------------
Disable D/A conversion sub-system
---------------------------------}
begin
if not DeviceInitialised then ITC_InitialiseBoard ;
DACActive := False ;
Result := DACActive ;
end ;
procedure ITC_WriteDACsAndDigitalPort(
var DACVolts : array of Single ; // D/A voltage settings [In]
nChannels : Integer ; // No. D/A channels to be updated [In]
DigValue : Integer // Digital bit valuues [In]
) ;
{ ----------------------------------------------------
Update D/A outputs with voltages suppled in DACVolts
and TTL digital O/P with bit pattern in DigValue
----------------------------------------------------}
const
NumBlocks = 4;
MaxDACValue = 32767 ;
MinDACValue = -32768 ;
var
DACScale : single ;
i,ch,DACValue : Integer ;
Err : Integer ; // ITC error number
iFIFO : Integer ; // DACFIFO index
iSEQ : Integer ; // Sequence array index
SequenceLength : Cardinal ; // No. of elements in sequence
NumSamplesToWrite : Cardinal ; // No. of samples to be output to DACs/Digital
NumSamplesAcquired : Cardinal ; // No. of A/D samples acquired so far
ExternalTrigger : Cardinal ; // Wait for external trigger flag (1=ext)
OutputEnable : Cardinal ; // Enable D/A outputs during sweep (1=enable)
begin
if not DeviceInitialised then ITC_InitialiseBoard ;
if not DeviceInitialised then Exit ;
if ADCActive then Exit ;
// Stop A/D sampling if it running
if ADCActive then ITC_StopADC ;
// Scale from Volts to binary integer units
DACScale := MaxDACValue/FDACVoltageRangeMax ;
{ Fill output FIFO with D/A and digital values }
iFIFO := 0 ;
for i := 0 to NumBlocks-1 do begin
for ch := 0 to nChannels-1 do begin
DACValue := Round(DACVolts[ch]*DACScale) ;
// Keep within legitimate limits
if DACValue > MaxDACValue then DACValue := MaxDACValue ;
if DACValue < MinDACValue then DACValue := MinDACValue ;
DACFIFO^[iFIFO] := DACValue ;
Inc(iFIFO) ;
end ;
DACFIFO^[iFIFO] := DigValue ;
Inc(iFIFO) ;
end ;
NumSamplesToWrite := iFIFO ;
// Set up FIFO acquisition sequence for A/D input channels
iSeq := 0 ;
// Add D/A channels
for ch := 0 to nChannels-1 do begin
if ch = 0 then Sequence[iSeq] := INPUT_AD0 or OUTPUT_DA0 or INPUT_UPDATE ;
if ch = 1 then Sequence[iSeq] := INPUT_AD0 or OUTPUT_DA1 or INPUT_UPDATE ;
if ch = 2 then Sequence[iSeq] := INPUT_AD0 or OUTPUT_DA2 or INPUT_UPDATE ;
if ch = 3 then Sequence[iSeq] := INPUT_AD0 or OUTPUT_DA3 or INPUT_UPDATE ;
Inc(iSeq) ;
end ;
// Add digital channel
Sequence[iSeq] := INPUT_AD0 or OUTPUT_DIGITAL or OUTPUT_UPDATE or INPUT_UPDATE ;
SequenceLength := iSeq + 1 ;
// Download sequence to interface
Err := ITC_SetSequence( Device, SequenceLength, Sequence ) ;
ITC_CheckError( Err, 'ITC_SetSequence' ) ;
// Initialise A/D-D/A FIFO
Err := ITC_InitializeAcquisition( Device ) ;
ITC_CheckError( Err, 'ITC_InitializeAcquisition' ) ;
// Write D/A samples to FIFO
Err := ITC_WriteFIFO( Device, NumSamplesToWrite, DACFIFO ) ;
ITC_CheckError(Err,'ITC_WriteFIFO') ;
// Set sampling interval
Err := ITC_SetSamplingInterval( Device, 100 ) ;
ITC_CheckError( Err, 'ITC_SetSamplingInterval' ) ;
// Start combined A/D & D/A sweep
ExternalTrigger := 0 ; // Start sweep immediately
OutputEnable := 1 ; // Enable D/A output on interface
Err := ITC_Start( Device,
ExternalTrigger,
OutputEnable ) ;
ITC_CheckError( Err, 'ITC_Start' ) ;
// Wait till all channels output
NumSamplesAcquired := 0 ;
while NumSamplesAcquired < (NumSamplesToWrite div 2) do begin
Err := ITC_GetFIFOReadAvailable( Device, NumSamplesAcquired ) ;
ITC_CheckError(Err,'ITC_GetFIFOReadAvailable') ;
end ;
Err := ITC_ReadFIFO( Device, NumSamplesAcquired, DACFIFO ) ;
ITC_CheckError(Err,'ITC_ReadFIFO') ;
// Stop A/D + D/A sampling
ITC_StopADC ;
end ;
function ITC_ReadADC(
Channel : Integer ; // A/D channel
ADCVoltageRange : Single // A/D input voltage range
) : SmallInt ;
// ---------------------------
// Read Analogue input channel
// ---------------------------
const
NumSamples = 8 ;
var
ADRange : Array[0..ITC18_NUMBEROFADCINPUTS-1] of Cardinal ;
i,ch : Integer ;
Err : Integer ;
NumSamplesNeeded : Cardinal ; // No. of samples to be acquired
NumSamplesAcquired : Cardinal ; // No. of A/D samples acquired so far
ExternalTrigger : Cardinal ;
OutputEnable : Cardinal ;
begin
Result := 0 ;
if not DeviceInitialised then ITC_InitialiseBoard ;
if ADCActive then Exit ;
if DeviceInitialised then begin
// Stop A/D sampling if it running
if ADCActive then ITC_StopADC ;
// Set A/D input voltage range for all channels
for i := 0 to FNumADCVoltageRanges do
if ADCVoltageRange = FADCVoltageRanges[i] then begin
for ch := 0 to High(ADRange) do ADRange[ch] := i ;
end ;
Err := ITC_SetRange( Device, ADRange ) ;
ITC_CheckError( Err, 'ITC_SetRange' ) ;
// Set up FIFO acquisition sequence for A/D input channels
case Channel of
0 : Sequence[0] := INPUT_AD0 ;
1 : Sequence[0] := INPUT_AD1 ;
2 : Sequence[0] := INPUT_AD2 ;
3 : Sequence[0] := INPUT_AD3 ;
4 : Sequence[0] := INPUT_AD4 ;
5 : Sequence[0] := INPUT_AD5 ;
6 : Sequence[0] := INPUT_AD6 ;
7 : Sequence[0] := INPUT_AD7 ;
end ;
Sequence[0] := Sequence[0] or INPUT_UPDATE ;
// Download sequence to interface
Err := ITC_SetSequence( Device, 1, Sequence ) ;
ITC_CheckError( Err, 'ITC_SetSequence' ) ;
// Set sampling interval (50 ticks, 50-75 us)
Err := ITC_SetSamplingInterval( Device, 50 ) ;
ITC_CheckError( Err, 'ITC_SetSamplingInterval' ) ;
// Initialise A/D FIFO
Err := ITC_InitializeAcquisition( Device ) ;
ITC_CheckError( Err, 'ITC_InitializeAcquisition' ) ;
// Start A/D sampling
ExternalTrigger := 0 ;
OutputEnable := 0 ;
Err := ITC_Start( Device,
ExternalTrigger,
OutputEnable ) ;
ITC_CheckError( Err, 'ITC_START' ) ;
// Wait till channels acquired
NumSamplesAcquired := 0 ;
NumSamplesNeeded := (-OutPointerSkipCount) + 2 ;
while NumSamplesAcquired < NumSamplesNeeded do begin
Err := ITC_GetFIFOReadAvailable( Device, NumSamplesAcquired ) ;
ITC_CheckError(Err,'ITC_GetFIFOReadAvailable') ;
end ;
Err := ITC_ReadFIFO( Device, NumSamplesAcquired, ADCFIFO ) ;
ITC_CheckError(Err,'ITC_ReadFIFO') ;
// Stop A/D + D/A sampling
ITC_StopADC ;
// Return value for selected channel
Result := ADCFIFO^[-OutPointerSkipCount] ;
end
else Result := 0 ;
end ;
procedure ITC_GetChannelOffsets(
var Offsets : Array of Integer ;
NumChannels : Integer
) ;
{ --------------------------------------------------------
Returns the order in which analog channels are acquired
and stored in the A/D data buffers
--------------------------------------------------------}
var
ch : Integer ;
begin
for ch := 0 to NumChannels-1 do Offsets[ch] := ch ;
end ;
procedure ITC_CloseLaboratoryInterface ;
{ -----------------------------------
Shut down lab. interface operations
----------------------------------- }
begin
if DeviceInitialised then begin
{ Stop any acquisition in progress }
ITC_StopADC ;
{ Close connection with interface }
ITC_Close( Device ) ;
// Free device control strucutre
if Device <> Nil then FreeMem( Device ) ;
// Free A/D, D/A and digital O/P buffers
Dispose(ADCFIFO) ;
Dispose(DACFIFO) ;
// Free DLL library
FreeLibrary( LibraryHnd ) ;
DeviceInitialised := False ;
DACActive := False ;
ADCActive := False ;
end ;
end ;
function TrimChar( Input : Array of ANSIChar ) : string ;
var
i : Integer ;
pInput : PANSIChar ;
begin
pInput := @Input ;
Result := '' ;
for i := 0 to StrLen(pInput)-1 do Result := Result + Input[i] ;
end ;
{ -------------------------------------------
Return the smallest value in the array 'Buf'
-------------------------------------------}
function MinInt(
const Buf : array of LongInt { List of numbers (IN) }
) : LongInt ; { Returns Minimum of Buf }
var
i,Min : LongInt ;
begin
Min := High(Min) ;
for i := 0 to High(Buf) do
if Buf[i] < Min then Min := Buf[i] ;
Result := Min ;
end ;
{ -------------------------------------------
Return the largest value in the array 'Buf'
-------------------------------------------}
function MaxInt(
const Buf : array of LongInt { List of numbers (IN) }
) : LongInt ; { Returns Maximum of Buf }
var
i,Max : LongInt ;
begin
Max := -High(Max) ;
for i := 0 to High(Buf) do
if Buf[i] > Max then Max := Buf[i] ;
Result := Max ;
end ;
Procedure ITC_CheckError(
Err : Cardinal ; // Error code
ErrSource : String ) ; // Name of procedure which returned Err
// ----------------------------------------------
// Report type and source of ITC interface error
// ----------------------------------------------
const
MAX_SIZE = 100 ;
var
MsgBuf: array[0..MAX_SIZE] of ANSIchar;
begin
if Err <> ACQ_SUCCESS then begin
ITC_GetStatusText( device, Err, MsgBuf, MAX_SIZE);
MessageDlg( ErrSource + ' - ' + StrPas(MsgBuf), mtError, [mbOK], 0) ;
end ;
end ;
Initialization
Device := Nil ;
LibraryHnd := 0 ;
InterfaceType := 0 ;
end.
|
unit CRepInfoGroupsFrame;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, JvExComCtrls, JvListView, StdCtrls, ResearchGroup;
type
TfrmInfoGroup = class(TFrame)
gbxInfoGroup: TGroupBox;
lvInfoGroup: TJvListView;
private
{ Private declarations }
FSelectedInfoGroups: TInfoGroups;
function GetSelectedInfoGroup: TInfoGroup;
function GetSelectedInfoGroups: TInfoGroups;
public
{ Public declarations }
procedure RefreshInfoGroups;
property SelectedInfoGroup: TInfoGroup read GetSelectedInfoGroup;
property SelectedInfoGroups: TInfoGroups read GetSelectedInfoGroups;
end;
implementation
uses Facade;
{$R *.dfm}
{ TfrmInfoGroup }
function TfrmInfoGroup.GetSelectedInfoGroup: TInfoGroup;
begin
Result := TInfoGroup(lvInfoGroup.Selected.Data);
end;
function TfrmInfoGroup.GetSelectedInfoGroups: TInfoGroups;
var i: integer;
begin
if not Assigned(FSelectedInfoGroups) then
begin
FSelectedInfoGroups := TInfoGroups.Create;
FSelectedInfoGroups.OwnsObjects := False;
end
else FSelectedInfoGroups.Clear;
for i := 0 to lvInfoGroup.Items.Count - 1 do
if lvInfoGroup.Items[i].Selected then
FSelectedInfoGroups.Add(TInfoGroup(lvInfoGroup.Items[i].Data), false, False);
Result := FSelectedInfoGroups;
end;
procedure TfrmInfoGroup.RefreshInfoGroups;
var i: Integer;
li: TListItem;
begin
lvInfoGroup.Items.Clear;
with TMainFacade.GetInstance.InfoGroups do
for i := 0 to Count - 1 do
begin
li := lvInfoGroup.Items.Add;
li.Caption := Items[i].Name;
li.SubItems.Add(Items[i].Tag);
li.SubItems.Add(Items[i].Place);
li.Data := Items[i];
end;
end;
end.
|
unit eVideoFile;
interface
uses
API_ORM,
eAudioStream,
eCommon,
eVideoStream;
type
TVideoReleaseType = class(TEntity)
private
FName: string;
public
class function GetStructure: TSructure; override;
published
property Name: string read FName write FName;
end;
TVideoReleaseTypeList = TEntityList<TVideoReleaseType>;
TVideoFile = class(TEntity)
private
FAudioStreamRels: TV2AStreamRelList;
FDuration: Integer;
FFormat: string;
FMovieID: Integer;
FMovieName: string;
FPath: string;
FReleaseType: TVideoReleaseType;
FReleaseTypeID: Integer;
FSize: Int64;
FVideoStreams: TVideoStreamList;
function GetAudioStreamRels: TV2AStreamRelList;
function GetVideoStreams: TVideoStreamList;
procedure SetReleaseTypeID(aValue: Integer);
public
class function GetStructure: TSructure; override;
property AudioStreamRels: TV2AStreamRelList read GetAudioStreamRels;
property VideoStreams: TVideoStreamList read GetVideoStreams;
published
property Duration: Integer read FDuration write FDuration;
property Format: string read FFormat write FFormat;
property MovieID: Integer read FMovieID write FMovieID;
property MovieName: string read FMovieName write FMovieName;
property Path: string read FPath write FPath;
property ReleaseType: TVideoReleaseType read FReleaseType write FReleaseType;
property ReleaseTypeID: Integer read FReleaseTypeID write SetReleaseTypeID;
property Size: Int64 read FSize write FSize;
end;
TVideoFileList = TEntityList<TVideoFile>;
implementation
uses
eVideoMovie;
procedure TVideoFile.SetReleaseTypeID(aValue: Integer);
begin
FReleaseTypeID := aValue;
if ReleaseType = nil then
ReleaseType := TVideoReleaseType.Create(aValue);
end;
class function TVideoReleaseType.GetStructure: TSructure;
begin
Result.TableName := 'VIDEO_RELEASE_TYPES';
end;
function TVideoFile.GetAudioStreamRels: TV2AStreamRelList;
begin
if not Assigned(FAudioStreamRels) then
FAudioStreamRels := TV2AStreamRelList.Create(Self);
Result := FAudioStreamRels;
end;
function TVideoFile.GetVideoStreams: TVideoStreamList;
begin
if not Assigned(FVideoStreams) then
FVideoStreams := TVideoStreamList.Create(Self);
Result := FVideoStreams;
end;
class function TVideoFile.GetStructure: TSructure;
begin
Result.TableName := 'VIDEO_FILES';
AddForeignKey(Result.ForeignKeyArr, 'MOVIE_ID', TMovie, 'ID');
AddForeignKey(Result.ForeignKeyArr, 'RELEASE_TYPE_ID', TVideoReleaseType, 'ID');
end;
end.
|
{Ä Fido Pascal Conference ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ PASCAL Ä
Msg : 357 of 367
From : Tom Lawrence 1:2605/606.0 11 Apr 93 23:56
To : Andrew Fort
Subj : Data structures
ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ
> Yep, you people out there may notice that in fact this is an extended
> fidonet type-2 mail packet packed message header.. I know you cannot
> just blockread this, since the DateTime/ToName/FromName/Subject
> fields are null-terminated, so how do I do it?
I usually Blockread the header up to the To field (the Date is null
terminated, but it's always 20 characters). Then, Blockread in the 36
characters for the To field, look for the #0, and move the file pointer back..
for example, suppose you blockread in 36 bytes, and the 0 was at the 17th
cell... 36-17=19, so you'd move the file pointer back 19 bytes
(Seek(F),FilePos(F)-19), then do the same thing with the From field, then the
subject. Or, if you want, Blockread 144 bytes into a buffer, extract each
string, and seek back in the file only once. StrTok is a handy function to use
for this, taken from C's StrTok function... here's some sample code: }
{********************************************************************}
Function StrTok(Var S:String;Tokens:String):String;
Var X,
Y,
Min:Byte;
T:String;
Begin
While Pos(S[1],Tokens)>0 Do
Begin
Delete(S,1,1);
If S='' Then Exit;
End;
Min:=Length(S);
For X:=1 to Length(Tokens) Do
Begin
Y:=Pos(Tokens[X],S);
If (Y>0) and (Y<Min) Then Min:=Y;
End;
If Min<Length(S) Then T:=Copy(S,1,Min-1)
Else T:=Copy(S,1,Min);
Delete(S,1,Min);
If Pos(T[Length(T)],Tokens)>0 Then Dec(T[0]);
StrTok:=T;
End;
{********************************************************************}
Var F:File;
S:String;
BytesRead:Word;
Begin
{* Assuming F is assigned to the message, opened, and you've
already read up to and including the Data field *}
BlockRead(F,S[1],144,BytesRead);
S[0]:=Char(Lo(BytesRead));
Message_To:=StrTok(S,#0);
Message_From:=StrTok(S,#0);
Message_Subject:=StrTok(S,#0);
Seek(F,FilePos(F)-(BytesRead-(Length(Message_To)+Length(Message_From)
+Length(Message_Subject))));
End. |
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [WMS_AGENDAMENTO]
The MIT License
Copyright: Copyright (C) 2016 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit WmsAgendamentoVO;
interface
uses
VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils;
type
[TEntity]
[TTable('WMS_AGENDAMENTO')]
TWmsAgendamentoVO = class(TVO)
private
FID: Integer;
FID_EMPRESA: Integer;
FDATA_OPERACAO: TDateTime;
FHORA_OPERACAO: String;
FLOCAL_OPERACAO: String;
FQUANTIDADE_VOLUME: Integer;
FPESO_TOTAL_VOLUME: Extended;
FQUANTIDADE_PESSOA: Integer;
FQUANTIDADE_HORA: Integer;
//Transientes
public
[TId('ID', [ldGrid, ldLookup, ldComboBox])]
[TGeneratedValue(sAuto)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property Id: Integer read FID write FID;
[TColumn('ID_EMPRESA', 'Id Empresa', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property IdEmpresa: Integer read FID_EMPRESA write FID_EMPRESA;
[TColumn('DATA_OPERACAO', 'Data Operacao', 80, [ldGrid, ldLookup, ldCombobox], False)]
property DataOperacao: TDateTime read FDATA_OPERACAO write FDATA_OPERACAO;
[TColumn('HORA_OPERACAO', 'Hora Operacao', 64, [ldGrid, ldLookup, ldCombobox], False)]
property HoraOperacao: String read FHORA_OPERACAO write FHORA_OPERACAO;
[TColumn('LOCAL_OPERACAO', 'Local Operacao', 450, [ldGrid, ldLookup, ldCombobox], False)]
property LocalOperacao: String read FLOCAL_OPERACAO write FLOCAL_OPERACAO;
[TColumn('QUANTIDADE_VOLUME', 'Quantidade Volume', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property QuantidadeVolume: Integer read FQUANTIDADE_VOLUME write FQUANTIDADE_VOLUME;
[TColumn('PESO_TOTAL_VOLUME', 'Peso Total Volume', 168, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftFloatComSeparador, taRightJustify)]
property PesoTotalVolume: Extended read FPESO_TOTAL_VOLUME write FPESO_TOTAL_VOLUME;
[TColumn('QUANTIDADE_PESSOA', 'Quantidade Pessoa', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property QuantidadePessoa: Integer read FQUANTIDADE_PESSOA write FQUANTIDADE_PESSOA;
[TColumn('QUANTIDADE_HORA', 'Quantidade Hora', 80, [ldGrid, ldLookup, ldCombobox], False)]
[TFormatter(ftZerosAEsquerda, taCenter)]
property QuantidadeHora: Integer read FQUANTIDADE_HORA write FQUANTIDADE_HORA;
//Transientes
end;
implementation
initialization
Classes.RegisterClass(TWmsAgendamentoVO);
finalization
Classes.UnRegisterClass(TWmsAgendamentoVO);
end.
|
unit f2hf;
{*******************************************************}
{ }
{ Form to HTML converter "F2H" }
{ }
{ Copyright (c) 1998-2018 HREF Tools Corp. }
{ http://www.href.com/f2h }
{ }
{ This file is licensed under a Creative Commons }
{ Share-Alike 3.0 License. }
{ http://creativecommons.org/licenses/by-sa/3.0/ }
{ If you use this file, please keep this notice }
{ intact. }
{ }
{ Developed by HREF Tools Corp. 1998-2011 }
{ First author: Philippe Maquet }
{ }
{*******************************************************}
{$I hrefdefines.inc}
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, ComCtrls, StdCtrls, Grids,
tpIntegerTypes,
f2h;
type
NaturalNumber = 1..High(Integer);
type
TSplitterD2 = class(TGraphicControl) // for Delphi2 compatibility
private
FLineDC: HDC;
FDownPos: TPoint;
FSplit: Integer;
FMinSize: NaturalNumber;
FMaxSize: Integer;
FControl: TControl;
FNewSize: Integer;
FActiveControl: TWinControl;
FOldKeyDown: TKeyEvent;
FBeveled: Boolean;
FLineVisible: Boolean;
FOnMoved: TNotifyEvent;
procedure AllocateLineDC;
procedure DrawLine;
procedure ReleaseLineDC;
procedure UpdateSize(X, Y: Integer);
procedure FocusKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure SetBeveled(Value: Boolean);
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 StopSizing;
public
constructor Create(AOwner: TComponent); override;
published
property Align default alLeft;
property Beveled: Boolean read FBeveled write SetBeveled default True;
property Color;
property MinSize: NaturalNumber read FMinSize write FMinSize default 30;
property ParentColor;
property OnMoved: TNotifyEvent read FOnMoved write FOnMoved;
end;
Tf2hFrm = class(TForm)
panLeft: TPanel;
panRight: TPanel;
phCtls: TPanel;
phAttrs: TPanel;
panBottom: TPanel;
grid: TDrawGrid;
treeCtls: TTreeView;
butOK: TButton;
butCancel: TButton;
butExport: TButton;
butBrowse: TButton;
labCtls: TLabel;
labAttrs: TLabel;
butDefault: TButton;
hintBar: TPanel;
chkWH: TCheckBox;
procedure FormResize(Sender: TObject);
procedure treeCtlsChange(Sender: TObject; Node: TTreeNode);
procedure gridDrawCell(Sender: TObject; Col, Row: Int32; Rect: TRect;
State: TGridDrawState);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormShow(Sender: TObject);
procedure butOKClick(Sender: TObject);
procedure gridEnter(Sender: TObject);
procedure gridExit(Sender: TObject);
procedure gridDblClick(Sender: TObject);
procedure gridKeyPress(Sender: TObject; var Key: Char);
procedure butExportClick(Sender: TObject);
procedure butBrowseClick(Sender: TObject);
procedure butDefaultClick(Sender: TObject);
procedure gridKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure gridMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
procedure FormCreate(Sender: TObject);
procedure gridGetEditText(Sender: TObject; ACol, ARow: Int32;
var Value: string);
procedure gridSetEditText(Sender: TObject; ACol, ARow: Int32;
const Value: string);
procedure gridSelectCell(Sender: TObject; Col, Row: Int32;
var CanSelect: Boolean);
private
_bConfirmed : Boolean;
_editAttr : THAttribute;
_form2HTML : TWHForm2HTML;
_lastHR : integer;
split : TSplitterD2;
procedure gridResized;
procedure invalidateChangedAttributes;
procedure invalidateGridCell(col, row : integer);
procedure restoreFormPosAndSize;
procedure saveFormPosAndSize;
procedure setAttrToDefault;
procedure setGridEditMode(row : integer);
procedure seTWHForm2HTML(Form2HTML : TWHForm2HTML);
procedure splitMoved(Sender: TObject);
procedure treeAddhAttrObj(parentNode : TTreeNode; hAttrObj : THAttrObject);
procedure WMGetMinMaxInfo(var msg : TWmGetMinMaxInfo); message WM_GETMINMAXINFO;
public
property Form2HTML : TWHForm2HTML read _form2HTML write seTWHForm2HTML;
end;
var
f2hFrm: Tf2hFrm;
implementation
{$R *.DFM}
uses
registry;
const
CREGINI_PATH = 'Software\HREFTools\Form2HTML';
INI_SECTION = 'Editor';
procedure Tf2hFrm.WMGetMinMaxInfo(var msg : TWmGetMinMaxInfo);
begin
with msg.MinMaxInfo^.ptMinTrackSize do begin
X := 568;
Y := 245;
end;
inherited;
end;
procedure Tf2hFrm.treeAddhAttrObj(parentNode : TTreeNode; hAttrObj : THAttrObject);
var
newParentNode : TTreeNode;
i : integer;
begin
if not (hAttrObj is THContainer) then begin
if hAttrObj.Attributes.count = 0 then
exit;
end;
hAttrObj.Attributes.save;
with treeCtls.items do begin
newParentNode := addChildObject(parentNode, hAttrObj.Name, hAttrObj);
if hAttrObj is THContainer then begin
with THContainer(hAttrObj) do begin
for i := 0 to count - 1 do
treeAddhAttrObj(newParentNode, Children[i]);
end;
end;
end;
treeCtls.AlphaSort;
end;
procedure Tf2hFrm.seTWHForm2HTML(Form2HTML : TWHForm2HTML);
begin
_form2HTML := Form2HTML;
treeAddhAttrObj(nil, _form2HTML.HForm);
treeAddhAttrObj(nil, _form2HTML.HMainContainer);
treeCtls.FullExpand;
end;
procedure Tf2hFrm.gridResized;
begin
with grid do
colWidths[1] := clientWidth - colWidths[0] - 1;
end;
procedure Tf2hFrm.FormResize(Sender: TObject);
begin
gridResized;
end;
procedure Tf2hFrm.splitMoved(Sender: TObject);
begin
gridResized;
end;
{procedure Tf2hFrm.splitMoved(Sender: TObject);
begin
gridResized;
end;}
procedure Tf2hFrm.treeCtlsChange(Sender: TObject; Node: TTreeNode);
var
hAttrObj : THAttrObject;
nAttributes : integer;
begin
hAttrObj := THAttrObject(treeCtls.selected.data);
nAttributes := hAttrObj.Attributes.count;
if nAttributes > 0 then
begin
with grid do begin
rowCount := nAttributes + 1;
phAttrs.visible := true;
if visible then
refresh
else
visible := true;
end;
setGridEditMode(1);
end
else begin
phAttrs.visible := false;
grid.visible := false;
end;
end;
procedure Tf2hFrm.invalidateGridCell(col, row : integer);
var
r : TRect;
begin
// Because TCustomgrid.invalidateCell is not accessible from
// TDrawGrid !
r := grid.cellRect(col, row);
Windows.InvalidateRect(grid.handle, @r, False);
end;
procedure Tf2hFrm.gridDrawCell(Sender: TObject; Col, Row: Int32;
Rect: TRect; State: TGridDrawState);
var
s : string;
hAttrObj : THAttrObject;
attr : THAttribute;
begin
s := '';
with grid.canvas do begin
with font do begin
if col = 0 then
style := style + [fsBold]
else
style := style - [fsBold];
end;
if row = 0 then
begin
if col = 0 then
s := 'Name'
else
s := 'Value';
font.color := clBtnText;
end
else begin
hAttrObj := treeCtls.selected.data;
with hAttrObj.Attributes do begin
attr := AttributeN[row-1];
with font do begin
if aoEditable in attr.options then
begin
if (gdSelected in state) and (not (gdFocused in state)) then
color := clHighlightText
else
color := clWindowText;
end
else
color := clGrayText;
end;
with attr do begin
if col = 0 then
s := Name
else
s := Value;
end;
end;
end;
with rect do
TextOut(left + 2, top + 2, s);
end;
end;
procedure Tf2hFrm.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
var
i : integer;
begin
if not _bConfirmed then begin
with treeCtls.Items do begin
for i := 0 to count - 1 do
THAttrObject(item[i].data).attributes.restore;
end;
end;
saveFormPosAndSize;
end;
procedure Tf2hFrm.setGridEditMode(row : integer);
var
attr : THAttribute;
begin
if treeCtls.selected <> nil then begin
attr := THAttrObject(treeCtls.selected.data).attributes.attributeN[row - 1];
with grid do begin
if not (aoEditable in attr.options) then
options := options - [goEditing]
else begin
if attr.attrType = atBoolean then
options := options - [goEditing]
else
options := options + [goEditing];
end;
end;
end;
end;
procedure Tf2hFrm.gridSelectCell(Sender: TObject; Col, Row: Int32;
var CanSelect: Boolean);
begin
if col = 0 then
begin
CanSelect := false;
grid.col := 1;
grid.row := row;
end
else
setGridEditMode(row);
end;
(*procedure Tf2hFrm.gridSelectCell(Sender: TObject; Col, Row: Integer;
var CanSelect: Boolean);
begin
if col = 0 then
begin
CanSelect := false;
grid.col := 1;
grid.row := row;
end
else
setGridEditMode(row);
end;*)
procedure Tf2hFrm.restoreFormPosAndSize;
var
regIni : TRegIniFile;
l, t, w, h : integer;
r : TRect;
procedure putRectInScreen;
begin
with r do begin
if left < 0 then
offsetRect(r, -left, 0);
if (right > screen.width) then
offsetRect(r, -(right-screen.width), 0);
if top < 0 then
offsetRect(r, 0, -top);
if (bottom > screen.height) then
offsetRect(r, 0, -(bottom-screen.height));
end;
end;
begin
regIni := nil;
try
regIni := TRegIniFile.create(CREGINI_PATH);
with regIni do begin
w := ReadInteger(INI_SECTION, 'Width', 620);
h := ReadInteger(INI_SECTION, 'Height', 440);
l := ReadInteger(INI_SECTION, 'Left', (screen.Width - w) div 2);
t := ReadInteger(INI_SECTION, 'Top', (screen.Height - h) div 2);
end;
r := Rect(l, t, l + w, t + h);
putRectInScreen;
with r do
SetBounds(left, top, right - left, bottom - top);
finally
regIni.free;
end;
end;
procedure Tf2hFrm.saveFormPosAndSize;
var
regIni : TRegIniFile;
begin
regIni := nil;
try
regIni := TRegIniFile.create(CREGINI_PATH);
with regIni do begin
WriteInteger(INI_SECTION, 'Width', Width);
WriteInteger(INI_SECTION, 'Height', Height);
WriteInteger(INI_SECTION, 'Left', Left);
WriteInteger(INI_SECTION, 'Top', Top);
end;
finally
regIni.free;
end;
end;
procedure Tf2hFrm.FormShow(Sender: TObject);
begin
grid.col := 1;
restoreFormPosAndSize;
end;
procedure Tf2hFrm.butOKClick(Sender: TObject);
begin
_bConfirmed := true;
modalResult := mrOK;
end;
procedure Tf2hFrm.gridEnter(Sender: TObject);
begin
butOK.default := false;
setGridEditMode(grid.row);
end;
procedure Tf2hFrm.gridExit(Sender: TObject);
begin
butOK.default := true;
end;
procedure Tf2hFrm.invalidateChangedAttributes;
var
i : integer;
hAttrObj : THAttrObject;
begin
with grid do begin
hAttrObj := THAttrObject(treeCtls.selected.data);
with hAttrObj do begin
for i := 0 to Attributes.count - 1 do begin
if Attributes.AttributeN[i].Changed then begin
invalidateGridCell(0, i + 1);
invalidateGridCell(1, i + 1);
end;
end;
end;
end;
end;
procedure Tf2hFrm.gridDblClick(Sender: TObject);
var
bEdited : Boolean;
begin
with grid do begin
_editAttr := THAttrObject(treeCtls.selected.data).attributes.attributeN[row - 1];
with _editAttr do begin
if (aoEditable in Options) then begin
if (aoDialog in Options) then
begin
if assigned(DialogProc) then
begin
EditorMode := False;
DialogProc(_editAttr, bEdited);
end
else
bEdited := false;
end
else begin
bEdited := True;
case attrType of
atBoolean:
BooleanValue := not BooleanValue;
atList:
begin
EditorMode := False;
Value := NextValue;
end;
else
bEdited := False;
end;
end;
if bEdited then begin
if _editAttr.Changed then
invalidateGridCell(col, row);
invalidateChangedAttributes;
end;
end;
end;
end;
end;
procedure Tf2hFrm.gridKeyPress(Sender: TObject; var Key: Char);
begin
with grid do begin
_editAttr := THAttrObject(treeCtls.selected.data).attributes.attributeN[row - 1];
with _editAttr do begin
if (attrType = atBoolean) and (aoEditable in Options) then begin
case key of
#13, #32:
BooleanValue := not BooleanValue;
't', 'T':
BooleanValue := true;
'f', 'F':
BooleanValue := false;
end;
if _editAttr.Changed then
invalidateGridCell(col, row);
invalidateChangedAttributes;
end;
end;
end;
end;
procedure Tf2hFrm.gridGetEditText(Sender: TObject; ACol, ARow: Int32;
var Value: String);
begin
_editAttr := THAttrObject(treeCtls.selected.data).attributes.attributeN[ARow - 1];
value := _editAttr.value;
end;
procedure Tf2hFrm.gridSetEditText(Sender: TObject; ACol, ARow: Int32;
const Value: String);
var
v : string;
begin
if grid.EditorMode then exit;
v := Value;
if _editAttr.isValid(v) then
begin
_editAttr.value := v;
invalidateChangedAttributes;
end
else
MessageBeep(word(-1));
end;
(*procedure Tf2hFrm.gridGetEditText(Sender: TObject; ACol, ARow: Int32;
var Value: String);
begin
_editAttr := THAttrObject(treeCtls.selected.data).attributes.attributeN[ARow - 1];
value := _editAttr.value;
end;
procedure Tf2hFrm.gridSetEditText(Sender: TObject; ACol, ARow: Int32;
const Value: String);
var
v : string;
begin
if grid.EditorMode then exit;
v := Value;
if _editAttr.isValid(v) then
begin
_editAttr.value := v;
invalidateChangedAttributes;
end
else
MessageBeep(word(-1));
end;*)
procedure Tf2hFrm.butExportClick(Sender: TObject);
begin
if Form2HTML <> nil then begin
with Form2HTML do begin
if chkWH.Checked then
exportWHChunkDialog
else
exportHTMLDialog;
end;
end;
end;
procedure Tf2hFrm.butBrowseClick(Sender: TObject);
begin
if Form2HTML <> nil then begin
with Form2HTML do begin
if chkWH.Checked then
browseWHChunkDialog
else
browseHTMLDialog;
end;
end;
end;
procedure Tf2hFrm.setAttrToDefault;
var
attr : THAttribute;
begin
attr := THAttrObject(treeCtls.selected.data).attributes.attributeN[grid.row - 1];
with attr do
Value := DefValue;
with grid do begin
if attr.Changed then
invalidateGridCell(col, row);
invalidateChangedAttributes;
end;
end;
procedure Tf2hFrm.butDefaultClick(Sender: TObject);
begin
setAttrToDefault;
grid.SetFocus;
end;
procedure Tf2hFrm.gridKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if not grid.editorMode then begin
if (key = VK_DELETE) and (shift = []) then begin
setAttrToDefault;
key := 0;
end;
end;
end;
procedure Tf2hFrm.gridMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
var
r : Integer; // col, row
begin
with grid do begin
if _lastHR <> -1 then begin
if getCapture <> handle then
setCapture(handle); // To be informed when mouse goes out
end;
r := Y div (grid.defaultRowHeight + 1);
if (X < 0) or (X > grid.Width) or (r < 1) or (r >= grid.rowCount) then begin
releaseCapture;
hintBar.caption := '';
_lastHR := -1;
exit;
end;
// Display hint only if not visible already
if (_lastHR <> r)then begin
_lastHR := r;
// Test hint string
hintBar.caption := ' ' + THAttrObject(treeCtls.selected.data).Attributes.AttributeN[r-1].Hint; // Ouf!
end;
end;
end;
procedure Tf2hFrm.FormCreate(Sender: TObject);
begin
_lastHR := -1;
split := TSplitterD2.create(self);
with split do begin
parent := self;
cursor := crHSplit;
left := 185;
minSize := 30;
width := 2;
beveled := False;
OnMoved := splitMoved;
end;
panLeft.align := alLeft;
split.align := alLeft;
panRight.align := alClient;
// Reference http://www.bobswart.nl/Weblog/Blog.aspx?RootId=5:5029
butCancel.ModalResult := ID_CANCEL;
end;
type
THack = class(TWinControl);
constructor TSplitterD2.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
Align := alLeft;
Width := 3;
Cursor := crHSplit;
FMinSize := 30;
FBeveled := True;
end;
procedure TSplitterD2.AllocateLineDC;
begin
FLineDC := GetDCEx(Parent.Handle, 0, DCX_CACHE or DCX_CLIPSIBLINGS
or DCX_LOCKWINDOWUPDATE);
end;
procedure TSplitterD2.DrawLine;
var
P: TPoint;
begin
FLineVisible := not FLineVisible;
P := Point(Left, Top);
if Align in [alLeft, alRight] then
P.X := Left + FSplit else
P.Y := Top + FSplit;
with P do PatBlt(FLineDC, X, Y, Width, Height, PATINVERT);
end;
procedure TSplitterD2.ReleaseLineDC;
begin
ReleaseDC(Parent.Handle, FLineDC);
end;
procedure TSplitterD2.Paint;
var
FrameBrush: HBRUSH;
R: TRect;
begin
R := ClientRect;
Canvas.Brush.Color := Color;
Canvas.FillRect(ClientRect);
if Beveled then
begin
if Align in [alLeft, alRight] then
InflateRect(R, -1, 2) else
InflateRect(R, 2, -1);
OffsetRect(R, 1, 1);
FrameBrush := CreateSolidBrush(ColorToRGB(clBtnHighlight));
FrameRect(Canvas.Handle, R, FrameBrush);
DeleteObject(FrameBrush);
OffsetRect(R, -2, -2);
FrameBrush := CreateSolidBrush(ColorToRGB(clBtnShadow));
FrameRect(Canvas.Handle, R, FrameBrush);
DeleteObject(FrameBrush);
end;
end;
procedure TSplitterD2.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
function FindControl: TControl;
var
P: TPoint;
I: Integer;
begin
Result := nil;
P := Point(Left, Top);
case Align of
alLeft: Dec(P.X);
alRight: Inc(P.X, Width);
alTop: Dec(P.Y);
alBottom: Inc(P.Y, Height);
else
Exit;
end;
for I := 0 to Parent.ControlCount - 1 do
begin
Result := Parent.Controls[I];
if PtInRect(Result.BoundsRect, P) then Exit;
end;
Result := nil;
end;
var
I: Integer;
begin
inherited;
if Button = mbLeft then
begin
FControl := FindControl;
FDownPos := Point(X, Y);
if Assigned(FControl) then
begin
if Align in [alLeft, alRight] then
begin
FMaxSize := Parent.ClientWidth - FMinSize;
for I := 0 to Parent.ControlCount - 1 do
with Parent.Controls[I] do
if Align in [alLeft, alRight] then Dec(FMaxSize, Width);
Inc(FMaxSize, FControl.Width);
end
else
begin
FMaxSize := Parent.ClientHeight - FMinSize;
for I := 0 to Parent.ControlCount - 1 do
with Parent.Controls[I] do
if Align in [alTop, alBottom] then Dec(FMaxSize, Height);
Inc(FMaxSize, FControl.Height);
end;
UpdateSize(X, Y);
AllocateLineDC;
with ValidParentForm(Self) do
if ActiveControl <> nil then
begin
FActiveControl := ActiveControl;
FOldKeyDown := THack(FActiveControl).OnKeyDown;
THack(FActiveControl).OnKeyDown := FocusKeyDown;
end;
DrawLine;
end;
end;
end;
procedure TSplitterD2.UpdateSize(X, Y: Integer);
var
S: Integer;
begin
if Align in [alLeft, alRight] then
FSplit := X - FDownPos.X
else
FSplit := Y - FDownPos.Y;
S := 0;
case Align of
alLeft: S := FControl.Width + FSplit;
alRight: S := FControl.Width - FSplit;
alTop: S := FControl.Height + FSplit;
alBottom: S := FControl.Height - FSplit;
end;
FNewSize := S;
if S < FMinSize then
FNewSize := FMinSize
else if S > FMaxSize then
FNewSize := FMaxSize;
if S <> FNewSize then
begin
if Align in [alRight, alBottom] then
S := S - FNewSize else
S := FNewSize - S;
Inc(FSplit, S);
end;
end;
procedure TSplitterD2.MouseMove(Shift: TShiftState; X, Y: Integer);
begin
inherited;
if Assigned(FControl) then
begin
DrawLine;
UpdateSize(X, Y);
DrawLine;
end;
end;
procedure TSplitterD2.MouseUp(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
inherited;
if Assigned(FControl) then
begin
DrawLine;
case Align of
alLeft: FControl.Width := FNewSize;
alTop: FControl.Height := FNewSize;
alRight:
begin
Parent.DisableAlign;
try
FControl.Left := FControl.Left + (FControl.Width - FNewSize);
FControl.Width := FNewSize;
finally
Parent.EnableAlign;
end;
end;
alBottom:
begin
Parent.DisableAlign;
try
FControl.Top := FControl.Top + (FControl.Height - FNewSize);
FControl.Height := FNewSize;
finally
Parent.EnableAlign;
end;
end;
end;
StopSizing;
end;
end;
procedure TSplitterD2.FocusKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Key = VK_ESCAPE then
StopSizing
else if Assigned(FOldKeyDown) then
FOldKeyDown(Sender, Key, Shift);
end;
procedure TSplitterD2.SetBeveled(Value: Boolean);
begin
FBeveled := Value;
Repaint;
end;
procedure TSplitterD2.StopSizing;
begin
if Assigned(FControl) then
begin
if FLineVisible then DrawLine;
FControl := nil;
ReleaseLineDC;
if Assigned(FActiveControl) then
begin
THack(FActiveControl).OnKeyDown := FOldKeyDown;
FActiveControl := nil;
end;
end;
if Assigned(FOnMoved) then
FOnMoved(Self);
end;
end.
|
// ##################################
// ###### IT PAT 2017 #######
// ###### PHASE 3 #######
// ###### Tiaan van der Riel #######
// ##################################
unit dmAccounts_u;
interface
uses
SysUtils, Classes, DB, ADODB;
type
TdmAccounts = class(TDataModule)
conAccounts: TADOConnection;
tblAccounts: TADOTable;
dsrAccounts: TDataSource;
tblAccountsPlayerID: TIntegerField;
tblAccountsUsername: TWideStringField;
tblAccountsName: TWideStringField;
tblAccountsSurname: TWideStringField;
tblAccountsTotalMatchesPlayed: TSmallintField;
tblAccountsMatchesWon: TSmallintField;
tblAccountsMatchesLost: TSmallintField;
tblAccountsTotalRoundsPlayed: TSmallintField;
tblAccountsRoundsWon: TSmallintField;
tblAccountsRoundsLost: TSmallintField;
tblAccountsKills: TSmallintField;
tblAccountsDeaths: TSmallintField;
tblAccountsAge: TSmallintField;
tblAccountsGender: TWideStringField;
tblAccountsEmailAdress: TWideStringField;
tblAccountsCellphoneNumber: TWideStringField;
tblAccountsIDNumber: TWideStringField;
tblAccountsPassword: TWideStringField;
procedure DataModuleCreate(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
dmAccounts: TdmAccounts;
implementation
{$R *.dfm}
procedure TdmAccounts.DataModuleCreate(Sender: TObject);
{ The purpose of this code is to construct the file path for the connectio string
of the database, this ensures that the user doesn`t have to worry about the database
not being able to be located just because the file path changed }
var
sFilePath: string;
begin
conAccounts.Close;
sFilePath := ExtractFilePath('frmLansLandia_p.exe') + 'dbAccounts.mdb';
conAccounts.ConnectionString :=
'Provider=Microsoft.Jet.OLEDB.4.0;' + 'Data Source=' + sFilePath;
tblAccounts.Open;
end;
end.
|
unit uCalculator;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, ComCtrls;
type
TfCalculator = class(TForm)
memResults: TMemo;
StatusBar: TStatusBar;
panTop: TPanel;
btnStone: TButton;
edtPrimesStart: TEdit;
btnCalcPrimes: TButton;
edtPrimesEnd: TEdit;
btnPrimeNumbers: TButton;
Label3: TLabel;
Label4: TLabel;
lblGCD: TLabel;
lblLCM: TLabel;
lblDIV: TLabel;
lblMOD: TLabel;
btnCLR: TButton;
cbxAppend: TCheckBox;
lblA: TLabel;
lblB: TLabel;
btnImp: TButton;
procedure btnCalcPrimesClick(Sender: TObject);
procedure btnPrimeNumbersClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btnStoneClick(Sender: TObject);
procedure edtPrimesStartChange(Sender: TObject);
procedure btnCLRClick(Sender: TObject);
procedure btnImpClick(Sender: TObject);
private
{ Private declarations }
public
procedure Status( s : string );
end;
var
fCalculator: TfCalculator;
PrimesInitialized : Boolean;
implementation
{$R *.dfm}
const MAX_PRIMES = 10000;
FORMATED = TRUE;
UNFORMATED = FALSE;
var Prime : array[0..MAX_PRIMES] of integer;
function isPrime( n : integer ) : Boolean;
var stillPrime : Boolean;
i : integer;
begin stillPrime := (n <> (n div 2) * 2);
i := 3;
while (i <= Sqrt(n))
do begin
stillPrime := stillPrime AND (n <> n div i * i);
i := i + 2;
end;
isPrime := stillPrime;
end;
procedure InitPrimesArray;
var i : integer;
c : integer; // counter
begin /// create table of prime numbers ///
Prime[0] := 2;
c := 0;
i := 3;
while( c < MAX_PRIMES )
do begin
if isPrime(i)
then begin
Inc( c );
Prime[c] := i;
end;
i := i + 2;
end;
PrimesInitialized := TRUE;
end;
function getPrimeFactors( Number : integer; Formated : Boolean ) : string;
var n : integer;
p : integer;
maxP : integer;
Multiply : string;
Ret : string;
retf : string;
c : integer;
s : string;
begin n := Number; // the actual rest of the number
ret := ''; // data containing factors "."-divided
p := 0; // number of prime being tested
maxP := 0; // biggest prime used
retf := ''; // data formated for returning
Multiply := ' * ';
if (Number > Prime[MAX_PRIMES])
then retf := 'ERROR: Factors for (n < ' + IntToStr(Prime[MAX_PRIMES]) + ') only!'
else begin
while (n > 1)
do begin
if (n = n div Prime[p] * Prime[p])
then begin
n := n div Prime[p];
ret := IntToStr(Prime[p]) + '.' + ret;
if (Prime[p] > maxP) then maxP := Prime[p];
p := 0;
end
else begin
Inc( p );
if (Prime[p] > n) then n := 1;
end;
end;
if (Number = 0) then ret := '0.';
if not Formated
then retf := ret
else begin
/// format powers ///
p := Pos( '.', Ret );
s := Copy( Ret, 1, p ); // get first factor
ret := Copy(Ret, p+1, Length(Ret) - p); // cut off this first factor
c := 1;
while (ret > '')
do begin
while ( s = Copy(Ret, 1, Length(s)) )
do begin
Ret := Copy(Ret, p+1, Length(Ret) - p);
Inc(c);
end;
retf := retf + Copy(s, 1, Length(s)-1); // the factor
if (c > 1) then retf := retf + '^' + IntToStr(c);
retf := retf + Multiply;
p := Pos('.', Ret);
s := Copy(Ret, 1, p); // get first factor
ret := Copy(Ret, p+1, Length(Ret)-p); // cut off this first factor
c := 1;
end;
retf := retf + Copy(s, 1, Length(s)-1);
if ( Copy(retf, 1+Length(retf)-Length(Multiply), Length(Multiply)) = Multiply )
then
retf := Copy(retf, 0, Length(retf) - Length(Multiply));
if (Number = 1) then retf := '1';
end;
end;
result := retf;
end;
function PeekNumber( List : string ) : integer;
var p, V, C : integer;
begin p := Pos('.', List);
Val( Copy(List, 1, p-1), V, C );
if (C = 0)
then result := V
else result := 0;
end;
function CutNumber( var List : string ) : integer;
var p, V, C : integer;
begin p := Pos('.', List);
Val( Copy(List, 1, p-1), V, C );
List := Copy(List, p+1, Length(List)-p);
if (C = 0)
then result := V
else result := 0;
end;
function getLCM( A, B : integer ) : integer;
var factorsA : string;
factorsB : string;
Sum : integer;
begin factorsA := getPrimeFactors( A, UNFORMATED );
factorsB := getPrimeFactors( B, UNFORMATED );
Sum := 1;
repeat A := PeekNumber( factorsA );
B := PeekNumber( factorsB );
if (A = B)
then begin
Sum := Sum * A;
CutNumber( factorsA );
CutNumber( factorsB );
end
else if (A < B)
then begin
Sum := Sum * B;
CutNumber( factorsB );
end
else if (A > B)
then begin
Sum := Sum * A;
CutNumber( factorsA );
end
else
begin
Sum := 0;
factorsA := '';
factorsB := '';
end;
until (factorsA = '') and (factorsB = '');
result := Sum;
end;
function getGCD( A, B : integer ) : integer;
var factorsA : string;
factorsB : string;
Sum : integer;
begin factorsA := getPrimeFactors( A, UNFORMATED );
factorsB := getPrimeFactors( B, UNFORMATED );
Sum := 1;
A := 1;
B := 1;
while (A > 0) and (B > 0)
do begin
A := PeekNumber( factorsA );
B := PeekNumber( factorsB );
if (A > 0) and (A = B)
then begin
Sum := Sum * A;
A := CutNumber( factorsA );
B := CutNumber( factorsB );
end;
while (PeekNumber(factorsA) <> PeekNumber(factorsB))
and (A > 0)
and (B > 0)
do
if (PeekNumber(factorsA) > PeekNumber(factorsB))
then A := CutNumber( factorsA )
else B := CutNumber( factorsB );
end;
result := Sum;
end;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
procedure TfCalculator.FormShow(Sender: TObject);
begin
if not PrimesInitialized
then
InitPrimesArray;
edtPrimesStartChange( Sender );
memResults.Lines.Add( 'Max prime = ' + IntToStr(Prime[MAX_PRIMES]) )
end;
procedure TfCalculator.Status( s : string );
begin
StatusBar.SimpleText := #32 + s;
Application.ProcessMessages;
end;
procedure TfCalculator.edtPrimesStartChange(Sender: TObject);
var
A, B : integer;
cA, cB : integer;
GCD : integer;
LCM : integer;
ADB : integer;
AMB : integer;
f : string;
begin Val( edtPrimesStart.Text, A, cA );
Val( edtPrimesEnd.Text, B, cB );
if (cA = 0) and (cB = 0) and (B <> 0)
then begin
ADB := A div B;
AMB := A mod B;
lblDIV.Caption := 'A div B = ' + IntToStr(ADB);
lblMOD.Caption := 'A mod B = ' + IntToStr(AMB);
btnStone.Enabled := (AMB = 0);
end
else begin
lblDIV.Caption := 'A div B';
lblMOD.Caption := 'A mod B';
end;
if (cA = 0) and (cB = 0)
then begin
GCD := getGCD( A, B );
LCM := getLCM( A, B );
lblGCD.Caption := 'GCD = ' + IntToStr(GCD);
lblLCM.Caption := 'LCM = ' + IntToStr(LCM);
end
else begin
lblGCD.Caption := 'GCD';
lblLCM.Caption := 'LCM';
end;
if (cA <> 0)
then lblA.Caption := 'A'
else begin
f := getPrimeFactors(A, FORMATED);
if (f = edtPrimesStart.Text)
then f := f + ' (prime)'
else f := 'A = ' + f;
lblA.Caption := f;
end;
if (cB <> 0)
then lblB.Caption := 'B'
else begin
f := getPrimeFactors(B, FORMATED);
if (f = edtPrimesStart.Text)
then f := f + ' (prime)'
else f := 'B = ' + f;
lblB.Caption := f;
end;
end;
procedure TfCalculator.btnPrimeNumbersClick(Sender: TObject);
var
first : integer;
last : integer;
i : integer;
begin first := StrToInt( edtPrimesStart.Text );
last := StrToInt( edtPrimesEnd.Text );
if (first > last)
then begin
i := last;
last := first;
first := i;
end;
Status( 'calculating...' );
memResults.Lines.BeginUpdate;
if not cbxAppend.Checked then memResults.Clear;
memResults.Lines.Add( 'List of prime numbers from ' + IntToStr(first) + ' to ' + IntToStr(last) + ':' );
for i := first to last
do
if isPrime(i)
then
memResults.Lines.Add( IntToStr(i) );
memResults.Lines.Add( '' );
memResults.Lines.EndUpdate;
Status( 'done.' );
end;
procedure TfCalculator.btnCalcPrimesClick(Sender: TObject);
var
first : integer;
last : integer;
i : integer;
f, s : string;
begin first := StrToInt( edtPrimesStart.Text );
last := StrToInt( edtPrimesEnd.Text );
if (first > last)
then begin
i := last;
last := first;
first := i;
end;
Status( 'calculating...' );
memResults.Lines.BeginUpdate;
if not cbxAppend.Checked then memResults.Clear;
for i := first to last
do
begin
f := getPrimeFactors(i, FORMATED);
s := IntToStr(i);
if (f = s)
then s := s + ' (prime)'
else s := s + ' = ' + f;
memResults.Lines.Add(s);
end;
memResults.Lines.Add( '' );
memResults.Lines.EndUpdate;
Status( 'done.' );
end;
procedure TfCalculator.btnStoneClick(Sender: TObject);
var CS, R, b : integer;
i, k : integer;
s, t, u : string;
begin Status( 'calculating...' );
memResults.Lines.BeginUpdate;
if not cbxAppend.Checked then memResults.Clear;
CS := StrToInt( edtPrimesStart.Text );
R := StrToInt( edtPrimesEnd.Text );
if (CS < R)
then begin
i := R;
R := CS;
CS := i;
end;
memResults.Lines.Add( 'List of all n = m * ' + IntToStr(R)
+ ', where m is prime and gcd(m, '
+ IntToStr(CS)
+ ') = 1' );
u := '(no results)';
for i := 1 to CS div (R * 2)
do begin
//t := getPrimeFactors(i, FORMATED);
if isPrime(i)
and (getGCD(i,CS) = 1)
then begin
memResults.Lines.Add( IntToStr(i*R) );
u := '';
end;
end;
memResults.Lines.Add( u );
memResults.Lines.EndUpdate;
Status( 'done.' );
end;
procedure TfCalculator.btnImpClick(Sender: TObject);
var CS, R, b : integer;
i, k : integer;
s, t, u : string;
NextUpdate : Cardinal;
begin Status( 'calculating...' );
memResults.Lines.BeginUpdate;
if not cbxAppend.Checked then memResults.Clear;
CS := StrToInt( edtPrimesStart.Text );
R := StrToInt( edtPrimesEnd.Text );
memResults.Lines.Add( 'List of all i * k, where (i * k) mod ' + IntToStr(CS) + ' = 1' );
u := '(no results)';
NextUpdate := GetTickCount + 50;
for i := 1 to CS div 2 do
for k := 1 to CS
do begin
if (k * i) mod CS = 1
then begin
b := (k * i) div CS;
memResults.Lines.Add( IntToStr(i) + ' * ' + IntToStr(k) + ' = ' +IntToStr(b)+ ' * ' +IntToStr(CS)+ ' + 1' );
u := '';
end;
if (GetTickCount > NextUpdate)
then begin
b := (100*i + k div CS) div (CS div 2);
//Status( 'calculating... ' + IntToStr(b) + '%' );
Status( 'calculating... ' {+ 'i=' + IntToStr(i) + ' k=' + IntToStr(b) + ' # '} + IntToStr(b) + '%' );
NextUpdate := GetTickCount + 333;
end;
end;
memResults.Lines.Add( u );
memResults.Lines.EndUpdate;
Status( 'done.' );
end;
procedure TfCalculator.btnCLRClick(Sender: TObject);
begin
memResults.Clear;
end;
begin
PrimesInitialized := FALSE;
end.
|
unit Pkg.Json.Settings;
interface
Type
TSettings = class
private
class var FInstance: TSettings;
var
FAddJsonPropertyAttributes: Boolean;
FPostFix: string;
FPostFixClassNames: Boolean;
FUsePascalCase: Boolean;
FSuppressZeroDate: Boolean;
constructor MakeSingleton;
public
constructor Create; reintroduce; deprecated 'Don''t use this!';
class function Instance: TSettings;
class function GetPostFix: string;
property AddJsonPropertyAttributes: Boolean read FAddJsonPropertyAttributes write FAddJsonPropertyAttributes;
property PostFixClassNames: Boolean read FPostFixClassNames write FPostFixClassNames;
property PostFix: string read FPostFix write FPostFix;
property UsePascalCase: Boolean read FUsePascalCase write FUsePascalCase;
property SuppressZeroDate: Boolean read FSuppressZeroDate write FSuppressZeroDate;
end;
implementation
uses System.SysUtils, System.Strutils;
{ TSettings }
constructor TSettings.Create;
begin
raise Exception.Create('Don''t call the constructor directly!');
end;
class function TSettings.GetPostFix: string;
begin
Result := IfThen(Instance.PostFixClassNames, Instance.PostFix, string.empty);
end;
class function TSettings.Instance: TSettings;
begin
if not Assigned(FInstance) then
FInstance := TSettings.MakeSingleton;
Result := FInstance;
end;
constructor TSettings.MakeSingleton;
begin
inherited Create;
FUsePascalCase := True;
FAddJsonPropertyAttributes := False;
FPostFixClassNames := False;
FPostFix := 'DTO';
FSuppressZeroDate := True;
end;
initialization
finalization
TSettings.Instance.Free;
end.
|
{
Find records in selection.
Hotkey: Ctrl+F
}
unit userscript;
var
frm: TForm;
lbRecords: TCheckListBox;
mnRecords: TPopupMenu;
MenuItem: TMenuItem;
chkHas: TCheckBox;
btnFind, btnJump, btnCancel: TButton;
edHas: TLabeledEdit;
findMode: integer;
findRecords: string;
slHasElements: TStringList;
slFound: TStringList;
//===========================================================================
// on key down event handler for options form
procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if Key = VK_RETURN then
TForm(Sender).ModalResult := mrYes;
if Key = VK_ESCAPE then
TForm(Sender).ModalResult := mrCancel;
end;
//===========================================================================
// on click event handler for "Select All" popup menu
procedure SelectAllClick(Sender: TObject);
begin
lbRecords.CheckAll(cbChecked, True, True);
end;
//===========================================================================
// on click event handler for "Select None" popup menu
procedure SelectNoneClick(Sender: TObject);
begin
lbRecords.CheckAll(cbUnchecked, True, True);
end;
//===========================================================================
// prepare search criterias
procedure PrepareData;
var
i: integer;
begin
for i := 0 to lbRecords.Items.Count - 1 do
if lbRecords.Checked[i] then begin
if findRecords <> '' then
findRecords := findRecords + ',';
findRecords := findRecords + Copy(lbRecords.Items[i], 1, 4);
end;
if findRecords = '' then
Exit;
if chkHas.Checked then begin
slHasElements.DelimitedText := edHas.Text;
for i := Pred(slHasElements.Count) downto 0 do begin
slHasElements[i] := Trim(slHasElements[i]);
if slHasElements[i] = '' then
slHasElements.Delete(i);
end;
end;
end;
//===========================================================================
// show search options form
procedure OptionsForm;
var
ini: TMemIniFile;
s: string;
i: integer;
begin
frm := TForm.Create(nil);
try
frm.Caption := 'Find records';
frm.Width := 650;
frm.Height := 400;
frm.Position := poScreenCenter;
frm.BorderStyle := bsDialog;
frm.KeyPreview := True;
frm.OnKeyDown := FormKeyDown;
lbRecords := TCheckListBox.Create(frm);
lbRecords.Parent := frm;
lbRecords.Left := 8;
lbRecords.Top := 8;
lbRecords.Width := 240;
lbRecords.Height := 350;
GetRecordDefNames(lbRecords.Items);
mnRecords := TPopupMenu.Create(frm);
lbRecords.PopupMenu := mnRecords;
MenuItem := TMenuItem.Create(mnRecords);
MenuItem.Caption := 'Select &All';
MenuItem.OnClick := SelectAllClick;
mnRecords.Items.Add(MenuItem);
MenuItem := TMenuItem.Create(mnRecords);
MenuItem.Caption := 'Select &None';
MenuItem.OnClick := SelectNoneClick;
mnRecords.Items.Add(MenuItem);
chkHas := TCheckBox.Create(frm);
chkHas.Parent := frm;
chkHas.Caption := 'Has Element(s)';
chkHas.Left := 260;
chkHas.Top := 8;
edHas := TLabeledEdit.Create(frm);
edHas.Parent := frm;
edHas.LabelPosition := lpAbove;
edHas.EditLabel.Caption := 'List of names as they appear when viewing record separated by comma';
edHas.Left := chkHas.Left + 16;
edHas.Top := chkHas.Top + 36;
edHas.Width := 350;
btnFind := TButton.Create(frm);
btnFind.Parent := frm;
btnFind.Caption := 'Find all records';
btnFind.ModalResult := mrOk;
btnFind.Width := 130;
btnFind.Left := 260;
btnFind.Top := 332;
btnJump := TButton.Create(frm);
btnJump.Parent := frm;
btnJump.Caption := 'Jump to first matched';
btnJump.ModalResult := mrYes;
btnJump.Width := 130;
btnJump.Left := btnFind.Left + btnFind.Width + 16;
btnJump.Top := btnFind.Top;
btnCancel := TButton.Create(frm);
btnCancel.Parent := frm;
btnCancel.Caption := 'Cancel';
btnCancel.ModalResult := mrCancel;
btnCancel.Left := btnJump.Left + btnJump.Width + 16;
btnCancel.Top := btnFind.Top;
// read settings from ini file
ini := TMemIniFile.Create(ScriptsPath + 'Find records.ini');
s := ini.ReadString(wbGameName, 'Records', '');
for i := 0 to Pred(lbRecords.Items.Count) do
if Pos(Copy(lbRecords.Items[i], 1, 4), s) > 0 then
lbRecords.Checked[i] := True;
chkHas.Checked := ini.ReadBool(wbGameName, 'DoHasElements', chkHas.Checked);
edHas.Text := ini.ReadString(wbGameName, 'HasElements', edHas.Text);
findMode := 0;
i := frm.ShowModal;
if i = mrOk then findMode := 1 else
if i = mrYes then findMode := 2;
// prepare search data and write settings to ini file
if findMode <> 0 then begin
PrepareData;
ini.WriteString(wbGameName, 'Records', findRecords);
ini.WriteBool(wbGameName, 'DoHasElements', chkHas.Checked);
ini.WriteString(wbGameName, 'HasElements', edHas.Text);
ini.UpdateFile;
end;
finally
frm.Free;
if Assigned(ini) then ini.Free;
end;
end;
//===========================================================================
// Free memory
procedure CleanUp;
begin
slHasElements.Free;
slFound.Free;
end;
//===========================================================================
function Initialize: Integer;
begin
slHasElements := TStringList.Create;
slHasElements.Delimiter := ',';
slHasElements.StrictDelimiter := true;
slFound := TStringList.Create;
OptionsForm;
if findMode = 0 then begin
Result := 1;
end else
if findRecords = '' then begin
AddMessage('No records selected.');
Result := 1;
end;
if Result <> 0 then
CleanUp;
end;
//===========================================================================
function Process(e: IInterface): Integer;
var
i: integer;
matched: boolean;
begin
if Pos(Signature(e), findRecords) = 0 then
Exit;
for i := 0 to Pred(slHasElements.Count) do
if ElementExists(e, slHasElements[i]) then begin
matched := True;
Break;
end;
if matched then
if findMode = 1 then
slFound.Add(Name(GetFile(e)) + ' - ' + Name(e))
else
if findMode = 2 then begin
JumpTo(e, True);
Result := 1;
CleanUp;
Exit;
end;
end;
//===========================================================================
function Finalize: Integer;
begin
if slFound.Count > 0 then begin
if MessageDlg(Format('Found %d records. Show them in messages?', [slFound.Count]), mtConfirmation, [mbYes, mbCancel], 0) = mrYes then
AddMessage(slFound.Text);
end else
AddMessage('No matching records found.');
CleanUp;
end;
end. |
{$include kode.inc}
unit kode_widget_image;
//----------------------------------------------------------------------
interface
//----------------------------------------------------------------------
uses
kode_bitmap,
kode_canvas,
kode_color,
kode_flags,
kode_rect,
kode_surface,
kode_widget;
type
KWidget_Image = class(KWidget)
protected
FBitmap : KBitmap;
FSurface : KSurface;
FStretch : Boolean;
public
property _stretch : Boolean read FStretch write FStretch;
public
constructor create(ARect:KRect; ABitmap:KBitmap; AStretch:Boolean=true; AAlignment:LongWord=kwa_none);
constructor create(ARect:KRect; ASurface:KSurface; AStretch:Boolean=true; AAlignment:LongWord=kwa_none);
destructor destroy; override;
public
procedure on_paint(ACanvas:KCanvas; ARect:KRect; AMode:LongWord=0); override;
end;
//----------------------------------------------------------------------
implementation
//----------------------------------------------------------------------
constructor KWidget_Image.create(ARect:KRect; ABitmap:KBitmap; AStretch:Boolean=true; AAlignment:LongWord=kwa_none);
begin
inherited create(ARect,AAlignment);
FName := 'KWidget_Image';
FBitmap := ABitmap;
FSurface := KSurface.create(ABitmap);
FStretch := AStretch;
end;
//----------
constructor KWidget_Image.create(ARect:KRect; ASurface:KSurface; AStretch:Boolean=true; AAlignment:LongWord=kwa_none);
begin
inherited create(ARect,AAlignment);
FName := 'KWidget_Bitmap';
FBitmap := nil;
FSurface := ASurface; //KSurface.create(ABitmap);
FStretch := AStretch;
end;
//----------
destructor KWidget_Image.destroy;
begin
if Assigned(FBitmap) then FSurface.destroy;
inherited;
end;
//----------
procedure KWidget_Image.on_paint(ACanvas:KCanvas; ARect:KRect; AMode:LongWord=0);
begin
if FStretch then
ACanvas.stretchSurface(FRect.x,FRect.y,FRect.w,FRect.h,FSurface,0,0,FSurface._width,FSurface._height)
else
ACanvas.drawSurface(FRect.x,FRect.y,FSurface,0,0,FSurface._width,FSurface._height);
//ACanvas.flexSurface(FRect,FSurface,0{kfm_tile},10,20,10,10);
inherited;
end;
//----------------------------------------------------------------------
end.
|
unit DtObj;
interface
type
HCkDtObj = Pointer;
HCkString = Pointer;
function CkDtObj_Create: HCkDtObj; stdcall;
procedure CkDtObj_Dispose(handle: HCkDtObj); stdcall;
function CkDtObj_getDay(objHandle: HCkDtObj): Integer; stdcall;
procedure CkDtObj_putDay(objHandle: HCkDtObj; newPropVal: Integer); stdcall;
procedure CkDtObj_getDebugLogFilePath(objHandle: HCkDtObj; outPropVal: HCkString); stdcall;
procedure CkDtObj_putDebugLogFilePath(objHandle: HCkDtObj; newPropVal: PWideChar); stdcall;
function CkDtObj__debugLogFilePath(objHandle: HCkDtObj): PWideChar; stdcall;
function CkDtObj_getHour(objHandle: HCkDtObj): Integer; stdcall;
procedure CkDtObj_putHour(objHandle: HCkDtObj; newPropVal: Integer); stdcall;
procedure CkDtObj_getLastErrorHtml(objHandle: HCkDtObj; outPropVal: HCkString); stdcall;
function CkDtObj__lastErrorHtml(objHandle: HCkDtObj): PWideChar; stdcall;
procedure CkDtObj_getLastErrorText(objHandle: HCkDtObj; outPropVal: HCkString); stdcall;
function CkDtObj__lastErrorText(objHandle: HCkDtObj): PWideChar; stdcall;
procedure CkDtObj_getLastErrorXml(objHandle: HCkDtObj; outPropVal: HCkString); stdcall;
function CkDtObj__lastErrorXml(objHandle: HCkDtObj): PWideChar; stdcall;
function CkDtObj_getLastMethodSuccess(objHandle: HCkDtObj): wordbool; stdcall;
procedure CkDtObj_putLastMethodSuccess(objHandle: HCkDtObj; newPropVal: wordbool); stdcall;
function CkDtObj_getMinute(objHandle: HCkDtObj): Integer; stdcall;
procedure CkDtObj_putMinute(objHandle: HCkDtObj; newPropVal: Integer); stdcall;
function CkDtObj_getMonth(objHandle: HCkDtObj): Integer; stdcall;
procedure CkDtObj_putMonth(objHandle: HCkDtObj; newPropVal: Integer); stdcall;
function CkDtObj_getSecond(objHandle: HCkDtObj): Integer; stdcall;
procedure CkDtObj_putSecond(objHandle: HCkDtObj; newPropVal: Integer); stdcall;
function CkDtObj_getStructTmMonth(objHandle: HCkDtObj): Integer; stdcall;
procedure CkDtObj_putStructTmMonth(objHandle: HCkDtObj; newPropVal: Integer); stdcall;
function CkDtObj_getStructTmYear(objHandle: HCkDtObj): Integer; stdcall;
procedure CkDtObj_putStructTmYear(objHandle: HCkDtObj; newPropVal: Integer); stdcall;
function CkDtObj_getUtc(objHandle: HCkDtObj): wordbool; stdcall;
procedure CkDtObj_putUtc(objHandle: HCkDtObj; newPropVal: wordbool); stdcall;
function CkDtObj_getVerboseLogging(objHandle: HCkDtObj): wordbool; stdcall;
procedure CkDtObj_putVerboseLogging(objHandle: HCkDtObj; newPropVal: wordbool); stdcall;
procedure CkDtObj_getVersion(objHandle: HCkDtObj; outPropVal: HCkString); stdcall;
function CkDtObj__version(objHandle: HCkDtObj): PWideChar; stdcall;
function CkDtObj_getYear(objHandle: HCkDtObj): Integer; stdcall;
procedure CkDtObj_putYear(objHandle: HCkDtObj; newPropVal: Integer); stdcall;
procedure CkDtObj_DeSerialize(objHandle: HCkDtObj; serializedDtObj: PWideChar); stdcall;
function CkDtObj_SaveLastError(objHandle: HCkDtObj; path: PWideChar): wordbool; stdcall;
function CkDtObj_Serialize(objHandle: HCkDtObj; outStr: HCkString): wordbool; stdcall;
function CkDtObj__serialize(objHandle: HCkDtObj): PWideChar; stdcall;
implementation
{$Include chilkatDllPath.inc}
function CkDtObj_Create; external DLLName;
procedure CkDtObj_Dispose; external DLLName;
function CkDtObj_getDay; external DLLName;
procedure CkDtObj_putDay; external DLLName;
procedure CkDtObj_getDebugLogFilePath; external DLLName;
procedure CkDtObj_putDebugLogFilePath; external DLLName;
function CkDtObj__debugLogFilePath; external DLLName;
function CkDtObj_getHour; external DLLName;
procedure CkDtObj_putHour; external DLLName;
procedure CkDtObj_getLastErrorHtml; external DLLName;
function CkDtObj__lastErrorHtml; external DLLName;
procedure CkDtObj_getLastErrorText; external DLLName;
function CkDtObj__lastErrorText; external DLLName;
procedure CkDtObj_getLastErrorXml; external DLLName;
function CkDtObj__lastErrorXml; external DLLName;
function CkDtObj_getLastMethodSuccess; external DLLName;
procedure CkDtObj_putLastMethodSuccess; external DLLName;
function CkDtObj_getMinute; external DLLName;
procedure CkDtObj_putMinute; external DLLName;
function CkDtObj_getMonth; external DLLName;
procedure CkDtObj_putMonth; external DLLName;
function CkDtObj_getSecond; external DLLName;
procedure CkDtObj_putSecond; external DLLName;
function CkDtObj_getStructTmMonth; external DLLName;
procedure CkDtObj_putStructTmMonth; external DLLName;
function CkDtObj_getStructTmYear; external DLLName;
procedure CkDtObj_putStructTmYear; external DLLName;
function CkDtObj_getUtc; external DLLName;
procedure CkDtObj_putUtc; external DLLName;
function CkDtObj_getVerboseLogging; external DLLName;
procedure CkDtObj_putVerboseLogging; external DLLName;
procedure CkDtObj_getVersion; external DLLName;
function CkDtObj__version; external DLLName;
function CkDtObj_getYear; external DLLName;
procedure CkDtObj_putYear; external DLLName;
procedure CkDtObj_DeSerialize; external DLLName;
function CkDtObj_SaveLastError; external DLLName;
function CkDtObj_Serialize; external DLLName;
function CkDtObj__serialize; external DLLName;
end.
|
unit UNumToVoice;
interface
uses UNumToText, MPlayer, classes, Windows, dialogs, forms, SysUtils;
Type TNumToVoice = class(TNumToText)
private mPlayer:TMediaPlayer;
playList:TStrings;//List of files to be played. Each entry contains several files separated by * mark.
protected procedure validate(num:integer);override;
protected function THOUSANDS:string;override;
protected function THOUSANDS_AND:string;override;
protected function CTens:TArrString2to9;override;
protected function CTensAnd:TArrString2to9;override;
protected function CFigures:TArrString0to19;override;
protected function CHundreds:TArrString1to9;override;
protected function CHundredsAnd:TArrString1to9;override;
protected function CDivider:string;override;
public procedure playVoiceStr(filesStr:string;mutex:Cardinal);
public constructor create(aHandle:HWND);reintroduce;
public destructor destroy();override;
end;
implementation
uses Controls, UVoicePlayerThread, uspeech;
function TNumToVoice.THOUSANDS: string;
begin
result:='0.wav';//not supported.
end;
function TNumToVoice.THOUSANDS_AND: string;
begin
result:='0.wav';//not supported.
end;
function TNumToVoice.CTens: TArrString2to9;
const ARR: TArrString2to9 = ('20.wav','30.wav','40.wav','50.wav','60.wav','70.wav',
'80.wav','90.wav');
begin
result:=ARR;
end;
function TNumToVoice.CTensAnd: TArrString2to9;
const ARR: TArrString2to9 = ('20_v.wav','30_v.wav','40_v.wav','50_v.wav','60_v.wav',
'70_v.wav','80_v.wav','90_v.wav');
begin
result:=ARR;
end;
function TNumToVoice.CFigures: TArrString0to19;
const ARR: TArrString0to19 = ('0.wav','1.wav','2.wav','3.wav','4.wav','5.wav',
'6.wav','7.wav','8.wav','9.wav','10.wav','11.wav','12.wav','13.wav',
'14.wav','15.wav','16.wav','17.wav','18.wav','19.wav');
begin
result:=ARR;
end;
function TNumToVoice.CHundreds: TArrString1to9;
const ARR: TArrString1to9 = ('100.wav','200.mp3','300.mp3','400.mp3','500.mp3',
'600.mp3','700.mp3','800.mp3', '900.mp3');
begin
result:=ARR;
end;
function TNumToVoice.CHundredsAnd: TArrString1to9;
const ARR: TArrString1to9 = ('100_v.wav','200_v.mp3','300_v.mp3','400_v.mp3',
'500_v.mp3','600_v.mp3','700_v.mp3','800_v.mp3', '900_v.mp3');
begin
result:=ARR;
end;
function TNumToVoice.CDivider: string;
begin
result:='*';
end;
procedure TNumToVoice.playVoiceStr(filesStr: string;mutex:Cardinal);
var t:TVoicePlayerThread;
begin
playList.Add(filesStr);
t:=TVoicePlayerThread.create(playList, mPlayer, mutex);
t.Resume;
end;
constructor TNumToVoice.create(aHandle:HWND);
begin
inherited create();
playList:=TStringList.Create;
mPlayer:=TMediaPlayer.CreateParented(aHandle);
mPlayer.Visible:=false;
mPlayer.FileName:=IncludeTrailingPathDelimiter(ExtractFilePath(Application.ExeName))+'numVoices\0.wav';
mPlayer.Open;
end;
destructor TNumToVoice.destroy;
begin
playList.Free;
mPlayer.Free();
inherited;
end;
procedure TNumToVoice.validate(num: integer);
begin
if ((num<0)or(num>999)) then
raise Exception.Create('عدد بايستي بين 1 تا 999 باشد');
end;
end.
|
unit TextEditor.Print.Preview;
{$M+}
interface
uses
Winapi.Messages, Winapi.Windows, System.Classes, System.SysUtils, System.UITypes, Vcl.Controls, Vcl.Forms,
Vcl.Graphics, TextEditor.Print
{$IFDEF ALPHASKINS}, acSBUtils, sCommonData{$ENDIF};
type
TTextEditorPreviewPageEvent = procedure(ASender: TObject; APageNumber: Integer) of object;
TTextEditorPreviewScale = (pscWholePage, pscPageWidth, pscUserScaled);
TTextEditorPrintPreview = class(TCustomControl)
strict private
FBorderStyle: TBorderStyle;
FBuffer: TBitmap;
{$IFDEF ALPHASKINS}
FSkinData: TsScrollWndData;
{$ENDIF}
FEditorPrint: TTextEditorPrint;
FOnPreviewPage: TTextEditorPreviewPageEvent;
FOnScaleChange: TNotifyEvent;
FPageBackgroundColor: TColor;
FPageNumber: Integer;
FPageSize: TPoint;
FScaleMode: TTextEditorPreviewScale;
FScalePercent: Integer;
FScrollPosition: TPoint;
{$IFDEF ALPHASKINS}
FScrollWnd: TacScrollWnd;
{$ENDIF}
FShowScrollHint: Boolean;
FWheelAccumulator: Integer;
FVirtualOffset: TPoint;
FVirtualSize: TPoint;
function GetEditorPrint: TTextEditorPrint;
function GetPageCount: Integer;
function GetPageHeight100Percent: Integer;
function GetPageHeightFromWidth(AWidth: Integer): Integer;
function GetPageWidth100Percent: Integer;
function GetPageWidthFromHeight(AHeight: Integer): Integer;
procedure PaintPaper(const ACanvas: TCanvas);
procedure SetBorderStyle(AValue: TBorderStyle);
procedure SetEditorPrint(AValue: TTextEditorPrint);
procedure SetPageBackgroundColor(AValue: TColor);
procedure SetScaleMode(AValue: TTextEditorPreviewScale);
procedure SetScalePercent(AValue: Integer);
procedure WMEraseBkgnd(var AMessage: TWMEraseBkgnd); message WM_ERASEBKGND;
procedure WMGetDlgCode(var AMessage: TWMGetDlgCode); message WM_GETDLGCODE;
procedure WMHScroll(var AMessage: TWMHScroll); message WM_HSCROLL;
procedure WMMouseWheel(var Message: TWMMouseWheel); message WM_MOUSEWHEEL;
procedure WMPaint(var AMessage: TWMPaint); message WM_PAINT;
procedure WMSize(var AMessage: TWMSize); message WM_SIZE;
procedure WMVScroll(var AMessage: TWMVScroll); message WM_VSCROLL;
protected
procedure CreateParams(var AParams: TCreateParams); override;
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
//procedure PaintWindow(DC: HDC); override;
procedure ScrollHorizontallyFor(AValue: Integer);
procedure ScrollHorizontallyTo(AValue: Integer); virtual;
procedure ScrollVerticallyFor(AValue: Integer);
procedure ScrollVerticallyTo(AValue: Integer); virtual;
procedure SizeChanged; virtual;
procedure UpdateScrollbars; virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
function CanFocus: Boolean; override;
procedure AfterConstruction; override;
procedure FirstPage;
procedure LastPage;
procedure Loaded; override;
procedure NextPage;
procedure Paint; override;
procedure PreviousPage;
procedure Print;
procedure UpdatePreview;
{$IFDEF ALPHASKINS}
procedure WndProc(var AMessage: TMessage); override;
{$ENDIF}
property PageCount: Integer read GetPageCount;
property PageNumber: Integer read FPageNumber;
published
property Align default alClient;
property BorderStyle: TBorderStyle read FBorderStyle write SetBorderStyle default bsSingle;
property Color default TColors.SysAppWorkspace;
property Cursor;
property EditorPrint: TTextEditorPrint read GetEditorPrint write SetEditorPrint;
property OnClick;
property OnMouseDown;
property OnMouseUp;
property OnPreviewPage: TTextEditorPreviewPageEvent read FOnPreviewPage write FOnPreviewPage;
property OnScaleChange: TNotifyEvent read FOnScaleChange write FOnScaleChange;
property PageBackgroundColor: TColor read FPageBackgroundColor write SetPageBackgroundColor default TColors.White;
property PopupMenu;
property ScaleMode: TTextEditorPreviewScale read FScaleMode write SetScaleMode default pscUserScaled;
property ScalePercent: Integer read FScalePercent write SetScalePercent default 100;
property ShowScrollHint: Boolean read FShowScrollHint write FShowScrollHint default True;
{$IFDEF ALPHASKINS}
property SkinData: TsScrollWndData read FSkinData write FSkinData;
{$ENDIF}
property Visible default True;
end;
implementation
uses
System.Types
{$IFDEF ALPHASKINS}, Winapi.CommCtrl, sConst, sMessages, sStyleSimply, sVCLUtils{$ENDIF};
const
MARGIN_WIDTH_LEFT_AND_RIGHT = 12;
MARGIN_HEIGHT_TOP_AND_BOTTOM = 12;
{ TTextEditorPrintPreview }
constructor TTextEditorPrintPreview.Create(AOwner: TComponent);
begin
{$IFDEF ALPHASKINS}
FSkinData := TsScrollWndData.Create(Self, True);
FSkinData.COC := COC_TsMemo;
{$ENDIF}
inherited;
Align := alClient;
ControlStyle := ControlStyle + [csOpaque, csNeedsBorderPaint];
FBorderStyle := bsSingle;
FScaleMode := pscUserScaled;
FScalePercent := 100;
FPageBackgroundColor := TColors.White;
Width := 200;
Height := 120;
ParentColor := False;
Color := TColors.SysAppWorkspace;
FPageNumber := 1;
FShowScrollHint := True;
FWheelAccumulator := 0;
Visible := True;
FBuffer := TBitmap.Create;
end;
procedure TTextEditorPrintPreview.AfterConstruction;
begin
inherited AfterConstruction;
{$IFDEF ALPHASKINS}
if HandleAllocated then
RefreshEditScrolls(SkinData, FScrollWnd);
UpdateData(FSkinData);
{$ENDIF}
end;
procedure TTextEditorPrintPreview.Loaded;
begin
inherited Loaded;
{$IFDEF ALPHASKINS}
FSkinData.Loaded(False);
RefreshEditScrolls(SkinData, FScrollWnd);
{$ENDIF}
end;
destructor TTextEditorPrintPreview.Destroy;
begin
FBuffer.Free;
{$IFDEF ALPHASKINS}
if Assigned(FScrollWnd) then
begin
FScrollWnd.Free;
FScrollWnd := nil;
end;
if Assigned(FSkinData) then
begin
FSkinData.Free;
FSkinData := nil;
end;
{$ENDIF}
inherited;
end;
procedure TTextEditorPrintPreview.CreateParams(var AParams: TCreateParams);
const
BorderStyles: array [TBorderStyle] of Cardinal = (0, WS_BORDER);
begin
inherited;
with AParams do
begin
Style := Style or WS_HSCROLL or WS_VSCROLL or BorderStyles[FBorderStyle] or WS_CLIPCHILDREN;
if NewStyleControls and Ctl3D and (FBorderStyle = bsSingle) then
begin
Style := Style and not WS_BORDER;
ExStyle := ExStyle or WS_EX_CLIENTEDGE;
end;
end;
end;
function TTextEditorPrintPreview.GetPageHeightFromWidth(AWidth: Integer): Integer;
begin
if Assigned(FEditorPrint) then
with FEditorPrint.PrinterInfo do
Result := MulDiv(AWidth, PhysicalHeight, PhysicalWidth)
else
Result := MulDiv(AWidth, 141, 100);
end;
function TTextEditorPrintPreview.GetPageWidthFromHeight(AHeight: Integer): Integer;
begin
if Assigned(FEditorPrint) then
with FEditorPrint.PrinterInfo do
Result := MulDiv(AHeight, PhysicalWidth, PhysicalHeight)
else
Result := MulDiv(AHeight, 100, 141);
end;
function TTextEditorPrintPreview.GetPageHeight100Percent: Integer;
var
LHandle: HDC;
LScreenDPI: Integer;
begin
Result := 0;
LHandle := GetDC(0);
LScreenDPI := GetDeviceCaps(LHandle, LogPixelsY);
ReleaseDC(0, LHandle);
if Assigned(FEditorPrint) then
with FEditorPrint.PrinterInfo do
Result := MulDiv(PhysicalHeight, LScreenDPI, YPixPerInch);
end;
function TTextEditorPrintPreview.GetPageWidth100Percent: Integer;
var
LHandle: HDC;
LScreenDPI: Integer;
begin
Result := 0;
LHandle := GetDC(0);
LScreenDPI := GetDeviceCaps(LHandle, LogPixelsX);
ReleaseDC(0, LHandle);
if Assigned(FEditorPrint) then
with FEditorPrint.PrinterInfo do
Result := MulDiv(PhysicalWidth, LScreenDPI, XPixPerInch);
end;
procedure TTextEditorPrintPreview.Notification(AComponent: TComponent; Operation: TOperation);
begin
inherited;
if (Operation = opRemove) and (AComponent = FEditorPrint) then
EditorPrint := nil;
end;
procedure TTextEditorPrintPreview.PaintPaper(const ACanvas: TCanvas);
var
LClipRect, LPaperRect: TRect;
LPaperRGN: HRGN;
begin
with ACanvas do
begin
LClipRect := ClipRect;
if IsRectEmpty(LClipRect) then
Exit;
Brush.Color := Self.Color;
Brush.Style := bsSolid;
Pen.Color := TColors.Black;
Pen.Width := 1;
Pen.Style := psSolid;
if (csDesigning in ComponentState) or not Assigned(FEditorPrint) then
begin
Winapi.Windows.ExtTextOut(Handle, 0, 0, ETO_OPAQUE, LClipRect, '', 0, nil);
Brush.Color := FPageBackgroundColor;
Rectangle(MARGIN_WIDTH_LEFT_AND_RIGHT, MARGIN_HEIGHT_TOP_AND_BOTTOM, MARGIN_WIDTH_LEFT_AND_RIGHT + 30,
MARGIN_HEIGHT_TOP_AND_BOTTOM + 43);
Exit;
end;
LPaperRect.Left := FVirtualOffset.X + FScrollPosition.X;
if ScaleMode = pscWholePage then
LPaperRect.Top := FVirtualOffset.Y
else
LPaperRect.Top := FVirtualOffset.Y + FScrollPosition.Y;
LPaperRect.Right := LPaperRect.Left + FPageSize.X;
LPaperRect.Bottom := LPaperRect.Top + FPageSize.Y;
LPaperRGN := CreateRectRgn(LPaperRect.Left, LPaperRect.Top, LPaperRect.Right + 1, LPaperRect.Bottom + 1);
if NULLREGION <> ExtSelectClipRgn(Handle, LPaperRGN, RGN_DIFF) then
Winapi.Windows.ExtTextOut(Handle, 0, 0, ETO_OPAQUE, LClipRect, '', 0, nil);
SelectClipRgn(Handle, LPaperRGN);
Brush.Color := FPageBackgroundColor;
Rectangle(LPaperRect.Left, LPaperRect.Top, LPaperRect.Right + 1, LPaperRect.Bottom + 1);
DeleteObject(LPaperRGN);
end;
end;
procedure TTextEditorPrintPreview.Paint;
var
LOriginalScreenPoint: TPoint;
LOldMode: Integer;
begin
PaintPaper(Canvas);
if (csDesigning in ComponentState) or not Assigned(FEditorPrint) then
Exit;
LOldMode := SetMapMode(Canvas.Handle, MM_ANISOTROPIC);
try
SetWindowExtEx(Canvas.Handle, FEditorPrint.PrinterInfo.PhysicalWidth, FEditorPrint.PrinterInfo.PhysicalHeight, nil);
SetViewPortExtEx(Canvas.Handle, FPageSize.X, FPageSize.Y, nil);
LOriginalScreenPoint.X := MulDiv(FEditorPrint.PrinterInfo.LeftMargin, FPageSize.X, FEditorPrint.PrinterInfo.PhysicalWidth);
LOriginalScreenPoint.Y := MulDiv(FEditorPrint.PrinterInfo.TopMargin, FPageSize.Y, FEditorPrint.PrinterInfo.PhysicalHeight);
Inc(LOriginalScreenPoint.X, FVirtualOffset.X + FScrollPosition.X);
if ScaleMode = pscWholePage then
Inc(LOriginalScreenPoint.Y, FVirtualOffset.Y)
else
Inc(LOriginalScreenPoint.Y, FVirtualOffset.Y + FScrollPosition.Y);
SetViewPortOrgEx(Canvas.Handle, LOriginalScreenPoint.X, LOriginalScreenPoint.Y, nil);
IntersectClipRect(Canvas.Handle, 0, 0, FEditorPrint.PrinterInfo.PrintableWidth, FEditorPrint.PrinterInfo.PrintableHeight);
FEditorPrint.PrintToCanvas(Canvas, FPageNumber);
SetWindowExtEx(Canvas.Handle, 0, 0, nil);
SetViewPortExtEx(Canvas.Handle, 0, 0, nil);
SetViewPortOrgEx(Canvas.Handle, 0, 0, nil);
finally
SetMapMode(Canvas.Handle, LOldMode);
end;
end;
procedure TTextEditorPrintPreview.ScrollHorizontallyFor(AValue: Integer);
begin
ScrollHorizontallyTo(FScrollPosition.X + AValue);
end;
procedure TTextEditorPrintPreview.ScrollHorizontallyTo(AValue: Integer);
var
LWidth, LPosition: Integer;
begin
LWidth := ClientWidth;
LPosition := LWidth - FVirtualSize.X;
if AValue < LPosition then
AValue := LPosition;
if AValue > 0 then
AValue := 0;
if FScrollPosition.X <> AValue then
begin
FScrollPosition.X := AValue;
UpdateScrollbars;
Invalidate;
end;
end;
procedure TTextEditorPrintPreview.ScrollVerticallyFor(AValue: Integer);
begin
ScrollVerticallyTo(FScrollPosition.Y + AValue);
end;
procedure TTextEditorPrintPreview.ScrollVerticallyTo(AValue: Integer);
var
LHeight, LPosition: Integer;
begin
LHeight := ClientHeight;
LPosition := LHeight - FVirtualSize.Y;
if AValue < LPosition then
AValue := LPosition;
if AValue > 0 then
AValue := 0;
if FScrollPosition.Y <> AValue then
begin
FScrollPosition.Y := AValue;
UpdateScrollbars;
Invalidate;
end;
end;
procedure TTextEditorPrintPreview.SizeChanged;
var
LWidth: Integer;
begin
if not (HandleAllocated and Assigned(FEditorPrint)) then
Exit;
case FScaleMode of
pscWholePage:
begin
FPageSize.X := ClientWidth - 2 * MARGIN_WIDTH_LEFT_AND_RIGHT;
FPageSize.Y := ClientHeight - 2 * MARGIN_HEIGHT_TOP_AND_BOTTOM;
LWidth := GetPageWidthFromHeight(FPageSize.Y);
if LWidth < FPageSize.X then
FPageSize.X := LWidth
else
FPageSize.Y := GetPageHeightFromWidth(FPageSize.X);
end;
pscPageWidth:
begin
FPageSize.X := ClientWidth - 2 * MARGIN_WIDTH_LEFT_AND_RIGHT;
FPageSize.Y := GetPageHeightFromWidth(FPageSize.X);
end;
pscUserScaled:
begin
FPageSize.X := MulDiv(GetPageWidth100Percent, FScalePercent, 100);
FPageSize.Y := MulDiv(GetPageHeight100Percent, FScalePercent, 100);
end;
end;
FVirtualSize.X := FPageSize.X + 2 * MARGIN_WIDTH_LEFT_AND_RIGHT;
FVirtualSize.Y := FPageSize.Y + 2 * MARGIN_HEIGHT_TOP_AND_BOTTOM;
FVirtualOffset.X := MARGIN_WIDTH_LEFT_AND_RIGHT;
if FVirtualSize.X < ClientWidth then
Inc(FVirtualOffset.X, (ClientWidth - FVirtualSize.X) div 2);
FVirtualOffset.Y := MARGIN_HEIGHT_TOP_AND_BOTTOM;
if FVirtualSize.Y < ClientHeight then
Inc(FVirtualOffset.Y, (ClientHeight - FVirtualSize.Y) div 2);
UpdateScrollbars;
FScrollPosition := Point(0, 0);
end;
procedure TTextEditorPrintPreview.UpdateScrollbars;
var
LScrollInfo: TScrollInfo;
begin
FillChar(LScrollInfo, SizeOf(TScrollInfo), 0);
LScrollInfo.cbSize := SizeOf(TScrollInfo);
LScrollInfo.fMask := SIF_ALL;
case FScaleMode of
pscWholePage:
begin
ShowScrollbar(Handle, SB_HORZ, False);
LScrollInfo.fMask := LScrollInfo.fMask or SIF_DISABLENOSCROLL;
LScrollInfo.nMin := 1;
if Assigned(FEditorPrint) then
begin
LScrollInfo.nMax := FEditorPrint.PageCount;
LScrollInfo.nPos := FPageNumber;
end
else
begin
LScrollInfo.nMax := 1;
LScrollInfo.nPos := 1;
end;
LScrollInfo.nPage := 1;
SetScrollInfo(Handle, SB_VERT, LScrollInfo, True);
end;
pscPageWidth:
begin
ShowScrollbar(Handle, SB_HORZ, False);
LScrollInfo.fMask := LScrollInfo.fMask or SIF_DISABLENOSCROLL;
LScrollInfo.nMax := FVirtualSize.Y;
LScrollInfo.nPos := -FScrollPosition.Y;
LScrollInfo.nPage := ClientHeight;
SetScrollInfo(Handle, SB_VERT, LScrollInfo, True);
end;
pscUserScaled:
begin
ShowScrollbar(Handle, SB_HORZ, True);
ShowScrollbar(Handle, SB_VERT, True);
LScrollInfo.fMask := LScrollInfo.fMask or SIF_DISABLENOSCROLL;
LScrollInfo.nMax := FVirtualSize.X;
LScrollInfo.nPos := -FScrollPosition.X;
LScrollInfo.nPage := ClientWidth;
SetScrollInfo(Handle, SB_HORZ, LScrollInfo, True);
LScrollInfo.nMax := FVirtualSize.Y;
LScrollInfo.nPos := -FScrollPosition.Y;
LScrollInfo.nPage := ClientHeight;
SetScrollInfo(Handle, SB_VERT, LScrollInfo, True);
end;
end;
end;
procedure TTextEditorPrintPreview.SetBorderStyle(AValue: TBorderStyle);
begin
if FBorderStyle <> AValue then
begin
FBorderStyle := AValue;
RecreateWnd;
end;
end;
procedure TTextEditorPrintPreview.SetPageBackgroundColor(AValue: TColor);
begin
if FPageBackgroundColor <> AValue then
begin
FPageBackgroundColor := AValue;
Invalidate;
end;
end;
function TTextEditorPrintPreview.GetEditorPrint: TTextEditorPrint;
begin
if not Assigned(FEditorPrint) then
FEditorPrint := TTextEditorPrint.Create(Self);
Result := FEditorPrint
end;
procedure TTextEditorPrintPreview.SetEditorPrint(AValue: TTextEditorPrint);
begin
if FEditorPrint <> AValue then
begin
FEditorPrint := AValue;
if Assigned(FEditorPrint) then
FEditorPrint.FreeNotification(Self);
end;
end;
procedure TTextEditorPrintPreview.SetScaleMode(AValue: TTextEditorPreviewScale);
begin
if FScaleMode <> AValue then
begin
FScaleMode := AValue;
FScrollPosition := Point(0, 0);
SizeChanged;
UpdateScrollbars;
if Assigned(FOnScaleChange) then
FOnScaleChange(Self);
Invalidate;
end;
end;
procedure TTextEditorPrintPreview.SetScalePercent(AValue: Integer);
begin
if FScalePercent <> AValue then
begin
FScaleMode := pscUserScaled;
FScrollPosition := Point(0, 0);
FScalePercent := AValue;
SizeChanged;
UpdateScrollbars;
Invalidate;
end
else
ScaleMode := pscUserScaled;
if Assigned(FOnScaleChange) then
FOnScaleChange(Self);
end;
procedure TTextEditorPrintPreview.WMEraseBkgnd(var AMessage: TWMEraseBkgnd);
begin
AMessage.Result := 1;
end;
procedure TTextEditorPrintPreview.WMHScroll(var AMessage: TWMHScroll);
var
LWidth: Integer;
begin
AMessage.Result := 0;
if FScaleMode <> pscWholePage then
begin
LWidth := ClientWidth;
case AMessage.ScrollCode of
SB_TOP:
ScrollHorizontallyTo(0);
SB_BOTTOM:
ScrollHorizontallyTo(-FVirtualSize.X);
SB_LINEDOWN:
ScrollHorizontallyFor(-(LWidth div 10));
SB_LINEUP:
ScrollHorizontallyFor(LWidth div 10);
SB_PAGEDOWN:
ScrollHorizontallyFor(-(LWidth div 2));
SB_PAGEUP:
ScrollHorizontallyFor(LWidth div 2);
SB_THUMBPOSITION, SB_THUMBTRACK:
begin
{$IFDEF ALPHASKINS}
Skindata.BeginUpdate;
{$ENDIF}
ScrollHorizontallyTo(-AMessage.Pos);
{$IFDEF ALPHASKINS}
Skindata.EndUpdate(True);
{$ENDIF}
end;
end;
end;
end;
procedure TTextEditorPrintPreview.WMSize(var AMessage: TWMSize);
begin
inherited;
if not (csDesigning in ComponentState) then
SizeChanged;
end;
var
GScrollHintWnd: THintWindow;
function GetScrollHint: THintWindow;
begin
if not Assigned(GScrollHintWnd) then
begin
GScrollHintWnd := HintWindowClass.Create(Application);
GScrollHintWnd.Visible := False;
end;
Result := GScrollHintWnd;
end;
procedure TTextEditorPrintPreview.WMVScroll(var AMessage: TWMVScroll);
begin
AMessage.Result := 0;
case AMessage.ScrollCode of
SB_TOP:
ScrollVerticallyTo(0);
SB_BOTTOM:
ScrollVerticallyTo(-FVirtualSize.Y);
SB_LINEDOWN:
ScrollVerticallyFor(-(ClientHeight div 10));
SB_LINEUP:
ScrollVerticallyFor(ClientHeight div 10);
SB_PAGEDOWN:
begin
FPageNumber := FPageNumber + 1;
if FPageNumber > FEditorPrint.PageCount then
FPageNumber := FEditorPrint.PageCount;
Invalidate;
end;
SB_PAGEUP:
begin
FPageNumber := FPageNumber - 1;
if FPageNumber < 1 then
FPageNumber := 1;
Invalidate;
end;
SB_THUMBPOSITION, SB_THUMBTRACK:
begin
{$IFDEF ALPHASKINS}
Skindata.BeginUpdate;
{$ENDIF}
ScrollVerticallyTo(-AMessage.Pos);
{$IFDEF ALPHASKINS}
Skindata.EndUpdate(True);
{$ENDIF}
end;
end;
end;
procedure TTextEditorPrintPreview.KeyDown(var Key: Word; Shift: TShiftState);
begin
case Key of
vkNext:
begin
FPageNumber := FPageNumber + 1;
if FPageNumber > FEditorPrint.PageCount then
FPageNumber := FEditorPrint.PageCount;
end;
vkPrior:
begin
FPageNumber := FPageNumber - 1;
if FPageNumber < 1 then
FPageNumber := 1;
end;
vkDown:
ScrollVerticallyFor(-(ClientHeight div 10));
vkUp:
ScrollVerticallyFor(ClientHeight div 10);
vkRight:
ScrollHorizontallyFor(-(ClientWidth div 10));
vkLeft:
ScrollHorizontallyFor(ClientWidth div 10);
end;
Invalidate;
end;
procedure TTextEditorPrintPreview.WMMouseWheel(var Message: TWMMouseWheel);
var
LCtrlPressed: Boolean;
procedure MouseWheelUp;
begin
if LCtrlPressed and (FPageNumber > 1) then
PreviousPage
else
ScrollVerticallyFor(WHEEL_DELTA);
end;
procedure MouseWheelDown;
begin
if LCtrlPressed and (FPageNumber < PageCount) then
NextPage
else
ScrollVerticallyFor(-WHEEL_DELTA);
end;
var
IsNegative: Boolean;
begin
LCtrlPressed := GetKeyState(vkControl) < 0;
Inc(FWheelAccumulator, message.WheelDelta);
while Abs(FWheelAccumulator) >= WHEEL_DELTA do
begin
IsNegative := FWheelAccumulator < 0;
FWheelAccumulator := Abs(FWheelAccumulator) - WHEEL_DELTA;
if IsNegative then
begin
if FWheelAccumulator <> 0 then
FWheelAccumulator := -FWheelAccumulator;
MouseWheelDown;
end
else
MouseWheelUp;
end;
end;
procedure TTextEditorPrintPreview.UpdatePreview;
var
LOldScale: Integer;
LOldMode: TTextEditorPreviewScale;
begin
LOldScale := ScalePercent;
LOldMode := ScaleMode;
ScalePercent := 100;
if Assigned(FEditorPrint) then
FEditorPrint.UpdatePages(Canvas);
SizeChanged;
Invalidate;
ScaleMode := LOldMode;
if ScaleMode = pscUserScaled then
ScalePercent := LOldScale;
if FPageNumber > FEditorPrint.PageCount then
FPageNumber := FEditorPrint.PageCount;
if Assigned(FOnPreviewPage) then
FOnPreviewPage(Self, FPageNumber);
UpdateScrollbars;
end;
procedure TTextEditorPrintPreview.FirstPage;
begin
FPageNumber := 1;
if Assigned(FOnPreviewPage) then
FOnPreviewPage(Self, FPageNumber);
Invalidate;
end;
procedure TTextEditorPrintPreview.LastPage;
begin
if Assigned(FEditorPrint) then
FPageNumber := FEditorPrint.PageCount;
if Assigned(FOnPreviewPage) then
FOnPreviewPage(Self, FPageNumber);
Invalidate;
end;
procedure TTextEditorPrintPreview.NextPage;
begin
FPageNumber := FPageNumber + 1;
if Assigned(FEditorPrint) and (FPageNumber > FEditorPrint.PageCount) then
FPageNumber := FEditorPrint.PageCount;
if Assigned(FOnPreviewPage) then
FOnPreviewPage(Self, FPageNumber);
Invalidate;
end;
procedure TTextEditorPrintPreview.PreviousPage;
begin
FPageNumber := FPageNumber - 1;
if Assigned(FEditorPrint) and (FPageNumber < 1) then
FPageNumber := 1;
if Assigned(FOnPreviewPage) then
FOnPreviewPage(Self, FPageNumber);
Invalidate;
end;
procedure TTextEditorPrintPreview.Print;
begin
if Assigned(FEditorPrint) then
begin
FEditorPrint.Print;
UpdatePreview;
end;
end;
function TTextEditorPrintPreview.GetPageCount: Integer;
begin
Result := EditorPrint.PageCount;
end;
{$IFDEF ALPHASKINS}
procedure TTextEditorPrintPreview.WndProc(var AMessage: TMessage);
const
ALT_KEY_DOWN = $20000000;
begin
{ Prevent Alt-Backspace from beeping }
if (AMessage.Msg = WM_SYSCHAR) and (AMessage.wParam = vkBack) and (AMessage.LParam and ALT_KEY_DOWN <> 0) then
AMessage.Msg := 0;
if AMessage.Msg = SM_ALPHACMD then
case AMessage.WParamHi of
AC_CTRLHANDLED:
begin
AMessage.Result := 1;
Exit;
end;
AC_GETAPPLICATION:
begin
AMessage.Result := LRESULT(Application);
Exit
end;
AC_REMOVESKIN:
if (ACUInt(AMessage.LParam) = ACUInt(SkinData.SkinManager)) and not (csDestroying in ComponentState) then
begin
if Assigned(FScrollWnd) then
begin
FreeAndNil(FScrollWnd);
RecreateWnd;
end;
Exit;
end;
AC_REFRESH:
if (ACUInt(AMessage.LParam) = ACUInt(SkinData.SkinManager)) and Visible then
begin
RefreshEditScrolls(SkinData, FScrollWnd);
CommonMessage(AMessage, FSkinData);
//Perform(WM_NCPAINT, 0, 0);
if HandleAllocated and Visible then
RedrawWindow(Handle, nil, 0, RDWA_REPAINT);
Exit;
end;
AC_SETNEWSKIN:
if (ACUInt(AMessage.LParam) = ACUInt(SkinData.SkinManager)) then
begin
CommonMessage(AMessage, FSkinData);
Exit;
end;
AC_GETDEFINDEX:
begin
if Assigned(FSkinData.SkinManager) then
AMessage.Result := FSkinData.SkinManager.SkinCommonInfo.Sections[ssEdit] + 1;
Exit;
end;
AC_ENDUPDATE:
Perform(CM_INVALIDATE, 0, 0);
end;
if not ControlIsReady(Self) or not Assigned(FSkinData) or not FSkinData.Skinned then
inherited
else
begin
if AMessage.Msg = SM_ALPHACMD then
case AMessage.WParamHi of
AC_ENDPARENTUPDATE:
if FSkinData.Updating then
begin
if not InUpdating(FSkinData, True) then
Perform(WM_NCPAINT, 0, 0);
Exit;
end;
end;
if CommonWndProc(AMessage, FSkinData) then
Exit;
inherited;
case AMessage.Msg of
TB_SETANCHORHIGHLIGHT, WM_SIZE:
Perform(WM_NCPAINT, 0, 0);
CM_SHOWINGCHANGED:
RefreshEditScrolls(SkinData, FScrollWnd);
CM_VISIBLECHANGED, CM_ENABLEDCHANGED, WM_SETFONT:
FSkinData.Invalidate;
end;
end;
end;
{$ENDIF}
function TTextEditorPrintPreview.CanFocus: Boolean;
begin
if csDesigning in ComponentState then
Result := False
else
Result := inherited CanFocus;
end;
procedure TTextEditorPrintPreview.WMGetDlgCode(var AMessage: TWMGetDlgCode);
begin
AMessage.Result := DLGC_WANTARROWS or DLGC_WANTCHARS;
end;
procedure TTextEditorPrintPreview.WMPaint(var AMessage: TWMPaint);
var
LDC, LCompatibleDC: HDC;
LCompatibleBitmap, LOldBitmap: HBITMAP;
LPaintStruct: TPaintStruct;
begin
if AMessage.DC <> 0 then
begin
if not (csCustomPaint in ControlState) and (ControlCount = 0) then
inherited
else
PaintHandler(AMessage);
end
else
begin
LDC := GetDC(0);
LCompatibleBitmap := CreateCompatibleBitmap(LDC, Width, Height);
ReleaseDC(0, LDC);
LCompatibleDC := CreateCompatibleDC(0);
LOldBitmap := SelectObject(LCompatibleDC, LCompatibleBitmap);
try
LDC := BeginPaint(Handle, LPaintStruct);
AMessage.DC := LCompatibleDC;
WMPaint(AMessage);
BitBlt(LDC, 0, 0, Width, Height, LCompatibleDC, 0, 0, SRCCOPY);
EndPaint(Handle, LPaintStruct);
finally
SelectObject(LCompatibleDC, LOldBitmap);
DeleteObject(LCompatibleBitmap);
DeleteDC(LCompatibleDC);
end;
end;
end;
end.
|
unit tpLabel; {Normal/Raised/Recessed label component; TLabel with methods to write the caption more easily.}
(*
Permission is hereby granted, on 24-Feb-2005, free of charge, to any person
obtaining a copy of this file (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.
Author of original version of this file: Michael Ax
*)
interface
uses
Forms, Dialogs, StdCtrls, SysUtils, Messages, Classes, Graphics, Controls,
Windows,
ucShell;
type
TTextStyle=(tsNone,tsRaised,tsRecessed);
TtpShellMode=(smNone,smOpen,smPrint);
TtpLabel=class(TLabel)
private
fShellMode: TtpShellMode;
fShellCommand: String;
fPosDepth: byte;
fNegDepth: byte;
FTextStyle:TTextStyle;
procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER;
procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
protected
procedure Paint; override;
procedure SetTextStyle(Value:TTextStyle);
function GetInteger: Longint;
procedure SetInteger(Value:Longint);
public
constructor Create(AOwner: TComponent); Override;
procedure Click; override;
procedure Inc;
procedure Dec;
procedure DoDrawText(var Rect: TRect;
Flags:{$IFDEF VER110}Word{$ELSE}LongInt{$ENDIF}); //Borland C++Builder 3.0
override;
published
property ShellMode: TtpShellMode read fShellMode write fShellMode;
property ShellCommand: String read fShellCommand write fShellCommand;
property TextStyle : tTextStyle read fTextStyle write SetTextStyle default tsRecessed;
property AsInteger : Longint read GetInteger write SetInteger stored false;
property PosDepth: byte read fPosDepth write fPosDepth default 1;
property NegDepth: byte read fNegDepth write fNegDepth default 1;
end;
{------------------------------------------------------------------------------}
procedure Register;
implementation
{------------------------------------------------------------------------------}
constructor TtpLabel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
fTextStyle:=tsRecessed;
fPosDepth:=1;
fNegDepth:=1;
end;
procedure TtpLabel.SetTextStyle( Value : TTextStyle );
begin
if Value<>fTextStyle then begin
fTextStyle:=Value;
Invalidate;
end;
end;
procedure TtpLabel.DoDrawText(var Rect:TRect;
Flags:{$IFDEF VER110}Word{$ELSE}Longint{$ENDIF}); //cpb
var
Text : array[ 0..255 ] of Char;
TmpRect : TRect;
UpperColor : TColor;
LowerColor : TColor;
begin
GetTextBuf(Text, SizeOf(Text));
if ( Flags and DT_CALCRECT <> 0) and
( ( Text[0] = #0 ) or ShowAccelChar and
( Text[0] = '&' ) and
( Text[1] = #0 ) ) then
StrCopy(Text, ' ');
if not ShowAccelChar then
Flags := Flags or DT_NOPREFIX;
Canvas.Font := Font;
if FTextStyle = tsRecessed then begin
UpperColor := clBtnShadow;
LowerColor := clBtnHighlight;
end
else begin
UpperColor := clBtnHighlight;
LowerColor := clBtnShadow;
end;
if FTextStyle in [ tsRecessed, tsRaised ] then begin
TmpRect := Rect;
OffsetRect( TmpRect, fPosDepth, fPosDepth );
Canvas.Font.Color := LowerColor;
DrawText(Canvas.Handle, Text, StrLen(Text), TmpRect, Flags);
TmpRect := Rect;
OffsetRect( TmpRect, -fNegDepth, -fNegDepth );
Canvas.Font.Color := UpperColor;
DrawText(Canvas.Handle, Text, StrLen(Text), TmpRect, Flags);
end;
Canvas.Font.Color := Font.Color;
if not Enabled then
Canvas.Font.Color := clGrayText;
DrawText(Canvas.Handle, Text, StrLen(Text), Rect, Flags);
end;
procedure TtpLabel.Paint;
const
Alignments: array[TAlignment] of Word = (DT_LEFT, DT_RIGHT, DT_CENTER);
var
Rect: TRect;
begin
with Canvas do begin
if not Transparent then begin
Brush.Color := Self.Color;
Brush.Style := bsSolid;
FillRect(ClientRect);
end;
Brush.Style:=bsClear;
Rect:=ClientRect;
DoDrawText(Rect,(DT_EXPANDTABS or DT_WORDBREAK) or Alignments[Alignment]);
end;
end;
{------------------------------------------------------------------------------}
function TtpLabel.GetInteger: Longint;
begin
Result:=StrToIntDef(Caption,0);
end;
procedure TtpLabel.SetInteger(Value:Longint);
begin
Caption:=IntToStr(Value);
end;
procedure TtpLabel.Inc;
begin
Caption:=Inttostr(Succ(StrToIntDef(Caption,0)));
end;
procedure TtpLabel.Dec;
begin
Caption:=Inttostr(Pred(StrToIntDef(Caption,0)));
end;
{-------------------------------------------------------------------------}
procedure TtpLabel.CMMouseEnter(var Message: TMessage);
begin
if ShellMode<>smNone then
Cursor:= crDrag;
inherited;
end;
procedure TtpLabel.CMMouseLeave(var Message: TMessage);
begin
if ShellMode<>smNone then
Cursor:= crDefault;
inherited;
end;
procedure TtpLabel.Click;
var
a1:string;
begin
inherited Click;
if ShellMode=smNone then
exit;
//
if ShellCommand<>'' then
a1:=ShellCommand
else
if Hint<>'' then
a1:=Hint
else
a1:=Caption;
//
case ShellMode of
smOpen: WinShellOpen(a1);
smPrint: WinShellPrint(a1);
end;
end;
//----------------------------------------------------------------------
procedure Register;
begin
RegisterComponents('TPACK', [TtpLabel]);
end;
//----------------------------------------------------------------------
{
procedure TForm1.UpdateBits(Value:Word);
var
i:integer;
begin
tplabel3.AsInteger:=Value;
with tpLabel4 do begin
Caption:='';
for i:=0 to 15 do begin
if Value and (1 shl i) = (1 shl i) then
Caption:='1'+Caption
else
Caption:='0'+Caption;
if (i>0) and (i<15) and (succ(i) mod 4 = 0) then
Caption:='.'+Caption;
end;
end;
end;
}
end.
|
//Validação
unit uEstadoControler;
interface
uses
System.SysUtils, Data.DB, uEstadoDto, uEstadoModel;
type
TEstadoControler = class
private
oModelEstado: TEstadoModel;
public
function BuscarEstados: TDataSource;
function Buscar(var AEstado: TEstadoDto): Boolean;
function Excluir(var AEstado: TEstadoDto): Boolean;
function Salvar(var AEstado: TEstadoDto): Boolean;
procedure Limpar(var AEstado: TEstadoDto);
constructor Create;
destructor Destroy; override;
end;
implementation
{ TEstadoControler }
function TEstadoControler.Buscar(var AEstado: TEstadoDto): Boolean;
begin
Result := False;
//EmptyStr = '';
if (trim(AEstado.UF) <> EmptyStr) then
Result := oModelEstado.Ler(AEstado);
end;
function TEstadoControler.Excluir(var AEstado: TEstadoDto): Boolean;
begin
Result := False;
//EmptyStr = '';
if AEstado.ID > 0 then
Result := oModelEstado.Deletar(AEstado.ID);
end;
function TEstadoControler.BuscarEstados: TDataSource;
begin
Result := oModelEstado.BuscarEstados;
end;
constructor TEstadoControler.Create;
begin
oModelEstado := TEstadoModel.Create;
end;
destructor TEstadoControler.Destroy;
begin
if Assigned(oModelEstado) then
FreeAndNil(oModelEstado);
inherited;
end;
procedure TEstadoControler.Limpar(var AEstado: TEstadoDto);
begin
AEstado.ID := 0;
AEstado.UF := EmptyStr;
AEstado.Nome := EmptyStr;
end;
function TEstadoControler.Salvar(var AEstado: TEstadoDto): Boolean;
begin
Result := False;
if AEstado.ID > 0 then
Result := oModelEstado.Alterar(AEstado)
else
begin
AEstado.ID := oModelEstado.BuscarID;
Result := oModelEstado.Inserir(AEstado);
end;
end;
end.
|
{*******************************************************}
{ }
{ NTS Aero UI Library }
{ Created by GooD-NTS ( good.nts@gmail.com ) }
{ http://ntscorp.ru/ Copyright(c) 2011 }
{ License: Mozilla Public License 1.1 }
{ }
{*******************************************************}
unit UI.Aero.Window;
interface
{$I '../../Common/CompilerVersion.Inc'}
uses
{$IFDEF HAS_UNITSCOPE}
System.SysUtils,
System.Classes,
System.Generics.Defaults,
System.Generics.Collections,
Winapi.Windows,
Winapi.Messages,
Winapi.UxTheme,
Winapi.DwmApi,
Vcl.Controls,
Vcl.Graphics,
Vcl.Themes,
Vcl.Imaging.GIFImg,
Vcl.Forms,
{$ELSE}
SysUtils, Classes, Windows, Messages, UxTheme, DwmApi,
Themes, Controls, Graphics, GIFImg, Forms,
{$ENDIF}
NTS.Code.Common.Types,
UI.Aero.Globals,
UI.Aero.Core;
type
TBaseAeroWindow = Class(AeroCore)
Private
DefaultWindowProc: TWndMethod;
ThemeData: hTheme;
StateID: Integer;
OldWidth,
OldHeight: Integer;
fSnapMode: TSnapMode;
fAutoSnap: BooLean;
fSnapSize: Integer;
fOnSnap: TNotifyEvent;
fOnUnSnap: TNotifyEvent;
function GetComposition: BooLean;
function GetWindowsVista: BooLean;
procedure FindWindow;
Procedure TestSnap(var Message: TMessage);
procedure LoadAeroTheme;
Protected
Window: TForm;
Procedure AEROWindowProc(var Message: TMessage); Virtual;
Procedure AEROWindowPaint(Sender: TObject);
Procedure CurrentThemeChanged; Virtual;
Public
BackGroundImage: TBitmap;
Constructor Create(AOwner: TComponent); OverRide;
Destructor Destroy; OverRide;
function IsRunTime: Boolean;
Published
Property WindowsVista: BooLean Read GetWindowsVista;
Property Composition: BooLean Read GetComposition;
Property AutoSnap: BooLean Read fAutoSnap Write fAutoSnap default False;
Property SnapSize: Integer Read fSnapSize Write fSnapSize default 0;
Property SnapMode: TSnapMode Read fSnapMode Write fSnapMode default smTop;
//
Property OnSnap: TNotifyEvent Read fOnSnap Write fOnSnap;
Property OnUnSnap: TNotifyEvent Read fOnUnSnap Write fOnUnSnap;
End;
TAeroWindow = class(TBaseAeroWindow)
private
fShowInTaskBar: BooLean;
fIcon: TImageFileName;
fShowCaptionBar: BooLean;
fDragWindow: BooLean;
fLines: TStrings;
FStringDictionary: TDictionary<string, string>;
fLinesCount: Integer;
procedure SetIcon(const Value: TImageFileName);
procedure SetShowCaptionBar(const Value: BooLean);
procedure SetShowInTaskBar(const Value: BooLean);
procedure DragMove(X,Y: Integer);
procedure SetLines(const Value: TStrings);
function GetStringListText: String;
procedure SetLinesCount(const Value: Integer);
procedure SetStringDictionary(const Value: TDictionary<string, string>);
protected
Procedure AEROWindowProc(var Message: TMessage); override;
Procedure ChangeTaskBar;
Procedure ChangeCaptionBar;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy(); override;
function GetString(Index: Integer): string; overload; inline;
function GetString(const key: string): string; overload; inline;
published
property Icon: TImageFileName Read fIcon Write SetIcon;
property ShowInTaskBar: BooLean Read fShowInTaskBar Write SetShowInTaskBar Default True;
property ShowCaptionBar: BooLean Read fShowCaptionBar Write SetShowCaptionBar Default True;
Property DragWindow: BooLean Read fDragWindow Write fDragWindow Default False;
property StringList: TStrings Read fLines Write SetLines;
property StringDictionary: TDictionary<string,string> read FStringDictionary write SetStringDictionary;
property LinesCount: Integer Read fLinesCount Write SetLinesCount;
property Text: String Read GetStringListText;
end;
implementation
uses
System.Types,
System.IOUtils,
NTS.Code.Helpers;
{ TBaseAeroWindow }
Constructor TBaseAeroWindow.Create(AOwner: TComponent);
begin
Inherited Create(AOwner);
if AeroCore.FirstInstance = nil then
begin
AeroCore.FirstInstance:= Self;
if AeroCore.RunWindowsVista then
AeroCore.CompositionActive:= IsCompositionActive
else
AeroCore.CompositionActive:= False;
end;
BackGroundImage:= TBitmap.Create;
FindWindow;
if not Assigned(Window) then
raise Exception.Create('Aero Engine: [Fatal error] Parent owner Window is nil.');
if IsRunTime then
begin
Self.DefaultWindowProc:= Window.WindowProc;
Window.WindowProc:= Self.AEROWindowProc;
Window.OnPaint:= Self.AEROWindowPaint;
end;
LoadAeroTheme;
StateID:= 1;
fAutoSnap:= False;
fSnapSize:= 0;
fSnapMode:= smTop;
fOnSnap:= nil;
fOnUnSnap:= nil;
end;
Destructor TBaseAeroWindow.Destroy;
begin
if IsRunTime then
begin
Window.WindowProc:= Self.DefaultWindowProc;
Window.OnPaint:= nil;
end;
if ThemeData <> 0 then
CloseThemeData(ThemeData);
if Assigned(BackGroundImage) then
BackGroundImage.Free;
if AeroCore.FirstInstance = Self then
AeroCore.FirstInstance:= nil;
Inherited Destroy;
end;
procedure TBaseAeroWindow.LoadAeroTheme;
begin
if RunWindowsVista and {$IFDEF HAS_VCLSTYLES}StyleServices.Enabled{$ELSE}ThemeServices.ThemesEnabled{$ENDIF} then
ThemeData:= OpenThemeData(0,'AeroWizard')
else
ThemeData:= 0;
end;
procedure TBaseAeroWindow.CurrentThemeChanged;
begin
if AeroCore.RunWindowsVista then
begin
if AeroCore.FirstInstance = Self then
AeroCore.CompositionActive:= IsCompositionActive
else
if AeroCore.FirstInstance = nil then
begin
AeroCore.FirstInstance:= Self;
AeroCore.CompositionActive:= IsCompositionActive;
end;
end
else
AeroCore.CompositionActive:= False;
if ThemeData <> 0 then
CloseThemeData(ThemeData);
LoadAeroTheme;
end;
procedure TBaseAeroWindow.FindWindow;
begin
if Owner is TForm then
Window:= TForm(Owner)
else
Window:= nil;
end;
function TBaseAeroWindow.GetComposition: BooLean;
begin
Result:= AeroCore.CompositionActive;
end;
function TBaseAeroWindow.GetWindowsVista: BooLean;
begin
Result:= RunWindowsVista;
end;
function TBaseAeroWindow.IsRunTime: Boolean;
begin
Result:= not (csDesigning in ComponentState);
end;
procedure TBaseAeroWindow.TestSnap(var Message: TMessage);
function CheckNewSize(var NewWidth, NewHeight: Integer): Boolean;
var
Magic: Integer;
OldValue: BooLean;
begin
Result:= True;
OldValue:= Window.GlassFrame.SheetOfGlass;
case fSnapMode of
smTop:
begin
Magic:= Window.Height-Window.ClientHeight;
if NewHeight <= Window.GlassFrame.Top+Magic+fSnapSize then
begin
NewHeight:= Window.GlassFrame.Top+Magic;
Window.GlassFrame.SheetOfGlass:= True;
if (OldValue <> Window.GlassFrame.SheetOfGlass) and Assigned(fOnSnap) then
fOnSnap(Self);
end
else
begin
Window.GlassFrame.SheetOfGlass:= False;
if (OldValue <> Window.GlassFrame.SheetOfGlass) and Assigned(fOnUnSnap) then
fOnUnSnap(Self);
end;
end;
smBottom:
begin
Magic:= (Window.Height-Window.ClientHeight);
if NewHeight <= Window.GlassFrame.Bottom+Magic+fSnapSize then
begin
NewHeight:= Window.GlassFrame.Bottom+Magic;
Window.GlassFrame.SheetOfGlass:= True;
if (OldValue <> Window.GlassFrame.SheetOfGlass) and Assigned(fOnSnap) then
fOnSnap(Self);
end
else
begin
Window.GlassFrame.SheetOfGlass:= False;
if (OldValue <> Window.GlassFrame.SheetOfGlass) and Assigned(fOnUnSnap) then
fOnUnSnap(Self);
end;
end;
smLeft:
begin
Magic:= (Window.Width-Window.ClientWidth);
if NewWidth <= Window.GlassFrame.Left+Magic+fSnapSize then
begin
NewWidth:= Window.GlassFrame.Left+Magic;
Window.GlassFrame.SheetOfGlass:= True;
if (OldValue <> Window.GlassFrame.SheetOfGlass) and Assigned(fOnSnap) then
fOnSnap(Self);
end
else
begin
Window.GlassFrame.SheetOfGlass:= False;
if (OldValue <> Window.GlassFrame.SheetOfGlass) and Assigned(fOnUnSnap) then
fOnUnSnap(Self);
end;
end;
smRight:
begin
Magic:= (Window.Width-Window.ClientWidth);
if NewWidth <= Window.GlassFrame.Right+Magic+fSnapSize then
begin
NewWidth:= Window.GlassFrame.Right+Magic;
Window.GlassFrame.SheetOfGlass:= True;
if (OldValue <> Window.GlassFrame.SheetOfGlass) and Assigned(fOnSnap) then
fOnSnap(Self);
end
else
begin
Window.GlassFrame.SheetOfGlass:= False;
if (OldValue <> Window.GlassFrame.SheetOfGlass) and Assigned(fOnUnSnap) then
fOnUnSnap(Self);
end;
end;
end;
end;
var
WinPos: PWindowPos;
begin
WinPos:= Pointer(Message.LParam);
with WinPos^ do
if (flags and SWP_NOSIZE = 0) and not CheckNewSize(cx, cy) then
flags := flags or SWP_NOSIZE;
Self.DefaultWindowProc(Message);
end;
procedure TBaseAeroWindow.AEROWindowPaint(Sender: TObject);
var
LClientRect: TRect;
begin
if RunWindowsVista and not Composition and {$IFDEF HAS_VCLSTYLES}StyleServices.Enabled{$ELSE}ThemeServices.ThemesEnabled{$ENDIF} then
begin
LClientRect:= Window.ClientRect;
LClientRect.Bottom:= LClientRect.Bottom+1;
if not Window.GlassFrame.SheetOfGlass then
ExcludeClipRect( Window.Canvas.Handle, Window.GlassFrame.Left,
Window.GlassFrame.Top, LClientRect.Right - Window.GlassFrame.Right,
LClientRect.Bottom - Window.GlassFrame.Bottom );
DrawThemeBackground(ThemeData, Window.Canvas.Handle, 1, StateID,
LClientRect, @LClientRect);
BackGroundImage.SetSize(Window.Width,Window.Height);
BackGroundImage.Canvas.Brush.Color:= Window.Color;
BackGroundImage.Canvas.FillRect(Rect(0, 0, Window.Width, Window.Height));
DrawThemeBackground(ThemeData, BackGroundImage.Canvas.Handle, 1, 1,
LClientRect, @LClientRect);
end;
end;
procedure TBaseAeroWindow.AEROWindowProc(var Message: TMessage);
begin
if (Message.Msg = WM_WINDOWPOSCHANGING) and fAutoSnap then
TestSnap(Message)
else
DefaultWindowProc(Message);
case Message.Msg of
WM_THEMECHANGED,
WM_DWMCOMPOSITIONCHANGED: CurrentThemeChanged;
WM_ACTIVATE:
if RunWindowsVista and not Composition and {$IFDEF HAS_VCLSTYLES}StyleServices.Enabled{$ELSE}ThemeServices.ThemesEnabled{$ENDIF}then
begin
case Message.wParam of
WA_ACTIVE, WA_CLICKACTIVE: StateID:= 1;
WA_INACTIVE: StateID:= 2;
end;
Window.Invalidate;
end;
WM_WINDOWPOSCHANGED:
if RunWindowsVista and not Composition and {$IFDEF HAS_VCLSTYLES}StyleServices.Enabled{$ELSE}ThemeServices.ThemesEnabled{$ENDIF} then
begin
if (OldWidth <> Window.ClientWidth) or (OldHeight <> Window.ClientHeight) then
begin
Window.Invalidate;
OldWidth:= Window.ClientWidth;
OldHeight:= Window.ClientHeight;
end;
end;
end;
end;
{ TAeroWindow }
constructor TAeroWindow.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
fIcon := '';
fShowInTaskBar := True;
fShowCaptionBar := True;
fDragWindow := False;
fLines := TStringList.Create();
FStringDictionary := TDictionary<string, string>.Create();
fLinesCount := 0;
end;
destructor TAeroWindow.Destroy();
begin
FStringDictionary.Free();
fLines.Free;
inherited Destroy();
end;
procedure TAeroWindow.DragMove(X, Y: Integer);
const
SC_DragMove = $F012;
var
NonGlassRect: TRect;
begin
if Window.GlassFrame.SheetOfGlass then
begin
ReleaseCapture;
Window.Perform(WM_SysCommand, SC_DragMove, 0);
end
else
begin
NonGlassRect:= Window.ClientRect;
NonGlassRect := Rect(Window.GlassFrame.Left, Window.GlassFrame.Top,
NonGlassRect.Right - Window.GlassFrame.Right,
NonGlassRect.Bottom - Window.GlassFrame.Bottom );
if not Point(X,Y).InRect(NonGlassRect) then
begin
ReleaseCapture;
Window.Perform(WM_SysCommand, SC_DragMove, 0);
end;
end;
end;
function TAeroWindow.GetString(Index: Integer): string;
begin
if (StringList.Count > 0) and (Index > -1) and (Index < StringList.Count - 1) then
Result := StringList[Index]
else
Result := 'GetString@' + IntToStr(Index);
end;
function TAeroWindow.GetString(const key: string): string;
begin
if not FStringDictionary.TryGetValue(key, Result) then
Result := key;
end;
function TAeroWindow.GetStringListText: String;
begin
Result:= fLines.Text;
end;
procedure TAeroWindow.AEROWindowProc(var Message: TMessage);
begin
if (Message.Msg = CM_SHOWINGCHANGED) and (Window.Showing) then
begin
ChangeCaptionBar;
ChangeTaskBar;
end;
Inherited AEROWindowProc(Message);
if (Message.Msg = WM_LBUTTONDOWN) and (fDragWindow) then
DragMove(Message.LParamLo, Message.LParamHi);
end;
procedure TAeroWindow.SetIcon(const Value: TImageFileName);
Procedure SetZeroIcon(FreeOld: BooLean);
begin
if FreeOld then
begin
DestroyIcon(SendMessage(Window.Handle, WM_GETICON, ICON_SMALL, 0));
DestroyIcon(SendMessage(Window.Handle, WM_SETICON, ICON_SMALL, 0));
end;
PostMessage(Window.Handle, WM_SETICON, ICON_SMALL, 0);
PostMessage(Window.Handle, WM_SETICON, ICON_BIG, 0);
end;
Procedure SetNewIcon;
var
Icon: hIcon;
begin
Icon:= LoadImage(HInstance,pChar(fIcon),IMAGE_ICON,
GetSystemMetrics(SM_CXSMICON),GetSystemMetrics(SM_CYSMICON),
LR_LOADFROMFILE);
PostMessage(Window.Handle, WM_SETICON, ICON_SMALL, Icon);
Icon:= LoadImage(HInstance,pChar(fIcon),IMAGE_ICON,
GetSystemMetrics(SM_CXICON),GetSystemMetrics(SM_CYICON),LR_LOADFROMFILE);
PostMessage(Window.Handle, WM_SETICON, ICON_BIG, Icon);
end;
begin
if fIcon <> Value then
begin
SetZeroIcon(fIcon <> '');
fIcon:= Value;
if TFile.Exists(fIcon) then
SetNewIcon;;
end;
end;
procedure TAeroWindow.SetLines(const Value: TStrings);
begin
fLines.Assign(Value);
end;
procedure TAeroWindow.SetLinesCount(const Value: Integer);
var
I: Integer;
begin
fLinesCount := Value;
if IsRunTime then
begin
FLines.Clear;
for I:=0 to Value do
FLines.Add(Window.Name+'.StringList.Item_'+IntToStr(I));
end;
end;
procedure TAeroWindow.SetShowCaptionBar(const Value: BooLean);
begin
if fShowCaptionBar <> Value then
begin
fShowCaptionBar:= Value;
if IsRunTime then
ChangeCaptionBar;
end;
end;
procedure TAeroWindow.SetShowInTaskBar(const Value: BooLean);
begin
if fShowInTaskBar <> Value then
begin
fShowInTaskBar:= Value;
if IsRunTime then
ChangeTaskBar;
end;
end;
procedure TAeroWindow.SetStringDictionary(const Value: TDictionary<string, string>);
begin
FStringDictionary.Free();
FStringDictionary := TDictionary<string, string>.Create(Value);
end;
procedure TAeroWindow.ChangeCaptionBar;
begin
if AeroCore.RunWindowsVista then
begin
if fShowCaptionBar then
SetWindowThemeNonClientAttributes(Window.Handle, WTNCA_VALIDBITS, 0)
else
SetWindowThemeNonClientAttributes(Window.Handle, WTNCA_VALIDBITS, WTNCA_VALIDBITS);
end;
end;
procedure TAeroWindow.ChangeTaskBar;
begin
if fShowInTaskBar then
SetWindowLong(Window.Handle,GWL_EXSTYLE,GetWindowLong(Window.Handle,GWL_EXSTYLE) or WS_EX_APPWINDOW)
else
SetWindowLong(Window.Handle,GWL_EXSTYLE,GetWindowLong(Window.Handle,GWL_EXSTYLE) and not WS_EX_APPWINDOW);
end;
{ Initialization & Finalization }
Initialization
begin
Screen.Cursors[crHandPoint] := LoadCursor(0,IDC_HAND);
GIFImageDefaultAnimate := True;
end;
Finalization
begin
// To Do: Type code here...
end;
end.
|
unit VisibleDSA.AlgoVisualizer;
interface
uses
System.SysUtils,
FMX.Graphics,
FMX.Forms,
VisibleDSA.AlgoVisHelper;
type
TAlgoVisualizer = class(TObject)
private
_money: TArray<integer>;
public
constructor Create;
destructor Destroy; override;
procedure Paint(canvas: TCanvas);
procedure Run;
end;
implementation
uses
System.Generics.Collections,
VisibleDSA.AlgoForm;
{ TAlgoVisualizer }
constructor TAlgoVisualizer.Create;
var
i: integer;
begin
SetLength(_money, 100);
for i := 0 to Length(_money) - 1 do
_money[i] := 100;
end;
destructor TAlgoVisualizer.Destroy;
begin
inherited Destroy;
end;
procedure TAlgoVisualizer.Paint(canvas: TCanvas);
var
w, h, i: integer;
begin
TArray.Sort<Integer>(_money);
w := canvas.Width div Length(_money);
h := canvas.Height div 2;
for i := 0 to Length(_money) - 1 do
begin
if _money[i] > 0 then
begin
TAlgoVisHelper.SetFill(CL_BLUE);
TAlgoVisHelper.FillRectangle(canvas, i * w + 1, h - _money[i], w - 1, _money[i]);
end
else if _money[i] < 0 then
begin
TAlgoVisHelper.SetFill(CL_RED);
TAlgoVisHelper.FillRectangle(canvas, i * w + 1, h, w - 1, Abs(_money[i]));
end;
end;
end;
procedure TAlgoVisualizer.Run;
var
i, j: integer;
begin
Randomize;
for i := 0 to Length(_money) - 1 do
begin
j := Random(Length(_money));
Inc(_money[j]);
Dec(_money[i]);
end;
TAlgoVisHelper.Pause(0);
AlgoForm.PaintBox.Repaint;
end;
end.
|
program genetic;
{
ищем максимум
Критерий останова: выполнение заданного числа итераций
Турнирная селекция
Одноточечное скрещивание
Мутация реверс
}
const
n = 12; {Число особей}
OSTANOV = 4000; {Проходов до остановы}
EXACT = 16384; {Точность}
v1 = 0.30;
type
ArrF = array[1..n] of real; {Значения функции}
individ = array[1..n] of integer; {Двоичная запись одного гена}
population = array[1..n] of individ; {Массив все генов}
var
pop: population;
mx: real;
function F(x: real): real;
begin
F := (x-2)*(x-2.5)*(x-3)*(x-3.5)*(1-exp(x-1.5))*ln(x+0.5);
end;
procedure dec2bin(x: real; var a: individ);
var i: integer;
begin
case trunc(x) of
1: begin a[1] := 0; a[2] := 1; end;
2: begin a[1] := 1; a[2] := 0; end;
3: begin a[1] := 1; a[2] := 1; end;
end;
x := x - trunc(x);
for i := 3 to n do begin
a[i] := trunc(2 * x);
x := 2 * x - trunc(2 * x);
end;
end;
function rand(x: real): boolean;
begin
if x=0 then rand:=false else rand := random(maxint)/maxint < x;
end;
function pow(a : real; b : integer): real;
var p : real;
i: integer;
begin
p := 1;
if b = 0 then pow := 1
else if b > 0 then
for i := 1 to b do begin
p := p*a;
pow := p;
end
else pow := 1/pow(a, -b);
end;
function bin2dec(a: individ): real;
var
i: integer;
x: real;
begin
x := 2*a[1] + a[2];
for i := 3 to n do
x := x + a[i]*pow(2, 2-i);
bin2dec := x;
end;
{Одноточечное скрещивание}
procedure crossbreeding(var A, B, C, D : individ);
var
k : integer;
i: integer;
begin
randomize;
k := random(n);
for i:=1 to n do
if i<=k then begin
C[i] := A[i];
D[i] := B[i];
end
else begin
C[i] := B[i];
D[i] := C[i];
end;
end;
{Скрещивание}
procedure cross(var Pop: population);
var i, l, s: integer;
newpop : population;
begin
for i:=1 to (n div 2) do
crossbreeding(pop[random(3)+1], pop[2*i-1], newpop[2*i], newpop[2*i - 1]);
for i:=1 to n do
if F(bin2dec(pop[i])) < F(bin2dec(newpop[i])) then
for l := 1 to n do
pop[i][l] := newpop[i][l];
end;
{Мутация реверс}
procedure mutation(var pop: population);
var i, j, k, c : integer;
begin
for i:=1 to n do begin
randomize;
k := random(n-1);
if rand(i/n) then
for j:= k to ((n+k) div 2) do begin
c := pop[i][j];
pop[i][j] := pop[i][n - j + k];
pop[i][ n - j + k] := c;
end;
end;
end;
procedure selection(var pop: population);
var
i, j, s, l: integer;
begin
for i := 1 to n div 2 do
for j := i + 1 to n do
if F(bin2dec(pop[i])) < F(bin2dec(pop[j])) then begin
for l := 1 to n do begin
s := pop[i][l];
pop[i][l] := pop[j][l];
pop[j][l] := s;
end;
end;
end;
procedure INIT(var pop: population);
var i : integer;
begin
randomize;
for i := 1 to n do begin
dec2bin(4*random(maxint)/maxint, pop[i]);
end;
end;
procedure loop (var pop : population; var mx : real);
var i, j, w: integer;
begin
for i:=1 to 100 do begin {это по количеству итераций болшая погрешность}
selection(pop);
cross(pop);
mutation(pop);
w:=1;
for j:=1 to n do
if F(bin2dec(pop[j]))>F(bin2dec(pop[w])) then
w:=j;
if F(bin2dec(pop[w]))>F(mx) then
mx := bin2dec(pop[w]);
end;
if F(mx) < 1.6 then begin
INIT(pop);
loop(pop, mx);
end;
end;
begin
{
Ответ
x:= 0.779822;
y:= 1.605418;
}
randomize;
INIT(pop);
mx := bin2dec(pop[1]);
loop(pop, mx);
writeln('x=', mx:3:6,' y=',F(mx):3:6);
end.
|
{
Set one item in a Papyrus Form[] property.
}
Unit CobbSingleSetPapyrusForm;
Uses 'Skyrim - Papyrus Resource Library';
Uses 'CobbTES5EditUtil';
Var
greSignatureAndID: TPerlRegEx;
sScriptTarget: String;
sNewPropertyName: String;
iPropertyIndex: Integer;
iFormID: Integer;
Function Initialize: integer;
Var
slLabels: TStringList;
slResult: TStringList;
eValue: IInterface;
eFile: IInterface;
Begin
greSignatureAndID := TPerlRegEx.Create;
greSignatureAndID.Options := [preSingleLine];
greSignatureAndID.RegEx := '^(\w\w\w\w) (\S+)$';
greSignatureAndID.Study;
//
// Ask the user what to do.
//
slLabels := TStringList.Create;
slLabels.Add('Add property to what script?');
slLabels.Add('Form[] property name?');
slLabels.Add('Index in the array?');
slLabels.Add('Enter the value of the new property as a Form ID, or as a signature, space, and Editor ID.');
slResult := PromptForStrings('Set Form property', slLabels);
If slResult.Count = 0 Then Begin
Result := 1;
Exit;
End Else Begin
sScriptTarget := slResult[0];
sNewPropertyName := slResult[1];
iPropertyIndex := StrToInt(Trim(slResult[2]));
Try
iFormID := StrToInt('$' + slResult[3]);
Except
greSignatureAndID.Subject := slResult[3];
greSignatureAndID.Start := 0;
If greSignatureAndID.MatchAgain Then Begin
eValue := GetRecordInAnyFileByEditorID(greSignatureAndID.Groups[1], greSignatureAndID.Groups[2]);
If Assigned(eValue) Then iFormID := FormID(eValue) Else Begin
AddMessage('The specified form does not exist.');
Result := 1;
Exit;
End;
End Else Begin
AddMessage('The specified value couldn''t be deciphered. Remember: if you''re specifying an Editor ID, you must prefix it with the signature (e.g. CONT) and a space.');
Result := 1;
Exit;
End;
End;
End;
End;
Function Process(e: IInterface) : Integer;
Begin
If ElementType(e) = etMainRecord Then
If ElementExists(e, 'VMAD') Then Begin
SetFormArrayPropertyItemOnScript(GetScript(e, sScriptTarget), sNewPropertyName, iPropertyIndex, iFormID);
End;
End;
End. |
unit PFL;
////////////////////////////////////////////////////////////////////////////////
//
// Author: Jaap Baak
// https://github.com/transportmodelling/Utils
//
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
interface
////////////////////////////////////////////////////////////////////////////////
Uses
Classes,SysUtils,SyncObjs;
Type
TLoopIteration = reference to Procedure(Iteration,Thread: Integer);
TParallelFor = Class
private
Type
TIterationThread = Class(TThread)
private
Loop: TParallelFor;
Thread,Iteration: Integer;
LoopIteration: TLoopIteration;
public
Procedure Execute; override;
end;
Var
LoopCompleted: TEvent;
FirstException: Exception;
Next,IterationCount,ThreadCount: Integer;
public
Constructor Create;
Procedure Execute(FromIteration,ToIteration: Integer; const Iteration: TLoopIteration); overload;
Procedure Execute(NThreads,FromIteration,ToIteration: Integer; const Iteration: TLoopIteration); overload;
Destructor Destroy; override;
end;
////////////////////////////////////////////////////////////////////////////////
implementation
////////////////////////////////////////////////////////////////////////////////
Procedure TParallelFor.TIterationThread.Execute;
begin
repeat
// Execute iteration
try
LoopIteration(Iteration,Thread);
except
on E: Exception do
begin
TMonitor.Enter(Loop);
try
Dec(Loop.ThreadCount);
if Loop.ThreadCount = 0 then Loop.LoopCompleted.SetEvent;
if Loop.FirstException = nil then Loop.FirstException := AcquireExceptionObject as Exception;
Terminate;
finally
TMonitor.Exit(Loop);
end;
end;
end;
// Collect next iteration
if not Terminated then
begin
TMonitor.Enter(Loop);
try
if (Loop.FirstException = nil) and (Loop.IterationCount > 0) then
begin
Iteration := Loop.Next;
Inc(Loop.Next);
Dec(Loop.IterationCount);
end else
begin
Dec(Loop.ThreadCount);
if Loop.ThreadCount = 0 then Loop.LoopCompleted.SetEvent;
Terminate;
end;
finally
TMonitor.Exit(Loop);
end;
end;
until Terminated;
end;
////////////////////////////////////////////////////////////////////////////////
Constructor TParallelFor.Create;
begin
inherited Create;
LoopCompleted := TEvent.Create(nil,false,true,'');
end;
Procedure TParallelFor.Execute(FromIteration,ToIteration: Integer; const Iteration: TLoopIteration);
begin
Execute(TThread.ProcessorCount,FromIteration,ToIteration,Iteration);
end;
Procedure TParallelFor.Execute(NThreads,FromIteration,ToIteration: Integer; const Iteration: TLoopIteration);
begin
if ToIteration >= FromIteration then
begin
FirstException := nil;
TMonitor.Enter(Self);
try
LoopCompleted.ResetEvent;
Next := FromIteration;
IterationCount := ToIteration-FromIteration+1;
while (IterationCount > 0) and (ThreadCount < NThreads) do
begin
var Thread := TIterationThread.Create(true);
Thread.Thread := ThreadCount;
Thread.Iteration := Next;
Thread.LoopIteration := Iteration;
Thread.Loop := Self;
Thread.FreeOnTerminate := true;
Thread.Start;
Inc(ThreadCount);
Inc(Next);
Dec(IterationCount);
end;
finally
TMonitor.Exit(Self);
end;
LoopCompleted.WaitFor(Infinite);
if FirstException <> nil then raise FirstException;
end;
end;
Destructor TParallelFor.Destroy;
begin
LoopCompleted.Free;
inherited Destroy;
end;
end.
|
unit HJYIntfObjs;
interface
type
//实现IInterface接口,但不同于TInterfacedObject,引用计数为0不会自动释放
THJYIntfObj = Class(TObject, IInterface)
protected
{IInterface}
function QueryInterface(const IID: TGUID; out Obj): HResult; stdcall;
function _AddRef: Integer; stdcall;
function _Release: Integer; stdcall;
end;
implementation
{ THJYIntfObj }
function THJYIntfObj.QueryInterface(const IID: TGUID; out Obj): HResult;
begin
if GetInterface(IID, Obj) then
Result := 0
else
Result := E_NOINTERFACE;
end;
function THJYIntfObj._AddRef: Integer;
begin
Result := -1;
end;
function THJYIntfObj._Release: Integer;
begin
Result := -1;
end;
end.
|
unit UMyBackupRemoveInfo;
interface
uses classes, UModelUtil, Generics.Collections, UChangeInfo, xmldom, XMLIntf, msxmldom, XMLDoc, UXmlUtil;
type
{$Region ' Pc 备份源文件删除 内存信息 ' }
{$Region ' 数据结构 ' }
// 删除的备份路径信息
TRemoveBackupPathInfo = class
public
FullPath : string;
PathType : string;
public
constructor Create( _FullPath, _PathType : string );
end;
TRemoveBackupPathPair = TPair< string , TRemoveBackupPathInfo >;
TRemoveBackupPathHash = class(TStringDictionary< TRemoveBackupPathInfo >);
// 删除的 Pc 文件信息
TRemoveBackupNofityInfo = class
public
PcID : string;
RemoveBackupPathHash : TRemoveBackupPathHash;
public
constructor Create( _PcID : string );
destructor Destroy; override;
end;
TRemoveBackupNotifyPair = TPair< string , TRemoveBackupNofityInfo >;
TRemoveBackupNotifyHash = class(TStringDictionary< TRemoveBackupNofityInfo >);
{$EndRegion}
{$Region ' 修改 ' }
// 修改
TRemoveBackupNotifyChangeInfo = class( TChangeInfo )
public
PcID : string;
RemoveBackupNotifyHash : TRemoveBackupNotifyHash;
public
constructor Create( _PcID : string );
procedure Update;override;
end;
// 修改 指定路径
TRemoveBackupNotifyWriteInfo = class( TRemoveBackupNotifyChangeInfo )
public
FullPath : string;
public
procedure SetFullPath( _FullPath : string );
end;
// 添加
TRemoveBackupNotifyAddInfo = class( TRemoveBackupNotifyWriteInfo )
private
PathType : string;
public
procedure SetPathType( _PathType : string );
procedure Update;override;
end;
// Pc 上线
TRemoveBackupNotifyPcOnlineInfo = class( TRemoveBackupNotifyChangeInfo )
public
procedure Update;override;
end;
// 删除
TRemoveBackupNotifyDeleteInfo = class( TRemoveBackupNotifyWriteInfo )
public
procedure Update;override;
end;
{$EndRegion}
// 删除 网络 Pc 的备份文件信息
TMyBackupRemoveNotifyInfo = class( TMyDataChange )
public
RemoveBackupNotifyHash : TRemoveBackupNotifyHash;
public
constructor Create;
destructor Destroy; override;
end;
{$EndRegion}
{$Region ' Pc 备份源文件删除 Xml 信息 ' }
{$Region ' 修改 ' }
// 修改
TRemoveBackupNotifyChangeXml = class( TChangeInfo )
public
PcID : string;
public
constructor Create( _PcID : string );
end;
// 修改 指定路径
TRemoveBackupNotifyWriteXml = class( TRemoveBackupNotifyChangeXml )
public
FullPath : string;
public
procedure SetFullPath( _FullPath : string );
end;
// 添加
TRemoveBackupNotifyAddXml = class( TRemoveBackupNotifyWriteXml )
private
PathType : string;
public
procedure SetPathType( _PathType : string );
procedure Update;override;
end;
// 删除
TRemoveBackupNotifyDeleteXml = class( TRemoveBackupNotifyWriteXml )
public
procedure Update;override;
end;
{$EndRegion}
{$Region ' 读取 ' }
TPcRemoveBackupPathReadHandle = class
private
PcID : string;
FullPath, PathType : string;
public
constructor Create( _PcID : string );
procedure SetPathInfo( _FullPath, _PathType : string );
procedure Update;
end;
// 读取 Xml 文件信息
TBackupRemoveNotifyRead = class
public
procedure Update;
end;
{$EndRegion}
// 删除 网络 Pc 的备份文件信息
TMyBackupFileRemoveWriteXml = class( TMyChildXmlChange )
end;
{$EndRegion}
const
Xml_PcID = 'pi';
Xml_RemoveBackupPathHash = 'rbph';
Xml_FullPath = 'fp';
Xml_PathType = 'pt';
var
MyBackupRemoveNotifyInfo : TMyBackupRemoveNotifyInfo;
MyBackupFileRemoveWriteXml : TMyBackupFileRemoveWriteXml;
implementation
uses UMyClient, UMyNetPcInfo;
{ TRemovePcFileInfo }
constructor TRemoveBackupNofityInfo.Create(_PcID: string);
begin
PcID := _PcID;
RemoveBackupPathHash := TRemoveBackupPathHash.Create;
end;
destructor TRemoveBackupNofityInfo.Destroy;
begin
RemoveBackupPathHash.Free;
inherited;
end;
{ TMyBackupFileRemoveInfo }
constructor TMyBackupRemoveNotifyInfo.Create;
begin
inherited;
RemoveBackupNotifyHash := TRemoveBackupNotifyHash.Create;
AddThread(1);
end;
destructor TMyBackupRemoveNotifyInfo.Destroy;
begin
DeleteThread(1);
RemoveBackupNotifyHash.Free;
inherited;
end;
{ TRemovePcFileAddInfo }
procedure TRemoveBackupNotifyAddInfo.SetPathType(_PathType: string);
begin
PathType := _PathType;
end;
procedure TRemoveBackupNotifyAddInfo.Update;
var
RemoveBackupPathHash : TRemoveBackupPathHash;
begin
inherited;
if not RemoveBackupNotifyHash.ContainsKey( PcID ) then
RemoveBackupNotifyHash.addOrSetValue( PcID, TRemoveBackupNofityInfo.Create( PcID ) );
RemoveBackupPathHash := RemoveBackupNotifyHash[ PcID ].RemoveBackupPathHash;
if RemoveBackupPathHash.ContainsKey( FullPath ) then
Exit;
RemoveBackupPathHash.AddOrSetValue( FullPath, TRemoveBackupPathInfo.Create( FullPath, PathType ) )
end;
{ TRemovePcFileChangeInfo }
constructor TRemoveBackupNotifyChangeInfo.Create(_PcID: string);
begin
PcID := _PcID;
end;
procedure TRemoveBackupNotifyChangeInfo.Update;
begin
RemoveBackupNotifyHash := MyBackupRemoveNotifyInfo.RemoveBackupNotifyHash;
end;
{ TRemovePcOnlineInfo }
procedure TRemoveBackupNotifyPcOnlineInfo.Update;
var
RemoveBackupPathHash : TRemoveBackupPathHash;
p : TRemoveBackupPathPair;
BackupFileRemoveMsg : TBackupFileRemoveMsg;
begin
inherited;
if not RemoveBackupNotifyHash.ContainsKey( PcID ) then
Exit;
RemoveBackupPathHash := RemoveBackupNotifyHash[ PcID ].RemoveBackupPathHash;
for p in RemoveBackupPathHash do
begin
BackupFileRemoveMsg := TBackupFileRemoveMsg.Create;
BackupFileRemoveMsg.SetPcID( PcInfo.PcID );
BackupFileRemoveMsg.SetFilePath( p.Value.FullPath );
MyClient.SendMsgToPc( PcID, BackupFileRemoveMsg );
end;
end;
{ TRemovePcFileWriteInfo }
procedure TRemoveBackupNotifyWriteInfo.SetFullPath(_FullPath: string);
begin
FullPath := _FullPath;
end;
{ TRemovePcFileRemoveInfo }
procedure TRemoveBackupNotifyDeleteInfo.Update;
var
RemoveBackupPathHash : TRemoveBackupPathHash;
begin
inherited;
if not RemoveBackupNotifyHash.ContainsKey( PcID ) then
Exit;
RemoveBackupPathHash := RemoveBackupNotifyHash[ PcID ].RemoveBackupPathHash;
if RemoveBackupPathHash.ContainsKey( FullPath ) then
RemoveBackupPathHash.Remove( FullPath );
if RemoveBackupPathHash.Count = 0 then
RemoveBackupNotifyHash.Remove( PcID );
end;
{ TRemovePcFileChangeXml }
constructor TRemoveBackupNotifyChangeXml.Create(_PcID: string);
begin
PcID := _PcID;
end;
{ TRemovePcFileWriteXml }
procedure TRemoveBackupNotifyWriteXml.SetFullPath(_FullPath: string);
begin
FullPath := _FullPath;
end;
{ TRemovePcFileAddXml }
procedure TRemoveBackupNotifyAddXml.SetPathType(_PathType: string);
begin
PathType := _PathType;
end;
procedure TRemoveBackupNotifyAddXml.Update;
var
RemoveNotifyNode : IXMLNode;
RemoveBackupPathHashNode : IXMLNode;
RemoveBackupPathNode : IXMLNode;
begin
RemoveNotifyNode := MyXmlUtil.AddListChild( RemoveBackupNotifyHashXml, PcID );
MyXmlUtil.AddChild( RemoveNotifyNode, Xml_PcID, PcID );
RemoveBackupPathHashNode := MyXmlUtil.AddChild( RemoveNotifyNode, Xml_RemoveBackupPathHash );
if MyXmlUtil.FindListChild( RemoveBackupPathHashNode, FullPath ) <> nil then
Exit;
RemoveBackupPathNode := MyXmlUtil.AddListChild( RemoveBackupPathHashNode, FullPath );
MyXmlUtil.AddChild( RemoveBackupPathNode, Xml_FullPath, FullPath );
MyXmlUtil.AddChild( RemoveBackupPathNode, Xml_PathType, PathType );
end;
{ TRemoveBackupPathInfo }
constructor TRemoveBackupPathInfo.Create(_FullPath, _PathType: string);
begin
FullPath := _FullPath;
PathType := _PathType;
end;
{ TRemoveBackupNotifyDeleteXml }
procedure TRemoveBackupNotifyDeleteXml.Update;
var
RemoveNotifyNode : IXMLNode;
RemoveBackupPathHashNode : IXMLNode;
begin
RemoveNotifyNode := MyXmlUtil.FindListChild( RemoveBackupNotifyHashXml, PcID );
if RemoveNotifyNode = nil then
Exit;
RemoveBackupPathHashNode := MyXmlUtil.AddChild( RemoveNotifyNode, Xml_RemoveBackupPathHash );
MyXmlUtil.DeleteListChild( RemoveBackupPathHashNode, FullPath );
if RemoveBackupPathHashNode.ChildNodes.Count = 0 then
MyXmlUtil.DeleteListChild( RemoveBackupNotifyHashXml, PcID );
end;
{ TBackupRemoveNotifyRead }
procedure TBackupRemoveNotifyRead.Update;
var
i, j : Integer;
RemoveBackupNotify : IXMLNode;
PcID, FullPath, PathType : string;
RemoveBackupPathHash, RemoveBackupPathNode : IXMLNode;
PcRemoveBackupPathReadHandle : TPcRemoveBackupPathReadHandle;
begin
for i := 0 to RemoveBackupNotifyHashXml.ChildNodes.Count - 1 do
begin
RemoveBackupNotify := RemoveBackupNotifyHashXml.ChildNodes[i];
PcID := MyXmlUtil.GetChildValue( RemoveBackupNotify, Xml_PcID );
RemoveBackupPathHash := MyXmlUtil.AddChild( RemoveBackupNotify, Xml_RemoveBackupPathHash );
for j := 0 to RemoveBackupPathHash.ChildNodes.Count - 1 do
begin
RemoveBackupPathNode := RemoveBackupPathHash.ChildNodes[j];
FullPath := MyXmlUtil.GetChildValue( RemoveBackupPathNode, Xml_FullPath );
PathType := MyXmlUtil.GetChildValue( RemoveBackupPathNode, Xml_PathType );
// 加载 备份删除路径
PcRemoveBackupPathReadHandle := TPcRemoveBackupPathReadHandle.Create( PcID );
PcRemoveBackupPathReadHandle.SetPathInfo( FullPath, PathType );
PcRemoveBackupPathReadHandle.Update;
PcRemoveBackupPathReadHandle.Free;
end;
end;
end;
{ TPcRemoveBackupPathReadHandle }
constructor TPcRemoveBackupPathReadHandle.Create(_PcID: string);
begin
PcID := _PcID;
end;
procedure TPcRemoveBackupPathReadHandle.SetPathInfo(_FullPath,
_PathType: string);
begin
FullPath := _FullPath;
PathType := _PathType;
end;
procedure TPcRemoveBackupPathReadHandle.Update;
var
RemoveBackupNotifyAddInfo : TRemoveBackupNotifyAddInfo;
begin
RemoveBackupNotifyAddInfo := TRemoveBackupNotifyAddInfo.Create( PcID );
RemoveBackupNotifyAddInfo.SetFullPath( FullPath );
RemoveBackupNotifyAddInfo.SetPathType( PathType );
MyBackupRemoveNotifyInfo.AddChange( RemoveBackupNotifyAddInfo );
end;
end.
|
(*
@abstract(Regroupe quelques routines pour la detection de l'OS, CPU et autres
informations sur le systeme en général. Plus quelques fonctions utiles pour
une application. (retrouver le dossier de l'application, dossier temporaire de l'OS etc...))
-------------------------------------------------------------------------------------------------------------
@created(24/02/2019)
@author(J.Delauney (BeanzMaster))
@bold(Historique) : @br
@unorderedList(
@item(Creation : 24/02/2019)
)
-------------------------------------------------------------------------------------------------------------
@bold(Notes :)@br
-------------------------------------------------------------------------------------------------------------
@bold(Dependances) : BZSceneStrConsts @br
-------------------------------------------------------------------------------------------------------------
@bold(Credits :)@br
@unorderedList(
@item(J.Delauney (BeanzMaster))
)
-------------------------------------------------------------------------------------------------------------
@bold(LICENCE) : MPL / LGPL
------------------------------------------------------------------------------------------------------------- *)
unit BZSystem;
//==============================================================================
{$mode objfpc}{$H+}
{$i ..\bzscene_options.inc}
//==============================================================================
interface
uses
Classes, SysUtils, fileutil, LazUtf8, lazfileutils, DateUtils,
LCLIntf, LCLType
{$IFDEF Windows}
,Windows, GetText
{$ENDIF}
{$IFDEF UNIX}
,BaseUnix, Unix, Unixutil, linux, users
{$IFDEF X11_SUPPORT}
,xlib
{$ENDIF}
{$IFDEF LCLCarbon}
,MacOSAll
{$ENDIF}
{$ENDIF};
//==============================================================================
const
{ Langue utilisée par défaut }
cDefaultLanguage : String = 'FR';
Type
{ Décrit les informations sur le systeme d'exploitation }
TBZPlatformInfo = record
Major: DWORD;
Minor: DWORD;
Revision: DWORD;
Version: string;
PlatformId :DWORD;
ID: string;
CodeName: string;
Description: string;
ProductBuildVersion: string;
end;
Type
{ Enumération des types et version de systemes d'exploitation }
TBZPlatformVersion = (
pvUnknown,
pvWin95,
pvWin98,
pvWinME,
pvWinNT3,
pvWinNT4,
pvWin2000,
pvWinXP,
pvWin2003,
pvWinVista,
pvWinSeven,
pvWin2008,
pvWin8,
pvWin10,
pvUNIXArc,
pvUNIXDebian,
pvUNIXopenSUSE,
pvUNIXFedora,
pvUNIXGentoo,
pvUNIXMandriva,
pvUNIXRedHat,
pvUNIXTurboUNIX,
pvUNIXUbuntu,
pvUNIXXandros,
pvUNIXOracle,
pvAppleMacOSX
);
//TBZPlatformVersionSet = set of TBZPlatformVersion;
Type
{ Décrit les capacités de l'affichage }
TBZDeviceCapabilities = record
Xdpi, Ydpi: integer; //< Nombre de pixel logique par pouce.
Depth: integer; //< profondeur de couleur (bit).
NumColors: integer; //< Nombre d'entrées dans la table des couleurs de l'appareil.
end;
//==============================================================================
Type
{ Definition des technologies spécifiques supportées par le CPU }
TBZCPUFeaturesSet = (cf3DNow, //< Extension EDX bit 31
cf3DNowExt, //< Extension EDX bit 30
cfMMX, //< EDX bit 23 + Extension EDX bit 23
cfEMMX, //< Extension EDX bit 22
cfSSE, //< EDX bit 25
cfSSE2, //< EDX bit 26
cfSSE3, //< ECX bit 0
cfSSSE3, //< ECX bit 9
cfSSE41, //< ECX bit 19
cfSSE42, //< ECX bit 20
cfSSE4A, //< Extension ECX bit 20
cfAVX, //< ECX bit 28
//cfAVX2,
cfFMA3, //< ECX bit 12
cfFMA4, //< Extension ECX bit 16
cfNX, //< Extension EDX bit 20
cfAES //< ECX bit 25
);
{ Extensions supportées par le CPU }
TBZCPUFeatures = set of TBZCPUFeaturesSet;
{ Informations générales sur le CPU }
TBZCPUInfos = record
Vendor : String;
BrandName : String;
//FamillyAsString : String;
Features : TBZCPUFeatures;
FeaturesAsString : String;
Signature : Integer;
Speed : Integer;
LogicalProcessors : byte;
ProcessorType:Integer;
Familly:integer;
Model:Integer;
ExtModel:Integer;
ExtFamilly:Integer;
Stepping:Integer;
end;
{ Informations sur l'utilisation de la mémoire }
TBZMemoryStatus = record
TotalPhys: Int64;
AvailPhys: Int64;
TotalPageFile: Int64;
AvailPageFile: Int64;
TotalVirtual: Int64;
AvailVirtual: Int64;
//AvailExtendedVirtual: Int64;
end;
{ Retourne la vitesse approximative du processeur }
function CPU_Speed: double;
{ Renvoie @TRUE si l'instruction RDRand est supporté. INTEL CPU seulement }
function CPU_Support_RDRAND:Boolean;
{ Renvoie @TRUE si l'instruction RDSeed est supporté. INTEL CPU seulement }
function CPU_Support_RDSEED:Boolean;
{ Retourne le nombre de processeur configurer par le systeme }
function GetProcessorCount: Cardinal;
{ Retourne si des des instructions spécifiques sont supportées par le processeur }
function CPU_HasFeature(const InstructionSet: TBZCPUFeaturesSet): Boolean;
{ Recupere la valeur du timer interne du CPU (RTDSC) }
function GetClockCycleTickCount: Int64;
{ Recupere la valeur du timer interne }
procedure QueryPerformanceCounter(var val: Int64);
{ Recupere la fréquence du timer interne }
function QueryPerformanceFrequency(var val: Int64): Boolean;
{ Retourne les infos sur l'OS }
function GetPlatformInfo: TBZPlatformInfo;
{ Retrourne la version de l'OS }
function GetplatformVersion : TBZPlatformVersion;
{ Retrourne la version de l'OS sous forme de chaine de caratères }
function GetplatformVersionAsString : string;
{ Retourne les carateristique d'affichage de l'appareil cf : TBZDeviceCapabilities }
function GetDeviceCapabilities: TBZDeviceCapabilities;
{ Retourne le nombre de bit pour l'affichage }
function GetCurrentColorDepth: Integer;
{ Retourne la largeur de l'affichage en DPI }
function GetDeviceLogicalPixelsX: Integer;
{ Retourne les carateristique d'affichage de l'appareil sous forme de chaine de caratères }
function GetDeviceCapabilitiesAsString: String;
{ Retourne des informations sur la mémoire. cf : TBZMemoryStatus. Seulement valable pour WINDOWS actuellement }
function GetMemoryStatus : TBZMemoryStatus;
{ Retourne le nom de fichier de l'application en cours }
function GetApplicationFileName : string;
{ Retourne le dossier de l'application en cours }
function GetApplicationPath : string;
{ Retourne le répertoire temporaire de l'OS }
function GetTempFolderPath : string;
{ Ouvre un fichier HTML ou une Url dans le navigateur par defaut }
procedure ShowHTMLUrl(Url: string);
{ Retourne la langue utilisée par le système}
function GetSystemLanguage: string;
{ Retourne le format de la decimal du systeme }
function GetDecimalSeparator: Char;
{ Definit le format décimal "." ou "," habituellement}
procedure SetDecimalSeparator(AValue: Char);
{ Retourne la valeur de la variable d'environement passé en paramètre sous forme de chaine de caractères}
function GetEnvironmentVariable(const Name: string): string;
{ Change les slashs et backslash et inversement suivant l'OS }
function FixPathDelimiter(S: string):String;
{ Efface les slashs et backslash d'un nom de fichier }
function RemoveFileNamePathDelimiter(S : String):String;
{ Vérifie si un dossier à les droits en écriture ou non }
function IsDirectoryWriteable(const AName: string): Boolean;
{ Retourne la taille du disque courrant }
function GetCurrentDiskSize : String;
{ Retourne l'espace libre du disque courrant }
function GetCurrentFreeDiskSpace : String;
{ Retourne le nom de l'utilisateur en cours }
function GetCurrentUserName: string;
//Function GetFileVersion: String;
//Function GetProductVersion: String;
{ Retourne la date de compilation de l'application }
Function GetCompiledDate: String;
{ Retourne l'heure de compilation de l'application }
Function GetCompiledTime: String;
{ Retourne la version de FPC qui a servi à compilé l'application }
Function GetCompilerInfo: String;
{ Retourne la version de la LCL utilisée }
Function GetLCLVersion: String;
{ Retourne le widget utilisé pour l'interface graphique de l'application }
function GetWidgetSet: string;
{ Retourne l'état des boutons de la souris n'importe ou (même en dehors d'une fenêtre) comme GetCursorPos}
function GetMouseButtonState: TShiftState;
//==============================================================================
Var
{ Variable globale de type TBZCPUInfos pour stocker les informations du processeur . Variable Initialisée automatiquement }
BZCPUInfos : TBZCPUInfos;
//==============================================================================
implementation
uses
resreader, resource, versiontypes, versionresource, LCLVersion, InterfaceBase, LCLPlatformDef,
forms,
BZSceneStrConsts
//BZUtils
{$IFDEF WINDOWS}
,ShellApi,
JwaWinBase,{, JwaWinNt}
winpeimagereader {need this for reading exe info}
{$ENDIF}
{$IFDEF UNIX}
,LCLProc,
elfreader {needed for reading ELF executables}
{$ENDIF}
{$IFDEF DARWIN}
,XMLRead,
DOM,
machoreader {needed for reading MACH-O executables}
{$ENDIF};
Const
WIDGETSET_GTK = 'GTK widget';
WIDGETSET_GTK2 = 'GTK 2 widget';
WIDGETSET_WIN = 'Win32/Win64 widget';
WIDGETSET_WINCE = 'WinCE widget';
WIDGETSET_CARBON = 'Carbon widget';
WIDGETSET_QT = 'QT widget';
WIDGETSET_fpGUI = 'fpGUI widget';
WIDGETSET_OTHER = 'Other gui';
//==============================================================================
{$IFDEF UNIX}
const _SC_NPROCESSORS_ONLN = 83;
function sysconf(i: cint): clong; cdecl; external name 'sysconf';
{$ENDIF}
{$IFDEF USE_ASM_OPTIMIZATIONS}
{$IFDEF CPU32}
function GetClockCycleTickCount: Int64; assembler; register;
asm
DB $0F,$31
end;
{$ENDIF}
{$IFDEF CPU64}
function GetClockCycleTickCount: Int64; assembler; register;
asm
RDTSC //dw 310Fh // rdtsc
shl rdx, 32
or rax, rdx
end;
{$ENDIF}
{$ELSE}
function GetClockCycleTickCount: Int64;
begin
result:=getTickCount64;
end;
{$ENDIF}
//asm
//{$ifdef CPU64}
// XOR rax, rax
// CPUID
// RDTSC //Get the CPU's time stamp counter.
// mov [Result], RAX
//{$else}
// XOR eax, eax
// CPUID
// RDTSC //Get the CPU's time stamp counter.
// mov [Result], eax
//{$endif}
//end;
function CPU_Speed: double;
{$IFDEF USE_ASM_OPTIMIZATIONS}
const
DelayTime = 500; // measure time in ms
var
TimerHi, TimerLo: DWOrd;
PriorityClass, Priority: Integer;
begin
{$IFDEF WINDOWS}
PriorityClass := GetPriorityClass(GetCurrentProcess);
Priority := GetthreadPriority(GetCurrentthread);
SetPriorityClass(GetCurrentProcess, REALTIME_PRIORITY_CLASS);
SetthreadPriority(GetCurrentthread, thread_PRIORITY_TIME_CRITICAL);
Sleep(10);
{$ENDIF}
asm
dw 310Fh // rdtsc
mov TimerLo, eax
mov TimerHi, edx
end;
Sleep(DelayTime);
asm
dw 310Fh // rdtsc
sub eax, TimerLo
sbb edx, TimerHi
mov TimerLo, eax
mov TimerHi, edx
end;
{$IFDEF WINDOWS}
SetthreadPriority(GetCurrentthread, Priority);
SetPriorityClass(GetCurrentProcess, PriorityClass);
Result := TimerLo / (1000.0 * DelayTime);
{$ENDIF}
end;
{$ELSE}
const
DelayTime = 200;
var
x, y: UInt64;
{$IFDEF WINDOWS}PriorityClass, Priority: Integer;{$ENDIF}
begin
{$IFDEF WINDOWS}
PriorityClass := GetPriorityClass(GetCurrentProcess);
Priority := GetThreadPriority(GetCurrentThread);
SetPriorityClass(GetCurrentProcess, REALTIME_PRIORITY_CLASS);
SetThreadPriority(GetCurrentThread, THREAD_PRIORITY_TIME_CRITICAL);
Sleep(10);
{$ENDIF}
x := GetClockCycleTickCount;
Sleep(DelayTime);
y := GetClockCycleTickCount;
{$IFDEF WINDOWS}
SetThreadPriority(GetCurrentThread, Priority);
SetPriorityClass(GetCurrentProcess, PriorityClass);
{$ENDIF}
Result := ((y - x) and $FFFFFFFF) / (1000 * DelayTime);
end;
{$ENDIF}
function GetProcessorCount: Cardinal;
{$IFDEF WINDOWS}
var
lpSysInfo: TSystemInfo;
begin
//lpSysInfo := nil;
GetSystemInfo({%H-}lpSysInfo);
Result := lpSysInfo.dwNumberOfProcessors;
end;
{$ELSE}
begin
//Result := 1;
result := sysconf(_SC_NPROCESSORS_ONLN);
end;
{$ENDIF}
var
vBZStartTime : TDateTime;
{$IFDEF WINDOWS}
vLastTime: TDateTime;
vDeltaMilliSecond: TDateTime;
{$ENDIF}
function CPUID_Available: Boolean; assembler;
asm
{$IFDEF CPU64}
//POP RDX
MOV EDX,False
PUSHFQ
POP RAX
MOV ECX,EAX
XOR EAX,$00200000
PUSH RAX
POPFQ
PUSHFQ
POP RAX
XOR ECX,EAX
JZ @1
MOV EDX,True
@1: PUSH RAX
POPFQ
MOV EAX,EDX
//PUSH RDX
{$ELSE}
MOV EDX,False
PUSHFD
POP EAX
MOV ECX,EAX
XOR EAX,$00200000
PUSH EAX
POPFD
PUSHFD
POP EAX
XOR ECX,EAX
JZ @1
MOV EDX,True
@1: PUSH EAX
POPFD
MOV EAX,EDX
{$ENDIF}
end;
function CPU_getLargestStandardFunction:integer; assembler;
asm
{$IFDEF cpu64}
PUSH RBX
MOV EAX,0
CPUID
POP RBX
{$ELSE}
PUSH EBX
MOV EAX,0
CPUID
POP EBX
{$ENDIF}
end;
function CPU_Signature: Integer; assembler;
asm
{$IFDEF CPU64}
PUSH RBX
MOV EAX,1
CPUID
POP RBX
{$ELSE}
PUSH EBX
MOV EAX,1
CPUID
POP EBX
{$ENDIF}
end;
function CPU_FeaturesEDX: Integer; assembler;
asm
{$IFDEF CPU64}
PUSH RBX
MOV EAX,1
CPUID
POP RBX
MOV EAX,EDX
{$ELSE}
PUSH EBX
MOV EAX,1
CPUID
POP EBX
MOV EAX,EDX
{$ENDIF}
end;
function CPU_FeaturesECX: Integer; assembler;
asm
{$IFDEF CPU64}
PUSH RBX
MOV EAX,1
CPUID
POP RBX
MOV EAX,ECX
{$ELSE}
PUSH EBX
MOV EAX,1
CPUID
POP EBX
MOV EAX,EDX
{$ENDIF}
end;
{$IFDEF CPU64}
function CPU_DetectFeaturesEDX(B:Byte):boolean; assembler;
asm
PUSH RBX
MOV R8B,CL
MOV EAX,1
CPUID
MOV EAX,EDX
MOV CL,R8B
SHR EAX,CL
AND EAX,1
POP RBX
end;
{$ELSE}
function CPU_DetectFeaturesEDX(B:Byte):boolean;
begin
Result := false;
End;
{asm
PUSH EBX
MOV BL,CL
MOV EAX,1
CPUID
MOV EAX,EDX
MOV CL,BL
SHR EAX,CL
AND EAX,1
POP EBX
end; }
{$ENDIF}
function CPU_DetectFeaturesECX(B:Byte):boolean; assembler;
asm
{$IFDEF CPU64}
PUSH RBX
MOV R8B,CL
MOV EAX,1
CPUID
MOV EAX,ECX
MOV CL,R8B
SHR EAX,CL
AND EAX,1
POP RBX
{$ELSE}
PUSH EBX
MOV BL ,CL
MOV EAX,1
CPUID
MOV EAX,ECX
MOV CL,BL
SHR EAX,CL
AND EAX,1
POP EBX
{$ENDIF}
end;
function CPU_ExtensionsAvailable: Boolean; assembler;
asm
{$IFDEF CPU64}
PUSH RBX
MOV @Result, True
MOV EAX, $80000000
CPUID
CMP EAX, $80000000
JBE @NOEXTENSION
JMP @EXIT
@NOEXTENSION:
MOV @Result, False
@EXIT:
POP RBX
{$ELSE}
PUSH EBX
MOV @Result, True
MOV EAX, $80000000
CPUID
CMP EAX, $80000000
JBE @NOEXTENSION
JMP @EXIT
@NOEXTENSION:
MOV @Result, False
@EXIT:
POP EBX
{$ENDIF}
end;
function CPU_DetectExtensionFeaturesECX(B:Byte):boolean; assembler;
asm
{$IFDEF CPU64}
PUSH RBX
MOV R8B,CL
MOV EAX,$80000001
CPUID
MOV EAX,ECX
MOV CL,R8B
SHR EAX,CL
AND EAX,1
POP RBX
{$ELSE}
PUSH EBX
MOV BL ,CL
MOV EAX,$80000001
CPUID
MOV EAX,ECX
MOV CL,BL
SHR EAX,CL
AND EAX,1
POP EBX
{$ENDIF}
end;
function CPU_DetectExtensionFeaturesEDX(B:Byte):boolean; assembler;
asm
{$IFDEF CPU64}
PUSH RBX
MOV R8B,CL
MOV EAX,$80000001
CPUID
MOV EAX,EDX
MOV CL,R8B
SHR EAX,CL
AND EAX,1
POP RBX
{$ELSE}
PUSH EBX
MOV BL,CL
MOV EAX,$80000001
CPUID
MOV EAX,EDX
MOV CL,BL
SHR EAX,CL
AND EAX,1
POP EBX
{$ENDIF}
end;
function CPU_FeaturesBitsEBX: Integer; assembler;
asm
{$IFDEF CPU64}
PUSH RBX
MOV EAX, $00000007
CPUID
MOV EAX,EBX
POP RBX
{$ELSE}
PUSH EBX
MOV EAX, $80000001
CPUID
POP EBX
MOV EAX,EDX
{$ENDIF}
end;
function CPU_LogicalProcessorCount: Integer; assembler;
asm
{$IFDEF CPU64}
PUSH RBX
MOV EAX, 1
CPUID
AND EBX, 00FF0000h
MOV EAX, EBX
SHR EAX, 16
POP RBX
{$ELSE}
PUSH EBX
MOV EAX, 1
CPUID
AND EBX, 00FF0000h
MOV EAX, EBX
SHR EAX, 16
POP EBX
{$ENDIF}
end;
function CPU_Brand: String;
var s:array[0..48] of ansichar;
begin
{$IFDEF CPU64}
//fillchar(s{%H-},sizeof(s),0);
asm
PUSH RBX
mov eax,080000000h
CPUID
cmp eax,080000004h
jb @@endbrandstr
//get first name part
mov eax,080000002h
CPUID
mov longword(s[0]),eax
mov longword(s[4]),ebx
mov longword(s[8]),ecx
mov longword(s[12]),edx
//get second name part
mov eax,080000003h
CPUID
mov longword(s[16]),eax
mov longword(s[20]),ebx
mov longword(s[24]),ecx
mov longword(s[28]),edx
//get third name part
mov eax,080000004h
CPUID
mov longword(s[32]),eax
mov longword(s[36]),ebx
mov longword(s[40]),ecx
mov longword(s[44]),edx
@@endbrandstr:
POP RBX
end;
{$ENDIF}
{$IFDEF CPU32}
asm
//check if necessary extended CPUID calls are
//supported, if not return null string
push ebx
mov eax,080000000h
CPUID
cmp eax,080000004h
jb @@endbrandstr
//get first name part
mov eax,080000002h
CPUID
mov DWord(s[0]),eax
mov DWord(s[4]),ebx
mov DWord(s[8]),ecx
mov DWord(s[12]),edx
//get second name part
mov eax,080000003h
CPUID
mov DWord(s[16]),eax
mov DWord(s[20]),ebx
mov DWord(s[24]),ecx
mov DWord(s[28]),edx
//get third name part
mov eax,080000004h
CPUID
mov DWord(s[32]),eax
mov DWord(s[36]),ebx
mov DWord(s[40]),ecx
mov DWord(s[44]),edx
@@endbrandstr:
pop ebx
end;
{$ENDIF}
result:=string(s);
end;
function CPU_VendorID: String;
var
s : array[0..11] of ansichar;
begin
{$IFDEF CPU64}
asm
PUSH RBX
mov eax,080000000h
CPUID
mov longword(s[0]),ebx
mov longword(s[4]),edx
mov longword(s[8]),ecx
POP RBX
end;
{$ENDIF}
{$IFDEF CPU32}
asm
push ebx
mov eax, 080000000h
CPUID
mov DWord(s[0]),ebx
mov DWord(s[4]),edx
mov DWord(s[8]),ecx
pop ebx
end;
{$ENDIF}
result:= string(s);
end;
function CPU_FeaturesAsString : String;
begin
result:='';
if not CPUID_Available then Exit;
{ciMMX , ciEMMX, ciSSE , ciSSE2 , ci3DNow , ci3DNowExt}
if CPU_HasFeature(cf3DNow) then result:=result+'3DNow';
if (result<>'') then result:=result+' / ';
if CPU_HasFeature(cf3DNowExt) then result:=result+'3DNowExt';
if (result<>'') then result:=result+' / ';
if CPU_HasFeature(cfMMX) then result:=result+'MMX';
if (result<>'') then result:=result+' / ';
if CPU_HasFeature(cfEMMX) then result:=result+'EMMX';
if (result<>'') then result:=result+' / ';
if CPU_HasFeature(cfSSE) then result:=result+'SSE';
if (result<>'') then result:=result+' / ';
if CPU_HasFeature(cfSSE2) then result:=result+'SSE2';
if (result<>'') then result:=result+' / ';
if CPU_HasFeature(cfSSE3) then result:=result+'SSE3';
if (result<>'') then result:=result+' / ';
if CPU_HasFeature(cfSSSE3) then result:=result+'SSSE3';
if (result<>'') then result:=result+' / ';
if CPU_HasFeature(cfSSE41) then result:=result+'SSE4.1';
if (result<>'') then result:=result+' / ';
if CPU_HasFeature(cfSSE42) then result:=result+'SSE4.2';
if (result<>'') then result:=result+' / ';
if CPU_HasFeature(cfSSE4A) then result:=result+'SSE4A';
if (result<>'') then result:=result+' / ';
if CPU_HasFeature(cfAVX) then result:=result+'AVX';
if (result<>'') then result:=result+' / ';
if CPU_HasFeature(cfFMA3) then result:=result+'FMA3';
if (result<>'') then result:=result+' / ';
if CPU_HasFeature(cfFMA4) then result:=result+'FMA4';
end;
function CPU_StepId:Integer;
begin
result:= CPU_Signature And $0000000F;// and $0F;
end;
function CPU_Model:Integer;
begin
result:= (CPU_Signature And $000000F0) Shr 4; //shr 4 and $0F;
end;
function CPU_ExtModel:Integer;
begin
// if CPU_Model >= 15 then
result:= (CPU_Signature And $000F0000) Shr 16; //shr 16 and $0F;
// else
// result:=0;
end;
function CPU_Familly:Integer;
begin
result:= (CPU_Signature And $00000F00) Shr 8; // shr 8 and $0F;
end;
function CPU_ExtFamilly:Integer;
begin
if CPU_Familly >= 15 then
result:= (CPU_Signature And $0FF00000) Shr 20 //shr 20 and $FF
else
result:=0;
end;
function CPU_Type:Integer;
begin
result:= (CPU_Signature And $00003000) Shr 12; // shr 12 and $03;
end;
function CPU_HasFeature(const InstructionSet: TBZCPUFeaturesSet): Boolean;
// Must be implemented for each target CPU on which specific functions rely
begin
Result := False;
if not CPUID_Available then Exit; // no CPUID available
if CPU_Signature shr 8 and $0F < 5 then Exit; // not a Pentium class
case InstructionSet of
cf3DNow :
begin
if (not CPU_ExtensionsAvailable) or (not CPU_DetectExtensionFeaturesEDX(30)) then Exit;
end;
cf3DNowExt :
begin
if (not CPU_ExtensionsAvailable) or (not CPU_DetectExtensionFeaturesEDX(31)) then Exit;
end;
cfEMMX:
begin
// check for SSE, necessary for Intel CPUs because they don't implement the
// extended info
if (not(CPU_DetectFeaturesEDX(25)) and
(not CPU_ExtensionsAvailable) or (not CPU_DetectExtensionFeaturesEDX(22))) then Exit;
end;
cfMMX :
begin
if (not CPU_DetectFeaturesEDX(23)) then exit;//CPU_DetectExtensionFeaturesEDX(23)) then Exit; // (not CPU_ExtensionsAvailable or (
end;
cfSSE :
begin
if (not CPU_DetectFeaturesEDX(25)) then exit;
end;
cfSSE2 :
begin
if (not CPU_DetectFeaturesEDX(26)) then exit;
end;
cfSSE3 :
begin
if (not CPU_ExtensionsAvailable) or (not CPU_DetectExtensionFeaturesECX(0)) then exit;
end;
cfSSSE3 :
begin
if (not CPU_ExtensionsAvailable) or(not CPU_DetectExtensionFeaturesECX(9)) then exit;
end;
cfSSE41 :
begin
if (not CPU_ExtensionsAvailable) or (not CPU_DetectExtensionFeaturesECX(19)) then exit;
end;
cfSSE42 :
begin
if (not CPU_ExtensionsAvailable) or (not CPU_DetectExtensionFeaturesECX(20)) then exit;
end;
cfSSE4A :
begin
if (not CPU_ExtensionsAvailable) or (not CPU_DetectExtensionFeaturesECX(6)) then exit;
end;
cfAVX:
begin
if (not CPU_ExtensionsAvailable) or not(CPU_DetectFeaturesECX(28)) then exit;
end;
cfFMA3 :
begin
if (not CPU_ExtensionsAvailable) or(not CPU_DetectExtensionFeaturesECX(12)) then exit;
end;
cfFMA4 :
begin
if (not CPU_ExtensionsAvailable) or (not CPU_DetectExtensionFeaturesECX(16)) then exit;
end;
else
Exit; // return -> instruction set not supported
end;
Result := True;
end;
function CPU_Support_RDRAND:Boolean;
begin
result:=false;
if not CPUID_Available then Exit;
result:= CPU_DetectFeaturesEDX(30);// ((CPU_FeaturesEDX and $40000000) = $40000000);
end;
function CPU_Support_RDSEED:Boolean;
begin
result:=false;
if not CPUID_Available then Exit;
result:= ((CPU_FeaturesBitsEBX and $40000) = $40000);
end;
procedure getCPUInfos(var ret :TBZCPUInfos);
var
// ret:TBZCPUInfos;
CPUFeaturesData : TBZCPUFeatures;
i : TBZCPUFeaturesSet;
begin
CPUFeaturesData := [];
if CPUID_Available then
begin
for I := Low(TBZCPUFeaturesSet) to High(TBZCPUFeaturesSet) do
if CPU_HasFeature(I) then CPUFeaturesData := CPUFeaturesData + [I];
with Ret do
begin
Vendor := CPU_VendorID;
BrandName := CPU_Brand;
//FamillyAsString := '-';//getCPUFamillyAsString;
Features := CPUFeaturesData;
FeaturesAsString := CPU_FeaturesAsString;
Signature := CPU_Signature;
ProcessorType := CPU_Type;
Model:=CPU_Model;
Familly:=CPU_Familly;
ExtModel:=CPU_ExtModel;
ExtFamilly:=CPU_ExtFamilly;
Stepping :=CPU_StepID;
Speed := round(CPU_Speed) ;
LogicalProcessors :=CPU_LogicalProcessorCount;
end;
end
else
begin
with Ret do
begin
Vendor := 'n/a';
BrandName := 'n/a';
Features := CPUFeaturesData;
Signature := 0;
ProcessorType := 0;
Model:= 0;
Familly:= 0;
ExtModel:= 0;
ExtFamilly:= 0;
Stepping := 0;
Speed :=round(CPU_Speed);
LogicalProcessors :=1;
end;
end;
// result:=ret;
end;
{ Returns time in milisecond from application start.}
function BZStartTime: Double;
{$IFDEF WINDOWS}
var
SystemTime: TSystemTime;
begin
GetLocalTime({%H-}SystemTime);
with SystemTime do
Result :=(wHour * (MinsPerHour * SecsPerMin * MSecsPerSec) +
wMinute * (SecsPerMin * MSecsPerSec) +
wSecond * MSecsPerSec +
wMilliSeconds) - vBZStartTime;
// Hack to fix time precession
if Result - vLastTime = 0 then
begin
Result := Result + vDeltaMilliSecond;
vDeltaMilliSecond := vDeltaMilliSecond + 0.1;
end
else begin
vLastTime := Result;
vDeltaMilliSecond := 0.1;
end;
end;
{$ENDIF}
{$IFDEF UNIX}
var
tz: timeval;
begin
fpgettimeofday(@tz, nil);
Result := tz.tv_sec - vBZStartTime;
Result := Result * 1000000;
Result := Result + tz.tv_usec;
// Delphi for UNIX variant (for future ;)
//var
// T: TTime_T;
// TV: TTimeVal;
// UT: TUnixTime;
//begin
// gettimeofday(TV, nil);
// T := TV.tv_sec;
// localtime_r(@T, UT);
// with UT do
// Result := (tm_hour * (MinsPerHour * SecsPerMin * MSecsPerSec) +
// tm_min * (SecsPerMin * MSecsPerSec) +
// tm_sec * MSecsPerSec +
// tv_usec div 1000) - vGLSStartTime;
end;
{$ENDIF}
{$IFDEF UNIX}
var
vProgStartSecond: int64;
procedure Init_vProgStartSecond;
//var
// tz: timeval;
//begin
// fpgettimeofday(@tz, nil);
// val := tz.tv_sec - vProgStartSecond;
// val := val * 1000000;
// val := val + tz.tv_usec;
//end;
var
tp: timespec; // timespec record tv_sec seconds tv_nsec nanoseconds
begin
//clock_gettime(CLOCK_MONOTONIC, @tp); // orig
clock_gettime(CLOCK_MONOTONIC_RAW, @tp);
// multiplier les secondes par 1000 pour pouvoir y ajouter les millisec,
// multiplier les secondes par 1000000 pour pouvoir y ajouter les microsec,
// multiplier les secondes par 1000000000 pour pouvoir y ajouter les nanosec
// du coup le "result" sera le nombre de milli-secondes depuis le démarrage de la machine
vProgStartSecond := (Int64(tp.tv_sec) * 1000000) + int64(tp.tv_nsec); //
end;
{$ENDIF}
procedure QueryPerformanceCounter(var val: Int64);
{$IFDEF WINDOWS}
begin
Windows.QueryPerformanceCounter(val);
end;
{$ENDIF}
{$IFDEF UNIX}
// NE FONCTIONNE PAS ET FAIT RALENTIR LE TBZCADENCER !!! A VOIR POURQUOI
//var
// tp: timespec; // timespec record tv_sec seconds tv_nsec nanoseconds
//begin
// clock_gettime(CLOCK_MONOTONIC, @tp); // orig
// //clock_gettime(CLOCK_MONOTONIC_RAW, @tp);
// val := ((tp.tv_sec - vProgStartSecond) * 1000000) + tp.tv_nsec; // valeur en milli secondes
//end;
var
tz: timeval;
begin
fpgettimeofday(@tz, nil);
val := tz.tv_sec - vProgStartSecond;
val := val * 1000000;
val := val + tz.tv_usec;
end;
{$ENDIF}
function QueryPerformanceFrequency(var val: Int64): Boolean;
{$IFDEF WINDOWS}
begin
Result := Boolean(Windows.QueryPerformanceFrequency(val));
end;
{$ENDIF}
{$IFDEF UNIX}
// https://stackoverflow.com/questions/13927317/what-is-free-pascals-equivalent-of-delphis-tstopwatch
//Var
// r : TBaseMesure;
//begin
//FIsHighResolution := (clock_getres(CLOCK_MONOTONIC,@r) = 0);
// FIsHighResolution := FIsHighResolution and (r.tv_nsec <> 0);
// if (r.tv_nsec <> 0) then
// FFrequency := C_BILLION div r.tv_nsec;
//end;
begin
val := 1000000;
Result := True;
end;
{$ENDIF}
function GetPlatformInfo: TBZPlatformInfo;
var
{$IFDEF WINDOWS}
OSVersionInfo : windows.TOSVersionInfo;
//LPOSVERSIONINFOA; //
{$ENDIF}
{$IFDEF UNIX}
{$IFNDEF DARWIN}
ReleseList: TStringList;
{$ENDIF}
str: String;
{$IFDEF DARWIN}
Documento: TXMLDocument;
Child: TDOMNode;
i:integer;
{$ENDIF}
{$ENDIF}
begin
{$IFDEF WINDOWS}
With Result do
begin
OSVersionInfo.dwOSVersionInfoSize := sizeof(TOSVersionInfo);
if not windows.GetVersionEx(OSVersionInfo) then {%H-}Exit;
Minor := OSVersionInfo.DwMinorVersion;
Major := OSVersionInfo.DwMajorVersion;
Revision := OSVersionInfo.dwBuildNumber;
PlatformId := OSVersionInfo.dwPlatformId;
Version := InttoStr(OSVersionInfo.DwMajorVersion)+'.'+InttoStr(OSVersionInfo.DwMinorVersion)
+' Build : '+InttoStr(OSVersionInfo.dwBuildNumber);
end;
{$ENDIF}
{$IFDEF UNIX}
{$IFNDEF DARWIN}
ReleseList := TStringList.Create;
With Result do
begin
ID := '';
Version := '';
CodeName := '';
Description := '';
Major:=0;
Minor:=0;
Revision:=0;;
PlatformId :=0;
ProductBuildVersion:='';
End;
with Result,ReleseList do
begin
if FileExists('/etc/lsb-release') then
LoadFromFile('/etc/lsb-release')
else Exit;
ID := Values['DISTRIB_ID'];
Version := Values['DISTRIB_RELEASE'];
CodeName := Values['DISTRIB_CODENAME'];
Description := Values['DISTRIB_DESCRIPTION'];
Destroy;
end;
{$ELSE}
if FileExists('System/Library/CoreServices/ServerVersion.plist') then
ReadXMLFile(Documento, 'System/Library/CoreServices/ServerVersion.plist')
else Exit;
Child := Documento.DocumentElement.FirstChild;
if Assigned(Child) then
begin
with Child.ChildNodes do
try
for i := 0 to (Count - 1) do
begin
if Item[i].FirstChild.NodeValue='ProductBuildVersion' then
Result.ProductBuildVersion:=Item[i].NextSibling.FirstChild.NodeValue;
if Item[i].FirstChild.NodeValue='ProductName' then
Result.ID:=Item[i].NextSibling.FirstChild.NodeValue;
if Item[i].FirstChild.NodeValue='ProductVersion' then
Result.Version:=Item[i].NextSibling.FirstChild.NodeValue;
end;
finally
Free;
end;
end;
{$ENDIF}
//Major.Minor.Revision
str:=Result.Version;
if str='' then Exit;
Result.Major:=StrtoInt( Utf8Copy(str, 1, Utf8Pos('.',str)-1) );
Utf8Delete(str, 1, Utf8Pos('.', str) );
//10.04
if Utf8Pos('.', str) = 0 then
begin
Result.Minor:=StrtoInt( Utf8Copy(str, 1, Utf8Length(str)) );
Result.Revision:=0;
end
else
//10.6.5
begin
Result.Minor:=StrtoInt( Utf8Copy(str, 1, Utf8Pos('.',str)-1) );
Utf8Delete(str, 1, Utf8Pos('.', str) );
Result.Revision:=StrtoInt( Utf8Copy(str, 1, Utf8Length(str)) );
end;
{$ENDIF}
end;
function GetplatformVersion : TBZPlatformVersion;
{$IFDEF Unix}
var
i: integer;
const
VersStr : array[TBZPlatformVersion] of string = (
'', '', '', '', '', '',
'', '', '', '', '', '', '',
'',
'Arc',
'Debian',
'openSUSE',
'Fedora',
'Gentoo',
'Mandriva',
'RedHat',
'TurboUNIX',
'Ubuntu',
'Xandros',
'Oracle',
'Mac OS X'
);
{$ENDIF}
begin
Result := pvUnknown;
{$IFDEF WINDOWS}
with GetPlatformInfo do
begin
if Version='' then Exit;
case Major of
0..2: Result := pvUnknown;
3: Result := pvWinNT3; // Windows NT 3
4: case Minor of
0: if PlatformId = VER_PLATFORM_WIN32_NT
then Result := pvWinNT4 // Windows NT 4
else Result := pvWin95; // Windows 95
10: Result := pvWin98; // Windows 98
90: Result := pvWinME; // Windows ME
end;
5: case Minor of
0: Result := pvWin2000; // Windows 2000
1: Result := pvWinXP; // Windows XP
2: Result := pvWin2003; // Windows 2003
end;
6: case Minor of
0: Result := pvWinVista; // Windows Vista
1: Result := pvWinSeven; // Windows Seven
2: Result := pvWin2008; // Windows 2008
3..4: Result := pvUnknown;
end;
7..8: Result := pvWin8;
9..10: Result := pvWin10;
end;
end;
{$ENDIF}
{$IFDEF UNIX}
with GetPlatformInfo do
begin
if Version='' then Exit;
For i:= 13 to Length(VersStr)-1 do
if ID=VersStr[TBZPlatformVersion(i)] then
Result := TBZPlatformVersion(i);
end;
{$ENDIF}
end;
function GetplatformVersionAsString : string;
const
VersStr : array[TBZPlatformVersion] of string = (
'Inconnu',
'Windows 95',
'Windows 98',
'Windows ME',
'Windows NT 3',
'Windows NT 4',
'Windows 2000',
'Windows XP',
'Windows 2003',
'Windows Vista',
'Windows Seven',
'Windows 2008',
'Windows 8',
'Windows 10',
'UNIX Arc',
'UNIX Debian',
'UNIX openSUSE',
'UNIX Fedora',
'UNIX Gentoo',
'UNIX Mandriva',
'UNIX RedHat',
'UNIX TurboUNIX',
'UNIX Ubuntu',
'UNIX Xandros',
'UNIX Oracle',
'Apple MacOSX');
begin
Result := VersStr[GetplatformVersion]+' ( Version : '+ GetPlatformInfo.Version +' )';
end;
function GetDeviceCapabilities: TBZDeviceCapabilities;
{$IFDEF WINDOWS}
var
Device: HDC;
begin
Device := GetDC(0);
try
result.Xdpi := GetDeviceCaps(Device, LOGPIXELSX);
result.Ydpi := GetDeviceCaps(Device, LOGPIXELSY);
result.Depth := GetDeviceCaps(Device, BITSPIXEL);
result.NumColors := GetDeviceCaps(Device, NUMCOLORS);
finally
ReleaseDC(0, Device);
end;
end;
{$ELSE}
{$IFDEF X11_SUPPORT}
var
dpy: PDisplay;
begin
dpy := XOpenDisplay(nil);
Result.Depth := DefaultDepth(dpy, DefaultScreen(dpy));
XCloseDisplay(dpy);
Result.Xdpi := 96;
Result.Ydpi := 96;
Result.NumColors := 1;
end;
{$ELSE}
begin
{$MESSAGE Warn 'Needs to be implemented'}
end;
{$ENDIF}
{$ENDIF}
function GetDeviceCapabilitiesAsString: String;
Var
s:String;
begin
s:='';
with GetDeviceCapabilities() do
begin
s:= 'Resolution : '+ Inttostr(Screen.Width)+'x'+Inttostr(Screen.Height)+#13#10;
s:=s+'DPI : '+ Inttostr(Xdpi) +'x'+inttostr(Ydpi)+#13#10;
s:=s+'Format : '+ Inttostr(Depth)+' Bits'+#13#10;
//s:=s+'Couleurs : '+ Inttostr(NumColors);
end;
result:=s;
end;
function GetDeviceLogicalPixelsX: Integer;
begin
result := GetDeviceCapabilities.Xdpi;
end;
function GetCurrentColorDepth: Integer;
begin
result := GetDeviceCapabilities.Depth;
end;
{$IFDEF WINDOWS}
type
MEMORYSTATUSEX = record
dwLength : DWORD;
dwMemoryLoad : DWORD;
ullTotalPhys : uint64;
ullAvailPhys : uint64;
ullTotalPageFile : uint64;
ullAvailPageFile : uint64;
ullTotalVirtual : uint64;
ullAvailVirtual : uint64;
ullAvailExtendedVirtual : uint64;
end;
function GlobalMemoryStatusEx(var Buffer: MEMORYSTATUSEX): BOOL; stdcall; external 'kernel32' name 'GlobalMemoryStatusEx';
{$ENDIF}
function GetMemoryStatus: TBZMemoryStatus;
{$IFDEF WINDOWS}
//type
// TGlobalMemoryStatusEx = procedure(var lpBuffer: TMemoryStatusEx); stdcall;
var
ms : TMemoryStatus;
MS_Ex: MemoryStatusEx;
begin
//Result.dwLength := SizeOf(Result);
If GetplatformVersion in [pvUnknown, pvWin95, pvWin98, pvWinME, pvWinNT3, pvWinNT4, pvWin2000 ] then
Begin
ms.dwLength := SizeOf(ms);
GlobalMemoryStatus({%H-}ms);
//Result.dwMemoryLoad := ms.dwMemoryLoad;
Result.TotalPhys := ms.dwTotalPhys;
Result.AvailPhys := ms.dwAvailPhys;
Result.TotalPageFile := ms.dwTotalPageFile;
Result.AvailPageFile := ms.dwAvailPageFile;
Result.TotalVirtual := ms.dwTotalVirtual;
Result.AvailVirtual := ms.dwAvailVirtual;
End
Else
Begin
FillChar({%H-}MS_Ex, SizeOf(MemoryStatusEx), 0);
MS_Ex.dwLength := SizeOf(MemoryStatusEx);
if GlobalMemoryStatusEx(MS_Ex) then
begin
Result.TotalPhys := MS_Ex.ullTotalPhys;
Result.AvailPhys := MS_Ex.ullAvailPhys;
Result.TotalPageFile := MS_Ex.ullTotalPageFile;
Result.AvailPageFile := MS_Ex.ullAvailPageFile;
Result.TotalVirtual := MS_Ex.ullTotalVirtual;
Result.AvailVirtual := MS_Ex.ullAvailVirtual;
End;
End;
End;
{$ELSE}
(* -----><------
procedure Split(const Delimiter: Char; Input: string; const Strings: TStrings);
begin
Assert(Assigned(Strings)) ;
Strings.Clear;
Strings.Delimiter := Delimiter;
Strings.DelimitedText := Input;
end;
procedure GetMemory(var st: TStringList);
var
s1, s2: string;
stTmp: TStringList;
begin
st.Clear;
st.LoadFromFile('/proc/meminfo');
if st.Count > 0 then
begin
stTmp:= TStringList.Create;
Split(' ', st[0], stTmp);
s1 := stTmp[1];
stTmp.Clear;
Split(' ', st[1], stTmp);
s2 := stTmp[1];
stTmp.Free;
st.Clear;
st.Add(s1); // total
st.Add(s2); // free
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
var
infototal, infolibre : double;
stList: TStringList;
s1 : string = ' Mémoire physique disponible : ';
s2 : string = ' octets sur ';
s3 : string = ' octets totaux, soit ';
s4 : string = ' % libre. ';
begin
stList:= TStringList.Create;
GetMemory(stList);
if stList.Count > 0 then
begin
infototal := StrToFloat(stList[0]);
infolibre := StrToFloat(stList[1]);
stb.SimpleText := s1 + Format('%.0n', [infolibre]) + s2 + Format('%.0n', [infototal])
+ s3 + FloatToStrF(((100 * infolibre) / infototal), ffFixed, 3, 0) + s4;
end;
stList.Free;
end;
*)
Begin
{$MESSAGE Warn 'Needs to be implemented'}
end;
{$ENDIF}
function GetApplicationFileName : string;
var
path: UTF8String;
begin
path := ExtractFileName(ParamStrUTF8(0));
result:=path;
end;
function GetApplicationPath : string;
//var
// path: UTF8String;
//begin
// path := ExtractFilePath(ParamStrUTF8(0));
// path := IncludeTrailingPathDelimiter(path);
// result:=path;
//end;
begin
{$ifdef darwin}
Result := Copy(Application.ExeName, 1, Pos(ApplicationName + '.app', Application.ExeName) - 1);
{$else}
Result := Application.Location;
{$endif}
Result := IncludeTrailingPathDelimiter(Result);
end;
function GetTempFolderPath : string;
{$IFDEF WINDOWS}
var lng: DWORD; thePath: string;
begin
SetLength(thePath{%H-}, MAX_PATH);
lng := GetTempPath(MAX_PATH, PChar(thePath));
SetLength(thePath, lng);
result := thePath;
end;
{$ELSE}
begin
result:=sysutils.GetTempDir;
end;
{$ENDIF}
procedure ShowHTMLUrl(Url: string);
begin
{$IFDEF WINDOWS}
ShellExecute(0, 'open', PChar(Url), nil, nil, SW_SHOW);
{$ENDIF}
{$IFDEF UNIX}
fpSystem(PChar('env xdg-open ' + Url));
{$ENDIF}
end;
function GetSystemLanguage: string;
// *** methode independante de la plateform pour lire la langue de l'interface de l'utilisateur ***
// *** platform-independent method to read the language of the user interface ***
var
l, fbl: string;
{$IFDEF LCLCarbon}
theLocaleRef: CFLocaleRef;
locale: CFStringRef;
buffer: StringPtr;
bufferSize: CFIndex;
encoding: CFStringEncoding;
success: boolean;
{$ENDIF}
begin
{$IFDEF LCLCarbon}
theLocaleRef := CFLocaleCopyCurrent;
locale := CFLocaleGetIdentifier(theLocaleRef);
encoding := 0;
bufferSize := 256;
buffer := new(StringPtr);
success := CFStringGetPascalString(locale, buffer, bufferSize, encoding);
if success then
l := string(buffer^)
else
l := '';
fbl := Copy(l, 1, 2);
dispose(buffer);
{$ELSE}
{$IFDEF LINUX}
fbl := Copy(GetEnvironmentVariableUTF8('LC_CTYPE'), 1, 2);
if fbl='' then fbl := Copy(GetEnvironmentVariableUTF8('LANG'), 1, 2);
if fbl='' then fbl:= cDefaultLanguage;
{$ELSE}
fbl := '';
l := '';
GetLanguageIDs(l, fbl);
{$ENDIF}
{$ENDIF}
Result := fbl;
end;
function GetDecimalSeparator: Char;
begin
Result :=DefaultFormatSettings.DecimalSeparator;
end;
procedure SetDecimalSeparator(AValue: Char);
begin
DefaultFormatSettings.DecimalSeparator := AValue;
end;
function GetEnvironmentVariable(const Name: string): string;
begin
Result := GetEnvironmentVariableUTF8(Name);
end;
function FixPathDelimiter(S: string):String;
var
I: Integer;
begin
Result := S;
for I := Length(Result) downto 1 do
begin
if (Result[I] = '/') or (Result[I] = '\') then
Result[I] := PathDelim;
End;
end;
function RemoveFileNamePathDelimiter(S : String) : String;
var
I: Integer;
Ext : String;
begin
Ext := ExtractFileExt(S);
S := ExtractFileNameWithoutExt(S);
Result := '';
for I := 1 to Length(S) do
begin
if (S[I] <> '/') or (S[I] <> '\') then Result := Result + S[I];
End;
Result := Result + Ext;
end;
function IsDirectoryWriteable(const AName: string): Boolean;
var
LFileName: String;
{$IFDEF MSWINDOWS}
LHandle: THandle;
{$ENDIF}
begin
LFileName := IncludeTrailingPathDelimiter(AName) + 'chk.tmp';
{$IFDEF MSWINDOWS}
LHandle := CreateFile(PChar(LFileName), GENERIC_READ or GENERIC_WRITE, 0, nil,
CREATE_NEW, FILE_ATTRIBUTE_TEMPORARY or FILE_FLAG_DELETE_ON_CLOSE, 0);
Result := LHandle <> INVALID_HANDLE_VALUE;
if Result then
CloseHandle(LHandle);
{$ELSE}
Result := fpAccess(PChar(LFileName), W_OK) <> 0;
{$ENDIF}
end;
// fonction sortie de BZUtils pour eviter une double référence dans l'implementation
function FormatByteSize(ABytes: Int64): String;
const
suffix : array[0..6] of String = ('b', 'Kb', 'Mb', 'Go', 'To', 'Po', 'Eo');
var
l : Integer;
fr : Double;
begin
l := 0;
fr := ABytes;
while fr >= 1024 do
begin
inc(l);
fr := fr / 1024;
end;
if fr >= 1000 then // ensures eg. 1022 MB will show 0.99 GB
begin
inc(l);
fr := fr / 1024;
end;
if l > High(suffix) then
Result := rsTooLarge
else
Result := Format('%f %s', [fr, suffix[l]]);
end;
function GetCurrentFreeDiskSpace : String;
begin
Result := FormatByteSize(DiskFree(0));
end;
function GetCurrentDiskSize : String;
begin
Result := FormatByteSize(DiskSize(0));
end;
// http://forum.lazarus.freepascal.org/index.php/topic,23171.msg138057.html#msg138057
function GetCurrentUserName: string;
{$IFDEF WINDOWS}
const
MaxLen = 256;
var
Len: DWORD;
WS: WideString;
Res: windows.BOOL;
{$ENDIF}
begin
Result := '';
{$IFDEF UNIX}
{$IF (DEFINED(LINUX)) OR (DEFINED(FREEBSD))}
//GetUsername in unit Users, fpgetuid in unit BaseUnix
Result := SysToUtf8(GetUserName(fpgetuid));
{$ELSE Linux/BSD}
Result := GetEnvironmentVariableUtf8('USER');
{$ENDIF UNIX}
{$ELSE}
{$IFDEF WINDOWS}
Len := MaxLen;
{$IFnDEF WINCE}
if Win32MajorVersion <= 4 then
begin
SetLength(Result,MaxLen);
Res := Windows.GetuserName(@Result[1], Len);
if Res then
begin
SetLength(Result,Len-1);
Result := SysToUtf8(Result);
end
else SetLength(Result,0);
end
else
{$ENDIF NOT WINCE}
begin
SetLength(WS{%H-}, MaxLen-1);
Res := Windows.GetUserNameW(@WS[1], Len);
if Res then
begin
SetLength(WS, Len - 1);
Result := Utf16ToUtf8(WS);
end
else SetLength(Result,0);
end;
{$ENDIF WINDOWS}
{$ENDIF UNIX}
end;
function GetWidgetSet: string;
begin
Result := LCLPlatformDisplayNames[WidgetSet.LCLPlatform];
// case WidgetSet.LCLPlatform of
//(* lpGtk,
// lpGtk2,
// lpGtk3,
// lpWin32,
// lpWinCE,
// lpCarbon,
// lpQT,
// lpQt5,
// lpfpGUI,
// lpNoGUI,
// lpCocoa,
// lpCustomDrawn,
// lpMUI *)
// lpGtk: Result := WIDGETSET_GTK;
// lpGtk2: Result := WIDGETSET_GTK2;
// lpWin32: Result := WIDGETSET_WIN;
// lpWinCE: Result := WIDGETSET_WINCE;
// lpCarbon:Result := WIDGETSET_CARBON;
// lpQT: Result := WIDGETSET_QT;
// lpfpGUI: Result := WIDGETSET_fpGUI;
// else
// Result:=WIDGETSET_OTHER;
// end;
end;
Function GetCompilerInfo: String;
begin
Result := 'FPC '+{$I %FPCVERSION%};
end;
Function GetLCLVersion: String;
begin
Result := 'LCL '+lcl_version;
end;
Function GetCompiledDate: String;
Begin
Result:= {$I %DATE%};
End;
Function GetCompiledTime: String;
Begin
Result:= {$I %TIME%};
End;
function GetMouseButtonState: TShiftState;
begin
Result := [];
if (GetKeyState(VK_LBUTTON) and $8000) <> 0 then
Include(Result, ssLeft);
if (GetKeyState(VK_MBUTTON) and $8000) <> 0 then
Include(Result, ssMiddle);
if (GetKeyState(VK_RBUTTON) and $8000) <> 0 then
Include(Result, ssRight);
end;
//==============================================================================
initialization
vBZStartTime := BZStartTime;
{$IFDEF UNIX}
Init_vProgStartSecond;
{$ENDIF}
//BZCpuInfos:=
getCPUInfos(BZCpuInfos);
//------------------------------------------------------------------------------
finalization
//==============================================================================
end.
|
{
ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi
Copyright (c) 2016, Isaque Pinheiro
All rights reserved.
GNU Lesser General Public License
Versão 3, 29 de junho de 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
A todos é permitido copiar e distribuir cópias deste documento de
licença, mas mudá-lo não é permitido.
Esta versão da GNU Lesser General Public License incorpora
os termos e condições da versão 3 da GNU General Public License
Licença, complementado pelas permissões adicionais listadas no
arquivo LICENSE na pasta principal.
}
{ @abstract(ORMBr Framework.)
@created(20 Jul 2016)
@author(Isaque Pinheiro <isaquepsp@gmail.com>)
@author(Skype : ispinheiro)
@abstract(Website : http://www.ormbr.com.br)
@abstract(Telagram : https://t.me/ormbr)
}
unit ormbr.dataset.clientdataset;
interface
uses
DB,
Rtti,
Classes,
SysUtils,
StrUtils,
DBClient,
Variants,
Generics.Collections,
/// orm
ormbr.criteria,
ormbr.dataset.adapter,
ormbr.dataset.base.adapter,
ormbr.dataset.events,
dbcbr.mapping.classes,
dbebr.factory.interfaces;
type
// Captura de eventos específicos do componente TClientDataSet
TClientDataSetEvents = class(TDataSetEvents)
private
FBeforeApplyUpdates: TRemoteEvent;
FAfterApplyUpdates: TRemoteEvent;
public
property BeforeApplyUpdates: TRemoteEvent read FBeforeApplyUpdates write FBeforeApplyUpdates;
property AfterApplyUpdates: TRemoteEvent read FAfterApplyUpdates write FAfterApplyUpdates;
end;
// Adapter TClientDataSet para controlar o Modelo e o Controle definido por:
// M - Object Model
TClientDataSetAdapter<M: class, constructor> = class(TDataSetAdapter<M>)
private
FOrmDataSet: TClientDataSet;
FClientDataSetEvents: TClientDataSetEvents;
function GetIndexFieldNames(AOrderBy: String): String;
protected
procedure DoBeforeApplyUpdates(Sender: TObject; var OwnerData: OleVariant); override;
procedure DoAfterApplyUpdates(Sender: TObject; var OwnerData: OleVariant); override;
procedure EmptyDataSetChilds; override;
procedure GetDataSetEvents; override;
procedure SetDataSetEvents; override;
procedure ApplyInserter(const MaxErros: Integer); override;
procedure ApplyUpdater(const MaxErros: Integer); override;
procedure ApplyDeleter(const MaxErros: Integer); override;
procedure ApplyInternal(const MaxErros: Integer); override;
public
constructor Create(AConnection: IDBConnection; ADataSet:
TDataSet; APageSize: Integer; AMasterObject: TObject); overload;
destructor Destroy; override;
procedure OpenIDInternal(const AID: Variant); override;
procedure OpenSQLInternal(const ASQL: string); override;
procedure OpenWhereInternal(const AWhere: string; const AOrderBy: string = ''); override;
procedure ApplyUpdates(const MaxErros: Integer); override;
procedure EmptyDataSet; override;
end;
implementation
uses
ormbr.bind,
ormbr.dataset.fields,
ormbr.core.consts,
ormbr.objects.helper,
ormbr.rtti.helper,
dbcbr.mapping.explorer;
{ TClientDataSetAdapter<M> }
constructor TClientDataSetAdapter<M>.Create(AConnection: IDBConnection;
ADataSet: TDataSet; APageSize: Integer; AMasterObject: TObject);
begin
inherited Create(AConnection, ADataSet, APageSize, AMasterObject);
// Captura o component TClientDataset da IDE passado como parâmetro
FOrmDataSet := ADataSet as TClientDataSet;
FClientDataSetEvents := TClientDataSetEvents.Create;
// Captura e guarda os eventos do dataset
GetDataSetEvents;
// Seta os eventos do ORM no dataset, para que ele sejam disparados
SetDataSetEvents;
//
if not FOrmDataSet.Active then
begin
FOrmDataSet.CreateDataSet;
FOrmDataSet.LogChanges := False;
end;
end;
destructor TClientDataSetAdapter<M>.Destroy;
begin
FOrmDataSet := nil;
FClientDataSetEvents.Free;
inherited;
end;
procedure TClientDataSetAdapter<M>.DoAfterApplyUpdates(Sender: TObject;
var OwnerData: OleVariant);
begin
if Assigned(FClientDataSetEvents.AfterApplyUpdates) then
FClientDataSetEvents.AfterApplyUpdates(Sender, OwnerData);
end;
procedure TClientDataSetAdapter<M>.DoBeforeApplyUpdates(Sender: TObject;
var OwnerData: OleVariant);
begin
if Assigned(FClientDataSetEvents.BeforeApplyUpdates) then
FClientDataSetEvents.BeforeApplyUpdates(Sender, OwnerData);
end;
procedure TClientDataSetAdapter<M>.EmptyDataSet;
begin
inherited;
FOrmDataSet.EmptyDataSet;
// Lista os registros das tabelas filhas relacionadas
EmptyDataSetChilds;
end;
procedure TClientDataSetAdapter<M>.EmptyDataSetChilds;
var
LChild: TPair<string, TDataSetBaseAdapter<M>>;
LDataSet: TClientDataSet;
begin
inherited;
if FMasterObject.Count = 0 then
Exit;
for LChild in FMasterObject do
begin
LDataSet := TClientDataSetAdapter<M>(LChild.Value).FOrmDataSet;
if LDataSet.Active then
LDataSet.EmptyDataSet;
end;
end;
procedure TClientDataSetAdapter<M>.GetDataSetEvents;
begin
inherited;
if Assigned(FOrmDataSet.BeforeApplyUpdates) then
FClientDataSetEvents.BeforeApplyUpdates := FOrmDataSet.BeforeApplyUpdates;
if Assigned(FOrmDataSet.AfterApplyUpdates) then
FClientDataSetEvents.AfterApplyUpdates := FOrmDataSet.AfterApplyUpdates;
end;
function TClientDataSetAdapter<M>.GetIndexFieldNames(AOrderBy: String): String;
var
LFields: TOrderByMapping;
LOrderBy: String;
begin
Result := '';
LOrderBy := AOrderBy;
if LOrderBy = '' then
begin
LFields := TMappingExplorer.GetMappingOrderBy(TClass(M));
if LFields <> nil then
LOrderBy := LFields.ColumnsName;
end;
if LOrderBy <> '' then
begin
LOrderBy := StringReplace(UpperCase(LOrderBy), ' ASC' , '', [rfReplaceAll]);
LOrderBy := StringReplace(UpperCase(LOrderBy), ' DESC', '', [rfReplaceAll]);
LOrderBy := StringReplace(UpperCase(LOrderBy), ',', ';', [rfReplaceAll]);
Result := LOrderBy;
end;
end;
procedure TClientDataSetAdapter<M>.OpenIDInternal(const AID: Variant);
var
LIsConnected: Boolean;
begin
FOrmDataSet.DisableControls;
DisableDataSetEvents;
LIsConnected := FConnection.IsConnected;
if not LIsConnected then
FConnection.Connect;
try
try
// Limpa os registro do dataset antes de garregar os novos dados
EmptyDataSet;
inherited;
FSession.OpenID(AID);
except
on E: Exception do
raise Exception.Create(E.Message);
end;
finally
EnableDataSetEvents;
// Define a order no dataset
FOrmDataSet.IndexFieldNames := GetIndexFieldNames('');
// Erro interno do FireDAC se no método First se o dataset estiver vazio
if not FOrmDataSet.IsEmpty then
FOrmDataSet.First;
FOrmDataSet.EnableControls;
if not LIsConnected then
FConnection.Disconnect;
end;
end;
procedure TClientDataSetAdapter<M>.OpenSQLInternal(const ASQL: string);
var
LIsConnected: Boolean;
begin
FOrmDataSet.DisableControls;
DisableDataSetEvents;
LIsConnected := FConnection.IsConnected;
if not LIsConnected then
FConnection.Connect;
try
try
// Limpa os registro do dataset antes de garregar os novos dados
EmptyDataSet;
inherited;
FSession.OpenSQL(ASQL);
except
on E: Exception do
raise Exception.Create(E.Message);
end;
finally
EnableDataSetEvents;
// Define a order no dataset
FOrmDataSet.IndexFieldNames := GetIndexFieldNames('');
// Erro interno do FireDAC se no método First se o dataset estiver vazio
if not FOrmDataSet.IsEmpty then
FOrmDataSet.First;
FOrmDataSet.EnableControls;
if not LIsConnected then
FConnection.Disconnect;
end;
end;
procedure TClientDataSetAdapter<M>.OpenWhereInternal(const AWhere, AOrderBy: string);
var
LIsConnected: Boolean;
begin
FOrmDataSet.DisableControls;
DisableDataSetEvents;
LIsConnected := FConnection.IsConnected;
if not LIsConnected then
FConnection.Connect;
try
try
// Limpa os registro do dataset antes de garregar os novos dados
EmptyDataSet;
inherited;
FSession.OpenWhere(AWhere, AOrderBy);
except
on E: Exception do
raise Exception.Create(E.Message);
end;
finally
EnableDataSetEvents;
// Define a order no dataset
FOrmDataSet.IndexFieldNames := GetIndexFieldNames(AOrderBy);
// Erro interno do FireDAC se no método First se o dataset estiver vazio
if not FOrmDataSet.IsEmpty then
FOrmDataSet.First;
FOrmDataSet.EnableControls;
if not LIsConnected then
FConnection.Disconnect;
end;
end;
procedure TClientDataSetAdapter<M>.ApplyInternal(const MaxErros: Integer);
var
LDetail: TDataSetBaseAdapter<M>;
LRecnoBook: TBookmark;
LOwnerData: OleVariant;
begin
LRecnoBook := FOrmDataSet.Bookmark;
FOrmDataSet.DisableControls;
DisableDataSetEvents;
try
ApplyInserter(MaxErros);
ApplyUpdater(MaxErros);
ApplyDeleter(MaxErros);
// Executa o ApplyInternal de toda a hierarquia de dataset filho.
if FMasterObject.Count = 0 then
Exit;
for LDetail in FMasterObject.Values do
begin
// Before Apply
LDetail.DoBeforeApplyUpdates(LDetail.FOrmDataSet, LOwnerData);
LDetail.ApplyInternal(MaxErros);
// After Apply
LDetail.DoAfterApplyUpdates(LDetail.FOrmDataSet, LOwnerData);
end;
finally
FOrmDataSet.GotoBookmark(LRecnoBook);
FOrmDataSet.FreeBookmark(LRecnoBook);
FOrmDataSet.EnableControls;
EnableDataSetEvents;
end;
end;
procedure TClientDataSetAdapter<M>.ApplyDeleter(const MaxErros: Integer);
var
LFor: Integer;
begin
inherited;
// Filtar somente os registros excluídos
if FSession.DeleteList.Count = 0 then
Exit;
for LFor := 0 to FSession.DeleteList.Count -1 do
FSession.Delete(FSession.DeleteList.Items[LFor]);
end;
procedure TClientDataSetAdapter<M>.ApplyInserter(const MaxErros: Integer);
var
LPrimaryKey: TPrimaryKeyColumnsMapping;
LColumn: TColumnMapping;
begin
inherited;
// Filtar somente os registros inseridos
FOrmDataSet.Filter := cInternalField + '=' + IntToStr(Integer(dsInsert));
FOrmDataSet.Filtered := True;
if not FOrmDataSet.IsEmpty then
FOrmDataSet.First;
try
while FOrmDataSet.RecordCount > 0 do
begin
// Append/Insert
if TDataSetState(FOrmDataSet.Fields[FInternalIndex].AsInteger) in [dsInsert] then
begin
// Ao passar como parametro a propriedade Current, e disparado o metodo
// que atualiza a var FCurrentInternal, para ser usada abaixo.
FSession.Insert(Current);
FOrmDataSet.Edit;
if FSession.ExistSequence then
begin
LPrimaryKey := TMappingExplorer.GetMappingPrimaryKeyColumns(FCurrentInternal.ClassType);
if LPrimaryKey = nil then
raise Exception.Create(cMESSAGEPKNOTFOUND);
for LColumn in LPrimaryKey.Columns do
begin
FOrmDataSet.FieldByName(LColumn.ColumnName).Value :=
LColumn.ColumnProperty
.GetNullableValue(TObject(FCurrentInternal)).AsVariant;
end;
// Atualiza o valor do AutoInc nas sub tabelas
SetAutoIncValueChilds;
end;
FOrmDataSet.Fields[FInternalIndex].AsInteger := -1;
FOrmDataSet.Post;
end;
end;
finally
FOrmDataSet.Filtered := False;
FOrmDataSet.Filter := '';
end;
end;
procedure TClientDataSetAdapter<M>.ApplyUpdater(const MaxErros: Integer);
var
LProperty: TRttiProperty;
LObject: TObject;
begin
inherited;
// Filtar somente os registros modificados
FOrmDataSet.Filter := cInternalField + '=' + IntToStr(Integer(dsEdit));
FOrmDataSet.Filtered := True;
if not FOrmDataSet.IsEmpty then
FOrmDataSet.First;
try
while FOrmDataSet.RecordCount > 0 do
begin
/// Edit
if TDataSetState(FOrmDataSet.Fields[FInternalIndex].AsInteger) in [dsEdit] then
begin
if (FSession.ModifiedFields.Items[M.ClassName].Count > 0) or
(FConnection.GetDriverName in [dnMongoDB]) then
begin
LObject := M.Create;
try
TBind.Instance.SetFieldToProperty(FOrmDataSet, LObject);
FSession.Update(LObject, M.ClassName);
finally
LObject.Free;
end;
end;
FOrmDataSet.Edit;
FOrmDataSet.Fields[FInternalIndex].AsInteger := -1;
FOrmDataSet.Post;
end;
end;
finally
FOrmDataSet.Filtered := False;
FOrmDataSet.Filter := '';
end;
end;
procedure TClientDataSetAdapter<M>.ApplyUpdates(const MaxErros: Integer);
var
LOwnerData: OleVariant;
LInTransaction: Boolean;
LIsConnected: Boolean;
begin
inherited;
// Controle de transação externa, controlada pelo desenvolvedor
LInTransaction := FConnection.InTransaction;
LIsConnected := FConnection.IsConnected;
if not LIsConnected then
FConnection.Connect;
try
if not LInTransaction then
FConnection.StartTransaction;
// Before Apply
DoBeforeApplyUpdates(FOrmDataSet, LOwnerData);
try
ApplyInternal(MaxErros);
// After Apply
DoAfterApplyUpdates(FOrmDataSet, LOwnerData);
if not LInTransaction then
FConnection.Commit;
except
if not LInTransaction then
FConnection.Rollback;
raise;
end;
finally
if FSession.ModifiedFields.ContainsKey(M.ClassName) then
begin
FSession.ModifiedFields.Items[M.ClassName].Clear;
FSession.ModifiedFields.Items[M.ClassName].TrimExcess;
end;
FSession.DeleteList.Clear;
FSession.DeleteList.TrimExcess;
if not LIsConnected then
FConnection.Disconnect;
end;
end;
procedure TClientDataSetAdapter<M>.SetDataSetEvents;
begin
inherited;
FOrmDataSet.BeforeApplyUpdates := DoBeforeApplyUpdates;
FOrmDataSet.AfterApplyUpdates := DoAfterApplyUpdates;
end;
end.
|
{***************************************************************************}
{ }
{ Модуль: Вектора }
{ Описание: Операции с векторами }
{ Автор: Зверинцев Дмитрий }
{ }
{***************************************************************************}
unit Vectors;
interface
uses
SysUtils,Complex;
type
PVector = ^TVector;
TVector = record
private
Vector:array of TNumber;
len:byte;
function GetVector(j: byte): TNumber;inline;
procedure SetVector(j: byte; const Value: TNumber);
procedure SetLen(value:byte);
public
class operator Add(const A,B:TVector):PVector;overload;inline;
class operator Add(const A:TNumber;const B:TVector):PVector;overload;
class operator Add(const A:TVector;const B:TNumber):PVector;overload;
class operator Subtract(const A,B:TVector):PVector;overload;
class operator Subtract(const A:TNumber;const B:TVector):PVector;overload;
class operator Subtract(const A:TVector;const B:TNumber):PVector;overload;
class operator Multiply(const A,B:TVector):TNumber;overload;
class operator Multiply(const A:TNumber;const B:TVector):PVector;overload;
class operator Multiply(const B:TVector;const A:TNumber):PVector;overload;
class operator Divide(const A:TNumber;const B:TVector):PVector;overload;
class operator Divide(const B:TVector;const A:TNumber):PVector;overload;
class function Mul(const A,B: TVector):PVector;static;
class function VAbs(const A:TVector):TNumber;static;
function ToString(const sett:TFormat):AnsiString;
property VectorLength:Byte read len write SetLen;
property Element[j:byte]:TNumber read GetVector write SetVector;default;
procedure Clear;
end;
resourcestring
InvalidLength = 'Векторы должны иметь однинаковую длину.';
Dim_3Vector = 'Вектор не трехмерный';
implementation
{ TVector }
procedure TVector.Clear;
begin
if (len > 0) then Vector := nil;
end;
function TVector.ToString(const sett:TFormat):AnsiString;
var i:TNumber;
begin
Result := '';
for i in Vector do
result := result + i.ToString(sett) + ',';
Delete(result,length(result),1);
end;
{$REGION ' minus '}
class operator TVector.Subtract(const A,B:TVector):PVector;
var j:integer;
begin
if (A.Len = B.Len) then
begin
New(Result);
Result.VectorLength:=A.len;
for j:=0 to A.Len-1 do
Result.Vector[j] := A.Vector[j] - B.Vector[j];
end
else raise Exception.Create(InvalidLength);
end;
class operator TVector.Subtract(const A:TVector;const B:TNumber):PVector;
var j:integer;
begin
New(Result);
Result.VectorLength := A.len;
for j:=0 to A.Len-1 do
Result.Vector[j] := A.Vector[j] - B;
end;
class operator TVector.Subtract(const A:TNumber;const B:TVector):PVector;
var j:integer;
begin
New(Result);
Result.VectorLength := B.len;
for j:=0 to B.Len-1 do
Result.Vector[j] := A - B.Vector[j];
end;
{$ENDREGION}
{$REGION ' plus '}
class operator TVector.Add(const A:TVector;const B:TNumber):PVector;
var j:integer;
begin
New(Result);
Result.VectorLength := A.len;
for j:=0 to A.Len-1 do
Result.Vector[j] := B + A.Vector[j];
end;
class operator TVector.Add(const A:TNumber;const B:TVector):PVector;
var j:integer;
begin
New(Result);
Result.VectorLength := B.len;
for j:=0 to B.Len-1 do
Result.Vector[j] := A + B.Vector[j];
end;
class operator TVector.Add(const A,B:TVector):PVector;
var j:integer;
begin
if (A.Len = B.Len) then
begin
New(Result);
Result.VectorLength := A.len;
for j:=0 to A.Len-1 do
Result.Vector[j] := A.Vector[j] + B.Vector[j];
end
else raise Exception.Create(InvalidLength);
end;
{$ENDREGION}
{$REGION ' multiply '}
class operator TVector.Multiply(const B:TVector;const A:TNumber):PVector;
var j:integer;
begin
New(Result);
Result.VectorLength := B.len;
for j:=0 to B.Len-1 do
Result.Vector[j] := A * B.Vector[j];
end;
class operator TVector.Multiply(const A:TNumber;const B:TVector):PVector;
var j:integer;
begin
New(Result);
Result.VectorLength := B.len;
for j:=0 to B.Len-1 do
Result.Vector[j] := A * B.Vector[j];
end;
class operator TVector.Multiply(const A,B: TVector):TNumber;
var i:integer;
begin
if (A.Len = B.Len) then
for i:=0 to A.Len-1 do
Result := Result + (A.Vector[i] * B.Vector[i])
else raise Exception.Create(InvalidLength);
end;
//
class function TVector.Mul(const A,B:TVector): PVector;
begin
if(A.Len = B.Len)and
((A.Len = 3) and (B.Len = 3))then
begin
New(Result);
Result.VectorLength := 3;
Result.Vector[0] := (A.Vector[1]*B.Vector[2])-(A.Vector[2]*b.Vector[1]);
Result.Vector[1] := (A.Vector[2]*B.Vector[0])-(A.Vector[0]*b.Vector[2]);
Result.Vector[2] := (A.Vector[0]*B.Vector[1])-(A.Vector[1]*b.Vector[0]);
end else raise Exception.Create(Dim_3Vector);
end;
{$ENDREGION}
class operator TVector.Divide(const A:TNumber;const B:TVector):PVector;
var j:integer;
begin
New(Result);
Result.VectorLength := B.len;
for j:=0 to B.Len-1 do
Result.Vector[j] := A / B.Vector[j];
end;
class operator TVector.Divide(const B:TVector;const A:TNumber):PVector;
var j:integer;
begin
New(Result);
Result.VectorLength := B.len;
for j:=0 to B.Len-1 do
Result.Vector[j] := B.Vector[j] / A;
end;
class function TVector.VAbs(const A:TVector):TNumber;
var i:byte;
begin
for i:=0 to A.Len-1 do
result :=result + (A.Vector[i]*A.Vector[i]);
result := AbsVal(result);
Result := Sqrtn(result,2);
end;
procedure TVector.SetVector(j: byte; const Value: TNumber);
begin
self.Vector[j] := Value
end;
procedure TVector.SetLen(value:byte);
begin
SetLength(Vector,value);
Len := value
end;
function TVector.GetVector(j: byte): TNumber;
begin
Result := Vector[j]
end;
end.
|
{----------------------------------------------------------------------
DEVIUM Content Management System
Copyright (C) 2004 by DEIV Development Team.
http://www.deiv.com/
$Header: /devium/Devium\040CMS\0402/Source/ControlPanel/cpMainForm.pas,v 1.4 2004/05/06 16:00:07 paladin Exp $
------------------------------------------------------------------------}
unit cpMainForm;
interface
uses
Forms, Classes, Controls, ComCtrls, ExtCtrls, TBSkinPlus, ImgList,
ActnList, cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit,
cxDropDownEdit, TB2Item, TB2Dock, TB2Toolbar, StdCtrls, Graphics,
PluginManagerIntf, cpSitesList, SettingsIntf, RzSndMsg, IniFiles;
type
TMainForm = class(TForm)
MainPanel: TPanel;
Image1: TImage;
TopLine: TPaintBox;
CloseButton: TImage;
BottomPanel: TPanel;
ToolBarHint: TLabel;
BottomToolBar: TTBToolbar;
TBItem6: TTBItem;
TBItem2: TTBItem;
TBItem4: TTBItem;
TBItem3: TTBItem;
Panel1: TPanel;
Label1: TLabel;
SitesList: TcxComboBox;
EditSitesList: TTBToolbar;
TBItem1: TTBItem;
PluginList: TListView;
ActionList: TActionList;
EditSites: TAction;
Send: TAction;
Action3: TAction;
Action4: TAction;
Config: TAction;
ImageList20: TImageList;
TBSkin: TTBSkin;
PluginsImageList: TImageList;
SendMessage: TRzSendMessage;
procedure Image1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure CloseButtonClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure EditSitesExecute(Sender: TObject);
procedure ConfigExecute(Sender: TObject);
procedure SitesListPropertiesChange(Sender: TObject);
procedure SendExecute(Sender: TObject);
procedure PluginListDblClick(Sender: TObject);
procedure Action3Execute(Sender: TObject);
private
FPluginManager: IPluginManager;
FSitesList: TSitesList;
FPath: String;
FSetings: ISettings;
FIniFile: TIniFile;
procedure LoadProjectList;
procedure FillProjectList;
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
uses Windows, Messages, PluginManager, SysUtils, cpSitesForm,
SettingsPlugin, cpSettingsForm, ControlPanelElementIntf,
DataModuleIntf, ShellAPI, Dialogs, PluginIntf;
const
INI_MAIN = 'Main';
INI_CURRENT = 'Current';
procedure TMainForm.Image1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
Windows.ReleaseCapture;
Windows.SendMessage(Handle, WM_SYSCOMMAND, $F012, 0);
end;
procedure TMainForm.CloseButtonClick(Sender: TObject);
begin
Close
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
FPath := ExtractFilePath(ParamStr(0));
FIniFile := TIniFile.Create(FPath + 'config.ini');
// init plugin manager
FPluginManager := TPluginManager.Create;
// ISetings
FSetings := TSettingsPlugin.Create(0, FPluginManager);
FPluginManager.RegisterPlugin(FSetings);
// load all plugins
FPluginManager.LoadPlugins;
// init sites list
FSitesList := TSitesList.Create(FPath + 'data');
// misc
LoadProjectList;
end;
procedure TMainForm.FormDestroy(Sender: TObject);
begin
FreeAndNil(FSitesList);
FPluginManager.UnloadPlugins;
FSetings := nil;
FPluginManager := nil;
FIniFile.Free;
end;
// Загружаем список проектов
procedure TMainForm.LoadProjectList;
var
i: Integer;
begin
SitesList.Properties.Items.Clear;
SitesList.Properties.Items.BeginUpdate;
for i := 0 to FSitesList.Count - 1 do
SitesList.Properties.Items.AddObject(FSitesList[i].Name, FSitesList[i]);
SitesList.Properties.EndUpdate;
SitesList.ItemIndex := FIniFile.ReadInteger(INI_MAIN, INI_CURRENT, 0);
end;
procedure TMainForm.EditSitesExecute(Sender: TObject);
begin
GetSitesForm(FSitesList, FPluginManager);
LoadProjectList;
FillProjectList;
end;
procedure TMainForm.ConfigExecute(Sender: TObject);
begin
GetSettingsForm(FPluginManager);
end;
procedure TMainForm.SitesListPropertiesChange(Sender: TObject);
var
LPath: String;
begin
if SitesList.ItemIndex = -1 then Exit;
LPath := TSite(SitesList.Properties.Items.Objects[SitesList.ItemIndex]).Path;
FSetings.Load(LPath);
FillProjectList;
// сохранение последнего сайта
FIniFile.WriteInteger(INI_MAIN, INI_CURRENT, SitesList.ItemIndex);
end;
procedure TMainForm.SendExecute(Sender: TObject);
begin
SendMessage.Send;
end;
procedure TMainForm.FillProjectList;
var
i: Integer;
Element: IControlPanelElement;
li: TListItem;
Site: TSite;
ini: TIniFile;
Plugin: IPlugin;
begin
PluginList.Clear;
PluginsImageList.Clear;
PluginList.Items.BeginUpdate;
Site := FSitesList[SitesList.ItemIndex];
ini := TIniFile.Create(Site.Path + 'settings.ini');
try
for i := 0 to FPluginManager.Plugins.Count - 1 do
begin
if Supports(FPluginManager.Plugins[i], IControlPanelElement, Element) then
begin
Supports(FPluginManager.Plugins[i], IPlugin, Plugin);
if ini.ReadBool('Plugins', Plugin.Name, False) then
begin
li := PluginList.Items.Add;
li.Caption := Element.DisplayName;
li.Data := Pointer(FPluginManager.Plugins[i]);
li.ImageIndex := PluginsImageList.AddMasked(Element.Bitmap, $00FF00FF);
end;
end;
end;
finally
ini.Free;
end;
PluginList.Items.EndUpdate;
end;
procedure TMainForm.PluginListDblClick(Sender: TObject);
var
Element: IControlPanelElement;
Intf: IInterface;
DataModule: IDataModule;
Site: TSite;
begin
if PluginList.ItemIndex = -1 then Exit;
Site := FSitesList[SitesList.ItemIndex];
Intf := IInterface(PluginList.Items[PluginList.ItemIndex].Data);
if Supports(Intf, IDataModule, DataModule) then
DataModule.DataPath := Site.Path;
if Supports(Intf, IControlPanelElement, Element) then
Element.Execute;
end;
procedure TMainForm.Action3Execute(Sender: TObject);
begin
ShellExecute(0, 'open', PChar('devium.chm'), nil, nil, SW_SHOWNORMAL);
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.