text stringlengths 14 6.51M |
|---|
unit AcessoDados;
interface
uses
FireDAC.Stan.Intf,
FireDAC.Stan.Option,
FireDAC.Stan.Error,
FireDAC.UI.Intf,
FireDAC.Phys.Intf,
FireDAC.Stan.Def,
FireDAC.Stan.Pool,
FireDAC.Stan.Async,
FireDAC.Phys,
Data.DB,
FireDAC.Comp.Client,
FireDAC.Phys.IBBase,
FireDAC.Phys.IB,
FireDAC.Phys.FB,
FireDAC.Stan.Param,
FireDAC.DatS,
FireDAC.DApt.Intf,
FireDAC.VCLUI.Wait,
FireDAC.Comp.UI,
FireDAC.DApt;
type
TAcessoDados = class
private
FConexao: TFDConnection;
FTransacao: TFDTransaction;
procedure Conectar;
function getStringConection: string;
public
constructor Create;
procedure Desconectar;
procedure AssociaTransacao;
procedure ConfirmaTransacao;
procedure CancelaTransacao;
function getConsulta: TFDQuery;
function getProcedimento(const NomeProc: string): TFDStoredProc;
function getComando: TFDCommand;
end;
implementation
uses
System.SysUtils, Vcl.Forms;
{ TAcessoDados }
procedure TAcessoDados.AssociaTransacao;
begin
if not Assigned(FTransacao) then begin
self.FTransacao := TFDTransaction.Create(nil);
self.FTransacao.Connection := FConexao;
self.FTransacao.StartTransaction;
end;
end;
procedure TAcessoDados.CancelaTransacao;
begin
if Assigned(FTransacao) then begin
self.FTransacao.Rollback;
FreeAndNil(FTransacao);
end;
end;
procedure TAcessoDados.Conectar;
begin
if not Assigned(FConexao) then begin
FConexao := TFDConnection.Create(nil);
FConexao.Params.Clear;
FConexao.LoginPrompt := false;
FConexao.Open(self.getStringConection);
end;
end;
procedure TAcessoDados.ConfirmaTransacao;
begin
if Assigned(FTransacao) then begin
self.FTransacao.Commit;
FreeAndNil(FTransacao);
end;
end;
function TAcessoDados.getComando: TFDCommand;
begin
Result := TFDCommand.Create(nil);
Result.Connection := FConexao;
Result.Prepare();
end;
function TAcessoDados.getConsulta: TFDQuery;
begin
Result := TFDQuery.Create(nil);
Result.Connection := FConexao;
end;
function TAcessoDados.getProcedimento(const NomeProc: string): TFDStoredProc;
begin
Result := TFDStoredProc.Create(nil);
Result.Connection := FConexao;
Result.StoredProcName := NomeProc;
Result.Prepare;
end;
constructor TAcessoDados.Create;
begin
self.Conectar;
end;
procedure TAcessoDados.Desconectar;
begin
self.FConexao.Connected := false;
self.FConexao.Close;
end;
function TAcessoDados.getStringConection: string;
begin
result := ExtractFilePath(Application.ExeName)+'Dados\Dipetrol.fdb;'+
' User_Name=SYSDBA; '+
' Password=masterkey; '+
' CharacterSet=WIN1252; '+
' DriverID=IB; '+
' Protocol=TCPIP; '+
' Server=localhost;';
end;
end.
|
unit PrevendaRepository;
interface
uses BasicRepository, ViewPrevendaVO, System.SysUtils, PrevendaVO,
Generics.Collections, ProdutoVO, PrevendaItemVO, VendedorVO,
PrevendaCartaoRecebimentoVO, PrevendaRecebimentoVO, ViewPrevendaItemVO;
type
TPrevendaRepository = class(TBasicRepository)
class function getPrevendaByNumero(numeroOfPrevenda: Integer):TViewPrevendaVO;
class function getPrevendaById(idOfPRevenda: Integer):TViewPrevendaVO;
class function InsertPrevenda(Prevenda: TPrevendaVO): Integer;
class function InsertPrevendaItem(PrevedaItem: TPrevendaItemVO): Boolean;
class function getPrevendaAll: TList<TViewPrevendaVO>;
class function getProdutoByCodigo(codigoOfProduto: Integer): TProdutoVO;
class function getProdutoByEan(eanOfProduto: string): TProdutoVO;
class function getVendedorById(idOfVendedor: Integer): TVendedorVO;
class procedure updatePrevenda(Prevenda: TPrevendaVO);
class procedure updatePrevendaItem(Item: TPrevendaItemVO); overload;
class procedure TranferirPrevenda(Atual, Destino: Integer);
class function getPrevendaItemById(idOfPrevedaItem: Integer): TPrevendaItemVO;
class function getPrevendaItemByIdPrevenda(idOfPrevenda: Integer): TList<TViewPrevendaItemVO>;
class procedure updatePrevendaItem(POld, PNew: TPrevendaItemVO); overload;
class procedure PrevendaRecebimentoInserir(idOfPrevenda: Integer; Recebimentos: TObjectList<TPrevendaRecebimentoVO>);
class procedure PrevendaCartaoRecebimentoInserir(idOfPrevenda: Integer; Cartoes: TObjectList<TPrevendaCartaoRecebimentoVO>);
end;
implementation
{ TPrevendaRepository }
class function TPrevendaRepository.getPrevendaAll: TList<TViewPrevendaVO>;
var
Filtro: string;
begin
Filtro:= 'ID > 0 AND MODULO = ' + QuotedStr('P');
Result:= Consultar<TViewPrevendaVO>(False,Filtro);
end;
class function TPrevendaRepository.getPrevendaById(
idOfPRevenda: Integer): TViewPrevendaVO;
var
Filtro: string;
begin
Filtro:= 'ID = ' + IntToStr(idOfPRevenda);
Result:= ConsultarUmObjeto<TViewPrevendaVO>(Filtro,True);
end;
class function TPrevendaRepository.getPrevendaByNumero(
numeroOfPrevenda: Integer): TViewPrevendaVO;
var
Filtro: string;
begin
Filtro:= 'NUMERO = ' + IntToStr(numeroOfPrevenda);
Result:= ConsultarUmObjeto<TViewPrevendaVO>(Filtro,False);
end;
class function TPrevendaRepository.getPrevendaItemById(
idOfPrevedaItem: Integer): TPrevendaItemVO;
begin
Result:= ConsultarUmObjeto<TPrevendaItemVO>('ID = ' + IntToStr(idOfPrevedaItem),False);
end;
class function TPrevendaRepository.getPrevendaItemByIdPrevenda(
idOfPrevenda: Integer): TList<TViewPrevendaItemVO>;
var
Filtro: string;
begin
Filtro:= 'ID_PREVENDA = ' + IntToStr(idOfPrevenda) + 'ORDER BY LANCAMENTO DESC';
Result:= Consultar<TViewPrevendaItemVO>(False,Filtro);
end;
class function TPrevendaRepository.getProdutoByCodigo(codigoOfProduto: Integer): TProdutoVO;
var
Filtro: string;
begin
Filtro:= 'CODIGO = ' + IntToStr(codigoOfProduto) + ' AND ATIVO = ' + QuotedStr('S');
Result:= ConsultarUmObjeto<TProdutoVO>(Filtro,False);
end;
class function TPrevendaRepository.getProdutoByEan(
eanOfProduto: string): TProdutoVO;
var
Filtro: string;
begin
Filtro:= 'EAN = ' + QuotedStr(eanOfProduto) + ' AND ATIVO = ' + QuotedStr('S');
Result:= ConsultarUmObjeto<TProdutoVO>(Filtro,False);
end;
class function TPrevendaRepository.getVendedorById(
idOfVendedor: Integer): TVendedorVO;
var
Filtro: string;
begin
Filtro:= 'ID = ' + IntToStr(idOfVendedor);
Result:= ConsultarUmObjeto<TVendedorVO>(Filtro,False);
end;
class function TPrevendaRepository.InsertPrevenda(
Prevenda: TPrevendaVO): Integer;
begin
Result:= Inserir(Prevenda);
end;
class function TPrevendaRepository.InsertPrevendaItem(
PrevedaItem: TPrevendaItemVO): Boolean;
begin
Result:= Inserir(PrevedaItem) > 0;
end;
class procedure TPrevendaRepository.PrevendaCartaoRecebimentoInserir(
idOfPrevenda: Integer; Cartoes: TObjectList<TPrevendaCartaoRecebimentoVO>);
var
I: Integer;
begin
for I := 0 to Pred(Cartoes.Count) do
begin
if Cartoes.Items[i].Id = 0 then
begin
Cartoes.Items[i].IdPrevenda:= idOfPrevenda;
Cartoes.Items[i].Id:= Inserir(Cartoes.Items[i]);
end;
end;
end;
class procedure TPrevendaRepository.PrevendaRecebimentoInserir(
idOfPrevenda: Integer; Recebimentos: TObjectList<TPrevendaRecebimentoVO>);
var
I: Integer;
begin
for I := 0 to Pred(Recebimentos.Count) do
begin
if Recebimentos.Items[i].Id = 0 then
begin
Recebimentos.Items[i].IdPrevenda:= idOfPrevenda;
Recebimentos.Items[i].Id:= Inserir(Recebimentos.Items[i]);
end;
end;
end;
class procedure TPrevendaRepository.TranferirPrevenda(Atual, Destino: Integer);
var
Filtro: string;
begin
Filtro:= 'UPDATE PREVENDA_ITEM SET ID_PREVENDA = ' + IntToStr(Destino) +
' WHERE ID_PREVENDA = ' + IntToStr(Atual);
ComandoSQL(Filtro);
Filtro:= 'UPDATE PREVENDA_RECEBIMENTO SET ID_PREVENDA = ' + IntToStr(Destino) +
' WHERE ID_PREVENDA = ' + IntToStr(Atual);
ComandoSQL(Filtro);
Filtro:= 'UPDATE PREVENDA_CARTAO_RECEBIMENTO SET ID_PREVENDA = ' + IntToStr(Destino) +
' WHERE ID_PREVENDA = ' + IntToStr(Atual);
ComandoSQL(Filtro);
end;
class procedure TPrevendaRepository.updatePrevenda(Prevenda: TPrevendaVO);
begin
Alterar(Prevenda);
end;
class procedure TPrevendaRepository.updatePrevendaItem(POld,
PNew: TPrevendaItemVO);
begin
Alterar(PNew,POld);
end;
class procedure TPrevendaRepository.updatePrevendaItem(Item: TPrevendaItemVO);
begin
Alterar(Item)
end;
end.
|
unit ShiftOpTest;
{$mode objfpc}{$H+}
interface
uses
fpcunit,
testregistry,
uIntXLibTypes,
uIntX;
type
{ TTestShiftOp }
TTestShiftOp = class(TTestCase)
published
procedure Zero();
procedure SimpleAndNeg();
procedure Complex();
procedure BigShift();
procedure MassiveShift();
end;
implementation
procedure TTestShiftOp.Zero();
var
int1: TIntX;
begin
int1 := TIntX.Create(0);
AssertTrue(int1 shl 100 = 0);
AssertTrue(int1 shr 100 = 0);
end;
procedure TTestShiftOp.SimpleAndNeg();
var
temp: TIntXLibUInt32Array;
int1: TIntX;
begin
SetLength(temp, 2);
temp[0] := 0;
temp[1] := 8;
int1 := TIntX.Create(8);
AssertTrue((int1 shl 0 = int1 shr 0) and (int1 shl 0 = 8));
AssertTrue((int1 shl 32 = int1 shr -32) and (int1 shl 32 =
TIntX.Create(temp, False)));
end;
procedure TTestShiftOp.Complex();
var
int1: TIntX;
begin
int1 := TIntX.Create('$0080808080808080');
AssertTrue((int1 shl 4).ToString(16) = '808080808080800');
AssertTrue(int1 shr 36 = $80808);
end;
procedure TTestShiftOp.BigShift();
var
int1: TIntX;
begin
int1 := 8;
AssertTrue(int1 shr 777 = 0);
end;
procedure TTestShiftOp.MassiveShift();
var
n: TIntX;
i: integer;
begin
for i := 1 to Pred(2000) do
begin
n := i;
n := n shl i;
n := n shr i;
AssertTrue(TIntX.Create(i).Equals(n));
end;
end;
initialization
RegisterTest(TTestShiftOp);
end.
|
namespace proholz.xsdparser;
interface
type
XsdParserCore = public class
protected
//
// * A object that contains a parse function to each {@link XsdAbstractElement} concrete
// * type supported by this mapper, this way based on the concrete {@link XsdAbstractElement} tag the according parse
// * method can be invoked.
//
//
class var parseMappers: Dictionary<String,BiFunction<XsdParserCore,XmlElement,ReferenceBase>>;
// *
// * A {@link Map} object that contains the all the XSD types and their respective types in the Java
// * language.
//
//
class var xsdTypesToCodeGen: Dictionary<String,String>;
// *
// * A {@link List} which contains all the top elements parsed by this class.
//
//
var parseElements:= new Dictionary<String,List<ReferenceBase>>();
// *
// * A {@link List} of {@link UnsolvedReference} elements that weren't solved. This list is consulted after all the
// * elements are parsed in order to find if there is any suitable parsed element to replace the unsolved element.
//
//
var unsolvedElements:= new Dictionary<String,List<UnsolvedReference>>();// := new HashMap();
// *
// * A {@link List} containing all the elements that even after parsing all the elements on the file, don't have a
// * suitable object to replace the reference. This list can be consulted after the parsing process to assert if there
// * is any missing information in the XSD file.
//
//
var parserUnsolvedElementsMap:= new List<UnsolvedReferenceItem>();// := new ArrayList();
// *
// * A {@link List} containing the paths of files that were present in either {@link XsdInclude} or {@link XsdImport}
// * objects that are present in the original or subsequent files. These paths are stored to be parsed as well, the
// * parsing process only ends when all the files present in this {@link List} are parsed.
//
//
var schemaLocations:= new List<String>();// := new ArrayList();
var currentFile: String;
class constructor;
// *
// * Verifies if a given {@link Node} object, i.e. {@code node} is a xsd:schema node.
// * @param node The node to verify.
// * @return True if the node is a xsd:schema or xs:schema. False otherwise.
//
method isXsdSchema(node: XmlElement): Boolean;
// *
// * This method resolves all the remaining {@link UnsolvedReference} objects present after all the elements are parsed.
// * It starts by iterating all {@link XsdParser#parseElements} and inserting all the parsed elements with a name
// * attribute in the concreteElementsMap variable. After that it iterates on the {@link XsdParser#unsolvedElements}
// * list in order to find if any of the unsolvedReferences can be solved by replacing the unsolvedElement by its
// * matching {@link NamedConcreteElement} object, present in the concreteElementsMap. The {@link UnsolvedReference}
// * objects matches a {@link NamedConcreteElement} object by having its ref attribute with the same value as the
// * name attribute of the {@link NamedConcreteElement}.
//
method resolveRefs;
begin
resolveInnerRefs();
resolveOtherNamespaceRefs();
end;
method resolveOtherNamespaceRefs;
method replaceUnsolvedImportedReference(concreteElementsMap: Dictionary<String,List<NamedConcreteElement>>; unsolvedReference: UnsolvedReference);
method resolveInnerRefs;
// *
// * Replaces a single {@link UnsolvedReference} object, with the respective {@link NamedConcreteElement} object. If
// * there isn't a {@link NamedConcreteElement} object to replace the {@link UnsolvedReference} object, information
// * is stored informing the user of this Project of the occurrence.
// * @param concreteElementsMap The map containing all named concreteElements.
// * @param unsolvedReference The unsolved reference to solve.
//
method replaceUnsolvedReference(concreteElementsMap: Dictionary<String,List<NamedConcreteElement>>; unsolvedReference: UnsolvedReference);
// *
// * Saves an occurrence of an element which couldn't be resolved in the {@link XsdParser#replaceUnsolvedReference}
// * method, which can be accessed at the end of the parsing process in order to verify if were there were any
// * references that couldn't be solved.
// * @param unsolvedReference The unsolved reference which couldn't be resolved.
//
method storeUnsolvedItem(unsolvedReference: UnsolvedReference);
method updateConfig(config: ParserConfig);
public
class method getXsdTypesToCodeGen: Dictionary<String,String>;
class method getParseMappers: Dictionary<String,BiFunction<XsdParserCore, XmlElement,ReferenceBase>>;
method addParsedElement(wrappedElement: ReferenceBase);
// *
// * Adds an UnsolvedReference object to the unsolvedElements list which should be solved
// * at a later time in the parsing process.
// * @param unsolvedReference The unsolvedReference to add to the unsolvedElements list.
//
method addUnsolvedReference(unsolvedReference: UnsolvedReference);
// *
// * Adds a new file to the parsing queue. This new file appears by having xsd:import or xsd:include tags in the
// * original file to parse.
// * @param schemaLocation A new file path of another XSD file to parse.
//
method addFileToParse(schemaLocation: String);
// *
// * @return The {@link List} of {@link UnsolvedReferenceItem} that represent all the objects with a reference that couldn't
// * be solved.
//
method getUnsolvedReferences: List<UnsolvedReferenceItem>;
(**
* @return A list of all the top level parsed xsd:elements by this class. It doesn't return any other elements apart
* from xsd:elements. To access the whole element tree use {@link XsdParser#getResultXsdSchemas()}
*)
method getResultXsdElements() : List<XsdElement>;
(**
* @return A {@link List} of all the {@link XsdSchema} elements parsed by this class. You can use the {@link XsdSchema}
* instances to navigate through the whole element tree.
*)
method getResultXsdSchemas() : List<XsdSchema>;
method getCurrentFile : String;
end;
implementation
class constructor XsdParserCore;
begin
var config := new DefaultParserConfig();
parseMappers := config.getParseMappers();
xsdTypesToCodeGen := config.getXsdTypesToCodeGen();
end;
method XsdParserCore.updateConfig(config: ParserConfig);
begin
xsdTypesToCodeGen := config.getXsdTypesToCodeGen();
parseMappers := config.getParseMappers();
end;
method XsdParserCore.addParsedElement(wrappedElement: ReferenceBase);
begin
var parsedfilename := Path.GetFileName(currentFile);
var elements := parseElements[parsedfilename];
if not assigned(elements) then begin
elements := new List<ReferenceBase>();
parseElements.Add(parsedfilename, elements);
end;
elements.add(wrappedElement);
end;
class method XsdParserCore.getParseMappers: Dictionary<String,BiFunction<XsdParserCore,XmlElement,ReferenceBase>>;
begin
exit parseMappers;
end;
class method XsdParserCore.getXsdTypesToCodeGen: Dictionary<String,String>;
begin
exit xsdTypesToCodeGen;
end;
method XsdParserCore.addFileToParse(schemaLocation: String);
begin
// Should use Path functions?
var fileName: String := schemaLocation.substring(schemaLocation.lastIndexOf('/') + 1);
if not schemaLocations.Contains(fileName)
and schemaLocation.endsWith('.xsd')
and schemaLocations
.Any((sl) -> not sl.endsWith(fileName)) then begin
schemaLocations.add(fileName);
end;
end;
method XsdParserCore.addUnsolvedReference(unsolvedReference: UnsolvedReference);
begin
var tempname := Path.GetFileName(currentFile);
var unsolved:= unsolvedElements[tempname];
if not assigned(unsolved) then begin
unsolved := new List<UnsolvedReference>();
unsolvedElements.Add(tempname, unsolved);
end;
unsolved.add(unsolvedReference);
end;
method XsdParserCore.getResultXsdSchemas: List<XsdSchema>;
begin
result := new List<XsdSchema>();
Var l1 := parseElements.Values;
// Simulates flatMap from Java
for each element in l1 do begin
for each ele in element do
if ele.getElement is XsdSchema then
result.Add(ele.getElement as XsdSchema);
end;
end;
method XsdParserCore.getResultXsdElements: List<XsdElement>;
begin
var elements := new List<XsdElement>();// = new ArrayList<>();
for each schema in getResultXsdSchemas do
begin
for each child in schema.getChildrenElements() do
elements.Add(child);
end;
exit elements;
end;
method XsdParserCore.getUnsolvedReferences: List<UnsolvedReferenceItem>;
begin
exit parserUnsolvedElementsMap;
end;
method XsdParserCore.storeUnsolvedItem(unsolvedReference: UnsolvedReference);
begin
if parserUnsolvedElementsMap.isEmpty() then begin
parserUnsolvedElementsMap.add(new UnsolvedReferenceItem(unsolvedReference));
end
else begin
var innerEntry: UnsolvedReferenceItem :=
parserUnsolvedElementsMap
//.stream()
.Where(unsolvedReferenceObj -> unsolvedReferenceObj.getUnsolvedReference().getRef().equals(unsolvedReference.getRef()))
.FirstOrDefault();
if assigned(innerEntry) then begin
innerEntry.getParents().Add(unsolvedReference.getParent());
end
else begin
parserUnsolvedElementsMap.add(new UnsolvedReferenceItem(unsolvedReference));
end;
end;
end;
method XsdParserCore.replaceUnsolvedReference(concreteElementsMap: Dictionary<String,List<NamedConcreteElement>>; unsolvedReference: UnsolvedReference);
begin
var concreteElements := concreteElementsMap[unsolvedReference.getRef()];
if (concreteElements <> nil) then begin
var oldElementAttributes := unsolvedReference.getElement().getAttributesMap();
for each matching concreteElement : NamedConcreteElement in concreteElements do begin
var substitutionElementWrapper: NamedConcreteElement;
if not unsolvedReference.isTypeRef() then begin
// Should be save because of NamedConcretElement
// Maybe we can add a save Property but......
Var temp := concreteElement.getElement() as XsdNamedElements;
var substitutionElement := temp.clone(oldElementAttributes);
substitutionElementWrapper := NamedConcreteElement(ReferenceBase.createFromXsd(substitutionElement));
end
else begin
substitutionElementWrapper := concreteElement;
end;
unsolvedReference.getParent().replaceUnsolvedElements(substitutionElementWrapper);
end;
end
else begin
storeUnsolvedItem(unsolvedReference);
end;
end;
method XsdParserCore.resolveInnerRefs;
begin
for each filename in parseElements.Keys do begin
var includedFiles := new List<String>();
var pa1 := parseElements[filename];
if assigned(pa1) then begin
var LL1 :=
pa1
.Where(ref -> (ref is ConcreteElement)).
Select(ref -> ref as ConcreteElement);
for each ele in LL1 do begin
if ele.getElement is XsdInclude then begin
var temp := XsdInclude(ele.getElement()).getSchemaLocation();
includedFiles.Add(temp);
end;
end;
end; // Pa1
var includedElements := new List<ReferenceBase>(parseElements[filename]);
// (parseElements[filename]);
includedFiles
.ForEach(item -> begin
var temp := parseElements[item];
if assigned(temp) then
includedElements.Add(temp);
end);
var concreteElementsMap :=
includedElements
.Where(item -> item is NamedConcreteElement)
.Select(item -> item as NamedConcreteElement)
.GroupBy(item -> item.getName)
.ToDictionary(item -> item.Key, item -> item.ToList());
var theunsolvedBase :=
unsolvedElements.getOrDefault(filename, new List<UnsolvedReference>());
var theunsolved :=
theunsolvedBase
.Where(unsolvedElement -> begin
var theref := unsolvedElement.getRef();
result := not theref.contains(":")
end
)
.ToList();
theunsolved
.ForEach(unsolvedElement ->
begin
replaceUnsolvedReference(concreteElementsMap, unsolvedElement)
end
);
end; // Filename in Scope
end;
method XsdParserCore.replaceUnsolvedImportedReference(concreteElementsMap: Dictionary<String,List<NamedConcreteElement>>; unsolvedReference: UnsolvedReference);
begin
// List<NamedConcreteElement>
var concreteElements := concreteElementsMap[unsolvedReference.getRef().substring(unsolvedReference.getRef().indexOf(':') + 1)];
if assigned(concreteElements) then begin
var oldElementAttributes:= unsolvedReference.getElement().getAttributesMap();
for each concreteElement: NamedConcreteElement in concreteElements do begin
var substitutionElementWrapper: NamedConcreteElement;
if not unsolvedReference.isTypeRef() then begin
if (concreteElement.getElement() is XsdNamedElements) then begin
var substitutionElement := XsdNamedElements(concreteElement.getElement()).clone(oldElementAttributes);
substitutionElementWrapper := NamedConcreteElement(ReferenceBase.createFromXsd(substitutionElement));
end;
end
else begin
substitutionElementWrapper := concreteElement;
end;
unsolvedReference.getParent().replaceUnsolvedElements(substitutionElementWrapper);
end;
end
else begin
storeUnsolvedItem(unsolvedReference);
end;
end;
method XsdParserCore.resolveOtherNamespaceRefs;
begin
parseElements
.Keys
.ForEach(fileName ->
begin
var lxsdSchema : XsdSchema :=
parseElements[fileName]
//.stream()
.Where(ref -> begin
exit (ref is ConcreteElement) and (ref.getElement() is XsdSchema);
end)
.Select(ref -> (ref.getElement() as XsdSchema))
.FirstorDefault();
var ns := lxsdSchema.getNamespaces();
unsolvedElements
.getOrDefault(fileName, new List<UnsolvedReference>())
//.stream()
.Where(unsolvedElement -> unsolvedElement.getRef().contains(":"))
.ToList()
.ForEach(unsolvedElement -> begin
var unsolvedElementNamespace := unsolvedElement.getRef().substring(0, unsolvedElement.getRef().indexOf(":"));
var foundNamespaceId :=
ns.Keys
// .stream()
.Where(namespaceId -> namespaceId.equals(unsolvedElementNamespace)).FirstOrDefault;
if assigned(foundNamespaceId) then begin
var importedFileLocation := ns[foundNamespaceId].getFile();
var importedFileName := importedFileLocation.substring(importedFileLocation.lastIndexOf("/")+1);
var importedElements :=
parseElements[importedFileLocation];
if importedElements = nil then
begin
var lTemp := parseElements.Keys
.FirstOrDefault(k -> k.endsWith(importedFileName));
if assigned(lTemp) then
importedElements :=
parseElements[lTemp];
end;
if assigned(importedElements) then begin
var concreteElementsMap :=
importedElements
.Where(concreteEle -> concreteEle is NamedConcreteElement)
.Select(concreteEle -> concreteEle as NamedConcreteElement)
.groupBy(Named -> Named.getName)
.ToDictionary(item -> item.Key, item -> item.ToList());;
replaceUnsolvedImportedReference(concreteElementsMap, unsolvedElement);
end;
end;
end);
end);
end;
method XsdParserCore.isXsdSchema(node: XmlElement): Boolean;
begin
var schemaNodeName: String := node.FullName;
exit schemaNodeName.equals(XsdSchema.XSD_TAG) or schemaNodeName.equals(XsdSchema.XS_TAG);
end;
method XsdParserCore.getCurrentFile: String;
begin
exit currentFile;
end;
end. |
(*
Category: SWAG Title: CRT ROUTINES
Original name: 0041.PAS
Description: Borders and Boxes for DOS text mode
Author: DANIEL DICKMAN
Date: 08-30-96 09:36
*)
{Unit Boxes;
Interface
}
Uses
Crt; { in SWAG .. set CRT.SWG }
{
Procedure Box (X1, Y1, X2, Y2 : Byte; C : Char; At : Byte);
Procedure SingleFrame (X1, Y1, X2, Y2, At : Byte);
Procedure DoubleFrame (X1, Y1, X2, Y2, At : Byte);
Procedure FramedBox (X1, Y1, X2, Y2, At : Byte; Single : Boolean);
Procedure SpecialFrame (X1, Y1, X2, Y2, At : Byte; Title : String);
Procedure SpecialBox (X1, Y1, X2, Y2, At : Byte; Title : String);
Implementation
}
Procedure FWrite (X, Y : Byte; C : Char; At : Byte);
Begin
GotoXy(X,Y);
textattr := at;
Write(c);
End;
Procedure FWrite (X, Y : Byte; S : String; At : Byte);
Begin
GotoXy(X,Y);
textattr := at;
Write(S);
End;
Procedure Box (X1, Y1, X2, Y2 : Byte; C : Char; At : Byte);
Var
A, B : Byte;
Begin
For A := Y1 To Y2 Do
Begin
For B := X1 To X2 Do
FWrite (B, A, C, At);
End;
End;
Procedure SingleFrame (X1, Y1, X2, Y2, At : Byte);
Var
A : Byte;
Begin
FWrite (X1, Y1, '+', At);
FWrite (X1, Y2, '+', At);
FWrite (X2, Y1, '+', At);
FWrite (X2, Y2, '+', At);
For A := (X1 + 1) To (X2 - 1) Do
Begin
FWrite (A, Y1, '-', At);
FWrite (A, Y2, '-', At);
End;
For A := (Y1 + 1) To (Y2 - 1) Do
Begin
FWrite (X1, A, '|', At);
FWrite (X2, A, '|', At);
End;
End;
Procedure DoubleFrame (X1, Y1, X2, Y2, At : Byte);
Var
A : Byte;
Begin
FWrite (X1, Y1, '#', At);
FWrite (X1, Y2, '#', At);
FWrite (X2, Y1, '#', At);
FWrite (X2, Y2, '#', At);
For A := (X1 + 1) To (X2 - 1) Do
Begin
FWrite (A, Y1, '=', At);
FWrite (A, Y2, '=', At);
End;
For A := (Y1 + 1) To (Y2 - 1) Do
Begin
FWrite (X1, A, '|', At);
FWrite (X2, A, '|', At);
End;
End;
Procedure FramedBox (X1, Y1, X2, Y2, At : Byte; Single : Boolean);
Begin
Box (X1 - 1, Y1, X2 + 1, Y2, #32, At);
If Single Then
SingleFrame (X1, Y1, X2, Y2, At)
Else
DoubleFrame (X1, Y1, X2, Y2, At);
End;
Procedure SpecialFrame (X1, Y1, X2, Y2, At : Byte; Title : String);
Var
A : Byte;
Begin
FWrite (X1, Y1, #218, At);
FWrite (X1, Y2, #192, At);
FWrite (X2, Y1, #191, At);
FWrite (X2, Y2, #217, At);
For A := (X1 + 1) To (X2 - 1) Do
FWrite (A, Y2, #196, At);
For A := (Y1 + 1) To (Y2 - 1) Do
Begin
FWrite (X1, A, #179, At);
FWrite (X2, A, #179, At);
End;
FWrite (X1 + 1, Y1, #180, At);
FWrite (X2 - 1, Y1, #195, At);
For A := (X1 + 2) To (X2 - 2) Do
FWrite (A, Y1, #32, $1F);
FWrite ((X2 - X1 - Length(Title)) div 2 + X1, Y1, Title, $1F);
End;
Procedure SpecialBox (X1, Y1, X2, Y2, At : Byte; Title : String);
Begin
Box (X1 - 1, Y1, X2 + 1, Y2, #32, At);
SpecialFrame (X1, Y1, X2, Y2, At, Title);
End;
Begin
Box(1, 1, 20, 5, 'x', 14);
SingleFrame(10, 7, 60, 11, 13);
DoubleFrame(62, 5, 77, 13, 12 + 16*2);
FramedBox(2, 15, 40, 18, 11 + 16*1, true);
End.
|
unit usbhid;
{$mode delphi}
interface
uses
Classes, SysUtils, libusb, Graphics, msgstr;
type
TPString = array [0..255] of Char;
TDeviceDescription = record
idVENDOR:integer;
idPRODUCT:integer;
nameProduct:PANSIChar;
nameVendor:PANSIChar;
end;
// usbOpenDevice() error codes:
const
USBOPEN_SUCCESS =0; // no error
USBOPEN_ERR_ACCESS =1; // not enough permissions to open device
USBOPEN_ERR_IO =2; // I/O error
USBOPEN_ERR_NOTFOUND =3; // device not found
USB2PC = USB_ENDPOINT_IN;
PC2USB = USB_ENDPOINT_OUT;
function usbGetStringAscii(handle: pusb_dev_handle; index: Integer; langid: Integer; var buf: TPString; buflen: Integer): integer;
function usbOpenDevice(var device: Pusb_dev_handle; DevDscr: TDeviceDescription): Integer;
function USBSendControlMessage(devHandle: Pusb_dev_handle; direction: byte; request, value, index, bufflen: integer; var buffer: array of byte): integer;
implementation
uses main;
function usbGetStringAscii(handle: pusb_dev_handle; index: Integer; langid: Integer; var buf: TPString; buflen: Integer): integer;
var
buffer: array [0..255] of char;
rval, i: Integer;
begin
rval := usb_control_msg(handle, USB_ENDPOINT_IN, USB_REQ_GET_DESCRIPTOR, (USB_DT_STRING shl 8) + index, langid, buffer, sizeof(buffer), 1000);
result:=rval;
if rval < 0 then exit;
result:=0;
if buffer[1] <> char(USB_DT_STRING) then Exit;
if BYTE(buffer[0]) < rval then
rval := BYTE(buffer[0]);
rval:= rval div 2;
(* lossy conversion to ISO Latin1 *)
for i := 1 to rval-1 do
begin
if i > buflen then (* destination buffer overflow *)
break;
buf[i-1] := buffer[2 * i];
if buffer[2 * i + 1] <> #0 then (* outside of ISO Latin1 range *)
buf[i-1] := char('?');
end;
buf[i-1] := #0;
Result := i-1;
end;
function usbOpenDevice(var device: Pusb_dev_handle; DevDscr: TDeviceDescription): Integer;
const
{$J+}
didUsbInit: integer = 0; //not a true constant but a static variable
{$J-}
var
bus: Pusb_bus;
dev: Pusb_device;
handle: Pusb_dev_handle;
errorCode: integer;
S: TPstring;
len: Integer;
begin
handle:=nil;
errorCode := USBOPEN_ERR_NOTFOUND;
if didUsbInit=0 then
begin
didUsbInit := 1;
usb_init;
end;
usb_find_busses;
usb_find_devices;
bus := usb_get_busses;
While assigned(bus) do
begin
dev := bus^.devices;
while assigned(dev) do
begin
if(dev.descriptor.idVendor = DevDscr.idVENDOR) and (dev.descriptor.idProduct = DevDscr.idPRODUCT) then
begin
handle := usb_open(dev); (* we need to open the device in order to query strings *)
if not assigned(handle) then
begin
errorCode := USBOPEN_ERR_ACCESS;
raise Exception.Create('Warning: cannot open USB device '+usb_strerror());
continue;
end;
if (DevDscr.nameVendor = nil) and (DevDscr.nameProduct = nil) then break; (* name does not matter *)
(* now check whether the names match: *)
len := usbGetStringAscii(handle, dev.descriptor.iManufacturer, $0409,S, sizeof(S));
if (len < 0) then
begin
errorCode := USBOPEN_ERR_IO;
raise Exception.Create('Warning: cannot query manufacturer for device: '+usb_strerror());
end
else
begin
errorCode := USBOPEN_ERR_NOTFOUND;
(* fprintf(stderr, "seen device from vendor ->%s<-\n", string); *)
if StrPas(S)=vendorName then
begin
len := usbGetStringAscii(handle, dev.descriptor.iProduct, $0409,S, sizeof(S));
if (len < 0) then
begin
errorCode := USBOPEN_ERR_IO;
raise Exception.Create('Warning: cannot query product for device: '+usb_strerror());
end
else
begin
errorCode := USBOPEN_ERR_NOTFOUND;
(* fprintf(stderr, "seen product ->%s<-\n", string); *)
if StrPas(S)=DevDscr.nameProduct then
break;
end; //if len
end; //if string_
end; //if len<0
usb_close(handle);
handle := nil;
end; //if dev descriptor
dev := dev.next;
end; //while assigned(dev)
if handle<>nil then break;
bus := bus.next;
end; //while assigned(bus)
if (handle <> nil) then
begin
errorCode := 0;
device := handle;
end;
Result := errorCode;
end;
function USBSendControlMessage(devHandle: Pusb_dev_handle; direction: byte; request, value, index, bufflen: integer; var buffer: array of byte): integer;
begin
Result := usb_control_msg(devHandle, USB_TYPE_VENDOR or USB_RECIP_DEVICE or direction, request, value, index, buffer, bufflen, 10000);
if result < 0 then
begin
if result = -116 then Main.LogPrint(STR_USB_TIMEOUT)
else
Main.LogPrint(AnsiToUtf8(usb_strerror));
end;
end;
end.
|
unit UPiece;
interface
uses
USquare;
type
TPiece = class
private
location: TSquare;
published
constructor create(location: TSquare);
public
function getLocation: TSquare;
procedure setLocation(location: TSquare);
end;
implementation
{ TPiece }
constructor TPiece.create(location: TSquare);
begin
self.location := location;
end;
function TPiece.getLocation: TSquare;
begin
result := location;
end;
procedure TPiece.setLocation(location: TSquare);
begin
self.location := location;
end;
end.
|
// Inherited;
unit ADOQueryControler;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms,
Dialogs, Db, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls,
System.TypInfo, Generics.Collections, Vcl.ExtCtrls, Vcl.DBCtrls,
SyncObjs, Vcl.Themes, Vcl.Buttons, Data.Win.ADODB, Winapi.ADOInt,
ThreadControler;
type
TStatus = class(TObject)
public
FEmConsulta: Boolean;
EmProcesso: Boolean;
end;
TThread = class(ThreadControler.TThread)
function NovaConexao(DataSourceReferencia: TDataSource; ProcedimentoOrigem: String; ComponenteVinculado: TObject):TRecordProcedure;overload;
procedure CancelarConsulta(ProcedimentoOrigem: String);
end;
TAdoQuery = class(Data.Win.ADODB.TADOQuery)
private
FSpeedButton: TSpeedButton;
FButton: TButton;
FCheckBox: TCheckBox;
FEmConsulta : Boolean;
FTPCallBack: TProc;
procedure SetComponenteVinculado(ComponenteVinculado : TObject);overload;
function GetComponenteVinculado:TObject;
procedure ADOConnection1WillExecute(Connection: TADOConnection;
var CommandText: WideString; var CursorType: TCursorType;
var LockType: TADOLockType; var CommandType: TCommandType;
var ExecuteOptions: TExecuteOptions; var EventStatus: TEventStatus;
const Command: _Command; const Recordset: _Recordset);
public
CaptionAnterior : TCaption;
Cancelado: Boolean;
property ComponenteVinculado: TObject read GetComponenteVinculado write SetComponenteVinculado;
property EmConsulta: Boolean read FEmConsulta;
procedure OpenAssync;
procedure Open;overload;
procedure Open(CallBack:TProc);overload;
procedure Open(CallBack:TProc; ComponenteVinculado: TObject);overload;
procedure Open(CallBack:TProcedure);overload;
procedure Open(CallBack:TProcedure; ComponenteVinculado: TObject);overload;
procedure Cancelar;
procedure EOnFetchProgress(DataSet: TCustomADODataSet; Progress, MaxProgress: Integer; var EventStatus: TEventStatus);
procedure EOnFetchComplete(DataSet: TCustomADODataSet; const Error: Error; var EventStatus: TEventStatus);
procedure ECBOnFetchComplete(DataSet: TCustomADODataSet; const Error: Error; var EventStatus: TEventStatus);
procedure CompletarConsulta(DataSet:TCustomADODataSet);
procedure PrepararOpen(EOnFetchComplete:TRecordsetEvent);
procedure Open(NomeProcedimento: String; Thread: TThread);overload;
procedure Open(NomeProcedimento: String; Thread: TThread; ComponenteVinculado: TObject);overload;
procedure Open(NomeProcedimento: String; Thread: TThread; CallBack:TProc); overload;
procedure Open(NomeProcedimento: String; Thread: TThread; ComponenteVinculado: TObject; CallBack:TProc); overload;
procedure Open(NomeProcedimento: String; Thread: TThread; CallBack:TProcedure); overload;
procedure Open(NomeProcedimento: String; Thread: TThread; ComponenteVinculado: TObject; CallBack:TProcedure); overload;
end;
TDSList = record
DS : TDataSource;
Qry : TAdoQuery;
Status: TStatus;
end;
TSQLList = record
Qry: TAdoQuery;
Button: TButton;
DS: TDataSource;
Connection: TADOConnection;
end;
function LocalizarDataSource(Qry: TAdoQuery): TDataSource;
type
TForm = class(Vcl.Forms.TForm)
procedure FormDestroy(Sender: TObject);
procedure FormCreate(Sender: TObject);
private
function IsForm: Boolean;
protected
FOnDestroy: TNotifyEvent;
FOnCreate: TNotifyEvent;
function GetOnDestroy: TNotifyEvent;
function GetOnCreate: TNotifyEvent;
property OnDestroy: TNotifyEvent read GetOnDestroy write FOnDestroy stored IsForm;
property OnCreate: TNotifyEvent read GetOnCreate write FOnCreate stored IsForm;
public
Thread : TThread;
end;
var
Form: TForm;
implementation
{$R *.DFM}
uses Main;
function TThread.NovaConexao(DataSourceReferencia: TDataSource; ProcedimentoOrigem: String; ComponenteVinculado: TObject): TRecordProcedure;
begin
TAdoQuery(DataSourceReferencia.DataSet).ComponenteVinculado := ComponenteVinculado;
Result := Form.Thread.NovaConexao(DataSourceReferencia,ProcedimentoOrigem);
end;
function TForm.GetOnCreate: TNotifyEvent;
begin
FOnCreate := FormCreate;
Result := FOnCreate;
end;
procedure TThread.CancelarConsulta(ProcedimentoOrigem: String);
begin
Queue(
Procedure
var
I, J: Integer;
Procedimento : TRecordProcedure;
begin
for I := 0 to FilaProcAssyncEmExecucao.Count - 1 do
if FilaProcAssyncEmExecucao.Items[I].InformacoesAdicionais.NomeProcedimento = ProcedimentoOrigem then begin
if (FilaProcAssyncEmExecucao.Items[I].Status.EmProcesso) and (FilaProcAssyncEmExecucao.Items[I].Status.FEmConsulta) then begin
Procedimento := FilaProcAssyncEmExecucao.Items[I];
for J := 0 to Procedimento.DSList.Count - 1 do begin
try
TAdoQuery(Procedimento.DSList.Items[J].Qry).Cancelar;
finally
Procedimento.DSList.Items[J].Status.FEmConsulta := False;
end;
end;
end;
end;
end);
end;
procedure TForm.FormCreate(Sender: TObject);
begin
Thread := TThread.Create(false);
TForm(Sender).Thread.Owner := Sender;
end;
procedure TForm.FormDestroy(Sender: TObject);
begin
if Thread <> nil
then Thread.Kill;
end;
function TForm.GetOnDestroy: TNotifyEvent;
begin
FOnDestroy := FormDestroy;
result := FOnDestroy;
end;
function TForm.IsForm: Boolean;//Esse controlador de thread só funciona em forms (para startar ele automáticamente, mas voce pode herdar a classe na unit que desejar e criar e startar a thread por lá) !!!
begin
Result := true;
end;
////////////////////////QUERY FACILITADORES////////////////////////////
procedure TAdoQuery.ADOConnection1WillExecute(Connection: TADOConnection; // Decidi colocar isso aqui para podermos centralizar o padrão ADOQueryWillExecute quando ele estiver em modo assyncrono (se ele tentará refazer a conexão, se irá dar alerta e fechar o sistema, etc...
var CommandText: WideString; var CursorType: TCursorType;
var LockType: TADOLockType; var CommandType: TCommandType;
var ExecuteOptions: TExecuteOptions; var EventStatus: TEventStatus;
const Command: _Command; const Recordset: _Recordset);
begin
Recordset.Properties['Preserve on commit'].Value := True;// Após confirmar uma transação, o conjunto de registros permanece ativo. Portanto, é possível buscar novas linhas; atualizar, excluir e inserir linhas; e assim por diante.
Recordset.Properties['Preserve on abort'].Value := True;// Após abortar uma transação, o conjunto de registros permanece ativo. Portanto, é possível buscar novas linhas, atualizar, excluir e inserir linhas e assim por diante.
end;
procedure TAdoQuery.SetComponenteVinculado(ComponenteVinculado : TObject);
begin
if ComponenteVinculado is TSpeedButton
then begin
FSpeedButton := TSpeedButton(ComponenteVinculado);
if FSpeedButton.Caption <> 'Cancelar'
then CaptionAnterior := FSpeedButton.Caption;
FButton := nil;
FCheckBox := nil;
end
else
if ComponenteVinculado is TButton
then begin
FButton := TButton(ComponenteVinculado);
if FButton.Caption <> 'Cancelar'
then CaptionAnterior := FButton.Caption;
FSpeedButton := nil;
FCheckBox := nil;
end
else
if ComponenteVinculado is TCheckBox
then begin
FCheckBox := TCheckBox(ComponenteVinculado);
if FCheckBox.Caption <> 'Cancelar'
then CaptionAnterior := FCheckBox.Caption;
FSpeedButton := nil;
FButton := nil;
end
else Exception.Create('Tipo não programado!');
end;
function TAdoQuery.GetComponenteVinculado: TObject;
begin
if FSpeedButton<>nil
then Result := FSpeedButton
else
if FButton <> nil
then Result := FButton
else
if FCheckBox <> nil
then Result := FCheckBox
else Result := nil;
end;
procedure TAdoQuery.Cancelar;
begin
if (ComponenteVinculado <> nil) then begin
if ( (ComponenteVinculado is TSpeedButton) and (TSpeedButton(ComponenteVinculado).Caption = 'Cancelar') ) or
( (ComponenteVinculado is TButton ) and (TButton (ComponenteVinculado).Caption = 'Cancelar') ) or
( (ComponenteVinculado is TCheckBox ) and (TCheckBox (ComponenteVinculado).Caption = 'Cancelar') )
then Cancelado := True;
end;
end;
procedure TAdoQuery.EOnFetchProgress(DataSet: TCustomADODataSet; Progress, MaxProgress: Integer; var EventStatus: TEventStatus);
begin
if (Cancelado) then begin
Syncronized(
procedure
begin
Command.Cancel;// Cancelei o comando open no banco de dados
TCheckBox (ComponenteVinculado).Caption := CaptionAnterior;
end);
end;
Cancelado := False;
end;
procedure TAdoQuery.EOnFetchComplete(DataSet: TCustomADODataSet; const Error: Error; var EventStatus: TEventStatus);
begin
CompletarConsulta(DataSet);
end;
procedure TAdoQuery.OpenAssync;//Starta uma consulta de forma assyncrona independente de Thread, porém não espera a consulta terminar, para cancelar tem que chamar o diretamente o método cancelar da qry.
begin
if ComponenteVinculado = nil
then raise Exception.Create('Button não configurado');
PrepararOpen(EOnFetchComplete);
end;
procedure TAdoQuery.Open;
begin
if ComponenteVinculado <> nil
then begin//O button da qry deve ser preenchido dentro da Thread(pois para cancelar esse componente deve conter o tratamento), então esperar não causa problemas
if TCheckBox(ComponenteVinculado).Caption = 'Cancelar'
then Cancelar;
if (ComponenteVinculado is TCheckBox) and (not (TCheckBox(ComponenteVinculado)).Checked)
then EXIT;
OpenAssync;
while FEmConsulta do Sleep(50);//Consultas com cancelar devem ser feitas em Thread, e para cancelar usar a procedure "CancelarConsulta".
end
else begin
if Pos('Listagem',Name) > 0 then begin
if not FEmConsulta
then PrepararOpen(EOnFetchComplete);
if Owner is TForm
then TForm(Owner).Enabled := False;
while FEmConsulta do Application.ProcessMessages;//Aqui está a "mágica", se não estiver em Thread ele continua a funcionar, porém, para querys que não são de listagem será necessário readequar o sistema para que ao pegar um valor ele espere a query terminar a consulta.
if Owner is TForm
then TForm(Owner).Enabled := True;
end
else begin
ExecuteOptions := [];
Active := True;//Ele dará um active normal, caso queira assyncrono use a com callback e readeque o código para ele só acessar a field quando a consulta estiver concluída.
end;
end;
end;
procedure TAdoQuery.CompletarConsulta(DataSet:TCustomADODataSet);
var DataSource : TDataSource;
begin
Syncronized(
procedure
begin
DataSet.Resync([]);
DataSource := LocalizarDataSource(TAdoQuery(Self));
if DataSource <> Nil
then DataSource.Enabled := True;
if (ComponenteVinculado is TSpeedButton)
then TSpeedButton(ComponenteVinculado).Caption := CaptionAnterior
else
if (ComponenteVinculado is TButton)
then TButton(ComponenteVinculado) .Caption := CaptionAnterior
else
if (ComponenteVinculado is TCheckBox)
then TCheckBox(ComponenteVinculado) .Caption := CaptionAnterior;
FEmConsulta := False;
Cancelado := False;
ExecuteOptions := [];
end);
end;
procedure TAdoQuery.PrepararOpen(EOnFetchComplete:TRecordsetEvent);
var DataSource: TDataSource;
begin
if (ComponenteVinculado is TCheckBox) and (not (TCheckBox(ComponenteVinculado)).Checked)
then EXIT;
Close;
Syncronized(
procedure
begin
Connection := CopiarObjetoConexao(Connection);
Connection.OnWillExecute := TWillExecuteEvent(LocalizarProcedurePeloNome('ADOConnection1WillExecute',TAdoQuery));
OnFetchProgress := EOnFetchProgress;
OnFetchComplete := EOnFetchComplete;
ExecuteOptions := [eoAsyncExecute, eoAsyncFetchNonBlocking];
Connection.Connected := True;
end
);
if ComponenteVinculado <> nil then begin
if (ComponenteVinculado is TSpeedButton)
then TSpeedButton(ComponenteVinculado).Caption := 'Cancelar'
else
if (ComponenteVinculado is TButton)
then TButton(ComponenteVinculado) .Caption := 'Cancelar'
else
if (ComponenteVinculado is TCheckBox)
then TCheckBox(ComponenteVinculado) .Caption := 'Cancelar';
end;
FEmConsulta := True;
Cancelado := False;
Try
Active := True;
Except
on E:Exception do begin
Infobox('Houve um problema ao tentar realizar a consulta no banco de dados:' + E.Message);
abort;
end;
end;
DataSource := LocalizarDataSource(TAdoQuery(Self));
if DataSource <> nil
then DataSource.Enabled := False;
end;
procedure TAdoQuery.ECBOnFetchComplete(DataSet: TCustomADODataSet;
const Error: Error; var EventStatus: TEventStatus);
begin
CompletarConsulta(DataSet);
FTPCallBack;
end;
procedure TAdoQuery.Open(CallBack: TProc);
begin
if FEmConsulta
then Cancelar
else begin
FTPCallBack := CallBack;
PrepararOpen(ECBOnFetchComplete);
end
end;
procedure TAdoQuery.Open(CallBack: TProcedure);
var Proc: TProc;
begin
Proc := Procedure Begin CallBack end;
Open(Proc);
end;
procedure TAdoQuery.Open(CallBack: TProc; ComponenteVinculado: TObject);
begin
if Self.ComponenteVinculado <> ComponenteVinculado
then Self.ComponenteVinculado := ComponenteVinculado;
Open(CallBack);
end;
procedure TAdoQuery.Open(CallBack: TProcedure; ComponenteVinculado: TObject);
begin
if Self.ComponenteVinculado <> ComponenteVinculado
then Self.ComponenteVinculado := ComponenteVinculado;
Open(CallBack);
end;
procedure TAdoQuery.Open(NomeProcedimento: String; Thread: TThread);
begin
Thread.NovaConexao(LocalizarDataSource(Self),NomeProcedimento);
Open;
end;
procedure TAdoQuery.Open(NomeProcedimento: String; Thread: TThread;
ComponenteVinculado: TObject);
begin
Thread.NovaConexao(LocalizarDataSource(Self),NomeProcedimento, ComponenteVinculado);
Open;
end;
procedure TAdoQuery.Open(NomeProcedimento: String; Thread: TThread;
CallBack: TProc);
begin
Thread.NovaConexao(LocalizarDataSource(Self),NomeProcedimento);
open(CallBack);
end;
procedure TAdoQuery.Open(NomeProcedimento: String; Thread: TThread;
ComponenteVinculado: TObject; CallBack: TProc);
begin
Thread.NovaConexao(LocalizarDataSource(Self),NomeProcedimento, ComponenteVinculado);
open(CallBack);
end;
procedure TAdoQuery.Open(NomeProcedimento: String; Thread: TThread;
ComponenteVinculado: TObject; CallBack: TProcedure);
var Proc: TProc;
begin
Proc := Procedure Begin CallBack end;
open(NomeProcedimento, Thread, ComponenteVinculado, Proc);
end;
procedure TAdoQuery.Open(NomeProcedimento: String; Thread: TThread;
CallBack: TProcedure);
var Proc: TProc;
begin
Proc := Procedure Begin CallBack end;
open(NomeProcedimento, Thread, Proc);
end;
function LocalizarDataSource(Qry: TAdoQuery): TDataSource;
var I : Integer;
begin
Result := Nil;
if Qry.Owner IS TForm then
for I := 0 to TForm(Qry.Owner).ComponentCount - 1 do // Localizando DataSource
if TForm(Qry.Owner).Components[I] IS TDataSource
then if TDataSource(TForm(Qry.Owner).Components[I]).DataSet.Name = Qry.Name
then begin
Result := TDataSource(TForm(Qry.Owner).Components[I]);
exit;
end;
end;
end.
|
(*
Category: SWAG Title: FILE HANDLING ROUTINES
Original name: 0028.PAS
Description: Check for file EXIST
Author: MARTIN RICHARDSON
Date: 09-26-93 09:04
*)
{*****************************************************************************
* Function ...... Exist()
* Purpose ....... Checks for the existance of a file/directory
* Parameters .... sExp File/directory name to check for
* Returns ....... TRUE if sExp exists
* Notes ......... Not picky, will even accept wild cards
* Author ........ Martin Richardson
* Date .......... May 13, 1992
*****************************************************************************}
uses Dos;
FUNCTION Exist( sExp: STRING ): BOOLEAN;
VAR s : SearchRec;
BEGIN
FINDFIRST( sExp, AnyFile, s );
Exist := (DOSError = 0);
END;
BEGIN
if (Exist('1.pas')) then
writeln('1.pas found')
else
writeln('1.pas not found');
END.
|
unit Objekt.DateTime;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes,
Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, DateUtils;
type
TTbDateTime = class(TComponent)
private
fJahr: Word;
fSekunde: Word;
fStunde: Word;
fTag: Word;
fMinute: Word;
fMonat: Word;
fMilli: Word;
function getDatum: TDateTime;
procedure TryStrToWord(aStr: string; var aWord: Word; const aDefault: Word = 0);
protected
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
property Jahr: Word read fJahr;
property Monat: Word read fMonat;
property Tag: Word read fTag;
property Stunde: Word read fStunde;
property Minute: Word read fMinute;
property Sekunde: Word read fSekunde;
property Milli: Word read fMilli;
property Datum: TDateTime read getDatum;
procedure SetMySqlDateTimeStr(aValue: string);
procedure setDatum(aValue: TDateTime);
procedure Init;
function SetTimeToDate(aDate, aTime: TDateTime): TDateTime;
end;
implementation
{ TTbDateTime }
constructor TTbDateTime.Create(AOwner: TComponent);
begin
inherited;
end;
destructor TTbDateTime.Destroy;
begin
inherited;
end;
function TTbDateTime.getDatum: TDateTime;
begin
Result := EncodeDateTime(fJahr, fMonat, fTag, fStunde, fMinute, fSekunde, fMilli);
end;
procedure TTbDateTime.Init;
var
dDatum: TDateTime;
begin
dDatum := 0;
DecodeDateTime(dDatum, fJahr, fMonat, fTag, fStunde, fMinute, fSekunde, fMilli);
end;
procedure TTbDateTime.setDatum(aValue: TDateTime);
begin
DecodeDateTime(aValue, fJahr, fMonat, fTag, fStunde, fMinute, fSekunde, fMilli);
end;
procedure TTbDateTime.SetMySqlDateTimeStr(aValue: string);
var
sJahr: string;
sMonat: string;
sTag: string;
sStunde: string;
sMin: string;
sSek: string;
wJahr: Word;
begin
Init;
if length(avalue) = 19 then
begin
sJahr := copy(avalue, 1, 4);
sMonat := copy(aValue, 6,2);
sTag := copy(aValue, 9,2);
sStunde := copy(aValue, 12,2);
sMin := copy(aValue, 15,2);
sSek := copy(aValue, 18,2);
TryStrToWord(sJahr, fJahr);
TryStrToWord(sMonat, fMonat);
TryStrToWord(sTag, fTag);
TryStrToWord(sStunde, fStunde);
TryStrToWord(sMin, fMinute);
TryStrToWord(sSek, fSekunde);
end;
if length(avalue) = 10 then
begin
sJahr := copy(avalue, 1, 4);
sMonat := copy(aValue, 6,2);
sTag := copy(aValue, 9,2);
TryStrToWord(sJahr, fJahr);
TryStrToWord(sMonat, fMonat);
TryStrToWord(sTag, fTag);
end;
end;
procedure TTbDateTime.TryStrToWord(aStr: string; var aWord: Word; const aDefault: Word = 0);
var
iTemp: Integer;
begin
try
if not TryStrToInt(aStr, iTemp) then
begin
aWord := aDefault;
exit;
end;
aWord := Word(iTemp);
except
aWord := aDefault;
end;
end;
function TTbDateTime.SetTimeToDate(aDate, aTime: TDateTime): TDateTime;
var
Tag: Word;
Monat: Word;
Jahr: Word;
Stunde: Word;
Minute: Word;
Sekunde: Word;
Milli: Word;
begin
DecodeDate(aDate, Jahr, Monat, Tag);
DecodeTime(aTime, Stunde, Minute, Sekunde, Milli);
Result := EncodeDateTime(Jahr, Monat, Tag, Stunde, Minute, Sekunde, Milli);
end;
end.
|
unit mParserBase;
interface
uses
API_HTTP,
API_MVC_DB,
eGroup,
eLink,
IdCookieManager,
System.Classes;
type
TEachGroupRef = reference to procedure(const aArrRow: string; var aGroup: TGroup);
TModelParser = class abstract(TModelDB)
private
FCurrLink: TLink;
function GetNextLink: TLink;
procedure AddZeroLink;
procedure AfterLoad(aIdCookieManager: TIdCookieManager);
procedure BeforeLoad(aIdCookieManager: TIdCookieManager);
procedure ParsePostData(var aPostStringList: TStringList; aPostData: string);
procedure ProcessLink(aLink: TLink; out aBodyGroup: TGroup);
protected
FHTTP: THTTP;
procedure AddAsEachGroup(aOwnerGroup: TGroup; aDataArr: TArray<string>; aEachGroupProc: TEachGroupRef);
procedure AddPostOrHeaderData(var aPostData: string; const aKey, aValue: string);
procedure AfterCreate; override;
procedure AfterPageLoad(aIdCookieManager: TIdCookieManager; aLink: TLink); virtual;
procedure BeforeDestroy; override;
procedure BeforePageLoad(aIdCookieManager: TIdCookieManager; aLink: TLink); virtual;
procedure ProcessPageRoute(const aPage: string; aLink: TLink; var aBodyGroup: TGroup); virtual; abstract;
public
inDomain: string;
inJobID: Integer;
procedure Start; override;
end;
implementation
uses
eJob,
FireDAC.Comp.Client,
System.SysUtils;
procedure TModelParser.AfterLoad(aIdCookieManager: TIdCookieManager);
begin
AfterPageLoad(aIdCookieManager, FCurrLink);
end;
procedure TModelParser.AfterPageLoad(aIdCookieManager: TIdCookieManager; aLink: TLink);
begin
end;
procedure TModelParser.BeforePageLoad(aIdCookieManager: TIdCookieManager; aLink: TLink);
begin
end;
procedure TModelParser.BeforeLoad(aIdCookieManager: TIdCookieManager);
begin
BeforePageLoad(aIdCookieManager, FCurrLink);
end;
procedure TModelParser.ParsePostData(var aPostStringList: TStringList; aPostData: string);
var
PostDataArr: TArray<string>;
PostDataRow: string;
begin
PostDataArr := aPostData.Split([';']);
for PostDataRow in PostDataArr do
aPostStringList.Add(PostDataRow);
end;
procedure TModelParser.AddPostOrHeaderData(var aPostData: string; const aKey, aValue: string);
begin
if not aPostData.IsEmpty then
aPostData := aPostData + ';';
aPostData := aPostData + Format('%s=%s', [aKey, aValue]);
end;
procedure TModelParser.AddAsEachGroup(aOwnerGroup: TGroup; aDataArr: TArray<string>; aEachGroupProc: TEachGroupRef);
var
ArrRow: string;
Group: TGroup;
begin
for ArrRow in aDataArr do
begin
Group := TGroup.Create(FDBEngine);
aEachGroupProc(ArrRow, Group);
aOwnerGroup.ChildGroupList.Add(Group);
end;
end;
procedure TModelParser.ProcessLink(aLink: TLink; out aBodyGroup: TGroup);
var
Page: string;
PostSL: TStringList;
begin
aBodyGroup := TGroup.Create(FDBEngine, aLink.BodyGroupID);
aBodyGroup.ParentGroupID := aLink.OwnerGroupID;
FCurrLink := aLink;
//FHTTP.SetHeaders(aLink.Headers);
{if aLink.PostData.IsEmpty then
Page := FHTTP.Get(aLink.Link)
else
begin
PostSL := TStringList.Create;
try
ParsePostData(PostSL, aLink.PostData);
Page := FHTTP.Post(aLink.Link, PostSL)
finally
PostSL.Free;
end;
end; }
ProcessPageRoute(Page, aLink, aBodyGroup);
end;
procedure TModelParser.AddZeroLink;
var
Job: TJob;
Link: TLink;
begin
Job := TJob.Create(FDBEngine, inJobID);
Link := TLink.Create(FDBEngine);
try
Link.JobID := Job.ID;
Link.Level := 0;
Link.URL := Job.ZeroLink;
Link.HandledTypeID := 1;
Link.Store;
finally
Job.Free;
Link.Free;
end;
end;
function TModelParser.GetNextLink: TLink;
var
dsQuery: TFDQuery;
SQL: string;
begin
dsQuery := TFDQuery.Create(nil);
try
SQL := 'select Id from links t where t.job_id = :JobID and t.handled_type_id = 1 order by t.level desc, t.id limit 1 ';
dsQuery.SQL.Text := SQL;
dsQuery.ParamByName('JobID').AsInteger := inJobID;
FDBEngine.OpenQuery(dsQuery);
if dsQuery.IsEmpty then
begin
AddZeroLink;
Result := GetNextLink;
end
else
Result := TLink.Create(FDBEngine, dsQuery.Fields[0].AsInteger);
finally
dsQuery.Free;
end;
end;
procedure TModelParser.BeforeDestroy;
begin
FHTTP.Free;
end;
procedure TModelParser.AfterCreate;
begin
FHTTP := THTTP.Create(True);
FHTTP.OnBeforeLoad := BeforeLoad;
FHTTP.OnAfterLoad := AfterLoad;
end;
procedure TModelParser.Start;
var
BodyGroup: TGroup;
Link: TLink;
begin
while not FCanceled do
begin
// CS
Link := GetNextLink;
Link.HandledTypeID := 2;
Link.Store;
// CS
try
ProcessLink(Link, BodyGroup);
BodyGroup.StoreAll;
Link.BodyGroupID := BodyGroup.ID;
Link.Store;
finally
BodyGroup.Free;
Link.Free;
end;
end;
end;
end.
|
{..............................................................................}
{ Summary ImportWaveforms - Demonstrate the use of the ImportWaveforms }
{ process to import data from a csv file }
{ Copyright (c) 2009 by Altium Limited }
{..............................................................................}
{..............................................................................}
Procedure ImportWaveformsFromFile_Real;
Begin
ResetParameters;
AddStringParameter('DocumentFilename', 'C:\ImportedWaveforms.sdf'); //filename of sdf file to import data into
AddStringParameter('FileName', 'C:\Transient Analysis.csv'); //file containing data to be imported in same format as data exported
AddStringParameter('ChartName', 'ImportedRealData'); //name of chart to import data into
AddStringParameter('ListSeparator', ','); //the separator char used in the data file
AddStringParameter('ChartType', 'XY-Scatter'); //chart type: 'Table' or 'XY-Scatter'
AddStringParameter('DataType', 'Real'); //waveform data type: real, complex or table
AddStringParameter('PlotWaves0','input'); //comma delimited list of wave names to add to Plot 0
AddStringParameter('PlotWaves1','output'); //comma delimited list of wave names to add to Plot 1
AddStringParameter('OverwriteWaves', 'True'); //set to true to silently overwrite existing waves of same name
AddStringParameter('XScaleMode', 'Linear'); //X-scale mode: Log10, Log2 or Linear
AddStringParameter('XUnits', 's'); //X-Axis unit string
AddStringParameter('XAxisLabel', 'Time'); //X-Axis label string
//the following two parameters are useful to reduce memory consumed importing large data files
AddStringParameter('OptimiseWaves', 'True'); //performs optimisation of imported waves to reduce memory usage (e.g. drops redundant points on straight line).
AddStringParameter('ImportWaves', 'input,output'); //comma delimited list of waves to import. If blank, or not given all waveforms will be imported.
RunProcess('SimView:ImportWaveforms');
End;
{..............................................................................}
{..............................................................................}
Procedure ImportWaveformsFromFile_Complex;
Begin
ResetParameters;
AddStringParameter('DocumentFilename', 'C:\ImportedWaveforms.sdf'); //filename of sdf file to import data into
AddStringParameter('FileName', 'C:\AC Analysis.csv'); //file containing data to be imported in same format as data exported
AddStringParameter('ChartName', 'ImportedComplexData'); //name of chart to import data into
AddStringParameter('ListSeparator', ','); //the separator char used in the data file
AddStringParameter('ChartType', 'XY-Scatter'); //chart type: 'Table' or 'XY-Scatter'
AddStringParameter('DataType', 'Complex'); //waveform data type: real or complex
AddStringParameter('PlotWaves0','input,output'); //comma delimited list of wave names to add to Plot 0
AddStringParameter('OverwriteWaves', 'True'); //set to true to silently overwrite existing waves of same name
AddStringParameter('XScaleMode', 'Log10'); //X-scale mode: Log10, Log2 or Linear
AddStringParameter('XUnits', 'Hz'); //X-Axis unit string
AddStringParameter('XAxisLabel', 'Frequency'); //X-Axis label string
RunProcess('SimView:ImportWaveforms');
End;
{..............................................................................}
{..............................................................................}
Procedure ImportWaveformsFromFile_Table;
Begin
ResetParameters;
AddStringParameter('DocumentFilename', 'C:\ImportedWaveforms.sdf'); //filename of sdf file to import data into
AddStringParameter('FileName', 'C:\Operating Point.CSV'); //file containing data to be imported in same format as data exported
AddStringParameter('ChartName', 'ImportedTableData'); //name of chart to import data into
AddStringParameter('ListSeparator', ','); //the separator char used in the data file
AddStringParameter('ChartType', 'Table'); //chart type: 'Table' or 'XY-Scatter'
AddStringParameter('DataType', 'Real'); //waveform data type: real or complex
AddStringParameter('PlotWaves0','input'); //comma delimited list of wave names to add to Plot 0
AddStringParameter('PlotWaves1','output'); //comma delimited list of wave names to add to Plot 1
AddStringParameter('OverwriteWaves', 'True'); //set to true to silently overwrite existing waves of same name
RunProcess('SimView:ImportWaveforms');
End;
{..............................................................................}
|
unit LCR_api;
interface
uses util1;
(*
* API.h
*
* This module provides C callable APIs for each of the command supported by LightCrafter4500 platform and detailed in the programmer's guide.
*
* Copyright (C) 2013 Texas Instruments Incorporated - http://www.ti.com/
* ALL RIGHTS RESERVED
*
*)
Const
STAT_BIT_FLASH_BUSY = $8;
HID_MESSAGE_MAX_SIZE = 512;
type
TLCRrectangle= record
firstPixel,firstLine,pixelsPerLine,linesPerFrame: smallint;
end;
TLCRcmd=(
SOURCE_SEL,
PIXEL_FORMAT,
CLK_SEL,
CHANNEL_SWAP,
FPD_MODE,
CURTAIN_COLOR,
POWER_CONTROL,
FLIP_LONG,
FLIP_SHORT,
TPG_SEL,
PWM_INVERT,
LED_ENABLE,
GET_VERSION,
SW_RESET,
DMD_PARK,
BUFFER_FREEZE,
STATUS_HW,
STATUS_SYS,
STATUS_MAIN,
CSC_DATA,
GAMMA_CTL,
BC_CTL,
PWM_ENABLE,
PWM_SETUP,
PWM_CAPTURE_CONFIG,
GPIO_CONFIG,
LED_CURRENT,
DISP_CONFIG,
TEMP_CONFIG,
TEMP_READ,
MEM_CONTROL,
I2C_CONTROL,
LUT_VALID,
DISP_MODE,
TRIG_OUT1_CTL,
TRIG_OUT2_CTL,
RED_STROBE_DLY,
GRN_STROBE_DLY,
BLU_STROBE_DLY,
PAT_DISP_MODE,
PAT_TRIG_MODE,
PAT_START_STOP,
BUFFER_SWAP,
BUFFER_WR_DISABLE,
CURRENT_RD_BUFFER,
PAT_EXPO_PRD,
INVERT_DATA,
PAT_CONFIG,
MBOX_ADDRESS,
MBOX_CONTROL,
MBOX_DATA,
TRIG_IN1_DELAY,
TRIG_IN2_CONTROL,
SPLASH_LOAD,
SPLASH_LOAD_TIMING,
GPCLK_CONFIG,
PULSE_GPIO_23,
ENABLE_LCR_DEBUG,
TPG_COLOR,
PWM_CAPTURE_READ,
PROG_MODE,
BL_STATUS,
BL_SPL_MODE,
BL_GET_MANID,
BL_GET_DEVID,
BL_GET_CHKSUM,
BL_SET_SECTADDR,
BL_SECT_ERASE,
BL_SET_DNLDSIZE,
BL_DNLD_DATA,
BL_FLASH_TYPE,
BL_CALC_CHKSUM,
BL_PROG_MODE);
var
LCR_SetInputSource: function(source: longword ; portWidth: longword ): integer;cdecl;
LCR_GetInputSource: function(var pSource: longword ; var portWidth: longword ): integer;cdecl;
LCR_SetPixelFormat: function(format: longword ): integer;cdecl;
LCR_GetPixelFormat: function(var pFormat: longword ): integer;cdecl;
LCR_SetPortClock: function(clock: longword ): integer;cdecl;
LCR_GetPortClock: function(var pClock: longword ): integer;cdecl;
LCR_SetDataChannelSwap: function(port: longword ; swap: longword ): integer;cdecl;
LCR_GetDataChannelSwap: function(var pPort: longword ; var pSwap: longword ): integer;cdecl;
LCR_SetFPD_Mode_Field: function(PixelMappingMode: longword ; SwapPolarity: boolean ; FieldSignalSelect: longword ): integer;cdecl;
LCR_GetFPD_Mode_Field: function(var pPixelMappingMode: longword ; var pSwapPolarity: boolean ; var pFieldSignalSelect: longword ): integer;cdecl;
LCR_SetPowerMode: function(w:boolean): integer;cdecl;
LCR_SetLongAxisImageFlip: function(w:boolean): integer;cdecl;
LCR_GetLongAxisImageFlip: function(): boolean;cdecl;
LCR_SetShortAxisImageFlip: function(w:boolean): integer;cdecl;
LCR_GetShortAxisImageFlip: function(): boolean;cdecl;
LCR_SetTPGSelect: function(pattern: longword ): integer;cdecl;
LCR_GetTPGSelect: function(var pPattern: longword ): integer;cdecl;
LCR_SetLEDPWMInvert: function(invert: boolean ): integer;cdecl;
LCR_GetLEDPWMInvert: function(var inverted: boolean ): integer;cdecl;
LCR_SetLedEnables: function(SeqCtrl: boolean ; Red: boolean ; Green: boolean ; Blue: boolean ): integer;cdecl;
LCR_GetLedEnables: function(var pSeqCtrl: boolean ; var pRed: boolean ; var pGreen: boolean ; var pBlue: boolean ): integer;cdecl;
LCR_GetVersion: function(var pApp_ver: longword ; var pAPI_ver: longword ; var pSWConfig_ver: longword ; var pSeqConfig_ver: longword ): integer;cdecl;
LCR_SoftwareReset: function(): integer;cdecl;
LCR_GetStatus: function(var pHWStatus: byte ; var pSysStatus: byte ; var pMainStatus: byte ): integer;cdecl;
LCR_SetPWMEnable: function(channel: longword ; Enable: boolean ): integer;cdecl;
LCR_GetPWMEnable: function(channel: longword ; var pEnable: boolean ): integer;cdecl;
LCR_SetPWMConfig: function(channel: longword ; pulsePeriod: longword ; dutyCycle: longword ): integer;cdecl;
LCR_GetPWMConfig: function(channel: longword ; var pPulsePeriod: longword ; var pDutyCycle: longword ): integer;cdecl;
LCR_SetPWMCaptureConfig: function(channel: longword ; enable: boolean ; sampleRate: longword ): integer;cdecl;
LCR_GetPWMCaptureConfig: function(channel: longword ; var pEnabled: boolean ; var pSampleRate: longword ): integer;cdecl;
LCR_SetGPIOConfig: function(pinNum: longword ; enAltFunc: boolean ; altFunc1: boolean ; dirOutput: boolean ; outTypeOpenDrain: boolean ; pinState: boolean ): integer;cdecl;
LCR_GetGPIOConfig: function(pinNum: longword ; var pEnAltFunc: boolean ; var pAltFunc1: boolean ; var pDirOutput: boolean ; var pOutTypeOpenDrain: boolean ; var pState: boolean ): integer;cdecl;
LCR_GetLedCurrents: function(var pRed: byte ; var pGreen: byte ; var pBlue: byte ): integer;cdecl;
LCR_SetLedCurrents: function(RedCurrent:byte; GreenCurrent: byte ; BlueCurrent: byte ): integer;cdecl;
LCR_SetDisplay: function(croppedArea: TLCRrectangle ; displayArea: TLCRrectangle ): integer;cdecl;
LCR_GetDisplay: function(var pCroppedArea: TLCRrectangle ; var pDisplayArea: TLCRrectangle ): integer;cdecl;
LCR_MemRead: function(addr: longword ; var readWord: longword ): integer;cdecl;
LCR_MemWrite: function(addr: longword ; data: longword ): integer;cdecl;
LCR_ValidatePatLutData: function(var pStatus: longword ): integer;cdecl;
LCR_SetPatternDisplayMode: function( w:boolean): integer;cdecl;
LCR_GetPatternDisplayMode: function(var w: boolean ): integer;cdecl;
LCR_SetTrigOutConfig: function(trigOutNum: longword ; invert: boolean ; rising: longword ; falling: longword ): integer;cdecl;
LCR_GetTrigOutConfig: function(trigOutNum: longword ; var pInvert: boolean ;var pRising: longword ; var pFalling: longword ): integer;cdecl;
LCR_SetRedLEDStrobeDelay: function(rising: byte ; falling: byte ): integer;cdecl;
LCR_SetGreenLEDStrobeDelay: function(rising: byte ; falling: byte ): integer;cdecl;
LCR_SetBlueLEDStrobeDelay: function(rising: byte ; falling: byte ): integer;cdecl;
LCR_GetRedLEDStrobeDelay: function(var rising, falling: byte ): integer ;cdecl;
LCR_GetGreenLEDStrobeDelay: function(var rising, falling: byte ): integer ;cdecl;
LCR_GetBlueLEDStrobeDelay: function(var rising, falling: byte ): integer ;cdecl;
LCR_EnterProgrammingMode: function(): integer;cdecl;
LCR_ExitProgrammingMode: function(): integer;cdecl;
// LCR_GetProgrammingMode: function(var ProgMode: boolean ): integer;cdecl;
LCR_GetFlashManID: function( var manID: word ): integer;cdecl;
LCR_GetFlashDevID: function(var devID: longword ): integer;cdecl;
LCR_GetBLStatus: function(var BL_Status: byte ): integer;cdecl;
LCR_SetFlashAddr: function(Addr: longword ): integer;cdecl;
LCR_FlashSectorErase: function(): integer;cdecl;
LCR_SetDownloadSize: function(dataLen: longword ): integer;cdecl;
LCR_DownloadData: function(var pByteArray: byte ; dataLen: longword ): integer;cdecl;
LCR_WaitForFlashReady: procedure ;cdecl;
LCR_SetFlashType: function(tp: byte): integer;cdecl;
LCR_CalculateFlashChecksum: function(): integer;cdecl;
LCR_GetFlashChecksum: function(var checksum: longword): integer;cdecl;
LCR_SetMode: function(SLmode: boolean): integer;cdecl;
LCR_GetMode: function(var pMode: boolean ): integer;cdecl;
LCR_LoadSplash: function(index: longword ): integer;cdecl;
LCR_GetSplashIndex: function(var pIndex: longword ): integer;cdecl;
LCR_SetTPGColor: function(redFG: word ; greenFG: word ; blueFG: word ; redBG: word ; greenBG: word ; blueBG: word ): integer;cdecl;
LCR_GetTPGColor: function(var pRedFG: word ; var pGreenFG: word ; var pBlueFG: word ; var pRedBG: word ; var pGreenBG: word ; var pBlueBG: word ): integer;cdecl;
LCR_ClearPatLut: function(): integer;cdecl;
LCR_AddToPatLut: function(TrigType: integer ; PatNum: integer ;BitDepth: integer ;LEDSelect: integer ;InvertPat: boolean ; InsertBlack: boolean ;BufSwap: boolean ; trigOutPrev: boolean ): integer;cdecl;
LCR_GetPatLutItem: function(index: integer ; var pTrigType: integer ; var pPatNum: integer ;var pBitDepth: integer ;var pLEDSelect: integer ;var pInvertPat: boolean ; var pInsertBlack: boolean ;var pBufSwap: boolean ; var pTrigOutPrev: boolean ): integer;cdecl;
LCR_SendPatLut: function(): integer;cdecl;
LCR_SendSplashLut: function( var lutEntries: byte ; numEntries: longword ): integer;cdecl;
LCR_GetPatLut: function(numEntries: integer ): integer;cdecl;
LCR_GetSplashLut: function(var pLut: byte ; numEntries: integer ): integer;cdecl;
LCR_SetPatternTriggerMode: function(w:boolean): integer;cdecl;
LCR_GetPatternTriggerMode: function(var w:boolean): integer;cdecl;
LCR_PatternDisplay: function(Action: integer ): integer;cdecl;
LCR_SetPatternConfig: function(numLutEntries: longword ; rep: boolean ; numPatsForTrigOut2: longword ; numSplash: longword ): integer;cdecl;
LCR_GetPatternConfig: function(var pNumLutEntries: longword ; var pRepeat: boolean ; var pNumPatsForTrigOut2: longword ; var pNumSplash: longword ): integer;cdecl;
LCR_SetExposure_FramePeriod: function(exposurePeriod: longword ; framePeriod: longword ): integer;cdecl;
LCR_GetExposure_FramePeriod: function(var pExposure: longword ; var pFramePeriod: longword ): integer;cdecl;
LCR_SetTrigIn1Delay: function(Delay: longword ): integer;cdecl;
LCR_GetTrigIn1Delay: function(var pDelay: longword ): integer;cdecl;
LCR_SetInvertData: function(invert: boolean ): integer;cdecl;
LCR_PWMCaptureRead: function(channel: longword ; var pLowPeriod: longword ; var pHighPeriod: longword ): integer;cdecl;
LCR_SetGeneralPurposeClockOutFreq: function(clkId: longword ; enable: boolean ; clkDivider: longword ): integer;cdecl;
LCR_GetGeneralPurposeClockOutFreq: function(clkId: longword ; var pEnabled: boolean ; var pClkDivider: longword ): integer;cdecl;
LCR_MeasureSplashLoadTiming: function(startIndex: longword ; numSplash: longword ): integer;cdecl;
LCR_ReadSplashLoadTiming: function(var pTimingData: longword ): integer;cdecl;
// LCR_GetGammaCorrection: function(var pTable: byte ; var pEnable: boolean ): integer;cdecl;
// LCR_SetGammaCorrection: function(table: byte ; enable: boolean ): integer;cdecl;
// LCR_GetColorSpaceConversion: function(var pAttr: byte ; var pCoefficients: word ): integer;cdecl;
USB_Open: function :integer;cdecl;
USB_IsConnected: function:boolean;cdecl;
USB_Write: function: integer;cdecl;
USB_Read: function: integer;cdecl;
USB_Close: function: integer;cdecl;
USB_Init: function: integer;cdecl;
USB_Exit: function: integer;cdecl;
function InitLCRlib: boolean;
implementation
var
hh:intG;
Const
LCRdll= 'lcrDll.dll';
function InitLCRlib: boolean;
begin
result:=true;
if hh<>0 then exit;
hh:=GloadLibrary( Appdir + LCRdll );
result:=(hh<>0);
if not result then exit;
LCR_SetInputSource:= getProc(hh, 'LCR_SetInputSource');
LCR_GetInputSource:= getProc(hh, 'LCR_GetInputSource');
LCR_SetPixelFormat:= getProc(hh, 'LCR_SetPixelFormat');
LCR_GetPixelFormat:= getProc(hh, 'LCR_GetPixelFormat');
LCR_SetPortClock:= getProc(hh, 'LCR_SetPortClock');
LCR_GetPortClock:= getProc(hh, 'LCR_GetPortClock');
LCR_SetDataChannelSwap:= getProc(hh, 'LCR_SetDataChannelSwap');
LCR_GetDataChannelSwap:= getProc(hh, 'LCR_GetDataChannelSwap');
LCR_SetFPD_Mode_Field:= getProc(hh, 'LCR_SetFPD_Mode_Field');
LCR_GetFPD_Mode_Field:= getProc(hh, 'LCR_GetFPD_Mode_Field');
LCR_SetPowerMode:= getProc(hh, 'LCR_SetPowerMode');
LCR_SetLongAxisImageFlip:= getProc(hh, 'LCR_SetLongAxisImageFlip');
LCR_GetLongAxisImageFlip:= getProc(hh, 'LCR_GetLongAxisImageFlip');
LCR_SetShortAxisImageFlip:= getProc(hh, 'LCR_SetShortAxisImageFlip');
LCR_GetShortAxisImageFlip:= getProc(hh, 'LCR_GetShortAxisImageFlip');
LCR_SetTPGSelect:= getProc(hh, 'LCR_SetTPGSelect');
LCR_GetTPGSelect:= getProc(hh, 'LCR_GetTPGSelect');
LCR_SetLEDPWMInvert:= getProc(hh, 'LCR_SetLEDPWMInvert');
LCR_GetLEDPWMInvert:= getProc(hh, 'LCR_GetLEDPWMInvert');
LCR_SetLedEnables:= getProc(hh, 'LCR_SetLedEnables');
LCR_GetLedEnables:= getProc(hh, 'LCR_GetLedEnables');
LCR_GetVersion:= getProc(hh, 'LCR_GetVersion');
LCR_SoftwareReset:= getProc(hh, 'LCR_SoftwareReset');
LCR_GetStatus:= getProc(hh, 'LCR_GetStatus');
LCR_SetPWMEnable:= getProc(hh, 'LCR_SetPWMEnable');
LCR_GetPWMEnable:= getProc(hh, 'LCR_GetPWMEnable');
LCR_SetPWMConfig:= getProc(hh, 'LCR_SetPWMConfig');
LCR_GetPWMConfig:= getProc(hh, 'LCR_GetPWMConfig');
LCR_SetPWMCaptureConfig:= getProc(hh, 'LCR_SetPWMCaptureConfig');
LCR_GetPWMCaptureConfig:= getProc(hh, 'LCR_GetPWMCaptureConfig');
LCR_SetGPIOConfig:= getProc(hh, 'LCR_SetGPIOConfig');
LCR_GetGPIOConfig:= getProc(hh, 'LCR_GetGPIOConfig');
LCR_GetLedCurrents:= getProc(hh, 'LCR_GetLedCurrents');
LCR_SetLedCurrents:= getProc(hh, 'LCR_SetLedCurrents');
LCR_SetDisplay:= getProc(hh, 'LCR_SetDisplay');
LCR_GetDisplay:= getProc(hh, 'LCR_GetDisplay');
LCR_MemRead:= getProc(hh, 'LCR_MemRead');
LCR_MemWrite:= getProc(hh, 'LCR_MemWrite');
LCR_ValidatePatLutData:= getProc(hh, 'LCR_ValidatePatLutData');
LCR_SetPatternDisplayMode:= getProc(hh, 'LCR_SetPatternDisplayMode');
LCR_GetPatternDisplayMode:= getProc(hh, 'LCR_GetPatternDisplayMode');
LCR_SetTrigOutConfig:= getProc(hh, 'LCR_SetTrigOutConfig');
LCR_GetTrigOutConfig:= getProc(hh, 'LCR_GetTrigOutConfig');
LCR_SetRedLEDStrobeDelay:= getProc(hh, 'LCR_SetRedLEDStrobeDelay');
LCR_SetGreenLEDStrobeDelay:= getProc(hh, 'LCR_SetGreenLEDStrobeDelay');
LCR_SetBlueLEDStrobeDelay:= getProc(hh, 'LCR_SetBlueLEDStrobeDelay');
LCR_GetRedLEDStrobeDelay:= getProc(hh, 'LCR_GetRedLEDStrobeDelay');
LCR_GetGreenLEDStrobeDelay:= getProc(hh, 'LCR_GetGreenLEDStrobeDelay');
LCR_GetBlueLEDStrobeDelay:= getProc(hh, 'LCR_GetBlueLEDStrobeDelay');
LCR_EnterProgrammingMode:= getProc(hh, 'LCR_EnterProgrammingMode');
LCR_ExitProgrammingMode:= getProc(hh, 'LCR_ExitProgrammingMode');
// LCR_GetProgrammingMode:= getProc(hh, 'LCR_GetProgrammingMode');
LCR_GetFlashManID:= getProc(hh, 'LCR_GetFlashManID');
LCR_GetFlashDevID:= getProc(hh, 'LCR_GetFlashDevID');
LCR_GetBLStatus:= getProc(hh, 'LCR_GetBLStatus');
LCR_SetFlashAddr:= getProc(hh, 'LCR_SetFlashAddr');
LCR_FlashSectorErase:= getProc(hh, 'LCR_FlashSectorErase');
LCR_SetDownloadSize:= getProc(hh, 'LCR_SetDownloadSize');
LCR_DownloadData:= getProc(hh, 'LCR_DownloadData');
LCR_WaitForFlashReady:= getProc(hh, 'LCR_WaitForFlashReady');
LCR_SetFlashType:= getProc(hh, 'LCR_SetFlashType');
LCR_CalculateFlashChecksum:= getProc(hh, 'LCR_CalculateFlashChecksum');
LCR_GetFlashChecksum:= getProc(hh, 'LCR_GetFlashChecksum');
LCR_SetMode:= getProc(hh, 'LCR_SetMode');
LCR_GetMode:= getProc(hh, 'LCR_GetMode');
LCR_LoadSplash:= getProc(hh, 'LCR_LoadSplash');
LCR_GetSplashIndex:= getProc(hh, 'LCR_GetSplashIndex');
LCR_SetTPGColor:= getProc(hh, 'LCR_SetTPGColor');
LCR_GetTPGColor:= getProc(hh, 'LCR_GetTPGColor');
LCR_ClearPatLut:= getProc(hh, 'LCR_ClearPatLut');
LCR_AddToPatLut:= getProc(hh, 'LCR_AddToPatLut');
LCR_GetPatLutItem:= getProc(hh, 'LCR_GetPatLutItem');
LCR_SendPatLut:= getProc(hh, 'LCR_SendPatLut');
LCR_SendSplashLut:= getProc(hh, 'LCR_SendSplashLut');
LCR_GetPatLut:= getProc(hh, 'LCR_GetPatLut');
LCR_GetSplashLut:= getProc(hh, 'LCR_GetSplashLut');
LCR_SetPatternTriggerMode:= getProc(hh, 'LCR_SetPatternTriggerMode');
LCR_GetPatternTriggerMode:= getProc(hh, 'LCR_GetPatternTriggerMode');
LCR_PatternDisplay:= getProc(hh, 'LCR_PatternDisplay');
LCR_SetPatternConfig:= getProc(hh, 'LCR_SetPatternConfig');
LCR_GetPatternConfig:= getProc(hh, 'LCR_GetPatternConfig');
LCR_SetExposure_FramePeriod:= getProc(hh, 'LCR_SetExposure_FramePeriod');
LCR_GetExposure_FramePeriod:= getProc(hh, 'LCR_GetExposure_FramePeriod');
LCR_SetTrigIn1Delay:= getProc(hh, 'LCR_SetTrigIn1Delay');
LCR_GetTrigIn1Delay:= getProc(hh, 'LCR_GetTrigIn1Delay');
LCR_SetInvertData:= getProc(hh, 'LCR_SetInvertData');
LCR_PWMCaptureRead:= getProc(hh, 'LCR_PWMCaptureRead');
LCR_SetGeneralPurposeClockOutFreq:= getProc(hh, 'LCR_SetGeneralPurposeClockOutFreq');
LCR_GetGeneralPurposeClockOutFreq:= getProc(hh, 'LCR_GetGeneralPurposeClockOutFreq');
LCR_MeasureSplashLoadTiming:= getProc(hh, 'LCR_MeasureSplashLoadTiming');
LCR_ReadSplashLoadTiming:= getProc(hh, 'LCR_ReadSplashLoadTiming');
// LCR_GetGammaCorrection:= getProc(hh, 'LCR_GetGammaCorrection');
// LCR_SetGammaCorrection:= getProc(hh, 'LCR_SetGammaCorrection');
// LCR_GetColorSpaceConversion:= getProc(hh, 'LCR_GetColorSpaceConversion');
USB_Open:= getProc(hh, 'USB_Open');
USB_IsConnected:= getProc(hh, 'USB_IsConnected');
USB_Write:= getProc(hh, 'USB_Write');
USB_Read:= getProc(hh, 'USB_Read');
USB_Close:= getProc(hh, 'USB_Close');
USB_Init:= getProc(hh, 'USB_Init');
USB_Exit:= getProc(hh, 'USB_Exit');
end;
end.
|
unit Odontologia.Modelo.Agenda.Interfaces;
interface
uses
Data.DB,
SimpleInterface,
Odontologia.Modelo.Estado.Cita.Interfaces,
Odontologia.Modelo.Medico.Interfaces,
Odontologia.Modelo.Paciente.Interfaces,
Odontologia.Modelo.Entidades.Agenda;
type
iModelAgenda = interface
['{A89CD856-0A9B-46E5-94E8-4D3FB4BC5CD7}']
function Entidad : TDAGENDA; overload;
function Entidad(aEntidad: TDAGENDA) : iModelAgenda; overload;
function DAO : iSimpleDAO<TDAGENDA>;
function DataSource(aDataSource: TDataSource) : iModelAgenda;
function Medico : iModelMedico;
function Paciente : iModelPaciente;
function EstadoCita : iModelEstadoCita;
end;
implementation
end.
|
//------------------------------------------------------------------------------
//! @author Polyakova M.V. Copyright (C) 2013 ILS LLC. All Rights Reserved.
//!
{ ! @file
@brief
Функции для работы с реестром
@details
В данном модуле реализованы следующие функции:
- считывание настроек ConnectionDBParams из реестра
- запись настроек в реестр
}
//------------------------------------------------------------------------------
unit MCLF_RWSR_SettingsRegistry;
interface
//------------------------------------------------------------------------------
uses
Windows, Messages, SysUtils, Classes, Registry, Vcl.Dialogs;
//------------------------------------------------------------------------------
type
//! Запись с параметрами соединения с БД
{! Содержит строку подключения к БД, таймаут
и ID последнего пользователя на данном компьюторе }
TConnectionDBParams = record
//! Таймаут подключения к БД
m_iTimeout: Smallint;
//! Строка соединения с БД
m_sConnectionString: string[255];
//! ID последнего пользователя
m_iLastUserID: Integer;
end;
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------- class TConnectionParamsInRegistry --------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//! Оператор настроек
{ ! Класс функций для работы с реестром:
считывание, запись настроек }
//------------------------------------------------------------------------------
TConnectionParamsInRegistry = class( TObject )
private
m_sMainRegistryKey : string;
m_sNameRegistry : string;
public
//! Конструктор по умолчанию
constructor Create (
const sMainRegistryKey : string = '\SOFTWARE\ILSystems\ILSMonitoring';
const sNameRegistry : string = 'Params' );
//! Деструктор класса, отменяем виртуальный метод уничтожения TObject
destructor Destroy; override;
//! Проверяем, запущена ли программа от имени администратора
function ProcessIsElevated: Boolean;
//! Считывание настроек из реестра
{ !
@param out
rcConnectionParams - настройки из реестра
@return
True при успешном выполнении }
function ReadSettingsFromRegistry ( var rcConnectionParams : TConnectionDBParams ): Boolean;
//! Запись настроек в реестр
{ ! @param in
rcConnectionParams - настройки
@return
True при успешном выполнении }
function WriteSettingsToRegistry ( var rcConnectionParams : TConnectionDBParams; const bNeedCreateKey : Boolean = False ): Boolean;
//! Проверка установлена ли служба
{
@return
True если установлена
}
function KeyExists( ): Boolean;
//! Проверка корректности настроек
function AreSettingsCorrect ( const rcConnectionParams : TConnectionDBParams ): Boolean;
//!Шифровка строки
{ @param in
sEncrypted Строка, подлежащая шифровке
@return
Зашифрованная строка
@author
Перепёлкин
}
function EncryptString( AString: AnsiString ): AnsiString;
//!Расшифровка строки (для чтения из реестра), зашифрованной с помощью утилиты GetDBConnection (ф-ция EncryptString)
{ @param in
sEncrypted Строка, подлежащая расшифровке
@return
Расшифрованная строка
@author
Максименко
}
function DecryptString( sEncrypted: AnsiString ): AnsiString;
//! Реализация записи в реестр
function WriteToRegistry( const sRootKey: HKEY; var iParams : Integer; const bNeedCreateKey : Boolean = False ): Boolean;
end;
const
//! сдвиг в таблице Ansi(используется в функциях шифровки и расшифровки строк)
bEncryptionShift: Byte = 100;
//var
//! признак того, что предложение перезапустить программу под админом уже показывалось
// (чтобы сообщение не показывалось при каждом обращении к реестру)
// bAdminMessageShown: Boolean = False ;
var
//! Если false, то данные в реестре незашифрованы
bRegistryCrypted: Boolean;
//------------------------------------------------------------------------------
implementation
//------------------------------------------------------------------------------
// Конструктор класса
//------------------------------------------------------------------------------
constructor TConnectionParamsInRegistry.Create(
const sMainRegistryKey : string = '\SOFTWARE\ILSystems\ILSMonitoring';
const sNameRegistry : string = 'Params' );
begin
inherited Create();
m_sMainRegistryKey := sMainRegistryKey;
m_sNameRegistry := sNameRegistry;
end;
//------------------------------------------------------------------------------
// Проверка корректности настроек
//------------------------------------------------------------------------------
function TConnectionParamsInRegistry.AreSettingsCorrect( const rcConnectionParams : TConnectionDBParams ): Boolean;
//------------------------------------------------------------------------------
var
// Признак ошибки
bErr: Boolean;
//------------------------------------------------------------------------------
begin
bErr := False;
// Проверяем заполненность параметров
if ( ( rcConnectionParams.m_sConnectionString = '' ) or ( rcConnectionParams.m_iTimeOut = 0 ) ) then
begin
bErr := True;
end;
Result := not bErr;
end;
//------------------------------------------------------------------------------
// Функция возвращает True если пользователь входит в группу
//------------------------------------------------------------------------------
function CheckTokenMembership(TokenHandle: THandle; SidToCheck: PSID; var
IsMember: BOOL): BOOL; stdcall; external advapi32;
//------------------------------------------------------------------------------
// Проверяем, запущена ли программа от имени администратора
//------------------------------------------------------------------------------
function TConnectionParamsInRegistry.ProcessIsElevated: Boolean;
//*** Максименко
const
// ID группы администраторов
AdminGroup = $00000220;
SECURITY_NT_AUTHORITY: TSIDIdentifierAuthority = (Value: (0, 0, 0, 0, 0, 5));
var
// указатель на токен
TokenHandle: THandle;
// буфер, в который функция GetTokenInformation пишет информацию о процессе
bufferTokenElevation: TOKEN_ELEVATION;
// размер буфера bufferTokenElevation
iBufferLength: Cardinal;
//указатель на структуру SID_IDENTIFIER_AUTHORITY
pIdentifierAuthority: TSIDIdentifierAuthority;
// указатель на идентификатор безопасности
pSid: Windows.PSID;
// результат проверки внешней функцией CheckTokenMembership
bIsMember: BOOL;
begin
TokenHandle := 0;
if CheckWin32Version( 6, 0 ) then //Vista или выше
begin
if OpenProcessToken( GetCurrentProcess, TOKEN_QUERY, TokenHandle ) then
begin
if GetTokenInformation( TokenHandle, TokenElevation, @bufferTokenElevation, SizeOf( bufferTokenElevation ), iBufferLength ) then
begin
if ( bufferTokenElevation.TokenIsElevated <> 0 ) then
begin
Result := True;
end
else
begin
Result := False;
end;
end
else
begin
Result := false;
end;
end
else
begin
Result := False;
end;
end
else
begin
pIdentifierAuthority := SECURITY_NT_AUTHORITY;
try
if AllocateAndInitializeSid( pIdentifierAuthority, 2, $00000020, AdminGroup, 0, 0, 0, 0, 0, 0, pSid ) then
begin
if not CheckTokenMembership( 0, pSid, bIsMember ) then
Result := False
else
Result := bIsMember;
end;
finally
FreeSid(pSid);
end;
end;
end;
//------------------------------------------------------------------------------
// Считывание настроек из реестра
//------------------------------------------------------------------------------
function TConnectionParamsInRegistry.ReadSettingsFromRegistry ( var rcConnectionParams : TConnectionDBParams ): Boolean;
//------------------------------------------------------------------------------
var
// Переменная для работы с реестром
Reg: TRegistry;
// Признак ошибки
bErr: Boolean;
// Переменная, в которую пишем тип параметра
regdatatypeParam: TRegDataType;
//------------------------------------------------------------------------------
begin
bErr := False;
// Читаем параметры из реестра
Reg := TRegistry.Create;
Reg.RootKey := HKEY_LOCAL_MACHINE;
if ( Reg.KeyExists( m_sMainRegistryKey ) = True ) then
begin
// Читаем параметры
try
Reg.OpenKeyReadOnly ( m_sMainRegistryKey );
Reg.ReadBinaryData( m_sNameRegistry, rcConnectionParams, SizeOf( rcConnectionParams ) );
(*if
//( Reg.ReadBinaryData( m_sNameRegistry, rcConnectionParams, SizeOf( rcConnectionParams ) ) = 0 ) and
( ProcessIsElevated () = False ) and ( bAdminMessageShown = False ) then
begin
ShowMessage( 'Невозможно прочитать данные из реестра. Попробуйте перезапустить программу от имени администратора!' );
bAdminMessageShown := True;
end; *)
//если зашифровано
if Pos( 'Password', rcConnectionParams.m_sConnectionString ) = 0 then
begin
rcConnectionParams.m_sConnectionString := DecryptString( rcConnectionParams.m_sConnectionString );
bRegistryCrypted := True;
end
else
begin
// Если данные в реестре незашифрованы, то не пускаем пользователя и рекомендуем обновить настройки в GetDBConnection
bErr := False; //bErr := True;
bRegistryCrypted := False;
{mAuthorization.cxTextEditPassword.Enabled := False;
fmAuthorization.cxButtonOk.Enabled := False;
fmAuthorization.cxLabelErrMess.Caption := 'Перенастройте соединение с помощью утилиты GetDBConnection!';}
end;
Reg.CloseKey;
except
on E: Exception do
begin
bErr := True;
(*
исключений при отсутствии доступа не наблюдается, поэтому убрано
if {( ProcessIsElevated ( ) = False ) and} ( bAdminMessageShown = False ) then
begin
ShowMessage( 'Невозможно прочитать данные из реестра. Попробуйте перезапустить программу от имени администратора!!' );
bAdminMessageShown := True;
end; *)
end;
end;
end
else
begin
bErr := True;
end;
Reg.Free();
Result := not bErr;
end;
//------------------------------------------------------------------------------
// Проверка установлена ли служба
//------------------------------------------------------------------------------
function TConnectionParamsInRegistry.KeyExists( ): Boolean;
//------------------------------------------------------------------------------
var
// Переменная для работы с реестром
ctRegistry: TRegistry;
// Признак ошибки
bErr: Boolean;
//------------------------------------------------------------------------------
begin
bErr := False;
ctRegistry := TRegistry.Create;
ctRegistry.RootKey := HKEY_LOCAL_MACHINE;
if ( ctRegistry.KeyExists ( m_sMainRegistryKey ) = False ) then
begin
bErr := True;
end;
ctRegistry.Free;
Result := not bErr;
end;
//------------------------------------------------------------------------------
// Реализация записи параметров в реестр
//------------------------------------------------------------------------------
function TConnectionParamsInRegistry.WriteSettingsToRegistry ( var rcConnectionParams : TConnectionDBParams; const bNeedCreateKey : Boolean = False ): Boolean;
//------------------------------------------------------------------------------
var
// Переменная для работы с реестром
ctRegistry: TRegistry;
// Признак ошибки
bErr: Boolean;
//------------------------------------------------------------------------------
begin
bErr := False;
ctRegistry := TRegistry.Create;
ctRegistry.RootKey := HKEY_LOCAL_MACHINE;
if (( ctRegistry.KeyExists( m_sMainRegistryKey ) = False ) and ( bNeedCreateKey = True )) then
begin
ctRegistry.CreateKey( m_sMainRegistryKey );
end;
if ( ctRegistry.KeyExists( m_sMainRegistryKey ) = True ) then
begin
try
ctRegistry.OpenKey( m_sMainRegistryKey, True );
rcConnectionParams.m_sConnectionString := EncryptString(rcConnectionParams.m_sConnectionString);
ctRegistry.WriteBinaryData( m_sNameRegistry, rcConnectionParams, SizeOf( rcConnectionParams ) );
ctRegistry.CloseKey;
except
on E: Exception do
begin
bErr := True;
end;
end;
end;
ctRegistry.Free();
Result := not bErr;
end;
//------------------------------------------------------------------------------
// Шифровка строки (для записи в реестр)
//------------------------------------------------------------------------------
function TConnectionParamsInRegistry.EncryptString( AString: AnsiString ): AnsiString;
var
// Счетчик номера символа в строке
i: Integer;
// номер в таблице ANSI расшифрованного байта
EncryptedCharNumber: Byte;
// строка для записи результата расшифровки
EncryptedString: string;
begin
EncryptedString := '';
for i := 1 to Length(AString) do
begin
EncryptedCharNumber := ( Ord(AString[i]) + bEncryptionShift ) mod 256;
EncryptedString := EncryptedString + AnsiChar(EncryptedCharNumber);
end;
Result := EncryptedString;
end;
//------------------------------------------------------------------------------
// Расшифровка строки (для чтения из реестра), зашифрованной с помощью утилиты
// GetDBConnection (ф-ция EncryptString)
//------------------------------------------------------------------------------
function TConnectionParamsInRegistry.DecryptString( sEncrypted: AnsiString ): AnsiString;
var
// Счетчик номера символа в строке
i: Integer;
// номер в таблице ANSI расшифрованного байта
bDecryptedChar: Byte;
// строка для записи результата расшифровки
sDecrypted: string;
begin
bDecryptedChar := 0;
sDecrypted := '';
for i := 1 to Length( sEncrypted ) do
begin
{в зашифрованной строке все символы "сдвинуты" по таблице ANSI на bEncryptionShift позиций,
для расшифровки "сдвигаем" обратно}
bDecryptedChar := ( Ord( sEncrypted[ i ] ) + ( 256 - bEncryptionShift ) ) mod 256;
sDecrypted := sDecrypted + AnsiChar( bDecryptedChar );
end;
Result := sDecrypted;
end;
//------------------------------------------------------------------------------
// Реализация записи в реестр
//------------------------------------------------------------------------------
function TConnectionParamsInRegistry.WriteToRegistry ( const sRootKey: HKEY; var iParams : Integer; const bNeedCreateKey : Boolean = False ): Boolean;
//------------------------------------------------------------------------------
var
// Переменная для работы с реестром
ctRegistry: TRegistry;
// Признак ошибки
bErr: Boolean;
//------------------------------------------------------------------------------
begin
bErr := False;
ctRegistry := TRegistry.Create;
ctRegistry.RootKey := sRootKey;
if (( ctRegistry.KeyExists( m_sMainRegistryKey ) = False ) and ( bNeedCreateKey = True )) then
begin
ctRegistry.CreateKey( m_sMainRegistryKey );
end;
if ( ctRegistry.KeyExists( m_sMainRegistryKey ) = True ) then
begin
try
ctRegistry.OpenKey( m_sMainRegistryKey, True );
ctRegistry.WriteInteger( m_sNameRegistry, iParams );
ctRegistry.CloseKey;
except
on E: Exception do
begin
bErr := True;
end;
end;
end;
ctRegistry.Free();
Result := not bErr;
end;
//------------------------------------------------------------------------------
// Деструктор класса
//------------------------------------------------------------------------------
destructor TConnectionParamsInRegistry.Destroy;
begin
inherited Destroy;
end;
end.
|
unit uRunOnce;
interface
uses PersonalCommon, uCommonDB, DB, Controls, SysUtils;
procedure RunOnce;
implementation
resourcestring histSQL = 'SELECT * FROM Act_History WHERE Name_Action = ''TableFHoursFix''';
resourcestring CurDateSelectSQL = 'SELECT DISTINCT Tbl_Day, Table_MONTH, Table_YEAR FROM Dt_Table';
resourcestring UpdateDateSQL = 'UPDATE Dt_Table SET Cur_Date = :Cur_Date WHERE ' +
' Tbl_Day = :Tbl_Day AND Table_YEAR = :Year AND Table_MONTH = :Month';
resourcestring SelectHoursSQL = 'SELECT DISTINCT Hours FROM Dt_Table';
resourcestring UpdateHoursSQL = 'UPDATE Dt_Table SET Hours_F=:Hours_F WHERE Hours=:Hours';
resourcestring SelectNHoursSQL = 'SELECT DISTINCT NHours FROM Dt_Table';
resourcestring UpdateNHoursSQL = 'UPDATE Dt_Table SET NHours_F=:NHours_F WHERE NHours=:NHours';
resourcestring SelectGHoursSQL = 'SELECT DISTINCT GHours FROM Dt_Table';
resourcestring UpdateGHoursSQL = 'UPDATE Dt_Table SET GHours_F=:GHours_F WHERE GHours=:GHours';
resourcestring SelectPHoursSQL = 'SELECT DISTINCT PHours FROM Dt_Table';
resourcestring UpdatePHoursSQL = 'UPDATE Dt_Table SET PHours_F=:PHours_F WHERE PHours=:PHours';
resourcestring SelectVHoursSQL = 'SELECT DISTINCT VHours FROM Dt_Table';
resourcestring UpdateVHoursSQL = 'UPDATE Dt_Table SET VHours_F=:VHours_F WHERE VHours=:VHours';
procedure TableFHoursFix;
var
histDs: TDataSet;
CurDateSelect: TDataSet;
Cur_Date: Variant;
TmpDS: TDataSet;
begin
histDs := Curr_DB.QueryData(histSQL);
if not histDs.Locate('Info', 'Cur_Date', []) then
begin
CurDateSelect := Curr_DB.QueryData(CurDateSelectSQL);
CurDateSelect.First;
while not CurDateSelect.Eof do
begin
Curr_DB.StoreFields(CurDateSelect, 'Tbl_Day, Table_Year, Table_Month');
Cur_Date := EncodeDate(Curr_DB['Table_Year'], Curr_DB['Table_Month'], Curr_DB['Tbl_Day']);
Curr_DB['Cur_Date'] := Cur_Date;
Curr_DB.ExecQuery(UpdateDateSQL, 'Cur_Date, Tbl_Day, Table_Month, Table_Year');
CurDateSelect.Next;
end;
Curr_DB.RemoveDataset(CurDateSelect);
Log_Action('TableFHoursFix', 'Cur_Date');
end;
if not histDs.Locate('Info', 'Hours_F', []) then
begin
TmpDs := Curr_DB.QueryData(SelectHoursSQL);
TmpDs.First;
while not TmpDs.Eof do
begin
Curr_DB.StoreFields(TmpDs, 'Hours');
Curr_DB['Hours_F'] := 24 * Curr_DB['Hours'];
Curr_DB.ExecQuery(UpdateHoursSQL, 'Hours_F, Hours');
TmpDs.Next;
end;
Curr_DB.RemoveDataset(TmpDs);
Log_Action('TableFHoursFix', 'Hours_F');
end;
if not histDs.Locate('Info', 'GHours_F', []) then
begin
TmpDs := Curr_DB.QueryData(SelectGHoursSQL);
TmpDs.First;
while not TmpDs.Eof do
begin
Curr_DB.StoreFields(TmpDs, 'GHours');
Curr_DB['GHours_F'] := 24 * Curr_DB['GHours'];
Curr_DB.ExecQuery(UpdateGHoursSQL, 'GHours_F, GHours');
TmpDs.Next;
end;
Curr_DB.RemoveDataset(TmpDs);
Log_Action('TableFHoursFix', 'GHours_F');
end;
if not histDs.Locate('Info', 'NHours_F', []) then
begin
TmpDs := Curr_DB.QueryData(SelectNHoursSQL);
TmpDs.First;
while not TmpDs.Eof do
begin
Curr_DB.StoreFields(TmpDs, 'NHours');
Curr_DB['NHours_F'] := 24 * Curr_DB['NHours'];
Curr_DB.ExecQuery(UpdateNHoursSQL, 'NHours_F, NHours');
TmpDs.Next;
end;
Curr_DB.RemoveDataset(TmpDs);
Log_Action('TableFHoursFix', 'NHours_F');
end;
if not histDs.Locate('Info', 'PHours_F', []) then
begin
TmpDs := Curr_DB.QueryData(SelectPHoursSQL);
TmpDs.First;
while not TmpDs.Eof do
begin
Curr_DB.StoreFields(TmpDs, 'PHours');
Curr_DB['PHours_F'] := 24 * Curr_DB['PHours'];
Curr_DB.ExecQuery(UpdatePHoursSQL, 'PHours_F, PHours');
TmpDs.Next;
end;
Curr_DB.RemoveDataset(TmpDs);
Log_Action('TableFHoursFix', 'PHours_F');
end;
if not histDs.Locate('Info', 'VHours_F', []) then
begin
TmpDs := Curr_DB.QueryData(SelectVHoursSQL);
TmpDs.First;
while not TmpDs.Eof do
begin
Curr_DB.StoreFields(TmpDs, 'VHours');
Curr_DB['VHours_F'] := 24 * Curr_DB['VHours'];
Curr_DB.ExecQuery(UpdateVHoursSQL, 'VHours_F, VHours');
TmpDs.Next;
end;
Curr_DB.RemoveDataset(TmpDs);
Log_Action('TableFHoursFix', 'VHours_F');
end;
Curr_DB.RemoveDataset(histDs);
end;
procedure RunOnce;
begin
TableFHoursFix;
end;
end.
|
// +-------------------------------------------------------------------------
// Microsoft Windows
// Copyright (c) Microsoft Corporation. All rights reserved.
// --------------------------------------------------------------------------
unit CMC.HString;
{$IFDEF FPC}
{$MODE delphi}
{$ENDIF}
interface
uses
Windows, Classes, SysUtils;
type
// Declaring a handle dummy struct for HSTRING the same way DECLARE_HANDLE does.
HSTRING__ = record
unused: integer;
end;
// Declare the HSTRING handle for C/C++
HString = ^HSTRING__;
// Declare the HSTRING_HEADER
THSTRING_HEADER = record
case integer of
0:
(Reserved1: pointer);
1:
(
{$IFDEF WIN64}
Reserved2: array [0 .. 23] of char;
{$ELSE}
Reserved2: array [0 .. 19] of char;
{$ENDIF}
);
end;
// Declare the HSTRING_BUFFER for the HSTRING's two-phase construction functions.
// This route eliminates the PCWSTR string copy that happens when passing it to
// the traditional WindowsCreateString(). The caller preallocates a string buffer,
// sets the wide character string values in that buffer, and finally promotes the
// buffer to an HSTRING. If a buffer is never promoted, it can still be deleted.
HSTRING_BUFFER = pointer;
implementation
end.
|
unit ULoteVO;
interface
uses Atributos, Classes, Constantes, Generics.Collections, SysUtils, UGenericVO, UCondominioVO;
type
[TEntity]
[TTable('Lote')]
TLoteVO = class(TGenericVO)
private
FidLote : Integer;
FdtLote : TDateTime;
FnrLote : String;
FdsLote : String;
FidCondominio : Integer;
public
CondominioVO : TCondominioVO;
[TId('idLote')]
[TGeneratedValue(sAuto)]
property idLote : Integer read FidLote write FidLote;
[TColumn('dtLote','Data',0,[ldGrid,ldLookup,ldComboBox], False)]
property dtLote: TDateTime read FdtLote write FdtLote;
[TColumn('nrLote','Lote',50,[ldGrid,ldLookup,ldComboBox], False)]
property nrLote: String read FnrLote write FnrLote;
[TColumn('dsLote','Descrição',600,[ldGrid,ldLookup,ldComboBox], False)]
property dsLote: string read FdsLote write FdsLote;
[TColumn('idCondominio','Condominio',0,[ldLookup,ldComboBox], False)]
property idCondominio: integer read FidCondominio write FidCondominio;
procedure ValidarCamposObrigatorios;
end;
implementation
procedure TLoteVO.ValidarCamposObrigatorios;
begin
if (self.FDtLote = 0) then
begin
raise Exception.Create('O campo Data é obrigatório!');
end;
if (Self.FnrLote = '') then
begin
raise Exception.Create('O campo Lote é obrigatório!');
end;
end;
end.
|
unit Dsource;
{-------------------------------------------------------------------}
{ Unit: Dsource.pas }
{ Project: EPANET2W }
{ Version: 2.0 }
{ Date: 5/29/00 }
{ 11/19/01 }
{ 6/25/07 }
{ Author: L. Rossman }
{ }
{ Form unit with a dialog box that edits water quality source }
{ options for a node. }
{ }
{ This unit and its form were totally re-written. - 6/25/07 }
{-------------------------------------------------------------------}
interface
uses
Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, StdCtrls, Uglobals, NumEdit;
type
TSourceForm = class(TForm)
NumEdit1: TNumEdit;
Edit1: TEdit;
Label1: TLabel;
Label2: TLabel;
BtnOK: TButton;
BtnCancel: TButton;
BtnHelp: TButton;
Label3: TLabel;
NumEdit2: TNumEdit;
Label4: TLabel;
NumEdit3: TNumEdit;
Label5: TLabel;
ComboBox1: TComboBox;
Label6: TLabel;
Label7: TLabel;
Bevel1: TBevel;
procedure FormCreate(Sender: TObject);
procedure BtnCancelClick(Sender: TObject);
procedure BtnOKClick(Sender: TObject);
procedure BtnHelpClick(Sender: TObject);
private
{ Private declarations }
theNode: TNode;
theIndex: Integer;
theItemIndex: Integer;
public
{ Public declarations }
Modified: Boolean;
end;
//var
// SourceForm: TSourceForm;
implementation
{$R *.DFM}
procedure TSourceForm.FormCreate(Sender: TObject);
//--------------------------------------------------
// OnCreate handler for form.
//--------------------------------------------------
var
i: Integer;
begin
// Set form's font
Uglobals.SetFont(self);
// Get pointer to node being edited
theNode := Node(CurrentList, CurrentItem[CurrentList]);
// Get index of Source Quality property for the node
case CurrentList of
JUNCS: theIndex := JUNC_SRCTYPE_INDEX;
RESERVS: theIndex := RES_SRCTYPE_INDEX;
TANKS: theIndex := TANK_SRCTYPE_INDEX;
else theIndex := -1;
end;
// Load current source quality properties into the form
if theIndex > 0 then
begin
ComboBox1.ItemIndex := 0;
for i := Low(SourceType) to High(SourceType) do
if SameText(theNode.Data[theIndex],SourceType[i]) then
begin
ComboBox1.ItemIndex := i;
break;
end;
NumEdit1.Text := theNode.Source.Quality;
Edit1.Text := theNode.Source.Pattern;
NumEdit2.Text := theNode.Source.Start;
NumEdit3.Text := theNode.Source.Duration;
end;
theItemIndex := ComboBox1.ItemIndex;
Modified := False;
end;
procedure TSourceForm.BtnOKClick(Sender: TObject);
//----------------------------------------------------
// OnClick handler for OK button.
// Transfers data from form to node being edited.
//----------------------------------------------------
begin
if theIndex > 0 then
begin
if Length(Trim(NumEdit1.Text)) = 0 then
begin
theNode.Source.Quality := '';
theNode.Source.Pattern := '';
theNode.Source.Start := '';
theNode.Source.Duration := '';
theNode.Data[theIndex] := SourceType[ComboBox1.ItemIndex];
end
else
begin
theNode.Data[theIndex] := SourceType[ComboBox1.ItemIndex];
theNode.Source.Quality := NumEdit1.Text;
theNode.Source.Pattern := Edit1.Text;
theNode.Source.Start := NumEdit2.Text;
theNode.Source.Duration := NumEdit3.Text;
end;
end;
if (NumEdit1.Modified)
or (Edit1.Modified)
or (NumEdit2.Modified)
or (NumEdit3.Modified)
or (ComboBox1.ItemIndex <> theItemIndex)
then Modified := True;
ModalResult := mrOK;
end;
procedure TSourceForm.BtnCancelClick(Sender: TObject);
//----------------------------------------------------
// OnClick handler for Cancel button.
//----------------------------------------------------
begin
ModalResult := mrCancel;
end;
procedure TSourceForm.BtnHelpClick(Sender: TObject);
begin
Application.HelpContext(245);
end;
end.
|
unit ThWebDataDictionary;
interface
uses
SysUtils, Classes, Controls, ThContent, ThWebVariable;
type
TThDictionaryDatum = class(TCollectionItem)
private
FDatum: TThDatum;
protected
function GetDisplayName: string; override;
function GetValidator: TThValidator;
function GetWebName: string;
function GetWebValue: string;
procedure SetDisplayName(const Value: string); override;
procedure SetValidator(const Value: TThValidator);
procedure SetWebName(const Value: string);
procedure SetWebValue(const Value: string);
protected
function OwnerComponent: TComponent;
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
procedure Notification(AComponent: TComponent; Operation: TOperation);
published
property DisplayName;
property WebName: string read GetWebName write SetWebName;
property WebValue: string read GetWebValue write SetWebValue;
property Validator: TThValidator read GetValidator write SetValidator;
end;
//
TThDictionaryData = class(TOwnedCollection)
private
function GetDictionaryItems(inIndex: Integer): TThDictionaryDatum;
procedure SetDictionaryItems(inIndex: Integer;
const Value: TThDictionaryDatum);
function GetNamedItems(const inName: string): TThDictionaryDatum;
procedure SetNamedItems(const inName: string;
const Value: TThDictionaryDatum);
public
constructor Create(AOwner: TComponent);
function AddItem: TThDictionaryDatum;
procedure ClearData;
function Find(const inName: string): TThDictionaryDatum; overload;
function Find(const inName: string;
out outItem: TThDictionaryDatum): Boolean; overload;
procedure Notification(AComponent: TComponent; Operation: TOperation);
procedure UpdateFromParams(inParams: TStrings);
public
property DictionaryItems[inIndex: Integer]: TThDictionaryDatum
read GetDictionaryItems write SetDictionaryItems; default;
property NamedItems[const inName: string]: TThDictionaryDatum
read GetNamedItems write SetNamedItems;
end;
//
TThWebDataDictionary = class(TThContentBase)
private
FData: TThDictionaryData;
function GetNamedItems(const inName: string): TThDictionaryDatum;
procedure SetNamedItems(const inName: string;
const Value: TThDictionaryDatum);
protected
procedure SetData(const Value: TThDictionaryData);
protected
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure ContentFromParams(const inParams: TStrings); override;
function HasNamedContent(const inName: string;
out outContent: string): Boolean; override;
public
property NamedItems[const inName: string]: TThDictionaryDatum
read GetNamedItems write SetNamedItems; default;
published
property Data: TThDictionaryData read FData
write SetData;
end;
//
TThDictionaryIterator = class(TList)
private
function GetDictionary: TThWebDataDictionary;
procedure ListComponents(inClass: TClass);
function GetDictionaries(inIndex: Integer): TThWebDataDictionary;
procedure SetContainer(const Value: TComponent);
protected
FContainer: TComponent;
FIndex: Integer;
public
constructor Create(inContainer: TComponent = nil);
function Next: Boolean;
procedure Reset;
property Container: TComponent read FContainer write SetContainer;
property Dictionary: TThWebDataDictionary read GetDictionary;
property Dictionaries[inIndex: Integer]: TThWebDataDictionary
read GetDictionaries;
property Index: Integer read FIndex write FIndex;
end;
implementation
{ TThDictionaryDatum }
constructor TThDictionaryDatum.Create(Collection: TCollection);
begin
inherited;
FDatum := TThDatum.Create;
end;
destructor TThDictionaryDatum.Destroy;
begin
FDatum.Free;
inherited;
end;
function TThDictionaryDatum.OwnerComponent: TComponent;
begin
Result := TComponent(Collection.Owner);
end;
function TThDictionaryDatum.GetValidator: TThValidator;
begin
Result := FDatum.Validator;
end;
procedure TThDictionaryDatum.SetValidator(const Value: TThValidator);
begin
if Validator <> nil then
Validator.RemoveFreeNotification(OwnerComponent);
FDatum.Validator := Value;
if Validator <> nil then
Validator.FreeNotification(OwnerComponent);
end;
procedure TThDictionaryDatum.Notification(AComponent: TComponent;
Operation: TOperation);
begin
if (Operation = opRemove) and (AComponent = Validator) then
FDatum.Validator := nil;
end;
function TThDictionaryDatum.GetWebName: string;
begin
Result := FDatum.WebName;
end;
function TThDictionaryDatum.GetWebValue: string;
begin
Result := FDatum.WebValue;
end;
procedure TThDictionaryDatum.SetWebName(const Value: string);
begin
if Value = '' then
FDatum.WebName := 'Unnamed'
else
FDatum.WebName := Value;
end;
procedure TThDictionaryDatum.SetWebValue(const Value: string);
begin
FDatum.WebValue := Value;
end;
function TThDictionaryDatum.GetDisplayName: string;
begin
Result := FDatum.DisplayName;
end;
procedure TThDictionaryDatum.SetDisplayName(const Value: string);
begin
FDatum.DisplayName := Value;
end;
{ TThDictionaryData }
constructor TThDictionaryData.Create(AOwner: TComponent);
begin
inherited Create(AOwner, TThDictionaryDatum);
end;
function TThDictionaryData.AddItem: TThDictionaryDatum;
begin
Result := TThDictionaryDatum(Add);
end;
function TThDictionaryData.Find(
const inName: string): TThDictionaryDatum;
var
i: Integer;
begin
for i := 0 to Pred(Count) do
if DictionaryItems[i].WebName = inName then
begin
Result := DictionaryItems[i];
exit;
end;
Result := nil;
end;
function TThDictionaryData.Find(const inName: string;
out outItem: TThDictionaryDatum): Boolean;
begin
outItem := Find(inName);
Result := (outItem <> nil);
end;
function TThDictionaryData.GetDictionaryItems(
inIndex: Integer): TThDictionaryDatum;
begin
Result := TThDictionaryDatum(Items[inIndex]);
end;
procedure TThDictionaryData.Notification(AComponent: TComponent;
Operation: TOperation);
var
i: Integer;
begin
for i := 0 to Pred(Count) do
DictionaryItems[i].Notification(AComponent, Operation);
end;
procedure TThDictionaryData.SetDictionaryItems(inIndex: Integer;
const Value: TThDictionaryDatum);
begin
Items[inIndex] := Value;
end;
procedure TThDictionaryData.UpdateFromParams(inParams: TStrings);
var
i: Integer;
begin
for i := 0 to Pred(Count) do
with DictionaryItems[i] do
if inParams.IndexOfName(WebName) >= 0 then
WebValue := inParams.Values[WebName];
end;
procedure TThDictionaryData.ClearData;
var
i: Integer;
begin
for i := 0 to Pred(Count) do
with DictionaryItems[i] do
WebValue := '';
end;
function TThDictionaryData.GetNamedItems(
const inName: string): TThDictionaryDatum;
begin
Result := Find(inName);
end;
procedure TThDictionaryData.SetNamedItems(const inName: string;
const Value: TThDictionaryDatum);
begin
Find(inName).Assign(Value);
end;
{ TThWebDataDictionary }
procedure TThWebDataDictionary.ContentFromParams(
const inParams: TStrings);
begin
Data.UpdateFromParams(inParams);
end;
constructor TThWebDataDictionary.Create(AOwner: TComponent);
begin
inherited;
FData := TThDictionaryData.Create(Self);
end;
destructor TThWebDataDictionary.Destroy;
begin
inherited;
end;
function TThWebDataDictionary.HasNamedContent(const inName: string;
out outContent: string): Boolean;
var
datum: TThDictionaryDatum;
begin
Result := Data.Find(inName, datum);
if Result then
outContent := datum.WebValue;
end;
procedure TThWebDataDictionary.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if Data <> nil then
Data.Notification(AComponent, Operation);
end;
procedure TThWebDataDictionary.SetData(const Value: TThDictionaryData);
begin
FData.Assign(Value);
end;
function TThWebDataDictionary.GetNamedItems(
const inName: string): TThDictionaryDatum;
begin
Result := Data.NamedItems[inName];
end;
procedure TThWebDataDictionary.SetNamedItems(const inName: string;
const Value: TThDictionaryDatum);
begin
Data.NamedItems[inName] := Value;
end;
{ TThDictionaryIterator }
constructor TThDictionaryIterator.Create(inContainer: TComponent);
begin
FIndex := -1;
Container := inContainer;
end;
function TThDictionaryIterator.GetDictionaries(
inIndex: Integer): TThWebDataDictionary;
begin
Result := TThWebDataDictionary(Items[inIndex]);
end;
procedure TThDictionaryIterator.ListComponents(inClass: TClass);
var
i: Integer;
begin
Clear;
if FContainer <> nil then
for i := 0 to FContainer.ComponentCount - 1 do
if FContainer.Components[i] is inClass then
Add(FContainer.Components[i]);
end;
procedure TThDictionaryIterator.Reset;
begin
Index := -1;
end;
function TThDictionaryIterator.Next: Boolean;
begin
Inc(FIndex);
Result := Index < Count;
if not Result then
Reset;
end;
function TThDictionaryIterator.GetDictionary: TThWebDataDictionary;
begin
Result := Dictionaries[Index];
end;
procedure TThDictionaryIterator.SetContainer(const Value: TComponent);
begin
FContainer := Value;
ListComponents(TThWebDataDictionary);
end;
end.
|
(*
* FPG EDIT : Edit FPG file from DIV2, FENIX and CDIV
*
*
* 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 uFrmExport;
interface
uses
LCLIntf, LCLType, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ExtCtrls,
uIniFile, ShellCtrls;
type
{ TfrmExport }
TfrmExport = class(TForm)
bbExport: TBitBtn;
gbImages: TGroupBox;
DirectoryListBox1: TShellTreeView ;
Panel1: TPanel;
rgResType: TRadioGroup;
rgFilename: TRadioGroup;
procedure bbExportClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDeactivate(Sender: TObject);
procedure FormActivate(Sender: TObject);
private
{ Private declarations }
_lng_str : string;
procedure _set_lng;
public
last_itemindex: integer;
{ Public declarations }
end;
var
frmExport: TfrmExport;
implementation
{$R *.lfm}
procedure TfrmExport._set_lng;
begin
if _lng_str = inifile_language then
Exit;
_lng_str := inifile_language;
end;
procedure TfrmExport.FormCreate(Sender: TObject);
begin
last_itemindex := 0;
end;
procedure TfrmExport.bbExportClick(Sender: TObject);
begin
end;
procedure TfrmExport.FormDeactivate(Sender: TObject);
begin
last_itemindex := rgResType.ItemIndex;
end;
procedure TfrmExport.FormActivate(Sender: TObject);
begin
_set_lng;
end;
end.
|
unit SYS_OPTIONS;
interface
uses pFIBDatabase, pFIBQuery, Controls, Classes, Graphics, IBase;
type
TAccessResult=record
Login : string;
Pswrd : string;
Name_User : string;
ID_User : integer;
User_Id_Card : integer;
User_Fio : string;
Connection : TISC_DB_HANDLE;
end;
const
SYS_TABLE = 'SYS_OPTIONS';
SYS_PASSWORD = 'aLxWjCREFG';
var
SYS_SERVER : integer;
SYS_MAX_DATE : TDate;
SYS_MAX_TIMESTAMP : TDateTime;
SYS_MIN_TIMESTAMP : TDateTime;
SYS_START_DATE : TDate;
SYS_DEF_ID_DEPARTMENT : integer;
SYS_DEF_NAME_DEPARTMENT : string;
EXCH_NAME_DEPARTMENT : string;
SYS_EXCH_ROLLBACK : boolean;
SYS_EXCH_CHECK_ID : boolean;
AccessResult : TAccessResult;
procedure sys_ReadOptions(ReadTransaction : TpFIBTransaction);
implementation
uses SysUtils, FIBQuery, BaseTypes;
procedure sys_ReadOptions(ReadTransaction : TpFIBTransaction);
var
Query : TpFIBQuery;
begin
Query := TpFIBQuery.Create(Nil);
Query.Transaction := ReadTransaction;
Query.SQL.Text := 'select * from SYS_OPTIONS';
Query.ExecQuery;
SYS_SERVER := Query['ID_SERVER'].Value;
SYS_MAX_DATE := Query['MAX_DATE'].Value;
SYS_MAX_TIMESTAMP := Query['MAX_TIMESTAMP'].Value;
SYS_MIN_TIMESTAMP := Query['MIN_TIMESTAMP'].AsDateTime;
SYS_START_DATE := Query['START_DATE'].AsDate;
SYS_EXCH_ROLLBACK := (Query['EXCH_ROLLBACK'].AsInteger = 1);
SYS_EXCH_CHECK_ID := (Query['EXCH_CHECK_ID'].AsInteger = 1);
SYS_DEF_ID_DEPARTMENT := Query['ID_DEPARTMENT'].AsInteger;
Query.Close;
Query.SQl.Text := 'select NAME_SHORT from SP_DEPARTMENT where ID_DEPARTMENT = ' + IntToStr(SYS_DEF_ID_DEPARTMENT);
Query.ExecQuery;
SYS_DEF_NAME_DEPARTMENT := Query['NAME_SHORT'].AsString;
Query.Close;
Query.SQL.Text := 'select ID_USER from USERS where ID_USER_EXT='
+ IntToStr(CurrentID_PCARD);
Query.ExecQuery;
id_user := Query.Fields[0].AsInteger;
Query.Close;
Query.SQL.Text := 'select SHORT_NAME from EXCH_INI_SERVERS where ID_SERVER='
+ IntToStr(SYS_SERVER);
Query.ExecQuery;
EXCH_NAME_DEPARTMENT := Query.Fields[0].AsString;
Query.Close;
Query.Free;
end;
begin
ShortDateFormat := 'dd.MM.yyyy';
DecimalSeparator := ',';
SYS_MAX_TIMESTAMP := StrToDate('30.12.9999');
SYS_MAX_DATE := StrToDate('30.12.9999');
end.
|
unit HumDB;
interface
uses
Windows, Classes, SysUtils, Forms, Share, Mudutil;
type
TIdxHeader = packed record //Size 124
sDesc: string[39]; //0x00
n2C: Integer; //0x2C
n30: Integer; //0x30
n34: Integer; //0x34
n38: Integer; //0x38
n3C: Integer; //0x3C
n40: Integer; //0x40
n44: Integer; //0x44
n48: Integer; //0x48
n4C: Integer; //0x4C
n50: Integer; //0x50
n54: Integer; //0x54
n58: Integer; //0x58
n5C: Integer; //0x5C
n60: Integer; //0x60 95
n70: Integer; //0x70 99
nQuickCount: Integer; //0x74 100
nHumCount: Integer; //0x78
nDeleteCount: Integer; //0x7C
nLastIndex: Integer; //0x80
dUpdateDate: TDateTime; //更新日期
end;
pTIdxHeader = ^TIdxHeader;
TIdxRecord = record
sChrName: string[15];
nIndex: Integer;
end;
pTIdxRecord = ^TIdxRecord;
TFileDB = class{读取BLUE Mir.DB类,以提速对比}
n4: Integer; //0x4
m_nFileHandle: Integer; //0x08
nC: Integer;
m_OnChange: TNotifyEvent; //0x10
m_boChanged: Boolean; //0x18
m_nLastIndex: Integer; //0x1C
m_dUpdateTime: TDateTime; //0x20
m_Header: TDBHeader1; //0x28
m_QuickList: TQuickList; //0xA4
m_DeletedList: TList; //已被删除的记录号
m_sDBFileName: string; //0xAC
m_sIdxFileName: string; //0xB0
private
procedure LoadQuickList;
function LoadDBIndex(): Boolean;
procedure SaveIndex();
function GetRecord(nIndex: Integer; var HumanRCD: TLF_HumDataInfo): Boolean;//获得记录
public
constructor Create(sFileName: string);
destructor Destroy; override;
procedure Lock;
procedure UnLock;
function Open(): Boolean;
function OpenEx(): Boolean;
procedure Close();
function Index(sName: string): Integer;
function Get(nIndex: Integer; var HumanRCD: TLF_HumDataInfo): Integer;
end;
var
HumDataDB: TFileDB;//'Mir.DB'
implementation
function CompareLStr(Src, targ: string; compn: Integer): Boolean;
var
I: Integer;
begin
Result := False;
if compn <= 0 then Exit;
if Length(Src) < compn then Exit;
if Length(targ) < compn then Exit;
Result := True;
for I := 1 to compn do
if UpCase(Src[I]) <> UpCase(targ[I]) then begin
Result := False;
Break;
end;
end;
function FileCopy(Source, Dest: string): Boolean;
var
fSrc, fDst, Len: Integer;
Size: LongInt;
Buffer: packed array[0..2047] of Byte;
begin
Result := False; { Assume that it WONT work }
if Source <> Dest then begin
fSrc := FileOpen(Source, fmOpenRead);
if fSrc >= 0 then begin
Size := FileSeek(fSrc, 0, 2);
FileSeek(fSrc, 0, 0);
fDst := FileCreate(Dest);
if fDst >= 0 then begin
while Size > 0 do begin
Len := FileRead(fSrc, Buffer, SizeOf(Buffer));
FileWrite(fDst, Buffer, Len);
Size := Size - Len;
end;
FileSetDate(fDst, FileGetDate(fSrc));
FileClose(fDst);
FileSetAttr(Dest, FileGetAttr(Source));
Result := True;
end;
FileClose(fSrc);
end;
end;
end;
{TFileDB}
constructor TFileDB.Create(sFileName: string); //0x0048A0F4
begin
n4 := 0;
boDataDBReady := False;
m_sDBFileName := sFileName;
m_sIdxFileName := sFileName + '.idx';
m_QuickList := TQuickList.Create;
m_DeletedList := TList.Create;
m_nLastIndex := -1;
if LoadDBIndex then boDataDBReady := True
else LoadQuickList();
end;
destructor TFileDB.Destroy;
begin
if boDataDBReady then SaveIndex();
m_QuickList.Free;
m_DeletedList.Free;
inherited;
end;
function TFileDB.LoadDBIndex: Boolean; //0x0048AA6C
var
nIdxFileHandle: Integer;
IdxHeader: TIdxHeader;
DBHeader: TDBHeader1;
IdxRecord: TIdxRecord;
HumRecord: TLF_HumDataInfo;
i: Integer;
n14: Integer;
begin
Result := False;
nIdxFileHandle := 0;
FillChar(IdxHeader, SizeOf(TIdxHeader), #0);
if FileExists(m_sIdxFileName) then
nIdxFileHandle := FileOpen(m_sIdxFileName, fmOpenReadWrite or fmShareDenyNone);
if nIdxFileHandle > 0 then begin
Result := True;
FileRead(nIdxFileHandle, IdxHeader, SizeOf(TIdxHeader));
try
if Open then begin
FileSeek(m_nFileHandle, 0, 0);
if FileRead(m_nFileHandle, DBHeader, SizeOf(TDBHeader1)) = SizeOf(TDBHeader1) then begin
if IdxHeader.nHumCount <> DBHeader.nHumCount then
Result := False;
if IdxHeader.sDesc <> sDBIdxHeaderDesc then
Result := False;
end; //0x0048AB65
if IdxHeader.nLastIndex <> DBHeader.nLastIndex then begin
Result := False;
end;
if IdxHeader.nLastIndex > -1 then begin
FileSeek(m_nFileHandle, IdxHeader.nLastIndex * SizeOf(TLF_HumDataInfo) + SizeOf(TDBHeader1), 0);
if FileRead(m_nFileHandle, HumRecord, SizeOf(TLF_HumDataInfo)) = SizeOf(TLF_HumDataInfo) then
if IdxHeader.dUpdateDate <> HumRecord.Header.UpdateDate then
Result := False;
end;
end; //0x0048ABD7
finally
Close();
end;
if Result then begin
m_nLastIndex := IdxHeader.nLastIndex;
m_dUpdateTime := IdxHeader.dUpdateDate;
for i := 0 to IdxHeader.nQuickCount - 1 do begin
if FileRead(nIdxFileHandle, IdxRecord, SizeOf(TIdxRecord)) = SizeOf(TIdxRecord) then begin
m_QuickList.AddObject(IdxRecord.sChrName, TObject(IdxRecord.nIndex));
end else begin
Result := False;
break;
end;
end; //0048AC7A
for i := 0 to IdxHeader.nDeleteCount - 1 do begin
if FileRead(nIdxFileHandle, n14, SizeOf(Integer)) = SizeOf(Integer) then
m_DeletedList.Add(Pointer(n14))
else begin
Result := False;
break;
end;
end;
end; //0048ACC5
FileClose(nIdxFileHandle);
end; //0048ACCD
if Result then begin
m_QuickList.SortString(0, m_QuickList.Count - 1);
end else m_QuickList.Clear;
end;
procedure TFileDB.LoadQuickList; //0x0048A440
var
nIndex: Integer;
DBHeader: TDBHeader1;
RecordHeader: TLF_HumRecordHeader;
begin
n4 := 0;
m_QuickList.Clear;
m_DeletedList.Clear;
try
if Open then begin
FileSeek(m_nFileHandle, 0, 0);
if FileRead(m_nFileHandle, DBHeader, SizeOf(TDBHeader1)) = SizeOf(TDBHeader1) then begin
for nIndex := 0 to DBHeader.nHumCount - 1 do begin
if FileSeek(m_nFileHandle, nIndex * SizeOf(TLF_HumDataInfo) + SizeOf(TDBHeader1), 0) = -1 then break;
if FileRead(m_nFileHandle, RecordHeader, SizeOf(TLF_HumRecordHeader)) <> SizeOf(TLF_HumRecordHeader) then break;
if not RecordHeader.boDeleted then begin
if RecordHeader.sName <> '' then begin
m_QuickList.AddObject(RecordHeader.sName, TObject(nIndex));
end else m_DeletedList.Add(TObject(nIndex));
end else begin
m_DeletedList.Add(TObject(nIndex));
end;
Application.ProcessMessages;
if Application.Terminated then begin
Close;
Exit;
end;
end;
end;
end;
finally
Close();
end;
m_QuickList.SortString(0, m_QuickList.Count - 1);
m_nLastIndex := m_Header.nLastIndex;
m_dUpdateTime := m_Header.dLastDate;
boDataDBReady := True;
end;
procedure TFileDB.Lock; //00048A254
begin
EnterCriticalSection(HumDB_CS);
end;
procedure TFileDB.UnLock; //0048A268
begin
LeaveCriticalSection(HumDB_CS);
end;
function TFileDB.Open: Boolean; //0048A304
begin
Lock();
n4 := 0;
m_boChanged := False;
if FileExists(m_sDBFileName) then begin
m_nFileHandle := FileOpen(m_sDBFileName, fmOpenReadWrite or fmShareDenyNone);
if m_nFileHandle > 0 then
FileRead(m_nFileHandle, m_Header, SizeOf(TDBHeader1));
end else begin //0048B999
m_nFileHandle := FileCreate(m_sDBFileName);
if m_nFileHandle > 0 then begin
m_Header.sDesc := DBFileDesc;
m_Header.nHumCount := 0;
m_Header.n6C := 0;
FileWrite(m_nFileHandle, m_Header, SizeOf(TDBHeader1));
end;
end;
if m_nFileHandle > 0 then Result := True
else Result := False;
end;
procedure TFileDB.Close; //0x0048A400
begin
FileClose(m_nFileHandle);
if m_boChanged and Assigned(m_OnChange) then begin
m_OnChange(Self);
end;
UnLock();
end;
function TFileDB.OpenEx: Boolean; //0x0048A27C
var
DBHeader: TDBHeader1;
begin
Lock();
m_boChanged := False;
m_nFileHandle := FileOpen(m_sDBFileName, fmOpenReadWrite or fmShareDenyNone);
if m_nFileHandle > 0 then begin
Result := True;
if FileRead(m_nFileHandle, DBHeader, SizeOf(TDBHeader1)) = SizeOf(TDBHeader1) then
m_Header := DBHeader;
n4 := 0;
end else Result := False;
end;
function TFileDB.Index(sName: string): Integer; //0x0048B534
begin
Result := m_QuickList.GetIndex(sName);
end;
function TFileDB.Get(nIndex: Integer; var HumanRCD: TLF_HumDataInfo): Integer; //0x0048B320
var
nIdx: Integer;
begin
nIdx := Integer(m_QuickList.Objects[nIndex]);
if GetRecord(nIdx, HumanRCD) then Result := nIdx
else Result := -1;
end;
function TFileDB.GetRecord(nIndex: Integer;
var HumanRCD: TLF_HumDataInfo): Boolean;
begin
if FileSeek(m_nFileHandle, nIndex * SizeOf(TLF_HumDataInfo) + SizeOf(TDBHeader1), 0) <> -1 then begin
FileRead(m_nFileHandle, HumanRCD, SizeOf(TLF_HumDataInfo));
FileSeek(m_nFileHandle, -SizeOf(TLF_HumDataInfo), 1);
n4 := nIndex;
Result := True;
end else Result := False;
end;
procedure TFileDB.SaveIndex; //0x0048A83C
var
IdxHeader: TIdxHeader;
nIdxFileHandle: Integer;
i: Integer;
nDeletedIdx: Integer;
IdxRecord: TIdxRecord;
begin
FillChar(IdxHeader, SizeOf(TIdxHeader), #0);
IdxHeader.sDesc := sDBIdxHeaderDesc;
IdxHeader.nQuickCount := m_QuickList.Count;
IdxHeader.nHumCount := m_Header.nHumCount;
IdxHeader.nDeleteCount := m_DeletedList.Count;
IdxHeader.nLastIndex := m_nLastIndex;
IdxHeader.dUpdateDate := m_dUpdateTime;
if FileExists(m_sIdxFileName) then
nIdxFileHandle := FileOpen(m_sIdxFileName, fmOpenReadWrite or fmShareDenyNone)
else nIdxFileHandle := FileCreate(m_sIdxFileName);
if nIdxFileHandle > 0 then begin
FileWrite(nIdxFileHandle, IdxHeader, SizeOf(TIdxHeader));
for i := 0 to m_QuickList.Count - 1 do begin
IdxRecord.sChrName := m_QuickList.Strings[i];
IdxRecord.nIndex := Integer(m_QuickList.Objects[i]);
FileWrite(nIdxFileHandle, IdxRecord, SizeOf(TIdxRecord));
end;
for i := 0 to m_DeletedList.Count - 1 do begin
nDeletedIdx := Integer(m_DeletedList.Items[i]);
FileWrite(nIdxFileHandle, nDeletedIdx, SizeOf(Integer));
end;
FileClose(nIdxFileHandle);
end;
end;
end.
|
unit abMasksDlg;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, CheckLst, nsGlobals, Registry, Menus,
Vcl.ActnList, Vcl.PlatformDefaultStyleActnCtrls, Vcl.ActnPopup;
type
TfrmMasks = class(TForm)
btnOk: TButton;
btnCancel: TButton;
GroupBox1: TGroupBox;
chklMasks: TCheckListBox;
edtNew: TEdit;
btnAdd: TButton;
btnDelete: TButton;
btnReplace: TButton;
pmContext: TPopupActionBar;
CheckAll2: TMenuItem;
UncheckAll2: TMenuItem;
N2: TMenuItem;
Delete2: TMenuItem;
acContext: TActionList;
acDelete: TAction;
acCheckAll: TAction;
acUncheckAll: TAction;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure btnAddClick(Sender: TObject);
procedure btnReplaceClick(Sender: TObject);
procedure chklMasksClick(Sender: TObject);
procedure btnDeleteClick(Sender: TObject);
procedure tbxClearClick(Sender: TObject);
procedure tbxCheckAllClick(Sender: TObject);
procedure tbxUnCheckAllClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
procedure GetMask(const AMask: string);
procedure SetMask(var AMask: string);
procedure RestoreKnownMasks;
procedure SaveKnownMasks;
protected
procedure UpdateActions; override;
public
{ Public declarations }
end;
function EditMasksDlg(const ACaption: string; var AMask: string): Boolean;
implementation
uses nsUtils, System.StrUtils;
{$R *.dfm}
function IsValidMask(const S: string): Boolean;
begin
Result := Pos('*.', Trim(S)) = 1;
end;
function EditMasksDlg(const ACaption: string; var AMask: string): Boolean;
begin
with TfrmMasks.Create(nil) do
try
Caption := StripHotkey(ACaption);
GetMask(AMask);
Result := ShowModal = mrOk;
if Result then
SetMask(AMask);
finally
Free;
end;
end;
{ TMasksForm }
procedure TfrmMasks.GetMask(const AMask: string);
var
Index: integer;
Str: TStrings;
I: integer;
begin
Str := TStringList.Create;
try
Str.Text := ReplaceStr(AMask, #59, #13#10);
for Index := 0 to Str.Count - 1 do
begin
if not IsValidMask(Str[Index]) then
Continue;
I := chklMasks.Items.IndexOf(Str[Index]);
if I = -1 then
I := chklMasks.Items.Add(Str[Index]);
chklMasks.Checked[I] := True;
end;
finally
Str.Free;
end;
end;
procedure TfrmMasks.RestoreKnownMasks;
var
S: string;
begin
with TRegIniFile.Create(REG_ROOT) do
try
S := ReadString(REG_KEY_LASTVALUES, REG_VAL_KNOWNNEXT, sFileMask);
chklMasks.Items.Text := ReplaceStr(S, #59, #13#10);
finally
Free;
end;
end;
procedure TfrmMasks.SaveKnownMasks;
var
S: string;
begin
with TRegIniFile.Create(REG_ROOT) do
try
S := ReplaceStr(chklMasks.Items.Text, #13#10, #59);
if (Length(S) > 0) and (S[Length(S)] = #59) then
SetLength(S, Length(S) - 1);
WriteString(REG_KEY_LASTVALUES, REG_VAL_KNOWNNEXT, S);
finally
Free;
end;
end;
procedure TfrmMasks.SetMask(var AMask: string);
var
Index: integer;
begin
AMask := EmptyStr;
for Index := 0 to chklMasks.Items.Count - 1 do
if chklMasks.Checked[Index] then
AMask := AMask + chklMasks.Items[Index] + #59;
if (Length(AMask) > 0) and (AMask[Length(AMask)] = #59) then
SetLength(AMask, Length(AMask) - 1);
end;
procedure TfrmMasks.UpdateActions;
begin
btnDelete.Enabled := chklMasks.ItemIndex <> -1;
btnAdd.Enabled := IsValidMask(edtNew.Text) and (chklMasks.Items.IndexOf(edtNew.Text) = -1);
btnReplace.Enabled := IsValidMask(edtNew.Text) and (chklMasks.ItemIndex <> -1) and
(chklMasks.Items.IndexOf(edtNew.Text) = -1);
acCheckAll.Enabled := chklMasks.Items.Count > 0;
acUnCheckAll.Enabled := chklMasks.Items.Count > 0;
acDelete.Enabled := chklMasks.Items.Count > 0;
end;
procedure TfrmMasks.FormCreate(Sender: TObject);
begin
RestoreKnownMasks;
end;
procedure TfrmMasks.FormDestroy(Sender: TObject);
begin
SaveKnownMasks;
end;
procedure TfrmMasks.FormShow(Sender: TObject);
begin
UpdateVistaFonts(Self);
end;
procedure TfrmMasks.btnAddClick(Sender: TObject);
var
I: integer;
begin
if IsValidMask(edtNew.Text) and (chklMasks.Items.IndexOf(Trim(edtNew.Text)) = -1) then
begin
I := chklMasks.Items.Add(Trim(edtNew.Text));
chklMasks.Checked[I] := True;
end;
end;
procedure TfrmMasks.btnReplaceClick(Sender: TObject);
begin
if IsValidMask(edtNew.Text) and (chklMasks.ItemIndex <> -1) and
(chklMasks.Items.IndexOf(Trim(edtNew.Text)) = -1) then
chklMasks.Items[chklMasks.ItemIndex] := Trim(edtNew.Text);
end;
procedure TfrmMasks.chklMasksClick(Sender: TObject);
begin
if chklMasks.ItemIndex <> -1 then
edtNew.Text := chklMasks.Items[chklMasks.ItemIndex];
end;
procedure TfrmMasks.btnDeleteClick(Sender: TObject);
begin
if chklMasks.ItemIndex <> -1 then
chklMasks.Items.Delete(chklMasks.ItemIndex);
end;
procedure TfrmMasks.tbxClearClick(Sender: TObject);
begin
if MessageDlg(sConfirmDeleteItems, mtConfirmation, [mbYes, mbNo], 0) <> mrYes then
Exit;
chklMasks.Items.Clear;
end;
procedure TfrmMasks.tbxCheckAllClick(Sender: TObject);
var
I: integer;
begin
chklMasks.Items.BeginUpdate;
try
for I := 0 to chklMasks.Items.Count - 1 do
chklMasks.Checked[I] := True;
finally
chklMasks.Items.EndUpdate;
end;
end;
procedure TfrmMasks.tbxUnCheckAllClick(Sender: TObject);
var
I: integer;
begin
chklMasks.Items.BeginUpdate;
try
for I := 0 to chklMasks.Items.Count - 1 do
chklMasks.Checked[I] := False;
finally
chklMasks.Items.EndUpdate;
end;
end;
end.
|
unit EcranCombat;
interface
uses GestionEcran, OptnAffichage, Variables;
{ Affichage de l'écran et appel des fonctions & procédures associées }
procedure afficher(Joueur : TJoueur);
{ Lance un assaut contre le joueur }
procedure assautAleatoire(Joueur : TJoueur);
{ Génère un nombre aléatoire de troupes ennemis en fonction de la taille indiquée }
procedure genererEnnemis(Joueur : TJoueur ; taille : String); // 'petit' ou 'grand'
implementation
uses EcranMilitaire, EcranAccueil;
var
LamaEnnemi : TUnite; // Unité LAMA (Soldat) ennemie
AlpagaEnnemi : TUnite; // Unité ALPAGA (Canon) ennemie
GuanacoEnnemi : TUnite; // Unité GUANACO (Cavalier) ennemie
nomEnnemi : String; // Nom de l'opposant
messageCombat : Boolean; // Le message de déroulement du combat est-il affiché ?
unite : String; // Unité ennemie attaquée pendant le tour
uniteEnnemi : String; // Unité alliée attaquée pendant le tour
nbElim : Integer; // Nombre de troupes ennemies éliminées pendant le tour
nbElimEnnemi : Integer; // Nombre de troupes allées éliminées pendant le tour
{ Initialisation de la TUnite LamaEnnemi }
procedure initLamaEnnemi;
begin
with LamaEnnemi do
begin
nom := 'Lama';
nb := 0;
ptsAttaque := 1;
prix := 1;
end;
end;
{ Initialisation de la TUnite AlpagaEnnemi }
procedure initAlpagaEnnemi;
begin
with AlpagaEnnemi do
begin
nom := 'Alpaga';
nb := 0;
ptsAttaque := 2;
prix := 2;
end;
end;
{ Initialisation de la TUnite GuanacoEnnemi }
procedure initGuanacoEnnemi;
begin
with GuanacoEnnemi do
begin
nom := 'Guanaco';
nb := 0;
ptsAttaque := 4;
prix := 3;
end;
end;
{ Lance un assaut contre le joueur }
procedure assautAleatoire(Joueur : TJoueur);
begin
effacerEcran();
// Affichage de l'en-tête
afficherEnTete(Joueur);
// Dessin du cadre principal et affichage du titre de l'écran
dessinerCadreXY(0,6, 119,28, simple, 15,0);
afficherTitre('COMBAT CONTRE : assaut littéraire' , 6);
// Affichage du message "Assaut"
couleurTexte(14);
deplacerCurseurXY(29,9);
write(' ______ ______ ______ ______ __ __ ______ ');
deplacerCurseurXY(29,10);
write('/\ __ \ /\ ___\ /\ ___\ /\ __ \ /\ \/\ \ /\__ _\ ');
deplacerCurseurXY(29,11);
write('\ \ __ \ \ \___ \ \ \___ \ \ \ __ \ \ \ \_\ \ \/_/\ \/ ');
deplacerCurseurXY(29,12);
write(' \ \_\ \_\ \/\_____\ \/\_____\ \ \_\ \_\ \ \_____\ \ \_\ ');
deplacerCurseurXY(29,13);
write(' \/_/\/_/ \/_____/ \/_____/ \/_/\/_/ \/_____/ \/_/ ');
couleurTexte(15);
dessinerCadreXY(32,17, 90,23, simple, 15,0);
deplacerCurseurXY(34,17);
write(' L''ennemi lance un assaut contre vous ! ');
deplacerCurseurXY(37,19);
write('Vous n''avez d''autre choix que de contre-attaquer.');
attendre(4800);
genererEnnemis(Joueur, 'assaut');
afficher(Joueur);
end;
{ Génère un nombre aléatoire d'unités ennemies en fonction de la taille
indiquée (petit, grand, surprise, joueur) et de la difficulté. }
procedure genererEnnemis(Joueur : TJoueur ; taille : String);
begin
{ (ré)Initialisation des troupes ennemies }
initLamaEnnemi();
initAlpagaEnnemi();
initGuanacoEnnemi();
Randomize;
// Dans le cas d'un PETIT groupe d'ennemis
if taille = 'petit' then
begin
nomEnnemi := 'petit pâturage de littéraires';
{ Génération aléatoire du nb d'ennemis en fonction de la difficulté choisie }
// Difficulté Linéaire
if getTribu(Joueur).difficulte = 'Linéaire' then
begin
LamaEnnemi.nb := 1 + Random(20);
AlpagaEnnemi.nb := Random(10);
GuanacoEnnemi.nb := 0 ;
end;
// Difficulté Appliqué
if getTribu(Joueur).difficulte = 'Appliqué' then
begin
LamaEnnemi.nb := 5 + Random(20);
AlpagaEnnemi.nb := 2 + Random(10);
GuanacoEnnemi.nb := Random(4);
end;
// Difficulté Quantique
if getTribu(Joueur).difficulte = 'Quantique' then
begin
LamaEnnemi.nb := 10 + Random(30);
AlpagaEnnemi.nb := 5 + Random(20);
GuanacoEnnemi.nb := 2 + Random(6);
end;
end;
// Dans le cas d'un GRAND groupe d'ennemis
if taille = 'grand' then
begin
nomEnnemi := 'grand pâturage de littéraires';
{ Génération aléatoire du nb d'ennemis en fonction de la difficulté choisie }
// Difficulté Linéaire
if getTribu(Joueur).difficulte = 'Linéaire' then
begin
LamaEnnemi.nb := 50 + Random(50);
AlpagaEnnemi.nb := 20 + Random(20);
GuanacoEnnemi.nb := 5 + Random(10);
end;
// Difficulté Appliqué
if getTribu(Joueur).difficulte = 'Appliqué' then
begin
LamaEnnemi.nb := 70 + Random(70);
AlpagaEnnemi.nb := 30 + Random(30);
GuanacoEnnemi.nb := 10 + Random(20);
end;
// Difficulté Appliqué
if getTribu(Joueur).difficulte = 'Quantique' then
begin
LamaEnnemi.nb := 80 + Random(80);
AlpagaEnnemi.nb := 40 + Random(40);
GuanacoEnnemi.nb := 15 + Random(30);
end;
end;
// Dans le cas d'un ASSAUT
if taille = 'assaut' then
begin
nomEnnemi := 'assaut littéraire';
{ Génération aléatoire du nb d'ennemis en fonction de la difficulté choisie }
// Difficulté Linéaire
if getTribu(Joueur).difficulte = 'Linéaire' then
begin
LamaEnnemi.nb := 1 + Random(5);
AlpagaEnnemi.nb := Random(5);
GuanacoEnnemi.nb := 0 ;
end;
// Difficulté Appliqué
if getTribu(Joueur).difficulte = 'Appliqué' then
begin
LamaEnnemi.nb := 5 + Random(10);
AlpagaEnnemi.nb := 2 + Random(5);
GuanacoEnnemi.nb := Random(2);
end;
// Difficulté Quantique
if getTribu(Joueur).difficulte = 'Quantique' then
begin
LamaEnnemi.nb := 5 + Random(20);
AlpagaEnnemi.nb := 2 + Random(10);
GuanacoEnnemi.nb := Random(4);
end;
end;
// Dans le cas particulier d'une attaque menée contre l'AUTRE JOUEUR
if taille = 'joueur' then
begin
if Joueur = Joueur1 then nomEnnemi := 'Joueur 2'
else if Joueur = Joueur2 then nomEnnemi := 'Joueur 1';
end;
end;
{ Lance une attaque contre l'unité indiquée (Lamas, Alpagas, Guanacos) }
procedure attaquer(Joueur : TJoueur ; troupe : String);
var
scoreAttaque : Integer; // Score d'attaque du joueur
scoreAttaqueEnnemi : Integer; // Score d'attaque de l'ordinateur
begin
// Calcul du score d'attaque du joueur
scoreAttaque := ( getLama(Joueur).nb * getLama(Joueur).ptsAttaque )
+ ( getAlpaga(Joueur).nb * getAlpaga(Joueur).ptsAttaque )
+ ( getGuanaco(Joueur).nb * getGuanaco(Joueur).ptsAttaque );
// Calcul du score d'attaque de l'ordinateur
scoreAttaqueEnnemi := ( LamaEnnemi.nb * LamaEnnemi.ptsAttaque )
+ ( AlpagaEnnemi.nb * AlpagaEnnemi.ptsAttaque )
+ ( GuanacoEnnemi.nb * GuanacoEnnemi.ptsAttaque );
{ Tour de jeu : JOUEUR }
// Calcul du nb d'unités ennemies réellement éliminées
nbElim := random(scoreAttaque);
// Cas dans lequel les LAMAS (Soldats) ennemis sont attaqués
if (troupe = 'Lamas') then
begin
unite := 'Lamas';
if nbElim > LamaEnnemi.nb then nbElim := LamaEnnemi.nb;
LamaEnnemi.nb := LamaEnnemi.nb - nbElim;
if LamaEnnemi.nb < 0 then LamaEnnemi.nb := 0;
end;
// Cas dans lequel les ALPAGAS (Canons) ennemis sont attaqués
if (troupe = 'Alpagas') then
begin
unite := 'Alpagas';
if nbElim > AlpagaEnnemi.nb then nbElim := AlpagaEnnemi.nb;
AlpagaEnnemi.nb := AlpagaEnnemi.nb - nbElim;
if AlpagaEnnemi.nb < 0 then AlpagaEnnemi.nb := 0;
end;
// Cas dans lequel les GUANACOS (Cavaliers) ennemis sont attaqués
if (troupe = 'Guanacos') then
begin
unite := 'Guanacos';
if nbElim > GuanacoEnnemi.nb then nbElim := GuanacoEnnemi.nb;
GuanacoEnnemi.nb := GuanacoEnnemi.nb - nbElim;
if GuanacoEnnemi.nb < 0 then GuanacoEnnemi.nb := 0;
end;
{ Tour de jeu : ORDINATEUR }
// Calcul du nb d'unités alliées réellement éliminées
nbElimEnnemi := random(scoreAttaqueEnnemi);
{ L'Ordinateur attaque en priorité les Lamas (Soldats) ; dès qu'il n'y en a plus,
il attaque les Alpagas (Canons)et enfin les Guanacos (Cavaliers). }
// Cas dans lequel les LAMAS (Soldats) alliés sont attaqués
if getLama(Joueur).nb <> 0 then
begin
uniteEnnemi := 'Lamas';
if nbElimEnnemi > getLama(Joueur).nb then nbElimEnnemi := getLama(Joueur).nb;
setLama_nb(Joueur, getLama(Joueur).nb - nbElimEnnemi);
if getLama(Joueur).nb < 0 then setLama_nb(Joueur, 0);
end
// Cas dans lequel les ALPAGAS (Canons) alliés sont attaqués
else if getAlpaga(Joueur).nb <> 0 then
begin
uniteEnnemi := 'Alpagas';
if nbElimEnnemi > getAlpaga(Joueur).nb then nbElimEnnemi := getAlpaga(Joueur).nb;
setAlpaga_nb(Joueur, getAlpaga(Joueur).nb - nbElimEnnemi);
if getAlpaga(Joueur).nb < 0 then setAlpaga_nb(Joueur, 0);
end
// Cas dans lequel les GUANACOS (Cavaliers) alliés sont attaqués
else if getGuanaco(Joueur).nb <> 0 then
begin
uniteEnnemi := 'Guanacos';
if nbElimEnnemi > getGuanaco(Joueur).nb then nbElimEnnemi := getGuanaco(Joueur).nb;
setGuanaco_nb(Joueur, getGuanaco(Joueur).nb - nbElimEnnemi);
if getGuanaco(Joueur).nb < 0 then setGuanaco_nb(Joueur, 0);
end;
messageCombat := True;
afficher(Joueur);
end;
{ Procédure spéciale dérivée de la procédure attaquer() configurée pour
opposer l'armée du joueur attaquant à celle du joueur défenseur. }
procedure attaquerJoueur(Joueur : TJoueur ; troupe : String);
var
Attaquant : TJoueur; // Joueur ATTAQUANT
Defenseur : TJoueur; // Joueur ATTAQUÉ (Défenseur)
scoreAttaqueAttaquant : Integer; // Score d'attaque du joueur attaquant
scoreAttaqueDefenseur : Integer; // Score d'attaque du joueur attaqué (défenseur)
begin
// Identifie l'Attaquant et le Défenseur à partir du Joueur à l'origine de l'attaque
{ Joueur 1 }
if Joueur = Joueur1 then
begin
Attaquant := Joueur1;
Defenseur := Joueur2;
end
{ Joueur 2 }
else if Joueur = Joueur2 then
begin
Attaquant := Joueur2;
Defenseur := Joueur1;
end;
// Calcul du score d'attaque du joueur attaquant
scoreAttaqueAttaquant := ( getLama(Attaquant).nb * getLama(Attaquant).ptsAttaque )
+ ( getAlpaga(Attaquant).nb * getAlpaga(Attaquant).ptsAttaque )
+ ( getGuanaco(Attaquant).nb * getGuanaco(Attaquant).ptsAttaque );
// Calcul du score d'attaque du joueur attaqué (défenseur)
scoreAttaqueDefenseur := ( getLama(Defenseur).nb * getLama(Defenseur).ptsAttaque )
+ ( getAlpaga(Defenseur).nb * getAlpaga(Defenseur).ptsAttaque )
+ ( getGuanaco(Defenseur).nb * getGuanaco(Defenseur).ptsAttaque );
{ Tour de jeu : ATTAQUANT }
// Calcul du nb d'unités ennemies réellement éliminées
nbElim := random(scoreAttaqueAttaquant);
// Cas dans lequel les LAMAS (Soldats) ennemis sont attaqués
if (troupe = 'Lamas') then
begin
unite := 'Lamas';
if nbElim > getLama(Defenseur).nb then nbElim := getLama(Defenseur).nb;
setLama_nb(Defenseur, getLama(Defenseur).nb - nbElim);
if getLama(Defenseur).nb < 0 then setLama_nb(Defenseur,0);
end;
// Cas dans lequel les ALPAGAS (Canons) ennemis sont attaqués
if (troupe = 'Alpagas') then
begin
unite := 'Alpagas';
if nbElim > getAlpaga(Defenseur).nb then nbElim := getAlpaga(Defenseur).nb;
setAlpaga_nb(Defenseur, getAlpaga(Defenseur).nb - nbElim);
if getAlpaga(Defenseur).nb < 0 then setAlpaga_nb(Defenseur,0);
end;
// Cas dans lequel les GUANACOS (Cavaliers) ennemis sont attaqués
if (troupe = 'Guanacos') then
begin
unite := 'Guanacos';
if nbElim > getGuanaco(Defenseur).nb then nbElim := getGuanaco(Defenseur).nb;
setGuanaco_nb(Defenseur, getGuanaco(Defenseur).nb - nbElim);
if getGuanaco(Defenseur).nb < 0 then setGuanaco_nb(Defenseur,0);
end;
{ Tour de jeu : DÉFENSEUR }
{ Le Défenseur ne joue pas à proprement parler ; les actions de son armée sont décidées
de la même manière que s'il s'agissait d'un ordinateur. }
// Calcul du nb d'unités alliées réellement éliminées
nbElimEnnemi := random(scoreAttaqueDefenseur);
{ L'Ordinateur attaque en priorité les Lamas (Soldats) ; dès qu'il n'y en a plus,
il attaque les Alpagas (Canons)et enfin les Guanacos (Cavaliers). }
// Cas dans lequel les LAMAS (Soldats) alliés sont attaqués
if getLama(Joueur).nb <> 0 then
begin
uniteEnnemi := 'Lamas';
if nbElimEnnemi > getLama(Joueur).nb then nbElimEnnemi := getLama(Joueur).nb;
setLama_nb(Joueur, getLama(Joueur).nb - nbElimEnnemi);
if getLama(Joueur).nb < 0 then setLama_nb(Joueur, 0);
end
// Cas dans lequel les ALPAGAS (Canons) alliés sont attaqués
else if getAlpaga(Joueur).nb <> 0 then
begin
uniteEnnemi := 'Alpagas';
if nbElimEnnemi > getAlpaga(Joueur).nb then nbElimEnnemi := getAlpaga(Joueur).nb;
setAlpaga_nb(Joueur, getAlpaga(Joueur).nb - nbElimEnnemi);
if getAlpaga(Joueur).nb < 0 then setAlpaga_nb(Joueur, 0);
end
// Cas dans lequel les GUANACOS (Cavaliers) alliés sont attaqués
else if getGuanaco(Joueur).nb <> 0 then
begin
uniteEnnemi := 'Guanacos';
if nbElimEnnemi > getGuanaco(Joueur).nb then nbElimEnnemi := getGuanaco(Joueur).nb;
setGuanaco_nb(Joueur, getGuanaco(Joueur).nb - nbElimEnnemi);
if getGuanaco(Joueur).nb < 0 then setGuanaco_nb(Joueur, 0);
end;
messageCombat := True;
afficher(Joueur);
end;
{ Génère aléatoirement un butin (bonus) en fonction d'une taille donnée (petit, grand, assaut) }
procedure genererButin(Joueur : TJoueur ; taille : String);
var
alea : Integer ; // Nombre aléatoire déterminant la catégorie du butin
{ Variables de gain }
gainSavoir : Integer; // Gain en savoir acquis
gainEquations : Integer; // Gain en équations résolues
gainLama : Integer; // Gain en Lamas
gainAlpaga : Integer; // Gain en Alpagas
gainGuanaco : Integer; // Gain en Guanacos
begin
Randomize;
alea := random(4);
if (taille = 'petit') OR (taille = 'assaut') then
{ Note : Bien que l'armée ennemie soit réduite dans un assaut,
on va dire que le côté "surprise" justifie un butin équivalent
à la victoire contre un petit pâturage de littéraires. }
begin
if alea = 0 then
begin
gainSavoir := random(100);
setElevage_savoirAcquis(Joueur, getElevage(Joueur).savoirAcquis + gainSavoir);
end;
if alea = 1 then
begin
gainEquations := random(120);
setElevage_equationsResolues(Joueur, getElevage(Joueur).equationsResolues + gainEquations);
end;
if alea = 2 then
begin
gainLama := random(20);
setLama_nb(Joueur, getLama(Joueur).nb + gainLama);
end;
if alea = 3 then
begin
gainAlpaga := random(10);
setAlpaga_nb(Joueur, getAlpaga(Joueur).nb + gainAlpaga);
end;
if alea = 4 then
begin
gainGuanaco := random(5);
setGuanaco_nb(Joueur, getGuanaco(Joueur).nb + gainGuanaco);
end;
end;
if taille = 'grand' then
begin
if alea = 0 then
begin
gainSavoir := random(400);
setElevage_savoirAcquis(Joueur, getElevage(Joueur).savoirAcquis + gainSavoir);
end;
if alea = 1 then
begin
gainEquations := random(1000);
setElevage_equationsResolues(Joueur, getElevage(Joueur).equationsResolues + gainEquations);
end;
if alea = 2 then
begin
gainLama := random(80);
setLama_nb(Joueur, getLama(Joueur).nb + gainLama);
end;
if alea = 3 then
begin
gainAlpaga := random(40);
setAlpaga_nb(Joueur, getAlpaga(Joueur).nb + gainAlpaga);
end;
if alea = 4 then
begin
gainGuanaco := random(20);
setGuanaco_nb(Joueur, getGuanaco(Joueur).nb + gainGuanaco);
end;
end;
deplacerCurseurXY(36,21);
if alea = 0 then write('Le savoir acquis par votre élevage augmente de ', gainSavoir);
if alea = 1 then write('Votre élevage a résolu ', gainEquations, ' équations supplémentaires');
if alea = 2 then write(gainLama, ' Lamas ont rejoint votre noble cause mathématique');
if alea = 3 then write(gainAlpaga, ' Alpagas ont rejoint votre noble cause mathématique');
if alea = 4 then write(gainGuanaco, ' Guanacos ont rejoint votre noble cause mathématique');
end;
{ Affiche l'écran de game over }
procedure perdrePartie(Joueur : TJoueur);
var
x : Integer; // Coordonnée x d'origine du dessin
espace : String; // Espace séparant chaque pavé
begin
{ Dans un premier temps, une animation similaire à celle de l'écran titre est lancée
pour signaler au joueur qu'il a perdu. On affiche ensuite un bilan de la partie jouée. }
effacerEcran;
// Initialisation des variables de travail
espace := ' ';
x := 32;
{ Fonctionne par pas de 2 'manuel', d'où le while plutôt qu'un for }
while x >= 14 do
begin
if x = 30 then attendre(100);
if x = 28 then couleurTexte(5);
if x = 26 then couleurTexte(13);
if x = 24 then couleurTexte(9);
if x = 22 then couleurTexte(11);
if x = 20 then couleurTexte(10);
if x = 18 then couleurTexte(14);
if x = 16 then couleurTexte(12);
if x = 14 then couleurTexte(15);
// Dessin des formes HAUT
deplacerCurseurXY(x,1);
writeln('+------+. ',espace,'+------+ ',espace,'+------+',espace,' +------+',espace,' .+------+');
deplacerCurseurXY(x,2);
writeln('|`. | `. ',espace,'|\ |\ ',espace,'| |',espace,' /| /|',espace,' .'' | .''|');
deplacerCurseurXY(x,3);
writeln('| `+--+---+',espace,'| +----+-+',espace,'+------+',espace,'+-+----+ |',espace,'+---+--+'' |');
deplacerCurseurXY(x,4);
writeln('| | | |',espace,'| | | |',espace,'| |',espace,'| | | |',espace,'| | | |');
deplacerCurseurXY(x,5);
writeln('+---+--+. |',espace,'+-+----+ |',espace,'+------+',espace,'| +----+-+',espace,'| .+--+---+');
deplacerCurseurXY(x,6);
writeln(' `. | `.|',espace,' \| \|',espace,'| |',espace,'|/ |/ ',espace,'|.'' | .''');
deplacerCurseurXY(x,7);
writeln(' `+------+',espace,' +------+',espace,'+------+',espace,'+------+ ',espace,'+------+'' ');
// Dessin des formes BAS
deplacerCurseurXY(x,18);
writeln(' .+------+',espace,' +------+',espace,'+------+',espace,'+------+',espace,' +------+.');
deplacerCurseurXY(x,19);
writeln(' .'' | .''|',espace,' /| /|',espace,'| |',espace,'|\ |\',espace,' |`. | `.');
deplacerCurseurXY(x,20);
writeln('+---+--+'' |',espace,'+-+----+ |',espace,'+------+',espace,'| +----+-+',espace,'| `+--+---+');
deplacerCurseurXY(x,21);
writeln('| | | |',espace,'| | | |',espace,'| |',espace,'| | | |',espace,'| | | |');
deplacerCurseurXY(x,22);
writeln('| ,+--+---+',espace,'| +----+-+',espace,'+------+',espace,'+-+----+ |',espace,'+---+--+ |');
deplacerCurseurXY(x,23);
writeln('|.'' | .''',espace,' |/ |/',espace,' | |',espace,' \| \|',espace,' `. | `. |');
deplacerCurseurXY(x,24);
writeln('+------+''',espace,' +------+',espace,' +------+',espace,' +------+',espace,' `+------+');
// Délai d'attente entre chaque image
attendre(100);
// On rajoute un espace pour disperser davantage les pavés
espace := espace + ' ';
// x est décrémenté de 2 pour garder le dessin centré
x := x - 2;
end;
attendre(40);
deplacerCurseurXY(49,10);
write('███████╗██╗███╗ ██╗');
attendre(40);
deplacerCurseurXY(49,11);
write('██╔════╝██║████╗ ██║');
attendre(40);
deplacerCurseurXY(49,12);
write('█████╗ ██║██╔██╗ ██║');
attendre(40);
deplacerCurseurXY(49,13);
write('██╔══╝ ██║██║╚██╗██║');
attendre(40);
deplacerCurseurXY(49,14);
write('██║ ██║██║ ╚████║');
attendre(40);
deplacerCurseurXY(49,15);
write('╚═╝ ╚═╝╚═╝ ╚═══╝');
// Le joueur appuie sur ENTRER et l'écran de fin de partie s'affiche
dessinerCadreXY(41,26, 77,28, simple, 15,0);
deplacerCurseurXY(43,27);
writeln('Appuyez sur ENTRER pour continuer');
deplacerCurseurXY(76,27);
readln;
effacerEcran;
// Dessin du titre
deplacerCurseurXY(46,2);
write(' ______ __ __ __ ');
deplacerCurseurXY(46,3);
write('/\ ___\ /\ \ /\ "-.\ \ ');
deplacerCurseurXY(46,4);
write('\ \ __\ \ \ \ \ \ \-. \ ');
deplacerCurseurXY(46,5);
write(' \ \_\ \ \_\ \ \_\\"\_\ ');
deplacerCurseurXY(46,6);
write(' \/_/ \/_/ \/_/ \/_/ ');
// Bilan de la partie
dessinerCadreXY(32,10, 90,20, simple, 15,0);
deplacerCurseurXY(34,10);
write(' Fin de la partie : Statistiques ');
deplacerCurseurXY(38,13);
write('La Tribu ', getTribu(Joueur).archetype, ' ');
couleurTexte(11);
write(getTribu(Joueur).nom);
couleurTexte(15);
deplacerCurseurXY(38,14);
write('a survécu ');
write(getTribu(Joueur).numJour);
write(' jours en difficulté ');
couleurTexte(13);
write(getTribu(Joueur).difficulte);
couleurTexte(15);
write('.');
deplacerCurseurXY(38,16);
write('Ses troupes ont victorieusement mené ');
couleurTexte(10);
write(getTribu(Joueur).victoires);
couleurTexte(15);
write(' combats');
deplacerCurseurXY(38,17);
write('mais ont été défaites lors de ');
couleurTexte(12);
write(getTribu(Joueur).defaites);
couleurTexte(15);
write(' batailles.');
deplacerCurseurXY(36,23);
couleurTexte(8);
write('Vous allez être redirigé vers le menu principal');
couleurTexte(15);
// Le joueur appuie sur ENTRER et est renvoyé à l'écran d'accueil
dessinerCadreXY(41,26, 77,28, simple, 15,0);
deplacerCurseurXY(43,27);
write('Appuyez sur ENTRER pour continuer');
deplacerCurseurXY(76,27);
readln;
EcranAccueil.afficher();
end;
{ Affiche l'écran de victoire }
procedure victoire(Joueur : TJoueur);
begin
effacerEcran();
// Affichage de l'en-tête
afficherEnTete(Joueur);
// Le nombre de victoires en combat du joueur est incrémenté
setTribu_victoires(Joueur, getTribu(Joueur).victoires + 1);
// Si l'attaque a été menée contre l'autre joueur, ce dernier gagne une défaite
if (nomEnnemi = 'Joueur 1') OR (nomEnnemi = 'Joueur 2') then
begin
if Joueur = Joueur1 then setTribu_defaites(Joueur2, getTribu(Joueur2).defaites + 1);
if Joueur = Joueur2 then setTribu_defaites(Joueur1, getTribu(Joueur1).defaites + 1);
end;
// Dessin du cadre principal et affichage du titre de l'écran
dessinerCadreXY(0,6, 119,28, simple, 15,0);
afficherTitre('COMBAT CONTRE : ' + nomEnnemi , 6);
// Affichage du message "Victoire"
couleurTexte(10);
deplacerCurseurXY(22,9);
write(' __ __ __ ______ ______ ______ __ ______ ______ ');
deplacerCurseurXY(22,10);
write('/\ \ / / /\ \ /\ ___\ /\__ _\ /\ __ \ /\ \ /\ == \ /\ ___\ ');
deplacerCurseurXY(22,11);
write('\ \ \''/ \ \ \ \ \ \____ \/_/\ \/ \ \ \/\ \ \ \ \ \ \ __< \ \ __\ ');
deplacerCurseurXY(22,12);
write(' \ \__| \ \_\ \ \_____\ \ \_\ \ \_____\ \ \_\ \ \_\ \_\ \ \_____\ ');
deplacerCurseurXY(22,13);
write(' \/_/ \/_/ \/_____/ \/_/ \/_____/ \/_/ \/_/ /_/ \/_____/ ');
couleurTexte(15);
dessinerCadreXY(32,17, 90,23, simple, 15,0);
deplacerCurseurXY(34,17);
write(' Vous triomphez de l''ennemi ! ');
deplacerCurseurXY(42,19);
write('Votre nombre de victoires s''élève à ');
couleurTexte(10);
write(getTribu(Joueur).victoires);
// Génère et affiche un butin aléatoire
if nomEnnemi = 'petit pâturage de littéraires' then genererButin(Joueur, 'petit')
else if nomEnnemi = 'grand pâturage de littéraires' then genererButin(Joueur, 'grand')
else if nomEnnemi = 'assaut littéraire' then genererButin(Joueur, 'assaut');
couleurTexte(15);
// Le message du déroulement du combat n'est plus affiché
messageCombat := False;
// Le joueur appuie sur ENTRER et est renvoyé à l'écran de gestion Militaire et Diplomatique
deplacerCurseurXY(43,26);
write('Appuyez sur ENTRER pour continuer');
deplacerCurseurXY(76,26);
readln;
EcranMilitaire.afficher(Joueur);
end;
{ Affiche l'écran de défaite }
procedure defaite(Joueur : TJoueur);
begin
effacerEcran();
// Affichage de l'en-tête
afficherEnTete(Joueur);
// Le nombre de défaites en combat du joueur est incrémenté
setTribu_defaites(Joueur, getTribu(Joueur).defaites + 1);
// Si l'attaque a été menée contre l'autre joueur, ce dernier gagne une victoire
if (nomEnnemi = 'Joueur 1') OR (nomEnnemi = 'Joueur 2') then
begin
if Joueur = Joueur1 then setTribu_victoires(Joueur2, getTribu(Joueur2).victoires + 1);
if Joueur = Joueur2 then setTribu_victoires(Joueur1, getTribu(Joueur1).victoires + 1);
end;
// Dessin du cadre principal et affichage du titre de l'écran
dessinerCadreXY(0,6, 119,28, simple, 15,0);
afficherTitre('COMBAT CONTRE : ' + nomEnnemi , 6);
// Affichage du message "Défaite"
couleurTexte(12);
deplacerCurseurXY(27,9);
write(' _____ ______ ______ ______ __ ______ ______ ');
deplacerCurseurXY(27,10);
write('/\ __-. /\ ___\ /\ ___\ /\ __ \ /\ \ /\__ _\ /\ ___\ ');
deplacerCurseurXY(27,11);
write('\ \ \/\ \ \ \ __\ \ \ __\ \ \ __ \ \ \ \ \/_/\ \/ \ \ __\ ');
deplacerCurseurXY(27,12);
write(' \ \____- \ \_____\ \ \_\ \ \_\ \_\ \ \_\ \ \_\ \ \_____\ ');
deplacerCurseurXY(27,13);
write(' \/____/ \/_____/ \/_/ \/_/\/_/ \/_/ \/_/ \/_____/ ');
couleurTexte(15);
dessinerCadreXY(32,17, 90,23, simple, 15,0);
deplacerCurseurXY(34,17);
write(' L''ennemi a eu raison de vous ! ');
deplacerCurseurXY(43,19);
write('Votre nombre de défaites s''élève à ');
couleurTexte(12);
write(getTribu(Joueur).defaites);
// Affiche le nombre de défaites restantes avant la fin de la partie
deplacerCurseurXY(37,21);
if getTribu(Joueur).defaites = getTribu(Joueur).limDefaites then write('Ces ', getTribu(Joueur).limDefaites, ' défaites ont été fatales pour votre Tribu.')
else write('Vos recherches seront anéanties dans ', getTribu(Joueur).limDefaites - getTribu(Joueur).defaites, ' défaites.');
couleurTexte(15);
// Le message du déroulement du combat n'est plus affiché
messageCombat := False;
// Le joueur appuie sur ENTRER et est renvoyé à l'écran de gestion Militaire et Diplomatique
deplacerCurseurXY(43,26);
write('Appuyez sur ENTRER pour continuer');
deplacerCurseurXY(76,26);
readln;
// Si c'était la défaite de trop, le joueur perd la partie
if getTribu(Joueur).defaites = getTribu(Joueur).limDefaites then perdrePartie(Joueur)
else EcranMilitaire.afficher(Joueur);
end;
{ Affiche un message résumant le déroulement du combat si messageCombat = True }
procedure afficherMsgCombat;
begin
{ Cadre du message }
dessinerCadreXY(58,14, 109,19, simple, 15,0);
deplacerCurseurXY(60,14);
write(' Champ de bataille ');
{ Si le combat a commencé }
if messageCombat = True then
begin
// Bilan de l'attaque du Joueur
deplacerCurseurXY(62,16);
if nbElim > 0 then couleurTexte(10)
else couleurTexte(8);
write('Vos troupes crachent sur ', nbElim, ' ', unite, ' ennemis.');
// Bilan de l'attaque de l'Ordinateur
deplacerCurseurXY(62,17);
if nbElimEnnemi > 0 then couleurTexte(12)
else couleurTexte(8);
write('L''ennemi crache sur ', nbElimEnnemi, ' de vos ', uniteEnnemi, '.');
couleurTexte(15);
end
{ Dans le cas où le combat vient de commencer }
else
begin
deplacerCurseurXY(62,16);
write('Préparez-vous au combat !');
end;
end;
{ Récupère le choix du joueur et détermine l'action à effectuer }
procedure choisir(Joueur : TJoueur);
var
choix : String; // Valeur entrée par la joueur
begin
{ Déplace le curseur dans le cadre "Action" }
deplacerCurseurXY(114,26);
readln(choix);
{ Liste des choix disponibles }
{ Si le combat oppose deux joueurs, on fait appel à la procédure spéciale
attaquerJoueur pour jouer un tour de combat. }
if (nomEnnemi = 'Joueur 1') OR (nomEnnemi = 'Joueur 2') then
begin
if (choix = '1') then attaquerJoueur(Joueur, 'Lamas');
if (choix = '2') then attaquerJoueur(Joueur, 'Alpagas');
if (choix = '3') then attaquerJoueur(Joueur, 'Guanacos')
{ Valeur saisie invalide }
else
begin
setMessage('Action non reconnue');
afficher(Joueur);
end;
end
else
begin
if (choix = '1') then attaquer(Joueur, 'Lamas');
if (choix = '2') then attaquer(Joueur, 'Alpagas');
if (choix = '3') then attaquer(Joueur, 'Guanacos')
{ Valeur saisie invalide }
else
begin
setMessage('Action non reconnue');
afficher(Joueur);
end;
end
end;
{ Affichage de l'écran et appel des fonctions & procédures associées }
procedure afficher(Joueur : TJoueur);
var
Defenseur : TJoueur; // Joueur Défenseur
begin
// Dans le cas d'une partie multijoueur, identifie le Défenseur d'après le Joueur à l'origine de l'attaque
if getMultijoueur() = True then
begin
{ Joueur 1 }
if Joueur = Joueur1 then
begin
Defenseur := Joueur2;
end
{ Joueur 2 }
else if Joueur = Joueur2 then
begin
Defenseur := Joueur1;
end;
end;
{ On vérifie d'abord si l'un des deux belligérants a remporté le combat,
auquel cas on affiche l'écran de Victoire/Défaite. }
if (getLama(Joueur).nb = 0) AND (getAlpaga(Joueur).nb = 0) AND (getGuanaco(Joueur).nb = 0) then defaite(Joueur);
// Si le combat oppose deux joueurs, la victoire est identifiée à partir de l'armée du défenseur
if (nomEnnemi = 'Joueur 1') OR (nomEnnemi = 'Joueur 2') then
begin
if (getLama(Defenseur).nb = 0) AND (getAlpaga(Defenseur).nb = 0) AND (getGuanaco(Defenseur).nb = 0) then victoire(Joueur);
end
// Sinon la victoire est identifiée à partir de l'armée de l'ordinateur
else if (LamaEnnemi.nb = 0) AND (AlpagaEnnemi.nb = 0) AND (GuanacoEnnemi.nb = 0) then victoire(Joueur);
{ INSTRUCTIONS D'AFFICHAGE }
effacerEcran();
{ Partie supérieure de l'écran }
afficherEnTete(Joueur);
dessinerCadreXY(0,6, 119,28, simple, 15,0);
afficherTitre('COMBAT CONTRE : ' + nomEnnemi , 6);
{ Corps de l'écran }
// Armée du Joueur
deplacerCurseurXY(3,10);
write('Descriptif de vos forces :');
deplacerCurseurXY(3,11);
write('¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯');
// Lamas
deplacerCurseurXY(5,12);
write(' Lamas : ');
if getLama(Joueur).nb = 0 then couleurTexte(8)
else couleurtexte(10);
write(getLama(Joueur).nb);
couleurTexte(15);
// Alpagas
deplacerCurseurXY(5,13);
write(' Alpagas : ');
if getAlpaga(Joueur).nb = 0 then couleurTexte(8)
else couleurtexte(10);
write(getAlpaga(Joueur).nb);
couleurTexte(15);
// Guanacos
deplacerCurseurXY(5,14);
write(' Guanacos : ');
if getGuanaco(Joueur).nb = 0 then couleurTexte(8)
else couleurtexte(10);
write(getGuanaco(Joueur).nb);
couleurTexte(15);
// Armée ennemie
deplacerCurseurXY(3,16);
write('Descriptif des forces ennemies :');
deplacerCurseurXY(3,17);
write('¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯');
// Lamas ennemis
deplacerCurseurXY(5,18);
write(' Lamas : ');
if (nomEnnemi = 'Joueur 1') OR (nomEnnemi = 'Joueur 2') then
begin
if getLama(Defenseur).nb = 0 then couleurTexte(8)
else couleurtexte(12);
write(getLama(Defenseur).nb);
end
else
begin
if LamaEnnemi.nb = 0 then couleurTexte(8)
else couleurtexte(12);
write(LamaEnnemi.nb);
end;
couleurTexte(15);
// Alpagas ennemis
deplacerCurseurXY(5,19);
write(' Alpagas : ');
if (nomEnnemi = 'Joueur 1') OR (nomEnnemi = 'Joueur 2') then
begin
if getAlpaga(Defenseur).nb = 0 then couleurTexte(8)
else couleurtexte(12);
write(getAlpaga(Defenseur).nb);
end
else
begin
if AlpagaEnnemi.nb = 0 then couleurTexte(8)
else couleurtexte(12);
write(AlpagaEnnemi.nb);
end;
couleurTexte(15);
// Guanacos ennemis
deplacerCurseurXY(5,20);
write(' Guanacos : ');
if (nomEnnemi = 'Joueur 1') OR (nomEnnemi = 'Joueur 2') then
begin
if getGuanaco(Defenseur).nb = 0 then couleurTexte(8)
else couleurtexte(12);
write(getGuanaco(Defenseur).nb);
end
else
begin
if GuanacoEnnemi.nb = 0 then couleurTexte(8)
else couleurtexte(12);
write(GuanacoEnnemi.nb);
end;
couleurTexte(15);
// Affichage du message résumant le déroulement du tour combat
afficherMsgCombat();
{ Choix disponibles }
afficherAction(3,24, '1', 'Cracher sur les lamas ennemis', 'vert');
afficherAction(3,25, '2', 'Cracher sur les Alpagas ennemis', 'vert');
afficherAction(3,26, '3', 'Cracher sur les Guanacos ennemis', 'vert');
{ Partie inférieure de l'écran }
afficherMessage();
afficherCadreAction();
choisir(Joueur);
end;
end.
|
unit ViewTributacaoIpi;
{$mode objfpc}{$H+}
interface
uses
HTTPDefs, BrookRESTActions, BrookUtils, FPJson, SysUtils, BrookHTTPConsts;
type
TViewTributacaoIpiOptions = class(TBrookOptionsAction)
end;
TViewTributacaoIpiRetrieve = class(TBrookRetrieveAction)
procedure Request({%H-}ARequest: TRequest; AResponse: TResponse); override;
end;
TViewTributacaoIpiShow = class(TBrookShowAction)
end;
TViewTributacaoIpiCreate = class(TBrookCreateAction)
end;
TViewTributacaoIpiUpdate = class(TBrookUpdateAction)
end;
TViewTributacaoIpiDestroy = class(TBrookDestroyAction)
end;
implementation
procedure TViewTributacaoIpiRetrieve.Request(ARequest: TRequest; AResponse: TResponse);
var
VRow: TJSONObject;
IdOperacao: String;
IdGrupo: String;
begin
IdOperacao := Values['id_operacao'].AsString;
IdGrupo := Values['id_grupo'].AsString;
Values.Clear;
Table.Where('ID_TRIBUT_OPERACAO_FISCAL = "' + IdOperacao + '" and ID_TRIBUT_GRUPO_TRIBUTARIO = "' + IdGrupo + '"');
if Execute then
begin
Table.GetRow(VRow);
try
Write(VRow.AsJSON);
finally
FreeAndNil(VRow);
end;
end
else
begin
AResponse.Code := BROOK_HTTP_STATUS_CODE_NOT_FOUND;
AResponse.CodeText := BROOK_HTTP_REASON_PHRASE_NOT_FOUND;
end;
// inherited Request(ARequest, AResponse);
end;
initialization
TViewTributacaoIpiOptions.Register('view_tributacao_ipi', '/view_tributacao_ipi');
TViewTributacaoIpiRetrieve.Register('view_tributacao_ipi', '/view_tributacao_ipi/:id_operacao/:id_grupo/');
TViewTributacaoIpiShow.Register('view_tributacao_ipi', '/view_tributacao_ipi/:id');
TViewTributacaoIpiCreate.Register('view_tributacao_ipi', '/view_tributacao_ipi');
TViewTributacaoIpiUpdate.Register('view_tributacao_ipi', '/view_tributacao_ipi/:id');
TViewTributacaoIpiDestroy.Register('view_tributacao_ipi', '/view_tributacao_ipi/:id');
end.
|
unit fpclib;
{******************************************************************************
* stdio.pp
*
* DelphineOS fpc library. It has to define a lot of functions that are used
* by the Free Pascal Compiler.
*
* Functions defined (for the moment) :
*
* - FPC_SHORTSTR_COPY : OK
* - FPC_INITIALIZEUNITS : NOT DONE
* - FPC_DO_EXIT : NOT DONE
*
* CopyLeft 2002 GaLi
*
* version 0.0 - 24/12/2001 - GaLi - Initial version
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*****************************************************************************}
INTERFACE
{$I ../../include/head/asm.h}
IMPLEMENTATION
procedure Move(const source;var dest;count:longint);[public , alias : '_SYSTEM$$_MOVE$$$$$$$$$LONGINT'];
//type
// bytearray = array [0..maxlongint] of byte;
var
i,size : longint;
begin
// Dec(count);
// for i:=0 to count do
// bytearray(dest)[i]:=bytearray(source)[i];
end;
procedure int_strconcat(s1,s2:pointer);[public,alias:'FPC_SHORTSTR_CONCAT'];
var
s1l, s2l : byte;
type
pstring = ^string;
begin
if (s1=nil) or (s2=nil) then
exit;
s1l:=length(pstring(s1)^);
s2l:=length(pstring(s2)^);
if s1l+s2l>255 then
s1l:=255-s2l;
move(pstring(s1)^[1],pstring(s2)^[s2l+1],s1l);
pstring(s2)^[0]:=char(s1l+s2l);
end;
procedure Init_System;[public, alias : 'INIT$_SYSTEM'];
begin
end;
procedure Finalize_Objpas;[public, alias : 'FINALIZE$_OBJPAS'];
begin
end;
procedure Threadvarlist_Objpas;[public, alias : 'THREADVARLIST_OBJPAS'];
begin
end;
{***********************************************************************************
* int_strcopy
*
* Input : string length, pointer to source and destination strings
* Output : None
*
* This procedure is ONLY used by the Free Pascal Compiler
**********************************************************************************}
procedure int_strcopy (len : dword ; sstr, dstr : pointer); assembler; [public, alias : 'FPC_SHORTSTR_COPY'];
asm
push eax
push ecx
cld
mov edi, dstr
mov esi, sstr
mov ecx, len
rep movsb
pop ecx
pop eax
end;
{******************************************************************************
* init
*
* This procedure is ONLY used by the FreePascal Compiler
*****************************************************************************}
procedure initialize_units; [public, alias : 'FPC_INITIALIZEUNITS'];
begin
end;
{******************************************************************************
* do_exit
*
* This procedure is used by the FreePascal Compiler
*****************************************************************************}
procedure do_exit; [public, alias : 'FPC_DO_EXIT'];
begin
end;
const
maxlongint = 2048;
Procedure fillchar(var x;count:longint;value:byte);[public];
type
longintarray = array [0..maxlongint] of longint;
bytearray = array [0..maxlongint] of byte;
var
i,v : longint;
begin
if count = 0 then exit;
v := 0;
v:=(value shl 8) or (value and $FF);
v:=(v shl 16) or (v and $ffff);
for i:=0 to (count div 4) -1 do
longintarray(x)[i]:=v;
for i:=(count div 4)*4 to count-1 do
bytearray(x)[i]:=value;
end;
procedure int_strcmp (dstr, sstr : pointer); assembler; [public, alias : 'FPC_SHORTSTR_COMPARE'];
asm
cld
xor ebx, ebx
xor eax, eax
mov esi, sstr
mov edi, dstr
mov al , [esi]
mov bl , [edi]
inc esi
inc edi
cmp eax, ebx { Same length ? }
jne @Fin
mov ecx, eax
rep cmpsb
@Fin:
end;
{
function strchararray(p:pchar; l : longint):shortstring;[public,alias:'FPC_CHARARRAY_TO_SHORTSTR'];
var
s: shortstring;
begin
if l>=256 then
l:=255
else if l<0 then
l:=0;
move(p^,s[1],l);
s[0]:=char(l);
strchararray := s;
end;
}
procedure str_to_chararray(strtyp, arraysize: longint; src,dest: pchar);[public,alias:'FPC_STR_TO_CHARARRAY'];
type
plongint = ^longint;
var
len: longint;
begin
case strtyp of
{ shortstring }
0:
begin
len := byte(src[0]);
inc(src);
end;
{$ifdef SUPPORT_ANSISTRING}
{ ansistring}
1: len := length(ansistring(pointer(src)));
{$endif SUPPORT_ANSISTRING}
{ longstring }
2:;
{ widestring }
3:;
end;
if len > arraysize then
len := arraysize;
{ make sure we don't dereference src if it can be nil (JM) }
if len > 0 then
move(src^,dest^,len);
fillchar(dest[len],arraysize-len,0);
end;
function strlen(p:pchar):longint;[public , alias :'_SYSTEM$$_STRLEN$PCHAR'];
var i : longint;
begin
i:=0;
while p[i]<>#0 do inc(i);
exit(i);
end;
{
function strpas(p:pchar):shortstring;[public,alias:'FPC_PCHAR_TO_SHORTSTR'];
var
l : longint;
s: shortstring;
begin
if p=nil then
l:=0
else
l:=strlen(p);
if l>255 then
l:=255;
if l>0 then
move(p^,s[1],l);
s[0]:=char(l);
strpas := s;
end;
}
function strcomp(str1,str2:pchar):boolean;[public , alias :'STRCOMP'];
begin
while (str1^ <> #0) or (str2^ <> #0) do
begin
If str1^ <> str2^ then exit(false);
str1+=1;
str2+=1;
end;
exit(true);
end;
Function InitVal(const s:shortstring;var negativ:boolean;var base:byte):ValSInt;
var
Code : Longint;
begin
{Skip Spaces and Tab}
code:=1;
while (code<=length(s)) and (s[code] in [' ',#9]) do
inc(code);
{Sign}
negativ:=false;
case s[code] of
'-' : begin
negativ:=true;
inc(code);
end;
'+' : inc(code);
end;
{Base}
base:=10;
if code<=length(s) then
begin
case s[code] of
'$' : begin
base:=16;
repeat
inc(code);
until (code>=length(s)) or (s[code]<>'0');
end;
'%' : begin
base:=2;
inc(code);
end;
end;
end;
InitVal:=code;
end;
{
Function ValUnsignedInt(Const S: ShortString; var Code: ValSInt): ValUInt; [public, alias:'FPC_VAL_UINT_SHORTSTR'];
var
u, prev: ValUInt;
base : byte;
negative : boolean;
begin
ValUnSignedInt:=0;
Code:=InitVal(s,negative,base);
If Negative or (Code>length(s)) Then
Exit;
while Code<=Length(s) do
begin
case s[Code] of
'0'..'9' : u:=Ord(S[Code])-Ord('0');
'A'..'F' : u:=Ord(S[Code])-(Ord('A')-10);
'a'..'f' : u:=Ord(S[Code])-(Ord('a')-10);
else
u:=16;
end;
prev := ValUnsignedInt;
If (u>=base) or
(ValUInt(MaxUIntValue-u) div ValUInt(Base)<prev) then
begin
ValUnsignedInt:=0;
exit;
end;
ValUnsignedInt:=ValUnsignedInt*ValUInt(base) + u;
inc(code);
end;
code := 0;
end;
}
end.
|
unit TextureBankItem;
interface
uses dglOpenGL, BasicMathsTypes, BasicDataTypes, BasicFunctions, Windows, Graphics,
JPEG, PNGImage, DDS, SysUtils, Abstract2DImageData, Dialogs;
type
TTextureBankItem = class
private
Counter: longword;
Editable : boolean;
ID : GLInt;
Filename: string;
MipmapCount : integer;
TextureSize : integer;
// Constructor and Destructor
procedure Clear;
// Gets
function GetMipmapCount: integer;
function GetSize: integer;
// Sets
procedure SetNumMipmaps(_Value: integer);
// I/O
procedure LoadBmpTexture(const _Filename : string);
procedure LoadJPEGTexture(const _Filename : string);
procedure LoadPNGTexture(const _Filename : string);
procedure LoadTGATexture(const _Filename : string);
procedure LoadDDSTexture(const _Filename : string);
procedure SaveBmpTexture(const _Filename : string);
procedure SaveJPEGTexture(const _Filename : string);
procedure SavePNGTexture(const _Filename : string);
procedure SaveTGATexture(const _Filename : string);
procedure SaveDDSTexture(const _Filename : string);
procedure UploadTexture(_Data : Pointer; _Format: GLInt; _Height,_Width,_Level: integer); overload;
procedure UploadTexture(const _Image : TAbstract2DImageData; _Format: GLInt; _Level: integer); overload;
public
TextureType : integer;
// Constructor and Destructor
constructor Create; overload;
constructor Create(const _Filename: string); overload;
constructor Create(const _Texture: GLInt); overload;
constructor Create(const _Bitmap : TBitmap); overload;
constructor Create(const _Bitmaps : TABitmap); overload;
constructor Create(const _Bitmap : TBitmap; const _AlphaMap: TByteMap); overload;
constructor Create(const _Bitmaps : TABitmap; const _AlphaMaps: TAByteMap); overload;
constructor Create(const _Data : Pointer; _Format: GLInt; _Height,_Width: integer); overload;
constructor Create(const _Image : TAbstract2DImageData); overload;
destructor Destroy; override;
// I/O
procedure LoadTexture(const _Filename : string); overload;
procedure LoadTexture(const _Bitmaps : TABitmap); overload;
procedure LoadTexture(const _Bitmap : TBitmap; _Level: integer); overload;
procedure LoadTexture(const _Bitmaps : TABitmap; const _AlphaMaps: TAByteMap); overload;
procedure LoadTexture(const _Bitmap : TBitmap; const _AlphaMap: TByteMap; _Level: integer); overload;
procedure LoadTexture(const _Data : Pointer; _Format: GLInt; _Height,_Width,_Level: integer); overload;
procedure LoadTexture(const _Image : TAbstract2DImageData; _Format: GLInt); overload;
procedure LoadTexture(const _Image : TAbstract2DImageData; _Format: GLInt;_Level: integer); overload;
procedure ReplaceTexture(const _Filename : string); overload;
procedure ReplaceTexture(const _Bitmaps : TABitmap); overload;
procedure ReplaceTexture(const _Bitmap : TBitmap; _Level: integer); overload;
procedure ReplaceTexture(const _Bitmaps : TABitmap; const _AlphaMaps: TAByteMap); overload;
procedure ReplaceTexture(const _Bitmap : TBitmap; const _AlphaMap: TByteMap; _Level: integer); overload;
procedure ReplaceTexture(const _Image : TAbstract2DImageData); overload;
procedure ReplaceTexture(const _Image : TAbstract2DImageData; _Level: integer); overload;
procedure SaveTexture(const _Filename: string);
function DownloadTexture(_Level : integer): TBitmap; overload;
function DownloadTexture(var _AlphaMap: TByteMap; _Level : integer): TBitmap; overload;
procedure DownloadTexture(_Level : integer; var _Image: TAbstract2DImageData); overload;
// Sets
procedure SetEditable(_value: boolean);
procedure SetFilename(_value: string);
// Gets
function GetEditable: boolean;
function GetFilename: string;
function GetID : GLInt;
// Copies
procedure Clone(_Texture: GLInt);
// Counter
function GetCount : integer;
procedure IncCounter;
procedure DecCounter;
// Properties
property NumMipmaps: integer read GetMipmapCount write SetNumMipmaps;
property Size: integer read GetSize;
end;
PTextureBankItem = ^TTextureBankItem;
implementation
// Constructors and Destructors
// This one starts a blank texture.
constructor TTextureBankItem.Create;
begin
glGenTextures(1, @ID);
Counter := 1;
Filename := '';
end;
constructor TTextureBankItem.Create(const _Filename: string);
begin
glGenTextures(1, @ID);
glEnable(GL_TEXTURE_2D);
LoadTexture(_Filename);
Counter := 1;
glDisable(GL_TEXTURE_2D);
end;
constructor TTextureBankItem.Create(const _Texture: GLInt);
begin
glEnable(GL_TEXTURE_2D);
glGenTextures(1, @ID);
Clone(_Texture);
Counter := 1;
Filename := '';
glDisable(GL_TEXTURE_2D);
end;
constructor TTextureBankItem.Create(const _Bitmap : TBitmap);
begin
glEnable(GL_TEXTURE_2D);
glGenTextures(1, @ID);
LoadTexture(_Bitmap,0);
Counter := 1;
SetNumMipmaps(1);
glDisable(GL_TEXTURE_2D);
end;
constructor TTextureBankItem.Create(const _Bitmaps : TABitmap);
begin
glGenTextures(1, @ID);
glEnable(GL_TEXTURE_2D);
LoadTexture(_Bitmaps);
Counter := 1;
glDisable(GL_TEXTURE_2D);
end;
constructor TTextureBankItem.Create(const _Bitmap : TBitmap; const _AlphaMap: TByteMap);
begin
glEnable(GL_TEXTURE_2D);
glGenTextures(1, @ID);
LoadTexture(_Bitmap,_AlphaMap,0);
Counter := 1;
SetNumMipmaps(1);
glDisable(GL_TEXTURE_2D);
end;
constructor TTextureBankItem.Create(const _Bitmaps : TABitmap; const _AlphaMaps: TAByteMap);
begin
glGenTextures(1, @ID);
glEnable(GL_TEXTURE_2D);
LoadTexture(_Bitmaps,_AlphaMaps);
Counter := 1;
glDisable(GL_TEXTURE_2D);
end;
constructor TTextureBankItem.Create(const _Data : Pointer; _Format: GLInt; _Height,_Width: integer);
begin
glGenTextures(1, @ID);
glEnable(GL_TEXTURE_2D);
LoadTexture(_Data,_Format,_Height,_Width,0);
Counter := 1;
SetNumMipmaps(1);
glDisable(GL_TEXTURE_2D);
end;
constructor TTextureBankItem.Create(const _Image : TAbstract2DImageData);
var
Format: TGLInt;
begin
glGenTextures(1, @ID);
glEnable(GL_TEXTURE_2D);
Format := _Image.GetOpenGLFormat;
LoadTexture(_Image,Format,0);
Counter := 1;
SetNumMipmaps(1);
glDisable(GL_TEXTURE_2D);
end;
destructor TTextureBankItem.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure TTextureBankItem.Clear;
begin
if (ID <> 0) and (ID <> -1) then
glDeleteTextures(1,@ID);
Filename := '';
end;
// I/O
procedure TTextureBankItem.LoadTexture(const _Filename : string);
var
Ext : string;
begin
if FileExists(_Filename) then
begin
Filename := CopyString(_Filename);
Ext := copy(Uppercase(filename), length(filename)-3, 4);
if ext = '.JPG' then
LoadJPEGTexture(Filename)
else if ext = '.BMP' then
LoadBMPTexture(Filename)
else if ext = '.PNG' then
LoadPNGTexture(Filename)
else if ext = '.TGA' then
LoadTGATexture(Filename)
else if ext = '.DDS' then
LoadDDSTexture(Filename);
end;
end;
// Code adapted from Jan Horn's Texture.pas from http://www.sulaco.co.za
procedure TTextureBankItem.LoadTexture(const _Bitmap : TBitmap; _Level: integer);
var
Data : Array of LongWord;
W, H : Integer;
Line : ^LongWord;
begin
SetLength(Data, _Bitmap.Width * _Bitmap.Height);
For H:= 0 to _Bitmap.Height-1 do
begin
Line := _Bitmap.ScanLine[_Bitmap.Height-H-1]; // flip bitmap
For W:= 0 to _Bitmap.Width-1 do
begin
// Switch ABGR to ARGB
Data[W+(H*_Bitmap.Width)] :=((Line^ and $FF) shl 16) + ((Line^ and $FF0000) shr 16) + (Line^ and $FF00FF00);
inc(Line);
end;
end;
UploadTexture(Addr(Data[0]),GL_RGB,_Bitmap.Height,_Bitmap.Width,_Level);
SetLength(Data,0);
end;
procedure TTextureBankItem.LoadTexture(const _Bitmaps: TABitmap);
var
i : integer;
begin
SetNumMipmaps(High(_Bitmaps)+1);
for i := Low(_Bitmaps) to High(_Bitmaps) do
begin
LoadTexture(_Bitmaps[i],i);
end;
end;
// Code adapted from Jan Horn's Texture.pas from http://www.sulaco.co.za
procedure TTextureBankItem.LoadTexture(const _Bitmap : TBitmap; const _AlphaMap : TByteMap; _Level: integer);
var
Data : Array of LongWord;
W, H : Integer;
Line : ^LongWord;
begin
SetLength(Data, _Bitmap.Width * _Bitmap.Height);
For H:= 0 to _Bitmap.Height-1 do
begin
Line := _Bitmap.ScanLine[_Bitmap.Height-H-1]; // flip bitmap
For W:= 0 to _Bitmap.Width-1 do
begin
// Switch ABGR to ARGB
Data[W+(H*_Bitmap.Width)] :=((Line^ and $FF) shl 16) + ((Line^ and $FF0000) shr 16) + (Line^ and $00FF00) + (_AlphaMap[W,_Bitmap.Height-H-1] shl 24);
inc(Line);
end;
end;
UploadTexture(Addr(Data[0]),GL_RGBA,_Bitmap.Height,_Bitmap.Width,_Level);
SetLength(Data,0);
end;
procedure TTextureBankItem.LoadTexture(const _Bitmaps: TABitmap; const _AlphaMaps: TAByteMap);
var
i : integer;
begin
SetNumMipmaps(High(_Bitmaps)+1);
for i := Low(_Bitmaps) to High(_Bitmaps) do
begin
LoadTexture(_Bitmaps[i],_AlphaMaps[i],i);
end;
end;
procedure TTextureBankItem.LoadTexture(const _Data : Pointer; _Format: GLInt; _Height,_Width,_Level: integer);
begin
UploadTexture(_Data,_Format,_Height,_Width,_Level);
end;
procedure TTextureBankItem.LoadTexture(const _Image : TAbstract2DImageData; _Format: GLInt);
begin
UploadTexture(_Image,_Format, 0);
SetNumMipMaps(MipMapCount);
end;
procedure TTextureBankItem.LoadTexture(const _Image : TAbstract2DImageData; _Format: GLInt;_Level: integer);
begin
UploadTexture(_Image,_Format,_Level);
end;
procedure TTextureBankItem.ReplaceTexture(const _Filename : string);
begin
Clear;
glEnable(GL_TEXTURE_2D);
glGenTextures(1, @ID);
glDisable(GL_TEXTURE_2D);
LoadTexture(_Filename);
end;
procedure TTextureBankItem.ReplaceTexture(const _Bitmaps : TABitmap);
begin
Clear;
glEnable(GL_TEXTURE_2D);
glGenTextures(1, @ID);
glDisable(GL_TEXTURE_2D);
LoadTexture(_Bitmaps);
end;
procedure TTextureBankItem.ReplaceTexture(const _Bitmap : TBitmap; _Level: integer);
begin
Clear;
glEnable(GL_TEXTURE_2D);
glGenTextures(1, @ID);
glDisable(GL_TEXTURE_2D);
LoadTexture(_Bitmap,_Level);
end;
procedure TTextureBankItem.ReplaceTexture(const _Bitmaps : TABitmap; const _AlphaMaps: TAByteMap);
begin
Clear;
glEnable(GL_TEXTURE_2D);
glGenTextures(1, @ID);
glDisable(GL_TEXTURE_2D);
LoadTexture(_Bitmaps,_AlphaMaps);
end;
procedure TTextureBankItem.ReplaceTexture(const _Bitmap : TBitmap; const _AlphaMap: TByteMap; _Level: integer);
begin
Clear;
glEnable(GL_TEXTURE_2D);
glGenTextures(1, @ID);
glDisable(GL_TEXTURE_2D);
LoadTexture(_Bitmap,_AlphaMap,_Level);
end;
procedure TTextureBankItem.ReplaceTexture(const _Image : TAbstract2DImageData);
begin
Clear;
glEnable(GL_TEXTURE_2D);
glGenTextures(1, @ID);
glDisable(GL_TEXTURE_2D);
LoadTexture(_Image,_Image.GetOpenGLFormat);
end;
procedure TTextureBankItem.ReplaceTexture(const _Image : TAbstract2DImageData; _Level: integer);
begin
Clear;
glEnable(GL_TEXTURE_2D);
glGenTextures(1, @ID);
glDisable(GL_TEXTURE_2D);
LoadTexture(_Image,_Image.GetOpenGLFormat,_Level);
end;
procedure TTextureBankItem.SaveTexture(const _Filename: string);
var
Ext : string;
begin
if Length(_Filename) > 0 then
Filename := CopyString(_Filename);
Ext := copy(Uppercase(Filename), length(Filename)-3, 4);
if ext = '.JPG' then
SaveJPEGTexture(Filename)
else if ext = '.BMP' then
SaveBMPTexture(Filename)
else if ext = '.PNG' then
SavePNGTexture(Filename)
else if ext = '.TGA' then
SaveTGATexture(Filename)
else if ext = '.DDS' then
SaveDDSTexture(Filename);
end;
procedure TTextureBankItem.LoadBmpTexture(const _Filename : string);
var
Bitmap : TBitmap;
begin
Bitmap := TBitmap.Create;
Bitmap.LoadFromFile(_Filename);
SetNumMipmaps(1);
LoadTexture(Bitmap,0);
Bitmap.Free;
end;
procedure TTextureBankItem.LoadJPEGTexture(const _Filename : string);
var
JPG : TJPEGImage;
Bitmap : TBitmap;
begin
Bitmap := TBitmap.Create;
JPG := TJPEGImage.Create;
JPG.LoadFromFile(_Filename);
Bitmap.PixelFormat := pf32bit;
Bitmap.Width := JPG.Width;
Bitmap.Height := JPG.Height;
Bitmap.Canvas.Draw(0,0,JPG);
SetNumMipmaps(1);
LoadTexture(Bitmap ,0);
Bitmap.Free;
JPG.Free;
end;
procedure TTextureBankItem.LoadPNGTexture(const _Filename : string);
var
PNG : TPNGObject;
Bitmap : TBitmap;
begin
Bitmap := TBitmap.Create;
PNG := TPNGObject.Create;
PNG.LoadFromFile(_Filename);
Bitmap.PixelFormat := pf32bit;
Bitmap.Width := PNG.Width;
Bitmap.Height := PNG.Height;
Bitmap.Canvas.Draw(0,0,PNG);
SetNumMipmaps(1);
LoadTexture(Bitmap ,0);
Bitmap.Free;
PNG.Free;
end;
// code adapted from Jan Horn's Texture.pas from http://www.sulaco.co.za
procedure TTextureBankItem.LoadTGATexture(const _Filename : string);
// Copy a pixel from source to dest and Swap the RGB color values
procedure CopySwapPixel(const Source, Destination : Pointer);
asm
push ebx
mov bl,[eax+0]
mov bh,[eax+1]
mov [edx+2],bl
mov [edx+1],bh
mov bl,[eax+2]
mov bh,[eax+3]
mov [edx+0],bl
mov [edx+3],bh
pop ebx
end;
var
TGAHeader : packed record // Header type for TGA images
FileType : Byte;
ColorMapType : Byte;
ImageType : Byte;
ColorMapSpec : Array[0..4] of Byte;
OrigX : Array [0..1] of Byte;
OrigY : Array [0..1] of Byte;
Width : Array [0..1] of Byte;
Height : Array [0..1] of Byte;
BPP : Byte;
ImageInfo : Byte;
end;
TGAFile : File;
BytesRead : Integer;
Image : Pointer; {or PRGBTRIPLE}
CompImage : Pointer;
Width, Height : Integer;
ColorDepth : Integer;
ImageSize : Integer;
BufferIndex : Integer;
CurrentByte : Integer;
CurrentPixel : Integer;
I : Integer;
Front: ^Byte;
Back: ^Byte;
Temp: Byte;
begin
SetNumMipmaps(1);
AssignFile(TGAFile, Filename);
Reset(TGAFile, 1);
// Read in the bitmap file header
BlockRead(TGAFile, TGAHeader, SizeOf(TGAHeader));
// Only support 24, 32 bit images
if (TGAHeader.ImageType <> 2) AND { TGA_RGB }
(TGAHeader.ImageType <> 10) then { Compressed RGB }
begin
CloseFile(tgaFile);
MessageBox(0, PChar('Couldn''t load "'+ Filename +'". Only 24 and 32bit TGA supported.'), PChar('TGA File Error'), MB_OK);
Exit;
end;
// Don't support colormapped files
if TGAHeader.ColorMapType <> 0 then
begin
CloseFile(TGAFile);
MessageBox(0, PChar('Couldn''t load "'+ Filename +'". Colormapped TGA files not supported.'), PChar('TGA File Error'), MB_OK);
Exit;
end;
// Get the width, height, and color depth
Width := TGAHeader.Width[0] + TGAHeader.Width[1] * 256;
Height := TGAHeader.Height[0] + TGAHeader.Height[1] * 256;
ColorDepth := TGAHeader.BPP;
ImageSize := Width*Height*(ColorDepth div 8);
if ColorDepth < 24 then
begin
CloseFile(TGAFile);
MessageBox(0, PChar('Couldn''t load "'+ Filename +'". Only 24 and 32 bit TGA files supported.'), PChar('TGA File Error'), MB_OK);
Exit;
end;
GetMem(Image, ImageSize);
if TGAHeader.ImageType = 2 then // Standard 24, 32 bit TGA file
begin
BlockRead(TGAFile, Image^, ImageSize, bytesRead);
if bytesRead <> ImageSize then
begin
CloseFile(TGAFile);
MessageBox(0, PChar('Couldn''t read file "'+ Filename +'".'), PChar('TGA File Error'), MB_OK);
Exit;
end;
// TGAs are stored BGR and not RGB, so swap the R and B bytes.
// 32 bit TGA files have alpha channel and gets loaded differently
if TGAHeader.BPP = 24 then
begin
for I :=0 to Width * Height - 1 do
begin
Front := Pointer(Integer(Image) + I*3);
Back := Pointer(Integer(Image) + I*3 + 2);
Temp := Front^;
Front^ := Back^;
Back^ := Temp;
end;
UploadTexture(Image, GL_RGB, Height, Width, 0);
end
else
begin
for I :=0 to Width * Height - 1 do
begin
Front := Pointer(Integer(Image) + I*4);
Back := Pointer(Integer(Image) + I*4 + 2);
Temp := Front^;
Front^ := Back^;
Back^ := Temp;
end;
UploadTexture(Image, GL_RGBA, Height, Width, 0);
end;
end;
// Compressed 24, 32 bit TGA files
if TGAHeader.ImageType = 10 then
begin
ColorDepth := ColorDepth DIV 8;
CurrentByte := 0;
CurrentPixel := 0;
BufferIndex := 0;
GetMem(CompImage, FileSize(TGAFile)-sizeOf(TGAHeader));
BlockRead(TGAFile, CompImage^, FileSize(TGAFile)-sizeOf(TGAHeader), BytesRead); // load compressed data into memory
if bytesRead <> FileSize(TGAFile)-sizeOf(TGAHeader) then
begin
CloseFile(TGAFile);
MessageBox(0, PChar('Couldn''t read file "'+ Filename +'".'), PChar('TGA File Error'), MB_OK);
Exit;
end;
// Extract pixel information from compressed data
repeat
Front := Pointer(Integer(CompImage) + BufferIndex);
Inc(BufferIndex);
if Front^ < 128 then
begin
For I := 0 to Front^ do
begin
CopySwapPixel(Pointer(Integer(CompImage)+BufferIndex+I*ColorDepth), Pointer(Integer(image)+CurrentByte));
CurrentByte := CurrentByte + ColorDepth;
inc(CurrentPixel);
end;
BufferIndex :=BufferIndex + (Front^+1)*ColorDepth
end
else
begin
For I := 0 to Front^ -128 do
begin
CopySwapPixel(Pointer(Integer(CompImage)+BufferIndex), Pointer(Integer(image)+CurrentByte));
CurrentByte := CurrentByte + ColorDepth;
inc(CurrentPixel);
end;
BufferIndex :=BufferIndex + ColorDepth
end;
until CurrentPixel >= Width*Height;
FreeMem(CompImage);
if ColorDepth = 3 then
UploadTexture(Image,GL_RGB,Height,Width,0)
else
UploadTexture(Image,GL_RGBA,Height,Width,0);
end;
CloseFile(TGAFile);
FreeMem(Image);
end;
procedure TTextureBankItem.LoadDDSTexture(const _Filename : string);
var
DDS : TDDSImage;
Width, Height: integer;
begin
DDS := TDDSImage.Create;
// The DDS Load procedure creates a new texture, so we'll have to eliminate
// the current one.
glEnable(GL_TEXTURE_2D);
if (ID <> 0) and (ID <> -1) then
glDeleteTextures(1,@ID);
DDS.LoadFromFile(_Filename,Cardinal(ID),false,Width,Height);
DDS.Free;
end;
procedure TTextureBankItem.SaveBmpTexture(const _Filename : string);
var
Bitmap : TBitmap;
begin
Bitmap := DownloadTexture(0);
Bitmap.SaveToFile(Filename);
Bitmap.Free;
end;
procedure TTextureBankItem.SaveJPEGTexture(const _Filename : string);
var
JPEGImage: TJPEGImage;
Bitmap : TBitmap;
begin
Bitmap := DownloadTexture(0);
JPEGImage := TJPEGImage.Create;
JPEGImage.Assign(Bitmap);
JPEGImage.SaveToFile(_Filename);
Bitmap.Free;
JPEGImage.Free;
end;
procedure TTextureBankItem.SavePNGTexture(const _Filename : string);
var
PNGImage: TPNGObject;
Bitmap : TBitmap;
begin
Bitmap := DownloadTexture(0);
PNGImage := TPNGObject.Create;
PNGImage.Assign(Bitmap);
PNGImage.SaveToFile(_Filename);
Bitmap.Free;
PNGImage.Free;
end;
procedure TTextureBankItem.SaveTGATexture(const _Filename : string);
var
buffer: array of byte;
Width, Height, i, c, temp: integer;
f: file;
Tempi : PGLInt;
begin
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D,ID);
GetMem(Tempi,4);
glGetTexLevelParameteriv(GL_TEXTURE_2D,0,GL_TEXTURE_WIDTH,tempi);
Width := tempi^;
FreeMem(tempi);
GetMem(tempi,4);
glGetTexLevelParameteriv(GL_TEXTURE_2D,0,GL_TEXTURE_HEIGHT,tempi);
Height := tempi^;
FreeMem(tempi);
try
SetLength(buffer, (Width * Height * 4) + 18);
begin
for i := 0 to 17 do
buffer[i] := 0;
buffer[2] := 2; //uncompressed type
buffer[12] := Width and $ff;
buffer[13] := Width shr 8;
buffer[14] := Height and $ff;
buffer[15] := Height shr 8;
buffer[16] := 32; //pixel size
buffer[17] := 8;
glGetTexImage(GL_TEXTURE_2D,0,GL_RGBA,GL_UNSIGNED_BYTE,Pointer(Cardinal(buffer) + 18));
AssignFile(f, _Filename);
Rewrite(f, 1);
for i := 0 to 17 do
BlockWrite(f, buffer[i], sizeof(byte) , temp);
c := 18;
for i := 0 to (Width * Height)-1 do
begin
// buffer[c+3] := 255 - buffer[c+3]; // invert alpha.
BlockWrite(f, buffer[c+2], sizeof(byte) , temp);
BlockWrite(f, buffer[c+1], sizeof(byte) , temp);
BlockWrite(f, buffer[c], sizeof(byte) , temp);
BlockWrite(f, buffer[c+3], sizeof(byte) , temp);
inc(c,4);
end;
closefile(f);
end;
finally
finalize(buffer);
end;
end;
procedure TTextureBankItem.SaveDDSTexture(const _Filename : string);
var
DDSImage : TDDSImage;
begin
DDSImage := TDDSImage.Create;
DDSImage.SaveToFile(_Filename,ID);
DDSImage.Free;
end;
procedure TTextureBankItem.UploadTexture(_Data : Pointer; _Format: GLInt; _Height,_Width,_Level: integer);
begin
TextureSize := _Width;
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, ID);
glTexImage2D(GL_TEXTURE_2D, _Level, _Format, _Width, _Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, _Data);
glDisable(GL_TEXTURE_2D);
end;
procedure TTextureBankItem.UploadTexture(const _Image : TAbstract2DImageData; _Format: GLInt; _Level: integer);
var
Data: AUInt32;
begin
TextureSize := _Image.XSize;
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, ID);
Data := _Image.SaveToGL_RGBA;
glTexImage2D(GL_TEXTURE_2D, _Level, _Format, _Image.XSize, _Image.YSize, 0, GL_RGBA, GL_UNSIGNED_BYTE, Addr(Data[0]));
SetLength(Data,0);
glDisable(GL_TEXTURE_2D);
end;
// Borrowed and adapted from Stucuk's code from OS: Voxel Viewer 1.80+ without AllWhite.
function TTextureBankItem.DownloadTexture(_Level : integer) : TBitmap;
var
RGBBits : PRGBQuad;
Pixel : PRGBQuad;
x,y : Integer;
Width, Height, maxx, maxy : cardinal;
Tempi : PGLInt;
begin
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D,ID);
GetMem(Tempi,4);
glGetTexLevelParameteriv(GL_TEXTURE_2D,_Level,GL_TEXTURE_WIDTH,tempi);
Width := tempi^;
FreeMem(tempi);
GetMem(tempi,4);
glGetTexLevelParameteriv(GL_TEXTURE_2D,_Level,GL_TEXTURE_HEIGHT,tempi);
Height := tempi^;
FreeMem(tempi);
GetMem(RGBBits, Width * Height * 4);
glGetTexImage(GL_TEXTURE_2D,_Level,GL_RGBA,GL_UNSIGNED_BYTE, RGBBits);
glDisable(GL_TEXTURE_2D);
Result := TBitmap.Create;
Result.PixelFormat := pf32Bit;
Result.Width := Width;
Result.Height := Height;
Pixel := RGBBits;
maxy := Height-1;
maxx := Width-1;
for y := 0 to maxy do
for x := 0 to maxx do
begin
Result.Canvas.Pixels[x,maxy-y] := RGB(Pixel.rgbBlue,Pixel.rgbGreen,Pixel.rgbRed);
inc(Pixel);
end;
FreeMem(RGBBits);
end;
function TTextureBankItem.DownloadTexture(var _AlphaMap: TByteMap; _Level : integer) : TBitmap;
var
RGBBits : PRGBQuad;
Pixel : PRGBQuad;
x,y : Integer;
Width, Height, maxx, maxy : cardinal;
Tempi : PGLInt;
begin
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D,ID);
GetMem(Tempi,4);
glGetTexLevelParameteriv(GL_TEXTURE_2D,_Level,GL_TEXTURE_WIDTH,tempi);
Width := tempi^;
FreeMem(tempi);
GetMem(tempi,4);
glGetTexLevelParameteriv(GL_TEXTURE_2D,_Level,GL_TEXTURE_HEIGHT,tempi);
Height := tempi^;
FreeMem(tempi);
GetMem(RGBBits, Width * Height * 4);
glGetTexImage(GL_TEXTURE_2D,_Level,GL_RGBA,GL_UNSIGNED_BYTE, RGBBits);
glDisable(GL_TEXTURE_2D);
Result := TBitmap.Create;
Result.PixelFormat := pf32Bit;
Result.Width := Width;
Result.Height := Height;
SetLength(_AlphaMap,Width,Height);
Pixel := RGBBits;
maxy := Height-1;
maxx := Width-1;
for y := 0 to maxy do
for x := 0 to maxx do
begin
Result.Canvas.Pixels[x,maxy-y] := RGB(Pixel.rgbBlue,Pixel.rgbGreen,Pixel.rgbRed);
_AlphaMap[x,maxy-y] := Pixel.rgbReserved;
inc(Pixel);
end;
FreeMem(RGBBits);
end;
procedure TTextureBankItem.DownloadTexture(_Level : integer; var _Image: TAbstract2DImageData);
var
Width, Height : cardinal;
Tempi : PGLInt;
Data: Pointer;
begin
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D,ID);
GetMem(Tempi,4);
glGetTexLevelParameteriv(GL_TEXTURE_2D,_Level,GL_TEXTURE_WIDTH,tempi);
Width := tempi^;
FreeMem(tempi);
GetMem(tempi,4);
glGetTexLevelParameteriv(GL_TEXTURE_2D,_Level,GL_TEXTURE_HEIGHT,tempi);
Height := tempi^;
FreeMem(tempi);
GetMem(Data, Width * Height * 4);
glGetTexImage(GL_TEXTURE_2D,_Level,GL_RGBA,GL_UNSIGNED_BYTE, Data);
glDisable(GL_TEXTURE_2D);
{
RData := Data;
for x := 0 to (Width * Height) - 1 do
begin
GData := PByte(Cardinal(Data) + 1);
BData := PByte(Cardinal(Data) + 2);
AData := PByte(Cardinal(Data) + 3);
if (RData^ + GData^ + BData^ + AData^) > 0 then
ShowMessage('Position: ' + IntToStr(x) + ' - (' + IntToStr(RData^) + ', ' + IntToStr(GData^) + ', ' + IntToStr(BData^) + ', ' + IntToStr(AData^) + ')');
RData := PByte(Cardinal(Data) + 4);
end;
}
_Image.LoadGL_RGBA(Addr(Data^),Width,Height);
FreeMem(Data);
end;
// Sets
procedure TTextureBankItem.SetEditable(_value: boolean);
begin
Editable := _value;
end;
procedure TTextureBankItem.SetFilename(_value: string);
begin
Filename := CopyString(_Value);
end;
procedure TTextureBankItem.SetNumMipmaps(_Value: integer);
var
BaseLevel,MaxLevel: TGLInt;
BorderColor: TVector4f;
begin
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, ID);
MipmapCount := _Value;
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
if MipMapCount < 1 then
MipMapCount := 1;
if MipmapCount > 1 then
begin
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
end
else
begin
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
end;
BaseLevel := 0;
glTexParameteriv(GL_TEXTURE_2D,GL_TEXTURE_BASE_LEVEL,@BaseLevel);
MaxLevel := MipMapCount - 1;
glTexParameteriv(GL_TEXTURE_2D,GL_TEXTURE_MAX_LEVEL,@MaxLevel);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
BorderColor.X := 0;
BorderColor.Y := 0;
BorderColor.Z := 0;
BorderColor.W := 1;
glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, @BorderColor);
glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_REPLACE);
glGenerateMipMap(GL_TEXTURE_2D);
glDisable(GL_TEXTURE_2D);
end;
// Gets
function TTextureBankItem.GetEditable: boolean;
begin
Result := Editable;
end;
function TTextureBankItem.GetFilename: string;
begin
Result := Filename;
end;
function TTextureBankItem.GetID : GLInt;
begin
Result := ID;
end;
function TTextureBankItem.GetMipmapCount: integer;
begin
Result := MipMapCount;
end;
function TTextureBankItem.GetSize: integer;
begin
Result := TextureSize;
end;
// Copies
procedure TTextureBankItem.Clone(_Texture: Integer);
var
Pixels : PByte;
x,xSize,ySize,BaseLevel,MaxLevel : integer;
tempi : PGLInt;
begin
glEnable(GL_TEXTURE_2D);
// Let's clone the texture here.
glBindTexture(GL_TEXTURE_2D,_Texture);
// How many mipmaps does it have?
GetMem(tempi,4);
glGetTexParameteriv(GL_TEXTURE_2D,GL_TEXTURE_MAX_LEVEL,tempi);
MaxLevel := tempi^;
FreeMem(tempi);
GetMem(tempi,4);
glGetTexParameteriv(GL_TEXTURE_2D,GL_TEXTURE_BASE_LEVEL,tempi);
BaseLevel := tempi^;
FreeMem(tempi);
if (MaxLevel = 1000) then
MaxLevel := BaseLevel;
// Now we setup the mipmap levels at the new texture.
glBindTexture(GL_TEXTURE_2D,ID);
glTexParameteriv(GL_TEXTURE_2D,GL_TEXTURE_BASE_LEVEL,@BaseLevel);
glTexParameteriv(GL_TEXTURE_2D,GL_TEXTURE_MAX_LEVEL,@MaxLevel);
for x := BaseLevel to MaxLevel do
begin
// Get the dimensions of the mipmap
glBindTexture(GL_TEXTURE_2D,_Texture);
GetMem(tempi,4);
glGetTexLevelParameteriv(GL_TEXTURE_2D,x,GL_TEXTURE_WIDTH,tempi);
xSize := tempi^;
FreeMem(tempi);
GetMem(tempi,4);
glGetTexLevelParameteriv(GL_TEXTURE_2D,x,GL_TEXTURE_HEIGHT,tempi);
ySize := tempi^;
FreeMem(tempi);
// Get data from mipmap.
GetMem(Pixels, xSize*ySize*4);
glGetTexImage(GL_TEXTURE_2D,x,GL_RGBA,GL_UNSIGNED_BYTE,Pixels);
// Copy data to the new texture's respective mipmap.
glBindTexture(GL_TEXTURE_2D,ID);
glTexImage2D(GL_TEXTURE_2D,x,GL_RGBA,xSize,ySize,0,GL_RGBA,GL_UNSIGNED_BYTE,Pixels);
FreeMem(Pixels);
end;
glDisable(GL_TEXTURE_2D);
end;
// Counter
function TTextureBankItem.GetCount : integer;
begin
Result := Counter;
end;
procedure TTextureBankItem.IncCounter;
begin
inc(Counter);
end;
procedure TTextureBankItem.DecCounter;
begin
Dec(Counter);
end;
end.
|
unit ThCustomCtrl;
interface
uses
Windows, Classes, Controls, Messages;
{$R-}
type
//:$ Ancestor class for all TurboHtml Windowed controls, base class for
//:$ TThStyledCustomControl.
//:: TThCustomControl adds auto-sizing and text handling machinery to
//:: TCustomControl.
TThCustomControl = class(TCustomControl)
private
{$ifdef __ThClx__}
FCaption: string;
{$endif}
FResizing: Boolean;
FTransparent: Boolean;
FOpaque: Boolean;
protected
// Protected not private so subclasses can set a default value
FAutoSize: Boolean;
//:$ Property setter for AutoSize.
//:: TurboHtml defines a custom AutoSize property so that it will be
//:: available for both VCL and CLX classes.
procedure SetCustomAutoSize(const Value: Boolean); virtual;
procedure SetOpaque(const Value: Boolean);
{$ifdef __ThClx__}
function GetText: TCaption; override;
procedure SetText(const inText: TCaption); override;
{$endif}
procedure SetTransparent(const Value: Boolean);
protected
procedure AdjustSize; override;
procedure Paint; override;
//:$ Adjusts the controls size based on it's contents.
//:: If AutoSize is true, then the PerformAutoSize procedure is called when
//:: the object should size itself. Descendant classes should override
//:: PerformAutoSize in order to implement AutoSizing.
procedure PerformAutoSize; virtual;
procedure Resize; override;
function ShouldAutoSize: Boolean; virtual;
{$ifdef __ThClx__}
procedure TextChanged; override;
{$else}
procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED;
//:$ Hook for the control to take action if it's text is changed (VCL).
//:: TextChanged calls AdjustSize and Invalidate. Descendant classes can
//:: override TextChanged for different behavior.
procedure TextChanged; virtual;
{$endif}
procedure WMEraseBkGnd(var Msg: TWMEraseBkGnd); message WM_ERASEBKGND;
procedure WMMove(var Message: TWMMove); message WM_MOVE;
protected
//:$ Specifies whether the control should size itself based on it's contents.
//:: If AutoSize is true, then the PerformAutoSize procedure is called when
//:: the object should size itself. Descendant classes should override
//:: PerformAutoSize.
property AutoSize: Boolean read FAutoSize write SetCustomAutoSize;
property Opaque: Boolean read FOpaque write SetOpaque;
property Transparent: Boolean read FTransparent write SetTransparent;
end;
implementation
{ TThCustomControl }
procedure TThCustomControl.Paint;
var
saveIndex: Integer;
canvasHandle: Integer;
begin
if Transparent then
begin
{ This code will re-paint the parent panel }
{ This way, you may have 1 trans panel on another }
saveIndex := SaveDC(Canvas.Handle);
canvasHandle := Integer(Canvas.Handle);
MoveWindowOrg(canvasHandle, -Left, -Top);
Parent.Perform(WM_PAINT, canvasHandle, 0);
RestoreDC(Canvas.Handle, saveIndex);
end;
end;
procedure TThCustomControl.WMEraseBkGnd(var Msg : TWMEraseBkGnd);
begin
if Transparent or Opaque then
Msg.Result := 0
else
inherited;
end;
procedure TThCustomControl.WMMove(Var Message:TWMMove);
begin
if Transparent then
Invalidate
else
inherited;
end;
{$ifdef __ThClx__}
function TThCustomControl.GetText: TCaption;
begin
Result := FCaption;
end;
procedure TThCustomControl.SetText(const inText: TCaption);
begin
if (FCaption <> inText) then
begin
FCaption := inText;
TextChanged;
end;
end;
{$else}
procedure TThCustomControl.CMTextChanged(var Message: TMessage);
begin
inherited;
TextChanged;
end;
{$endif}
procedure TThCustomControl.SetCustomAutoSize(const Value: Boolean);
begin
FAutoSize := Value;
if FAutoSize then
AdjustSize
else if (Parent <> nil) then
Parent.Realign;
end;
procedure TThCustomControl.Resize;
begin
inherited;
if not FResizing then
try
FResizing := true;
AdjustSize;
finally
FResizing := false;
end;
end;
procedure TThCustomControl.TextChanged;
begin
AdjustSize;
Invalidate;
end;
function TThCustomControl.ShouldAutoSize: Boolean;
begin
Result := AutoSize;
end;
procedure TThCustomControl.AdjustSize;
begin
if ShouldAutoSize
and not (csLoading in ComponentState)
and not (csDestroying in ComponentState) then
PerformAutoSize
else
inherited;
end;
procedure TThCustomControl.PerformAutoSize;
begin
//
end;
procedure TThCustomControl.SetTransparent(const Value: Boolean);
begin
FTransparent := Value;
Invalidate;
end;
procedure TThCustomControl.SetOpaque(const Value: Boolean);
begin
FOpaque := Value;
Invalidate;
end;
end.
|
unit BrushToolUnit;
interface
uses
System.UITypes,
System.SysUtils,
System.Classes,
System.Math,
Winapi.Windows,
Vcl.Forms,
Vcl.ComCtrls,
Vcl.StdCtrls,
Vcl.Controls,
Vcl.Graphics,
Vcl.Dialogs,
Vcl.ExtCtrls,
Dmitry.Graphics.Types,
Dmitry.Graphics.Utils,
Dmitry.Controls.WebLink,
ToolsUnit,
uSettings,
uEditorTypes,
uMemory;
type
TBrushToolClass = class(TToolsPanelClass)
private
{ Private declarations }
BrushSizeCaption: TStaticText;
BrushSizeTrackBar: TTrackBar;
BrusTransparencyCaption: TStaticText;
BrusTransparencyTrackBar: TTrackBar;
BrushColorCaption: TStaticText;
BrushColorChooser: TShape;
BrushColorChooserDialog: TColorDialog;
FButtonCustomColor: TButton;
LabelMethod: TLabel;
CloseLink: TWebLink;
MakeItLink: TWebLink;
SaveSettingsLink: TWebLink;
Drawing: Boolean;
BeginPoint, EndPoint: TPoint;
FProcRecteateImage: TNotifyEvent;
FOwner: TObject;
NewImage: TBitmap;
Cur: HIcon;
Initialized: Boolean;
FButtonPressed: Boolean;
Brush: TBrushToDraw;
procedure SetProcRecteateImage(const Value: TNotifyEvent);
procedure ButtonMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure ButtonMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure ButtonMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
protected
function LangID: string; override;
public
{ Public declarations }
MethodDrawChooser: TComboBox;
FDrawlayer: PARGB32Array;
LastRect: TRect;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure ClosePanelEvent(Sender: TObject);
procedure ClosePanel; override;
procedure MakeTransform; override;
procedure DoMakeImage(Sender: TObject);
procedure SetBeginPoint(P: TPoint);
procedure SetNextPoint(P: TPoint);
procedure SetEndPoint(P: TPoint);
procedure DrawBrush;
property ProcRecteateImage: TNotifyEvent read FProcRecteateImage write SetProcRecteateImage;
procedure SetOwner(AOwner: TObject);
procedure Initialize;
procedure NewCursor;
procedure BrushSizeChanged(Sender: TObject);
procedure BrushTransparencyChanged(Sender: TObject);
function GetCur: HIcon;
procedure ColorClick(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure DoSaveSettings(Sender: TObject);
class function ID: string; override;
function GetProperties: string; override;
procedure SetProperties(Properties: string); override;
procedure ExecuteProperties(Properties: string; OnDone: TNotifyEvent); override;
end;
implementation
{ TBrushToolClass }
procedure TBrushToolClass.ClosePanel;
begin
if Assigned(OnClosePanel) then
OnClosePanel(Self);
inherited;
end;
procedure TBrushToolClass.ClosePanelEvent(Sender: TObject);
begin
CancelTempImage(True);
ClosePanel;
end;
constructor TBrushToolClass.Create(AOwner: TComponent);
begin
inherited;
Cur := 0;
Align := AlClient;
FButtonPressed := False;
Drawing := False;
Initialized := False;
BrushSizeCaption := TStaticText.Create(AOwner);
BrushSizeCaption.Top := 5;
BrushSizeCaption.Left := 8;
BrushSizeCaption.Caption := L('Brush size [%d]');
BrushSizeCaption.Parent := Self;
BrushSizeTrackBar := TTrackBar.Create(AOwner);
BrushSizeTrackBar.Top := BrushSizeCaption.Top + BrushSizeCaption.Height + 5;
BrushSizeTrackBar.Left := 8;
BrushSizeTrackBar.Width := 160;
BrushSizeTrackBar.OnChange := BrushSizeChanged;
BrushSizeTrackBar.Min := 1;
BrushSizeTrackBar.Max := 500;
BrushSizeTrackBar.Position := AppSettings.ReadInteger('Editor', 'BrushToolSize', 30);
BrushSizeTrackBar.Parent := Self;
BrusTransparencyCaption := TStaticText.Create(AOwner);
BrusTransparencyCaption.Top := BrushSizeTrackBar.Top + BrushSizeTrackBar.Height + 3;
BrusTransparencyCaption.Left := 8;
BrusTransparencyCaption.Caption := L('Transparency');
BrusTransparencyCaption.Parent := Self;
BrusTransparencyTrackBar := TTrackBar.Create(AOwner);
BrusTransparencyTrackBar.Top := BrusTransparencyCaption.Top + BrusTransparencyCaption.Height + 5;
BrusTransparencyTrackBar.Left := 8;
BrusTransparencyTrackBar.Width := 160;
BrusTransparencyTrackBar.OnChange := BrushTransparencyChanged;
BrusTransparencyTrackBar.Min := 1;
BrusTransparencyTrackBar.Max := 100;
BrusTransparencyTrackBar.Position := AppSettings.ReadInteger('Editor', 'BrushTransparency', 100);
BrusTransparencyTrackBar.Parent := Self;
BrusTransparencyCaption.Caption := Format(L('Transparency [%d]'), [BrusTransparencyTrackBar.Position]);
LabelMethod := TLabel.Create(AOwner);
LabelMethod.Left := 8;
LabelMethod.Top := BrusTransparencyTrackBar.Top + BrusTransparencyTrackBar.Height + 5;
LabelMethod.Parent := Self;
LabelMethod.Caption := L('Method') + ':';
MethodDrawChooser := TComboBox.Create(AOwner);
MethodDrawChooser.Top := LabelMethod.Top + LabelMethod.Height + 5;
MethodDrawChooser.Left := 8;
MethodDrawChooser.Width := 150;
MethodDrawChooser.Height := 20;
MethodDrawChooser.Parent := Self;
MethodDrawChooser.Style := CsDropDownList;
MethodDrawChooser.Items.Add(L('Normal'));
MethodDrawChooser.Items.Add(L('Color replace'));
MethodDrawChooser.ItemIndex := AppSettings.ReadInteger('Editor', 'BrushToolStyle', 0);
MethodDrawChooser.OnChange := BrushTransparencyChanged;
BrushColorChooser := TShape.Create(AOwner);
BrushColorChooser.Top := MethodDrawChooser.Top + MethodDrawChooser.Height + 12;
BrushColorChooser.Left := 10;
BrushColorChooser.Width := 20;
BrushColorChooser.Height := 20;
BrushColorChooser.Brush.Color := AppSettings.ReadInteger('Editor', 'BrushToolColor', 0);
BrushColorChooser.OnMouseDown := ColorClick;
BrushColorChooser.Parent := Self;
BrushColorCaption := TStaticText.Create(AOwner);
BrushColorCaption.Top := MethodDrawChooser.Top + MethodDrawChooser.Height + 15;
BrushColorCaption.Left := BrushColorChooser.Left + BrushColorChooser.Width + 5;
BrushColorCaption.Caption := L('Brush color');
BrushColorCaption.Parent := Self;
FButtonCustomColor := TButton.Create(Self);
FButtonCustomColor.Parent := Self;
FButtonCustomColor.Top := BrushColorCaption.Top + BrushColorCaption.Height + 5;
FButtonCustomColor.Width := 80;
FButtonCustomColor.Height := 21;
FButtonCustomColor.Left := 8;
FButtonCustomColor.Caption := L('Choose color');
FButtonCustomColor.OnMouseDown := ButtonMouseDown;
FButtonCustomColor.OnMouseMove := ButtonMouseMove;
FButtonCustomColor.OnMouseUp := ButtonMouseUp;
BrushColorChooserDialog := TColorDialog.Create(AOwner);
SaveSettingsLink := TWebLink.Create(Self);
SaveSettingsLink.Parent := AOwner as TWinControl;
SaveSettingsLink.Text := L('Save settings');
SaveSettingsLink.Top := FButtonCustomColor.Top + FButtonCustomColor.Height + 15;
SaveSettingsLink.Left := 10;
SaveSettingsLink.Visible := True;
SaveSettingsLink.Color := ClBtnface;
SaveSettingsLink.OnClick := DoSaveSettings;
SaveSettingsLink.LoadFromResource('SAVETOFILE');
SaveSettingsLink.RefreshBuffer(True);
MakeItLink := TWebLink.Create(Self);
MakeItLink.Parent := AOwner as TWinControl;
MakeItLink.Text := L('Apply');
MakeItLink.Top := SaveSettingsLink.Top + SaveSettingsLink.Height + 5;
MakeItLink.Left := 10;
MakeItLink.Visible := True;
MakeItLink.Color := ClBtnface;
MakeItLink.OnClick := DoMakeImage;
MakeItLink.LoadFromResource('DOIT');
MakeItLink.RefreshBuffer(True);
CloseLink := TWebLink.Create(Self);
CloseLink.Parent := AOwner as TWinControl;
CloseLink.Text := L('Close tool');
CloseLink.Top := MakeItLink.Top + MakeItLink.Height + 5;
CloseLink.Left := 10;
CloseLink.Visible := True;
CloseLink.Color := ClBtnface;
CloseLink.OnClick := ClosePanelEvent;
CloseLink.LoadFromResource('CANCELACTION');
CloseLink.RefreshBuffer(True);
end;
destructor TBrushToolClass.Destroy;
begin
F(BrushSizeCaption);
F(BrushSizeTrackBar);
F(BrusTransparencyCaption);
F(BrusTransparencyTrackBar);
F(BrushColorCaption);
F(BrushColorChooser);
F(BrushColorChooserDialog);
if Cur <> 0 then
DestroyIcon(Cur);
F(MakeItLink);
F(CloseLink);
inherited;
end;
procedure TBrushToolClass.DoMakeImage(Sender: TObject);
begin
MakeTransform;
end;
procedure TBrushToolClass.DrawBrush;
var
R, G, B: Byte;
Rad: Integer;
begin
R := GetRValue(BrushColorChooser.Brush.Color);
G := GetGValue(BrushColorChooser.Brush.Color);
B := GetBValue(BrushColorChooser.Brush.Color);
Rad := Max(1, Round(BrushSizeTrackBar.Position));
DoBrush(FDrawlayer, Brush, Image.Width, Image.Height, BeginPoint.X, BeginPoint.Y, EndPoint.X, EndPoint.Y, R, G, B, Rad);
LastRect := Rect(BeginPoint.X, BeginPoint.Y, EndPoint.X, EndPoint.Y);
LastRect := NormalizeRect(LastRect);
LastRect.Top := Max(0, LastRect.Top - Rad div 2);
LastRect.Left := Max(0, LastRect.Left - Rad div 2);
LastRect.Bottom := Min(Image.Height - 1, LastRect.Bottom + Rad div 2);
LastRect.Right := Min(Image.Width - 1, LastRect.Right + Rad div 2);
Editor.Transparency := BrusTransparencyTrackBar.Position / 100;
if Assigned(FProcRecteateImage) then
FProcRecteateImage(Self);
end;
procedure TBrushToolClass.Initialize;
begin
NewImage := TBitmap.Create;
NewImage.Assign(Image);
SetTempImage(NewImage);
Initialized:=true;
end;
function TBrushToolClass.LangID: string;
begin
Result := 'BrushTool';
end;
procedure TBrushToolClass.MakeTransform;
var
I: Integer;
P: PARGBArray;
begin
inherited;
SetLength(P, Image.Height);
for I := 0 to Image.Height - 1 do
P[I] := NewImage.ScanLine[I];
StretchFastATrans(0, 0, Image.Width, Image.Height, Image.Width, Image.Height, FDrawlayer, P,
BrusTransparencyTrackBar.Position / 100, MethodDrawChooser.ItemIndex);
ImageHistory.Add(NewImage, '{' + ID + '}[' + GetProperties + ']');
SetImagePointer(NewImage);
ClosePanel;
end;
procedure TBrushToolClass.SetBeginPoint(P: TPoint);
begin
Drawing := True;
BeginPoint := P;
EndPoint := P;
DrawBrush;
end;
procedure TBrushToolClass.SetEndPoint(P: TPoint);
begin
Drawing := False;
end;
procedure TBrushToolClass.SetNextPoint(P: TPoint);
begin
if Drawing then
begin
BeginPoint := EndPoint;
EndPoint := P;
DrawBrush;
end;
end;
procedure TBrushToolClass.SetOwner(AOwner: TObject);
begin
FOwner := AOwner;
end;
procedure TBrushToolClass.SetProcRecteateImage(const Value: TNotifyEvent);
begin
FProcRecteateImage := Value;
end;
procedure TBrushToolClass.NewCursor;
var
Rad, CurSize: Integer;
AndMask : TBitmap;
IconInfo : TIconInfo;
Bit: TBitmap;
begin
if not Initialized then
Exit;
Rad := Max(2, Round(BrushSizeTrackBar.Position));
CurSize := Min(500, Max(2, Round(BrushSizeTrackBar.Position * Editor.Zoom)));
CreateBrush(Brush, Rad);
if not Editor.VirtualBrushCursor then
begin
Bit := TBitmap.Create;
try
Bit.PixelFormat := pf1bit;
Bit.SetSize(CurSize, CurSize);
Bit.PixelFormat := pf4bit;
AndMask := TBitmap.Create;
try
AndMask.Monochrome := True;
AndMask.Width := CurSize;
AndMask.Height := CurSize;
AndMask.Canvas.Brush.Color := $FFFFFF;
AndMask.Canvas.Pen.Color := $FFFFFF;
AndMask.Canvas.FillRect(Rect(0, 0, Bit.Width, Bit.Height));
Bit.Canvas.Pen.Color := $0;
Bit.Canvas.Brush.Color := $0;
Bit.Canvas.FillRect(Rect(0, 0, Bit.Width, Bit.Height));
Bit.Canvas.Pen.Color := $FFFFFF;
Bit.Canvas.Ellipse(Rect(0, 0, Bit.Width, Bit.Height));
IconInfo.FIcon := True;
IconInfo.XHotspot := 1;
IconInfo.YHotspot := 1;
IconInfo.HbmMask := AndMask.Handle;
IconInfo.HbmColor := Bit.Handle;
if Cur <> 0 then
DestroyIcon(Cur);
Cur := 0;
Cur := CreateIconIndirect(IconInfo);
finally
F(AndMask);
end;
finally
F(Bit);
end;
Screen.Cursors[67] := Cur;
end else
begin
ClearBrush(Editor.VBrush);
MakeRadialBrush(Editor.VBrush, CurSize div 2);
end;
end;
procedure TBrushToolClass.BrushSizeChanged(Sender: TObject);
begin
BrushSizeCaption.Caption := Format(L('Brush size [%d]'), [BrushSizeTrackBar.Position]);
NewCursor;
end;
function TBrushToolClass.GetCur: HIcon;
begin
Result := Cur;
end;
procedure TBrushToolClass.ColorClick(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
BrushColorChooserDialog.Color := BrushColorChooser.Brush.Color;
if BrushColorChooserDialog.Execute then
BrushColorChooser.Brush.Color := BrushColorChooserDialog.Color;
end;
procedure TBrushToolClass.DoSaveSettings(Sender: TObject);
begin
AppSettings.WriteInteger('Editor', 'BrushToolStyle', MethodDrawChooser.ItemIndex);
AppSettings.WriteInteger('Editor', 'BrushToolColor', BrushColorChooser.Brush.Color);
AppSettings.WriteInteger('Editor', 'BrushToolSize', BrushSizeTrackBar.Position);
AppSettings.WriteInteger('Editor', 'BrushTransparency', BrusTransparencyTrackBar.Position);
end;
procedure TBrushToolClass.BrushTransparencyChanged(Sender: TObject);
begin
if not Initialized then
Exit;
BrusTransparencyCaption.Caption := Format(L('Transparency [%d]'), [BrusTransparencyTrackBar.Position]);
Editor.Transparency := BrusTransparencyTrackBar.Position / 100;
if Assigned(FProcRecteateImage) then
FProcRecteateImage(Self);
end;
procedure TBrushToolClass.ButtonMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
Screen.Cursor := CrCross;
FButtonPressed := True;
end;
procedure TBrushToolClass.ButtonMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
var
C: TCanvas;
P: TPoint;
begin
if FButtonPressed then
begin
C := TCanvas.Create;
try
GetCursorPos(P);
C.Handle := GetDC(GetWindow(GetDesktopWindow, GW_OWNER));
BrushColorChooser.Brush.Color := C.Pixels[P.X, P.Y];
finally
F(C);
end;
end;
end;
procedure TBrushToolClass.ButtonMouseUp(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
Screen.Cursor := CrDefault;
FButtonPressed := False;
end;
function TBrushToolClass.GetProperties: string;
begin
Result := '';
end;
class function TBrushToolClass.ID: string;
begin
Result := '{542FC0AD-A013-4973-90D4-E6D6E9F65D2C}';
end;
procedure TBrushToolClass.ExecuteProperties(Properties: String;
OnDone: TNotifyEvent);
begin
end;
procedure TBrushToolClass.SetProperties(Properties: String);
begin
end;
end.
|
unit Objekt.BaseList;
interface
uses
SysUtils, Classes, Contnrs;
type
TBaseList = class
private
function GetCount: Integer;
protected
fList: TObjectList;
fId: Integer;
public
constructor Create; virtual;
destructor Destroy; override;
property Count: Integer read GetCount;
procedure Clear; virtual;
end;
implementation
{ Tci_BaseList }
constructor TBaseList.Create;
begin
fList := TObjectList.Create;
fId := 0;
end;
destructor TBaseList.Destroy;
begin
FreeAndNil(fList);
inherited;
end;
procedure TBaseList.Clear;
begin
fList.Clear;
fId := 0;
end;
function TBaseList.GetCount: Integer;
begin
Result := fList.Count;
end;
end.
|
// ************************************************************************
// ***************************** CEF4Delphi *******************************
// ************************************************************************
//
// CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based
// browser in Delphi applications.
//
// The original license of DCEF3 still applies to CEF4Delphi.
//
// For more information about CEF4Delphi visit :
// https://www.briskbard.com/index.php?lang=en&pageid=cef
//
// Copyright © 2017 Salvador Díaz Fau. All rights reserved.
//
// ************************************************************************
// ************ vvvv Original license and comments below vvvv *************
// ************************************************************************
(*
* Delphi Chromium Embedded 3
*
* Usage allowed under the restrictions of the Lesser GNU General Public License
* or alternatively the restrictions of the Mozilla Public License 1.1
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* Unit owner : Henri Gourvest <hgourvest@gmail.com>
* Web site : http://www.progdigy.com
* Repository : http://code.google.com/p/delphichromiumembedded/
* Group : http://groups.google.com/group/delphichromiumembedded
*
* Embarcadero Technologies, Inc is not permitted to use or redistribute
* this source code without explicit permission.
*
*)
unit uCEFv8Value;
{$IFNDEF CPUX64}
{$ALIGN ON}
{$MINENUMSIZE 4}
{$ENDIF}
{$I cef.inc}
interface
uses
{$IFDEF DELPHI16_UP}
System.Classes,
{$ELSE}
Classes,
{$ENDIF}
uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes, uCEFv8Types;
type
TCefv8ValueRef = class(TCefBaseRefCountedRef, ICefv8Value)
protected
function IsValid: Boolean;
function IsUndefined: Boolean;
function IsNull: Boolean;
function IsBool: Boolean;
function IsInt: Boolean;
function IsUInt: Boolean;
function IsDouble: Boolean;
function IsDate: Boolean;
function IsString: Boolean;
function IsObject: Boolean;
function IsArray: Boolean;
function IsFunction: Boolean;
function IsSame(const that: ICefv8Value): Boolean;
function GetBoolValue: Boolean;
function GetIntValue: Integer;
function GetUIntValue: Cardinal;
function GetDoubleValue: Double;
function GetDateValue: TDateTime;
function GetStringValue: ustring;
function IsUserCreated: Boolean;
function HasException: Boolean;
function GetException: ICefV8Exception;
function ClearException: Boolean;
function WillRethrowExceptions: Boolean;
function SetRethrowExceptions(rethrow: Boolean): Boolean;
function HasValueByKey(const key: ustring): Boolean;
function HasValueByIndex(index: Integer): Boolean;
function DeleteValueByKey(const key: ustring): Boolean;
function DeleteValueByIndex(index: Integer): Boolean;
function GetValueByKey(const key: ustring): ICefv8Value;
function GetValueByIndex(index: Integer): ICefv8Value;
function SetValueByKey(const key: ustring; const value: ICefv8Value; attribute: TCefV8PropertyAttributes): Boolean;
function SetValueByIndex(index: Integer; const value: ICefv8Value): Boolean;
function SetValueByAccessor(const key: ustring; settings: TCefV8AccessControls; attribute: TCefV8PropertyAttributes): Boolean;
function GetKeys(const keys: TStrings): Integer;
function SetUserData(const data: ICefv8Value): Boolean;
function GetUserData: ICefv8Value;
function GetExternallyAllocatedMemory: Integer;
function AdjustExternallyAllocatedMemory(changeInBytes: Integer): Integer;
function GetArrayLength: Integer;
function GetFunctionName: ustring;
function GetFunctionHandler: ICefv8Handler;
function ExecuteFunction(const obj: ICefv8Value; const arguments: TCefv8ValueArray): ICefv8Value;
function ExecuteFunctionWithContext(const context: ICefv8Context; const obj: ICefv8Value; const arguments: TCefv8ValueArray): ICefv8Value;
public
class function UnWrap(data: Pointer): ICefv8Value;
class function NewUndefined: ICefv8Value;
class function NewNull: ICefv8Value;
class function NewBool(value: Boolean): ICefv8Value;
class function NewInt(value: Integer): ICefv8Value;
class function NewUInt(value: Cardinal): ICefv8Value;
class function NewDouble(value: Double): ICefv8Value;
class function NewDate(value: TDateTime): ICefv8Value;
class function NewString(const str: ustring): ICefv8Value;
class function NewObject(const Accessor: ICefV8Accessor; const Interceptor: ICefV8Interceptor): ICefv8Value;
class function NewObjectProc(const getter: TCefV8AccessorGetterProc;
const setter: TCefV8AccessorSetterProc;
const getterbyname : TCefV8InterceptorGetterByNameProc;
const setterbyname : TCefV8InterceptorSetterByNameProc;
const getterbyindex : TCefV8InterceptorGetterByIndexProc;
const setterbyindex : TCefV8InterceptorSetterByIndexProc): ICefv8Value;
class function NewArray(len: Integer): ICefv8Value;
class function NewFunction(const name: ustring; const handler: ICefv8Handler): ICefv8Value;
end;
implementation
uses
uCEFMiscFunctions, uCEFLibFunctions, uCEFv8Accessor, uCEFv8Handler, uCEFv8Exception, uCEFv8Interceptor;
function TCefv8ValueRef.AdjustExternallyAllocatedMemory(changeInBytes: Integer): Integer;
begin
Result := PCefV8Value(FData)^.adjust_externally_allocated_memory(PCefV8Value(FData), changeInBytes);
end;
class function TCefv8ValueRef.NewArray(len: Integer): ICefv8Value;
begin
Result := UnWrap(cef_v8value_create_array(len));
end;
class function TCefv8ValueRef.NewBool(value: Boolean): ICefv8Value;
begin
Result := UnWrap(cef_v8value_create_bool(Ord(value)));
end;
class function TCefv8ValueRef.NewDate(value: TDateTime): ICefv8Value;
var
dt: TCefTime;
begin
dt := DateTimeToCefTime(value);
Result := UnWrap(cef_v8value_create_date(@dt));
end;
class function TCefv8ValueRef.NewDouble(value: Double): ICefv8Value;
begin
Result := UnWrap(cef_v8value_create_double(value));
end;
class function TCefv8ValueRef.NewFunction(const name: ustring;
const handler: ICefv8Handler): ICefv8Value;
var
n: TCefString;
begin
n := CefString(name);
Result := UnWrap(cef_v8value_create_function(@n, CefGetData(handler)));
end;
class function TCefv8ValueRef.NewInt(value: Integer): ICefv8Value;
begin
Result := UnWrap(cef_v8value_create_int(value));
end;
class function TCefv8ValueRef.NewUInt(value: Cardinal): ICefv8Value;
begin
Result := UnWrap(cef_v8value_create_uint(value));
end;
class function TCefv8ValueRef.NewNull: ICefv8Value;
begin
Result := UnWrap(cef_v8value_create_null);
end;
class function TCefv8ValueRef.NewObject(const Accessor: ICefV8Accessor; const Interceptor: ICefV8Interceptor): ICefv8Value;
begin
Result := UnWrap(cef_v8value_create_object(CefGetData(Accessor), CefGetData(Interceptor)));
end;
class function TCefv8ValueRef.NewObjectProc(const getter: TCefV8AccessorGetterProc;
const setter: TCefV8AccessorSetterProc;
const getterbyname : TCefV8InterceptorGetterByNameProc;
const setterbyname : TCefV8InterceptorSetterByNameProc;
const getterbyindex : TCefV8InterceptorGetterByIndexProc;
const setterbyindex : TCefV8InterceptorSetterByIndexProc): ICefv8Value;
begin
Result := NewObject(TCefFastV8Accessor.Create(getter, setter) as ICefV8Accessor,
TCefFastV8Interceptor.Create(getterbyname, setterbyname, getterbyindex, setterbyindex) as ICefV8Interceptor);
end;
class function TCefv8ValueRef.NewString(const str: ustring): ICefv8Value;
var
s: TCefString;
begin
s := CefString(str);
Result := UnWrap(cef_v8value_create_string(@s));
end;
class function TCefv8ValueRef.NewUndefined: ICefv8Value;
begin
Result := UnWrap(cef_v8value_create_undefined);
end;
function TCefv8ValueRef.DeleteValueByIndex(index: Integer): Boolean;
begin
Result := PCefV8Value(FData)^.delete_value_byindex(PCefV8Value(FData), index) <> 0;
end;
function TCefv8ValueRef.DeleteValueByKey(const key: ustring): Boolean;
var
k: TCefString;
begin
k := CefString(key);
Result := PCefV8Value(FData)^.delete_value_bykey(PCefV8Value(FData), @k) <> 0;
end;
function TCefv8ValueRef.ExecuteFunction(const obj: ICefv8Value;
const arguments: TCefv8ValueArray): ICefv8Value;
var
args: PPCefV8Value;
i: Integer;
begin
GetMem(args, SizeOf(PCefV8Value) * Length(arguments));
try
for i := 0 to Length(arguments) - 1 do
args[i] := CefGetData(arguments[i]);
Result := TCefv8ValueRef.UnWrap(PCefV8Value(FData)^.execute_function(PCefV8Value(FData),
CefGetData(obj), Length(arguments), args));
finally
FreeMem(args);
end;
end;
function TCefv8ValueRef.ExecuteFunctionWithContext(const context: ICefv8Context;
const obj: ICefv8Value; const arguments: TCefv8ValueArray): ICefv8Value;
var
args: PPCefV8Value;
i: Integer;
begin
GetMem(args, SizeOf(PCefV8Value) * Length(arguments));
try
for i := 0 to Length(arguments) - 1 do
args[i] := CefGetData(arguments[i]);
Result := TCefv8ValueRef.UnWrap(PCefV8Value(FData)^.execute_function_with_context(PCefV8Value(FData),
CefGetData(context), CefGetData(obj), Length(arguments), args));
finally
FreeMem(args);
end;
end;
function TCefv8ValueRef.GetArrayLength: Integer;
begin
Result := PCefV8Value(FData)^.get_array_length(PCefV8Value(FData));
end;
function TCefv8ValueRef.GetBoolValue: Boolean;
begin
Result := PCefV8Value(FData)^.get_bool_value(PCefV8Value(FData)) <> 0;
end;
function TCefv8ValueRef.GetDateValue: TDateTime;
begin
Result := CefTimeToDateTime(PCefV8Value(FData)^.get_date_value(PCefV8Value(FData)));
end;
function TCefv8ValueRef.GetDoubleValue: Double;
begin
Result := PCefV8Value(FData)^.get_double_value(PCefV8Value(FData));
end;
function TCefv8ValueRef.GetExternallyAllocatedMemory: Integer;
begin
Result := PCefV8Value(FData)^.get_externally_allocated_memory(PCefV8Value(FData));
end;
function TCefv8ValueRef.GetFunctionHandler: ICefv8Handler;
begin
Result := TCefv8HandlerRef.UnWrap(PCefV8Value(FData)^.get_function_handler(PCefV8Value(FData)));
end;
function TCefv8ValueRef.GetFunctionName: ustring;
begin
Result := CefStringFreeAndGet(PCefV8Value(FData)^.get_function_name(PCefV8Value(FData)))
end;
function TCefv8ValueRef.GetIntValue: Integer;
begin
Result := PCefV8Value(FData)^.get_int_value(PCefV8Value(FData))
end;
function TCefv8ValueRef.GetUIntValue: Cardinal;
begin
Result := PCefV8Value(FData)^.get_uint_value(PCefV8Value(FData))
end;
function TCefv8ValueRef.GetKeys(const keys: TStrings): Integer;
var
list: TCefStringList;
i: Integer;
str: TCefString;
begin
list := cef_string_list_alloc;
try
Result := PCefV8Value(FData)^.get_keys(PCefV8Value(FData), list);
FillChar(str, SizeOf(str), 0);
for i := 0 to cef_string_list_size(list) - 1 do
begin
FillChar(str, SizeOf(str), 0);
cef_string_list_value(list, i, @str);
keys.Add(CefStringClearAndGet(str));
end;
finally
cef_string_list_free(list);
end;
end;
function TCefv8ValueRef.SetUserData(const data: ICefv8Value): Boolean;
begin
Result := PCefV8Value(FData)^.set_user_data(PCefV8Value(FData), CefGetData(data)) <> 0;
end;
function TCefv8ValueRef.GetStringValue: ustring;
begin
Result := CefStringFreeAndGet(PCefV8Value(FData)^.get_string_value(PCefV8Value(FData)));
end;
function TCefv8ValueRef.IsUserCreated: Boolean;
begin
Result := PCefV8Value(FData)^.is_user_created(PCefV8Value(FData)) <> 0;
end;
function TCefv8ValueRef.IsValid: Boolean;
begin
Result := PCefV8Value(FData)^.is_valid(PCefV8Value(FData)) <> 0;
end;
function TCefv8ValueRef.HasException: Boolean;
begin
Result := PCefV8Value(FData)^.has_exception(PCefV8Value(FData)) <> 0;
end;
function TCefv8ValueRef.GetException: ICefV8Exception;
begin
Result := TCefV8ExceptionRef.UnWrap(PCefV8Value(FData)^.get_exception(PCefV8Value(FData)));
end;
function TCefv8ValueRef.ClearException: Boolean;
begin
Result := PCefV8Value(FData)^.clear_exception(PCefV8Value(FData)) <> 0;
end;
function TCefv8ValueRef.WillRethrowExceptions: Boolean;
begin
Result := PCefV8Value(FData)^.will_rethrow_exceptions(PCefV8Value(FData)) <> 0;
end;
function TCefv8ValueRef.SetRethrowExceptions(rethrow: Boolean): Boolean;
begin
Result := PCefV8Value(FData)^.set_rethrow_exceptions(PCefV8Value(FData), Ord(rethrow)) <> 0;
end;
function TCefv8ValueRef.GetUserData: ICefv8Value;
begin
Result := TCefv8ValueRef.UnWrap(PCefV8Value(FData)^.get_user_data(PCefV8Value(FData)));
end;
function TCefv8ValueRef.GetValueByIndex(index: Integer): ICefv8Value;
begin
Result := TCefv8ValueRef.UnWrap(PCefV8Value(FData)^.get_value_byindex(PCefV8Value(FData), index))
end;
function TCefv8ValueRef.GetValueByKey(const key: ustring): ICefv8Value;
var
k: TCefString;
begin
k := CefString(key);
Result := TCefv8ValueRef.UnWrap(PCefV8Value(FData)^.get_value_bykey(PCefV8Value(FData), @k))
end;
function TCefv8ValueRef.HasValueByIndex(index: Integer): Boolean;
begin
Result := PCefV8Value(FData)^.has_value_byindex(PCefV8Value(FData), index) <> 0;
end;
function TCefv8ValueRef.HasValueByKey(const key: ustring): Boolean;
var
k: TCefString;
begin
k := CefString(key);
Result := PCefV8Value(FData)^.has_value_bykey(PCefV8Value(FData), @k) <> 0;
end;
function TCefv8ValueRef.IsArray: Boolean;
begin
Result := PCefV8Value(FData)^.is_array(PCefV8Value(FData)) <> 0;
end;
function TCefv8ValueRef.IsBool: Boolean;
begin
Result := PCefV8Value(FData)^.is_bool(PCefV8Value(FData)) <> 0;
end;
function TCefv8ValueRef.IsDate: Boolean;
begin
Result := PCefV8Value(FData)^.is_date(PCefV8Value(FData)) <> 0;
end;
function TCefv8ValueRef.IsDouble: Boolean;
begin
Result := PCefV8Value(FData)^.is_double(PCefV8Value(FData)) <> 0;
end;
function TCefv8ValueRef.IsFunction: Boolean;
begin
Result := PCefV8Value(FData)^.is_function(PCefV8Value(FData)) <> 0;
end;
function TCefv8ValueRef.IsInt: Boolean;
begin
Result := PCefV8Value(FData)^.is_int(PCefV8Value(FData)) <> 0;
end;
function TCefv8ValueRef.IsUInt: Boolean;
begin
Result := PCefV8Value(FData)^.is_uint(PCefV8Value(FData)) <> 0;
end;
function TCefv8ValueRef.IsNull: Boolean;
begin
Result := PCefV8Value(FData)^.is_null(PCefV8Value(FData)) <> 0;
end;
function TCefv8ValueRef.IsObject: Boolean;
begin
Result := PCefV8Value(FData)^.is_object(PCefV8Value(FData)) <> 0;
end;
function TCefv8ValueRef.IsSame(const that: ICefv8Value): Boolean;
begin
Result := PCefV8Value(FData)^.is_same(PCefV8Value(FData), CefGetData(that)) <> 0;
end;
function TCefv8ValueRef.IsString: Boolean;
begin
Result := PCefV8Value(FData)^.is_string(PCefV8Value(FData)) <> 0;
end;
function TCefv8ValueRef.IsUndefined: Boolean;
begin
Result := PCefV8Value(FData)^.is_undefined(PCefV8Value(FData)) <> 0;
end;
function TCefv8ValueRef.SetValueByAccessor(const key: ustring;
settings: TCefV8AccessControls; attribute: TCefV8PropertyAttributes): Boolean;
var
k: TCefString;
begin
k := CefString(key);
Result:= PCefV8Value(FData)^.set_value_byaccessor(PCefV8Value(FData), @k,
PByte(@settings)^, PByte(@attribute)^) <> 0;
end;
function TCefv8ValueRef.SetValueByIndex(index: Integer;
const value: ICefv8Value): Boolean;
begin
Result:= PCefV8Value(FData)^.set_value_byindex(PCefV8Value(FData), index, CefGetData(value)) <> 0;
end;
function TCefv8ValueRef.SetValueByKey(const key: ustring;
const value: ICefv8Value; attribute: TCefV8PropertyAttributes): Boolean;
var
k: TCefString;
begin
k := CefString(key);
Result:= PCefV8Value(FData)^.set_value_bykey(PCefV8Value(FData), @k,
CefGetData(value), PByte(@attribute)^) <> 0;
end;
class function TCefv8ValueRef.UnWrap(data: Pointer): ICefv8Value;
begin
if data <> nil then
Result := Create(data) as ICefv8Value else
Result := nil;
end;
end.
|
(*
Category: SWAG Title: DATE & TIME ROUTINES
Original name: 0057.PAS
Description: Natural display of time
Author: DAVID ADAMSON
Date: 11-25-95 09:26
*)
(*
QT displays the time in natural English.
Example: It's twenty past seven.
*)
program QueryTime;
uses Dos;
const
QNear: array[0..4] of string[11] = (
'',' just past',' just after',' nearly',' almost');
{You may wish to change naught to twelve.}
Numbers: array[0..12] of string[6] = ('naught',
'one','two','three','four','five','six','seven','eight','nine',
'ten', 'eleven', 'twelve');
{REXX : String[30] = 'REXX - Mike Colishaw 1979, 85';
PASCAL : String[30] = 'Pascal - Brad Zavitsky 1995';
TWEAKS : String[30] = 'Tweaks - David Adamson 1995';}
var
Hour, Min, Sec, S100: Word;
Out: string[79];
procedure Tell;
begin
Writeln('QT displays the time in natural english.');
end;
begin
Out := '';
if paramcount > 0 then Tell; {Describe the program}
Writeln;
GetTime(Hour, Min, Sec, S100); {Get the time from DOS}
{writeln(hour,':', min,':',sec); Un-comment for testing }
if Sec > 29 then inc(Min); {Where we are in 5 minute bracket}
Out := 'It''s' + QNear[Min mod 5]; {Start building the result}
if Min > 32 then Inc(Hour); {We are TO the hour}
inc(Min, 2); {Shift minutes to straddle a 5-minute point}
{For special case the result for Noon and midnight hours}
if ((hour mod 12) = 0) and ((min mod 60) <= 4) then
begin
if Hour = 12 then Writeln(Out, ' Noon.')
else Writeln(Out, ' Midnight.');
Halt;
end; {We are finished here}
Dec(Min, Min mod 5); {Find the nearest five minutes}
if Hour > 12 then Dec(Hour, 12); {Get rid of 24hour clock}
case Min of
5: Out := Out + ' five past ';
10: Out := Out + ' ten past ';
15: Out := Out + ' a quarter past ';
20: Out := Out + ' twenty past ';
25: Out := Out + ' twenty-five past ';
30: Out := Out + ' half past ';
35: Out := Out + ' twenty-five to ';
40: Out := Out + ' twenty to ';
45: Out := Out + ' a quarter to ';
50: Out := Out + ' ten to ';
55: Out := Out + ' five to ';
else
begin
Out := Out + ' ';
Min := 0;
end;
end; {Case}
Out := Out + Numbers[Hour];
if min = 0 then Out := Out + ' o''clock';
Writeln(Out,'.');
end.
|
Unit ImageLoadRequest;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
Interface
Uses
Windows,
IRPMonDll, IRPMonRequest;
Type
TImageLoadRequest = Class (TDriverRequest)
Private
FImageBase : Pointer;
FImageSize : NativeUInt;
FExtraInfo : Boolean;
FKernelDriver : Boolean;
FMappedToAllPids : Boolean;
FPartialMap : Boolean;
FSigningLevel : EImageSigningLevel;
FSignatureType : EImageSignatureType;
Public
Constructor Create(Var ARequest:REQUEST_IMAGE_LOAD); Overload;
Function GetColumnName(AColumnType:ERequestListModelColumnType):WideString; Override;
Function GetColumnValueRaw(AColumnType:ERequestListModelColumnType; Var AValue:Pointer; Var AValueSize:Cardinal):Boolean; Override;
Function GetColumnValue(AColumnType:ERequestListModelColumnType; Var AResult:WideString):Boolean; Override;
Property ImageBase : Pointer Read FImageBase;
Property ImageSize : NativeUInt Read FImageSize;
Property KernelDriver : Boolean Read FKernelDriver;
Property MappedToAllPids : Boolean Read FMappedToAllPids;
Property ExtraInfo : Boolean Read FExtraInfo;
Property PartialMap : Boolean Read FPartialMap;
Property SigningLevel : EImageSigningLevel Read FSigningLevel;
Property SignatureType : EImageSignatureType Read FSignatureType;
end;
Implementation
Uses
SysUtils;
Constructor TImageLoadRequest.Create(Var ARequest:REQUEST_IMAGE_LOAD);
Var
tmp : WideString;
rawReq : PREQUEST_IMAGE_LOAD;
begin
Inherited Create(ARequest.Header);
rawReq := PREQUEST_IMAGE_LOAD(FRaw);
AssignData(Pointer(PByte(rawReq) + SizeOf(REQUEST_IMAGE_LOAD)), rawReq.DataSize);
SetFileObject(ARequest.FileObject);
FImageBase := ARequest.ImageBase;
FImageSize := ARequest.ImageSize;
FSigningLevel := ARequest.SignatureLevel;
FSignatureType := ARequest.SignatureType;
FKernelDriver := ARequest.KernelDriver;
FMappedToAllPids := ARequest.MappedToAllPids;
FExtraInfo := ARequest.ExtraInfo;
FPartialMap := ARequest.PartialMap;
tmp := '';
SetLength(tmp, FDataSize Div SIzeOf(WideChar));
Move(FData^, PWideChar(tmp)^, FDataSize);
SetFileName(tmp);
end;
Function TImageLoadRequest.GetColumnName(AColumnType:ERequestListModelColumnType):WideString;
begin
Result := '';
case AColumnType of
rlmctArg1: Result := 'Image base';
rlmctArg2: Result := 'Image size';
rlmctArg3: Result := 'Signature type';
rlmctArg4: Result := 'Signature level';
Else Result := Inherited GetColumnName(AColumnType);
end;
end;
Function TImageLoadRequest.GetColumnValueRaw(AColumnType:ERequestListModelColumnType; Var AValue:Pointer; Var AValueSize:Cardinal):Boolean;
begin
Result := True;
Case AColumnType Of
rlmctDeviceObject,
rlmctDeviceName,
rlmctDriverObject,
rlmctIOSBStatusValue,
rlmctIOSBStatusConstant,
rlmctIOSBInformation,
rlmctResultValue,
rlmctResultConstant,
rlmctDriverName : Result := False;
rlmctArg1 : begin
AValue := @FImageBase;
AValueSize := SizeOf(FImageBase);
end;
rlmctArg2 : begin
AValue := @FImageSize;
AValueSize := SizeOf(FImageSize);
end;
rlmctArg3 : begin
AValue := @FSignatureType;
AValueSize := SizeOf(FSignatureType);
end;
rlmctArg4 : begin
AValue := @FSigningLevel;
AValueSize := SizeOf(FSigningLevel);
end;
Else Result := Inherited GetColumnValueRaw(AColumnType, AValue, AValueSize);
end;
end;
Function TImageLoadRequest.GetColumnValue(AColumnType:ERequestListModelColumnType; Var AResult:WideString):Boolean;
begin
Result := True;
Case AColumnType Of
rlmctDeviceObject,
rlmctDeviceName,
rlmctDriverObject,
rlmctIOSBStatusValue,
rlmctIOSBStatusConstant,
rlmctIOSBInformation,
rlmctResultValue,
rlmctResultConstant,
rlmctDriverName : Result := False;
rlmctArg1 : AResult := Format('0x%p', [FImageBase]);
rlmctArg2 : AResult := Format('%u', [FImageSize]);
rlmctArg3 : AResult := ImageSignatureTypeToString(FSignatureType);
rlmctArg4 : AResult := ImageSigningLevelToString(SigningLevel);
Else Result := Inherited GetColumnValue(AColumnType, AResult);
end;
end;
End.
|
unit DgInp;
interface
uses Windows, Forms, Classes, DAQDefs,
pwrdaq32, pdfw_def, pd_hcaps;
type
// base acquisition thread
TDigitalInput = class(TThread)
private
hAdapter: DWORD;
dwError: DWORD;
FFrequency: DWORD;
FOnUpdateView: TUpdateViewProc;
protected
procedure DoTerminate; override;
public
constructor Create(Adapter: DWORD);
procedure Execute; override;
property Frequency: DWORD read FFrequency write FFrequency;
property OnUpdateView: TUpdateViewProc read FOnUpdateView write FOnUpdateView;
end;
implementation
constructor TDigitalInput.Create(Adapter: DWORD);
begin
hAdapter := Adapter;
Frequency := 500;
inherited Create(False);
end;
procedure TDigitalInput.Execute;
var Value: DWORD;
begin
// digital input - init sequence
try
// initialize DInp subsystem
if not PdAdapterAcquireSubsystem(hAdapter, @dwError, DigitalIn, 1)
then raise TPwrDaqException.Create('PdAdapterAcquireSubsystem', dwError);
// thread loop
while not Terminated do try
if not _PdDInRead(hAdapter, @dwError, @Value)
then raise TPwrDaqException.Create('_PdDInRead', dwError);
if Assigned(OnUpdateView)
then OnUpdateView(Value);
try Sleep (10000 div Frequency); except end;
except
raise;
end;
except
Application.HandleException(Self);
end;
end;
procedure TDigitalInput.DoTerminate;
begin
// stop input sequence
try
// release DInp subsystem and close adapter
if not PdAdapterAcquireSubsystem(hAdapter, @dwError, DigitalIn, 0)
then raise TPwrDaqException.Create('PdAdapterAcquireSubsystem', dwError);
except
// Handle any exception
Application.HandleException(Self);
end;
inherited;
end;
end.
|
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.Core.Options.Install;
interface
uses
DPM.Core.Types,
DPM.Core.Logging,
DPM.Core.Options.Search;
type
TInstallOptions = class(TSearchOptions)
private
FPackageFile : string;
FVersionString : string;
FNoCache : boolean;
FProjectPath : string;
FProjects : TArray<string>;
FFloat : boolean;
FIsUpgrade : boolean;
class var
FDefault : TInstallOptions;
protected
function GetPackageId : string;
procedure SetPackageId(const Value : string);
constructor CreateClone(const original : TInstallOptions); reintroduce;
public
class constructor CreateDefault;
class property Default : TInstallOptions read FDefault;
constructor Create; override;
function Validate(const logger : ILogger) : Boolean; override;
function Clone : TInstallOptions; reintroduce;
property IsUpgrade : boolean read FIsUpgrade write FIsUpgrade;
property PackageId : string read GetPackageId write SetPackageId;
property PackageFile : string read FPackageFile write FPackageFile;
property ProjectPath : string read FProjectPath write FProjectPath;
property Projects : TArray<string> read FProjects write FProjects;
property VersionString : string read FVersionString write FVersionString;
end;
implementation
uses
System.SysUtils,
System.RegularExpressions,
DPM.Core.Constants;
{ TInstallOptions }
function TInstallOptions.Clone : TInstallOptions;
begin
result := TInstallOptions.CreateClone(self);
end;
constructor TInstallOptions.Create;
begin
inherited;
FExact := true;
end;
constructor TInstallOptions.CreateClone(const original : TInstallOptions);
begin
inherited CreateClone(original);
FPackageFile := original.FPackageFile;
FVersionString := original.FVersionString;
FNoCache := original.FNoCache;
FProjectPath := original.FProjectPath;
FFloat := original.FFloat;
Force := original.Force;
FIsUpgrade := original.IsUpgrade;
end;
class constructor TInstallOptions.CreateDefault;
begin
FDefault := TInstallOptions.Create;
end;
function TInstallOptions.GetPackageId : string;
begin
result := SearchTerms;
end;
procedure TInstallOptions.SetPackageId(const Value : string);
begin
SearchTerms := value;
end;
function TInstallOptions.Validate(const logger : ILogger) : Boolean;
var
packageString : string;
error : string;
theVersion : TPackageVersion;
begin
//must call inherited
result := inherited Validate(logger);
if ConfigFile = '' then
begin
Logger.Error('No configuration file specified');
exit;
end;
PackageFile := PackageId;
if (PackageId <> '') then
begin
if TRegEx.IsMatch(PackageId, cPackageIdRegex) then
begin
// Logger.Error('The specified package Id [' + PackageId + '] is not a valid Package Id.');
FPackageFile := ''
end
else if not FileExists(FPackageFile) then
begin
Logger.Error('The specified packageFile [' + FPackageFile + '] does not exist.');
result := false;
end
else
begin
packageString := ChangeFileExt(ExtractFileName(FPackageFile), '');
if not TRegEx.IsMatch(packageString, cPackageFileRegex) then
begin
Logger.Error('The specified packageFile name [' + packageString + '] is not in the correct format.');
result := false;
end;
PackageId := '';
end;
end;
if VersionString <> '' then
begin
if not TPackageVersion.TryParseWithError(VersionString, theVersion, error) then
begin
Logger.Error('The specified package Version [' + VersionString + '] is not a valid version - ' + error);
result := false;
end;
Self.Version := theVersion;
end;
if (FProjectPath = '') and (Length(FProjects) = 0) then
begin
Logger.Error('Project path cannot be empty, must either be a directory or project file.');
result := false;
end;
FIsValid := result;
end;
end.
|
unit CallSettings;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Grids,
Client, Simplex.Types;
type
TfrmCallSettings = class(TForm)
gbxCallSettigs: TGroupBox;
btnOK: TButton;
btnCancel: TButton;
sgCallSettings: TStringGrid;
procedure FormCreate(Sender: TObject);
procedure sgCallSettingsSelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
private
FReadOnly: Boolean;
public
{ Public declarations }
end;
function GetCallArguments(AOwner: TComponent; AArguments: SpxArgumentArray;
out AValues: SpxVariantArray): Boolean;
procedure ShowCallArguments(AOwner: TComponent; AArguments: SpxArgumentArray;
AValues: SpxVariantArray);
implementation
{$R *.dfm}
function GetCallArguments(AOwner: TComponent; AArguments: SpxArgumentArray;
out AValues: SpxVariantArray): Boolean;
var frmCallSettings: TfrmCallSettings;
i: Integer;
begin
Result := False;
SetLength(AValues, Length(AArguments));
for i := Low(AValues) to High(AValues) do
begin
AValues[i].ValueRank := AArguments[i].DataType.ValueRank;
AValues[i].BuiltInType := AArguments[i].DataType.BuiltInType;
end;
if (Length(AArguments) = 0) then
begin
Result := True;
Exit;
end;
frmCallSettings := TfrmCallSettings.Create(AOwner);
try
with frmCallSettings do
begin
Caption := 'Call input arguments';
FReadOnly := False;
sgCallSettings.RowCount := Length(AArguments) + 1;
for i := Low(AArguments) to High(AArguments) do
begin
sgCallSettings.Cells[0, i + 1] := AArguments[i].Name;
sgCallSettings.Cells[1, i + 1] := ValueToStr(AValues[i]);
sgCallSettings.Cells[2, i + 1] := TypeToStr(AValues[i]);
sgCallSettings.Cells[3, i + 1] := AArguments[i].Description.Text;
end;
if (ShowModal() <> mrOK) then Exit;
for i := Low(AArguments) to High(AArguments) do
if not StrToValue(AValues[i].BuiltInType,
sgCallSettings.Cells[1, i + 1], AValues[i]) then
begin
ShowMessage('Incorrect argument');
Exit;
end;
end;
Result := True;
finally
FreeAndNil(frmCallSettings);
end;
end;
procedure ShowCallArguments(AOwner: TComponent; AArguments: SpxArgumentArray;
AValues: SpxVariantArray);
var frmCallSettings: TfrmCallSettings;
i: Integer;
begin
frmCallSettings := TfrmCallSettings.Create(AOwner);
try
with frmCallSettings do
begin
Caption := 'Call output arguments';
FReadOnly := True;
sgCallSettings.RowCount := Length(AArguments) + 1;
for i := Low(AArguments) to High(AArguments) do
begin
sgCallSettings.Cells[0, i + 1] := AArguments[i].Name;
sgCallSettings.Cells[1, i + 1] := ValueToStr(AValues[i]);
sgCallSettings.Cells[2, i + 1] := TypeToStr(AValues[i]);
sgCallSettings.Cells[3, i + 1] := AArguments[i].Description.Text;
end;
ShowModal();
end;
finally
FreeAndNil(frmCallSettings);
end;
end;
procedure TfrmCallSettings.FormCreate(Sender: TObject);
begin
sgCallSettings.Cells[0, 0] := 'Name';
sgCallSettings.Cells[1, 0] := 'Value';
sgCallSettings.Cells[2, 0] := 'Type';
sgCallSettings.Cells[3, 0] := 'Description';
FReadOnly := False;
end;
procedure TfrmCallSettings.sgCallSettingsSelectCell(Sender: TObject; ACol,
ARow: Integer; var CanSelect: Boolean);
begin
if (FReadOnly = False) and (ACol = 1) then
sgCallSettings.Options := sgCallSettings.Options + [goEditing]
else sgCallSettings.Options := sgCallSettings.Options - [goEditing];
end;
end.
|
//////////////////////////////////////////////////////////////////////////
// This file is a part of NotLimited.Framework.Wpf NuGet package.
// You are strongly discouraged from fiddling with it.
// If you do, all hell will break loose and living will envy the dead.
//////////////////////////////////////////////////////////////////////////
using System;
using System.Globalization;
using System.Windows.Data;
namespace NotLimited.Framework.Wpf.Converters
{
[ValueConversion(typeof(bool), typeof(bool))]
public class InvertedBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
return !((bool)value);
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException();
}
}
} |
unit HS4bind;
interface
uses
HS4Bind.Interfaces;
type
THS4Bind = class(TInterfacedObject, iHS4Bind)
private
FCredencial : iHS4BindCredential;
public
constructor Create;
destructor Destroy; override;
class function New : iHS4Bind;
function Credential : iHS4BindCredential;
function SendFile : iHS4BindSend;
function GetFile : iHS4BindGet;
end;
implementation
uses
HS4Bind.Send,
HS4Bind.Get,
HS4Bind.Credential;
{ THS4Bind }
constructor THS4Bind.Create;
begin
end;
function THS4Bind.Credential: iHS4BindCredential;
begin
if not Assigned(FCredencial) then
FCredencial := THS4BindCredential.New(Self);
Result := FCredencial;
end;
destructor THS4Bind.Destroy;
begin
inherited;
end;
function THS4Bind.GetFile: iHS4BindGet;
begin
Result:= THS4BindGet.new(Self);
end;
class function THS4Bind.New: iHS4Bind;
begin
Result:= self.Create;
end;
function THS4Bind.SendFile: iHS4BindSend;
begin
Result:= THS4BindSend.new(Self);
end;
end. |
unit aStrings;
{by Jesse, Matt, and Nick}
{----} interface {----}
uses
CRT;
type
StringType = array [0..255] of Char;
procedure StringLength (var AString : StringType;var actualength:byte);
procedure StringWriteLn (var AString : StringType);
procedure StringReadLn (var StringResult : StringType);
PROCEDURE CONCAT (var S1,S2:STRINGTYPE );
procedure copy (astring:stringtype;start,count:integer);
function pos (tofind,s :stringtype):integer;
procedure delete (var s:stringtype; startpos, count:integer);
procedure stringinsert(insertstring:stringtype; var master:stringtype;
pos:integer);
{----} implementation {----}
procedure StringLength (var AString : StringType;var actualength:byte);
begin
actualength := 255;
while ((actualength > 0) and (AString [actualength] = #0)) do
Dec (Actualength);
end;
procedure ClearStringResult(var astring:stringtype);
var
PosT : Integer;
begin
for PosT := 0 to 255 do
begin
astring [PosT] := Chr (0);
end;
end;
procedure StringWriteLn (var AString : StringType);
var
StringResult : StringType;
PosT : Integer;
byteresult:byte;
begin
StringLength (AString,byteresult);
for PosT := 0 to ByteResult do
begin
Write (AString [PosT]);
end;
WriteLn;
end;
procedure StringReadLn (var StringResult : StringType);
var
PosT : Integer;
begin
PosT := 0;
clearstringresult(stringresult);
repeat
StringResult [PosT] := ReadKey;
if (not (StringResult [PosT] = Chr (13))) then
begin
Write (StringResult [PosT]);
Inc (PosT);
end;
until (StringResult [PosT] = Chr (13));
stringresult[post]:= chr(0);
WriteLn;
end;
PROCEDURE CONCAT (var S1,S2:STRINGTYPE);
VAR
LENGTH,NBR:INTEGER;
s2length,byteresult:byte;
BEGIN
nbr:=0;
StringLength (S1,byteresult);
stringlength (s2,s2length);
WHILE (byteresult+1+nbr) <255 DO
begin
S1[ByteResult+1+nbr]:=S2[NBr];
nbr:=nbr+1;
end;
END;
procedure copy (astring:stringtype;start,count:integer);
var
nbr:integer;
begin
for nbr:= 1 to count do
astring[start+nbr]:=astring[start+count+nbr];
end;
{-----------------------------------------------------------------------}
function pos (tofind,s :stringtype):integer;
var
run,nbr,findnbr:integer;
match:Boolean;
byteresult:byte;
AByteResult :Byte;
begin
run:=0;
match:=true;
StringLength (S,byteresult);
AByteResult := ByteResult;
for nbr:=1 to AByteResult do
begin
findnbr:=0;
StringLength (ToFind,byteresult);
while match and (run<ByteResult) do
begin
run:=run+1;
findnbr:=findnbr+1;
if s[nbr+run]=tofind[findnbr] then
match:=true
else match:=false;
end;
end;
if match then pos:=(nbr-run);
end;
{-------------------------------------------------------------------------}
procedure delete (var s:stringtype; startpos, count:integer);
var
byteresult:byte;
nbr,nbr2:integer;
begin
StringLength (S,byteresult);
s[startpos]:=s[startpos+count];
for nbr := 1 to count do
s[startpos+nbr]:=s[startpos+count+nbr];
if ByteResult > startpos+nbr
then for nbr2:= (startpos + count) to ByteResult do
s[nbr2] := s[ByteResult+1]
end;
{--------------------------------------------------------------------------}
{procedure stringwrite(var s:stringtype);
var
count:integer;
begin
for count := 0 to stringlength(s) do
write s[count];
end;
{--------------------------------------------------------------------------}
procedure stringinsert(insertstring:stringtype; var master:stringtype;
pos:integer);
var
count:integer;
byteresult,AByteResult : Byte;
begin
StringLength (InsertString,byteresult);
AByteResult := ByteResult;
StringLength (Master,byteresult);
for count:= 0 to aByteResult do
begin
{ master[ByteResult+1]:=master[pos+count+AByteResult];
master[pos+count+AByteResult]:=master[pos+count];
master[pos+count]:=insertstring[count];}
master[pos+count]:=insertstring[pos+count];
end;
end;
end. |
unit MenuPresenter;
interface
uses
Interfaces;
type
TMenuPresenter = class(TInterfacedObject, IMenuPresenter)
private
FView: IMenuView;
public
constructor Create(AView: IMenuView);
procedure Start;
end;
implementation
{ TMenuPresenter }
constructor TMenuPresenter.Create(AView: IMenuView);
begin
FView := AView;
AView.SetPresenter(Self);
end;
procedure TMenuPresenter.Start;
begin
//
end;
end.
|
unit ScannerTests;
{$mode objfpc}{$H+}
interface
uses
TestFramework, HandlebarsScanner;
type
TTokenInfo = record
Content: String;
Value: THandlebarsToken;
end;
TTokenArray = array of THandlebarsToken;
{ TTokenList }
TTokenList = class
private
FValues: TTokenArray;
FContents: array of String;
function GetItems(Index: Integer): TTokenInfo;
public
procedure Add(Value: THandlebarsToken; const Content: String);
property Values: TTokenArray read FValues;
property Items[Index: Integer]: TTokenInfo read GetItems; default;
end;
{ TScannerTests }
TScannerTests = class(TTestCase)
private
FTokens: TTokenList;
FScanner: THandlebarsScanner;
procedure CheckEquals(expected, actual: THandlebarsToken; const ErrorMsg: string = ''); overload;
procedure CheckEquals(expected, actual: array of THandlebarsToken; const ErrorMsg: string = ''); overload;
procedure CheckEquals(expectedValue: THandlebarsToken; const ExpectedContent: String;
const actual: TTokenInfo; const ErrorMsg: string = ''); overload; overload;
procedure CreateScanner(const Source: String);
procedure CreateTokens(const Source: String);
protected
procedure TearDown; override;
published
procedure EmptyTemplate;
procedure OnlyContent;
procedure MultilineContent;
//adapted from handlebars.js/spec/tokenizer.js
procedure SimpleMustache;
procedure UnescapeWithAmpersand;
procedure UnescapeWithTripleMustache;
procedure EscapeDelimiters;
procedure EscapeMultipleDelimiters;
procedure EscapeTripleStash;
procedure EscapeEscapeCharacter;
procedure EscapeMultipleEscapeCharacters;
procedure EscapeAfterEscapedEscapeCharacther;
procedure EscapeAfterEscapedMustache;
procedure EscapeEscapeCharacterOnTripleStash;
procedure SimplePath;
procedure SimplePathWithDots;
procedure PathLiteralsWithBrackets;
procedure MultiplePathLiteralsWithBrackets;
procedure ScapedLiteralsInBrackets;
procedure SingleDotPath;
procedure ParentPath;
procedure PathWithThis;
procedure SimpleMustacheWithSpaces;
procedure SimpleMustacheWithLineBreaks;
procedure RawContent;
procedure SimplePartial;
procedure PartialWithContext;
procedure PartialWithPath;
procedure PartialBlock;
procedure Comments;
procedure SimpleBlock;
procedure Directives;
procedure Inverse;
procedure InverseWithId;
procedure Params;
procedure StringParam;
procedure StringParamWithSpace;
procedure StringParamWithQuote;
procedure StringParamWithEscaped;
procedure NumberParam;
procedure BooleanParam;
procedure UndefinedAndNullParam;
procedure HashArguments;
procedure AtIdentifier;
procedure InvalidMustache;
procedure SubExpression;
procedure NestedSubExpression;
procedure NestedSubExpressionLiteral;
procedure BlockParam;
end;
implementation
uses
sysutils;
function SameTokens(const Array1, Array2: array of THandlebarsToken): Boolean;
var
ItemCount, i: Integer;
begin
ItemCount := Length(Array1);
Result := ItemCount = Length(Array2);
if Result then
begin
for i := 0 to ItemCount - 1 do
begin
if Array1[i] <> Array2[i] then
begin
Result := False;
Exit;
end;
end;
end;
end;
function TokenArrayToStr(const Tokens: array of THandlebarsToken): String;
var
i: Integer;
TokenStr: String;
begin
Result := '[';
for i := 0 to Length(Tokens) - 1 do
begin
WriteStr(TokenStr, Tokens[i]);
Result := Result + TokenStr;
if i < Length(Tokens) - 1 then
Result := Result + ',';
end;
Result := Result + ']';
end;
{ TTokenList }
function TTokenList.GetItems(Index: Integer): TTokenInfo;
var
Count: Integer;
begin
Count := Length(FValues);
if Index > Count - 1 then
raise Exception.CreateFmt('There''s no token at index %d', [Index]);
Result.Value := FValues[Index];
Result.Content := FContents[Index];
end;
procedure TTokenList.Add(Value: THandlebarsToken; const Content: String);
var
Count: Integer;
begin
Count := Length(FValues);
SetLength(FValues, Count + 1);
SetLength(FContents, Count + 1);
FValues[Count] := Value;
FContents[Count] := Content;
end;
procedure TScannerTests.CheckEquals(expected, actual: THandlebarsToken; const ErrorMsg: string);
var
ExpectedStr, ActualStr: String;
begin
OnCheckCalled;
if expected <> actual then
begin
WriteStr(ExpectedStr, expected);
WriteStr(ActualStr, actual);
FailNotEquals(ExpectedStr, ActualStr, ErrorMsg, CallerAddr);
end;
end;
procedure TScannerTests.CheckEquals(expected, actual: array of THandlebarsToken;
const ErrorMsg: string);
var
ExpectedStr, ActualStr: String;
begin
OnCheckCalled;
if not SameTokens(expected, actual) then
begin
ActualStr := TokenArrayToStr(actual);
ExpectedStr := TokenArrayToStr(expected);
FailNotEquals(ExpectedStr, ActualStr, ErrorMsg, CallerAddr);
end;
end;
procedure TScannerTests.CheckEquals(expectedValue: THandlebarsToken; const ExpectedContent: String;
const actual: TTokenInfo; const ErrorMsg: string);
var
ActualStr, ExpectedStr: String;
begin
OnCheckCalled;
if expectedValue <> actual.Value then
begin
WriteStr(ExpectedStr, expectedValue);
WriteStr(ActualStr, actual.Value);
FailNotEquals(ExpectedStr, ActualStr, ErrorMsg, CallerAddr);
end else if ExpectedContent <> actual.Content then
begin
FailNotEquals(ExpectedContent, actual.Content, ErrorMsg, CallerAddr);
end;
end;
procedure TScannerTests.CreateScanner(const Source: String);
begin
FScanner.Free;
FScanner := THandlebarsScanner.Create(Source);
end;
procedure TScannerTests.CreateTokens(const Source: String);
var
Scanner: THandlebarsScanner;
Value: THandlebarsToken;
Content: String;
begin
FTokens.Free;
FTokens := TTokenList.Create;
Scanner := THandlebarsScanner.Create(Source);
try
Value := Scanner.FetchToken;
while not (Value in [tkEOF, tkInvalid]) do
begin
Content := Scanner.CurTokenString;
FTokens.Add(Value, Content);
Value := Scanner.FetchToken;
end;
finally
Scanner.Destroy;
end;
end;
procedure TScannerTests.TearDown;
begin
FreeAndNil(FTokens);
FreeAndNil(FScanner);
inherited TearDown;
end;
procedure TScannerTests.EmptyTemplate;
begin
CreateScanner('');
CheckEquals(tkEOF, FScanner.FetchToken);
CheckEquals(tkEOF, FScanner.CurToken);
CheckEquals('', FScanner.CurTokenString);
//again
CheckEquals(tkEOF, FScanner.FetchToken);
CheckEquals(tkEOF, FScanner.CurToken);
CheckEquals('', FScanner.CurTokenString);
end;
procedure TScannerTests.OnlyContent;
begin
CreateTokens('xx');
CheckEquals([tkContent], FTokens.Values);
CheckEquals(tkContent, 'xx', FTokens[0]);
CreateTokens(' yy ');
CheckEquals([tkContent], FTokens.Values);
CheckEquals(tkContent, ' yy ', FTokens[0]);
end;
procedure TScannerTests.MultilineContent;
begin
CreateTokens(' foo ' + LineEnding + ' bar ');
CheckEquals([tkContent], FTokens.Values);
CheckEquals(tkContent, ' foo ' + LineEnding + ' bar ', FTokens[0]);
CreateTokens(' foo ' + LineEnding);
CheckEquals([tkContent], FTokens.Values);
CheckEquals(tkContent, ' foo ' + LineEnding, FTokens[0]);
CreateTokens(LineEnding + ' foo ');
CheckEquals([tkContent], FTokens.Values);
CheckEquals(tkContent, LineEnding + ' foo ', FTokens[0]);
end;
procedure TScannerTests.SimpleMustache;
begin
CreateTokens('{{foo}}');
CheckEquals([tkOPEN, tkID, tkCLOSE], FTokens.Values);
CheckEquals(tkOpen, '{{', FTokens[0]);
CheckEquals(tkID, 'foo', FTokens[1]);
CheckEquals(tkClose, '}}', FTokens[2]);
end;
procedure TScannerTests.UnescapeWithAmpersand;
begin
CreateTokens('{{&bar}}');
CheckEquals([tkOPEN, tkID, tkCLOSE], FTokens.Values);
CheckEquals(tkOPEN, '{{&', FTokens[0]);
CheckEquals(tkID, 'bar', FTokens[1]);
end;
procedure TScannerTests.UnescapeWithTripleMustache;
begin
CreateTokens('{{{bar}}}');
CheckEquals([tkOPENUNESCAPED, tkID, tkCLOSEUNESCAPED], FTokens.Values);
CheckEquals(tkID, 'bar', FTokens[1]);
end;
procedure TScannerTests.EscapeDelimiters;
begin
//todo: review how scaped delimiters are tokenized.
//handlebars.js creates a new content token probably due to how the tokenizer works
//we don't have this limitation an the code could be simplified. for now keep as is
CreateTokens('{{foo}} \{{bar}} {{baz}}');
CheckEquals([tkOPEN, tkID, tkCLOSE, tkCONTENT, tkCONTENT, tkOPEN, tkID, tkCLOSE], FTokens.Values);
CheckEquals(tkCONTENT, ' ', FTokens[3]);
CheckEquals(tkCONTENT, '{{bar}} ', FTokens[4]);
end;
procedure TScannerTests.EscapeMultipleDelimiters;
begin
CreateTokens('{{foo}} \{{bar}} \{{baz}}');
CheckEquals([tkOPEN, tkID, tkCLOSE, tkCONTENT, tkCONTENT, tkCONTENT], FTokens.Values);
CheckEquals(tkCONTENT, ' ', FTokens[3]);
CheckEquals(tkCONTENT, '{{bar}} ', FTokens[4]);
CheckEquals(tkCONTENT, '{{baz}}', FTokens[5]);
end;
procedure TScannerTests.EscapeTripleStash;
begin
CreateTokens('{{foo}} \{{{bar}}} {{baz}}');
CheckEquals([tkOPEN, tkID, tkCLOSE, tkCONTENT, tkCONTENT, tkOPEN, tkID, tkCLOSE], FTokens.Values);
CheckEquals(tkCONTENT, '{{{bar}}} ', FTokens[4]);
end;
procedure TScannerTests.EscapeEscapeCharacter;
begin
CreateTokens('{{foo}} \\{{bar}} {{baz}}');
CheckEquals([tkOPEN, tkID, tkCLOSE, tkCONTENT, tkOPEN, tkID, tkCLOSE, tkCONTENT, tkOPEN, tkID, tkCLOSE], FTokens.Values);
CheckEquals(tkCONTENT, ' \', FTokens[3]);
CheckEquals(tkID, 'bar', FTokens[5]);;
end;
procedure TScannerTests.EscapeMultipleEscapeCharacters;
begin
CreateTokens('{{foo}} \\{{bar}} \\{{baz}}');
CheckEquals([tkOPEN, tkID, tkCLOSE, tkCONTENT, tkOPEN, tkID, tkCLOSE, tkCONTENT, tkOPEN, tkID, tkCLOSE], FTokens.Values);
CheckEquals(tkCONTENT, ' \', FTokens[3]);
CheckEquals(tkID, 'bar', FTokens[5]);
CheckEquals(tkCONTENT, ' \', FTokens[7]);
CheckEquals(tkID, 'baz', FTokens[9]);
end;
procedure TScannerTests.EscapeAfterEscapedEscapeCharacther;
begin
CreateTokens('{{foo}} \\{{bar}} \{{baz}}');
//handlebars.js tokenizer adds an empty content. Probably odds of jison
CheckEquals([tkOPEN, tkID, tkCLOSE, tkCONTENT, tkOPEN, tkID, tkCLOSE, tkCONTENT, tkCONTENT{, tkCONTENT}], FTokens.Values);
CheckEquals(tkCONTENT, ' \', FTokens[3]);
CheckEquals(tkOPEN, '{{', FTokens[4]);
CheckEquals(tkID, 'bar', FTokens[5]);
CheckEquals(tkCONTENT, ' ', FTokens[7]);
CheckEquals(tkCONTENT, '{{baz}}', FTokens[8]);
end;
procedure TScannerTests.EscapeAfterEscapedMustache;
begin
CreateTokens('{{foo}} \{{bar}} \\{{baz}}');
//another oddity of handlebars.js tokenizer (jison)
//sometimes the escaped is tokenized alone, sometimes with the previous content
CheckEquals([tkOPEN, tkID, tkCLOSE, tkCONTENT, tkCONTENT, {tkCONTENT,} tkOPEN, tkID, tkCLOSE], FTokens.Values);
CheckEquals(tkCONTENT, ' ', FTokens[3]);
//original tests
//CheckEquals(tkCONTENT, '{{bar}} ', FTokens[4]);
//CheckEquals(tkCONTENT, '\', FTokens[5]);
//CheckEquals(tkOPEN, '{{', FTokens[6]);
//CheckEquals(tkID, 'baz', FTokens[7]);
CheckEquals(tkCONTENT, '{{bar}} \', FTokens[4]);
CheckEquals(tkOPEN, '{{', FTokens[5]);
CheckEquals(tkID, 'baz', FTokens[6]);
end;
procedure TScannerTests.EscapeEscapeCharacterOnTripleStash;
begin
CreateTokens('{{foo}} \\{{{bar}}} {{baz}}');
CheckEquals([tkOPEN, tkID, tkCLOSE, tkCONTENT, tkOPENUNESCAPED, tkID, tkCLOSEUNESCAPED, tkCONTENT, tkOPEN, tkID, tkCLOSE], FTokens.Values);
CheckEquals(tkCONTENT, ' \', FTokens[3]);
CheckEquals(tkID, 'bar', FTokens[5]);
end;
procedure TScannerTests.SimplePath;
begin
CreateTokens('{{foo/bar}}');
CheckEquals([tkOPEN, tkID, tkSEP, tkID, tkCLOSE], FTokens.Values);
CheckEquals(tkId, 'foo', FTokens[1]);
CheckEquals(tkSep, '/', FTokens[2]);
CheckEquals(tkId, 'bar', FTokens[3]);
end;
procedure TScannerTests.SimplePathWithDots;
begin
CreateTokens('{{foo.bar}}');
CheckEquals([tkOPEN, tkID, tkSEP, tkID, tkCLOSE], FTokens.Values);
CreateTokens('{{foo.bar.baz}}');
CheckEquals([tkOPEN, tkID, tkSEP, tkID, tkSEP, tkID, tkCLOSE], FTokens.Values);
end;
procedure TScannerTests.PathLiteralsWithBrackets;
begin
CreateTokens('{{foo.[bar]}}');
CheckEquals([tkOPEN, tkID, tkSEP, tkID, tkCLOSE], FTokens.Values);
CheckEquals(tkId, 'foo', FTokens[1]);
CheckEquals(tkSep, '.', FTokens[2]);
CheckEquals(tkId, '[bar]', FTokens[3]);
end;
procedure TScannerTests.MultiplePathLiteralsWithBrackets;
begin
CreateTokens('{{foo.[bar]}}{{foo.[baz]}}');
CheckEquals([tkOPEN, tkID, tkSEP, tkID, tkCLOSE, tkOPEN, tkID, tkSEP, tkID, tkCLOSE], FTokens.Values);
end;
procedure TScannerTests.ScapedLiteralsInBrackets;
begin
//todo: double check how is supposed to work
CreateTokens('{{foo.[bar\]]}}');
CheckEquals([tkOPEN, tkID, tkSEP, tkID, tkCLOSE], FTokens.Values);
CheckEquals(tkId, '[bar]]', FTokens[3]);
end;
procedure TScannerTests.SingleDotPath;
begin
CreateTokens('{{.}}');
CheckEquals([tkOPEN, tkID, tkCLOSE], FTokens.Values);
CheckEquals(tkId, '.', FTokens[1]);
CreateTokens('{{ . }}');
CheckEquals([tkOPEN, tkID, tkCLOSE], FTokens.Values);
CheckEquals(tkId, '.', FTokens[1]);
end;
procedure TScannerTests.ParentPath;
begin
CreateTokens('{{../foo/bar}}');
CheckEquals([tkOPEN, tkID, tkSEP, tkID, tkSEP, tkID, tkCLOSE], FTokens.Values);
CheckEquals(tkID, '..', FTokens[1]);
CreateTokens('{{../foo.bar}}');
CheckEquals([tkOPEN, tkID, tkSEP, tkID, tkSEP, tkID, tkCLOSE], FTokens.Values);
CheckEquals(tkID, '..', FTokens[1]);
end;
procedure TScannerTests.PathWithThis;
begin
CreateTokens('{{this/foo}}');
CheckEquals([tkOPEN, tkID, tkSEP, tkID, tkCLOSE], FTokens.Values);
CheckEquals(tkID, 'this', FTokens[1]);
CheckEquals(tkID, 'foo', FTokens[3]);
end;
procedure TScannerTests.SimpleMustacheWithSpaces;
begin
CreateTokens('{{ foo }}');
CheckEquals([tkOPEN, tkID, tkCLOSE], FTokens.Values);
CheckEquals(tkOpen, '{{', FTokens[0]);
CheckEquals(tkID, 'foo', FTokens[1]);
CheckEquals(tkClose, '}}', FTokens[2]);
end;
procedure TScannerTests.SimpleMustacheWithLineBreaks;
begin
CreateTokens('{{ foo ' + LineEnding + ' bar }}');
CheckEquals([tkOPEN, tkID, tkID, tkCLOSE], FTokens.Values);
CheckEquals(tkID, 'foo', FTokens[1]);
CreateTokens('{{ foo ' + LineEnding + LineEnding + ' bar }}');
CheckEquals([tkOPEN, tkID, tkID, tkCLOSE], FTokens.Values);
CheckEquals(tkID, 'foo', FTokens[1]);
end;
procedure TScannerTests.RawContent;
begin
CreateTokens('foo {{ bar }} baz');
CheckEquals([tkCONTENT, tkOPEN, tkID, tkCLOSE, tkCONTENT], FTokens.Values);
CheckEquals(tkCONTENT, 'foo ', FTokens[0]);
CheckEquals(tkCONTENT, ' baz', FTokens[4]);
end;
procedure TScannerTests.SimplePartial;
begin
CreateTokens('{{> foo}}');
CheckEquals([tkOPENPARTIAL, tkID, tkCLOSE], FTokens.Values);
CheckEquals(tkOpenPartial, '{{>', FTokens[0]);
CreateTokens('{{>foo}}');
CheckEquals([tkOPENPARTIAL, tkID, tkCLOSE], FTokens.Values);
CreateTokens('{{>foo }}');
CheckEquals([tkOPENPARTIAL, tkID, tkCLOSE], FTokens.Values);
end;
procedure TScannerTests.PartialWithContext;
begin
CreateTokens('{{> foo bar }}');
CheckEquals([tkOPENPARTIAL, tkID, tkID, tkCLOSE], FTokens.Values);
end;
procedure TScannerTests.PartialWithPath;
begin
CreateTokens('{{>foo/bar.baz }}');
CheckEquals([tkOPENPARTIAL, tkID, tkSEP, tkID, tkSEP, tkID, tkCLOSE], FTokens.Values);
end;
procedure TScannerTests.PartialBlock;
begin
CreateTokens('{{#> foo}}');
CheckEquals([tkOPENPARTIALBLOCK, tkID, tkCLOSE], FTokens.Values);
end;
procedure TScannerTests.Comments;
begin
CreateTokens('foo {{! this is a comment }} bar {{ baz }}');
CheckEquals([tkCONTENT, tkCOMMENT, tkCONTENT, tkOPEN, tkID, tkCLOSE], FTokens.Values);
CheckEquals(tkCOMMENT, '{{! this is a comment }}', FTokens[1]);
CreateTokens('foo {{!-- this is a {{comment}} --}} bar {{ baz }}');
CheckEquals([tkCONTENT, tkCOMMENT, tkCONTENT, tkOPEN, tkID, tkCLOSE], FTokens.Values);
CheckEquals(tkCOMMENT, '{{!-- this is a {{comment}} --}}', FTokens[1]);
CreateTokens('foo {{!-- this is a'+LineEnding+'{{comment}}'+LineEnding+'--}} bar {{ baz }}');
CheckEquals([tkCONTENT, tkCOMMENT, tkCONTENT, tkOPEN, tkID, tkCLOSE], FTokens.Values);
CheckEquals(tkCOMMENT, '{{!-- this is a'+LineEnding+'{{comment}}'+LineEnding+'--}}', FTokens[1]);
CreateTokens('{{! this is {{a}} content }}');
CheckEquals([tkComment, tkCONTENT], FTokens.Values);
CheckEquals(tkComment, '{{! this is {{a}}', FTokens[0]);
CheckEquals(tkContent, ' content }}', FTokens[1]);
CreateTokens('Begin.'+ LineEnding +' {{! Indented Comment Block! }}'+ LineEnding +'End.'+ LineEnding);
CheckEquals([tkContent, tkComment, tkContent], FTokens.Values);
CheckEquals(tkContent, 'Begin.'+ LineEnding + ' ', FTokens[0]);
CheckEquals(tkComment, '{{! Indented Comment Block! }}', FTokens[1]);
CheckEquals(tkContent, LineEnding +'End.'+ LineEnding, FTokens[2]);
end;
procedure TScannerTests.SimpleBlock;
begin
CreateTokens('{{#foo}}content{{/foo}}');
CheckEquals([tkOPENBLOCK, tkID, tkCLOSE, tkCONTENT, tkOPENENDBLOCK, tkID, tkCLOSE], FTokens.Values);
end;
procedure TScannerTests.Directives;
begin
CreateTokens('{{#*foo}}content{{/foo}}');
CheckEquals([tkOPENBLOCK, tkID, tkCLOSE, tkCONTENT, tkOPENENDBLOCK, tkID, tkCLOSE], FTokens.Values);
CheckEquals(tkOpenBlock, '{{#*', FTokens[0]);
CheckEquals(tkId, 'foo', FTokens[1]);
CreateTokens('{{*foo}}');
CheckEquals([tkOPEN, tkID, tkCLOSE], FTokens.Values);
CheckEquals(tkOpen, '{{*', FTokens[0]);
CheckEquals(tkId, 'foo', FTokens[1]);
end;
procedure TScannerTests.Inverse;
begin
CreateTokens('{{^}}');
CheckEquals([tkINVERSE], FTokens.Values);
CreateTokens('{{else}}');
CheckEquals([tkINVERSE], FTokens.Values);
CreateTokens('{{ else }}');
CheckEquals([tkINVERSE], FTokens.Values);
end;
procedure TScannerTests.InverseWithId;
begin
CreateTokens('{{^foo}}');
CheckEquals([tkOPENINVERSE, tkID, tkCLOSE], FTokens.Values);
CheckEquals(tkOpenInverse, '{{^', FTokens[0]);
CheckEquals(tkID, 'foo', FTokens[1]);
CreateTokens('{{^ foo }}');
CheckEquals([tkOPENINVERSE, tkID, tkCLOSE], FTokens.Values);
CheckEquals(tkID, 'foo', FTokens[1]);
end;
procedure TScannerTests.Params;
begin
CreateTokens('{{ foo bar baz }}');
CheckEquals([tkOPEN, tkID, tkID, tkID, tkCLOSE], FTokens.Values);
CheckEquals(tkID, 'foo', FTokens[1]);
CheckEquals(tkID, 'bar', FTokens[2]);
CheckEquals(tkID, 'baz', FTokens[3]);
end;
procedure TScannerTests.StringParam;
begin
CreateTokens('{{ foo bar "baz" }}');
CheckEquals([tkOPEN, tkID, tkID, tkSTRING, tkCLOSE], FTokens.Values);
CheckEquals(tkSTRING, 'baz', FTokens[3]);
CreateTokens('{{ foo bar ''baz'' }}');
CheckEquals([tkOPEN, tkID, tkID, tkSTRING, tkCLOSE], FTokens.Values);
CheckEquals(tkSTRING, 'baz', FTokens[3]);
end;
procedure TScannerTests.StringParamWithSpace;
begin
CreateTokens('{{ foo bar "baz bat" }}');
CheckEquals([tkOPEN, tkID, tkID, tkSTRING, tkCLOSE], FTokens.Values);
CheckEquals(tkSTRING, 'baz bat', FTokens[3]);
end;
procedure TScannerTests.StringParamWithQuote;
begin
//todo: double check how is supposed to work
CreateTokens('{{ foo "bar\"baz" }}');
CheckEquals([tkOPEN, tkID, tkSTRING, tkCLOSE], FTokens.Values);
CheckEquals(tkSTRING, 'bar"baz', FTokens[2]);
CreateTokens('{{ foo ''bar\''baz'' }}');
CheckEquals([tkOPEN, tkID, tkSTRING, tkCLOSE], FTokens.Values);
CheckEquals(tkSTRING, 'bar''baz', FTokens[2]);
end;
procedure TScannerTests.StringParamWithEscaped;
begin
//todo
end;
procedure TScannerTests.NumberParam;
begin
CreateTokens('{{ foo 1 }}');
CheckEquals([tkOPEN, tkID, tkNUMBER, tkCLOSE], FTokens.Values);
CheckEquals(tkNUMBER, '1', FTokens[2]);
CreateTokens('{{ foo 1.1 }}');
CheckEquals([tkOPEN, tkID, tkNUMBER, tkCLOSE], FTokens.Values);
CheckEquals(tkNUMBER, '1.1', FTokens[2]);
CreateTokens('{{ foo -1 }}');
CheckEquals([tkOPEN, tkID, tkNUMBER, tkCLOSE], FTokens.Values);
CheckEquals(tkNUMBER, '-1', FTokens[2]);
CreateTokens('{{ foo -1.1 }}');
CheckEquals([tkOPEN, tkID, tkNUMBER, tkCLOSE], FTokens.Values);
CheckEquals(tkNUMBER, '-1.1', FTokens[2]);
end;
procedure TScannerTests.BooleanParam;
begin
CreateTokens('{{ foo true }}');
CheckEquals([tkOPEN, tkID, tkBOOLEAN, tkCLOSE], FTokens.Values);
CheckEquals(tkBOOLEAN, 'true', FTokens[2]);
CreateTokens('{{ foo false }}');
CheckEquals([tkOPEN, tkID, tkBOOLEAN, tkCLOSE], FTokens.Values);
CheckEquals(tkBOOLEAN, 'false', FTokens[2]);
end;
procedure TScannerTests.UndefinedAndNullParam;
begin
CreateTokens('{{ foo undefined null }}');
CheckEquals([tkOPEN, tkID, tkUNDEFINED, tkNULL, tkCLOSE], FTokens.Values);
CheckEquals(tkUNDEFINED, 'undefined', FTokens[2]);
CheckEquals(tkNULL, 'null', FTokens[3]);
end;
procedure TScannerTests.HashArguments;
begin
CreateTokens('{{ foo bar=baz }}');
CheckEquals([tkOPEN, tkID, tkID, tkEQUALS, tkID, tkCLOSE], FTokens.Values);
CreateTokens('{{ foo bar baz=bat }}');
CheckEquals([tkOPEN, tkID, tkID, tkID, tkEQUALS, tkID, tkCLOSE], FTokens.Values);
CreateTokens('{{ foo bar baz=1 }}');
CheckEquals([tkOPEN, tkID, tkID, tkID, tkEQUALS, tkNUMBER, tkCLOSE], FTokens.Values);
CreateTokens('{{ foo bar baz=true }}');
CheckEquals([tkOPEN, tkID, tkID, tkID, tkEQUALS, tkBOOLEAN, tkCLOSE], FTokens.Values);
CreateTokens('{{ foo bar baz=false }}');
CheckEquals([tkOPEN, tkID, tkID, tkID, tkEQUALS, tkBOOLEAN, tkCLOSE], FTokens.Values);
CreateTokens('{{ foo bar'+LineEnding+' baz=bat }}');
CheckEquals([tkOPEN, tkID, tkID, tkID, tkEQUALS, tkID, tkCLOSE], FTokens.Values);
CreateTokens('{{ foo bar baz="bat" }}');
CheckEquals([tkOPEN, tkID, tkID, tkID, tkEQUALS, tkSTRING, tkCLOSE], FTokens.Values);
CreateTokens('{{ foo bar baz="bat" bam=wot }}');
CheckEquals([tkOPEN, tkID, tkID, tkID, tkEQUALS, tkSTRING, tkID, tkEQUALS, tkID, tkCLOSE], FTokens.Values);
CreateTokens('{{foo omg bar=baz bat="bam"}}');
CheckEquals([tkOPEN, tkID, tkID, tkID, tkEQUALS, tkID, tkID, tkEQUALS, tkSTRING, tkCLOSE], FTokens.Values);
CheckEquals(tkID, 'omg', FTokens[2]);
end;
procedure TScannerTests.AtIdentifier;
begin
CreateTokens('{{ @foo }}');
CheckEquals([tkOPEN, tkDATA, tkID, tkCLOSE], FTokens.Values);
CheckEquals(tkID, 'foo', FTokens[2]);
CreateTokens('{{ foo @bar }}');
CheckEquals([tkOPEN, tkID, tkDATA, tkID, tkCLOSE], FTokens.Values);
CheckEquals(tkID, 'bar', FTokens[3]);
CreateTokens('{{ foo bar=@baz }}');
CheckEquals([tkOPEN, tkID, tkID, tkEQUALS, tkDATA, tkID, tkCLOSE], FTokens.Values);
CheckEquals(tkID, 'baz', FTokens[5]);
end;
procedure TScannerTests.InvalidMustache;
begin
CreateTokens('{{foo}');
CheckEquals([tkOPEN, tkID], FTokens.Values);
CreateTokens('{{foo & }}');
CheckEquals([tkOPEN, tkID], FTokens.Values);
end;
procedure TScannerTests.SubExpression;
begin
CreateTokens('{{foo (bar)}}');
CheckEquals([tkOPEN, tkID, tkOPENSEXPR, tkID, tkCLOSESEXPR, tkCLOSE], FTokens.Values);
CheckEquals(tkID, 'foo', FTokens[1]);
CheckEquals(tkID, 'bar', FTokens[3]);
CreateTokens('{{foo (a-x b-y)}}');
CheckEquals([tkOPEN, tkID, tkOPENSEXPR, tkID, tkID, tkCLOSESEXPR, tkCLOSE], FTokens.Values);
CheckEquals(tkID, 'foo', FTokens[1]);
CheckEquals(tkID, 'a-x', FTokens[3]);
CheckEquals(tkID, 'b-y', FTokens[4]);
end;
procedure TScannerTests.NestedSubExpression;
begin
CreateTokens('{{foo (bar (lol rofl)) (baz)}}');
CheckEquals([tkOPEN, tkID, tkOPENSEXPR, tkID, tkOPENSEXPR, tkID, tkID, tkCLOSESEXPR, tkCLOSESEXPR, tkOPENSEXPR, tkID, tkCLOSESEXPR, tkCLOSE], FTokens.Values);
CheckEquals(tkID, 'bar', FTokens[3]);
CheckEquals(tkID, 'lol', FTokens[5]);
CheckEquals(tkID, 'rofl', FTokens[6]);
CheckEquals(tkID, 'baz', FTokens[10]);
end;
procedure TScannerTests.NestedSubExpressionLiteral;
begin
CreateTokens('{{foo (bar (lol true) false) (baz 1) (blah ''b'') (blorg "c")}}');
CheckEquals([tkOPEN, tkID, tkOPENSEXPR, tkID, tkOPENSEXPR, tkID, tkBOOLEAN, tkCLOSESEXPR, tkBOOLEAN, tkCLOSESEXPR, tkOPENSEXPR, tkID, tkNUMBER, tkCLOSESEXPR, tkOPENSEXPR, tkID, tkSTRING, tkCLOSESEXPR, tkOPENSEXPR, tkID, tkSTRING, tkCLOSESEXPR, tkCLOSE], FTokens.Values);
end;
procedure TScannerTests.BlockParam;
begin
CreateTokens('{{#foo as |bar|}}');
CheckEquals([tkOPENBLOCK, tkID, tkOPENBLOCKPARAMS, tkID, tkCLOSEBLOCKPARAMS, tkCLOSE], FTokens.Values);
CreateTokens('{{#foo as |bar baz|}}');
CheckEquals([tkOPENBLOCK, tkID, tkOPENBLOCKPARAMS, tkID, tkID, tkCLOSEBLOCKPARAMS, tkCLOSE], FTokens.Values);
CreateTokens('{{#foo as | bar baz |}}');
CheckEquals([tkOPENBLOCK, tkID, tkOPENBLOCKPARAMS, tkID, tkID, tkCLOSEBLOCKPARAMS, tkCLOSE], FTokens.Values);
CreateTokens('{{#foo as as | bar baz |}}');
CheckEquals([tkOPENBLOCK, tkID, tkID, tkOPENBLOCKPARAMS, tkID, tkID, tkCLOSEBLOCKPARAMS, tkCLOSE], FTokens.Values);
CreateTokens('{{else foo as |bar baz|}}');
CheckEquals([tkOPENINVERSECHAIN, tkID, tkOPENBLOCKPARAMS, tkID, tkID, tkCLOSEBLOCKPARAMS, tkCLOSE], FTokens.Values);
end;
initialization
RegisterTest('Scanner', TScannerTests.Suite);
end.
|
unit ThreadRepeaterPool;
interface
uses
Classes, SysUtils, ThreadRepeater;
type
TThreadRepeaterPool = class (TComponent)
private
FList : TList;
procedure create_Pool;
procedure release_Pool;
procedure on_Repeat(Sender:TObject);
private
FTimeOut: integer;
FSize: integer;
FOnRepeat: TNotifyEvent;
procedure SetTimeOut(const Value: integer);
public
constructor Create(AOwner: TComponent; ASize:integer); reintroduce; virtual;
destructor Destroy; override;
procedure Start;
procedure Stop;
published
property Size : integer read FSize;
property TimeOut : integer read FTimeOut write SetTimeOut;
property OnRepeat : TNotifyEvent read FOnRepeat write FOnRepeat;
end;
implementation
{ TThreadRepeaterPool }
constructor TThreadRepeaterPool.Create(AOwner: TComponent; ASize:integer);
begin
inherited Create(AOwner);
FSize := ASize;
FList := TList.Create;
create_Pool;
end;
procedure TThreadRepeaterPool.create_Pool;
var
Loop: Integer;
begin
for Loop := 1 to FSize do FList.Add(TThreadRepeater.Create(Self));
end;
destructor TThreadRepeaterPool.Destroy;
begin
Stop;
release_Pool;
FreeAndNil(FList);
inherited;
end;
procedure TThreadRepeaterPool.on_Repeat(Sender: TObject);
begin
if Assigned(FOnRepeat) then FOnRepeat(Self);
end;
procedure TThreadRepeaterPool.release_Pool;
var
Loop: Integer;
Repeater : TThreadRepeater;
begin
for Loop := 0 to FList.Count-1 do begin
Repeater := Pointer(FList[Loop]);
Repeater.Free;
end;
FList.Clear;
end;
procedure TThreadRepeaterPool.SetTimeOut(const Value: integer);
var
Loop: Integer;
Repeater : TThreadRepeater;
begin
FTimeOut := Value;
for Loop := 0 to FList.Count-1 do begin
Repeater := Pointer(FList[Loop]);
Repeater.TimeOut := Value;
end;
end;
procedure TThreadRepeaterPool.Start;
var
Loop: Integer;
Repeater : TThreadRepeater;
begin
for Loop := 0 to FList.Count-1 do begin
Repeater := Pointer(FList[Loop]);
Repeater.Execute(on_Repeat);
end;
end;
procedure TThreadRepeaterPool.Stop;
var
Loop: Integer;
Repeater : TThreadRepeater;
begin
for Loop := 0 to FList.Count-1 do begin
Repeater := Pointer(FList[Loop]);
Repeater.Stop;
end;
end;
end.
|
{
GLDynamicTexture Demo.
Use F2 and F3 to toggle between PBO and non-PBO updates,
if your card supports it.
Use F4 to toggle partial updates.
Version history:
16/10/07 - LC - Updated to use DirtyRectangle property
12/07/07 - DaStr - Restored FPC compatibility
29/06/07 - DaStr - Initial version (by LordCrc)
}
unit Unit1;
interface
uses
GLLCLViewer,
SysUtils, Classes, Controls, Forms, ExtCtrls,
GLScene, GLObjects, GLTexture, GLCadencer, GLCrossPlatform, GLMaterial,
GLCoordinates, GLBaseClasses, GLRenderContextInfo;
type
TForm1 = class(TForm)
GLScene1: TGLScene;
GLSceneViewer1: TGLSceneViewer;
GLMaterialLibrary1: TGLMaterialLibrary;
GLCamera1: TGLCamera;
GLLightSource1: TGLLightSource;
GLDummyCube1: TGLDummyCube;
GLCube1: TGLCube;
GLDirectOpenGL1: TGLDirectOpenGL;
GLCadencer1: TGLCadencer;
Timer1: TTimer;
procedure FormKeyDown(Sender: TObject; var Key: word; Shift: TShiftState);
procedure FormResize(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure GLDirectOpenGL1Render(Sender: TObject; var rci: TRenderContextInfo);
procedure Timer1Timer(Sender: TObject);
procedure GLCadencer1Progress(Sender: TObject; const DeltaTime, newTime: double);
private
{ Private declarations }
frame: integer;
partial: boolean;
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
uses
GLUtils, GLContext, GLDynamicTexture, LCLType;
procedure TForm1.FormCreate(Sender: TObject);
begin
GLSceneViewer1.Align := alClient;
end;
procedure TForm1.FormKeyDown(Sender: TObject; var Key: word; Shift: TShiftState);
var
tex: TGLTexture;
img: TGLDynamicTextureImage;
begin
tex := GLMaterialLibrary1.TextureByName('Anim');
if not (tex.Image is TGLDynamicTextureImage) then
Exit;
img := TGLDynamicTextureImage(tex.Image);
case Key of
VK_F2:
begin
img.UsePBO := False;
GLSceneViewer1.ResetPerformanceMonitor;
frame := 0;
end;
VK_F3:
begin
img.UsePBO := True;
GLSceneViewer1.ResetPerformanceMonitor;
frame := 0;
end;
VK_F4:
begin
partial := not partial;
end;
end;
end;
procedure TForm1.FormResize(Sender: TObject);
begin
GLCamera1.SceneScale := GLSceneViewer1.ClientWidth / 400;
end;
procedure TForm1.GLCadencer1Progress(Sender: TObject; const DeltaTime, newTime: double);
begin
GLSceneViewer1.Invalidate;
end;
procedure TForm1.GLDirectOpenGL1Render(Sender: TObject; var rci: TRenderContextInfo);
var
tex: TGLTexture;
img: TGLDynamicTextureImage;
p: PRGBQuad;
X, Y: integer;
begin
tex := GLMaterialLibrary1.TextureByName('Anim');
if tex.Disabled then
begin
tex.ImageClassName := TGLDynamicTextureImage.ClassName;
img := TGLDynamicTextureImage(tex.Image);
img.Width := 256;
img.Height := 256;
tex.TextureFormat := tfRGBA;
tex.TextureMode := tmReplace;
tex.Disabled := False;
end;
img := TGLDynamicTextureImage(tex.Image);
img.BeginUpdate;
// draw some silly stuff
p := img.Data;
frame := frame + 1;
// first frame must always be drawn completely
if partial and (frame > 1) then
begin
// do partial update, set the dirty rectangle
// note that we do NOT offset the p pointer,
// since it is relative to the dirty rectangle,
// not the complete texture
// also note that the right/bottom edge is not included
// in the upload
img.DirtyRectangle := GLRect(img.Width div 4, img.Height div 4,
img.Width * 3 div 4, img.Height * 3 div 4);
end;
for Y := img.DirtyRectangle.Top to img.DirtyRectangle.Bottom - 1 do
begin
for X := img.DirtyRectangle.Left to img.DirtyRectangle.Right - 1 do
begin
p^.rgbRed := ((X xor Y) + frame) and 255;
p^.rgbGreen := ((X + frame) xor Y) and 255;
p^.rgbBlue := ((X - frame) xor (Y + frame)) and 255;
Inc(p);
end;
end;
img.EndUpdate;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
const
PBOText: array[boolean] of string = ('PBO disabled', 'PBO enabled');
var
tex: TGLTexture;
img: TGLDynamicTextureImage;
s: string;
begin
tex := GLMaterialLibrary1.TextureByName('Anim');
if (tex.Image is TGLDynamicTextureImage) then
begin
img := TGLDynamicTextureImage(tex.Image);
s := PBOText[img.UsePBO];
end;
Caption := Format('%s - %s', [GLSceneViewer1.FramesPerSecondText, s]);
GLSceneViewer1.ResetPerformanceMonitor;
end;
end.
|
unit NFSMaskButtonedEdit;
interface
{$R 'NFSMaskButtonedEdit.dcr'}
uses
SysUtils, Classes, vcl.Controls, vcl.StdCtrls, vcl.Mask, vcl.ImgList, vcl.ExtCtrls, Messages, vcl.Menus,
Windows, vcl.Themes, vcl.Forms, vcl.Graphics, NfsCustomMaskEdit, System.UITypes,
System.Types;
type
TNFSCustomMaskButtonedEdit = class;
TNFSEditButton = class(TPersistent)
strict private
type
TButtonState = (bsNormal, bsHot, bsPushed);
TGlyph = class(TCustomControl)
private
FButton: TNFSEditButton;
FState: TButtonState;
protected
procedure Click; override;
procedure CreateWnd; override;
procedure Paint; override;
procedure WndProc(var Message: TMessage); override;
public
constructor Create(AButton: TNFSEditButton); reintroduce; virtual;
end;
protected
type
TButtonPosition = (bpLeft, bpRight);
strict private
FDisabledImageIndex: TImageIndex;
FDropDownMenu: TPopupMenu;
FEditControl: TNFSCustomMaskButtonedEdit;
FGlyph: TGlyph;
FHotImageIndex: TImageIndex;
FImageIndex: TImageIndex;
FPosition: TButtonPosition;
FPressedImageIndex: TImageIndex;
function GetEnabled: Boolean;
function GetCustomHint: TCustomHint;
function GetHint: string;
function GetImages: TImageList;
function GetVisible: Boolean;
procedure SetDisabledImageIndex(const Value: TImageIndex);
procedure SetEnabled(const Value: Boolean);
procedure SetCustomHint(const Value: TCustomHint);
procedure SetHint(const Value: string);
procedure SetHotImageIndex(const Value: TImageIndex);
procedure SetImageIndex(const Value: TImageIndex);
procedure SetPressedImageIndex(const Value: TImageIndex);
procedure SetVisible(const Value: Boolean);
protected
function GetOwner: TPersistent; override;
procedure UpdateBounds; dynamic;
property EditControl: TNFSCustomMaskButtonedEdit read FEditControl;
property Glyph: TGlyph read FGlyph;
property Images: TImageList read GetImages;
property Position: TButtonPosition read FPosition;
public
constructor Create(EditControl: TNFSCustomMaskButtonedEdit; APosition: TButtonPosition); reintroduce; virtual;
destructor Destroy; override;
published
property CustomHint: TCustomHint read GetCustomHint write SetCustomHint;
property DisabledImageIndex: TImageIndex read FDisabledImageIndex write SetDisabledImageIndex default -1;
property DropDownMenu: TPopupMenu read FDropDownMenu write FDropDownMenu;
property Enabled: Boolean read GetEnabled write SetEnabled default True;
property Hint: string read GetHint write SetHint;
property HotImageIndex: TImageIndex read FHotImageIndex write SetHotImageIndex default -1;
property ImageIndex: TImageIndex read FImageIndex write SetImageIndex default -1;
property PressedImageIndex: TImageIndex read FPressedImageIndex write SetPressedImageIndex default -1;
property Visible: Boolean read GetVisible write SetVisible default False;
end;
TNFSEditButtonClass = class of TNFSEditButton;
TNFSCustomMaskButtonedEdit = class(TNfsCustomMaskEdit)
private
FCanvas: TControlCanvas;
FImages: TImageList;
FImageChangeLink: TChangeLink;
FLeftButton: TNFSEditButton;
FRightButton: TNFSEditButton;
function AdjustTextHint(Margin: Integer; const Value: string): string;
procedure ImageListChange(Sender: TObject);
procedure SetImages(const Value: TImageList);
function GetOnLeftButtonClick: TNotifyEvent;
function GetOnRightButtonClick: TNotifyEvent;
procedure SetLeftButton(const Value: TNFSEditButton);
procedure SetOnLeftButtonClick(const Value: TNotifyEvent);
procedure SetOnRightButtonClick(const Value: TNotifyEvent);
procedure SetRightButton(const Value: TNFSEditButton);
protected
procedure DoSetTextHint(const Value: string); override;
function GetEditButtonClass: TNFSEditButtonClass; dynamic;
procedure Notification(AComponent: TComponent; Operation: TOperation); override;
procedure UpdateEditMargins; reintroduce;
procedure WndProc(var Message: TMessage); override;
property LeftButton: TNFSEditButton read FLeftButton write SetLeftButton;
property RightButton: TNFSEditButton read FRightButton write SetRightButton;
property OnLeftButtonClick: TNotifyEvent read GetOnLeftButtonClick write SetOnLeftButtonClick;
property OnRightButtonClick: TNotifyEvent read GetOnRightButtonClick write SetOnRightButtonClick;
property Images: TImageList read FImages write SetImages;
public
procedure DefaultHandler(var Message); override;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
end;
TNFSMaskButtonedEdit = class(TNFSCustomMaskButtonedEdit)
private
protected
public
published
property Align;
property Alignment;
property Anchors;
property AutoSelect;
property AutoSize;
property BevelEdges;
property BevelInner;
property BevelOuter;
property BevelKind;
property BevelWidth;
property BiDiMode;
property BorderStyle;
property CharCase;
property Color;
property Constraints;
property Ctl3D;
property DoubleBuffered;
property DragCursor;
property DragKind;
property DragMode;
property Enabled;
property EditMask;
property Font;
property ImeMode;
property ImeName;
property MaxLength;
property ParentBiDiMode;
property ParentColor;
property ParentCtl3D;
property ParentDoubleBuffered;
property ParentFont;
property ParentShowHint;
property PasswordChar;
property PopupMenu;
property ReadOnly;
property ShowHint;
property TabOrder;
property TabStop;
property Text;
property TextHint;
property Touch;
property Visible;
property OnChange;
property OnClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnGesture;
property OnKeyDown;
property OnKeyPress;
property OnKeyUp;
property OnMouseActivate;
property OnMouseDown;
property OnMouseEnter;
property OnMouseLeave;
property OnMouseMove;
property OnMouseUp;
property OnStartDock;
property OnStartDrag;
property Images;
property LeftButton;
property RightButton;
property OnLeftButtonClick;
property OnRightButtonClick;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('new frontiers', [TNFSMaskButtonedEdit]);
end;
{ TNFSCustomMaskButtonedEdit }
function TNFSCustomMaskButtonedEdit.AdjustTextHint(Margin: Integer;
const Value: string): string;
var
LWidth, Count: Integer;
begin
if (Margin = 0) or (Win32MajorVersion >= 6) then
inherited DoSetTextHint(Value)
else
begin
FCanvas.Font := Font;
LWidth := FCanvas.TextWidth(' ');
Count := Margin div LWidth;
if (Margin mod LWidth) > 0 then
Inc(Count);
inherited DoSetTextHint(StringOfChar(' ', Count) + Value);
end;
end;
constructor TNFSCustomMaskButtonedEdit.Create(AOwner: TComponent);
begin
inherited;
FCanvas := TControlCanvas.Create;
FCanvas.Control := Self;
FImageChangeLink := TChangeLink.Create;
FImageChangeLink.OnChange := ImageListChange;
FLeftButton := GetEditButtonClass.Create(Self, bpLeft);
FRightButton := GetEditButtonClass.Create(Self, bpRight);
end;
{$LEGACYIFEND ON}
procedure TNFSCustomMaskButtonedEdit.DefaultHandler(var Message);
{$IF DEFINED(CLR)}
var
LMessage: TMessage;
{$IFEND}
begin
inherited;
{$IF DEFINED(CLR)}
LMessage := UnwrapMessage(TObject(Message));
case LMessage.Msg of
{$ELSE}
case TMessage(Message).Msg of
{$IFEND}
CN_CTLCOLOREDIT:
begin
FLeftButton.Glyph.Invalidate;
FRightButton.Glyph.Invalidate;
end;
WM_SIZE: FRightButton.UpdateBounds;
end;
end;
{$LEGACYIFEND OFF}
destructor TNFSCustomMaskButtonedEdit.Destroy;
begin
FreeAndNil(FCanvas);
FreeAndNil(FImageChangeLink);
FreeAndNil(FLeftButton);
FreeAndNil(FRightButton);
inherited;
end;
procedure TNFSCustomMaskButtonedEdit.DoSetTextHint(const Value: string);
begin
AdjustTextHint(0, Value);
end;
function TNFSCustomMaskButtonedEdit.GetEditButtonClass: TNFSEditButtonClass;
begin
Result := TNFSEditButton;
end;
function TNFSCustomMaskButtonedEdit.GetOnLeftButtonClick: TNotifyEvent;
begin
Result := LeftButton.Glyph.OnClick;
end;
function TNFSCustomMaskButtonedEdit.GetOnRightButtonClick: TNotifyEvent;
begin
Result := RightButton.Glyph.OnClick;
end;
procedure TNFSCustomMaskButtonedEdit.ImageListChange(Sender: TObject);
begin
if HandleAllocated then
begin
FLeftButton.UpdateBounds;
FRightButton.UpdateBounds;
UpdateEditMargins;
end;
end;
procedure TNFSCustomMaskButtonedEdit.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited Notification(AComponent, Operation);
if Operation = opRemove then
begin
if AComponent = FImages then
begin
FImages := nil;
FLeftButton.UpdateBounds;
FRightButton.UpdateBounds;
UpdateEditMargins;
end
else if (LeftButton <> nil) and (AComponent = LeftButton.DropDownMenu) then
LeftButton.DropDownMenu := nil
else if (RightButton <> nil) and (AComponent = RightButton.DropDownMenu) then
RightButton.DropDownMenu := nil;
end;
end;
procedure TNFSCustomMaskButtonedEdit.SetImages(const Value: TImageList);
begin
if Value <> FImages then
begin
if FImages <> nil then
FImages.UnRegisterChanges(FImageChangeLink);
FImages := Value;
if FImages <> nil then
begin
FImages.RegisterChanges(FImageChangeLink);
FImages.FreeNotification(Self);
end;
FLeftButton.UpdateBounds;
FRightButton.UpdateBounds;
UpdateEditMargins;
end;
end;
procedure TNFSCustomMaskButtonedEdit.SetLeftButton(const Value: TNFSEditButton);
begin
FLeftButton.Assign(Value);
end;
procedure TNFSCustomMaskButtonedEdit.SetOnLeftButtonClick(const Value: TNotifyEvent);
begin
LeftButton.Glyph.OnClick := Value;
end;
procedure TNFSCustomMaskButtonedEdit.SetOnRightButtonClick(const Value: TNotifyEvent);
begin
RightButton.Glyph.OnClick := Value;
end;
procedure TNFSCustomMaskButtonedEdit.SetRightButton(const Value: TNFSEditButton);
begin
FRightButton.Assign(Value);
end;
procedure TNFSCustomMaskButtonedEdit.UpdateEditMargins;
var
LMargin, RMargin: Integer;
begin
if HandleAllocated then
begin
LMargin := 0;
RMargin := 0;
if (Images <> nil) then
begin
if LeftButton.Visible then
LMargin := Images.Width + 2;
if RightButton.Visible then
RMargin := Images.Width + 2;
end;
SendMessage(Handle, EM_SETMARGINS, EC_LEFTMARGIN or EC_RIGHTMARGIN, MakeLong(LMargin, RMargin));
AdjustTextHint(LMargin, TextHint);
Invalidate;
end;
end;
procedure TNFSCustomMaskButtonedEdit.WndProc(var Message: TMessage);
var
LLeft, LTop: Integer;
begin
case Message.Msg of
CN_CTLCOLORSTATIC,
CN_CTLCOLOREDIT:
if FImages <> nil then
begin
if LeftButton.Visible then
begin
LLeft := LeftButton.Glyph.Left;
LTop := LeftButton.Glyph.Top;
if StyleServices.Enabled and Ctl3D then
begin
Inc(LLeft);
Inc(LTop);
end;
ExcludeClipRect(Message.WParam, LLeft + 1, LTop + 1,
LeftButton.Glyph.Width + LeftButton.Glyph.Left, LeftButton.Glyph.Height);
end;
if RightButton.Visible then
begin
LTop := RightButton.Glyph.Top;
if StyleServices.Enabled and Ctl3D then
Inc(LTop);
ExcludeClipRect(Message.WParam, RightButton.Glyph.Left, LTop + 1,
RightButton.Glyph.Width + RightButton.Glyph.Left, RightButton.Glyph.Height);
end;
end;
end;
inherited;
case Message.Msg of
CM_BORDERCHANGED,
CM_CTL3DCHANGED:
begin
if not (csLoading in ComponentState) then
begin
LeftButton.UpdateBounds;
RightButton.UpdateBounds;
end;
end;
CM_FONTCHANGED:
if not (csLoading in ComponentState) then
UpdateEditMargins;
end;
end;
constructor TNFSEditButton.Create(EditControl: TNFSCustomMaskButtonedEdit;
APosition: TButtonPosition);
begin
inherited Create;
FEditControl := EditControl;
FGlyph := TGlyph.Create(Self);
FHotImageIndex := -1;
FImageIndex := -1;
FPosition := APosition;
FPressedImageIndex := -1;
FDisabledImageIndex := -1;
end;
destructor TNFSEditButton.Destroy;
begin
FGlyph.Parent.RemoveControl(FGlyph);
FGlyph.Free;
inherited;
end;
function TNFSEditButton.GetCustomHint: TCustomHint;
begin
Result := FGlyph.CustomHint;
end;
function TNFSEditButton.GetEnabled: Boolean;
begin
Result := FGlyph.Enabled;
end;
function TNFSEditButton.GetHint: string;
begin
Result := FGlyph.Hint;
end;
function TNFSEditButton.GetImages: TImageList;
begin
Result := FEditControl.Images;
end;
function TNFSEditButton.GetOwner: TPersistent;
begin
Result := FEditControl;
end;
function TNFSEditButton.GetVisible: Boolean;
begin
Result := FGlyph.Visible;
end;
procedure TNFSEditButton.SetCustomHint(const Value: TCustomHint);
begin
if Value <> FGlyph.CustomHint then
FGlyph.CustomHint := Value;
end;
procedure TNFSEditButton.SetDisabledImageIndex(const Value: TImageIndex);
begin
if Value <> FDisabledImageIndex then
begin
FDisabledImageIndex := Value;
if not Enabled then
FGlyph.Invalidate;
end;
end;
procedure TNFSEditButton.SetEnabled(const Value: Boolean);
begin
if Value <> FGlyph.Enabled then
begin
FGlyph.Enabled := Value;
FGlyph.Invalidate;
end;
end;
procedure TNFSEditButton.SetHint(const Value: string);
begin
if Value <> FGlyph.Hint then
FGlyph.Hint := Value;
end;
procedure TNFSEditButton.SetHotImageIndex(const Value: TImageIndex);
begin
if Value <> FHotImageIndex then
begin
FHotImageIndex := Value;
if FGlyph.FState = bsHot then
FGlyph.Invalidate;
end;
end;
procedure TNFSEditButton.SetImageIndex(const Value: TImageIndex);
begin
if Value <> FImageIndex then
begin
FImageIndex := Value;
if FGlyph.FState = bsNormal then
FGlyph.Invalidate;
end;
end;
procedure TNFSEditButton.SetPressedImageIndex(const Value: TImageIndex);
begin
if Value <> FPressedImageIndex then
begin
FPressedImageIndex := Value;
if FGlyph.FState = bsPushed then
FGlyph.Invalidate;
end;
end;
procedure TNFSEditButton.SetVisible(const Value: Boolean);
begin
if Value <> FGlyph.Visible then
begin
FGlyph.Visible := Value;
FEditControl.UpdateEditMargins;
end;
end;
procedure TNFSEditButton.UpdateBounds;
var
EdgeSize, NewLeft: Integer;
begin
if FGlyph <> nil then
begin
if Images <> nil then
begin
FGlyph.Width := Images.Width;
FGlyph.Height := Images.Height;
end
else
begin
FGlyph.Width := 0;
FGlyph.Height := 0;
end;
FGlyph.Top := 0;
NewLeft := FGlyph.Left;
if not StyleServices.Enabled then
FGlyph.Top := 1;
case FPosition of
bpLeft:
begin
if StyleServices.Enabled then
NewLeft := 0
else
NewLeft := 1;
end;
bpRight:
begin
NewLeft := FEditControl.Width - FGlyph.Width;
if FEditControl.BorderStyle <> bsNone then
Dec(NewLeft, 4);
if FEditControl.BevelKind <> bkNone then
begin
EdgeSize := 0;
if FEditControl.BevelInner <> bvNone then
Inc(EdgeSize, FEditControl.BevelWidth);
if FEditControl.BevelOuter <> bvNone then
Inc(EdgeSize, FEditControl.BevelWidth);
if beRight in FEditControl.BevelEdges then
Dec(NewLeft, EdgeSize);
if beLeft in FEditControl.BevelEdges then
Dec(NewLeft, EdgeSize);
end;
if not StyleServices.Enabled then
Dec(NewLeft);
end;
end;
if (not FEditControl.Ctl3D) and (FEditControl.BorderStyle <> bsNone) then
begin
FGlyph.Top := 2;
Inc(NewLeft, 2);
end;
FGlyph.Left := NewLeft;
if (csDesigning in FEditControl.ComponentState) and not Visible then
FGlyph.Width := 0;
end;
end;
procedure TNFSEditButton.TGlyph.Click;
begin
// Replicate from TControl to set Sender to owning TButtonedEdit control
if Assigned(OnClick) and (Action <> nil) and not DelegatesEqual(@OnClick, @Action.OnExecute) then
OnClick(FButton.EditControl)
else if not (csDesigning in ComponentState) and (ActionLink <> nil) then
ActionLink.Execute(FButton.EditControl)
else if Assigned(OnClick) then
OnClick(FButton.EditControl);
end;
procedure TNFSEditButton.TGlyph.CreateWnd;
begin
inherited;
if Visible then
FButton.FEditControl.UpdateEditMargins;
end;
procedure TNFSEditButton.TGlyph.Paint;
var
LIndex: Integer;
begin
inherited;
if (FButton.Images <> nil) and Visible then
begin
LIndex := FButton.ImageIndex;
if Enabled then
begin
case FState of
bsHot:
if FButton.HotImageIndex <> -1 then
LIndex := FButton.HotImageIndex;
bsPushed:
if FButton.PressedImageIndex <> -1 then
LIndex := FButton.PressedImageIndex;
end;
end
else
if FButton.DisabledImageIndex <> -1 then
LIndex := FButton.DisabledImageIndex;
if LIndex <> -1 then
FButton.Images.Draw(Canvas, 0, 0, LIndex);
end;
end;
procedure TNFSEditButton.TGlyph.WndProc(var Message: TMessage);
var
LPoint: TPoint;
begin
if (Message.Msg = WM_CONTEXTMENU) and (FButton.EditControl.PopupMenu = nil) then
Exit;
inherited;
case Message.Msg of
CM_MOUSEENTER: FState := bsHot;
CM_MOUSELEAVE: FState := bsNormal;
WM_LBUTTONDOWN:
if FButton.FDropDownMenu <> nil then
begin
if not (csDesigning in Parent.ComponentState) then
begin
LPoint := ClientToScreen(Point(0, FButton.EditControl.Height));
FButton.FDropDownMenu.Popup(LPoint.X, LPoint.Y);
end;
end
else
FState := bsPushed;
WM_LBUTTONUP: FState := bsHot;
CM_VISIBLECHANGED: FButton.UpdateBounds;
else
Exit;
end;
Invalidate;
end;
constructor TNFSEditButton.TGlyph.Create(AButton: TNFSEditButton);
begin
inherited Create(AButton.FEditControl);
FButton := AButton;
FState := bsNormal;
Parent := FButton.FEditControl;
Visible := False;
end;
end.
|
unit NewtonRagdoll;
interface
uses
System.Classes,
System.SysUtils,
GLVectorGeometry,
GLVectorTypes,
GLVectorFileObjects,
NewtonImport;
type
TNewtonRagdoll = class
private
FERP, FSlideLimit, FAngleLimit: single;
FEnabled: boolean;
newtonworld: PNewtonWorld;
procedure SetSlideLimit(value: single);
procedure SetAngleLimit(value: single);
procedure SetERP(value: single);
procedure SetEnabled(value: boolean);
procedure Clean;
public
actor: TGLActor;
bodies: TList;
joints: array of PNewtonJoint;
norm_matrices: array of TMatrix;
envelopes: array of record kind: byte;
m: TMatrix;
pt: TVector3f;
w, d, h, mass: single;
end;
property Enabled: boolean read FEnabled write SetEnabled;
property SlideLimit: single read FSlideLimit write SetSlideLimit;
property AngleLimit: single read FAngleLimit write SetAngleLimit;
property ERP: single read FERP write SetERP;
constructor Create(model: TGLActor; world: PNewtonWorld;
min_env_size: single = 0.8; slide_limit: single = 0.5; erp_: single = 0.8;
angle_limit: single = 15; full: boolean = true);
procedure Conform;
destructor Destroy; override;
procedure LoadFromFile(filename: string);
procedure SaveToFile(filename: string);
function TranslatePos(n: integer; add: boolean): TVector;
end;
function GetBoneParent(actor: TGLActor; bone: integer): integer;
implementation
function TNewtonRagdoll.TranslatePos;
begin
with envelopes[n] do
if add then
Result := VectorAdd(m.w, VectorAdd(VectorScale(m.X, pt.X),
VectorAdd(VectorScale(m.Y, pt.Y), VectorScale(m.Z, pt.Z))))
else
Result := VectorSubtract(m.w, VectorAdd(VectorScale(m.X, pt.X),
VectorAdd(VectorScale(m.Y, pt.Y), VectorScale(m.Z, pt.Z))));
end;
function GetBoneParent;
var
i, j: integer;
begin
Result := 0;
for i := 0 to actor.Skeleton.BoneCount - 2 do
if actor.Skeleton.BoneByID(i) <> nil then
for j := 0 to actor.Skeleton.BoneByID(i).Count - 1 do
if actor.Skeleton.BoneByID(i).Items[j].BoneID = bone then
begin
Result := i;
Exit;
end;
end;
procedure NewtonApplyForceAndTorqueCallback(const body: PNewtonBody;
timestep: single; threadIndex: integer); cdecl;
var
m: single;
i: TVector3f;
F: TVector3f;
begin
NewtonBodyGetMassMatrix(body, @m, @i.X, @i.Y, @i.Z);
F := AffineVectorMake(0, -9.81 * m, 0);
NewtonBodyAddForce(body, @F.X);
end;
function NewtonJointCallBack(const Universal: PNewtonJoint;
desc: PNewtonHingeSliderUpdateDesc): cardinal; cdecl;
var
angle: single;
begin
// if Abs(desc.m_accel)>100 then
// desc.m_accel:=desc.m_accel/2;
// desc.m_accel:=NewtonUniversalCalculateStopAlpha1(Universal,desc,0);
{ angle:=NewtonUniversalGetJointAngle0(Universal);
if angle<-2.6 then desc.m_accel:=NewtonUniversalCalculateStopAlpha0(Universal,desc,-2.6);
if angle>0 then desc.m_accel:=NewtonUniversalCalculateStopAlpha0(Universal,desc,0);
angle:=NewtonUniversalGetJointAngle1(Universal);
if angle<-2.6 then desc.m_accel:=NewtonUniversalCalculateStopAlpha1(Universal,desc,-2.6);
if angle>0 then desc.m_accel:=NewtonUniversalCalculateStopAlpha1(Universal,desc,0);
}
Result := 0;
end;
constructor TNewtonRagdoll.Create;
var
i, j: integer;
p1, p2: TVector4f;
d: single;
collision: PNewtonCollision;
begin
d := 0;
if full then
begin
inherited Create;
actor := model;
newtonworld := world;
end;
FEnabled := false;
bodies := TList.Create;
SetLength(envelopes, actor.Skeleton.BoneCount - 1);
SetLength(norm_matrices, actor.Skeleton.BoneCount - 1);
SetLength(joints, actor.Skeleton.BoneCount - 1);
for i := 0 to actor.Skeleton.BoneCount - 2 do
begin
p1 := actor.Skeleton.BoneByID(i).GlobalMatrix.W;
if actor.Skeleton.BoneByID(i).BoneCount > 1 then
p2 := actor.Skeleton.BoneByID(i).Items[0].GlobalMatrix.W
else
p2 := p1;
p1 := VectorTransform(p1, actor.AbsoluteMatrix);
p2 := VectorTransform(p2, actor.AbsoluteMatrix);
with envelopes[i] do
begin
if full then
begin
kind := 1;
mass := 1;
d := 2 * min_env_size;
h := 2 * min_env_size;
w := 0.8 * VectorLength(VectorSubtract(p2, p1));
if w < 1 then
begin
w := min_env_size;
d := min_env_size;
h := min_env_size;
end;
pt := AffineVectorMake(w * 0.5 / 0.8, 0, 0);
// p2:=m[0]; m[0]:=m[1]; m[1]:=p2;
end;
m := MatrixMultiply(actor.Skeleton.BoneByID(i).GlobalMatrix,
actor.AbsoluteMatrix);
m.W := TranslatePos(i, true);
case kind of
0, 1:
begin
collision := NewtonCreateBox(newtonworld, w, h, d, nil);
bodies.add(NewtonCreateBody(world, collision));
NewtonBodySetMassMatrix(bodies[bodies.Count - 1], mass, w, h, d);
end;
2:
begin
bodies.add(NewtonCreateBody(world, NewtonCreateCylinder(newtonworld,
w, h, nil)));
NewtonBodySetMassMatrix(bodies[bodies.Count - 1], mass, 2, w, h);
end;
3:
begin
bodies.add(NewtonCreateBody(world, NewtonCreateSphere(newtonworld,
w, w, w, nil)));
NewtonBodySetMassMatrix(bodies[bodies.Count - 1], mass, w, w, w);
end;
end;
NewtonBodySetLinearDamping(bodies[i], 0);
NewtonBodySetAngularDamping(bodies[i], @d);
NewtonBodySetMatrix(bodies[i], @m);
NewtonBodySetForceAndTorqueCallBack(bodies[i],
NewtonApplyForceAndTorqueCallback);
end;
end;
FERP := erp_;
FSlideLimit := slide_limit;
FAngleLimit := angle_limit;
for i := 0 to actor.Skeleton.BoneCount - 2 do
begin
j := GetBoneParent(actor, i);
if i = j then
Continue;
p1 := TranslatePos(i, false);
with envelopes[i] do
joints[i] := NewtonConstraintCreateHinge(newtonworld, @p1, @m.Y,
bodies[i], bodies[j]);
NewtonJointSetCollisionState(joints[i], 1);
NewtonHingeSetUserCallback(joints[i], NewtonJointCallBack);
end;
end;
procedure TNewtonRagdoll.Conform;
var
i: integer;
begin
if Enabled = false then
Exit;
for i := 0 to Length(envelopes) - 1 do
with envelopes[i] do
begin
NewtonBodyGetMatrix(bodies[i], @m);
m.W := TranslatePos(i, false);
actor.Skeleton.BoneByID(i).SetGlobalMatrixForRagDoll(m);
end;
actor.Skeleton.MorphMesh(true);
end;
procedure TNewtonRagdoll.Clean;
var
i: integer;
begin
for i := 0 to Length(joints) - 1 do
if joints[i] <> nil then
NewtonDestroyJoint(newtonworld, joints[i]);
SetLength(joints, 0);
for i := 0 to bodies.Count - 1 do
NewtonDestroyBody(newtonworld, bodies[i]);
bodies.Clear;
FreeAndNil(bodies);
end;
destructor TNewtonRagdoll.Destroy;
begin
Clean;
SetLength(envelopes, 0);
SetLength(norm_matrices, 0);
inherited Destroy;
end;
procedure TNewtonRagdoll.SetEnabled;
var
i: integer;
a: TMatrix;
v: TVector3f;
begin
if FEnabled = value then
Exit;
FEnabled := value;
if value = true then
begin
actor.Skeleton.StartRagdoll;
for i := 0 to Length(envelopes) - 1 do
norm_matrices[i] := envelopes[i].m;
Exit;
end;
actor.Skeleton.StopRagdoll;
for i := 0 to Length(envelopes) - 1 do
begin
v := NullVector;
NewtonBodySetVelocity(bodies[i], @v);
NewtonBodySetOmega(bodies[i], @v);
NewtonBodySetForce(bodies[i], @v);
NewtonBodySetTorque(bodies[i], @v);
envelopes[i].m := norm_matrices[i];
a := envelopes[i].m;
NewtonBodySetMatrix(bodies[i], @a);
NewtonBodySetCollision(bodies[i], nil);
actor.Skeleton.BoneByID(i).SetGlobalMatrixForRagDoll(a);
end;
actor.Skeleton.MorphMesh(true);
end;
procedure TNewtonRagdoll.SetSlideLimit;
begin
FSlideLimit := value;
end;
procedure TNewtonRagdoll.SetAngleLimit;
begin
FAngleLimit := value;
end;
procedure TNewtonRagdoll.SetERP;
var
i: integer;
begin
FERP := value;
end;
procedure TNewtonRagdoll.LoadFromFile;
var
i: integer;
s, a, e: single;
F: TFileStream;
begin
F := TFileStream.Create(filename, fmOpenRead);
F.Read(i, SizeOf(i));
SetLength(envelopes, i);
F.Read(s, SizeOf(s));
F.Read(e, SizeOf(e));
F.Read(a, SizeOf(a));
Clean;
for i := 0 to Length(envelopes) - 1 do
begin
F.Read(envelopes[i].kind, SizeOf(envelopes[i].kind));
F.Read(envelopes[i].w, SizeOf(envelopes[i].w));
F.Read(envelopes[i].h, SizeOf(envelopes[i].h));
F.Read(envelopes[i].d, SizeOf(envelopes[i].d));
F.Read(envelopes[i].mass, SizeOf(envelopes[i].mass));
F.Read(envelopes[i].pt, SizeOf(envelopes[i].pt));
end;
/// Create(actor, newtonworld, 0.8, s, e, a, false);
F.Free;
end;
procedure TNewtonRagdoll.SaveToFile;
var
i: integer;
F: TFileStream;
begin
if FileExists(filename) then
F := TFileStream.Create(filename, fmOpenWrite)
else
F := TFileStream.Create(filename, fmCreate);
i := Length(envelopes);
F.Write(i, SizeOf(i));
F.Write(FSlideLimit, SizeOf(FSlideLimit));
F.Write(FERP, SizeOf(FERP));
F.Write(FAngleLimit, SizeOf(FAngleLimit));
for i := 0 to Length(envelopes) - 1 do
begin
F.Write(envelopes[i].kind, SizeOf(envelopes[i].kind));
F.Write(envelopes[i].w, SizeOf(envelopes[i].w));
F.Write(envelopes[i].h, SizeOf(envelopes[i].h));
F.Write(envelopes[i].d, SizeOf(envelopes[i].d));
F.Write(envelopes[i].mass, SizeOf(envelopes[i].mass));
F.Write(envelopes[i].pt, SizeOf(envelopes[i].pt));
end;
F.Free;
end;
end.
|
{*******************************************************************************
* *
* ksDrawFunctions - control drawing functions for ksListView *
* *
* https://github.com/gmurt/KernowSoftwareFMX *
* *
* Copyright 2015 Graham Murt *
* *
* email: graham@kernow-software.co.uk *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* *
*******************************************************************************}
{ *** HTML SUPPORT - PLEASE READ ***
In order to use the HTML formatting within ksListView, you will need to have the
TMS Pack for FireMonkey installed.
You can get this from the following link...
http://www.tmssoftware.com/site/tmsfmxpack.asp
Once installed, simply uncomment the conditional define below
}
//{$DEFINE USE_TMS_HTML_ENGINE}
unit ksDrawFunctions;
interface
uses Classes, FMX.Graphics, FMX.Types, Types, System.UIConsts, System.UITypes,
FMX.ListView.Types, Generics.Collections, FMX.Platform;
type
TksButtonStyle = (ksButtonDefault, ksButtonSegmentLeft, ksButtonSegmentMiddle, ksButtonSegmentRight);
function GetScreenScale: single;
function IsBlankBitmap(ABmp: TBitmap; const ABlankColor: TAlphaColor = claNull): Boolean;
function GetColorOrDefault(AColor, ADefaultIfNull: TAlphaColor): TAlphaColor;
procedure DrawSwitch(ACanvas: TCanvas; ARect: TRectF; AChecked, AEnabled: Boolean; ASelectedColor: TAlphaColor);
procedure DrawButton(ACanvas: TCanvas; ARect: TRectF; AText: string; ASelected: Boolean; AColor: TAlphaColor; AStyle: TksButtonStyle);
function TextWidth(AText: string; AFont: TFont): single;
function TextHeight(AText: string; AFont: TFont; AWordWrap: Boolean; const AWidth: single = 0): single;
function TextSizeHtml(AText: string; AFont: TFont; const AWidth: single = 0): TPointF;
procedure RenderText(ACanvas: TCanvas;
x, y,
AWidth, AHeight: single;
AText: string;
AFont: TFont;
ATextColor: TAlphaColor;
AWordWrap: Boolean;
AHorzAlign: TTextAlign;
AVertAlign: TTextAlign;
ATrimming: TTextTrimming);
procedure RenderHhmlText(ACanvas: TCanvas;
x, y,
AWidth, AHeight: single;
AText: string;
AFont: TFont;
ATextColor: TAlphaColor;
AWordWrap: Boolean;
AHorzAlign: TTextAlign;
AVertAlign: TTextAlign;
ATrimming: TTextTrimming);
implementation
uses SysUtils, FMX.TextLayout, Math, FMX.Objects, FMX.Styles, FMX.Styles.Objects,
FMX.Forms {$IFDEF USE_TMS_HTML_ENGINE} , FMX.TMSHTMLEngine {$ENDIF};
var
_ScreenScale: single;
ATextLayout: TTextLayout;
function GetColorOrDefault(AColor, ADefaultIfNull: TAlphaColor): TAlphaColor;
begin
Result := AColor;
if Result = claNull then
Result := ADefaultIfNull;
end;
function GetScreenScale: single;
var
Service: IFMXScreenService;
begin
if _ScreenScale > 0 then
begin
Result := _ScreenScale;
Exit;
end;
Service := IFMXScreenService(TPlatformServices.Current.GetPlatformService
(IFMXScreenService));
Result := Service.GetScreenScale;
{$IFDEF IOS}
//if Result < 2 then
// Result := 2;
{$ENDIF}
_ScreenScale := Result;
end;
function TextSizeHtml(AText: string; AFont: TFont; const AWidth: single = 0): TPointF;
{$IFDEF USE_TMS_HTML_ENGINE}
var
AnchorVal,
StripVal,
FocusAnchor: string;
XSize,
YSize: single;
HyperLinks,
MouseLink: Integer;
HoverRect:TRectF;
ABmp: TBitmap;
{$ENDIF}
begin
Result := PointF(0, 0);
{$IFDEF USE_TMS_HTML_ENGINE}
XSize := AWidth;
if XSize <= 0 then
XSize := MaxSingle;
ABmp := TBitmap.Create(10, 10);
try
ABmp.BitmapScale := GetScreenScale;
ABmp.Canvas.Assign(AFont);
{$IFDEF USE_TMS_HTML_ENGINE}
HTMLDrawEx(ABmp.Canvas, AText, RectF(0, 0, XSize, MaxSingle), 0,0, 0, 0, 0, False,
False, False, False, False, False, False, 1, claNull,
claNull, claNull, claNull, AnchorVal, StripVal, FocusAnchor, XSize, YSize, HyperLinks, MouseLink,
HoverRect, 1, nil, 1);
Result := PointF(XSize, YSize);
{$ELSE}
Result := PointF(0, 0);
{$ENDIF}
finally
FreeAndNil(ABmp);
end;
{$ENDIF}
end;
function TextWidth(AText: string; AFont: TFont): single;
var
APoint: TPointF;
begin
ATextLayout.BeginUpdate;
// Setting the layout MaxSize
APoint.X := MaxSingle;
APoint.Y := 100;
ATextLayout.MaxSize := aPoint;
ATextLayout.Text := AText;
ATextLayout.WordWrap := False;
ATextLayout.Font.Assign(AFont);
ATextLayout.HorizontalAlign := TTextAlign.Leading;
ATextLayout.EndUpdate;
Result := ATextLayout.Width;
end;
function TextHeight(AText: string; AFont: TFont; AWordWrap: Boolean; const AWidth: single = 0): single;
var
APoint: TPointF;
begin
ATextLayout.BeginUpdate;
// Setting the layout MaxSize
APoint.X := MaxSingle;
if AWidth > 0 then
APoint.X := AWidth;
APoint.Y := 100;
ATextLayout.MaxSize := aPoint;
ATextLayout.Text := AText;
ATextLayout.WordWrap := AWordWrap;
ATextLayout.Font.Assign(AFont);
ATextLayout.HorizontalAlign := TTextAlign.Leading;
ATextLayout.VerticalAlign := TTextAlign.Leading;
ATextLayout.EndUpdate;
Result := ATextLayout.TextHeight;
end;
procedure RenderText(ACanvas: TCanvas;
x, y,
AWidth, AHeight: single;
AText: string;
AFont: TFont;
ATextColor: TAlphaColor;
AWordWrap: Boolean;
AHorzAlign: TTextAlign;
AVertAlign: TTextAlign;
ATrimming: TTextTrimming);
begin
ATextLayout.BeginUpdate;
ATextLayout.Text := AText;
ATextLayout.WordWrap := AWordWrap;
ATextLayout.Font.Assign(AFont);
ATextLayout.Color := ATextColor;
ATextLayout.HorizontalAlign := AHorzAlign;
ATextLayout.VerticalAlign := AVertAlign;
ATextLayout.Trimming := ATrimming;
ATextLayout.TopLeft := PointF(x, y);
ATextLayout.MaxSize := PointF(AWidth, AHeight);
ATextLayout.EndUpdate;
ATextLayout.RenderLayout(ACanvas);
end;
procedure RenderHhmlText(ACanvas: TCanvas;
x, y,
AWidth, AHeight: single;
AText: string;
AFont: TFont;
ATextColor: TAlphaColor;
AWordWrap: Boolean;
AHorzAlign: TTextAlign;
AVertAlign: TTextAlign;
ATrimming: TTextTrimming);
{$IFDEF USE_TMS_HTML_ENGINE}
var
AnchorVal,
StripVal,
FocusAnchor: string;
XSize,
YSize: single;
HyperLinks,
MouseLink: Integer;
HoverRect:TRectF;
{$ENDIF}
begin
{$IFDEF USE_TMS_HTML_ENGINE}
ACanvas.Fill.Color := ATextColor;
ACanvas.Font.Assign(AFont);
HTMLDrawEx(ACanvas, AText, RectF(x,y , x+AWidth, y+AHeight), 0,0, 0, 0, 0, False,
False, True, False, False, False, AWordWrap, 1, claNull,
claNull, claNull, claNull, AnchorVal, StripVal, FocusAnchor, XSize, YSize, HyperLinks, MouseLink,
HoverRect, 1, nil, 1);
{$ELSE}
AFont.Size := 10;
RenderText(ACanvas, x, y, AWidth, AHeight, 'Requires TMS FMX', AFont, ATextColor, AWordWrap, AHorzAlign, AVertAlign, ATrimming);
{$ENDIF}
end;
function IsBlankBitmap(ABmp: TBitmap; const ABlankColor: TAlphaColor = claNull): Boolean;
var
ABlank: TBitmap;
begin
ABlank := TBitmap.Create(ABmp.Width, ABmp.Height);
try
ABlank.Clear(ABlankColor);
Result := ABmp.EqualsBitmap(ABlank);
finally
FreeAndNil(ABlank);
end;
end;
procedure DrawSwitch(ACanvas: TCanvas; ARect: TRectF; AChecked, AEnabled: Boolean; ASelectedColor: TAlphaColor);
var
ABmp: TBitmap;
r: TRectF;
ASwitchRect: TRectF;
begin
ABmp := TBitmap.Create(Round(ARect.Width * GetScreenScale), Round(ARect.Height * GetScreenScale));
try
ABmp.Clear(claNull);
ABmp.BitmapScale := GetScreenScale;
ABmp.Canvas.BeginScene;
ABmp.Canvas.StrokeThickness := GetScreenScale;
r := RectF(0, 0, ABmp.Height, ABmp.Height);
if not AChecked then
ASwitchRect := r;
ABmp.Canvas.Stroke.Color := claSilver;
ABmp.Canvas.Fill.Color := claWhite;
if AChecked then
Abmp.Canvas.Fill.Color := ASelectedColor;
if AEnabled = False then
ABmp.Canvas.Fill.Color := claGainsboro;
ABmp.Canvas.FillEllipse(r, 1, ABmp.Canvas.Fill);
ABmp.Canvas.DrawEllipse(r, 1, ABmp.Canvas.Stroke);
OffsetRect(r, ABmp.Width-r.Height, 0);
if AChecked then
ASwitchRect := r;
ABmp.Canvas.FillEllipse(r, 1, ABmp.Canvas.Fill);
ABmp.Canvas.DrawEllipse(r, 1, ABmp.Canvas.Stroke);
//ABmp.Canvas.Fill.Color := claWhite;
ABmp.Canvas.FillRect(RectF(0 + (r.Width/2), 0, ABmp.Width - (r.Width/2), ABmp.Height), 0, 0, AllCorners, 1, ABmp.Canvas.Fill);
r := RectF(ABmp.Height/2, 0, ABmp.Width-(ABmp.Height/2), ABmp.Height);
ABmp.Canvas.FillRect(r, 0, 0, AllCorners, 1, ABmp.Canvas.Fill);
ABmp.Canvas.StrokeThickness := 3;
r.Bottom := r.Bottom -1;
r.Left := r.Left - (GetScreenScale*4);
r.Right := r.Right + (GetScreenScale*4);
ABmp.Canvas.DrawRectSides(r, 0, 0, AllCorners, 1, [TSide.Top, TSide.Bottom], ABmp.Canvas.Stroke);
ABmp.Canvas.StrokeThickness := 2;
ABmp.Canvas.Fill.Color := claWhite;
if AEnabled = False then
begin
ABmp.Canvas.Fill.Color := $FFEEEEEE;
end;
if AChecked then
begin
InflateRect(ASwitchRect, -2, -2);
ABmp.Canvas.FillEllipse(ASwitchRect, 1, ABmp.Canvas.Fill);
end
else
begin
InflateRect(ASwitchRect, -1, -1);
ABmp.Canvas.Stroke.Color := claSilver;
ABmp.Canvas.DrawEllipse(ASwitchRect, 1, ABmp.Canvas.Stroke);
end;
ABmp.Canvas.EndScene;
ACanvas.DrawBitmap(ABmp, RectF(0, 0, ABmp.Width, ABmp.Height), ARect, 1, False);
finally
FreeAndNil(ABmp);
end;
end;
procedure DrawButton(ACanvas: TCanvas; ARect: TRectF; AText: string; ASelected: Boolean; AColor: TAlphaColor; AStyle: TksButtonStyle);
var
ABmp: TBitmap;
r: TRectF;
ARadius: single;
AFill, AOutline, AFontColor: TAlphaColor;
AScale: single;
begin
AScale := 2;
ARadius := 5*AScale;
ABmp := TBitmap.Create(Round(ARect.Width * AScale), Round(ARect.Height * AScale));
try
if AColor = claNull then
AColor := claDodgerblue;
ABmp.Clear(claNull);
ABmp.BitmapScale := AScale;
r := RectF(0, 0, ABmp.Width, ABmp.Height);
ABmp.Canvas.BeginScene;
ABmp.Canvas.StrokeThickness := AScale;
ABmp.Canvas.Stroke.Color := claSilver;
ABmp.Canvas.Font.Size := (13 * AScale);
if ASelected then
begin
AFill := AColor;
AOutline := AColor;
AFontColor := claWhite;
end
else
begin
AFill := claWhite;
AOutline := AColor;
AFontColor := AColor;
end;
ABmp.Canvas.Blending := True;
ABmp.Canvas.Fill.Color := AFill;
ABmp.Canvas.Stroke.Color := AOutline;
if AStyle = ksButtonSegmentLeft then
begin
ABmp.Canvas.FillRect(r, ARadius, ARadius, [TCorner.TopLeft, TCorner.BottomLeft], 1, ABmp.Canvas.Fill);
ABmp.Canvas.DrawRect(r, ARadius, ARadius, [TCorner.TopLeft, TCorner.BottomLeft], 1, ABmp.Canvas.Stroke);
end
else
if AStyle = ksButtonSegmentRight then
begin
ABmp.Canvas.FillRect(r, ARadius, ARadius, [TCorner.TopRight, TCorner.BottomRight], 1, ABmp.Canvas.Fill);
ABmp.Canvas.DrawRect(r, ARadius, ARadius, [TCorner.TopRight, TCorner.BottomRight], 1, ABmp.Canvas.Stroke);
end
else
begin
ABmp.Canvas.FillRect(r, 0, 0, AllCorners, 1, ABmp.Canvas.Fill);
ABmp.Canvas.DrawRect(r, 0, 0, AllCorners, 1, ABmp.Canvas.Stroke);
end;
ABmp.Canvas.Fill.Color := AFontColor;
ABmp.Canvas.FillText(r, AText, False, 1, [], TTextAlign.Center);
ABmp.Canvas.EndScene;
ACanvas.DrawBitmap(ABmp, RectF(0, 0, ABmp.Width, ABmp.Height), ARect, 1, True);
finally
FreeAndNil(ABmp);
end;
end;
procedure DrawCheckMarkAccessory(ACanvas: TCanvas; ARect: TRectF; AColor: TAlphaColor);
var
ABmp: TBitmap;
r: TRectF;
begin
ABmp := TBitmap.Create(Round(ARect.Width * GetScreenScale), Round(ARect.Height * GetScreenScale));
try
ABmp.Clear(claNull);
ABmp.BitmapScale := GetScreenScale;
ABmp.Canvas.BeginScene;
ABmp.Canvas.StrokeThickness := 2*GetScreenScale;
ABmp.Canvas.Stroke.Color := AColor;
r := RectF(0, 0, ABmp.Height, ABmp.Height);
ABmp.Canvas.DrawLine(PointF(4, ABmp.Height/2), PointF(ABmp.Width/3, ABmp.Height-4), 1);
ABmp.Canvas.DrawLine(PointF(ABmp.Width/3, ABmp.Height-4), PointF(ABmp.Width-4, 0), 1);
ABmp.Canvas.EndScene;
ACanvas.DrawBitmap(ABmp, RectF(0, 0, ABmp.Width, ABmp.Height), ARect, 1, False);
finally
FreeAndNil(ABmp);
end;
end;
procedure DrawMoreAccessory(ACanvas: TCanvas; ARect: TRectF; AColor: TAlphaColor);
var
ABmp: TBitmap;
APath: TPathData;
APadding: single;
begin
ABmp := TBitmap.Create(Round(ARect.Width * GetScreenScale), Round(ARect.Height * GetScreenScale));
try
ABmp.Clear(claNull);
ABmp.BitmapScale := GetScreenScale;
ABmp.Canvas.BeginScene;
ABmp.Canvas.StrokeThickness := GetScreenScale*2;
ABmp.Canvas.Stroke.Color := AColor;
ABmp.Canvas.StrokeJoin := TStrokeJoin.Miter;
APadding := GetScreenScale;
APath := TPathData.Create;
try
APath.MoveTo(PointF(ABmp.Width / 2, ABmp.Height-APadding));
APath.LineTo(PointF(ABmp.Width-APadding, (ABmp.Height/2)));
APath.LineTo(PointF(ABmp.Width / 2, APadding));
APath.MoveTo(PointF(ABmp.Width-APadding, (ABmp.Height/2)));
APath.ClosePath;
ABmp.Canvas.DrawPath(APath, 1);
finally
FreeAndNil(APath);
end;
ABmp.Canvas.EndScene;
ACanvas.DrawBitmap(ABmp, RectF(0, 0, ABmp.Width, ABmp.Height), ARect, 1, False);
finally
FreeAndNil(ABmp);
end;
end;
initialization
_ScreenScale := 0;
ATextLayout := TTextLayoutManager.DefaultTextLayout.Create;
finalization
FreeAndNil(ATextLayout);
end.
|
unit Desktop;
interface
uses
Classes, Controls,
LrObserverList, LrDocument;
type
TDesktop = class(TList)
private
FIndex: Integer;
FLastIndex: Integer;
FNilDocument: TLrDocument;
FDocumentObservers: TLrObserverList;
FOnDocumentsChanged: TNotifyEvent;
FOnCurrentChanged: TNotifyEvent;
protected
function GetCurrent: TLrDocument;
function GetDocuments(inIndex: Integer): TLrDocument;
function GoodIndex: Boolean;
procedure CurrentChanged;
procedure DocumentsChanged;
procedure DocumentChange(inSender: TObject);
procedure RemoveDocument(inDocument: TLrDocument);
procedure SetCurrent(inDocument: TLrDocument);
procedure SetDocuments(inIndex: Integer; const Value: TLrDocument);
procedure SetIndex(const Value: Integer);
procedure SetOnCurrentChanged(const Value: TNotifyEvent);
procedure SetOnDocumentsChanged(const Value: TNotifyEvent);
procedure ValidateCurrent;
public
constructor Create;
destructor Destroy; override;
function CloseAll: Boolean;
function StartCloseCurrent: Boolean;
function FindDocument(const inDocument: TLrDocument): Integer; overload;
function FindDocument(const inFilename: string): TLrDocument; overload;
function FinishCloseCurrent: Boolean;
procedure AddDocument(inDocument: TLrDocument);
procedure AddDocumentObserver(inEvent: TNotifyEvent);
procedure RemoveDocumentObserver(inEvent: TNotifyEvent);
property Current: TLrDocument read GetCurrent write SetCurrent;
property Documents[inIndex: Integer]: TLrDocument read GetDocuments
write SetDocuments;
property Index: Integer read FIndex write SetIndex;
property LastIndex: Integer read FLastIndex write FLastIndex;
property OnCurrentChanged: TNotifyEvent read FOnCurrentChanged
write SetOnCurrentChanged;
property OnDocumentsChanged: TNotifyEvent read FOnDocumentsChanged
write SetOnDocumentsChanged;
end;
implementation
{ TDesktop }
constructor TDesktop.Create;
begin
FIndex := -1;
FNilDocument := TLrDocument.Create;
FDocumentObservers := TLrObserverList.Create;
end;
destructor TDesktop.Destroy;
begin
FDocumentObservers.Free;
FNilDocument.Free;
inherited;
end;
procedure TDesktop.AddDocumentObserver(inEvent: TNotifyEvent);
begin
FDocumentObservers.Add(inEvent);
end;
procedure TDesktop.RemoveDocumentObserver(inEvent: TNotifyEvent);
begin
FDocumentObservers.Remove(inEvent);
end;
procedure TDesktop.SetOnDocumentsChanged(const Value: TNotifyEvent);
begin
FOnDocumentsChanged := Value;
end;
procedure TDesktop.SetOnCurrentChanged(const Value: TNotifyEvent);
begin
FOnCurrentChanged := Value;
end;
procedure TDesktop.CurrentChanged;
begin
// if Assigned(FOnCurrentChanged) then
// FOnCurrentChanged(Self);
end;
procedure TDesktop.DocumentsChanged;
begin
if Assigned(OnDocumentsChanged) then
OnDocumentsChanged(Self);
end;
function TDesktop.GoodIndex: Boolean;
begin
Result := (Index >= 0) and (Index < Count);
end;
procedure TDesktop.AddDocument(inDocument: TLrDocument);
begin
Add(inDocument);
//inDocument.OnChange := DocumentChange;
DocumentsChanged;
Index := Pred(Count);
//Project.DocumentOpened(inDocument);
end;
procedure TDesktop.RemoveDocument(inDocument: TLrDocument);
begin
//Project.DocumentClosed(inDocument);
Remove(inDocument);
end;
function TDesktop.GetDocuments(inIndex: Integer): TLrDocument;
begin
Result := TLrDocument(Items[inIndex]);
end;
procedure TDesktop.SetDocuments(inIndex: Integer;
const Value: TLrDocument);
begin
Items[inIndex] := Value;
end;
function TDesktop.FindDocument(const inFilename: string): TLrDocument;
var
i: Integer;
begin
Result := nil;
for i := 0 to Pred(Count) do
if Documents[i].Filename = inFilename then
begin
Result := Documents[i];
break;
end;
end;
function TDesktop.FindDocument(const inDocument: TLrDocument): Integer;
var
i: Integer;
begin
Result := -1;
for i := 0 to Pred(Count) do
if Documents[i] = inDocument then
begin
Result := i;
break;
end;
end;
procedure TDesktop.SetIndex(const Value: Integer);
begin
Current.Deactivate;
FIndex := Value;
DocumentsChanged;
//CurrentChanged;
Current.Activate;
end;
function TDesktop.GetCurrent: TLrDocument;
begin
if GoodIndex then
Result := Documents[Index]
else
Result := FNilDocument;
end;
procedure TDesktop.SetCurrent(inDocument: TLrDocument);
begin
Index := FindDocument(inDocument);
end;
procedure TDesktop.ValidateCurrent;
begin
if not GoodIndex then
Index := Pred(Count)
else begin
DocumentsChanged;
//CurrentChanged;
Current.Activate;
end;
end;
function TDesktop.StartCloseCurrent: Boolean;
begin
Result := Current.Close;
end;
function TDesktop.FinishCloseCurrent: Boolean;
begin
Current.Deactivate;
Result := Current.Closed;
if Result then
begin
Current.Free;
RemoveDocument(Current);
end;
ValidateCurrent;
end;
function TDesktop.CloseAll: Boolean;
var
i: Integer;
begin
Result := true;
Current.Deactivate;
i := Pred(Count);
while (i > 0) and Result do
begin
// True result to Close method indicates only that the close
// was not cancelled. It does not indicate that the
// document actually is closed.
// Check Closed property to test for true closure.
Result := Documents[i].Close;
if Result then
begin
if Documents[i].Closed then
begin
Documents[i].Free;
RemoveDocument(Documents[i]);
//DocumentsChanged;
end;
Dec(i);
end;
end;
//DocumentsChanged;
ValidateCurrent;
end;
procedure TDesktop.DocumentChange(inSender: TObject);
begin
FDocumentObservers.Notify(inSender);
end;
end.
|
unit FastRGB;
// TFastRGB
// Gordon Alex Cowie <gfody@jps.net>
// www.jps.net/gfody
// shared properties for TFastBMP,TFastDDB,TFast256
interface
type
TFColor = record b,g,r:Byte end;
PFColor =^TFColor;
TLine = array[0..0]of TFColor;
PLine =^TLine;
TPLines = array[0..0]of PLine;
PPLines =^TPLines;
TFastRGB=class
Gap, // RowInc - Width
RowInc, // width in bytes
Size, // size of Bits
Width, // width in pixels
Height: Integer;
Pixels: PPLines;
Bits: Pointer;
procedure SetSize(fWidth,fHeight:Integer); virtual; abstract;
procedure Draw(fdc,x,y:Integer); virtual; abstract;
procedure Stretch(fdc,x,y,w,h:Integer); virtual; abstract;
procedure DrawRect(fdc,x,y,w,h,sx,sy:Integer); virtual; abstract;
procedure StretchRect(fdc,x,y,w,h,sx,sy,sw,sh:Integer); virtual; abstract;
procedure TileDraw(fdc,x,y,w,h:Integer); virtual; abstract;
procedure Resize(Dst:TFastRGB); virtual; abstract;
procedure SmoothResize(Dst:TFastRGB); virtual; abstract;
procedure CopyRect(Dst:TFastRGB;x,y,w,h,sx,sy:Integer); virtual; abstract;
procedure Tile(Dst:TFastRGB); virtual; abstract;
end;
const //colors dur
tfBlack : TFColor=(b:0;g:0;r:0);
tfMaroon : TFColor=(b:0;g:0;r:128);
tfGreen : TFColor=(b:0;g:128;r:0);
tfOlive : TFColor=(b:0;g:128;r:128);
tfNavy : TFColor=(b:128;g:0;r:0);
tfPurple : TFColor=(b:128;g:0;r:128);
tfTeal : TFColor=(b:128;g:128;r:0);
tfGray : TFColor=(b:128;g:128;r:128);
tfSilver : TFColor=(b:192;g:192;r:192);
tfRed : TFColor=(b:0;g:0;r:255);
tfLime : TFColor=(b:0;g:255;r:0);
tfYellow : TFColor=(b:0;g:255;r:255);
tfBlue : TFColor=(b:255;g:0;r:0);
tfFuchsia : TFColor=(b:255;g:0;r:255);
tfAqua : TFColor=(b:255;g:255;r:0);
tfLtGray : TFColor=(b:192;g:192;r:192);
tfDkGray : TFColor=(b:128;g:128;r:128);
tfWhite : TFColor=(b:255;g:255;r:255);
function FRGB(r,g,b:Byte):TFColor;
function IntToColor(i:Integer):TFColor;
function IntToByte(i:Integer):Byte;
function TrimInt(i,Min,Max:Integer):Integer;
implementation
function FRGB(r,g,b:Byte):TFColor;
begin
Result.b:=b;
Result.g:=g;
Result.r:=r;
end;
function IntToColor(i:Integer):TFColor;
begin
Result.b:=i shr 16;
Result.g:=i shr 8;
Result.r:=i;
end;
function IntToByte(i:Integer):Byte;
begin
if i>255 then Result:=255
else if i<0 then Result:=0
else Result:=i;
end;
function TrimInt(i,Min,Max:Integer):Integer;
begin
if i>Max then Result:=Max
else if i<Min then Result:=Min
else Result:=i;
end;
end.
|
{ Thread safe generic queue implementation with optional async notification
of main thread, WaitWor, non-blocking or blocking Get() with Timeout, etc.
Copyright (C) 2017 Bernd Kreuss <prof7bit@gmail.com>
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version with the following modification:
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent modules,and
to copy and distribute the resulting executable under terms of your choice,
provided that you also meet, for each linked independent module, the terms
and conditions of the license of that module. An independent module is a
module which is not derived from or based on this library. If you modify
this library, you may extend this exception to your version of the library,
but you are not obligated to do so. If you do not wish to do so, delete this
exception statement from your version.
This 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 Library General Public License
for more details.
You should have received a copy of the GNU Library General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
unit LockedQueue;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, gdeque, syncobjs;
type
TQueueEventProc = procedure of object;
{ TLockedQueue }
generic TLockedQueue<T> = class
type
TData = specialize TDeque<T>;
PT = ^T;
public
OnDataAvailable: TQueueEventProc;
constructor Create;
destructor Destroy; override;
function Get(out Element: T; Timeout: Cardinal): Boolean;
function Get(out Element: T): Boolean;
procedure Put(Element: T);
procedure PutArray(FirstElement: PT; Count: SizeUint);
procedure PutFront(Element: T);
procedure Lock;
procedure Unlock;
function Size: SizeUint;
function IsEmpty: Boolean;
function WaitFor(Timeout: Cardinal): TWaitResult;
private
FData: TData;
FLock: TCriticalSection;
FEvent: TEvent;
procedure CallOnDataSync;
procedure CallOnDataAsync;
end;
implementation
{ TTSQueue }
constructor TLockedQueue.Create;
begin
FData := TData.Create();
FLock := TCriticalSection.Create;
FEvent := TSimpleEvent.Create;
end;
destructor TLockedQueue.Destroy;
begin
FEvent.Free;
FLock.Free;
FData.Free;
inherited Destroy;
end;
function TLockedQueue.Get(out Element: T; Timeout: Cardinal): Boolean;
begin
Result := False;
if WaitFor(Timeout) = wrSignaled then begin
Lock;
Result := Get(Element);
Unlock;
end;
end;
procedure TLockedQueue.Lock;
begin
FLock.Acquire;
end;
procedure TLockedQueue.Unlock;
begin
FLock.Release;
end;
procedure TLockedQueue.Put(Element: T);
begin
Lock;
FData.PushBack(Element);
if Size() = 1 then begin
FEvent.SetEvent;
CallOnDataSync;
end;
Unlock;
end;
procedure TLockedQueue.PutArray(FirstElement: PT; Count: SizeUint);
var
I: Integer;
begin
Lock;
for I := 0 to Count - 1 do begin
FData.PushBack(FirstElement[I]);
end;
if Size() = Count then begin
FEvent.SetEvent;
CallOnDataSync;
end;
Unlock;
end;
procedure TLockedQueue.PutFront(Element: T);
begin
Lock;
FData.PushFront(Element);
if Size() = 1 then begin
FEvent.SetEvent;
CallOnDataSync;
end;
Unlock;
end;
function TLockedQueue.Get(out Element: T): Boolean;
begin
Result := False;
Lock;
if not IsEmpty then begin
Element := FData.Front();
FData.PopFront();
Result := True;
if IsEmpty then
FEvent.ResetEvent;
end;
Unlock;
end;
function TLockedQueue.Size: SizeUint;
begin
Result := FData.Size;
end;
function TLockedQueue.IsEmpty: Boolean;
begin
Result := FData.IsEmpty();
end;
function TLockedQueue.WaitFor(Timeout: Cardinal): TWaitResult;
begin
Result := FEvent.WaitFor(Timeout);
end;
procedure TLockedQueue.CallOnDataSync;
begin
if Assigned(OnDataAvailable) then
TThread.Queue(nil, @CallOnDataAsync);
end;
procedure TLockedQueue.CallOnDataAsync;
begin
if Assigned(OnDataAvailable) then
OnDataAvailable;
end;
end.
|
unit ini_Unit_Meas_Form;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Db, FIBDataSet, pFIBDataSet, Buttons, ToolWin, ComCtrls, Grids, DBGrids,
FIBQuery, pFIBQuery, pFIBStoredProc, Menus, ActnList,
cxInplaceContainer, cxTL, cxControls, cxGraphics, cxCustomData, cxStyles,
cxTextEdit, ib_externals, Variants, FIBDatabase, pFIBDatabase,
cxClasses, cxGridTableView, pUtils, ImgList;
type
Tini_Unit_Meas_Form1 = class(TForm)
ToolBar1: TToolBar;
AddButton: TSpeedButton;
DelButton: TSpeedButton;
EditButton: TSpeedButton;
RefreshButton: TSpeedButton;
CloseButton: TSpeedButton;
StoredProc: TpFIBStoredProc;
SelectButton: TSpeedButton;
Query: TpFIBQuery;
PopupMenu: TPopupMenu;
AddPopup: TMenuItem;
EditPopup: TMenuItem;
DelPopup: TMenuItem;
N4: TMenuItem;
RefreshPopup: TMenuItem;
SelectPopup: TMenuItem;
ActionList: TActionList;
ActionMod: TAction;
ActionDel: TAction;
ActionAdd: TAction;
ActionSel: TAction;
ActionRefresh: TAction;
ActionExit: TAction;
TreeList: TcxTreeList;
id_group_unitm_Column: TcxTreeListColumn;
name_group_unitm_name_unit_meas_Column: TcxTreeListColumn;
short_name_Column: TcxTreeListColumn;
id_unit_meas_Column: TcxTreeListColumn;
Coefficient_Column: TcxTreeListColumn;
Database: TpFIBDatabase;
pFIBTransaction1: TpFIBTransaction;
cxStyleRepository1: TcxStyleRepository;
cxStyle1: TcxStyle;
cxStyle2: TcxStyle;
cxStyle3: TcxStyle;
cxStyle4: TcxStyle;
cxStyle5: TcxStyle;
cxStyle6: TcxStyle;
cxStyle7: TcxStyle;
cxStyle8: TcxStyle;
cxStyle9: TcxStyle;
cxStyle10: TcxStyle;
cxStyle11: TcxStyle;
cxStyle12: TcxStyle;
cxStyle13: TcxStyle;
cxStyle14: TcxStyle;
cxStyle15: TcxStyle;
cxStyle16: TcxStyle;
cxStyle17: TcxStyle;
cxStyle18: TcxStyle;
cxStyle19: TcxStyle;
cxStyle20: TcxStyle;
cxStyle21: TcxStyle;
cxStyle22: TcxStyle;
cxStyle23: TcxStyle;
cxStyle24: TcxStyle;
cxStyle25: TcxStyle;
cxStyle26: TcxStyle;
cxStyle27: TcxStyle;
GridTableViewStyleSheetDevExpress: TcxGridTableViewStyleSheet;
TreeListStyleSheetDevExpress: TcxTreeListStyleSheet;
N1: TMenuItem;
ImageList1: TImageList;
procedure CloseButtonClick(Sender: TObject);
procedure RefreshButtonClick(Sender: TObject);
procedure AddButtonClick(Sender: TObject);
procedure DelButtonClick(Sender: TObject);
procedure EditButtonClick(Sender: TObject);
procedure SelectButtonClick(Sender: TObject);
procedure DBGrid1DblClick(Sender: TObject);
procedure DBGrid1KeyPress(Sender: TObject; var Key: Char);
procedure FormDestroy(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure SelectUnitMeas(Node: TcxTreeListNode);
procedure TreeListDblClick(Sender: TObject);
procedure TreeListKeyPress(Sender: TObject; var Key: Char);
procedure AddPopupClick(Sender: TObject);
procedure EditPopupClick(Sender: TObject);
procedure DelPopupClick(Sender: TObject);
procedure RefreshPopupClick(Sender: TObject);
procedure SelectPopupClick(Sender: TObject);
procedure ActionModExecute(Sender: TObject);
procedure ActionDelExecute(Sender: TObject);
procedure ActionAddExecute(Sender: TObject);
procedure ActionSelExecute(Sender: TObject);
procedure ActionRefreshExecute(Sender: TObject);
procedure Refresh(id_Group, id_Unit, index : integer);
procedure ActionExitExecute(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure TreeListKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
public
id_pos : integer;
destructor Destroy; override;
function tagShow(SpravOptions : pUtils.TSpravOptions; id_Group_UnitMeas : integer) : pUtils.TResultArray;
end;
var
ini_Unit_Meas_Form1 : Tini_Unit_Meas_Form1;
Options : TSpravOptions;
idGroupUnitM : integer;
id_UnitM_Add_Param : integer;
id_Group_UnitM_Add_Param : integer;
KeyboardLayout : string = '00000419';
function ShowSprav2(AOwner : TComponent; DBHandle : PVoid; fs : TFormStyle; id_unit_meas : int64) : Variant; stdcall;
exports ShowSprav2;
implementation
uses ini_Unit_Meas_Form_Add, ini_Group_UnitM_Unit_Meas,
ini_Group_UnitM_Form_Add, ini_Group_unitM_Form;
{$R *.DFM}
function ShowSprav2(AOwner : TComponent; DBHandle : PVoid; fs : TFormStyle; id_unit_meas : int64) : Variant; stdcall;
var
SpravForm : Tini_Unit_Meas_Form1;
res : TResultArray;
begin
SpravForm := Tini_Unit_Meas_Form1.Create(AOwner);
SpravForm.Database.Handle := DBHandle;
SpravForm.FormStyle := fs;
SpravForm.id_pos := id_unit_meas;
Result := NULL;
if fs = fsNormal then begin
if SpravForm.ShowModal = mrOK then begin
Result := VarArrayOf([SpravForm.TreeList.FocusedNode.Values[1], SpravForm.TreeList.FocusedNode.Values[2], SpravForm.TreeList.FocusedNode.Values[3]]);
end;
end;
end;
destructor Tini_Unit_Meas_Form1.Destroy;
begin
ini_Unit_Meas_Form1 := nil;
inherited;
end;
function Tini_Unit_Meas_Form1.tagShow(SpravOptions : TSpravOptions;
id_Group_UnitMeas : integer) : pUtils.TResultArray;
var
mr : integer;
idVar : integer;
TextVar : string;
CoefVar : integer;
begin
if ini_Unit_Meas_Form1 <> nil then begin
if not SpravOptions.isModal then ini_Unit_Meas_Form1.Show;
Exit;
end;
Options := SpravOptions;
Application.CreateForm(Tini_Unit_Meas_Form1, ini_Unit_Meas_Form1);
idGroupUnitM := id_Group_UnitMeas;
SetLength(Result, 0);
if Options.isModal then begin
mr := ini_Unit_Meas_Form1.ShowModal;
if mr = mrOK then begin
idVar := ini_Unit_Meas_Form1.TreeList.FocusedNode.Values[1];
TextVar := ini_Unit_Meas_Form1.TreeList.FocusedNode.Values[3];
CoefVar := ini_Unit_Meas_Form1.TreeList.FocusedNode.Values[4];
SetLength(Result, 3);
Result[0] := idVar;
Result[1] := TextVar;
Result[2] := CoefVar;
end;
end else begin
ini_Unit_Meas_Form1.FormStyle := fsMDIChild;
ini_Unit_Meas_Form1.Show;
end;
end;
procedure Tini_Unit_Meas_Form1.Refresh(id_Group, id_Unit, index : integer);
var
Node : TcxTreeListNode;
id_Group_UnitM : integer;
Name_Group_UnitM : string;
i : integer;
begin
TreeList.Clear;
Query.SQL.Text := 'select * from PUB_SP_GROUP_UNITM_VIEW';
Query.ExecQuery;
if Query.RecordCount = 0 then begin
Query.Close;
Exit;
end;
while not Query.Eof do begin
id_Group_UnitM := Query.FieldByName('ID_GROUP_UNITM').AsInteger;
Name_Group_UnitM := Query.FieldByName('NAME_GROUP_UNITM').AsString;
if idGroupUnitM > 0 then
if id_Group_UnitM <> idGroupUnitM then begin
Query.Next;
Continue;
end;
Node := TreeList.Add;
Node.Values[0] := id_Group_UnitM;
Node.Values[1] := -1;
Node.Values[2] := Name_Group_UnitM;
Node.AddChild;
Query.Next;
end;
Query.Close;
for i := 0 to TreeList.Count - 1 do begin
SelectUnitMeas(TreeList.Items[i]);
end;
i := 0;
if id_Group > 0 then begin
while i < TreeList.LastNode.AbsoluteIndex do
if TreeList.Nodes.AbsoluteItems[i].Values[0] = id_Group then begin
TreeList.Nodes.AbsoluteItems[i].Focused := True;
Break;
end
else Inc(i);
end
else if id_Unit > 0 then begin
while i < TreeList.LastNode.AbsoluteIndex do
if TreeList.Nodes.AbsoluteItems[i].Values[1] = id_Unit then begin
TreeList.Nodes.AbsoluteItems[i].Focused := True;
Break;
end
else Inc(i);
end
else if index > 0 then
if TreeList.Nodes.AbsoluteItems[Index] <> nil then TreeList.Nodes.AbsoluteItems[Index].Focused := True;
end;
procedure Tini_Unit_Meas_Form1.SelectUnitMeas(Node: TcxTreeListNode);
var
id_Group_UnitM : integer;
id_Unit_Meas : integer;
Name_Unit_Meas : string;
Short_Name : string;
Coefficient : integer;
Child : TcxTreeListNode;
begin
id_Group_UnitM := Node.Values[0];
Query.SQL.Text := 'select * from PUB_SP_UNIT_MEAS_SELECT(' + IntToStr(id_Group_UnitM) + ')';
Query.ExecQuery;
Node.DeleteChildren;
if Query.RecordCount = 0 then begin
Query.Close;
Exit;
end;
while not Query.eof do begin
id_Unit_Meas := Query.FieldByName('ID_UNIT_MEAS').AsInteger;
Name_Unit_Meas := Query.FieldByName('NAME_UNIT_MEAS').AsString;
Short_Name := Query.FieldByName('SHORT_NAME').AsString;
Coefficient := Query.FieldByName('COEFFICIENT').AsInteger;
Child := Node.AddChild;
Child.Values[0] := -1;
Child.Values[1] := id_Unit_Meas;
Child.Values[2] := Name_Unit_Meas;
Child.Values[3] := Short_Name;
Child.Values[4] := Coefficient;
Query.Next;
end;
Query.Close;
end;
procedure Tini_Unit_Meas_Form1.CloseButtonClick(Sender: TObject);
begin
if Options.isModal then ModalResult := mrCancel
else Close;
end;
procedure Tini_Unit_Meas_Form1.RefreshButtonClick(Sender: TObject);
begin
if TreeList.FocusedNode = nil then
Refresh(-1, -1, -1)
else
Refresh(-1, -1, TreeList.FocusedNode.AbsoluteIndex);
end;
procedure Tini_Unit_Meas_Form1.AddButtonClick(Sender: TObject);
var
AddForm : Tini_Group_UnitM_Form_Add1;
GrpForm : Tini_Group_UnitM_Unit_Meas1;
begin
GrpForm := Tini_Group_UnitM_Unit_Meas1.Create(Self);
if TreeList.FocusedNode <> nil then
if TreeList.FocusedNode.Values[0] < -1 then GrpForm.RadioGroup1.ItemIndex := 1
else GrpForm.RadioGroup1.ItemIndex := 0;
GrpForm.ShowModal;
if GrpForm.ModalResult = mrOk then begin
if GrpForm.RadioGroup1.ItemIndex = 0 then begin
Addform := Tini_Group_UnitM_Form_Add1.Create(Self);
Addform.Caption := 'Додати групу одиниць вимірювання';
Addform.ShowModal;
if Addform.ModalResult = mrOk then begin
StoredProc.Transaction.StartTransaction;
StoredProc.ExecProcedure('PUB_SP_GROUP_UNIT_ADD', [Addform.Name_Group_UnitM.Text]);
id_Group_UnitM_Add_Param := StoredProc.Fields[0].AsInteger;
StoredProc.Transaction.Commit;
Refresh(StoredProc.Fields[0].AsInteger, -1, -1);
end;
end
else begin
if ini_Unit_Meas_Form_Add1 <> nil then exit;
ini_Unit_Meas_Form_Add1:=Tini_Unit_Meas_Form_Add1.Create(self);
ini_Unit_Meas_Form_Add1.DBHandle:=Database.Handle;
ini_Unit_Meas_Form_Add1.Caption := 'Додати одиниці вимірювання';
if TreeList.FocusedNode.Values[0] >= 0 then begin
ini_Unit_Meas_Form_Add1.Name_Group_UnitM.Text := TreeList.FocusedNode.values[2];
ini_Unit_Meas_Form_Add1.id_Group_UnitM := TreeList.FocusedNode.values[0];
end
else begin
ini_Unit_Meas_Form_Add1.Name_Group_UnitM.Text := TreeList.FocusedNode.Parent.Values[2];
ini_Unit_Meas_Form_Add1.id_Group_UnitM := TreeList.FocusedNode.Parent.Values[0];
end;
ini_Unit_Meas_Form_Add1.ShowModal;
if ini_Unit_Meas_Form_Add1.ModalResult = mrOk then begin
StoredProc.Transaction.StartTransaction;
StoredProc.ExecProcedure('PUB_SP_UNIT_MEAS_ADD', [ini_Unit_Meas_Form_Add1.id_Group_UnitM,
ini_Unit_Meas_Form_Add1.Name_Unit_Meas.Text, ini_Unit_Meas_Form_Add1.Short_Name.Text,
ini_Unit_Meas_Form_Add1.Coefficient.Text]);
id_UnitM_Add_Param := StoredProc.Fields[0].AsInteger;
StoredProc.Transaction.Commit;
Refresh(-1, StoredProc.Fields[0].AsInteger, -1);
end;
end;
end;
end;
procedure Tini_Unit_Meas_Form1.DelButtonClick(Sender: TObject);
var
exp : boolean;
begin
if TreeList.FocusedNode = nil then Exit;
exp := TreeList.FocusedNode.Expanded;
if not exp then TreeList.FocusedNode.Expand(false);
if TreeList.FocusedNode.Count <> 0 then begin
if not exp then TreeList.FocusedNode.Collapse(false);
agShowMessage('Спочатку ви повинні знищити усі одиниці вимірювання,'
+' що належить до цієї групи одиниць вимірювання.');
exit;
end;
if TreeList.FocusedNode.Values[0] >= 0 then begin
case agMessageDlg('Знищення запису', 'Ви дійсно бажаєте знищити цю групу одиниць виміру?', mtConfirmation, [mbYes, mbNo]) of
mrYes :
begin
StoredProc.Transaction.StartTransaction;
StoredProc.ExecProcedure('PUB_SP_GROUP_UNIT_DEL', [TreeList.FocusedNode.Values[0]]);
StoredProc.Transaction.Commit;
Refresh(-1, -1, TreeList.FocusedNode.AbsoluteIndex);
end;
mrNo : Exit;
end;
end
else begin
case agMessageDlg('Знищення запису', 'Ви дійсно бажаєте знищити цю одиницю виміру?', mtConfirmation, [mbYes, mbNo]) of
mrYes :
begin
StoredProc.Transaction.StartTransaction;
StoredProc.ExecProcedure('PUB_SP_UNIT_MEAS_DEL', [TreeList.FocusedNode.Values[1]]);
StoredProc.Transaction.Commit;
Refresh(-1, -1, TreeList.FocusedNode.AbsoluteIndex);
end;
mrNo : Exit;
end;
end;
end;
procedure Tini_Unit_Meas_Form1.EditButtonClick(Sender: TObject);
var
AddForm : Tini_Group_UnitM_Form_Add1;
AddForm2 : Tini_Unit_Meas_Form_Add1;
begin
if TreeList.FocusedNode = nil then Exit;
if TreeList.FocusedNode.Values[0] >= 0 then begin
AddForm := Tini_Group_UnitM_Form_Add1.Create(Self);
AddForm.Caption := 'Змінити групу одиниць вимірювання';
AddForm.Name_Group_UnitM.Text := TreeList.FocusedNode.Values[2];
id_Group_UnitM := TreeList.FocusedNode.Values[0];
AddForm.ShowModal;
if AddForm.ModalResult = mrOk then begin
StoredProc.Transaction.StartTransaction;
StoredProc.ExecProcedure('PUB_SP_GROUP_UNIT_MODIFY', [ini_Group_UnitM_Form_Add.id_Group_UnitM,
AddForm.Name_Group_UnitM.Text]);
StoredProc.Transaction.Commit;
Refresh(TreeList.FocusedNode.Values[0], -1, -1);
end;
end
else begin
AddForm2 := Tini_Unit_Meas_Form_Add1.Create(Self);
AddForm2.Caption := 'Змінити одиниці вимірювання';
AddForm2.Name_Unit_Meas.Text := TreeList.FocusedNode.Values[2];
AddForm2.Name_Group_UnitM.Text := TreeList.FocusedNode.Parent.Values[2];
AddForm2.Short_Name.Text := TreeList.FocusedNode.Values[3];
AddForm2.Coefficient.Text := TreeList.FocusedNode.Values[4];
AddForm2.id_Group_UnitM := TreeList.FocusedNode.Parent.Values[0];
AddForm2.ShowModal;
if AddForm2.ModalResult = mrOk then begin
StoredProc.Transaction.StartTransaction;
StoredProc.ExecProcedure('PUB_SP_UNIT_MEAS_MODIFY', [TreeList.FocusedNode.Values[1],
AddForm2.id_Group_UnitM, AddForm2.Name_Unit_Meas.Text,
AddForm2.Short_Name.Text, AddForm2.Coefficient.Text]);
StoredProc.Transaction.Commit;
Refresh(-1, TreeList.FocusedNode.Values[1], -1);
end;
end;
end;
procedure Tini_Unit_Meas_Form1.SelectButtonClick(Sender: TObject);
begin
if TreeList.FocusedNode.Values[0] >= 0 then exit;
ModalResult := mrOk;
end;
procedure Tini_Unit_Meas_Form1.DBGrid1DblClick(Sender: TObject);
begin
SelectButtonClick(Sender);
end;
procedure Tini_Unit_Meas_Form1.DBGrid1KeyPress(Sender: TObject;
var Key: Char);
begin
if Key = #13 then SelectButtonClick(Sender);
end;
procedure Tini_Unit_Meas_Form1.FormDestroy(Sender: TObject);
begin
ini_Unit_Meas_Form1 := NIL;
end;
procedure Tini_Unit_Meas_Form1.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action := caFree;
end;
procedure Tini_Unit_Meas_Form1.TreeListDblClick(Sender: TObject);
begin
if (TreeList.FocusedNode.Values[0] < 0) and SelectButton.Visible then SelectButtonClick(Sender);
end;
procedure Tini_Unit_Meas_Form1.TreeListKeyPress(Sender: TObject;
var Key: Char);
begin
// if Key = #27 then CloseButtonClick(Sender);
// if (TreeList.FocusedNode.Values[0] < 0) and SelectButton.Visible and (Key = #13) then SelectButtonClick(Sender);
end;
procedure Tini_Unit_Meas_Form1.AddPopupClick(Sender: TObject);
begin
AddButtonClick(Sender);
end;
procedure Tini_Unit_Meas_Form1.EditPopupClick(Sender: TObject);
begin
EditButtonClick(Sender);
end;
procedure Tini_Unit_Meas_Form1.DelPopupClick(Sender: TObject);
begin
DelButtonClick(Sender);
end;
procedure Tini_Unit_Meas_Form1.RefreshPopupClick(Sender: TObject);
begin
RefreshButtonClick(Sender);
end;
procedure Tini_Unit_Meas_Form1.SelectPopupClick(Sender: TObject);
begin
SelectButtonClick(Sender);
end;
procedure Tini_Unit_Meas_Form1.ActionModExecute(Sender: TObject);
begin
EditButtonClick(Sender);
end;
procedure Tini_Unit_Meas_Form1.ActionDelExecute(Sender: TObject);
begin
DelButtonClick(Sender);
end;
procedure Tini_Unit_Meas_Form1.ActionAddExecute(Sender: TObject);
begin
AddButtonClick(Sender);
end;
procedure Tini_Unit_Meas_Form1.ActionSelExecute(Sender: TObject);
begin
TreeListDblClick(Sender);
end;
procedure Tini_Unit_Meas_Form1.ActionRefreshExecute(Sender: TObject);
begin
RefreshButtonClick(Sender);
end;
procedure Tini_Unit_Meas_Form1.ActionExitExecute(Sender: TObject);
begin
CloseButtonClick(Sender);
end;
procedure Tini_Unit_Meas_Form1.FormShow(Sender: TObject);
var i:Integer;
begin
RefreshButtonClick(Sender);
TreeList.FullExpand;
LoadKeyboardLayout(PAnsiChar('00000419'), KLF_ACTIVATE or KLF_SUBSTITUTE_OK)
end;
procedure Tini_Unit_Meas_Form1.TreeListKeyDown(Sender: TObject;
var Key: Word; Shift: TShiftState);
begin
if Key=VK_RETURN then
SelectButtonClick(self);
end;
end.
|
{ ****************************************************************************** }
{ * Generic list of any type (TGenericStructList). * }
{ ****************************************************************************** }
{ * https://zpascal.net * }
{ * https://github.com/PassByYou888/zAI * }
{ * https://github.com/PassByYou888/ZServer4D * }
{ * https://github.com/PassByYou888/PascalString * }
{ * https://github.com/PassByYou888/zRasterization * }
{ * https://github.com/PassByYou888/CoreCipher * }
{ * https://github.com/PassByYou888/zSound * }
{ * https://github.com/PassByYou888/zChinese * }
{ * https://github.com/PassByYou888/zExpression * }
{ * https://github.com/PassByYou888/zGameWare * }
{ * https://github.com/PassByYou888/zAnalysis * }
{ * https://github.com/PassByYou888/FFMPEG-Header * }
{ * https://github.com/PassByYou888/zTranslate * }
{ * https://github.com/PassByYou888/InfiniteIoT * }
{ * https://github.com/PassByYou888/FastMD5 * }
{ ****************************************************************************** }
{
Based on FPC FGL unit, copyright by FPC team.
License of FPC RTL is the same as our engine (modified LGPL,
see COPYING.txt for details).
Fixed to compile also under FPC 2.4.0 and 2.2.4.
Some small comfortable methods added.
}
unit FPCGenericStructlist;
{$IFDEF FPC}
{$mode objfpc}{$H+}
{$IF defined(VER2_2)} {$DEFINE OldSyntax} {$IFEND}
{$IF defined(VER2_4)} {$DEFINE OldSyntax} {$IFEND}
{$define HAS_ENUMERATOR}
{$ifdef VER2_2} {$undef HAS_ENUMERATOR} {$endif}
{$ifdef VER2_4_0} {$undef HAS_ENUMERATOR} {$endif}
{ Just undef enumerator always, in FPC 2.7.1 it's either broken
or I shouldn't overuse TFPGListEnumeratorSpec. }
{$undef HAS_ENUMERATOR}
{ FPC < 2.6.0 had buggy version of the Extract function,
also with different interface, see http://bugs.freepascal.org/view.php?id=19960. }
{$define HAS_EXTRACT}
{$ifdef VER2_2} {$undef HAS_EXTRACT} {$endif}
{$ifdef VER2_4} {$undef HAS_EXTRACT} {$endif}
{$ENDIF FPC}
interface
{$IFDEF FPC}
uses fgl;
type
{ Generic list of types that are compared by CompareByte.
This is equivalent to TFPGList, except it doesn't override IndexOf,
so your type doesn't need to have a "=" operator built-in inside FPC.
When calling IndexOf or Remove, it will simply compare values using
CompareByte, this is what TFPSList.IndexOf uses.
This way it works to create lists of records, vectors (constant size arrays),
old-style TP objects, and also is suitable to create a list of methods
(since for methods, the "=" is broken, for Delphi compatibility,
see http://bugs.freepascal.org/view.php?id=9228).
We also add some trivial helper methods like @link(Add) and @link(L). }
generic TGenericsList<t> = class(TFPSList)
private
type
TCompareFunc = function(const Item1, Item2: t): Integer;
TTypeList = array[0..MaxGListSize] of t;
PTypeList = ^TTypeList;
{$ifdef HAS_ENUMERATOR} TFPGListEnumeratorSpec = specialize TFPGListEnumerator<t>; {$endif}
{$ifndef OldSyntax}protected var{$else}
{$ifdef PASDOC}protected var{$else} { PasDoc can't handle "var protected", and I don't know how/if they should be handled? }
var protected{$endif}{$endif} FOnCompare: TCompareFunc;
procedure CopyItem(Src, dest: Pointer); override;
procedure Deref(Item: Pointer); override;
function Get(index: Integer): t; {$ifdef CLASSESINLINE} inline; {$endif}
function GetList: PTypeList; {$ifdef CLASSESINLINE} inline; {$endif}
function ItemPtrCompare(Item1, Item2: Pointer): Integer;
procedure Put(index: Integer; const Item: t); {$ifdef CLASSESINLINE} inline; {$endif}
public
constructor Create;
function Add(const Item: t): Integer; {$ifdef CLASSESINLINE} inline; {$endif}
{$ifdef HAS_EXTRACT} function Extract(const Item: t): t; {$ifdef CLASSESINLINE} inline; {$endif} {$endif}
function First: t; {$ifdef CLASSESINLINE} inline; {$endif}
{$ifdef HAS_ENUMERATOR} function GetEnumerator: TFPGListEnumeratorSpec; {$ifdef CLASSESINLINE} inline; {$endif} {$endif}
function IndexOf(const Item: t): Integer;
procedure Insert(index: Integer; const Item: t); {$ifdef CLASSESINLINE} inline; {$endif}
function Last: t; {$ifdef CLASSESINLINE} inline; {$endif}
{$ifndef OldSyntax}
procedure Assign(Source: TGenericsList);
{$endif OldSyntax}
function Remove(const Item: t): Integer; {$ifdef CLASSESINLINE} inline; {$endif}
procedure Sort(Compare: TCompareFunc);
property Items[index: Integer]: t read Get write Put; default;
property List: PTypeList read GetList;
property ListData: PTypeList read GetList;
end;
{$ENDIF FPC}
implementation
{$IFDEF FPC}
constructor TGenericsList.Create;
begin
inherited Create(SizeOf(t));
end;
procedure TGenericsList.CopyItem(Src, dest: Pointer);
begin
t(dest^) := t(Src^);
end;
procedure TGenericsList.Deref(Item: Pointer);
begin
Finalize(t(Item^));
end;
function TGenericsList.Get(index: Integer): t;
begin
Result := t(inherited Get(index)^);
end;
function TGenericsList.GetList: PTypeList;
begin
Result := PTypeList(FList);
end;
function TGenericsList.ItemPtrCompare(Item1, Item2: Pointer): Integer;
begin
Result := FOnCompare(t(Item1^), t(Item2^));
end;
procedure TGenericsList.Put(index: Integer; const Item: t);
begin
inherited Put(index, @Item);
end;
function TGenericsList.Add(const Item: t): Integer;
begin
Result := inherited Add(@Item);
end;
{$ifdef HAS_EXTRACT}
function TGenericsList.Extract(const Item: t): t;
begin
inherited Extract(@Item, @Result);
end;
{$endif}
function TGenericsList.First: t;
begin
Result := t(inherited First^);
end;
{$ifdef HAS_ENUMERATOR}
function TGenericsList.GetEnumerator: TFPGListEnumeratorSpec;
begin
Result := TFPGListEnumeratorSpec.Create(Self);
end;
{$endif}
function TGenericsList.IndexOf(const Item: t): Integer;
begin
Result := inherited IndexOf(@Item);
end;
procedure TGenericsList.Insert(index: Integer; const Item: t);
begin
t(inherited Insert(index)^) := Item;
end;
function TGenericsList.Last: t;
begin
Result := t(inherited Last^);
end;
{$ifndef OldSyntax}
procedure TGenericsList.Assign(Source: TGenericsList);
var
i: Integer;
begin
Clear;
for i := 0 to Source.Count - 1 do
Add(Source[i]);
end;
{$endif OldSyntax}
function TGenericsList.Remove(const Item: t): Integer;
begin
Result := IndexOf(Item);
if Result >= 0 then
Delete(Result);
end;
procedure TGenericsList.Sort(Compare: TCompareFunc);
begin
FOnCompare := Compare;
inherited Sort(@ItemPtrCompare);
end;
{$ENDIF FPC}
end.
|
unit MapDataSetField;
interface
uses
System.SysUtils, System.Classes, Vcl.DBCtrls, Data.DB, MapEvent, Vcl.Controls,
System.UITypes, System.Generics.Collections, DBDateTime;
type
TMapDataSetField = class(TComponent)
private
FDataSource: TDataSource;
FLimitEditCharacters: Integer;
FOnCreateDbEdit: TOnCreateDbEdit;
FConteiner: TWinControl;
FOnCreateDbMemo: TOnCreateDbMemo;
FCharCase: TEditCharCase;
FOnCreateDbDateTime: TOnCreateDbDateTime;
FOnCreateDbCheckBox: TOnCreateDbCheckBox;
FMultipleSelection: TStrings;
FOnCreateDbComboBox: TOnCreateDbComboBox;
procedure SetDataSource(const Value: TDataSource);
procedure SetOnCreateDbEdit(const Value: TOnCreateDbEdit);
procedure SetLimitEditCharacters(const Value: Integer);
procedure SetConteiner(const Value: TWinControl);
procedure SetOnCreateDbMemo(const Value: TOnCreateDbMemo);
procedure SetCharCase(const Value: TEditCharCase);
procedure SetOnCreateDbDateTime(const Value: TOnCreateDbDateTime);
procedure SetOnCreateDbCheckBox(const Value: TOnCreateDbCheckBox);
procedure SetMultipleSelection(const Value: TStrings);
procedure SetOnCreateDbComboBox(const Value: TOnCreateDbComboBox);
strict private
FListDbEdit: TList<TDBEdit>;
FListDbMemo: TList<TDBMemo>;
FListDbDateTime: TList<TDBDateTime>;
FListDbComboBox: TList<TDBComboBox>;
FListDbCheckBox: TList<TDBCheckBox>;
procedure CreateDbEdit(AField: TField);
procedure CreateDbMemo(AField: TField);
procedure CreateDbDateTime(AField: TField);
procedure CreateDbComboBox(AField: TField);
procedure CreateDbCheckBox(AField: TField);
protected
public
procedure Open();
procedure Close();
procedure MapDataSet(AActive: Boolean = False);
procedure SetValueField(AFieldName: string; AValue: string);
function GetDataSet: TDataSet;
function GetDbEdit(AName: string): TDBEdit;
function GetDbMemo(AName: string): TDBMemo;
function GetDbDateTime(AName: string): TDBDateTime;
function GetDbCombobox(AName: string): TDBComboBox;
function GetDbCheckBox(AName: string): TDBCheckBox;
function GetField(AFieldName: string): TField;
function GetValueField(AFieldName: string): string;
property ListDbEdit: TList<TDBEdit> read FListDbEdit;
property ListDbMemo: TList<TDBMemo> read FListDbMemo;
property ListDbDateTime: TList<TDBDateTime> read FListDbDateTime;
property ListDbComboBox: TList<TDBComboBox> read FListDbComboBox;
property ListDbCheckBox: TList<TDBCheckBox> read FListDbCheckBox;
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property CharCase: TEditCharCase read FCharCase write SetCharCase
default TEditCharCase.ecNormal;
property MultipleSelection: TStrings read FMultipleSelection
write SetMultipleSelection;
property Conteiner: TWinControl read FConteiner write SetConteiner;
property LimitEditCharacters: Integer read FLimitEditCharacters
write SetLimitEditCharacters;
property DataSource: TDataSource read FDataSource write SetDataSource;
property OnCreateDbEdit: TOnCreateDbEdit read FOnCreateDbEdit
write SetOnCreateDbEdit;
property OnCreateDbMemo: TOnCreateDbMemo read FOnCreateDbMemo
write SetOnCreateDbMemo;
property OnCreateDbDateTime: TOnCreateDbDateTime read FOnCreateDbDateTime
write SetOnCreateDbDateTime;
property OnCreateDbComboBox: TOnCreateDbComboBox read FOnCreateDbComboBox
write SetOnCreateDbComboBox;
property OnCreateDbCheckBox: TOnCreateDbCheckBox read FOnCreateDbCheckBox
write SetOnCreateDbCheckBox;
end;
implementation
uses
Vcl.StdCtrls;
const
DB_NAME_EDIT = 'edt';
DB_NAME_MEMO = 'mmo';
DB_NAME_DATETIME = 'dtm';
DB_NAME_COMBOBOX = 'cbx';
DB_NAME_CHECKBOX = 'chx';
{ TMapDataSetField }
procedure TMapDataSetField.Close;
begin
GetDataSet.Close;
end;
constructor TMapDataSetField.Create(AOwner: TComponent);
begin
inherited;
FListDbEdit := TList<TDBEdit>.Create;
FListDbMemo := TList<TDBMemo>.Create;
FListDbDateTime := TList<TDBDateTime>.Create;
FListDbComboBox := TList<TDBComboBox>.Create;
FListDbCheckBox := TList<TDBCheckBox>.Create;
FMultipleSelection := TStringList.Create;
end;
procedure TMapDataSetField.CreateDbCheckBox(AField: TField);
var
LConteiner: TWinControl;
LDbCheckBox: TDBCheckBox;
begin
LDbCheckBox := TDBCheckBox.Create(Self);
LDbCheckBox.AlignWithMargins := True;
LDbCheckBox.DataSource := DataSource;
LDbCheckBox.DataField := AField.FieldName;
LDbCheckBox.Caption := AField.DisplayLabel;
LDbCheckBox.Name := DB_NAME_CHECKBOX + LowerCase(AField.FieldName);
LConteiner := TWinControl.Create(Conteiner);
LConteiner.Width := AField.DisplayWidth * 4;
LConteiner.Height := 48;
LDbCheckBox.Parent := LConteiner;
LConteiner.Parent := Conteiner;
FListDbCheckBox.Add(LDbCheckBox);
LDbCheckBox.Align := TAlign.alBottom;
if Assigned(FOnCreateDbCheckBox) then
OnCreateDbCheckBox(LDbCheckBox, LConteiner);
end;
procedure TMapDataSetField.CreateDbComboBox(AField: TField);
var
LLabel: TLabel;
LDbComboBox: TDBComboBox;
LConteiner: TWinControl;
begin
LLabel := TLabel.Create(Self);
LLabel.Align := TAlign.alTop;
LLabel.AlignWithMargins := True;
LLabel.Caption := AField.DisplayLabel;
LDbComboBox := TDBComboBox.Create(Self);
LDbComboBox.Align := TAlign.alTop;
LDbComboBox.AlignWithMargins := True;
LDbComboBox.DataSource := DataSource;
LDbComboBox.DataField := AField.FieldName;
LDbComboBox.Name := DB_NAME_COMBOBOX + LowerCase(AField.FieldName);
FListDbComboBox.Add(LDbComboBox);
LConteiner := TWinControl.Create(Conteiner);
LConteiner.Width := AField.DisplayWidth * 4;
LConteiner.Height := LLabel.Height + LDbComboBox.Height + 10;
LLabel.Parent := LConteiner;
LDbComboBox.Parent := LConteiner;
LConteiner.Parent := Conteiner;
if Assigned(FOnCreateDbComboBox) then
OnCreateDbComboBox(LDbComboBox, LLabel, LConteiner);
end;
procedure TMapDataSetField.CreateDbDateTime(AField: TField);
var
LLabel: TLabel;
LDbDateTime: TDBDateTime;
LConteiner: TWinControl;
begin
LLabel := TLabel.Create(Self);
LLabel.Align := TAlign.alTop;
LLabel.AlignWithMargins := True;
LLabel.Caption := AField.DisplayLabel;
LDbDateTime := TDBDateTime.Create(Self);
LDbDateTime.Align := TAlign.alTop;
LDbDateTime.AlignWithMargins := True;
LDbDateTime.DataSource := DataSource;
LDbDateTime.DataField := AField.FieldName;
LDbDateTime.Name := DB_NAME_DATETIME + LowerCase(AField.FieldName);
FListDbDateTime.Add(LDbDateTime);
LConteiner := TWinControl.Create(Conteiner);
LConteiner.Width := AField.DisplayWidth * 4;
LConteiner.Height := LLabel.Height + LDbDateTime.Height + 10;
LLabel.Parent := LConteiner;
LDbDateTime.Parent := LConteiner;
LConteiner.Parent := Conteiner;
if Assigned(FOnCreateDbDateTime) then
OnCreateDbDateTime(LDbDateTime, LLabel, LConteiner);
end;
procedure TMapDataSetField.CreateDbEdit(AField: TField);
var
LLabel: TLabel;
LDbEdit: TDBEdit;
LConteiner: TWinControl;
begin
LLabel := TLabel.Create(Self);
LLabel.Align := TAlign.alTop;
LLabel.AlignWithMargins := True;
LLabel.Caption := AField.DisplayLabel;
LDbEdit := TDBEdit.Create(Self);
LDbEdit.Align := TAlign.alTop;
LDbEdit.AlignWithMargins := True;
LDbEdit.DataSource := DataSource;
LDbEdit.DataField := AField.FieldName;
LDbEdit.CharCase := CharCase;
LDbEdit.Name := DB_NAME_EDIT + LowerCase(AField.FieldName);
FListDbEdit.Add(LDbEdit);
LConteiner := TWinControl.Create(Conteiner);
LConteiner.Width := AField.DisplayWidth * 4;
LConteiner.Height := LLabel.Height + LDbEdit.Height + 10;
LLabel.Parent := LConteiner;
LDbEdit.Parent := LConteiner;
LConteiner.Parent := Conteiner;
if Assigned(FOnCreateDbEdit) then
OnCreateDbEdit(LDbEdit, LLabel, LConteiner);
end;
procedure TMapDataSetField.CreateDbMemo(AField: TField);
var
LLabel: TLabel;
LDbMemo: TDBMemo;
LConteiner: TWinControl;
begin
LLabel := TLabel.Create(Self);
LLabel.Align := TAlign.alTop;
LLabel.AlignWithMargins := True;
LLabel.Caption := AField.DisplayLabel;
LDbMemo := TDBMemo.Create(Self);
LDbMemo.Align := TAlign.alTop;
LDbMemo.AlignWithMargins := True;
LDbMemo.DataSource := DataSource;
LDbMemo.DataField := AField.FieldName;
LDbMemo.Name := DB_NAME_MEMO + LowerCase(AField.FieldName);
FListDbMemo.Add(LDbMemo);
LConteiner := TWinControl.Create(Conteiner);
LConteiner.Width := AField.DisplayWidth * 4;
LConteiner.Height := LLabel.Height + LDbMemo.Height + 10;
LLabel.Parent := LConteiner;
LDbMemo.Parent := LConteiner;
LConteiner.Parent := Conteiner;
if Assigned(FOnCreateDbMemo) then
OnCreateDbMemo(LDbMemo, LLabel, LConteiner);
end;
destructor TMapDataSetField.Destroy;
begin
FreeAndNil(FListDbEdit);
FreeAndNil(FListDbMemo);
FreeAndNil(FListDbDateTime);
FreeAndNil(FListDbComboBox);
FreeAndNil(FListDbCheckBox);
FreeAndNil(FMultipleSelection);
inherited;
end;
function TMapDataSetField.GetDataSet: TDataSet;
begin
Result := DataSource.DataSet;
end;
function TMapDataSetField.GetDbCheckBox(AName: string): TDBCheckBox;
var
LDB: TDBCheckBox;
begin
Result := nil;
for LDB in FListDbCheckBox do
begin
if LDB.Name = DB_NAME_CHECKBOX + LowerCase(AName) then
Result := LDB;
end;
if Result = nil then
raise Exception.Create('BDCheckBox ' + AName + ' Not Found');
end;
function TMapDataSetField.GetDbCombobox(AName: string): TDBComboBox;
var
LDB: TDBComboBox;
begin
Result := nil;
for LDB in FListDbComboBox do
begin
if LDB.Name = DB_NAME_COMBOBOX + LowerCase(AName) then
Result := LDB;
end;
if Result = nil then
raise Exception.Create('DBComboBox ' + AName + ' Not Found');
end;
function TMapDataSetField.GetDbDateTime(AName: string): TDBDateTime;
var
LDB: TDBDateTime;
begin
Result := nil;
for LDB in FListDbDateTime do
begin
if LDB.Name = DB_NAME_DATETIME + LowerCase(AName) then
Result := LDB;
end;
if Result = nil then
raise Exception.Create('DBDateTime ' + AName + ' Not Found');
end;
function TMapDataSetField.GetDbEdit(AName: string): TDBEdit;
var
LDB: TDBEdit;
begin
Result := nil;
for LDB in FListDbEdit do
begin
if LDB.Name = DB_NAME_EDIT + LowerCase(AName) then
Result := LDB;
end;
if Result = nil then
raise Exception.Create('DBEdit ' + AName + ' Not Found');
end;
function TMapDataSetField.GetDbMemo(AName: string): TDBMemo;
var
LDB: TDBMemo;
begin
Result := nil;
for LDB in FListDbMemo do
begin
if LDB.Name = DB_NAME_MEMO + LowerCase(AName) then
Result := LDB;
end;
if Result = nil then
raise Exception.Create('DBMemo ' + AName + ' Not Found');
end;
function TMapDataSetField.GetField(AFieldName: string): TField;
begin
Result := DataSource.DataSet.FindField(AFieldName);
if Result = nil then
raise Exception.Create('Field Not Found');
end;
function TMapDataSetField.GetValueField(AFieldName: string): string;
begin
Result := GetField(AFieldName).AsString;
end;
procedure TMapDataSetField.MapDataSet(AActive: Boolean);
var
LField: TField;
LDataSet: TDataSet;
begin
if FConteiner = nil then
raise Exception.Create('Conteiner Not Found');
if FDataSource = nil then
raise Exception.Create('DataSource Not Found');
if FDataSource.DataSet = nil then
raise Exception.Create('DataSet Not Found');
LDataSet := GetDataSet;
for LField in LDataSet.Fields do
begin
if LField.Visible = False then
Continue;
if FMultipleSelection.IndexOf(LField.FieldName) <> -1 then
CreateDbComboBox(LField)
else
begin
case LField.DataType of
ftString, ftSmallint, ftInteger, ftFloat, ftBCD, ftCurrency, ftFmtMemo,
ftWideString, ftLargeint, ftFMTBcd, ftFixedWideChar, ftWideMemo,
ftLongWord, ftShortint, ftSingle, ftMemo, ftTime, ftOraTimeStamp,
ftTimeStamp:
begin
if LField.Size <= LimitEditCharacters then
CreateDbEdit(LField)
else
CreateDbMemo(LField);
end;
ftBoolean:
CreateDbCheckBox(LField);
ftDateTime, ftDate:
CreateDbDateTime(LField);
end;
end;
end;
LDataSet.Active := AActive;
end;
procedure TMapDataSetField.Open;
begin
GetDataSet.Open;
end;
procedure TMapDataSetField.SetCharCase(const Value: TEditCharCase);
begin
FCharCase := Value;
end;
procedure TMapDataSetField.SetConteiner(const Value: TWinControl);
begin
FConteiner := Value;
end;
procedure TMapDataSetField.SetDataSource(const Value: TDataSource);
begin
FDataSource := Value;
end;
procedure TMapDataSetField.SetLimitEditCharacters(const Value: Integer);
begin
FLimitEditCharacters := Value;
end;
procedure TMapDataSetField.SetMultipleSelection(const Value: TStrings);
begin
FMultipleSelection.Assign(Value);
end;
procedure TMapDataSetField.SetOnCreateDbCheckBox(const Value
: TOnCreateDbCheckBox);
begin
FOnCreateDbCheckBox := Value;
end;
procedure TMapDataSetField.SetOnCreateDbComboBox(const Value
: TOnCreateDbComboBox);
begin
FOnCreateDbComboBox := Value;
end;
procedure TMapDataSetField.SetOnCreateDbDateTime(const Value
: TOnCreateDbDateTime);
begin
FOnCreateDbDateTime := Value;
end;
procedure TMapDataSetField.SetOnCreateDbEdit(const Value: TOnCreateDbEdit);
begin
FOnCreateDbEdit := Value;
end;
procedure TMapDataSetField.SetOnCreateDbMemo(const Value: TOnCreateDbMemo);
begin
FOnCreateDbMemo := Value;
end;
procedure TMapDataSetField.SetValueField(AFieldName, AValue: string);
var
LDataSet: TDataSet;
begin
LDataSet := GetDataSet;
if not LDataSet.Active then
raise Exception.Create('DataSet Not Active');
LDataSet.Edit;
LDataSet.FieldByName(AFieldName).AsString := AValue;
LDataSet.Post;
end;
end.
|
unit UExporta;
interface
type
TExportacao = class abstract
public
function Exportar: String; virtual; abstract;
end;
TExportaTexto = class(TExportacao)
private
FTexto: String;
procedure SetTexto(const Value: String);
published
property Texto: String read FTexto write SetTexto;
end;
TExportaInvertido = class (TExportaTexto)
// if(quantidade > 0)
{
//retornará a quantidade de letras correspondente a este parâmetro
}
// else{
//retornará o texto invertido
end;
implementation
{ TExportaTexto }
procedure TExportaTexto.SetTexto(const Value: String);
begin
if Length(Value) <> 0 then
FTexto := Value;
end;
end.
|
//
// VXScene Component Library, based on GLScene http://glscene.sourceforge.net
//
{
Texture-based Lens flare object.
}
unit VXS.TexLensFlare;
interface
{$I VXScene.inc}
uses
System.Classes,
VXS.OpenGL,
VXS.Scene,
VXS.VectorGeometry,
VXS.PersistentClasses,
VXS.Objects,
VXS.Texture,
VXS.Context,
VXS.RenderContextInfo,
VXS.BaseClasses,
VXS.State,
VXS.VectorTypes;
type
TVXTextureLensFlare = class(TVXBaseSceneObject)
private
FSize: integer;
FCurrSize: Single;
FNumSecs: integer;
FAutoZTest: boolean;
//used for internal calculation
FDeltaTime: Double;
FImgSecondaries: TVXTexture;
FImgRays: TVXTexture;
FImgRing: TVXTexture;
FImgGlow: TVXTexture;
FSeed: Integer;
procedure SetImgGlow(const Value: TVXTexture);
procedure SetImgRays(const Value: TVXTexture);
procedure SetImgRing(const Value: TVXTexture);
procedure SetImgSecondaries(const Value: TVXTexture);
procedure SetSeed(const Value: Integer);
protected
procedure SetSize(aValue: integer);
procedure SetNumSecs(aValue: integer);
procedure SetAutoZTest(aValue: boolean);
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure BuildList(var rci: TVXRenderContextInfo); override;
procedure DoProgress(const progressTime: TVXProgressTimes); override;
published
// MaxRadius of the flare.
property Size: integer read FSize write SetSize default 50;
// Random seed
property Seed: Integer read FSeed write SetSeed;
// Number of secondary flares.
property NumSecs: integer read FNumSecs write SetNumSecs default 8;
// Number of segments used when rendering circles.
//property Resolution: integer read FResolution write SetResolution default 64;
property AutoZTest: boolean read FAutoZTest write SetAutoZTest default True;
// The Textures
property ImgGlow: TVXTexture read FImgGlow write SetImgGlow;
property ImgRays: TVXTexture read FImgRays write SetImgRays;
property ImgRing: TVXTexture read FImgRing write SetImgRing;
property ImgSecondaries: TVXTexture read FImgSecondaries write SetImgSecondaries;
property ObjectsSorting;
property Position;
property Visible;
property OnProgress;
property Behaviours;
property Effects;
end;
//------------------------------------------------------------------
implementation
//------------------------------------------------------------------
// ------------------
// ------------------ TVXTextureLensFlare ------------------
// ------------------
constructor TVXTextureLensFlare.Create(AOwner: TComponent);
begin
inherited;
Randomize;
FSeed := Random(2000) + 465;
// Set default parameters:
ObjectStyle := ObjectStyle + [osDirectDraw, osNoVisibilityCulling];
FSize := 50;
FCurrSize := FSize;
FNumSecs := 8;
FAutoZTest := True;
FImgRays := TVXTexture.Create(Self);
FImgSecondaries := TVXTexture.Create(Self);
FImgRing := TVXTexture.Create(Self);
FImgGlow := TVXTexture.Create(Self);
end;
procedure TVXTextureLensFlare.SetSize(aValue: integer);
begin
if FSize <> aValue then
begin
FSize := aValue;
FCurrSize := FSize;
StructureChanged;
end;
end;
procedure TVXTextureLensFlare.SetNumSecs(aValue: integer);
begin
if FNumSecs <> aValue then
begin
FNumSecs := aValue;
StructureChanged;
end;
end;
procedure TVXTextureLensFlare.SetAutoZTest(aValue: boolean);
begin
if FAutoZTest <> aValue then
begin
FAutoZTest := aValue;
StructureChanged;
end;
end;
procedure TVXTextureLensFlare.BuildList(var rci: TVXRenderContextInfo);
var
v, rv, screenPos, posVector: TAffineVector;
depth, rnd: Single;
flag: Boolean;
i: Integer;
CurrentBuffer: TVXSceneBuffer;
begin
CurrentBuffer := TVXSceneBuffer(rci.buffer);
SetVector(v, AbsolutePosition);
// are we looking towards the flare?
rv := VectorSubtract(v, PAffineVector(@rci.cameraPosition)^);
if VectorDotProduct(rci.cameraDirection, rv) > 0 then
begin
// find out where it is on the screen.
screenPos := CurrentBuffer.WorldToScreen(v);
if (screenPos.X < rci.viewPortSize.cx) and (screenPos.X >= 0)
and (screenPos.Y < rci.viewPortSize.cy) and (screenPos.Y >= 0) then
begin
if FAutoZTest then
begin
depth := CurrentBuffer.GetPixelDepth(Round(ScreenPos.X),
Round(rci.viewPortSize.cy - ScreenPos.Y));
// but is it behind something?
if screenPos.Z >= 1 then
flag := (depth >= 1)
else
flag := (depth >= screenPos.Z);
end
else
flag := True;
end
else
flag := False;
end
else
flag := False;
MakeVector(posVector,
screenPos.X - rci.viewPortSize.cx / 2,
screenPos.Y - rci.viewPortSize.cy / 2, 0);
// make the glow appear/disappear progressively
if Flag then
if FCurrSize < FSize then
FCurrSize := FCurrSize + FDeltaTime * 200 {FSize * 4};
if not Flag then
if FCurrSize > 0 then
FCurrSize := FCurrSize - FDeltaTime * 200 {FSize * 4};
if FCurrSize <= 0 then
Exit;
// Prepare matrices
glMatrixMode(GL_MODELVIEW);
glPushMatrix;
glLoadMatrixf(@CurrentBuffer.BaseProjectionMatrix);
glMatrixMode(GL_PROJECTION);
glPushMatrix;
glLoadIdentity;
glScalef(2 / rci.viewPortSize.cx, 2 / rci.viewPortSize.cy, 1);
rci.VXStates.Disable(stLighting);
rci.VXStates.Disable(stDepthTest);
rci.VXStates.Enable(stBlend);
rci.VXStates.SetBlendFunc(bfOne, bfOne);
//Rays and Glow on Same Position
glPushMatrix;
glTranslatef(posVector.X, posVector.Y, posVector.Z);
if not ImgGlow.Disabled and Assigned(ImgGlow.Image) then
begin
ImgGlow.Apply(rci);
glBegin(GL_QUADS);
glTexCoord2f(0, 0);
glVertex3f(-FCurrSize, -FCurrSize, 0);
glTexCoord2f(1, 0);
glVertex3f(FCurrSize, -FCurrSize, 0);
glTexCoord2f(1, 1);
glVertex3f(FCurrSize, FCurrSize, 0);
glTexCoord2f(0, 1);
glVertex3f(-FCurrSize, FCurrSize, 0);
glEnd;
ImgGlow.UnApply(rci);
end;
if not ImgRays.Disabled and Assigned(ImgRays.Image) then
begin
ImgRays.Apply(rci);
glBegin(GL_QUADS);
glTexCoord2f(0, 0);
glVertex3f(-FCurrSize, -FCurrSize, 0);
glTexCoord2f(1, 0);
glVertex3f(FCurrSize, -FCurrSize, 0);
glTexCoord2f(1, 1);
glVertex3f(FCurrSize, FCurrSize, 0);
glTexCoord2f(0, 1);
glVertex3f(-FCurrSize, FCurrSize, 0);
glEnd;
ImgRays.UnApply(rci);
end;
glPopMatrix;
if not ImgRing.Disabled and Assigned(ImgRing.Image) then
begin
glPushMatrix;
glTranslatef(posVector.X * 1.1, posVector.Y * 1.1, posVector.Z);
ImgRing.Apply(rci);
glBegin(GL_QUADS);
glTexCoord2f(0, 0);
glVertex3f(-FCurrSize, -FCurrSize, 0);
glTexCoord2f(1, 0);
glVertex3f(FCurrSize, -FCurrSize, 0);
glTexCoord2f(1, 1);
glVertex3f(FCurrSize, FCurrSize, 0);
glTexCoord2f(0, 1);
glVertex3f(-FCurrSize, FCurrSize, 0);
glEnd;
ImgRing.UnApply(rci);
glPopMatrix;
end;
if not ImgSecondaries.Disabled and Assigned(ImgSecondaries.Image) then
begin
RandSeed := FSeed;
glPushMatrix;
ImgSecondaries.Apply(rci);
for i := 1 to FNumSecs do
begin
rnd := 2 * Random - 1;
v := PosVector;
if rnd < 0 then
ScaleVector(V, rnd)
else
ScaleVector(V, 0.8 * rnd);
glPushMatrix;
glTranslatef(v.X, v.Y, v.Z);
rnd := random * 0.5 + 0.1;
glBegin(GL_QUADS);
glTexCoord2f(0, 0);
glVertex3f(-FCurrSize * rnd, -FCurrSize * rnd, 0);
glTexCoord2f(1, 0);
glVertex3f(FCurrSize * rnd, -FCurrSize * rnd, 0);
glTexCoord2f(1, 1);
glVertex3f(FCurrSize * rnd, FCurrSize * rnd, 0);
glTexCoord2f(0, 1);
glVertex3f(-FCurrSize * rnd, FCurrSize * rnd, 0);
glEnd;
glPopMatrix
end;
ImgSecondaries.UnApply(rci);
glPopMatrix;
end;
// restore state
glPopMatrix;
glMatrixMode(GL_MODELVIEW);
glPopMatrix;
if Count > 0 then
Self.RenderChildren(0, Count - 1, rci);
end;
procedure TVXTextureLensFlare.DoProgress(const progressTime: TVXProgressTimes);
begin
FDeltaTime := progressTime.deltaTime;
inherited;
end;
procedure TVXTextureLensFlare.SetImgGlow(const Value: TVXTexture);
begin
FImgGlow.Assign(Value);
StructureChanged;
end;
procedure TVXTextureLensFlare.SetImgRays(const Value: TVXTexture);
begin
FImgRays.Assign(Value);
StructureChanged;
end;
procedure TVXTextureLensFlare.SetImgRing(const Value: TVXTexture);
begin
FImgRing.Assign(Value);
StructureChanged;
end;
procedure TVXTextureLensFlare.SetImgSecondaries(const Value: TVXTexture);
begin
FImgSecondaries.Assign(Value);
StructureChanged;
end;
destructor TVXTextureLensFlare.Destroy;
begin
FImgRays.Free;
FImgSecondaries.Free;
FImgRing.Free;
FImgGlow.Free;
inherited;
end;
procedure TVXTextureLensFlare.SetSeed(const Value: Integer);
begin
FSeed := Value;
StructureChanged;
end;
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
RegisterClasses([TVXTextureLensFlare]);
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, clisted, nfsCheckListEdit, contnrs;
type
TCheckObj = class
Id: Integer;
Kurz: string;
Text: string;
Checked: Boolean;
end;
type
TForm1 = class(TForm)
edt: TNfsCheckListEdit;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure edtStateChanged(Sender: TObject; var aText: string);
private
fList: TObjectList;
function getAnzeigeText(aValue: string): string;
public
{ Public-Deklarationen }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
function ErzeugeCheckObj(aKurz, aText: String; var aId: Integer): TCheckObj;
begin
inc(aId);
Result := TCheckObj.Create;
Result.Id := aId;
Result.Kurz := aKurz;
Result.Text := aKurz + ' ' + aText;
Result.Checked := false;
fList.Add(Result);
end;
var
i1: Integer;
begin
fList := TObjectList.Create;
i1 := 0;
ErzeugeCheckObj('1', 'Test1', i1);
ErzeugeCheckObj('2', 'Test2', i1);
ErzeugeCheckObj('3', 'Test3', i1);
ErzeugeCheckObj('4', 'Test4', i1);
ErzeugeCheckObj('5', 'Test5', i1);
ErzeugeCheckObj('6', 'Test6', i1);
ErzeugeCheckObj('7', 'Test7', i1);
ErzeugeCheckObj('8', 'Test8', i1);
ErzeugeCheckObj('9', 'Test9', i1);
ErzeugeCheckObj('10', 'Test10', i1);
ErzeugeCheckObj('10', 'Test11', i1);
ErzeugeCheckObj('10', 'Test12', i1);
ErzeugeCheckObj('10', 'Test13', i1);
edt.Clear;
for i1 := 0 to fList.Count -1 do
edt.Items.AddObject(TCheckObj(fList.Items[i1]).Text, fList.Items[i1]);
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
FreeAndNil(fList);
end;
function TForm1.getAnzeigeText(aValue: string): string;
var
s: string;
iAnfang: Integer;
iEnde: Integer;
begin
s := aValue;
iAnfang := Pos('[', s);
iEnde := Pos(']', s);
if (iAnfang > 0) and (iEnde > 0) then
s := copy(s, iAnfang+1, iEnde-iAnfang-1)
else
s := '';
Result := s;
end;
procedure TForm1.edtStateChanged(Sender: TObject; var aText: string);
var
i1: Integer;
x: TCheckObj;
begin
aText := '';
for i1 := 0 to edt.Items.Count -1 do
begin
x := TCheckObj(edt.Items.Objects[i1]);
if not edt.Checked[i1] then
continue;
if aText = '' then
aText := x.Kurz
else
aText := aText + ',' + x.Kurz;
end;
if aText > '' then
aText := '[' + aText + ']';
end;
end.
|
unit XLSHTMLDecode;
{-
********************************************************************************
******* XLSReadWriteII V3.00 *******
******* *******
******* Copyright(C) 1999,2006 Lars Arvidsson, Axolot Data *******
******* *******
******* email: components@axolot.com *******
******* URL: http://www.axolot.com *******
********************************************************************************
** Users of the XLSReadWriteII component must accept the following **
** disclaimer of warranty: **
** **
** XLSReadWriteII is supplied as is. The author disclaims all warranties, **
** expressedor implied, including, without limitation, the warranties of **
** merchantability and of fitness for any purpose. The author assumes no **
** liability for damages, direct or consequential, which may result from the **
** use of XLSReadWriteII. **
********************************************************************************
}
{$B-}
{$H+}
{$R-}
{$I XLSRWII2.inc}
interface
uses Classes, SysUtils, XLSUtils2;
function UTF8ToWideString(S: string): WideString;
function DecodeHTMLText(Text: WideString): WideString;
implementation
type THTMLChar = record
Name: string;
Value: WideChar;
end;
// Taken from http://www.w3.org/TR/REC-html40/sgml/entities.html.
const HTMLChars: array[0..252] of THTMLChar = (
// ISO 8859-1 characters
(Name: 'nbsp'; Value: #160), // no-break space = non-breaking space, U+00A0 ISOnum
(Name: 'iexcl'; Value: #161), // inverted exclamation mark, U+00A1 ISOnum
(Name: 'cent'; Value: #162), // cent sign, U+00A2 ISOnum
(Name: 'pound'; Value: #163), // pound sign, U+00A3 ISOnum
(Name: 'curren'; Value: #164), // currency sign, U+00A4 ISOnum
(Name: 'yen'; Value: #165), // yen sign = yuan sign, U+00A5 ISOnum
(Name: 'brvbar'; Value: #166), // broken bar = broken vertical bar, U+00A6 ISOnum
(Name: 'sect'; Value: #167), // section sign, U+00A7 ISOnum
(Name: 'uml'; Value: #168), // diaeresis = spacing diaeresis, U+00A8 ISOdia
(Name: 'copy'; Value: #169), // copyright sign, U+00A9 ISOnum
(Name: 'ordf'; Value: #170), // feminine ordinal indicator, U+00AA ISOnum
(Name: 'laquo'; Value: #171), // left-pointing double angle quotation mark = left pointing guillemet, U+00AB ISOnum
(Name: 'not'; Value: #172), // not sign, U+00AC ISOnum
(Name: 'shy'; Value: #173), // soft hyphen = discretionary hyphen, U+00AD ISOnum
(Name: 'reg'; Value: #174), // registered sign = registered trade mark sign, U+00AE ISOnum
(Name: 'macr'; Value: #175), // macron = spacing macron = overline = APL overbar, U+00AF ISOdia
(Name: 'deg'; Value: #176), // degree sign, U+00B0 ISOnum
(Name: 'plusmn'; Value: #177), // plus-minus sign = plus-or-minus sign, U+00B1 ISOnum
(Name: 'sup2'; Value: #178), // superscript two = superscript digit two = squared, U+00B2 ISOnum
(Name: 'sup3'; Value: #179), // superscript three = superscript digit three = cubed, U+00B3 ISOnum
(Name: 'acute'; Value: #180), // acute accent = spacing acute, U+00B4 ISOdia
(Name: 'micro'; Value: #181), // micro sign, U+00B5 ISOnum
(Name: 'para'; Value: #182), // pilcrow sign = paragraph sign, U+00B6 ISOnum
(Name: 'middot'; Value: #183), // middle dot = Georgian comma = Greek middle dot, U+00B7 ISOnum
(Name: 'cedil'; Value: #184), // cedilla = spacing cedilla, U+00B8 ISOdia
(Name: 'sup1'; Value: #185), // superscript one = superscript digit one, U+00B9 ISOnum
(Name: 'ordm'; Value: #186), // masculine ordinal indicator, U+00BA ISOnum
(Name: 'raquo'; Value: #187), // right-pointing double angle quotation mark = right pointing guillemet, U+00BB ISOnum
(Name: 'frac14'; Value: #188), // vulgar fraction one quarter = fraction one quarter, U+00BC ISOnum
(Name: 'frac12'; Value: #189), // vulgar fraction one half = fraction one half, U+00BD ISOnum
(Name: 'frac34'; Value: #190), // vulgar fraction three quarters = fraction three quarters, U+00BE ISOnum
(Name: 'iquest'; Value: #191), // inverted question mark = turned question mark, U+00BF ISOnum
(Name: 'Agrave'; Value: #192), // latin capital letter A with grave = latin capital letter A grave, U+00C0 ISOlat1
(Name: 'Aacute'; Value: #193), // latin capital letter A with acute, U+00C1 ISOlat1
(Name: 'Acirc'; Value: #194), // latin capital letter A with circumflex, U+00C2 ISOlat1
(Name: 'Atilde'; Value: #195), // latin capital letter A with tilde, U+00C3 ISOlat1
(Name: 'Auml'; Value: #196), // latin capital letter A with diaeresis, U+00C4 ISOlat1
(Name: 'Aring'; Value: #197), // latin capital letter A with ring above = latin capital letter A ring, U+00C5 ISOlat1
(Name: 'AElig'; Value: #198), // latin capital letter AE = latin capital ligature AE, U+00C6 ISOlat1
(Name: 'Ccedil'; Value: #199), // latin capital letter C with cedilla, U+00C7 ISOlat1
(Name: 'Egrave'; Value: #200), // latin capital letter E with grave, U+00C8 ISOlat1
(Name: 'Eacute'; Value: #201), // latin capital letter E with acute, U+00C9 ISOlat1
(Name: 'Ecirc'; Value: #202), // latin capital letter E with circumflex, U+00CA ISOlat1
(Name: 'Euml'; Value: #203), // latin capital letter E with diaeresis, U+00CB ISOlat1
(Name: 'Igrave'; Value: #204), // latin capital letter I with grave, U+00CC ISOlat1
(Name: 'Iacute'; Value: #205), // latin capital letter I with acute, U+00CD ISOlat1
(Name: 'Icirc'; Value: #206), // latin capital letter I with circumflex, U+00CE ISOlat1
(Name: 'Iuml'; Value: #207), // latin capital letter I with diaeresis, U+00CF ISOlat1
(Name: 'ETH'; Value: #208), // latin capital letter ETH, U+00D0 ISOlat1
(Name: 'Ntilde'; Value: #209), // latin capital letter N with tilde, U+00D1 ISOlat1
(Name: 'Ograve'; Value: #210), // latin capital letter O with grave, U+00D2 ISOlat1
(Name: 'Oacute'; Value: #211), // latin capital letter O with acute, U+00D3 ISOlat1
(Name: 'Ocirc'; Value: #212), // latin capital letter O with circumflex, U+00D4 ISOlat1
(Name: 'Otilde'; Value: #213), // latin capital letter O with tilde, U+00D5 ISOlat1
(Name: 'Ouml'; Value: #214), // latin capital letter O with diaeresis, U+00D6 ISOlat1
(Name: 'times'; Value: #215), // multiplication sign, U+00D7 ISOnum
(Name: 'Oslash'; Value: #216), // latin capital letter O with stroke = latin capital letter O slash, U+00D8 ISOlat1
(Name: 'Ugrave'; Value: #217), // latin capital letter U with grave, U+00D9 ISOlat1
(Name: 'Uacute'; Value: #218), // latin capital letter U with acute, U+00DA ISOlat1
(Name: 'Ucirc'; Value: #219), // latin capital letter U with circumflex, U+00DB ISOlat1
(Name: 'Uuml'; Value: #220), // latin capital letter U with diaeresis, U+00DC ISOlat1
(Name: 'Yacute'; Value: #221), // latin capital letter Y with acute, U+00DD ISOlat1
(Name: 'THORN'; Value: #222), // latin capital letter THORN, U+00DE ISOlat1
(Name: 'szlig'; Value: #223), // latin small letter sharp s = ess-zed, U+00DF ISOlat1
(Name: 'agrave'; Value: #224), // latin small letter a with grave = latin small letter a grave, U+00E0 ISOlat1
(Name: 'aacute'; Value: #225), // latin small letter a with acute, U+00E1 ISOlat1
(Name: 'acirc'; Value: #226), // latin small letter a with circumflex, U+00E2 ISOlat1
(Name: 'atilde'; Value: #227), // latin small letter a with tilde, U+00E3 ISOlat1
(Name: 'auml'; Value: #228), // latin small letter a with diaeresis, U+00E4 ISOlat1
(Name: 'aring'; Value: #229), // latin small letter a with ring above = latin small letter a ring, U+00E5 ISOlat1
(Name: 'aelig'; Value: #230), // latin small letter ae = latin small ligature ae, U+00E6 ISOlat1
(Name: 'ccedil'; Value: #231), // latin small letter c with cedilla, U+00E7 ISOlat1
(Name: 'egrave'; Value: #232), // latin small letter e with grave, U+00E8 ISOlat1
(Name: 'eacute'; Value: #233), // latin small letter e with acute, U+00E9 ISOlat1
(Name: 'ecirc'; Value: #234), // latin small letter e with circumflex, U+00EA ISOlat1
(Name: 'euml'; Value: #235), // latin small letter e with diaeresis, U+00EB ISOlat1
(Name: 'igrave'; Value: #236), // latin small letter i with grave, U+00EC ISOlat1
(Name: 'iacute'; Value: #237), // latin small letter i with acute, U+00ED ISOlat1
(Name: 'icirc'; Value: #238), // latin small letter i with circumflex, U+00EE ISOlat1
(Name: 'iuml'; Value: #239), // latin small letter i with diaeresis, U+00EF ISOlat1
(Name: 'eth'; Value: #240), // latin small letter eth, U+00F0 ISOlat1
(Name: 'ntilde'; Value: #241), // latin small letter n with tilde, U+00F1 ISOlat1
(Name: 'ograve'; Value: #242), // latin small letter o with grave, U+00F2 ISOlat1
(Name: 'oacute'; Value: #243), // latin small letter o with acute, U+00F3 ISOlat1
(Name: 'ocirc'; Value: #244), // latin small letter o with circumflex, U+00F4 ISOlat1
(Name: 'otilde'; Value: #245), // latin small letter o with tilde, U+00F5 ISOlat1
(Name: 'ouml'; Value: #246), // latin small letter o with diaeresis, U+00F6 ISOlat1
(Name: 'divide'; Value: #247), // division sign, U+00F7 ISOnum
(Name: 'oslash'; Value: #248), // latin small letter o with stroke, = latin small letter o slash, U+00F8 ISOlat1
(Name: 'ugrave'; Value: #249), // latin small letter u with grave, U+00F9 ISOlat1
(Name: 'uacute'; Value: #250), // latin small letter u with acute, U+00FA ISOlat1
(Name: 'ucirc'; Value: #251), // latin small letter u with circumflex, U+00FB ISOlat1
(Name: 'uuml'; Value: #252), // latin small letter u with diaeresis, U+00FC ISOlat1
(Name: 'yacute'; Value: #253), // latin small letter y with acute, U+00FD ISOlat1
(Name: 'thorn'; Value: #254), // latin small letter thorn, U+00FE ISOlat1
(Name: 'yuml'; Value: #255), // latin small letter y with diaeresis, U+00FF ISOlat1
// symbols, mathematical symbols, and Greek letters
// Latin Extended-B
(Name: 'fnof'; Value: #402), // latin small f with hook = function = florin, U+0192 ISOtech
// Greek
(Name: 'Alpha'; Value: #913), // greek capital letter alpha, U+0391
(Name: 'Beta'; Value: #914), // greek capital letter beta, U+0392
(Name: 'Gamma'; Value: #915), // greek capital letter gamma, U+0393 ISOgrk3
(Name: 'Delta'; Value: #916), // greek capital letter delta, U+0394 ISOgrk3
(Name: 'Epsilon'; Value: #917), // greek capital letter epsilon, U+0395
(Name: 'Zeta'; Value: #918), // greek capital letter zeta, U+0396
(Name: 'Eta'; Value: #919), // greek capital letter eta, U+0397
(Name: 'Theta'; Value: #920), // greek capital letter theta, U+0398 ISOgrk3
(Name: 'Iota'; Value: #921), // greek capital letter iota, U+0399
(Name: 'Kappa'; Value: #922), // greek capital letter kappa, U+039A
(Name: 'Lambda'; Value: #923), // greek capital letter lambda, U+039B ISOgrk3
(Name: 'Mu'; Value: #924), // greek capital letter mu, U+039C
(Name: 'Nu'; Value: #925), // greek capital letter nu, U+039D
(Name: 'Xi'; Value: #926), // greek capital letter xi, U+039E ISOgrk3
(Name: 'Omicron'; Value: #927), // greek capital letter omicron, U+039F
(Name: 'Pi'; Value: #928), // greek capital letter pi, U+03A0 ISOgrk3
(Name: 'Rho'; Value: #929), // greek capital letter rho, U+03A1
(Name: 'Sigma'; Value: #931), // greek capital letter sigma, U+03A3 ISOgrk3,
// there is no Sigmaf, and no U+03A2 character either
(Name: 'Tau'; Value: #932), // greek capital letter tau, U+03A4
(Name: 'Upsilon'; Value: #933), // greek capital letter upsilon, U+03A5 ISOgrk3
(Name: 'Phi'; Value: #934), // greek capital letter phi, U+03A6 ISOgrk3
(Name: 'Chi'; Value: #935), // greek capital letter chi, U+03A7
(Name: 'Psi'; Value: #936), // greek capital letter psi, U+03A8 ISOgrk3
(Name: 'Omega'; Value: #937), // greek capital letter omega, U+03A9 ISOgrk3
(Name: 'alpha'; Value: #945), // greek small letter alpha, U+03B1 ISOgrk3
(Name: 'beta'; Value: #946), // greek small letter beta, U+03B2 ISOgrk3
(Name: 'gamma'; Value: #947), // greek small letter gamma, U+03B3 ISOgrk3
(Name: 'delta'; Value: #948), // greek small letter delta, U+03B4 ISOgrk3
(Name: 'epsilon'; Value: #949), // greek small letter epsilon, U+03B5 ISOgrk3
(Name: 'zeta'; Value: #950), // greek small letter zeta, U+03B6 ISOgrk3
(Name: 'eta'; Value: #951), // greek small letter eta, U+03B7 ISOgrk3
(Name: 'theta'; Value: #952), // greek small letter theta, U+03B8 ISOgrk3
(Name: 'iota'; Value: #953), // greek small letter iota, U+03B9 ISOgrk3
(Name: 'kappa'; Value: #954), // greek small letter kappa, U+03BA ISOgrk3
(Name: 'lambda'; Value: #955), // greek small letter lambda, U+03BB ISOgrk3
(Name: 'mu'; Value: #956), // greek small letter mu, U+03BC ISOgrk3
(Name: 'nu'; Value: #957), // greek small letter nu, U+03BD ISOgrk3
(Name: 'xi'; Value: #958), // greek small letter xi, U+03BE ISOgrk3
(Name: 'omicron'; Value: #959), // greek small letter omicron, U+03BF NEW
(Name: 'pi'; Value: #960), // greek small letter pi, U+03C0 ISOgrk3
(Name: 'rho'; Value: #961), // greek small letter rho, U+03C1 ISOgrk3
(Name: 'sigmaf'; Value: #962), // greek small letter final sigma, U+03C2 ISOgrk3
(Name: 'sigma'; Value: #963), // greek small letter sigma, U+03C3 ISOgrk3
(Name: 'tau'; Value: #964), // greek small letter tau, U+03C4 ISOgrk3
(Name: 'upsilon'; Value: #965), // greek small letter upsilon, U+03C5 ISOgrk3
(Name: 'phi'; Value: #966), // greek small letter phi, U+03C6 ISOgrk3
(Name: 'chi'; Value: #967), // greek small letter chi, U+03C7 ISOgrk3
(Name: 'psi'; Value: #968), // greek small letter psi, U+03C8 ISOgrk3
(Name: 'omega'; Value: #969), // greek small letter omega, U+03C9 ISOgrk3
(Name: 'thetasym'; Value: #977), // greek small letter theta symbol, U+03D1 NEW
(Name: 'upsih'; Value: #978), // greek upsilon with hook symbol, U+03D2 NEW
(Name: 'piv'; Value: #982), // greek pi symbol, U+03D6 ISOgrk3
// General Punctuation
(Name: 'bull'; Value: #8226), // bullet = black small circle, U+2022 ISOpub,
// bullet is NOT the same as bullet operator, U+2219
(Name: 'hellip'; Value: #8230), // horizontal ellipsis = three dot leader, U+2026 ISOpub
(Name: 'prime'; Value: #8242), // prime = minutes = feet, U+2032 ISOtech
(Name: 'Prime'; Value: #8243), // double prime = seconds = inches, U+2033 ISOtech
(Name: 'oline'; Value: #8254), // overline = spacing overscore, U+203E NEW
(Name: 'frasl'; Value: #8260), // fraction slash, U+2044 NEW
// Letterlike Symbols
(Name: 'weierp'; Value: #8472), // script capital P = power set = Weierstrass p, U+2118 ISOamso
(Name: 'image'; Value: #8465), // blackletter capital I = imaginary part, U+2111 ISOamso
(Name: 'real'; Value: #8476), // blackletter capital R = real part symbol, U+211C ISOamso
(Name: 'trade'; Value: #8482), // trade mark sign, U+2122 ISOnum
(Name: 'alefsym'; Value: #8501), // alef symbol = first transfinite cardinal, U+2135 NEW
// alef symbol is NOT the same as hebrew letter alef, U+05D0 although the same
// glyph could be used to depict both characters
// Arrows
(Name: 'larr'; Value: #8592), // leftwards arrow, U+2190 ISOnum
(Name: 'uarr'; Value: #8593), // upwards arrow, U+2191 ISOnu
(Name: 'rarr'; Value: #8594), // rightwards arrow, U+2192 ISOnum
(Name: 'darr'; Value: #8595), // downwards arrow, U+2193 ISOnum
(Name: 'harr'; Value: #8596), // left right arrow, U+2194 ISOamsa
(Name: 'crarr'; Value: #8629), // downwards arrow with corner leftwards = carriage return, U+21B5 NEW
(Name: 'lArr'; Value: #8656), // leftwards double arrow, U+21D0 ISOtech
// ISO 10646 does not say that lArr is the same as the 'is implied by' arrow but
// also does not have any other charater for that function. So ? lArr can be used
// for 'is implied by' as ISOtech sugg
(Name: 'uArr'; Value: #8657), // upwards double arrow, U+21D1 ISOamsa
(Name: 'rArr'; Value: #8658), // rightwards double arrow, U+21D2 ISOtech
// ISO 10646 does not say this is the 'implies' character but does not have another
// character with this function so ? rArr can be used for 'implies' as ISOtech suggests
(Name: 'dArr'; Value: #8659), // downwards double arrow, U+21D3 ISOamsa
(Name: 'hArr'; Value: #8660), // left right double arrow, U+21D4 ISOamsa
// Mathematical Operators
(Name: 'forall'; Value: #8704), // for all, U+2200 ISOtech
(Name: 'part'; Value: #8706), // partial differential, U+2202 ISOtech
(Name: 'exist'; Value: #8707), // there exists, U+2203 ISOtech
(Name: 'empty'; Value: #8709), // empty set = null set = diameter, U+2205 ISOamso
(Name: 'nabla'; Value: #8711), // nabla = backward difference, U+2207 ISOtech
(Name: 'isin'; Value: #8712), // element of, U+2208 ISOtech
(Name: 'notin'; Value: #8713), // not an element of, U+2209 ISOtech
(Name: 'ni'; Value: #8715), // contains as member, U+220B ISOtech
(Name: 'prod'; Value: #8719), // n-ary product = product sign, U+220F ISOamsb
// prod is NOT the same character as U+03A0 'greek capital letter pi' though the
// same glyph might be used for both
(Name: 'sum'; Value: #8721), // n-ary sumation, U+2211 ISOamsb
// sum is NOT the same character as U+03A3 'greek capital letter sigma' though the
// same glyph might be used for both
(Name: 'minus'; Value: #8722), // minus sign, U+2212 ISOtech
(Name: 'lowast'; Value: #8727), // asterisk operator, U+2217 ISOtech
(Name: 'radic'; Value: #8730), // square root = radical sign, U+221A ISOtech
(Name: 'prop'; Value: #8733), // proportional to, U+221D ISOtech
(Name: 'infin'; Value: #8734), // infinity, U+221E ISOtech
(Name: 'ang'; Value: #8736), // angle, U+2220 ISOamso
(Name: 'and'; Value: #8743), // logical and = wedge, U+2227 ISOtech
(Name: 'or'; Value: #8744), // logical or = vee, U+2228 ISOtech
(Name: 'cap'; Value: #8745), // intersection = cap, U+2229 ISOtech
(Name: 'cup'; Value: #8746), // union = cup, U+222A ISOtech
(Name: 'int'; Value: #8747), // integral, U+222B ISOtech
(Name: 'there4'; Value: #8756), // therefore, U+2234 ISOtech
(Name: 'sim'; Value: #8764), // tilde operator = varies with = similar to, U+223C ISOtech
// tilde operator is NOT the same character as the tilde, U+007E, although the same
// glyph might be used to represent both
(Name: 'cong'; Value: #8773), // approximately equal to, U+2245 ISOtech
(Name: 'asymp'; Value: #8776), // almost equal to = asymptotic to, U+2248 ISOamsr
(Name: 'ne'; Value: #8800), // not equal to, U+2260 ISOtech
(Name: 'equiv'; Value: #8801), // identical to, U+2261 ISOtech
(Name: 'le'; Value: #8804), // less-than or equal to, U+2264 ISOtech
(Name: 'ge'; Value: #8805), // greater-than or equal to, U+2265 ISOtech
(Name: 'sub'; Value: #8834), // subset of, U+2282 ISOtech
(Name: 'sup'; Value: #8835), // superset of, U+2283 ISOtech
// note that nsup, 'not a superset of, U+2283' is not covered by the Symbol font
// encoding and is not included.
(Name: 'nsub'; Value: #8836), // not a subset of, U+2284 ISOamsn
(Name: 'sube'; Value: #8838), // subset of or equal to, U+2286 ISOtech
(Name: 'supe'; Value: #8839), // superset of or equal to, U+2287 ISOtech
(Name: 'oplus'; Value: #8853), // circled plus = direct sum, U+2295 ISOamsb
(Name: 'otimes'; Value: #8855), // circled times = vector product, U+2297 ISOamsb
(Name: 'perp'; Value: #8869), // up tack = orthogonal to = perpendicular, U+22A5 ISOtech
(Name: 'sdot'; Value: #8901), // dot operator, U+22C5 ISOamsb
// dot operator is NOT the same character as U+00B7 middle dot
// Miscellaneous Technical
(Name: 'lceil'; Value: #8968), // left ceiling = apl upstile, U+2308 ISOamsc
(Name: 'rceil'; Value: #8969), // right ceiling, U+2309 ISOamsc
(Name: 'lfloor'; Value: #8970), // left floor = apl downstile, U+230A ISOamsc
(Name: 'rfloor'; Value: #8971), // right floor, U+230B ISOamsc
(Name: 'lang'; Value: #9001), // left-pointing angle bracket = bra, U+2329 ISOtech
// lang is NOT the same character as U+003C 'less than' or U+2039 'single
// left-pointing angle quotation mark'
(Name: 'rang'; Value: #9002), // right-pointing angle bracket = ket, U+232A ISOtech
// rang is NOT the same character as U+003E 'greater than' or U+203A 'single
// right-pointing angle quotation mark'
// Geometric Shapes
(Name: 'loz'; Value: #9674), // lozenge, U+25CA ISOpub
// Miscellaneous Symbols
(Name: 'spades'; Value: #9824), // black spade suit, U+2660 ISOpub
// black here seems to mean filled as opposed to hollow
(Name: 'clubs'; Value: #9827), // black club suit = shamrock, U+2663 ISOpub
(Name: 'hearts'; Value: #9829), // black heart suit = valentine, U+2665 ISOpub
(Name: 'diams'; Value: #9830), // black diamond suit, U+2666 ISOpub
// markup-significant and internationalization characters
// C0 Controls and Basic Latin
(Name: 'quot'; Value: #34), // quotation mark = APL quote, U+0022 ISOnum
(Name: 'amp'; Value: #38), // ampersand, U+0026 ISOnum
(Name: 'apos'; Value: #39), // single quote
(Name: 'lt'; Value: #60), // less-than sign, U+003C ISOnum
(Name: 'gt'; Value: #62), // greater-than sign, U+003E ISOnum
// Latin Extended-A
(Name: 'OElig'; Value: #338), // latin capital ligature OE, U+0152 ISOlat2
(Name: 'oelig'; Value: #339), // latin small ligature oe, U+0153 ISOlat2
// ligature is a misnomer, this is a separate character in some languages
(Name: 'Scaron'; Value: #352), // latin capital letter S with caron, U+0160 ISOlat2
(Name: 'scaron'; Value: #353), // latin small letter s with caron, U+0161 ISOlat2
(Name: 'Yuml'; Value: #376), // latin capital letter Y with diaeresis, U+0178 ISOlat2
// Spacing Modifier Letters
(Name: 'circ'; Value: #710), // modifier letter circumflex accent, U+02C6 ISOpub
(Name: 'tilde'; Value: #732), // small tilde, U+02DC ISOdia
// General Punctuation
(Name: 'ensp'; Value: #8194), // en space, U+2002 ISOpub
(Name: 'emsp'; Value: #8195), // em space, U+2003 ISOpub
(Name: 'thinsp'; Value: #8201), // thin space, U+2009 ISOpub
(Name: 'zwnj'; Value: #8204), // zero width non-joiner, U+200C NEW RFC 2070
(Name: 'zwj'; Value: #8205), // zero width joiner, U+200D NEW RFC 2070
(Name: 'lrm'; Value: #8206), // left-to-right mark, U+200E NEW RFC 2070
(Name: 'rlm'; Value: #8207), // right-to-left mark, U+200F NEW RFC 2070
(Name: 'ndash'; Value: #8211), // en dash, U+2013 ISOpub
(Name: 'mdash'; Value: #8212), // em dash, U+2014 ISOpub
(Name: 'lsquo'; Value: #8216), // left single quotation mark, U+2018 ISOnum
(Name: 'rsquo'; Value: #8217), // right single quotation mark, U+2019 ISOnum
(Name: 'sbquo'; Value: #8218), // single low-9 quotation mark, U+201A NEW
(Name: 'ldquo'; Value: #8220), // left double quotation mark, U+201C ISOnum
(Name: 'rdquo'; Value: #8221), // right double quotation mark, U+201D ISOnum
(Name: 'bdquo'; Value: #8222), // double low-9 quotation mark, U+201E NEW
(Name: 'dagger'; Value: #8224), // dagger, U+2020 ISOpub
(Name: 'Dagger'; Value: #8225), // double dagger, U+2021 ISOpub
(Name: 'permil'; Value: #8240), // per mille sign, U+2030 ISOtech
(Name: 'lsaquo'; Value: #8249), // single left-pointing angle quotation mark, U+2039 ISO proposed
// lsaquo is proposed but not yet ISO standardized
(Name: 'rsaquo'; Value: #8250), // single right-pointing angle quotation mark, U+203A ISO proposed
// rsaquo is proposed but not yet ISO standardized
(Name: 'euro'; Value: #8364) // euro sign, U+20AC NEW
);
var
ii: integer;
HTMLCharList: TStringList;
function UTF8ToWideString(S: string): WideString;
var
i,x,m,V: Integer;
begin
Result := '';
i := 1;
while i <= Length(S) do begin
x := Ord(S[i]);
if x < $80 then begin
Result := Result + S[i];
Inc(i);
end
else begin
if (x and $E0) = $C0 then
m := $1F
else if (x and $F0) = $E0 then
m := $0F
else if (x and $F8) = $F0 then
m := $07
else if (x and $FC) = $F8 then
m := $03
else if (x and $FE) = $FC then
m := $01
else
m := 0;
V := x and m;
Inc(i);
while i <= Length(S) do begin
x := Ord(S[i]);
if (x and $C0) = $80 then
V := (V shl 6) + (x and $3F)
else
Break;
Inc(i);
end;
Result := Result + WideChar(V)
end;
end;
end;
function DecodeHTMLText(Text: WideString): WideString;
var
i,j: integer;
S: string;
begin
Result := '';
i := 1;
while i <= Length(Text) do begin
if Text[i] = '&' then begin
j := i;
Inc(i);
while (i <= Length(Text)) and (Text[i] <> ';') do
Inc(i);
S := Copy(Text,j + 1,i - j - 1);
j := HTMLCharList.IndexOf(S);
if j >= 0 then
Result := Result + WideChar(HTMLCharList.Objects[j]);
Inc(i);
end
else begin
Result := Result + Text[i];
Inc(i);
end;
end;
end;
initialization
HTMLCharList := TStringList.Create;
for ii := 0 to High(HTMLChars) do
HTMLCharList.AddObject(HTMLChars[ii].Name,Pointer(HTMLChars[ii].Value));
HTMLCharList.Sorted := True;
finalization
HTMLCharList.Free;
end.
|
unit ExtensionTypeUnit;
interface
uses sysUtils, Generics.Collections, Generics.Defaults;
Type
TExtensionType = (etModelInput, etModelOutput, etModpathInput,
etModpathOutput, etZoneBudgetInput, etZoneBudgetOutput, etMt3dmsInput,
etMt3dmsOutput, etAncillary);
TExtensionObject = Class(TObject)
Extension: string;
ExtensionType: TExtensionType;
Description: string;
end;
TExtensionList = class (TObjectList<TExtensionObject>)
public
procedure SetDefaultExtensions;
procedure SortRecords;
end;
function ExtractFileExtendedExt(FileName: string): string;
implementation
function ExtractFileExtendedExt(FileName: string): string;
var
AnExt: string;
begin
result := '';
repeat
AnExt := ExtractFileExt(FileName);
result := AnExt + result;
// result := ExtractFileExt(FileName);
FileName := ChangeFileExt(FileName, '');
until ((AnExt = '') or AnsiSameText(AnExt, '.reference'));
end;
{ TExtensionList }
procedure TExtensionList.SetDefaultExtensions;
var
ExtRec: TExtensionObject;
begin
Clear;
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.nam';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Name file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.nam.archive';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Name file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.mt_nam';
ExtRec.ExtensionType := etMt3dmsInput;
ExtRec.Description := 'MT3DMS Name file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.mt_nam.archive';
ExtRec.ExtensionType := etMt3dmsInput;
ExtRec.Description := 'MT3DMS Name file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.mto';
ExtRec.ExtensionType := etMt3dmsOutput;
ExtRec.Description := 'MT3DMS Observation Output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.jtf';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'Jupiter Template file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.dis';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Discretization file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.bas';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Basic Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.lpf';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Layer Property Flow Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.zon';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Zone Array input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.mlt';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Mulitplier Array input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.chd';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Time-Variant Specified Head Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.pcg';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Preconditioned Conjugate Gradient Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.ghb';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW General Head Boundary Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.wel';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Well Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.riv';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW River Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.drn';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Drain Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.drt';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Drain-Return Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.rch';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Recharge Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.evt';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Evapotranspiration Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.ets';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Evapotranspiration Segments Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.res';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Reservoir Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.lak';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Lake Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.sfr';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Streamflow Routing Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.uzf';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Unsaturated Zone Flow Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.gmg';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Geometric Multigrid Flow Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.sip';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Strongly Implicit Procedure Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.de4';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Direct Solver Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.oc';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Output Control input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.gag';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Gage Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.ob_hob';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Head Observation Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.hfb';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Horizontal Flow Barrier Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.strt';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODPATH Starting Locations input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.mpm';
ExtRec.ExtensionType := etModpathInput;
ExtRec.Description := 'MODPATH Main input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.mpbas';
ExtRec.ExtensionType := etModpathInput;
ExtRec.Description := 'MODPATH Basic input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.tim';
ExtRec.ExtensionType := etModpathInput;
ExtRec.Description := 'MODPATH Time input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.mprsp';
ExtRec.ExtensionType := etModpathInput;
ExtRec.Description := 'MODPATH Response input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.mprsp.archive';
ExtRec.ExtensionType := etModpathInput;
ExtRec.Description := 'MODPATH Response input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.mpsim';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODPATH Simulation input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.mpsim.archive';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODPATH Simulation input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.huf';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Hydrogeologic Unit Flow Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.kdep';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Hydraulic-Conductivity Depth-Dependence Capability input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.lvda';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Model-Layer Variable-Direction Horizontal Anisotropy Capability input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.mnw2';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Multi-Node Well Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.bcf';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Block-Centered Flow Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.sub';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Subsidence and Aquifer-System Compaction Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.zb_zones';
ExtRec.ExtensionType := etZonebudgetInput;
ExtRec.Description := 'ZONEBUDGET Zoned input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.zb_response';
ExtRec.ExtensionType := etZonebudgetInput;
ExtRec.Description := 'ZONEBUDGET Response file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.zb_response.archive';
ExtRec.ExtensionType := etZonebudgetInput;
ExtRec.Description := 'ZONEBUDGET Response file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.swt';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Subsidence and Aquifer-System Compaction Package for Water-Table Aquifers input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.hyd';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW HYDMOD Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.lgr';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW-LGR Local Grid Refinement input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.lgr.archive';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW-LGR Local Grid Refinement input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.nwt';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW-NWT Newton Solver Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.upw';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW-NWT Upstream Weighting Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.btn';
ExtRec.ExtensionType := etMt3dmsInput;
ExtRec.Description := 'MT3DMS Basic Transport Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.adv';
ExtRec.ExtensionType := etMt3dmsInput;
ExtRec.Description := 'MT3DMS Advection Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.dsp';
ExtRec.ExtensionType := etMt3dmsInput;
ExtRec.Description := 'MT3DMS Dispersion Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.ssm';
ExtRec.ExtensionType := etMt3dmsInput;
ExtRec.Description := 'MT3DMS Sink and Source Mixing Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.rct';
ExtRec.ExtensionType := etMt3dmsInput;
ExtRec.Description := 'MT3DMS Chemical Reactions Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.gcg';
ExtRec.ExtensionType := etMt3dmsInput;
ExtRec.Description := 'MT3DMS Generalized Conjugate Gradient Solver Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.tob';
ExtRec.ExtensionType := etMt3dmsInput;
ExtRec.Description := 'MT3DMS Transport Observation Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.lmt';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW Link to MT3DMS output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.pcgn';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Preconditioned Conjugate Gradient Solver with Improved Nonlinear Control input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.FluxBcs';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'SUTRA Flow time-dependent sources and boundary conditions input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.UFluxBcs';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'SUTRA concentration or enerty time-dependent sources and boundary conditions input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.SPecPBcs';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'SUTRA Specified pressure time-dependent sources and boundary conditions input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.SPecUBcs';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'SUTRA Specified concentration or temperature time-dependent sources and boundary conditions input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.8d';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'SUTRA input file data set 8D';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.inp';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'SUTRA Main input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.ics';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'SUTRA Initial Conditions input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.str';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Stream Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.fhb';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Flow and Head Boundary Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.fmp';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW-OWHM Farm Process input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.ROOT';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW-OWHM Farm Process input file data set 11';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.SW_Losses';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW-OWHM Farm Process input file data set 13';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.PSI';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW-OWHM Farm Process input file data set 14';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.ET_Func';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW-OWHM Farm Process input file data set 15';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.TimeSeries';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW-OWHM Farm Process input file data set 16';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.IFALLOW';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW-OWHM Farm Process input file data set 17';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.CropFunc';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW-OWHM Farm Process input file data set 34';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.WaterCost';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW-OWHM Farm Process input file data set 35';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.FID';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW-OWHM Farm Process input file data set 26';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.OFE';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW-OWHM Farm Process input file data set 7';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.CID';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW-OWHM Farm Process input file data set 28';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.CropUse';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW-OWHM Farm Process input file data set 30a';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.ETR';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW-OWHM Farm Process input file data set 30b';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.ET_Frac';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW-OWHM Farm Process input file data set 12';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.cfp';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW-CFP Conduit Flow Process input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.swi';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Seawater Intrusion Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.swr';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW-NWT Surface-Water Routing Process input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.mnw1';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Multi-Node Well Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.ic';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW-6 Initial Conditions input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.npf';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW-6 Node Property Flow package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.sto';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW-6 Storage package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.sms';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW-6 Sparse Matrix Solution package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.tdis';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW-6 Time-Discretization input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.rip';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW-OWHM Riparean Evapotranspiration Package input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.lkin';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'SUTRA Lake input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.bcof';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'SUTRA Fluid Source Boundary Condition input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.bcos';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'SUTRA Solute or Energy Source Boundary Condition input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.bcop';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'SUTRA Specified Pressure input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.bcou';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'SUTRA Specified Concentration or Temperature input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.fil';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'SUTRA File Assignment input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.fil.archive';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'SUTRA File Assignment input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.pval';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Parameter Value input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.rch.R_Mult*';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Recharge Multiplier Array';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.evt.ET_Mult*';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Evapotranspiration Multiplier Array';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.ets.ETS_Mult*';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Evapotranspiration Segments Multiplier Array';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.rch.R_Zone*';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Recharge Zone Array';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.evt.ET_Zone*';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Evapotranspiration Zone Array';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.ets.ETS_Zone*';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Evapotranspiration Segments Zone Array';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.ftl';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW MT3DMS Flow Transport Link input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.lst';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW Listing file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.fhd';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW Formatted Head file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.bhd';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW Binary Head file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.fdn';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW Formatted Drawdown file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.bdn';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW Binary Drawdown file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.cbc';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW Cell-By-Cell flow file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.huf_fhd';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW HUF Formatted Head file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.huf_bhd';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW HUF Binary Head file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.huf_flow';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW HUF Flow File';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.Sub_Out';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW Combined SUB output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.Swt_Out';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW Combined SWT output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.SubSubOut';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SUB Subsidence output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.SubComMlOut';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SUB Compaction by model layer output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.SubComIsOut';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SUB Compaction by interbed system output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.SubVdOut';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SUB Vertical displacement output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.SubNdCritHeadOut';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SUB Critical head for no-delay interbeds output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.SubDCritHeadOut';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SUB Critical head for delay interbeds output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.SwtSubOut';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SWT Subsidence output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.SwtComMLOut';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SWT Compaction by model layer output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.SwtComIsOut';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SWT Compaction by interbed system output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.SwtVDOut';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SWT Vertical displacement output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.SwtPreConStrOut';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW Preconsolidation stress output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.SwtDeltaPreConStrOut';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SWT Change in preconsolidation stress output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.SwtGeoStatOut';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SWT Geostatic stress output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.SwtDeltaGeoStatOut';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SWT Change in geostatic stress output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.SwtEffStressOut';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SWT Effective stress output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.SwtDeltaEffStressOut';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SWT Change in effective stress output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.SwtVoidRatioOut';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SWT Void ratio output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.SwtThickCompSedOut';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SWT Thickness of compressible sediments output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.SwtLayerCentElevOut';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SWT Layer-center elevation output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.ucn';
ExtRec.ExtensionType := etMt3dmsOutput;
ExtRec.Description := 'MT3DMS Concentration output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.zta';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW Zeta Surface output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.Swr_ReachGroupFlows_A';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SWR Reach Group Flows ASCII output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.Swr_ReachGroupFlows_B';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SWR Reach Group Flows binary output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.Swr_ReachStage_A';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SWR Reach Stage ASCII output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.Swr_ReachStage_B';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SWR Reach Stage binary output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.Swr_ReachExchange_A';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SWR Reach Exchange ASCII output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.Swr_ReachExchange_B';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SWR Reach Exchange binary output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.Swr_LateralFlow_A';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SWR Lateral Flow ASCII output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.Swr_LateralFlow_B';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SWR Lateral Flow binary output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.Swr_StructureFlow_A';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SWR Structure Flow ASCII output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.Swr_StructureFlow_B';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SWR Structure Flow binary output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.Swr_TimeStepLength_A';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SWR Time Step Length ASCII output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.Swr_TimeStepLength_B';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SWR Time Step Length binary output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.Swr_Convergence';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SWR Convergence output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.Swr_RIV';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW River package file created by the SWR Package';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.Swr_Obs_A';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SWR Observation ASCII output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.Swr_Obs_B';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SWR Observation binary output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.Swr_DirectRunoff';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SWR Direct Runoff output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.nod';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'SUTRA Node output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.ele';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'SUTRA Element output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.OUT';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'SUTRA main output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.FDS_BIN';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW Farm Process Demand and Supply binary output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.FB_COMPACT_BIN_OUT';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW Farm Process Farm Compact Budget binary output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.FB_DETAILS_BIN_OUT';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW Farm Process Farm Detailed Budget binary output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.fpb';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'Footprint binary output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.fpt';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'Footprint text output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.bfh_head';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW-LGR Boundary Flow and Head Package file for heads';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.bfh_flux';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW-LGR Boundary Flow and Head Package file for flows';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.csv';
ExtRec.ExtensionType := etZonebudgetOutput;
ExtRec.Description := 'ZONEBUDGET Comma Separated Values file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.2.csv';
ExtRec.ExtensionType := etZonebudgetOutput;
ExtRec.Description := 'ZONEBUDGET Comma Separated Values file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.hob_out';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW Head Observations output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.ob_chob';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Observations of Flow at Specified Heads input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.ob_gbob';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Observations of Flow at General Head Boundaries input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.ob_rvob';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Observations of Flow at Rivers input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.ob_drob';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Observations of Flow at Drains input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.ob_stob';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW Observations of Flow at Streams input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.rvob_out';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW Observations of Flow at Rivers output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.chob_out';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW Observations of Flow at Specified Heads output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.gbob_out';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW Observations of Flow at General Head Boundaries output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.drob_out';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW Observations of Flow at Drains output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.stob_out';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW Observations of Flow at Streams output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.obs';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'SUTRA Observation Output file in OBS format';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.obc';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'SUTRA Observation Output file in OBC format';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.rst';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'SUTRA Restart file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.smy';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'SUTRA Simulation Progress file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.zblst';
ExtRec.ExtensionType := etZonebudgetOutput;
ExtRec.Description := 'ZONEBUDGET Listing File';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.gsf';
ExtRec.ExtensionType := etAncillary;
ExtRec.Description := 'PEST Grid Specification file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.gpt';
ExtRec.ExtensionType := etAncillary;
ExtRec.Description := 'ModelMuse text file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.gpb';
ExtRec.ExtensionType := etAncillary;
ExtRec.Description := 'ModelMuse binary file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.mmZLib';
ExtRec.ExtensionType := etAncillary;
ExtRec.Description := 'ModelMuse compressed binary file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.axml';
ExtRec.ExtensionType := etAncillary;
ExtRec.Description := 'ModelMuse Archive Information file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.reference';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'Georeference file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.shp';
ExtRec.ExtensionType := etAncillary;
ExtRec.Description := 'Shapefile shapes file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.shx';
ExtRec.ExtensionType := etAncillary;
ExtRec.Description := 'Shapefile shape index file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.dbf';
ExtRec.ExtensionType := etAncillary;
ExtRec.Description := 'Shapefile attribute database';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.prj';
ExtRec.ExtensionType := etAncillary;
ExtRec.Description := 'Projection file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.sbn';
ExtRec.ExtensionType := etAncillary;
ExtRec.Description := 'Shapefile spatial index of the features';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.sbx';
ExtRec.ExtensionType := etAncillary;
ExtRec.Description := 'Shapefile spatial index of the features';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.fbn';
ExtRec.ExtensionType := etAncillary;
ExtRec.Description := 'Shapefile spatial index of the read-only features';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.fbx';
ExtRec.ExtensionType := etAncillary;
ExtRec.Description := 'Shapefile spatial index of the read-only features';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.ain';
ExtRec.ExtensionType := etAncillary;
ExtRec.Description := 'Shapefile attribute index of the active fields in a table';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.aix';
ExtRec.ExtensionType := etAncillary;
ExtRec.Description := 'Shapefile attribute index of the active fields in a table';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.aix';
ExtRec.ExtensionType := etModpathInput;
ExtRec.Description := 'Shapefile geocoding index for read-write datasets';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.mxs';
ExtRec.ExtensionType := etModpathInput;
ExtRec.Description := 'Shapefile geocoding index for read-write datasets (ODB format)';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.atx';
ExtRec.ExtensionType := etModpathInput;
ExtRec.Description := 'Shapefile an attribute index for the .dbf file in the form of shapefile.columnname.atx (ArcGIS 8 and later)';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.shp.xml';
ExtRec.ExtensionType := etModpathInput;
ExtRec.Description := 'Shapefile geospatial metadata in XML format, such as ISO 19115 or other XML schema';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.cpg';
ExtRec.ExtensionType := etModpathInput;
ExtRec.Description := 'Shapefile used to specify the code page (only for .dbf) for identifying the character encoding to be used';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.qix';
ExtRec.ExtensionType := etModpathInput;
ExtRec.Description := 'Shapefile an alternative quadtree spatial index used by MapServer and GDAL/OGR software';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.mpn';
ExtRec.ExtensionType := etModpathInput;
ExtRec.Description := 'MODPATH Name file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.mpn.archive';
ExtRec.ExtensionType := etModpathInput;
ExtRec.Description := 'MODPATH Name file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.end';
ExtRec.ExtensionType := etModpathOutput;
ExtRec.Description := 'MODPATH Endpoint file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.end_bin';
ExtRec.ExtensionType := etModpathOutput;
ExtRec.Description := 'MODPATH Binary Endpoint file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.path';
ExtRec.ExtensionType := etModpathOutput;
ExtRec.Description := 'MODPATH Pathline file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.path_bin';
ExtRec.ExtensionType := etModpathOutput;
ExtRec.Description := 'MODPATH Binary Pathline file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.ts';
ExtRec.ExtensionType := etModpathOutput;
ExtRec.Description := 'MODPATH Timeseries file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.ts_bin';
ExtRec.ExtensionType := etModpathOutput;
ExtRec.Description := 'MODPATH Binary Timeseries file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.cbf';
ExtRec.ExtensionType := etModpathOutput;
ExtRec.Description := 'MODPATH Budget file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.mplst';
ExtRec.ExtensionType := etModpathOutput;
ExtRec.Description := 'MODPATH Listing file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.log';
ExtRec.ExtensionType := etModpathOutput;
ExtRec.Description := 'MODPATH log file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.mls';
ExtRec.ExtensionType := etMt3dmsOutput;
ExtRec.Description := 'MT3DMS listing file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '._mas';
ExtRec.ExtensionType := etMt3dmsOutput;
ExtRec.Description := 'MT3DMS Mass Budget Output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.dat';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'PHAST thermodynamic database input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.trans.dat';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'PHAST transport input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.chem.dat';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'PHAST chemical-reactions input file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.O.chem.dat';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'PHAST chemical-reactions output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.head.dat';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'PHAST head output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.h5';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'PHAST data output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.O.kd';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'PHAST fluid and solute-dispersive conductance distributions output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.O.head';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'PHAST potentiometric head output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.xyz.head';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'PHAST potentiometric head output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.O.comps';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'PHAST component concentration distributions output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.xyz.comps';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'PHAST component concentration distributions output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.O.chem';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'PHAST selected chemical information output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.xyz.chem';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'PHAST selected chemical information output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.O.vel';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'PHAST velocity distribution output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.xyz.vel';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'PHAST velocity distribution output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.O.wel';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'PHAST well data output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.xyz.wel';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'PHAST well data output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.O.bal';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'PHAST regional fluid-flow and solute-flow rates and the regional cumulative-flow results output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.O.bcf';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'PHAST fluid and solute flow rates through boundaries output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.cnf';
ExtRec.ExtensionType := etMt3dmsOutput;
ExtRec.Description := 'MT3DMS Grid Configuration output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.O.probdef';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'PHAST Flow and transport problem definition output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.sel';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'PHAST Selected Output';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.sfrg*';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW SFR Gage output';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.lakg*';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW LAK Gage output';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.restart.gz';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'SUTRA restart file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.advobs';
ExtRec.ExtensionType := etModpathOutput;
ExtRec.Description := 'MODPATH Advection Observation file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.UzfRch';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW UZF Recharge output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.UzfDisch';
ExtRec.ExtensionType := etModelOutput;
ExtRec.Description := 'MODFLOW UZF Discharge output file';
Add(ExtRec);
ExtRec := TExtensionObject.Create;
ExtRec.Extension := '.wel_tab*';
ExtRec.ExtensionType := etModelInput;
ExtRec.Description := 'MODFLOW-NWT Well tab file';
Add(ExtRec);
SortRecords;
end;
procedure TExtensionList.SortRecords;
begin
Sort(TComparer<TExtensionObject>.Construct(function
(const Left, Right: TExtensionObject): Integer
begin
Result := AnsiCompareText(Left.Extension,Right.Extension);
end));
end;
end.
|
unit AvgHolPrintDM;
interface
uses
SysUtils, Classes, DB, FIBDataSet, pFIBDataSet, FIBDatabase, pFIBDatabase,
frxClass, frxDBSet, frxDesgn, IBase, IniFiles, Forms, Dates, Variants,
Unit_SprSubs_Consts, ZProc, ZSvodTypesUnit, Controls, FIBQuery,
pFIBQuery, pFIBStoredProc, ZMessages, Dialogs, Math, ZSvodProcUnit,
Unit_ZGlobal_Consts;
type
TDM = class(TDataModule)
DB: TpFIBDatabase;
ReadTransaction: TpFIBTransaction;
DSetGlobal: TpFIBDataSet;
ReportDSetGlobal: TfrxDBDataset;
DSet1: TpFIBDataSet;
ReportDset1: TfrxDBDataset;
DSetSetup: TpFIBDataSet;
ReportDSetSetup: TfrxDBDataset;
DSourceGlobal: TDataSource;
frxDesigner1: TfrxDesigner;
DSet2: TpFIBDataSet;
ReportDSet2: TfrxDBDataset;
DSet3: TpFIBDataSet;
ReportDSet3: TfrxDBDataset;
Report: TfrxReport;
procedure DataModuleDestroy(Sender: TObject);
procedure ReportGetValue(const VarName: String; var Value: Variant);
private
public
function PrintSpr(AParameter:TAvgHolParam):variant;
end;
implementation
{$R *.dfm}
const NameReport = 'Reports\Zarplata\AvgHol.fr3';
function TDM.PrintSpr(AParameter:TAvgHolParam):variant;
begin
Screen.Cursor:=crHourGlass;
try
DSetGlobal.SQLs.SelectSQL.Text:='SELECT * FROM Z_GET_HOLIDAY_PRINT_COMMON('+
IntToStr(AParameter.Id)+')';
DSet1.SQLs.SelectSQL.Text := 'SELECT * FROM Z_GET_HOLIDAY_PRINT(?ID_MAN_HOLIDAY)';
DSet3.SQLs.SelectSQL.Text := 'SELECT * FROM Z_GET_HOLIDAY_PRINT_2(?ID_MAN_HOLIDAY)';
DB.Handle:=AParameter.DB_Handle;
ReadTransaction.StartTransaction;
DSetGlobal.Open;
DSet1.Open;
DSet2.SQLs.SelectSQL.Text := 'SELECT * FROM Z_COUNT_AVARAGE_PAYMENT('+
VarToStr(DSet1['KOD_SETUP'])+',12,'+VarToStr(DSet1['RMOVING'])+')';
DSet3.Open;
except
on E:Exception do
begin
ZShowMessage(Error_Caption[LanguageIndex],e.Message,mtError,[mbOK]);
Exit;
end;
end;
Report.Clear;
Report.LoadFromFile(ExtractFilePath(Application.ExeName)+NameReport,True);
{ Report.Variables.Clear;
Report.Variables[' '+'User Category']:=NULL;
Report.Variables.AddVariable('User Category',
'PPeriod',
''''+KodSetupToPeriod(PKodSetup,0)+'''');}
Screen.Cursor:=crDefault;
if zDesignReport then Report.DesignReport
else Report.ShowReport;
Report.Free;
end;
procedure TDM.DataModuleDestroy(Sender: TObject);
begin
if ReadTransaction.InTransaction then ReadTransaction.Commit;
end;
procedure TDM.ReportGetValue(const VarName: String; var Value: Variant);
begin
if UpperCase(VarName)='P_KOD_SETUP' then
Value := KodSetupToPeriod(DSet2['KS'],0);
end;
end.
|
unit GLDPyramid;
interface
uses
Classes, GL, GLDTypes, GLDConst, GLDClasses, GLDObjects;
type
TGLDPyramid = class(TGLDEditableObject)
private
FWidth: GLfloat;
FDepth: GLfloat;
FHeight: GLfloat;
FWidthSegs: GLushort;
FDepthSegs: GLushort;
FHeightSegs: GLushort;
FFrontPoints: PGLDVector3fArray;
FFrontNormals: PGLDVector3fArray;
FBackPoints: PGLDVector3fArray;
FBackNormals: PGLDVector3fArray;
FLeftPoints: PGLDVector3fArray;
FLeftNormals: PGLDVector3fArray;
FRightPoints: PGLDVector3fArray;
FRightNormals: PGLDVector3fArray;
FBottomPoints: PGLDVector3fArray;
FBottomNormals: PGLDVector3fArray;
function GetFrontPoint(i, j: GLushort): PGLDVector3f;
function GetBackPoint(i, j: GLushort): PGLDVector3f;
function GetLeftPoint(i, j: GLushort): PGLDVector3f;
function GetRightPoint(i, j: GLushort): PGLDVector3f;
function GetBottomPoint(i, j: GLushort): PGLDVector3f;
function GetPoint(si, i, j: GLushort): PGLDVector3f;
procedure SetWidth(Value: GLfloat);
procedure SetDepth(Value: GLfloat);
procedure SetHeight(Value: GLfloat);
procedure SetWidthSegs(Value: GLushort);
procedure SetDepthSegs(Value: GLushort);
procedure SetHeightSegs(Value: GLushort);
function GetParams: TGLDPyramidParams;
procedure SetParams(Value: TGLDPyramidParams);
protected
procedure CalcBoundingBox; override;
procedure CreateGeometry; override;
procedure DestroyGeometry; override;
procedure DoRender; override;
procedure SimpleRender; override;
public
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
class function SysClassType: TGLDSysClassType; override;
class function VisualObjectClassType: TGLDVisualObjectClass; override;
class function RealName: string; override;
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream); override;
function CanConvertTo(_ClassType: TClass): GLboolean; override;
function ConvertTo(Dest: TPersistent): GLboolean; override;
function ConvertToTriMesh(Dest: TPersistent): GLboolean;
function ConvertToQuadMesh(Dest: TPersistent): GLboolean;
function ConvertToPolyMesh(Dest: TPersistent): GLboolean;
property Params: TGLDPyramidParams read GetParams write SetParams;
published
property Width: GLfloat read FWidth write SetWidth;
property Depth: GLfloat read FDepth write SetDepth;
property Height: GLfloat read FHeight write SetHeight;
property WidthSegs: GLushort read FWidthSegs write SetWidthSegs default GLD_PYRAMID_WIDTHSEGS_DEFAULT;
property DepthSegs: GLushort read FDepthSegs write SetDepthSegs default GLD_PYRAMID_DEPTHSEGS_DEFAULT;
property HeightSegs: GLushort read FHeightSegs write SetHeightSegs default GLD_PYRAMID_HEIGHTSEGS_DEFAULT;
end;
implementation
uses
SysUtils, GLDGizmos, GLDX, GLDMesh, GLDUtils;
var
vPyramidCounter: GLuint = 0;
constructor TGLDPyramid.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
Inc(vPyramidCounter);
FName := GLD_PYRAMID_STR + IntToStr(vPyramidCounter);
FWidth := GLD_STD_PYRAMIDPARAMS.Width;
FDepth := GLD_STD_PYRAMIDPARAMS.Depth;
FHeight := GLD_STD_PYRAMIDPARAMS.Height;
FWidthSegs := GLD_STD_PYRAMIDPARAMS.WidthSegs;
FDepthSegs := GLD_STD_PYRAMIDPARAMS.DepthSegs;
FHeightSegs := GLD_STD_PYRAMIDPARAMS.HeightSegs;
FPosition.Vector3f := GLD_STD_PLANEPARAMS.Position;
FRotation.Params := GLD_STD_PLANEPARAMS.Rotation;
CreateGeometry;
end;
destructor TGLDPyramid.Destroy;
begin
inherited Destroy;
end;
procedure TGLDPyramid.Assign(Source: TPersistent);
begin
if (Source = nil) or (Source = Self) then Exit;
if not (Source is TGLDPyramid) then Exit;
inherited Assign(Source);
SetParams(TGLDPyramid(Source).GetParams);
end;
procedure TGLDPyramid.DoRender;
var
iW, iD, iH: GLushort;
begin
for iH := 1 to FHeightSegs do
begin
glBegin(GL_QUAD_STRIP);
for iW := 1 to FWidthSegs + 1 do
begin
glNormal3fv(@FFrontNormals^[(iH - 1) * (FWidthSegs + 1) + iW]);
glVertex3fv(@FFrontPoints^[(iH - 1) * (FWidthSegs + 1) + iW]);
glNormal3fv(@FFrontNormals^[iH * (FWidthSegs + 1) + iW]);
glVertex3fv(@FFrontPoints^[iH * (FWidthSegs + 1) + iW]);
end;
glEnd;
glBegin(GL_QUAD_STRIP);
for iW := 1 to FWidthSegs + 1 do
begin
glNormal3fv(@FBackNormals^[(iH - 1) * (FWidthSegs + 1) + iW]);
glVertex3fv(@FBackPoints^[(iH - 1) * (FWidthSegs + 1) + iW]);
glNormal3fv(@FBackNormals^[iH * (FWidthSegs + 1) + iW]);
glVertex3fv(@FBackPoints^[iH * (FWidthSegs + 1) + iW]);
end;
glEnd;
glBegin(GL_QUAD_STRIP);
for iD := 1 to FDepthSegs + 1 do
begin
glNormal3fv(@FLeftNormals^[(iH - 1) * (FDepthSegs + 1) + iD]);
glVertex3fv(@FLeftPoints^[(iH - 1) * (FDepthSegs + 1) + iD]);
glNormal3fv(@FLeftNormals^[iH * (FDepthSegs + 1) + iD]);
glVertex3fv(@FLeftPoints^[iH * (FDepthSegs + 1) + iD]);
end;
glEnd;
glBegin(GL_QUAD_STRIP);
for iD := 1 to FDepthSegs + 1 do
begin
glNormal3fv(@FRightNormals^[(iH - 1) * (FDepthSegs + 1) + iD]);
glVertex3fv(@FRightPoints^[(iH - 1) * (FDepthSegs + 1) + iD]);
glNormal3fv(@FRightNormals^[iH * (FDepthSegs + 1) + iD]);
glVertex3fv(@FRightPoints^[iH * (FDepthSegs + 1) + iD]);
end;
glEnd;
end;
for iD := 1 to FDepthSegs do
begin
glBegin(GL_QUAD_STRIP);
for iW := 1 to FWidthSegs + 1 do
begin
glNormal3fv(@FBottomNormals^[(iD - 1) * (FWidthSegs + 1) + iW]);
glVertex3fv(@FBottomPoints^[(iD - 1) * (FWidthSegs + 1) + iW]);
glNormal3fv(@FBottomNormals^[iD * (FWidthSegs + 1) + iW]);
glVertex3fv(@FBottomPoints^[iD * (FWidthSegs + 1) + iW]);
end;
glEnd;
end;
end;
procedure TGLDPyramid.SimpleRender;
var
iW, iD, iH: GLushort;
begin;
for iH := 1 to FHeightSegs do
begin
glBegin(GL_QUAD_STRIP);
for iW := 1 to FWidthSegs + 1 do
begin
glVertex3fv(@FFrontPoints^[(iH - 1) * (FWidthSegs + 1) + iW]);
glVertex3fv(@FFrontPoints^[iH * (FWidthSegs + 1) + iW]);
end;
glEnd;
glBegin(GL_QUAD_STRIP);
for iW := 1 to FWidthSegs + 1 do
begin
glVertex3fv(@FBackPoints^[(iH - 1) * (FWidthSegs + 1) + iW]);
glVertex3fv(@FBackPoints^[iH * (FWidthSegs + 1) + iW]);
end;
glEnd;
glBegin(GL_QUAD_STRIP);
for iD := 1 to FDepthSegs + 1 do
begin
glVertex3fv(@FLeftPoints^[(iH - 1) * (FDepthSegs + 1) + iD]);
glVertex3fv(@FLeftPoints^[iH * (FDepthSegs + 1) + iD]);
end;
glEnd;
glBegin(GL_QUAD_STRIP);
for iD := 1 to FDepthSegs + 1 do
begin
glVertex3fv(@FRightPoints^[(iH - 1) * (FDepthSegs + 1) + iD]);
glVertex3fv(@FRightPoints^[iH * (FDepthSegs + 1) + iD]);
end;
glEnd;
end;
for iD := 1 to FDepthSegs do
begin
glBegin(GL_QUAD_STRIP);
for iW := 1 to FWidthSegs + 1 do
begin
glVertex3fv(@FBottomPoints^[(iD - 1) * (FWidthSegs + 1) + iW]);
glVertex3fv(@FBottomPoints^[iD * (FWidthSegs + 1) + iW]);
end;
glEnd;
end;
end;
procedure TGLDPyramid.CalcBoundingBox;
begin
FBoundingBox := GLDXCalcBoundingBox(
[GLDXVector3fArrayData(FFrontPoints, (FWidthSegs + 1) * (FHeightSegs + 1)),
GLDXVector3fArrayData(FBackPoints, (FWidthSegs + 1) * (FHeightSegs + 1)),
GLDXVector3fArrayData(FLeftPoints, (FDepthSegs + 1) * (FHeightSegs + 1)),
GLDXVector3fArrayData(FRightPoints, (FDepthSegs + 1) * (FHeightSegs + 1)),
GLDXVector3fArrayData(FBottomPoints, (FWidthSegs + 1) * (FDepthSegs + 1))]);
end;
procedure TGLDPyramid.CreateGeometry;
var
iWS, iHS, iDS: GLushort;
iWidth, iDepth: GLfloat;
begin
if FWidthSegs < 1 then FWidthSegs := 1 else
if FWidthSegs > 1000 then FWidthSegs := 1000;
if FDepthSegs < 1 then FDepthSegs := 1 else
if FDepthSegs > 1000 then FDepthSegs := 1000;
if FHeightSegs < 1 then FHeightSegs := 1 else
if FHeightSegs > 1000 then FHeightSegs := 1000;
ReallocMem(FFrontPoints, (FWidthSegs + 1) * (FHeightSegs + 1) * SizeOf(TGLDVector3f));
ReallocMem(FFrontNormals, (FWidthSegs + 1) * (FHeightSegs + 1) * SizeOf(TGLDVector3f));
ReallocMem(FBackPoints, (FWidthSegs + 1) * (FHeightSegs + 1) * SizeOf(TGLDVector3f));
ReallocMem(FBackNormals, (FWidthSegs + 1) * (FHeightSegs + 1) * SizeOf(TGLDVector3f));
ReallocMem(FLeftPoints, (FDepthSegs + 1) * (FHeightSegs + 1) * SizeOf(TGLDVector3f));
ReallocMem(FLeftNormals, (FDepthSegs + 1) * (FHeightSegs + 1) * SizeOf(TGLDVector3f));
ReallocMem(FRightPoints, (FDepthSegs + 1) * (FHeightSegs + 1) * SizeOf(TGLDVector3f));
ReallocMem(FRightNormals, (FDepthSegs + 1) * (FHeightSegs + 1) * SizeOf(TGLDVector3f));
ReallocMem(FBottomPoints, (FWidthSegs + 1) * (FDepthSegs + 1) * SizeOf(TGLDVector3f));
ReallocMem(FBottomNormals, (FWidthSegs + 1) * (FDepthSegs + 1) * SizeOf(TGLDVector3f));
for iHS := 1 to FHeightSegs + 1 do
begin
iWidth := (iHS - 1) * (FWidth / FHeightSegs);
iDepth := (iHS - 1) * (FDepth / FHeightSegs);
for iWS := 1 to FWidthSegs + 1 do
begin
FFrontPoints^[(iHS - 1) * (FWidthSegs + 1) + iWS] := GLDXVector3f(
(-(iWidth / 2)) + ((iWS - 1) * (iWidth / FWidthSegs)),
(FHeight / 2) - ((iHS - 1) * (FHeight / FHeightSegs)),
(iDepth / 2));
FBackPoints^[(iHS - 1) * (FWidthSegs + 1) + iWS] := GLDXVector3f(
(iWidth / 2) - ((iWS - 1) * (iWidth / FWidthSegs)),
(FHeight / 2) - ((iHS - 1) * (FHeight / FHeightSegs)),
-(iDepth / 2));
end;
for iDS := 1 to FDepthSegs + 1 do
begin
FLeftPoints^[(iHS - 1) * (FDepthSegs + 1) + iDS] := GLDXVector3f(
-(iWidth / 2),
(FHeight / 2) - ((iHS - 1) * (FHeight / FHeightSegs)),
-(iDepth / 2) + ((iDS - 1) * (iDepth / FDepthSegs)));
FRightPoints^[(iHS - 1) * (FDepthSegs + 1) + iDS] := GLDXVector3f(
(iWidth / 2),
(FHeight / 2) - ((iHS - 1) * (FHeight / FHeightSegs)),
(iDepth / 2) - ((iDS - 1) * (iDepth / FDepthSegs)));
end;
end;
for iDS := 1 to FDepthSegs + 1 do
for iWS := 1 to FWidthSegs + 1 do
begin
FBottomPoints^[(iDS - 1) * (FWidthSegs + 1) + iWS] := GLDXVector3f(
-(FWidth / 2) + ((iWS - 1) * (FWidth / FWidthSegs)),
-(FHeight / 2),
(FDepth / 2) - ((iDS - 1) * (FDepth / FDepthSegs)));
end;
FModifyList.ModifyPoints(
[GLDXVector3fArrayData(FFrontPoints, (FWidthSegs + 1) * (FHeightSegs + 1)),
GLDXVector3fArrayData(FBackPoints, (FWidthSegs + 1) * (FHeightSegs + 1)),
GLDXVector3fArrayData(FLeftPoints, (FDepthSegs + 1) * (FHeightSegs + 1)),
GLDXVector3fArrayData(FRightPoints, (FDepthSegs + 1) * (FHeightSegs + 1)),
GLDXVector3fArrayData(FBottomPoints, (FWidthSegs + 1) * (FDepthSegs + 1))]);
GLDXCalcQuadPatchNormals(GLDXQuadPatchData3f(
GLDXVector3fArrayData(FFrontPoints, (FHeightSegs + 1) * (FWidthSegs + 1)),
GLDXVector3fArrayData(FFrontNormals, (FHeightSegs + 1) * (FWidthSegs + 1)),
FHeightSegs, FWidthSegs));
GLDXCalcQuadPatchNormals(GLDXQuadPatchData3f(
GLDXVector3fArrayData(FBackPoints, (FHeightSegs + 1) * (FWidthSegs + 1)),
GLDXVector3fArrayData(FBackNormals, (FHeightSegs + 1) * (FWidthSegs + 1)),
FHeightSegs, FWidthSegs));
GLDXCalcQuadPatchNormals(GLDXQuadPatchData3f(
GLDXVector3fArrayData(FLeftPoints, (FHeightSegs + 1) * (FDepthSegs + 1)),
GLDXVector3fArrayData(FLeftNormals, (FHeightSegs + 1) * (FDepthSegs + 1)),
FHeightSegs, FDepthSegs));
GLDXCalcQuadPatchNormals(GLDXQuadPatchData3f(
GLDXVector3fArrayData(FRightPoints, (FHeightSegs + 1) * (FDepthSegs + 1)),
GLDXVector3fArrayData(FRightNormals, (FHeightSegs + 1) * (FDepthSegs + 1)),
FHeightSegs, FDepthSegs));
GLDXCalcQuadPatchNormals(GLDXQuadPatchData3f(
GLDXVector3fArrayData(FBottomPoints, (FWidthSegs + 1) * (FDepthSegs + 1)),
GLDXVector3fArrayData(FBottomNormals, (FWidthSegs + 1) * (FDepthSegs + 1)),
FDepthSegs, FWidthSegs));
CalcBoundingBox;
end;
procedure TGLDPyramid.DestroyGeometry;
begin
if FFrontPoints <> nil then ReallocMem(FFrontPoints, 0);
if FFrontNormals <> nil then ReallocMem(FFrontNormals, 0);
if FBackPoints <> nil then ReallocMem(FBackPoints, 0);
if FBackNormals <> nil then ReallocMem(FBackNormals, 0);
if FLeftPoints <> nil then ReallocMem(FLeftPoints, 0);
if FLeftNormals <> nil then ReallocMem(FLeftNormals, 0);
if FRightPoints <> nil then ReallocMem(FRightPoints, 0);
if FRightNormals <> nil then ReallocMem(FRightNormals, 0);
if FBottomPoints <> nil then ReallocMem(FBottomPoints, 0);
if FBottomNormals <> nil then ReallocMem(FBottomNormals, 0);
FFrontPoints := nil; FFrontNormals := nil;
FBackPoints := nil; FBackNormals := nil;
FLeftPoints := nil; FLeftNormals := nil;
FRightPoints := nil; FRightNormals := nil;
FBottomPoints := nil; FBottomNormals := nil;
end;
class function TGLDPyramid.SysClassType: TGLDSysClassType;
begin
Result := GLD_SYSCLASS_PYRAMID;
end;
class function TGLDPyramid.VisualObjectClassType: TGLDVisualObjectClass;
begin
Result := TGLDPyramid;
end;
class function TGLDPyramid.RealName: string;
begin
Result := GLD_PYRAMID_STR;
end;
procedure TGLDPyramid.LoadFromStream(Stream: TStream);
begin
inherited LoadFromStream(Stream);
Stream.Read(FWidth, SizeOf(GLfloat));
Stream.Read(FDepth, SizeOf(GLfloat));
Stream.Read(FHeight, SizeOf(GLfloat));
Stream.Read(FWidthSegs, SizeOf(GLushort));
Stream.Read(FDepthSegs, SizeOf(GLushort));
Stream.Read(FHeightSegs, SizeOf(GLushort));
CreateGeometry;
end;
procedure TGLDPyramid.SaveToStream(Stream: TStream);
begin
inherited SaveToStream(Stream);
Stream.Write(FWidth, SizeOf(GLfloat));
Stream.Write(FDepth, SizeOf(GLfloat));
Stream.Write(FHeight, SizeOf(GLfloat));
Stream.Write(FWidthSegs, SizeOf(GLushort));
Stream.Write(FDepthSegs, SizeOf(GLushort));
Stream.Write(FHeightSegs, SizeOf(GLushort));
end;
function TGLDPyramid.CanConvertTo(_ClassType: TClass): GLboolean;
begin
Result := (_ClassType = TGLDPyramid) or
(_ClassType = TGLDTriMesh) or
(_ClassType = TGLDQuadMesh) or
(_ClassType = TGLDPolyMesh);
end;
function TGLDPyramid.ConvertTo(Dest: TPersistent): GLboolean;
begin
Result := False;
if not Assigned(Dest) then Exit;
if Dest.ClassType = Self.ClassType then
begin
Dest.Assign(Self);
Result := True;
end else
if Dest is TGLDTriMesh then
Result := ConvertToTriMesh(Dest) else
if Dest is TGLDQuadMesh then
Result := ConvertToQuadMesh(Dest) else
if Dest is TGLDPolyMesh then
Result := ConvertToPolyMesh(Dest);
end;
{$WARNINGS OFF}
function TGLDPyramid.ConvertToTriMesh(Dest: TPersistent): GLboolean;
var
PC: GLuint;
Offset: array[1..5] of GLuint;
ie, je: array[1..5] of GLushort;
si, i, j: GLushort;
F: TGLDTriFace;
begin
Result := False;
if not Assigned(Dest) then Exit;
if not (Dest is TGLDTriMesh) then Exit;
PC := 2 * ((FWidthSegs + 1) * (FHeightSegs + 1) +
(FDepthSegs + 1) * (FHeightSegs + 1)) +
(FWidthSegs + 1) + (FDepthSegs + 1);
Offset[1] := 0;
Offset[2] := (FWidthSegs + 1) * (FHeightSegs + 1);
Offset[3] := Offset[2] * 2;
Offset[4] := Offset[3] + (FDepthSegs + 1) * (FHeightSegs + 1);
Offset[5] := Offset[4] + (FDepthSegs + 1) * (FHeightSegs + 1);
for si := 1 to 4 do
ie[si] := FHeightSegs;
ie[5] := FDepthSegs;
for si := 1 to 2 do
begin
je[si] := FWidthSegs;
je[2 + si] := FDepthSegs;
end;
je[5] := FWidthSegs;
with TGLDTriMesh(Dest) do
begin
DeleteVertices;
VertexCapacity := PC;
F.Smoothing := GLD_SMOOTH_ALL;
for si := 1 to 5 do
for i := 1 to ie[si] + 1 do
for j := 1 to je[si] + 1 do
AddVertex(GetPoint(si, i, j)^, True);
for si := 1 to 5 do
for i := 1 to ie[si] do
for j := 1 to je[si] do
begin
if (si = 5) or (i <> 1) then
begin
F.Point1 := Offset[si] + (i - 1) * (je[si] + 1) + j;
F.Point2 := Offset[si] + i * (je[si] + 1) + j;
F.Point3 := Offset[si] + (i - 1) * (je[si] + 1) + j + 1;
AddFace(F);
end;
F.Point1 := Offset[si] + (i - 1) * (je[si] + 1) + j + 1;
F.Point2 := Offset[si] + i * (je[si] + 1) + j;
F.Point3 := Offset[si] + i * (je[si] + 1) + j + 1;
AddFace(F);
end;
CalcNormals;
CalcBoundingBox;
PGLDColor4f(Color.GetPointer)^ := Self.FColor.Color4f;
PGLDVector4f(Position.GetPointer)^ := Self.FPosition.Vector4f;
PGLDRotation3D(Rotation.GetPointer)^ := Self.FRotation.Params;
TGLDTriMesh(Dest).Selected := Self.Selected;
TGLDTriMesh(Dest).Name := Self.Name;
end;
Result := True;
end;
function TGLDPyramid.ConvertToQuadMesh(Dest: TPersistent): GLboolean;
var
PC: GLuint;
Offset: array[1..5] of GLuint;
ie, je: array[1..5] of GLushort;
si, i, j: GLushort;
F: TGLDQuadFace;
begin
Result := False;
if not Assigned(Dest) then Exit;
if not (Dest is TGLDQuadMesh) then Exit;
PC := 2 * ((FWidthSegs + 1) * (FHeightSegs + 1) +
(FDepthSegs + 1) * (FHeightSegs + 1)) +
(FWidthSegs + 1) + (FDepthSegs + 1);
Offset[1] := 0;
Offset[2] := (FWidthSegs + 1) * (FHeightSegs + 1);
Offset[3] := Offset[2] * 2;
Offset[4] := Offset[3] + (FDepthSegs + 1) * (FHeightSegs + 1);
Offset[5] := Offset[4] + (FDepthSegs + 1) * (FHeightSegs + 1);
for si := 1 to 4 do
ie[si] := FHeightSegs;
ie[5] := FDepthSegs;
for si := 1 to 2 do
begin
je[si] := FWidthSegs;
je[2 + si] := FDepthSegs;
end;
je[5] := FWidthSegs;
with TGLDQuadMesh(Dest) do
begin
DeleteVertices;
VertexCapacity := PC;
F.Smoothing := GLD_SMOOTH_ALL;
for si := 1 to 5 do
for i := 1 to ie[si] + 1 do
for j := 1 to je[si] + 1 do
AddVertex(GetPoint(si, i, j)^, True);
for si := 1 to 5 do
for i := 1 to ie[si] do
for j := 1 to je[si] do
begin
F.Point1 := Offset[si] + (i - 1) * (je[si] + 1) + j;
F.Point2 := Offset[si] + i * (je[si] + 1) + j;
F.Point3 := Offset[si] + i * (je[si] + 1) + j + 1;
if (si <> 5) and (i = 1) then
F.Point4 := F.Point1
else F.Point4 := Offset[si] + (i - 1) * (je[si] + 1) + j + 1;
AddFace(F);
end;
CalcNormals;
CalcBoundingBox;
PGLDColor4f(Color.GetPointer)^ := Self.FColor.Color4f;
PGLDVector4f(Position.GetPointer)^ := Self.FPosition.Vector4f;
PGLDRotation3D(Rotation.GetPointer)^ := Self.FRotation.Params;
TGLDQuadMesh(Dest).Selected := Self.Selected;
TGLDQuadMesh(Dest).Name := Self.Name;
end;
Result := True;
end;
function TGLDPyramid.ConvertToPolyMesh(Dest: TPersistent): GLboolean;
var
PC: GLuint;
Offset: array[1..5] of GLuint;
ie, je: array[1..5] of GLushort;
si, i, j: GLushort;
P: TGLDPolygon;
begin
Result := False;
if not Assigned(Dest) then Exit;
if not (Dest is TGLDPolyMesh) then Exit;
PC := 2 * ((FWidthSegs + 1) * (FHeightSegs + 1) +
(FDepthSegs + 1) * (FHeightSegs + 1)) +
(FWidthSegs + 1) + (FDepthSegs + 1);
Offset[1] := 0;
Offset[2] := (FWidthSegs + 1) * (FHeightSegs + 1);
Offset[3] := Offset[2] * 2;
Offset[4] := Offset[3] + (FDepthSegs + 1) * (FHeightSegs + 1);
Offset[5] := Offset[4] + (FDepthSegs + 1) * (FHeightSegs + 1);
for si := 1 to 4 do
ie[si] := FHeightSegs;
ie[5] := FDepthSegs;
for si := 1 to 2 do
begin
je[si] := FWidthSegs;
je[2 + si] := FDepthSegs;
end;
je[5] := FWidthSegs;
with TGLDPolyMesh(Dest) do
begin
DeleteVertices;
VertexCapacity := PC;
for si := 1 to 5 do
for i := 1 to ie[si] + 1 do
for j := 1 to je[si] + 1 do
AddVertex(GetPoint(si, i, j)^, True);
for si := 1 to 5 do
for i := 1 to ie[si] do
for j := 1 to je[si] do
begin
P := GLD_STD_POLYGON;
if (si <> 5) and (i = 1) then
GLDURealloc(P, 3)
else GLDURealloc(P, 4);
P.Data^[1] := Offset[si] + (i - 1) * (je[si] + 1) + j;
P.Data^[2] := Offset[si] + i * (je[si] + 1) + j;
P.Data^[3] := Offset[si] + i * (je[si] + 1) + j + 1;
if not ((si <> 5) and (i = 1)) then
P.Data^[4] := Offset[si] + (i - 1) * (je[si] + 1) + j + 1;
AddFace(P);
end;
CalcNormals;
CalcBoundingBox;
PGLDColor4f(Color.GetPointer)^ := Self.FColor.Color4f;
PGLDVector4f(Position.GetPointer)^ := Self.FPosition.Vector4f;
PGLDRotation3D(Rotation.GetPointer)^ := Self.FRotation.Params;
TGLDPolyMesh(Dest).Selected := Self.Selected;
TGLDPolyMesh(Dest).Name := Self.Name;
end;
Result := True;
end;
function TGLDPyramid.GetFrontPoint(i, j: GLushort): PGLDVector3f;
begin
Result := @FFrontPoints^[(i - 1) * (FWidthSegs + 1) + j];
end;
function TGLDPyramid.GetBackPoint(i, j: GLushort): PGLDVector3f;
begin
Result := @FBackPoints^[(i - 1) * (FWidthSegs + 1) + j];
end;
function TGLDPyramid.GetLeftPoint(i, j: GLushort): PGLDVector3f;
begin
Result := @FLeftPoints^[(i - 1) * (FDepthSegs + 1) + j];
end;
function TGLDPyramid.GetRightPoint(i, j: GLushort): PGLDVector3f;
begin
Result := @FRightPoints^[(i - 1) * (FDepthSegs + 1) + j];
end;
function TGLDPyramid.GetBottomPoint(i, j: GLushort): PGLDVector3f;
begin
Result := @FBottomPoints^[(i - 1) * (FWidthSegs + 1) + j];
end;
function TGLDPyramid.GetPoint(si, i, j: GLushort): PGLDVector3f;
begin
case si of
1: Result := GetFrontPoint(i, j);
2: Result := GetBackPoint(i, j);
3: Result := GetLeftPoint(i, j);
4: Result := GetRightPoint(i, j);
5: Result := GetBottomPoint(i, j);
else Result := 0;
end;
end;
{$WARNINGS ON}
procedure TGLDPyramid.SetWidth(Value: GLfloat);
begin
if FWidth = Value then Exit;
FWidth := Value;
CreateGeometry;
Change;
end;
procedure TGLDPyramid.SetDepth(Value: GLfloat);
begin
if FDepth = Value then Exit;
FDepth := Value;
CreateGeometry;
Change;
end;
procedure TGLDPyramid.SetHeight(Value: GLfloat);
begin
if FHeight = Value then Exit;
FHeight := Value;
CreateGeometry;
Change;
end;
procedure TGLDPyramid.SetWidthSegs(Value: GLushort);
begin
if FWidthSegs = Value then Exit;
FWidthSegs := Value;
CreateGeometry;
Change;
end;
procedure TGLDPyramid.SetDepthSegs(Value: GLushort);
begin
if FDepthSegs = Value then Exit;
FDepthSegs := Value;
CreateGeometry;
Change;
end;
procedure TGLDPyramid.SetHeightSegs(Value: GLushort);
begin
if FHeightSegs = Value then Exit;
FHeightSegs := Value;
CreateGeometry;
Change;
end;
function TGLDPyramid.GetParams: TGLDPyramidParams;
begin
Result := GLDXPyramidParams(FColor.Color3ub, FWidth, FDepth, FHeight,
FWidthSegs, FDepthSegs, FHeightSegs, FPosition.Vector3f, FRotation.Params);
end;
procedure TGLDPyramid.SetParams(Value: TGLDPyramidParams);
begin
if GLDXPyramidParamsEqual(GetParams, Value) then Exit;
PGLDColor3f(FColor.GetPointer)^ := GLDXColor3f(Value.Color);
FWidth := Value.Width;
FDepth := Value.Depth;
FHeight := Value.Height;
FWidthSegs := Value.WidthSegs;
FDepthSegs := Value.DepthSegs;
FHeightSegs := Value.HeightSegs;
PGLDVector3f(FPosition.GetPointer)^ := Value.Position;
PGLDRotation3D(FRotation.GetPointer)^ := Value.Rotation;
CreateGeometry;
Change;
end;
end.
|
unit ProjectView;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ComCtrls, ImgList, ActnList, Menus,
ProjectDocument, ServerDatabases;
type
TProjectViewForm = class(TForm)
Tree: TTreeView;
Icons: TImageList;
ProjectPopup: TPopupMenu;
Actions: TActionList;
SetupServers1: TMenuItem;
SetupDatabases1: TMenuItem;
AddFolderAction: TAction;
N1: TMenuItem;
AddFolder1: TMenuItem;
procedure FormCreate(Sender: TObject);
procedure TreeGetSelectedIndex(Sender: TObject; Node: TTreeNode);
procedure AddFolderActionExecute(Sender: TObject);
private
FProject: TProjectDocument;
{ Private declarations }
function GetDatabasesNode: TTreeNode;
function GetItemsNode: TTreeNode;
function GetServersNode: TTreeNode;
procedure ProjectChange(Sender: TObject);
procedure UpdateDatabases;
procedure UpdateItems;
procedure UpdateServers;
procedure UpdateTables(inProfile: TServerDatabaseProfile);
procedure SetProject(const Value: TProjectDocument);
protected
property DatabasesNode: TTreeNode read GetDatabasesNode;
property ItemsNode: TTreeNode read GetItemsNode;
property ServersNode: TTreeNode read GetServersNode;
public
{ Public declarations }
procedure UpdateProject;
property Project: TProjectDocument read FProject write SetProject;
end;
var
ProjectViewForm: TProjectViewForm;
implementation
uses
LrTreeUtils,
htDatabaseProfile, htDb,
ServerSetup, DatabasesSetup, Controller;
{$R *.dfm}
procedure TProjectViewForm.FormCreate(Sender: TObject);
begin
Icons.Overlay(11, 0);
end;
procedure TProjectViewForm.SetProject(const Value: TProjectDocument);
begin
FProject := Value;
Project.OnChange := ProjectChange;
UpdateProject;
end;
function TProjectViewForm.GetServersNode: TTreeNode;
begin
Result := Tree.Items.GetFirstNode;
end;
function TProjectViewForm.GetDatabasesNode: TTreeNode;
begin
Result := ServersNode.GetNextSibling;
end;
function TProjectViewForm.GetItemsNode: TTreeNode;
begin
Result := DatabasesNode.GetNextSibling;
end;
procedure TProjectViewForm.TreeGetSelectedIndex(Sender: TObject;
Node: TTreeNode);
begin
Node.SelectedIndex := Node.ImageIndex;
end;
procedure TProjectViewForm.ProjectChange(Sender: TObject);
begin
UpdateProject;
end;
procedure TProjectViewForm.UpdateProject;
begin
UpdateServers;
UpdateDatabases;
UpdateItems;
end;
procedure TProjectViewForm.UpdateServers;
var
i: Integer;
begin
Tree.Items.BeginUpdate;
try
ServersNode.DeleteChildren;
for i := 0 to Pred(Project.Servers.Count) do
with Project.Servers[i] do
with Tree.Items.AddChild(ServersNode, Name) do
begin
ImageIndex := Ord(Target);
if Project.Servers.DefaultIdent = Ident then
OverlayIndex := 0;
end;
ServersNode.AlphaSort(true);
ServersNode.Expand(true);
finally
Tree.Items.EndUpdate;
end;
end;
procedure TProjectViewForm.UpdateTables(inProfile: TServerDatabaseProfile);
var
n: TTreeNode;
db: ThtDb;
s: TStringList;
i: Integer;
begin
n := Tree.Items.AddChild(DatabasesNode, inProfile.Name);
n.ImageIndex := 4;
if inProfile.Databases.Count > 0 then
begin
db := ThtDb.Create(nil);
try
db.Profile := inProfile.Databases[0] ;
db.Connected := true;
if db.Connected then
begin
s := TStringList.Create;
try
db.ListTables(s);
for i := 0 to Pred(s.Count) do
Tree.Items.AddChild(n, s[i]).ImageIndex := 10;
finally
s.Free;
end;
end;
finally
db.Free;
end;
end;
end;
procedure TProjectViewForm.UpdateDatabases;
var
i: Integer;
begin
Tree.Items.BeginUpdate;
try
DatabasesNode.DeleteChildren;
for i := 0 to Pred(Project.Databases.Count) do
UpdateTables(Project.Databases[i]);
DatabasesNode.AlphaSort(true);
DatabasesNode.Expand(true);
finally
Tree.Items.EndUpdate;
end;
end;
procedure TProjectViewForm.UpdateItems;
var
i: Integer;
n: TTreeNode;
//c: TLrNodeCache;
begin
Tree.Items.BeginUpdate;
try
//c := LrCreateNodeCache(Tree);
try
ItemsNode.DeleteChildren;
for i := 0 to Pred(Project.Items.Count) do
with Project.Items[i] do
begin
n := Tree.Items.AddChild(ItemsNode, DisplayName);
n.ImageIndex := 15; //ImageIndex;
end;
ItemsNode.AlphaSort(true);
ItemsNode.Expand(true);
finally
//LrConsumeNodeCache(Tree, c);
end;
finally
Tree.Items.EndUpdate;
end;
end;
procedure TProjectViewForm.AddFolderActionExecute(Sender: TObject);
var
item: TSubItemsItem;
begin
with Tree do
if (Selected <> nil) and (Selected.HasAsParent(ItemsNode)) then
begin
item := TSubitemsItem.Create;
Project.AddItem(item);
end;
end;
end.
|
PROGRAM RandNum;
VAR
x: LONGINT;
FUNCTION IntRand: INTEGER;
const
A = 3421;
K = 1;
BEGIN
x := (A * x + K) MOD (High(INTEGER) + 1);
IntRand := x;
END;
// 0 <= x < n
FUNCTION WrongRangeRand(n: INTEGER): INTEGER;
BEGIN
WrongRangeRand := IntRand MOD n;
END;
FUNCTION RangeRand(n: INTEGER): INTEGER;
VAR
x: INTEGER;
BEGIN
REPEAT
x := IntRand;
UNTIL x < ((High(INTEGER) + 1) DIV n) * n;
RangeRand := x MOD n;
END;
// 0.0 <= x < 1.0
FUNCTION RealRand: REAL;
BEGIN
RealRand := IntRand / (High(Integer) + 1);
END;
FUNCTION ApproxPi(n: LONGINT): REAL;
VAR
k, i: LONGINT;
x, y: REAL;
BEGIN
k := 0;
FOR i := 1 TO n DO BEGIN
x := RealRand;
y := RealRand;
IF (x * x) + (y * y) < 1 then
k := k +1;
END;
ApproxPi := 4 * k / n;
END;
VAR
i: LONGINT;
BEGIN
FOR i := 1 To 10000 DO BEGIN
x := 0;
WriteLn(i * 100, ': ', ApproxPi(i * 100));
END;
END.
// VAR
// i: INTEGER;
// BEGIN
// x := 0; // RandSeed
// FOR i := 1 TO 10 DO
// Write(IntRand, ' ');
// WriteLn;
// x := 0;
// FOR i := 1 TO 10 DO
// Write(IntRand, ' ');
// WriteLn;
// END. |
unit uSprOrder;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, DB, ADODB, StdCtrls, Grids, DBGrids, StrUtils, ImgList,
uSprJoin, Math, Buttons;
type
TsprOrderItem = class(TCollectionItem)
private
FDesc: Boolean;
FFieldName: string;
FCaption: string;
FOrder: string;
FJoin: TsprJoin;
procedure SetFieldName(const Value: string);
procedure Clear;
public
constructor Create(Collection: TCollection); override;
destructor Destroy; override;
function GetAsString: string;
function GetJoinAlias: string;
property Join: TsprJoin read FJoin;
property Order: string read FOrder;
published
property FieldName: string read FFieldName write
SetFieldName;
property Desc: Boolean read FDesc write FDesc;
property Caption: string read FCaption;
end;
TsprOrder = class(TOwnedCollection)
protected
function GetItem(Index: Integer): TsprOrderItem;
//procedure SetItem(Index: Integer; AObject: TsprOrderItem);
procedure SetAsString(const Value: string);
public
constructor Create(Owner: TPersistent);
destructor Destroy; override;
property Items[Index: Integer]: TsprOrderItem read GetItem;// write SetItem; default;
//Find existing item by PropertyName
function Find(FieldName: string): TsprOrderItem;
//Find or Create filter by Property Name
function Add(FieldName: string; Desc: Boolean = False): TsprOrderItem;
function Remove(FieldName: string): Integer;
//procedure Clear; reintroduce;
procedure By(FieldNames: string; InvertExistingOrder: Boolean = True);
end;
implementation
constructor TsprOrderItem.Create(Collection: TCollection);
begin
inherited;
FJoin := TsprJoin.Create;
FDesc := False;
end;
destructor TsprOrderItem.Destroy;
begin
FJoin.Free;
inherited;
end;
procedure TsprOrderItem.Clear;
begin
FJoin.Clear;
FFieldName := '';
FOrder := '';
FCaption := '';
end;
procedure TsprOrderItem.SetFieldName(const Value: string);
var
vDS: TDataSet;
vField: TField;
vStr: string;
L: TStringList;
begin
if FFieldName = Value then
Exit;
vDS := TDataSet(Collection.Owner);
vField := vDS.FindField(Value);
Clear;
if Assigned(vField) then
begin
if vField.FieldKind in [fkCalculated] then
Exit;
FFieldName := Value;
FCaption := vField.DisplayLabel;
if vField.Origin <> '' then
vStr := vField.Origin
else
vStr := vField.FieldName;
FJoin.ProcessField(vField, vStr, GetJoinAlias, FOrder);
end;
end;
function TsprOrderItem.GetJoinAlias: string;
begin
Result := 'spr_order' + IntToStr(Self.ID);
end;
function TsprOrderItem.GetAsString: string;
begin
Result := '';
if FieldName <> '' then
begin
if Desc then
Result := Order + ' desc'
else
Result := Order;
end;
end;
//********************************
constructor TsprOrder.Create(Owner: TPersistent);
begin
inherited Create(Owner, TsprOrderItem);
end;
destructor TsprOrder.Destroy;
begin
inherited;
end;
function TsprOrder.Find(FieldName: string): TsprOrderItem;
var
i: Integer;
begin
for i := 0 to Count - 1 do
begin
Result := Items[i];
if SameText(Result.FieldName, FieldName) then
Exit;
end;
Result := nil;
end;
function TsprOrder.GetItem(Index: Integer): TsprOrderItem;
begin
Result := TsprOrderItem(inherited GetItem(Index));
end;
function TsprOrder.Remove(FieldName: string): Integer;
var
Item: TsprOrderItem;
begin
Item := Find(FieldName);
if Item = nil then
Result := -1
else
begin
Result := Item.Index;
Item.Free;
end;
end;
function TsprOrder.Add(FieldName: string; Desc: Boolean = False): TsprOrderItem;
begin
Result := (inherited Add as TsprOrderItem);
Result.FieldName := FieldName;
Result.Desc := Desc;
end;
procedure TsprOrder.SetAsString(const Value: string);
var
i: Integer;
s: string;
begin
Clear;
try
s := '';
for i := 1 to Length(Value) do
if Value[i] in [',', ';'] then
begin
Add(s);
s := '';
end
else
s := s + Value[i];
if s <> '' then
Add(s);
except
Clear;
raise;
end
end;
procedure TsprOrder.By(FieldNames: string; InvertExistingOrder: Boolean = True);
procedure SetupOrder(FieldName: string);
var
OrderItem: TsprOrderItem;
begin
OrderItem := Find(FieldName);
if OrderItem <> nil then
begin
if InvertExistingOrder then
OrderItem.Desc := not OrderItem.Desc;
end
else
SetAsString(FieldName);
end;
begin
SetupOrder(FieldNames);
end;
end.
|
unit TerminologyServices;
interface
uses
SysUtils, Classes,
StringSupport,
AdvObjects, AdvStringLists,
FHIRTypes, FHIRComponents, FHIRResources,
YuStemmer;
Type
TFhirFilterOperator = FHIRTypes.TFhirFilterOperator;
TCodeSystemProviderContext = class (TAdvObject)
public
function Link : TCodeSystemProviderContext; overload;
end;
TCodeSystemProviderFilterContext = class (TAdvObject)
public
function Link : TCodeSystemProviderFilterContext; overload;
end;
TCodeSystemProviderFilterPreparationContext = class (TAdvObject)
public
function Link : TCodeSystemProviderFilterPreparationContext; overload;
end;
TSearchFilterText = class (TAdvObject)
private
FFilter: string;
FStems : TStringList;
FStemmer : TYuStemmer_8;
procedure process;
public
constructor Create(filter : String); overload;
destructor Destroy; override;
function Link : TSearchFilterText; overload;
function null : Boolean;
function passes(value : String) : boolean; overload;
function passes(stems : TAdvStringList) : boolean; overload;
property filter : string read FFilter;
property stems : TStringList read FStems;
end;
TCodeSystemProvider = {abstract} class (TAdvObject)
public
function Link : TCodeSystemProvider; overload;
function TotalCount : integer; virtual; abstract;
function ChildCount(context : TCodeSystemProviderContext) : integer; virtual; abstract;
function getcontext(context : TCodeSystemProviderContext; ndx : integer) : TCodeSystemProviderContext; virtual; abstract;
function system : String; virtual; abstract;
function getDisplay(code : String):String; virtual; abstract;
function locate(code : String) : TCodeSystemProviderContext; virtual; abstract;
function locateIsA(code, parent : String) : TCodeSystemProviderContext; virtual; abstract;
function IsAbstract(context : TCodeSystemProviderContext) : boolean; virtual; abstract;
function Code(context : TCodeSystemProviderContext) : string; virtual; abstract;
function Display(context : TCodeSystemProviderContext) : string; virtual; abstract;
procedure Displays(context : TCodeSystemProviderContext; list : TStringList); overload; virtual; abstract;
procedure Displays(code : String; list : TStringList); overload; virtual; abstract;
function doesFilter(prop : String; op : TFhirFilterOperator; value : String) : boolean; virtual;
function getPrepContext : TCodeSystemProviderFilterPreparationContext; virtual;
function searchFilter(filter : TSearchFilterText; prep : TCodeSystemProviderFilterPreparationContext) : TCodeSystemProviderFilterContext; virtual; abstract;
function filter(prop : String; op : TFhirFilterOperator; value : String; prep : TCodeSystemProviderFilterPreparationContext) : TCodeSystemProviderFilterContext; virtual; abstract;
function prepare(prep : TCodeSystemProviderFilterPreparationContext) : boolean; virtual; // true if the underlying provider collapsed multiple filters
function filterLocate(ctxt : TCodeSystemProviderFilterContext; code : String) : TCodeSystemProviderContext; virtual; abstract;
function FilterMore(ctxt : TCodeSystemProviderFilterContext) : boolean; virtual; abstract;
function FilterConcept(ctxt : TCodeSystemProviderFilterContext): TCodeSystemProviderContext; virtual; abstract;
function InFilter(ctxt : TCodeSystemProviderFilterContext; concept : TCodeSystemProviderContext) : Boolean; virtual; abstract;
procedure Close(ctxt : TCodeSystemProviderFilterPreparationContext); overload; virtual;
procedure Close(ctxt : TCodeSystemProviderFilterContext); overload; virtual; abstract;
procedure Close(ctxt : TCodeSystemProviderContext); overload; virtual; abstract;
end;
implementation
{ TCodeSystemProvider }
procedure TCodeSystemProvider.Close(ctxt: TCodeSystemProviderFilterPreparationContext);
begin
// do nothing
end;
function TCodeSystemProvider.doesFilter(prop: String; op: TFhirFilterOperator; value: String): boolean;
var
ctxt : TCodeSystemProviderFilterContext;
begin
ctxt := filter(prop, op, value, nil);
result := ctxt <> nil;
if result then
Close(ctxt);
end;
function TCodeSystemProvider.getPrepContext: TCodeSystemProviderFilterPreparationContext;
begin
result := nil;
end;
function TCodeSystemProvider.Link: TCodeSystemProvider;
begin
result := TCodeSystemProvider(inherited link);
end;
function TCodeSystemProvider.prepare(prep : TCodeSystemProviderFilterPreparationContext) : boolean;
begin
result := false;
end;
{ TSearchFilterText }
constructor TSearchFilterText.create(filter: String);
begin
Create;
FStemmer := GetStemmer_8('english');
FStems := TStringList.Create;
FFilter := filter;
process;
end;
destructor TSearchFilterText.destroy;
begin
FStems.Free;
FStemmer.Free;
inherited;
end;
function TSearchFilterText.Link: TSearchFilterText;
begin
result := TSearchFilterText(inherited link);
end;
function TSearchFilterText.null: Boolean;
begin
result := FStems.Count = 0;
end;
function TSearchFilterText.passes(value: String): boolean;
var
s : String;
i : integer;
begin
result := Null;
while not result and (value <> '') Do
begin
StringSplit(value, [',', ' ', ':', '.', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '{', '}', '[', ']', '|', '\', ';', '"', '<', '>', '?', '/', '~', '`', '-', '_', '+', '='], s, value);
if (s <> '') Then
result := FStems.Find(lowercase(FStemmer.stem(s)), i);
End;
end;
function TSearchFilterText.passes(stems: TAdvStringList): boolean;
var
i, j : integer;
begin
result := Null;
for i := 0 to stems.count - 1 do
result := result or FStems.find(stems[i], j);
end;
procedure TSearchFilterText.process;
var
s, t : String;
begin
t := FFilter;
while (t <> '') Do
begin
StringSplit(t, [',', ' ', ':', '.', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '{', '}', '[', ']', '|', '\', ';', '"', '<', '>', '?', '/', '~', '`', '-', '_', '+', '='], s, t);
if (s <> '') Then
FStems.Add(lowercase(FStemmer.stem(s)));
End;
FStems.Sort;
end;
{ TCodeSystemProviderContext }
function TCodeSystemProviderContext.Link: TCodeSystemProviderContext;
begin
result := TCodeSystemProviderContext(inherited link);
end;
{ TCodeSystemProviderFilterContext }
function TCodeSystemProviderFilterContext.Link: TCodeSystemProviderFilterContext;
begin
result := TCodeSystemProviderFilterContext(inherited link);
end;
{ TCodeSystemProviderFilterPreparationContext }
function TCodeSystemProviderFilterPreparationContext.Link: TCodeSystemProviderFilterPreparationContext;
begin
result := TCodeSystemProviderFilterPreparationContext(inherited Link);
end;
end.
|
(*
Category: SWAG Title: DATE & TIME ROUTINES
Original name: 0017.PAS
Description: TIME2.PAS
Author: SWAG SUPPORT TEAM
Date: 05-28-93 13:37
*)
{ PW>question, I want to declare Type Time as (Hour,Min). Where hour and
PW>minute are predeifed Types 0..23 and 0..59 respectively. I then take
PW>the Type Time and use it as a field in a Record. How would I promt a
PW>user to enter the time? Ie. Enter (date,min): ??? Is there a way to do
PW>this without reading a String and then Formatting it and changing it to
PW>Integers?
It can be done, but it's probably not worth the efFort to process it that
way. I do this a lot, and I allow entering the Time as hh:mm or hhmm, where
it's simply a String. then, I parse out the ":", if it exists, and do a couple
of divide and mod operations to then convert it to seconds - and store it that
way. I also have a routine which will Format seconds into time. I do this
enough (I'm in the race timing business), that I've found it easy to do this
throughout my system - and keep all data in seconds. I have a
parsing/conversion routine and a conversion/display routine in my global Unit.
Something like this:
}
Var S : String;
I,T,N : Word;
begin
Write ('Enter Time as hh:mm '); readln (S);
if Pos(':',S) > 0 then Delete (S,Pos(':',S),1); Val (S,I,N);
T := ((I div 100) * 3600) + ((I mod 100) * 60);
Write(T);
end.
{
There should be some error-checking in this, but I'm sure you can figure it
out...
}
|
// Wheberson Hudson Migueletti, em Brasília, 1999.
// Para mostrar o conteúdo de arquivos ZIP
unit DelphiZip;
interface
uses Windows, Classes, SysUtils;
const
cLocal_File_Header_Signature = $04034B50;
cCentral_File_Header_Signature= $02014B50;
cEnd_Central_Dir_Signature = $06054B50;
type
Local_File_Header= packed record
Version_Needed_To_Extract: Word;
General_Purpose_Bit_Flag : Word;
Compression_Method : Word;
Last_Mod_File_Time : Word;
Last_Mod_File_Date : Word;
Crc32 : LongInt;
Compressed_Size : LongInt;
Uncompressed_Size : LongInt;
Filename_Length : Word;
Extra_Field_Length : Word;
end;
Central_Directory_File_Header= packed record
Version_Made_By : Word;
Version_Needed_To_Extract : Word;
General_Purpose_Bit_Flag : Word;
Compression_Method : Word;
Last_Mod_File_Time : Word;
Last_Mod_File_Date : Word;
Crc32 : LongInt;
Compressed_Size : LongInt;
Uncompressed_Size : LongInt;
Filename_Length : Word;
Extra_Field_Length : Word;
File_Comment_Length : Word;
Disk_Number_Start : Word;
Internal_File_Attributes : Word;
External_File_Attributes : LongInt;
Relative_Offset_Local_Header: LongInt;
end;
End_Central_Dir_Record= packed record
Number_This_Disk : Word;
Number_Disk_With_Start_Central_Directory: Word;
Total_Entries_Central_Dir_On_This_Disk : Word;
Total_Entries_Central_Dir : Word;
Size_Central_Directory : LongInt;
Offset_Start_Central_Directory : LongInt;
Zipfile_Comment_Length : Word;
end;
PInfoZip= ^TInfoZip;
TInfoZip= record
Descompactado: LongInt;
Compactado : LongInt;
Modificado : TDateTime;
end;
TZip= class
protected
Stream: TStream;
function Armazenar (Arquivo: String; Descompactado, Compactado: LongInt; Data, Hora: Word): Boolean;
public
Status: Boolean;
Lista : TStringList;
constructor Create;
destructor Destroy; override;
function ExtrairNomePath (const Completo: String; var Path: String): String;
function IsValid (const FileName: String): Boolean;
procedure LoadFromFile (const FileName: String);
end;
implementation
type
PBuffer= ^TBuffer;
TBuffer= array[1..1] of Char;
function Converter (Buffer: PBuffer; Tamanho: Integer): String;
var
K: Integer;
begin
SetLength (Result, Tamanho);
for K:= 1 to Tamanho do
Result[K]:= Buffer^[K];
end; // Converter ()
constructor TZip.Create;
begin
inherited Create;
Lista:= TStringList.Create;
end; // Create ()
destructor TZip.Destroy;
begin
Lista.Free;
inherited Destroy;
end; // Destroy ()
function TZip.ExtrairNomePath (const Completo: String; var Path: String): String;
var
K, P: Integer;
begin
P:= 0;
for K:= Length (Completo) downto 1 do
if (Completo[K] = '\') or (Completo[K] = '/') then begin
P:= K;
Break;
end;
Result:= Copy (Completo, P+1, Length (Completo)-P);
if P > 0 then
Path:= Copy (Completo, 1, P)
else
Path:= '';
end; // ExtrairNomePath ()
function TZip.Armazenar (Arquivo: String; Descompactado, Compactado: LongInt; Data, Hora: Word): Boolean;
var
Aux : LongInt;
Info : PInfoZip;
DataHora: TDateTime;
begin
Status:= False;
try
try
LongRec (Aux).Hi:= Data;
LongRec (Aux).Lo:= Hora;
DataHora := FileDateToDateTime (Aux);
except
DataHora:= 0;
end;
New (Info);
Info^.Descompactado:= Descompactado;
Info^.Compactado := Compactado;
Info^.Modificado := DataHora;
Lista.AddObject (Arquivo, TObject (Info));
Status:= True;
finally
Result:= Status;
end;
end; // Armazenar ()
function TZip.IsValid (const FileName: String): Boolean;
var
Signature: LongInt;
begin
Result:= False;
Status:= False;
if FileExists (Filename) then begin
try
Stream:= TFileStream.Create (FileName, fmOpenRead);
Result:= (Stream.Read (Signature, SizeOf (LongInt)) = SizeOf (LongInt)) and (Signature = cLocal_File_Header_Signature);
Status:= True;
finally
Stream.Free;
end;
end;
end; // IsValid ()
procedure TZip.LoadFromFile (const FileName: String);
var
Signature: LongInt;
procedure CapturarLocalFileHeader;
var
Local: Local_File_Header;
begin
try
Stream.Read (Local, SizeOf (Local_File_Header));
with Local do
Stream.Seek (Compressed_Size + Filename_Length + Extra_Field_Length, soFromCurrent);
except
Status:= False;
end;
end; // CapturarLocalFileHeader ()
procedure CapturarCentralFileHeader;
var
Buffer : PBuffer;
Central: Central_Directory_File_Header;
begin
Status:= False;
try
Stream.Read (Central, SizeOf (Central_Directory_File_Header));
except
Exit;
end;
with Central do begin
try
GetMem (Buffer, Filename_Length);
Stream.Read (Buffer^, Filename_Length);
if Armazenar (Converter (Buffer, Filename_Length), Uncompressed_Size, Compressed_Size, Last_Mod_File_Date, Last_Mod_File_Time) then begin
Stream.Seek (Extra_Field_Length + File_Comment_Length, soFromCurrent);
Status:= True;
end;
finally
FreeMem (Buffer, Filename_Length);
end;
end;
end; // CapturarCentralFileHeader ()
procedure CapturarEndFileHeader;
var
EndHeader: End_Central_Dir_Record;
begin
try
Stream.Read (EndHeader, SizeOf (End_Central_Dir_Record));
with EndHeader do
Stream.Seek (Zipfile_Comment_Length, soFromCurrent);
except
Status:= False;
end;
end; // CapturarEndFileHeader ()
begin
Status:= False;
try
Stream:= TMemoryStream.Create;
TMemoryStream (Stream).LoadFromFile (FileName);
Lista.Clear;
Status:= True;
while Status and (Stream.Position < Stream.Size) do begin
try
Stream.Read (Signature, SizeOf (LongInt));
case Signature of
cLocal_File_Header_Signature : CapturarLocalFileHeader;
cCentral_File_Header_Signature: CapturarCentralFileHeader;
cEnd_Central_Dir_Signature : CapturarEndFileHeader;
end;
except
Status:= False;
end;
end;
finally
Stream.Free;
end;
end; // LoadFromFile ()
end.
// Final do Arquivo
|
unit OvExpTypeRef;
interface
uses uCommonForm,
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
Base, StdCtrls, Menus, Db, DBTables, Grids, DBGridEh, Buttons,
ExtCtrls,uOilQuery,Ora, uOilStoredProc, ActnList, MemDS, DBAccess,
RXCtrls;
type
TOvExpTypeRefForm = class(TBaseForm)
Label1: TLabel;
edName: TEdit;
qID: TFloatField;
qNAME: TStringField;
procedure bbSearchClick(Sender: TObject);
procedure bbClearClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
OvExpTypeRefForm: TOvExpTypeRefForm;
implementation
{$R *.DFM}
procedure TOvExpTypeRefForm.bbSearchClick(Sender: TObject);
begin
Try
With q Do
Begin
Close;
SQL.Clear;
SQL.Add('Select * from V_OIL_OV_EXP_TYPE');
If edName.Text <> '' Then
SQL.Add('Where Upper(name) like ''%'+ANSIUpperCase(edName.Text)+'%''');
SQL.Add('order by NAME');
Open;
End;
Except On E:Exception Do
MessageDlg(TranslateText('Îøèáêà : ')+E.message,mtError,[mbOk],0);
End;
end;
procedure TOvExpTypeRefForm.bbClearClick(Sender: TObject);
begin
edName.Clear;
end;
procedure TOvExpTypeRefForm.FormShow(Sender: TObject);
begin
bbClearClick(Nil);
edName.SetFocus;
bbSearchClick(nil);
end;
end.
|
unit CCJSO_MyOrder;
{
© PgkSoft 04.09.2015
Журнал интернет заказов
Механизм избранных заказов
Подчиненный раздел «Управление избранными заказами»
}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ToolWin, ComCtrls, ExtCtrls, DB, ADODB, ActnList, Grids, DBGrids,
StdCtrls, Menus;
type
TRetCondMyOrder = Record
Order : integer;
NUser : integer;
SUser : string;
end;
type
TfrmCCJSO_MyOrder = class(TForm)
pnlCond: TPanel;
pnlTool: TPanel;
pnlControl: TPanel;
pnlControl_Bar: TPanel;
pnlControl_Status: TPanel;
StatusBar: TStatusBar;
pnlGrid: TPanel;
tlbarControl: TToolBar;
pnlTool_Show: TPanel;
pnlTool_Bar: TPanel;
ToolBar: TToolBar;
MainGrid: TDBGrid;
ActionList: TActionList;
dsMark: TDataSource;
qrspMark: TADOStoredProc;
aControl_Exit: TAction;
aControl_CondOrder: TAction;
aControl_CondUserOrders: TAction;
tlbtnControl_CondOrder: TToolButton;
tlbtnControl_CondUserOrders: TToolButton;
tlbtnControl_Exit: TToolButton;
lblCondUser: TLabel;
edCondUser: TEdit;
aCodition: TAction;
aTool_RP_MarkOrders: TAction;
tlbtnPM_Report: TToolButton;
pmReport: TPopupMenu;
pmiTool_RP_MarkOrders: TMenuItem;
qrspRPMyOrders: TADOStoredProc;
procedure FormCreate(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure aControl_ExitExecute(Sender: TObject);
procedure aControl_CondOrderExecute(Sender: TObject);
procedure aControl_CondUserOrdersExecute(Sender: TObject);
procedure MainGridDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
procedure aCoditionExecute(Sender: TObject);
procedure aTool_RP_MarkOrdersExecute(Sender: TObject);
procedure dsMarkDataChange(Sender: TObject; Field: TField);
private
{ Private declarations }
ISignActive : smallint;
ISignReturn : smallint;
USER : integer;
RetCondMyOrder : TRetCondMyOrder;
procedure ShowGets;
procedure ExecCondition;
procedure CreateCondition;
public
{ Public declarations }
procedure SetUser(Parm : integer);
function GetSignReturn : smallint;
function GetCondMyOrder : TRetCondMyOrder;
end;
const
cJSOMyOrder_ReturnExit = 0;
cJSOMyOrder_ReturnCondOrder = 1;
cJSOMyOrder_ReturnCondUserOrders = 2;
var
frmCCJSO_MyOrder: TfrmCCJSO_MyOrder;
implementation
uses
StrUtils, Util, ComObj, Excel97, DateUtils,
Umain, UCCenterJournalNetZkz, ExDBGRID;
{$R *.dfm}
procedure TfrmCCJSO_MyOrder.FormCreate(Sender: TObject);
begin
{ Инициализация }
ISignActive := 0;
ISignReturn := cJSOMyOrder_ReturnExit;
RetCondMyOrder.Order := 0;
RetCondMyOrder.NUser := 0;
RetCondMyOrder.SUser := '';
end;
procedure TfrmCCJSO_MyOrder.FormActivate(Sender: TObject);
begin
if ISignActive = 0 then begin
{ Стартовая настройка свойств }
{ Иконка формы }
//FCCenterJournalNetZkz.imgMain.GetIcon(310,self.Icon);
{ Форма активна }
ISignActive := 1;
ExecCondition;
ShowGets;
end;
end;
procedure TfrmCCJSO_MyOrder.ShowGets;
var
SCaption : string;
begin
if ISignActive = 1 then begin
SCaption := VarToStr(qrspMark.RecordCount);
pnlTool_Show.Caption := SCaption; pnlTool_Show.Width := TextPixWidth(SCaption, pnlTool_Show.Font) + 20;
if qrspMark.IsEmpty then begin
{ Пустой набор данных }
aControl_CondOrder.Enabled := false;
aControl_CondUserOrders.Enabled := false;
RetCondMyOrder.Order := 0;
RetCondMyOrder.NUser := 0;
RetCondMyOrder.SUser := '';
end else begin
{ НЕ пустой набор данных }
aControl_CondOrder.Enabled := true;
aControl_CondUserOrders.Enabled := true;
end;
end;
end;
procedure TfrmCCJSO_MyOrder.SetUser(Parm : integer); begin USER := Parm; end;
function TfrmCCJSO_MyOrder.GetSignReturn : smallint; begin result := ISignReturn; end;
function TfrmCCJSO_MyOrder.GetCondMyOrder : TRetCondMyOrder; begin result := RetCondMyOrder; end;
procedure TfrmCCJSO_MyOrder.ExecCondition;
var
RN: Integer;
begin
if not qrspMark.IsEmpty then RN := qrspMark.FieldByName('NRN').AsInteger else RN := -1;
if qrspMark.Active then qrspMark.Active := false;
CreateCondition;
qrspMark.Active := true;
qrspMark.Locate('NRN', RN, []);
end;
procedure TfrmCCJSO_MyOrder.CreateCondition;
var
SUser : string;
begin
SUser := '';
if length(trim(edCondUser.Text)) <> 0 then SUser := edCondUser.Text;
qrspMark.Parameters.ParamValues['@User'] := SUser;
end;
procedure TfrmCCJSO_MyOrder.aControl_ExitExecute(Sender: TObject);
begin
ISignReturn := cJSOMyOrder_ReturnExit;
self.Close;
end;
procedure TfrmCCJSO_MyOrder.aControl_CondOrderExecute(Sender: TObject);
begin
ISignReturn := cJSOMyOrder_ReturnCondOrder;
self.Close;
end;
procedure TfrmCCJSO_MyOrder.aControl_CondUserOrdersExecute(Sender: TObject);
begin
ISignReturn := cJSOMyOrder_ReturnCondUserOrders;
self.Close;
end;
procedure TfrmCCJSO_MyOrder.MainGridDrawColumnCell(Sender: TObject; const Rect: TRect; DataCol: Integer; Column: TColumn; State: TGridDrawState);
var
db: TDBGrid;
begin
if Sender = nil then Exit;
db := TDBGrid(Sender);
if (gdSelected in State) then begin
db.Canvas.Font.Style := [fsBold];
end;
db.DefaultDrawColumnCell(Rect, DataCol, Column, State);
end;
procedure TfrmCCJSO_MyOrder.aCoditionExecute(Sender: TObject);
begin
if ISignActive = 1 then begin
{ Формируем условие отбора }
ExecCondition;
end;
end;
procedure TfrmCCJSO_MyOrder.aTool_RP_MarkOrdersExecute(Sender: TObject);
var
vExcel : OleVariant;
vDD : OleVariant;
WS : OleVariant;
Cells : OleVariant;
I : integer;
iExcelNumLineStart : integer;
iExcelNumLine : integer;
fl_cnt : integer;
num_cnt : integer;
iInteriorColor : integer;
iHorizontalAlignment : integer;
RecNumb : integer;
RecCount : integer;
SFontSize : string;
SUser : string;
begin
SFontSize := '10';
try
StatusBar.SimpleText := 'Запуск табличного процессора...';
vExcel := CreateOLEObject('Excel.Application');
vDD := vExcel.Workbooks.Add;
WS := vDD.Sheets[1];
iExcelNumLine := 0;
{ Заголовок отчета }
inc(iExcelNumLine);
vExcel.ActiveCell[iExcelNumLine, 1].Value := 'Избранные заказы';
inc(iExcelNumLine);
vExcel.ActiveCell[iExcelNumLine, 1].Value := 'Дата формирования: ' + FormatDateTime('dd-mm-yyyy hh:nn:ss', Now);
inc(iExcelNumLine);
StatusBar.SimpleText := 'Формирование набора данных...';
if qrspRPMyOrders.Active then qrspRPMyOrders.Active := false;
SUser := '';
if length(trim(edCondUser.Text)) <> 0 then SUser := edCondUser.Text;
qrspMark.Parameters.ParamValues['@User'] := SUser;
qrspRPMyOrders.Open;
RecCount := qrspRPMyOrders.RecordCount;
RecNumb := 0;
{ Заголовок таблицы }
inc(iExcelNumLine);
iExcelNumLineStart := iExcelNumLine;
fl_cnt := qrspRPMyOrders.FieldCount;
for I := 1 to fl_cnt do begin
vExcel.ActiveCell[iExcelNumLine, I].Value := qrspRPMyOrders.Fields[I - 1].FieldName;
SetPropExcelCell(WS, i, iExcelNumLine, 19, xlCenter);
vExcel.Cells[iExcelNumLine, I].Font.Size := SFontSize;
end;
{ Вывод таблицы }
qrspRPMyOrders.First;
while not qrspRPMyOrders.Eof do begin
inc(RecNumb);
StatusBar.SimpleText := 'Формирование отчета: '+VarToStr(RecNumb)+'/'+VarToStr(RecCount);
inc(iExcelNumLine);
for num_cnt := 1 to fl_cnt do begin
vExcel.ActiveCell[iExcelNumLine, num_cnt].Value := qrspRPMyOrders.Fields[num_cnt - 1].AsString;
SetPropExcelCell(WS, num_cnt, iExcelNumLine, 0, xlLeft);
vExcel.Cells[iExcelNumLine, num_cnt].Font.Size := SFontSize;
end;
qrspRPMyOrders.Next;
end;
{ Ширина колонок }
vExcel.Columns[01].ColumnWidth := 20; { Исполнитель }
vExcel.Columns[02].ColumnWidth := 10; { Закреплено }
vExcel.Columns[03].ColumnWidth := 20; { Направлено от }
vExcel.Columns[04].ColumnWidth := 07; { Заказ }
vExcel.Columns[05].ColumnWidth := 10; { Дата заказа }
vExcel.Columns[06].ColumnWidth := 20; { Клиент }
vExcel.Columns[07].ColumnWidth := 10; { Сумма }
{ Перенос слов }
WS.Range[CellName(01,iExcelNumLineStart) + ':' + CellName(fl_cnt,iExcelNumLine)].WrapText:=true;
inc(iExcelNumLine);
{ Показываем }
vExcel.Visible := True;
except
on E: Exception do begin
if vExcel = varDispatch then vExcel.Quit;
end;
end;
StatusBar.SimpleText := '';
end;
procedure TfrmCCJSO_MyOrder.dsMarkDataChange(Sender: TObject; Field: TField);
begin
if qrspMark.IsEmpty then begin
RetCondMyOrder.Order := 0;
RetCondMyOrder.NUser := 0;
RetCondMyOrder.SUser := '';
end else begin
RetCondMyOrder.Order := MainGrid.DataSource.DataSet.FieldByName('NOrder').AsInteger;
RetCondMyOrder.NUser := MainGrid.DataSource.DataSet.FieldByName('NUSer').AsInteger;
RetCondMyOrder.SUser := MainGrid.DataSource.DataSet.FieldByName('SUSer').AsString;
end;
end;
end.
|
{******************************************************************************}
{ CnPack For Delphi/C++Builder }
{ 中国人自己的开放源码第三方开发包 }
{ (C)Copyright 2001-2017 CnPack 开发组 }
{ ------------------------------------ }
{ }
{ 本开发包是开源的自由软件,您可以遵照 CnPack 的发布协议来修 }
{ 改和重新发布这一程序。 }
{ }
{ 发布这一开发包的目的是希望它有用,但没有任何担保。甚至没有 }
{ 适合特定目的而隐含的担保。更详细的情况请参阅 CnPack 发布协议。 }
{ }
{ 您应该已经和开发包一起收到一份 CnPack 发布协议的副本。如果 }
{ 还没有,可访问我们的网站: }
{ }
{ 网站地址:http://www.cnpack.org }
{ 电子邮件:master@cnpack.org }
{ }
{******************************************************************************}
unit CnConsole;
{* |<PRE>
================================================================================
* 软件名称:不可视工具组件包
* 单元名称:控制台组件 TCnConsole 单元
* 单元作者:刘啸 (liuxiao@cnpack.org)
* 菩提
* 备 注:为 GUI 程序增加控制台
* 开发平台:PWinXP + Delphi 5.0
* 兼容测试:PWinXP + Delphi 5.0
* 本 地 化:该单元中无字符串资源
* 单元标识:$Id$
* 修改记录:2008.10.14 v1.1
* 菩提加入控制文本颜色的功能
* 2006.10.05 v1.0
* 创建单元
================================================================================
|</PRE>}
interface
{$I CnPack.inc}
uses
SysUtils, Classes, Windows,
CnClasses, CnConsts, CnCompConsts;
{控制台文本的颜色常量}
const
tfBlue =1;
tfGreen =2;
tfRed =4;
tfIntensity = 8;
tfWhite = $f;
tbBlue =$10;
tbGreen =$20;
tbRed =$40;
tbIntensity = $80;
type
TCnConsole = class(TCnComponent)
private
FConsoleTitle: string;
FEnabled: Boolean;
FConsoleHandle:THandle;
procedure SetConsoleTitle(const Value: string);
procedure SetEnabled(const Value: Boolean);
protected
procedure GetComponentInfo(var AName, Author, Email, Comment: string); override;
public
procedure ResetConsole;
{* 复位控制台,在属性Enabled为True时有效。}
procedure SetTextColor(const aColor:WORD);
{* 设置控制台的前景颜色}
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property Enabled: Boolean read FEnabled write SetEnabled;
{* 为True时启动控制台,为False关闭控制台}
property ConsoleTitle: string read FConsoleTitle write SetConsoleTitle;
{* 控制台的标题}
end;
implementation
{ TCnConsole }
constructor TCnConsole.Create(AOwner: TComponent);
begin
inherited;
FEnabled := False;
end;
destructor TCnConsole.Destroy;
begin
if not (csDesigning in ComponentState) and FEnabled then
FreeConsole;
inherited;
end;
procedure TCnConsole.GetComponentInfo(var AName, Author, Email,
Comment: string);
begin
AName := SCnConsoleName;
Author := SCnPack_LiuXiao;
Email := SCnPack_LiuXiaoEmail;
Comment := SCnConsoleComment;
end;
procedure TCnConsole.ResetConsole;
begin
if csDesigning in ComponentState then
Exit;
if FEnabled then
begin
FreeConsole;
AllocConsole;
FConsoleHandle := GetStdHandle(STD_OUTPUT_HANDLE);
if FConsoleTitle <> '' then
Windows.SetConsoleTitle(PChar(FConsoleTitle));
end;
end;
procedure TCnConsole.SetConsoleTitle(const Value: string);
begin
FConsoleTitle := Value;
if FEnabled and not (csDesigning in ComponentState) then
if (FConsoleTitle <> '') or not (csLoading in ComponentState) then
Windows.SetConsoleTitle(PChar(FConsoleTitle));
end;
procedure TCnConsole.SetEnabled(const Value: Boolean);
begin
if FEnabled <> Value then
begin
FEnabled := Value;
if csDesigning in ComponentState then
Exit;
if FEnabled then
begin
AllocConsole;
SetConsoleTitle(PChar(FConsoleTitle));
FConsoleHandle := GetStdHandle(STD_OUTPUT_HANDLE);
end
else
begin
FreeConsole;
end;
end;
end;
procedure TCnConsole.SetTextColor(const aColor: WORD);
begin
if FEnabled then
SetConsoleTextAttribute(FConsoleHandle, aColor);
end;
end.
|
unit uProdutoDAOClient;
interface
uses DBXCommon, DBXClient, DBXJSON, DSProxy, Classes, SysUtils, DB, SqlExpr, DBXDBReaders, Produto, DBXJSONReflect,
Generics.Collections, FornecedorProduto, Validade;
type
TProdutoDAOClient = class(TDSAdminClient)
private
FListCommand: TDBXCommand;
FNextCodigoCommand: TDBXCommand;
FNextCodigoBarrasCommand: TDBXCommand;
FInsertCommand: TDBXCommand;
FUpdateCommand: TDBXCommand;
FDeleteCommand: TDBXCommand;
FFindByCodigoCommand: TDBXCommand;
FListFornecedoresByProdutoCommand: TDBXCommand;
FListValidadesByProdutoCommand: TDBXCommand;
FListagemProdutosCommand: TDBXCommand;
FExisteCodigoBarrasCommand: TDBXCommand;
FListProdutosPertoVencimentoCommand: TDBXCommand;
public
constructor Create(ADBXConnection: TDBXConnection); overload;
constructor Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean); overload;
destructor Destroy; override;
function List: TDBXReader;
function NextCodigo: string;
function NextCodigoBarras: string;
function Insert(produto: TProduto): Boolean;
function Update(produto: TProduto): Boolean;
function Delete(produto: TProduto): Boolean;
function FindByCodigo(Codigo: string): TProduto;
function ListFornecedoresByProduto(Codigo: string): TList<TFornecedorProduto>;
function ListValidadesByProduto(Codigo: string): TList<TValidade>;
function ListagemProdutos(CodigoTipoProduto: string; CodigoFornecedor: string; Estoque: Integer): TDBXReader;
function ExisteCodigoBarras(CodigoBarras: string): Boolean;
function ListProdutosPertoVencimento: TDBXReader;
end;
implementation
function TProdutoDAOClient.List: TDBXReader;
begin
if FListCommand = nil then
begin
FListCommand := FDBXConnection.CreateCommand;
FListCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FListCommand.Text := 'TProdutoDAO.List';
FListCommand.Prepare;
end;
FListCommand.ExecuteUpdate;
Result := FListCommand.Parameters[0].Value.GetDBXReader(FInstanceOwner);
end;
function TProdutoDAOClient.NextCodigo: string;
begin
if FNextCodigoCommand = nil then
begin
FNextCodigoCommand := FDBXConnection.CreateCommand;
FNextCodigoCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FNextCodigoCommand.Text := 'TProdutoDAO.NextCodigo';
FNextCodigoCommand.Prepare;
end;
FNextCodigoCommand.ExecuteUpdate;
Result := FNextCodigoCommand.Parameters[0].Value.GetWideString;
end;
function TProdutoDAOClient.NextCodigoBarras: string;
begin
if FNextCodigoBarrasCommand = nil then
begin
FNextCodigoBarrasCommand := FDBXConnection.CreateCommand;
FNextCodigoBarrasCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FNextCodigoBarrasCommand.Text := 'TProdutoDAO.NextCodigoBarras';
FNextCodigoBarrasCommand.Prepare;
end;
FNextCodigoBarrasCommand.ExecuteUpdate;
Result := FNextCodigoBarrasCommand.Parameters[0].Value.GetWideString;
end;
function TProdutoDAOClient.Insert(produto: TProduto): Boolean;
begin
if FInsertCommand = nil then
begin
FInsertCommand := FDBXConnection.CreateCommand;
FInsertCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FInsertCommand.Text := 'TProdutoDAO.Insert';
FInsertCommand.Prepare;
end;
if not Assigned(produto) then
FInsertCommand.Parameters[0].Value.SetNull
else
begin
FMarshal := TDBXClientCommand(FInsertCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler;
try
FInsertCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(produto), True);
if FInstanceOwner then
produto.Free
finally
FreeAndNil(FMarshal)
end
end;
FInsertCommand.ExecuteUpdate;
Result := FInsertCommand.Parameters[1].Value.GetBoolean;
end;
function TProdutoDAOClient.Update(produto: TProduto): Boolean;
begin
if FUpdateCommand = nil then
begin
FUpdateCommand := FDBXConnection.CreateCommand;
FUpdateCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FUpdateCommand.Text := 'TProdutoDAO.Update';
FUpdateCommand.Prepare;
end;
if not Assigned(produto) then
FUpdateCommand.Parameters[0].Value.SetNull
else
begin
FMarshal := TDBXClientCommand(FUpdateCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler;
try
FUpdateCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(produto), True);
if FInstanceOwner then
produto.Free
finally
FreeAndNil(FMarshal)
end
end;
FUpdateCommand.ExecuteUpdate;
Result := FUpdateCommand.Parameters[1].Value.GetBoolean;
end;
function TProdutoDAOClient.Delete(produto: TProduto): Boolean;
begin
if FDeleteCommand = nil then
begin
FDeleteCommand := FDBXConnection.CreateCommand;
FDeleteCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FDeleteCommand.Text := 'TProdutoDAO.Delete';
FDeleteCommand.Prepare;
end;
if not Assigned(produto) then
FDeleteCommand.Parameters[0].Value.SetNull
else
begin
FMarshal := TDBXClientCommand(FDeleteCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler;
try
FDeleteCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(produto), True);
if FInstanceOwner then
produto.Free
finally
FreeAndNil(FMarshal)
end
end;
FDeleteCommand.ExecuteUpdate;
Result := FDeleteCommand.Parameters[1].Value.GetBoolean;
end;
function TProdutoDAOClient.FindByCodigo(Codigo: string): TProduto;
begin
if FFindByCodigoCommand = nil then
begin
FFindByCodigoCommand := FDBXConnection.CreateCommand;
FFindByCodigoCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FFindByCodigoCommand.Text := 'TProdutoDAO.FindByCodigo';
FFindByCodigoCommand.Prepare;
end;
FFindByCodigoCommand.Parameters[0].Value.SetWideString(Codigo);
FFindByCodigoCommand.ExecuteUpdate;
if not FFindByCodigoCommand.Parameters[1].Value.IsNull then
begin
FUnMarshal := TDBXClientCommand(FFindByCodigoCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler;
try
Result := TProduto(FUnMarshal.UnMarshal(FFindByCodigoCommand.Parameters[1].Value.GetJSONValue(True)));
if FInstanceOwner then
FFindByCodigoCommand.FreeOnExecute(Result);
finally
FreeAndNil(FUnMarshal)
end
end
else
Result := nil;
end;
function TProdutoDAOClient.ListFornecedoresByProduto(Codigo: string): TList<TFornecedorProduto>;
begin
if FListFornecedoresByProdutoCommand = nil then
begin
FListFornecedoresByProdutoCommand := FDBXConnection.CreateCommand;
FListFornecedoresByProdutoCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FListFornecedoresByProdutoCommand.Text := 'TProdutoDAO.ListFornecedoresByProduto';
FListFornecedoresByProdutoCommand.Prepare;
end;
FListFornecedoresByProdutoCommand.Parameters[0].Value.SetWideString(Codigo);
FListFornecedoresByProdutoCommand.ExecuteUpdate;
if not FListFornecedoresByProdutoCommand.Parameters[1].Value.IsNull then
begin
FUnMarshal := TDBXClientCommand(FListFornecedoresByProdutoCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler;
try
Result := TList<FornecedorProduto.TFornecedorProduto>(FUnMarshal.UnMarshal(FListFornecedoresByProdutoCommand.Parameters[1].Value.GetJSONValue(True)));
if FInstanceOwner then
FListFornecedoresByProdutoCommand.FreeOnExecute(Result);
finally
FreeAndNil(FUnMarshal)
end
end
else
Result := nil;
end;
function TProdutoDAOClient.ListValidadesByProduto(Codigo: string): TList<TValidade>;
begin
if FListValidadesByProdutoCommand = nil then
begin
FListValidadesByProdutoCommand := FDBXConnection.CreateCommand;
FListValidadesByProdutoCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FListValidadesByProdutoCommand.Text := 'TProdutoDAO.ListValidadesByProduto';
FListValidadesByProdutoCommand.Prepare;
end;
FListValidadesByProdutoCommand.Parameters[0].Value.SetWideString(Codigo);
FListValidadesByProdutoCommand.ExecuteUpdate;
if not FListValidadesByProdutoCommand.Parameters[1].Value.IsNull then
begin
FUnMarshal := TDBXClientCommand(FListValidadesByProdutoCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler;
try
Result := TList<Validade.TValidade>(FUnMarshal.UnMarshal(FListValidadesByProdutoCommand.Parameters[1].Value.GetJSONValue(True)));
if FInstanceOwner then
FListValidadesByProdutoCommand.FreeOnExecute(Result);
finally
FreeAndNil(FUnMarshal)
end
end
else
Result := nil;
end;
function TProdutoDAOClient.ListagemProdutos(CodigoTipoProduto: string; CodigoFornecedor: string; Estoque: Integer): TDBXReader;
begin
if FListagemProdutosCommand = nil then
begin
FListagemProdutosCommand := FDBXConnection.CreateCommand;
FListagemProdutosCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FListagemProdutosCommand.Text := 'TProdutoDAO.ListagemProdutos';
FListagemProdutosCommand.Prepare;
end;
FListagemProdutosCommand.Parameters[0].Value.SetWideString(CodigoTipoProduto);
FListagemProdutosCommand.Parameters[1].Value.SetWideString(CodigoFornecedor);
FListagemProdutosCommand.Parameters[2].Value.SetInt32(Estoque);
FListagemProdutosCommand.ExecuteUpdate;
Result := FListagemProdutosCommand.Parameters[3].Value.GetDBXReader(FInstanceOwner);
end;
function TProdutoDAOClient.ExisteCodigoBarras(CodigoBarras: string): Boolean;
begin
if FExisteCodigoBarrasCommand = nil then
begin
FExisteCodigoBarrasCommand := FDBXConnection.CreateCommand;
FExisteCodigoBarrasCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FExisteCodigoBarrasCommand.Text := 'TProdutoDAO.ExisteCodigoBarras';
FExisteCodigoBarrasCommand.Prepare;
end;
FExisteCodigoBarrasCommand.Parameters[0].Value.SetWideString(CodigoBarras);
FExisteCodigoBarrasCommand.ExecuteUpdate;
Result := FExisteCodigoBarrasCommand.Parameters[1].Value.GetBoolean;
end;
function TProdutoDAOClient.ListProdutosPertoVencimento: TDBXReader;
begin
if FListProdutosPertoVencimentoCommand = nil then
begin
FListProdutosPertoVencimentoCommand := FDBXConnection.CreateCommand;
FListProdutosPertoVencimentoCommand.CommandType := TDBXCommandTypes.DSServerMethod;
FListProdutosPertoVencimentoCommand.Text := 'TProdutoDAO.ListProdutosPertoVencimento';
FListProdutosPertoVencimentoCommand.Prepare;
end;
FListProdutosPertoVencimentoCommand.ExecuteUpdate;
Result := FListProdutosPertoVencimentoCommand.Parameters[0].Value.GetDBXReader(FInstanceOwner);
end;
constructor TProdutoDAOClient.Create(ADBXConnection: TDBXConnection);
begin
inherited Create(ADBXConnection);
end;
constructor TProdutoDAOClient.Create(ADBXConnection: TDBXConnection; AInstanceOwner: Boolean);
begin
inherited Create(ADBXConnection, AInstanceOwner);
end;
destructor TProdutoDAOClient.Destroy;
begin
FreeAndNil(FListCommand);
FreeAndNil(FNextCodigoCommand);
FreeAndNil(FInsertCommand);
FreeAndNil(FUpdateCommand);
FreeAndNil(FDeleteCommand);
FreeAndNil(FFindByCodigoCommand);
FreeAndNil(FListFornecedoresByProdutoCommand);
FreeAndNil(FListagemProdutosCommand);
inherited;
end;
end.
|
unit uMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls
, uObserver
, uTickTockTimer
, uFactory;
type
TFormMain = class(TForm, IVMObserver)
pnlClock: TPanel;
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure FormCreate(Sender: TObject);
public
procedure UpdateObserver(const Sender: TObject);
end;
var
FormMain: TFormMain;
implementation
{$R *.dfm}
{ TForm1 }
procedure TFormMain.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
gClockTimer.Detach(self);
end;
procedure TFormMain.FormCreate(Sender: TObject);
begin
gClockTimer.Attach(self);
end;
procedure TFormMain.UpdateObserver(const Sender: TObject);
begin
if Sender is TClockTimer then
pnlClock.Caption := (gClockTimer as TClockTimer).Time;
end;
initialization
System.ReportMemoryLeaksOnShutdown := True;
gClockTimer := TFactoryClass.CreateClockTimer;
finalization
gClockTimer := nil;
end.
|
unit UrsJSONCommonSerializers;
interface
uses
System.Rtti,
UrsJSONUtils;
type
TJsonBooleanDefaultAttribute = class(TJsonFieldAttribute)
protected
function IsDefault(const AValue: TValue): Boolean; override;
end;
TJsonDateTimeAttribute = class(TJsonFieldAttribute)
strict protected
function SerializeToString(const AValue: TValue): string; virtual;
function DeserializeString(const AStr: string): TValue;
protected
function Serialize(const AValue: TValue; out AJson: TJSONValue): Boolean; override;
function Deserialize(AContext, AJson: TJSONValue; out AValue: TValue): Boolean; override;
end;
TJsonISODateTimeAttribute = class(TJsonDateTimeAttribute)
strict private
const
CDTDelim = 'T';
strict protected
function SerializeToString(const AValue: TValue): string; override;
protected
function Deserialize(AContext, AJson: TJSONValue; out AValue: TValue): Boolean; override;
end;
TJsonRawAttribute = class(TJsonFieldAttribute)
protected
function Serialize(const AValue: TValue; out AJson: TJSONValue): Boolean; override;
end;
TJsonStringAttribute = class(TJsonFieldAttribute)
protected
function Deserialize(AContext, AJson: TJSONValue; out AValue: TValue): Boolean; override;
end;
TJsonStringDefAttribute = class(TJsonStringAttribute)
protected
function IsDefault(const AValue: TValue): Boolean; override;
function GetDefault(out AVal: TValue): Boolean; override;
end;
TJsonGUIDAttribute = class(TJsonFieldAttribute)
strict private
const
CNULL_GUID: TGUID = (
D1: 0;
D2: 0;
D3: 0;
D4: (0, 0, 0, 0, 0, 0, 0, 0);
);
protected
function Serialize(const AValue: TValue; out AJson: TJSONValue): Boolean; override;
function Deserialize(AContext, AJson: TJSONValue; out AValue: TValue): Boolean; override;
function IsDefault(const AValue: TValue): Boolean; override;
function GetDefault(out AVal: TValue): Boolean; override;
end;
implementation
uses
{$IF CompilerVersion > 26} // XE5
System.JSON,
{$ELSE}
Data.DBXJSON, UrsJSONPortable,
{$ENDIF}
System.SysUtils;
type
TDateTimeFormatter = class abstract
strict private
const
CDateFormat = 'yyyy-mm-dd';
CTimeFormat = 'hh:nn:ss';
class var
FFormatSettings: TFormatSettings;
private
const
CDTSepPos = Length(CDateFormat);
strict private
class constructor Create;
public
class property FormatSettings: TFormatSettings read FFormatSettings;
end;
{ TDateTimeFormatter }
class constructor TDateTimeFormatter.Create;
begin
FFormatSettings := TFormatSettings.Create;
FFormatSettings.DateSeparator := '-';
FFormatSettings.TimeSeparator := ':';
FFormatSettings.DecimalSeparator := '.';
FFormatSettings.ShortDateFormat := CDateFormat;
FFormatSettings.LongDateFormat := CDateFormat + ' ' + CTimeFormat;
FFormatSettings.ShortTimeFormat := CTimeFormat;
FFormatSettings.LongTimeFormat := CTimeFormat;
end;
{ TJsonBooleanDefaultAttribute }
function TJsonBooleanDefaultAttribute.IsDefault(const AValue: TValue): Boolean;
begin
Result := not AValue.AsBoolean;
end;
{ TJsonDateTimeAttribute }
function TJsonDateTimeAttribute.SerializeToString(const AValue: TValue): string;
begin
Result := DateTimeToStr(AValue.AsType<TDateTime>, TDateTimeFormatter.FormatSettings);
end;
function TJsonDateTimeAttribute.DeserializeString(
const AStr: string): TValue;
begin
Result := TValue.From<TDateTime>(
StrToDateTime(AStr, TDateTimeFormatter.FormatSettings));
end;
function TJsonDateTimeAttribute.Serialize(const AValue: TValue;
out AJson: TJSONValue): Boolean;
begin
AJson := TJSONString.Create(SerializeToString(AValue));
Result := True;
end;
function TJsonDateTimeAttribute.Deserialize(AContext, AJson: TJSONValue;
out AValue: TValue): Boolean;
begin
AValue := DeserializeString(AJson.Value);
Result := True;
end;
{ TJsonISODateTimeAttribute }
function TJsonISODateTimeAttribute.SerializeToString(
const AValue: TValue): string;
begin
Result := inherited SerializeToString(AValue);
Result[TDateTimeFormatter.CDTSepPos] := CDTDelim;
end;
function TJsonISODateTimeAttribute.Deserialize(AContext, AJson: TJSONValue;
out AValue: TValue): Boolean;
var
LStr: string;
LTPos: Integer;
LEndPos: Integer;
Li: Integer;
begin
LStr := AJson.Value;
LTPos := -1;
LEndPos := -1;
for Li := 1 to Length(LStr) do begin
case LStr[Li] of
CDTDelim: LTPos := Li;
' ', '+', '-': begin
if LTPos <> -1 then begin
LEndPos := Li - 1;
Break;
end;
end;
end;
end;
if LEndPos <> -1 then
SetLength(LStr, LEndPos);
if LTPos <> -1 then
LStr[LTPos] := ' ';
AValue := DeserializeString(LStr);
Result := True;
end;
{ TJsonRawAttribute }
function TJsonRawAttribute.Serialize(const AValue: TValue;
out AJson: TJSONValue): Boolean;
begin
AJson := TJSONRaw.Create(AValue.AsType<TArray<Byte>>);
Result := True;
end;
{ TJsonStringAttribute }
function TJsonStringAttribute.Deserialize(AContext, AJson: TJSONValue;
out AValue: TValue): Boolean;
begin
AValue := AJson.ToString;
Result := True;
end;
{ TJsonStringDefAttribute }
function TJsonStringDefAttribute.IsDefault(const AValue: TValue): Boolean;
begin
Result := AValue.AsString = '';
end;
function TJsonStringDefAttribute.GetDefault(out AVal: TValue): Boolean;
begin
AVal := TValue.From<string>('');
Result := True;
end;
{ TJsonGUIDAttribute }
function TJsonGUIDAttribute.Serialize(const AValue: TValue;
out AJson: TJSONValue): Boolean;
begin
AJson := TJSONString.Create(GUIDToString(AValue.AsType<TGUID>));
Result := True;
end;
function TJsonGUIDAttribute.Deserialize(AContext, AJson: TJSONValue;
out AValue: TValue): Boolean;
begin
AValue := TValue.From<TGUID>(StringToGUID(AJson.Value));
Result := True;
end;
function TJsonGUIDAttribute.IsDefault(const AValue: TValue): Boolean;
begin
Result := IsEqualGUID(AValue.AsType<TGUID>, CNULL_GUID);
end;
function TJsonGUIDAttribute.GetDefault(out AVal: TValue): Boolean;
begin
AVal := TValue.From<TGUID>(CNULL_GUID);
Result := True;
end;
end.
|
unit MainLoader;
interface
uses
Windows, Messages, Ini,ShellAPI,SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,ErrorLogsUnit;
type
TLoaderForm = class(TForm)
procedure FormShow(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
function RunDOS(const CommandLine: string): string; //执行CMD后返回结果
var
LoaderForm: TLoaderForm;
implementation
{$R *.dfm}
function RunDOS(const CommandLine: string): string;
procedure CheckResult(b: Boolean);
begin
if not b then
raise Exception.Create(SysErrorMessage(GetLastError));
end;
var
HRead, HWrite: THandle;
StartInfo: TStartupInfo;
ProceInfo: TProcessInformation;
b: Boolean;
sa: TSecurityAttributes;
inS: THandleStream;
sRet: TStrings;
begin
Result := '';
FillChar(sa, sizeof(sa), 0);
// 设置允许继承,否则在NT和2000下无法取得输出结果
sa.nLength := sizeof(sa);
sa.bInheritHandle := True;
sa.lpSecurityDescriptor := nil;
b := CreatePipe(HRead, HWrite, @sa, 0);
CheckResult(b);
FillChar(StartInfo, sizeof(StartInfo), 0);
StartInfo.cb := sizeof(StartInfo);
StartInfo.wShowWindow := SW_HIDE;
// 使用指定的句柄作为标准输入输出的文件句柄,使用指定的显示方式
StartInfo.dwFlags := STARTF_USESTDHANDLES or STARTF_USESHOWWINDOW;
StartInfo.hStdError := HWrite;
StartInfo.hStdInput := GetStdHandle(STD_INPUT_HANDLE); // HRead;
StartInfo.hStdOutput := HWrite;
b := CreateProcess(nil, // lpApplicationName: PChar
PChar(CommandLine), // lpCommandLine: PChar
nil, // lpProcessAttributes: PSecurityAttributes
nil, // lpThreadAttributes: PSecurityAttributes
True, // bInheritHandles: BOOL
CREATE_NEW_CONSOLE, nil, nil, StartInfo, ProceInfo);
CheckResult(b);
WaitForSingleObject(ProceInfo.hProcess, INFINITE);
inS := THandleStream.Create(HRead);
if inS.Size > 0 then
begin
sRet := TStringList.Create;
sRet.LoadFromStream(inS);
Result := sRet.Text;
sRet.Free;
end;
inS.Free;
CloseHandle(HRead);
CloseHandle(HWrite);
end;
procedure TLoaderForm.FormShow(Sender: TObject);
var
FileName :string;
ProcID: Cardinal;
begin
FileName := Ini.ReadIni('server','file');
ShellExecute(Application.Handle, nil, pchar(FileName), nil,nil, SW_SHOW);
// Application.Terminate;
// addErrors(RunDOS(FileName));
// addErrors(GetEnvironmentVariable('JAVA_HOME'));
// ShowMessage(GetEnvironmentVariable('JAVA_HOME'));
end;
end.
|
{$i deltics.inc}
unit Test.Path;
interface
uses
Deltics.Smoketest;
type
PathTests = class(TTest)
procedure AbsoluteReturnsAbsolutePathUnmodified;
procedure AbsoluteReturnsRelativePathAsAbsolute;
procedure AbsoluteToRelative;
procedure AbsoluteToRelativeRaisesEPathExceptionIfPathIsNotAbsolute;
procedure Append;
procedure Branch;
procedure BranchReturnsEmptyStringWhenThereIsNoParent;
procedure IsAbsolute;
procedure IsNavigation;
procedure IsRelative;
procedure Leaf;
procedure MakePath;
procedure RelativeToAbsolute;
procedure Volume;
end;
implementation
uses
Deltics.IO.Path;
{ PathTests }
procedure PathTests.AbsoluteReturnsAbsolutePathUnmodified;
var
s: String;
begin
s := Path.Absolute('c:\thisIsAbsolute', 'c:\root');
Test('Absolute(<absolute>)').Assert(s).Equals('c:\thisIsAbsolute');
end;
procedure PathTests.AbsoluteReturnsRelativePathAsAbsolute;
var
s1, s2, s3: String;
begin
s1 := Path.Absolute('\thisIsRelative', 'c:\root\sub');
s2 := Path.Absolute('.\thisIsRelative', 'c:\root\sub');
s3 := Path.Absolute('..\thisIsRelative', 'c:\root\sub');
Test('Absolute(<\relative>, c:\root\sub)').Assert(s1).Equals('c:\thisIsRelative');
Test('Absolute(<.\relative>, c:\root\sub)').Assert(s2).Equals('c:\root\sub\thisIsRelative');
Test('Absolute(<.\relative>, c:\root)').Assert(s3).Equals('c:\root\thisIsRelative');
end;
procedure PathTests.AbsoluteToRelative;
var
s1, s2, s3: String;
begin
s1 := Path.AbsoluteToRelative('c:\thisIsRelative', 'c:\root\sub');
s2 := Path.AbsoluteToRelative('c:\root\sub\thisIsRelative', 'c:\root\sub');
s3 := Path.AbsoluteToRelative('c:\root\thisIsRelative', 'c:\root\sub');
Test('AbsoluteToRelative(<c:\relative>, c:\root\sub)').Assert(s1).Equals('..\..\thisIsRelative');
Test('AbsoluteToRelative(<c:\root\sub\relative>, c:\root\sub)').Assert(s2).Equals('.\thisIsRelative');
Test('AbsoluteToRelative(<c:\root\relative>, c:\root\sub)').Assert(s3).Equals('..\thisIsRelative');
end;
procedure PathTests.AbsoluteToRelativeRaisesEPathExceptionIfPathIsNotAbsolute;
begin
Test.Raises(EPathException);
Path.AbsoluteToRelative('\thisIsRelative', 'c:\root\sub');
end;
procedure PathTests.Append;
var
s: String;
begin
s := Path.Append('', '');
Test('Append(<empty>, <empty>)').Assert(s).Equals('');
s := Path.Append('', 'sub');
Test('Append(<empty>, sub)').Assert(s).Equals('sub');
s := Path.Append('base', '');
Test('Append(base, <empty>)').Assert(s).Equals('base');
s := Path.Append('root', 'sub');
Test('Append(root, sub)').Assert(s).Equals('root\sub');
s := Path.Append('root\', 'sub');
Test('Append(root\, sub)').Assert(s).Equals('root\sub');
s := Path.Append('root\', '\sub');
Test('Append(root\, \sub)').Assert(s).Equals('root\sub');
s := Path.Append('root', '\sub');
Test('Append(root, \sub)').Assert(s).Equals('root\sub');
end;
procedure PathTests.Branch;
var
s: String;
begin
s := Path.Branch('');
Test('Branch(<empty>)').Assert(s).Equals('');
s := Path.Branch('\');
Test('Branch(\)').Assert(s).IsEmpty;
s := Path.Branch('c:\windows');
Test('Branch(c:\windows)').Assert(s).Equals('c:\');
s := Path.Branch('c:\windows\');
Test('Branch(c:\windows\)').Assert(s).Equals('c:\');
s := Path.Branch('c:\');
Test('Branch(c:\)').Assert(s).IsEmpty;
s := Path.Branch('c:');
Test('Branch(c:)').Assert(s).IsEmpty;
s := Path.Branch('\\');
Test('Branch(\\)').Assert(s).IsEmpty;
s := Path.Branch('\\host');
Test('Branch(\\host)').Assert(s).IsEmpty;
s := Path.Branch('\\host\share');
Test('Branch(\\host\share)').Assert(s).Equals('\\host');
s := Path.Branch('foo\bar');
Test('Branch(foo\bar)').Assert(s).Equals('foo');
s := Path.Branch('foo\bar\none');
Test('Branch(foo\bar\none)').Assert(s).Equals('foo\bar');
end;
procedure PathTests.BranchReturnsEmptyStringWhenThereIsNoParent;
var
s: String;
begin
s := Path.Branch('c:\');
Test('Branch(c:\)').Assert(s).IsEmpty;
end;
procedure PathTests.IsAbsolute;
var
result: Boolean;
begin
result := Path.IsAbsolute('c:\folder');
Test('IsAbsolute(c:\folder)').Assert(result).IsTrue;
result := Path.IsAbsolute('\\host\share\folder');
Test('IsAbsolute(\\host\share\folder)').Assert(result).IsTrue;
result := Path.IsAbsolute('\folder');
Test('IsAbsolute(\folder)').Assert(result).IsFalse;
end;
procedure PathTests.IsNavigation;
var
result: Boolean;
begin
result := Path.IsNavigation('.');
Test('IsNavigation(.)').Assert(result).IsTrue;
result := Path.IsNavigation('..');
Test('IsNavigation(..)').Assert(result).IsTrue;
result := Path.IsNavigation('');
Test('IsNavigation()').Assert(result).IsFalse;
result := Path.IsNavigation('.\relative');
Test('IsNavigation(.\relative)').Assert(result).IsFalse;
result := Path.IsNavigation('..\relative');
Test('IsNavigation(..\relative)').Assert(result).IsFalse;
end;
procedure PathTests.IsRelative;
var
result: Boolean;
begin
result := Path.IsRelative('c:\folder');
Test('IsRelative(c:\folder)').Assert(result).IsFalse;
result := Path.IsRelative('\\host\share\folder');
Test('IsRelative(\\host\share\folder)').Assert(result).IsFalse;
result := Path.IsRelative('\folder');
Test('IsRelative(\folder)').Assert(result).IsTrue;
result := Path.IsRelative('.\folder');
Test('IsRelative(.\folder)').Assert(result).IsTrue;
result := Path.IsRelative('..\folder');
Test('IsRelative(..\folder)').Assert(result).IsTrue;
end;
procedure PathTests.Leaf;
var
s: String;
begin
s := Path.Leaf('');
Test('Leaf(<empty>)').Assert(s).IsEmpty;
s := Path.Leaf('\');
Test('Leaf(\)').Assert(s).IsEmpty;
s := Path.Leaf('\\');
Test('Leaf(\\)').Assert(s).IsEmpty;
s := Path.Leaf('foo\bar');
Test('Leaf(foo\bar)').Assert(s).Equals('bar');
s := Path.Leaf('foo\bar\none');
Test('Leaf(foo\bar\none)').Assert(s).Equals('none');
end;
procedure PathTests.MakePath;
var
s: String;
begin
s := Path.MakePath(['foo', 123, 'bar']);
Test('MakePath([foo, 123, bar]>)').Assert(s).Equals('foo\123\bar');
end;
procedure PathTests.RelativeToAbsolute;
var
s1, s2, s3: String;
begin
s1 := Path.RelativeToAbsolute('.\thisIsRelative', 'c:\root\sub');
s2 := Path.RelativeToAbsolute('..\thisIsRelative', 'c:\root\sub');
s3 := Path.RelativeToAbsolute('\thisIsRelative', 'c:\root\sub');
Test('RelativeToAbsolute(<.\relative>, c:\root\sub)').Assert(s1).Equals('c:\root\sub\thisIsRelative');
Test('RelativeToAbsolute(<..\root\sub\relative>, c:\root\sub)').Assert(s2).Equals('c:\root\thisIsRelative');
Test('RelativeToAbsolute(<\root\relative>, c:\root\sub)').Assert(s3).Equals('c:\thisIsRelative');
end;
procedure PathTests.Volume;
var
s: String;
begin
s := Path.Volume('c:\path');
Test('Volume(c:\path)').Assert(s).Equals('c:');
s := Path.Volume('\\host\share\path');
Test('Volume(\\host\share\path)').Assert(s).Equals('\\host\share');
end;
end.
|
unit uFrmMarginTable;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, PAIDETODOS, siComp, siLangRT, StdCtrls, LblEffct, ExtCtrls,
cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, DB,
cxDBData, Buttons, ADODB, PowerADOQuery, cxGridLevel, cxClasses,
cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGrid, ComCtrls, dxExEdtr, dxTL, dxCntner, DBClient;
type
TFrmMarginTable = class(TFrmParent)
dsBrowse: TDataSource;
quMargemTable: TADODataSet;
quMargemTableMargemTable: TStringField;
pnPanel: TPanel;
btGroup: TSpeedButton;
TreeList: TdxTreeList;
clTreeText: TdxTreeListColumn;
clTreeValue: TdxTreeListColumn;
quBrowse: TADODataSet;
quBrowseIDGroup: TIntegerField;
quBrowseCategory: TStringField;
quBrowseIDSalePriceMargemTable: TIntegerField;
quBrowseSalePriceMargemPercent: TFloatField;
quBrowseUseSalePricePercent: TBooleanField;
quBrowseIDMSRPMargemTable: TIntegerField;
quBrowseMSRPMargemPercent: TFloatField;
quBrowseUseMSRPPercent: TBooleanField;
quBrowseIDModelGroup: TIntegerField;
quBrowseModelGroup: TStringField;
quBrowseMGSalePriceMargemPercent: TFloatField;
quBrowseMGUseSalePricePercent: TBooleanField;
quBrowseMGIDSalePriceMargemTable: TIntegerField;
quBrowseMGIDMSRPMargemTable: TIntegerField;
quBrowseMGMSRPMargemPercent: TFloatField;
quBrowseMGUseMSRPPercent: TBooleanField;
quBrowseIDModelSubGroup: TIntegerField;
quBrowseModelSubGroup: TStringField;
quBrowseMSGSalePriceMargemPercent: TFloatField;
quBrowseMSGUseSalePricePercent: TBooleanField;
quBrowseMSGIDSalePriceMargemTable: TIntegerField;
quBrowseMSGIDMSRPMargemTable: TIntegerField;
quBrowseMSGMSRPMargemPercent: TFloatField;
quBrowseMSGUseMSRPPercent: TBooleanField;
clTreeMSRP: TdxTreeListColumn;
TreeListID: TdxTreeListColumn;
TreeListType: TdxTreeListColumn;
btRecalcAllGroup: TSpeedButton;
cdsMarginRecalcAll: TClientDataSet;
cdsMarginRecalcAllIsUpdate: TBooleanField;
cdsMarginRecalcAllModel: TStringField;
cdsMarginRecalcAllDescription: TStringField;
cdsMarginRecalcAllIDModel: TIntegerField;
cdsMarginRecalcAllCostPrice: TBCDField;
cdsMarginRecalcAllNewSellingPrice: TBCDField;
cdsMarginRecalcAllNewMSRPPrice: TBCDField;
cdsMarginRecalcAllSalePrice: TBCDField;
cdsMarginRecalcAllMSRP: TBCDField;
cdsMarginRecalcAllRealMarkUpValue: TBCDField;
cdsMarginRecalcAllRealMarkUpPercent: TBCDField;
cdsMarginRecalcAllMarginPercent: TBCDField;
cdsMarginRecalcAllMarginValue: TBCDField;
cdsMarginRecalcAllCategory: TStringField;
cdsMarginRecalcAllSubCategory: TStringField;
cdsMarginRecalcAllModelGroup: TStringField;
cdsMarginRecalcAllMarkUp: TBCDField;
cmdUpdateModel: TADOCommand;
procedure btCloseClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btGroupClick(Sender: TObject);
procedure quBrowseAfterOpen(DataSet: TDataSet);
procedure btRecalcAllGroupClick(Sender: TObject);
private
AView : TcxCustomGridTableView;
procedure CallShortCut(IDMenu, IDSubMenu : Integer);
procedure GetGroupValue(var SaleCatValue, SaleGroValue, SaleSubValue,
MSRPCatValue, MSRPGroValue, MSRPSubValue : String);
function GetMargemTableName(ID: Integer): String;
procedure DisplayMarginTable;
procedure AddListItems(IDC, IDG, IDS : Integer; Category, CValue, Group, GValue, Sub, SValue,
MSRPCValue, MSRPGValue, MSRPSValue : String);
procedure OpenBrowser;
procedure CloseBrowser;
procedure RefreshBrowser;
procedure UpdateNewPrices;
procedure RecalcAllInventory;
public
procedure Start;
end;
implementation
uses uStringFunctions, uDM, uFrmMarginTableApply, MenuPrincipal,
uDMCalcPrice, uContentClasses, uObjectServices, uHandleError,
uMsgBox, uMsgConstant;
{$R *.dfm}
procedure TFrmMarginTable.Start;
begin
OpenBrowser;
DM.imgSubMenu.GetBitmap(29, btGroup.Glyph);
ShowModal;
end;
procedure TFrmMarginTable.btCloseClick(Sender: TObject);
begin
inherited;
Close;
end;
function TFrmMarginTable.GetMargemTableName(ID: Integer): String;
var Friend : String;
begin
with quMargemTable do
begin
if Active then
Close;
Parameters.ParamByName('IDMargemTable').Value := ID;
Open;
Result := quMargemTableMargemTable.AsString;
Close;
end;
end;
procedure TFrmMarginTable.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
CloseBrowser;
end;
procedure TFrmMarginTable.DisplayMarginTable;
var
CValue,
GValue,
SValue,
MSRPCValue,
MSRPGValue,
MSRPSValue : String;
begin
TreeList.ClearNodes;
with quBrowse do
begin
DisableControls;
First;
while not EOF do
begin
if quBrowseCategory.AsString <> '' then
begin
GetGroupValue(CValue, GValue, SValue, MSRPCValue, MSRPGValue, MSRPSValue);
AddListItems(quBrowseIDGroup.AsInteger,
quBrowseIDModelGroup.AsInteger,
quBrowseIDModelSubGroup.AsInteger,
quBrowseCategory.AsString,
CValue,
quBrowseModelGroup.AsString,
GValue,
quBrowseModelSubGroup.AsString,
SValue,
MSRPCValue,
MSRPGValue,
MSRPSValue);
end;
Next;
end;
EnableControls;
end;
TreeList.FullExpand;
end;
procedure TFrmMarginTable.AddListItems(IDC, IDG, IDS : Integer; Category, CValue,
Group, GValue, Sub, SValue, MSRPCValue, MSRPGValue, MSRPSValue : String);
var
fParent,
fGroup,
fSub : TdxTreeListNode;
i : integer;
begin
fParent := nil;
fGroup := nil;
fSub := nil;
if CValue = '' then
CValue := '0%';
if (GValue = '0%') or (GValue = '') then
GValue := CValue;
if (SValue = '0%') or (SValue = '') then
SValue := GValue;
if MSRPCValue = '' then
MSRPCValue := '0%';
if (MSRPGValue = '0%') or (MSRPGValue = '') then
MSRPGValue := MSRPCValue;
if (MSRPSValue = '0%') or (MSRPSValue = '') then
MSRPSValue := MSRPGValue;
//Parent
for i := 0 to TreeList.Count-1 do
begin
fParent := TreeList.Items[i];
if Category = fParent.Strings[0] then
Break;
fParent := nil;
end;
if (Category <> '') and (fParent = nil) then
begin
fParent := TreeList.Add;
fParent.Strings[0] := Category;
fParent.Strings[1] := CValue;
fParent.Strings[2] := MSRPCValue;
fParent.Strings[3] := IntToStr(IDC);
fParent.Strings[4] := IntToStr(1);
end;
//Group
for i := 0 to fParent.Count-1 do
begin
fGroup := fParent.Items[i];
if Group = fParent.Items[i].Strings[0] then
Break;
fGroup := nil;
end;
if (Group <> '') and (fGroup = nil) then
begin
fGroup := fParent.AddChild;
fGroup.Strings[0] := Group;
fGroup.Strings[1] := GValue;
fGroup.Strings[2] := MSRPGValue;
fGroup.Strings[3] := IntToStr(IDG);
fGroup.Strings[4] := IntToStr(2);
end;
//Sub
if fGroup = nil then
Exit;
for i := 0 to fGroup.Count-1 do
begin
fSub := fGroup.Items[i];
if Sub = fGroup.Items[i].Strings[0] then
Break;
fSub := nil;
end;
if (Sub <> '') and (fSub = nil) then
begin
fSub := fGroup.AddChild;
fSub.Strings[0] := Sub;
fSub.Strings[1] := SValue;
fSub.Strings[2] := MSRPSValue;
fSub.Strings[3] := IntToStr(IDS);
fSub.Strings[4] := IntToStr(3);
end;
end;
procedure TFrmMarginTable.CloseBrowser;
begin
with quBrowse do
if Active then
Close;
end;
procedure TFrmMarginTable.OpenBrowser;
begin
with quBrowse do
if not Active then
Open;
end;
procedure TFrmMarginTable.RefreshBrowser;
begin
CloseBrowser;
OpenBrowser;
end;
procedure TFrmMarginTable.CallShortCut(IDMenu, IDSubMenu: Integer);
var
fImgOld : Integer;
fsMenu,
fsSubMenu : String;
begin
try
fImgOld := DM.fMainMenu.Image;
fsMenu := DM.fMainMenu.MenuName;
fsSubMenu := DM.fMainMenu.SubMenuName;
MainMenu.IDMenu := IDMenu;
MainMenu.IDSubMenu := IDSubMenu;
MainMenu.SubMenuClick(nil);
RefreshBrowser;
finally
MainMenu.IDMenu := 8;
MainMenu.IDSubMenu := 8;
DM.fMainMenu.Image := fImgOld;
DM.fMainMenu.MenuName := fsMenu;
DM.fMainMenu.SubMenuName:= fsSubMenu;
end;
end;
procedure TFrmMarginTable.btGroupClick(Sender: TObject);
var
iID : Integer;
fType : TModelGroupingType;
begin
inherited;
//iNodeIndex := TreeList.FocusedNode.AbsoluteIndex;
iID := StrToIntDef(TreeList.FocusedNode.Strings[3], -1);
Case StrToIntDef(TreeList.FocusedNode.Strings[4], -1) of
CATEGORY : fType := mgtCategory;
SUBCATEG : fType := mgtGroup;
GROUP : fType := mgtSubGroup;
0, -1: Exit;
end;
with TFrmMarginTableApply.Create(Self) do
if Start(iID, fType) then
RefreshBrowser;
end;
procedure TFrmMarginTable.GetGroupValue(var SaleCatValue, SaleGroValue, SaleSubValue,
MSRPCatValue, MSRPGroValue, MSRPSubValue : String);
begin
//Sale
if quBrowseUseSalePricePercent.Value then
SaleCatValue := quBrowseSalePriceMargemPercent.AsString + '%'
else
SaleCatValue := GetMargemTableName(quBrowseIDSalePriceMargemTable.AsInteger);
if quBrowseMGUseSalePricePercent.Value then
SaleGroValue := quBrowseMGSalePriceMargemPercent.AsString + '%'
else
SaleGroValue := GetMargemTableName(quBrowseMGIDSalePriceMargemTable.AsInteger);
if quBrowseMSGUseSalePricePercent.Value then
SaleSubValue := quBrowseMSGSalePriceMargemPercent.AsString + '%'
else
SaleSubValue := GetMargemTableName(quBrowseMSGIDSalePriceMargemTable.AsInteger);
//MSRP
if quBrowseUseMSRPPercent.Value then
MSRPCatValue := quBrowseMSRPMargemPercent.AsString + '%'
else
MSRPCatValue := GetMargemTableName(quBrowseIDMSRPMargemTable.AsInteger);
if quBrowseMGUseMSRPPercent.Value then
MSRPGroValue := quBrowseMGMSRPMargemPercent.AsString + '%'
else
MSRPGroValue := GetMargemTableName(quBrowseMGIDMSRPMargemTable.AsInteger);
if quBrowseMSGUseMSRPPercent.Value then
MSRPSubValue := quBrowseMSGMSRPMargemPercent.AsString + '%'
else
MSRPSubValue := GetMargemTableName(quBrowseMSGIDMSRPMargemTable.AsInteger);
end;
procedure TFrmMarginTable.quBrowseAfterOpen(DataSet: TDataSet);
begin
inherited;
DisplayMarginTable;
end;
procedure TFrmMarginTable.RecalcAllInventory;
var
ID: Integer;
begin
with quBrowse do
try
Screen.Cursor := crHourGlass;
DisableControls;
Application.ProcessMessages;
ID := -1;
First;
while not Eof do
begin
if (quBrowseIDModelSubGroup.AsInteger <> 0) and (ID <> quBrowseIDModelSubGroup.AsInteger) then
begin
ID := quBrowseIDModelSubGroup.AsInteger;
try
cdsMarginRecalcAll.CreateDataSet;
cdsMarginRecalcAll.Data := DM.FDMCalcPrice.GetNewSaleMSRPPrices(quBrowseIDModelSubGroup.AsInteger,cptBoth,mgtSubGroup);
UpdateNewPrices;
cdsMarginRecalcAll.Close;
except
on E: Exception do
begin
DM.SetError(CRITICAL_ERROR, Self.Name, 'FrmMarginTable.RecalcAllGroup.Exception' + #13#10 + E.Message);
MsgBox(E.Message, vbCritical + vbOkOnly);
end;
end;
end;
Next;
end;
ID := -1;
First;
while not Eof do
begin
if (quBrowseIDModelGroup.AsInteger <> 0) and (ID <> quBrowseIDModelGroup.AsInteger) then
begin
ID := quBrowseIDModelGroup.AsInteger;
try
cdsMarginRecalcAll.CreateDataSet;
cdsMarginRecalcAll.Data := DM.FDMCalcPrice.GetNewSaleMSRPPrices(quBrowseIDModelGroup.AsInteger,cptBoth,mgtGroup);
UpdateNewPrices;
cdsMarginRecalcAll.Close;
except
on E: Exception do
begin
DM.SetError(CRITICAL_ERROR, Self.Name, 'FrmMarginTable.RecalcAllGroup.Exception' + #13#10 + E.Message);
MsgBox(E.Message, vbCritical + vbOkOnly);
end;
end;
end;
Next;
end;
ID := -1;
First;
while not Eof do
begin
if (ID <> quBrowseIDGroup.AsInteger) then
begin
ID := quBrowseIDGroup.AsInteger;
try
cdsMarginRecalcAll.CreateDataSet;
cdsMarginRecalcAll.Data := DM.FDMCalcPrice.GetNewSaleMSRPPrices(quBrowseIDGroup.AsInteger,cptBoth,mgtCategory);
UpdateNewPrices;
cdsMarginRecalcAll.Close;
except
on E: Exception do
begin
DM.SetError(CRITICAL_ERROR, Self.Name, 'FrmMarginTable.RecalcAllGroup.Exception' + #13#10 + E.Message);
MsgBox(E.Message, vbCritical + vbOkOnly);
end;
end;
end;
Next;
end;
finally
Screen.Cursor := crDefault;
MsgBox(MSG_INF_ADJUSTMENT, vbOkOnly);
EnableControls;
end;
end;
procedure TFrmMarginTable.btRecalcAllGroupClick(Sender: TObject);
begin
if MsgBox(MSG_QST_CONFIRM, vbYesNo + vbSuperCritical) = vbYes then
RecalcAllInventory;
end;
procedure TFrmMarginTable.UpdateNewPrices;
var
ModelService: TMRModelService;
Model: TModel;
begin
try
ModelService := TMRModelService.Create();
Model := TModel.Create();
ModelService.SQLConnection := DM.ADODBConnect;
with cdsMarginRecalcAll do
if not IsEmpty then
try
Filter := 'IsUpdate = 1';
Filtered := True;
First;
while not Eof do
begin
//Model
Model.IDModel := FieldByName('IDModel').AsInteger;
Model.Model := FieldByName('Model').AsString;
Model.SellingPrice := FieldByName('NewSellingPrice').AsCurrency;
Model.SuggRetail := FieldByName('NewMSRPPrice').AsCurrency;
Model.VendorCost := FieldByName('CostPrice').AsCurrency;
Model.Markup := FieldByName('MarkUp').AsFloat;
Model.IDUserLastSellingPrice := DM.fUser.ID;
Model.DateLastCost := Now;
Model.DateLastSellingPrice := Now;
//Update
ModelService.UpdatePrices(Model);
Next;
end;
finally
Filter := '';
Filtered := False;
end;
finally
FreeAndNil(Model);
FreeAndNil(ModelService);
Close;
end;
end;
end.
|
unit GameLogic;
interface
type
TDirection = (drLeftUp, drRightUp, drLeftDown, drRightDown);
TDirectionTable = array [TDirection, 0..31] of Integer;
PPosition = ^TPosition;
TPosition = record
Field: array[0..31] of ShortInt;
MoveStr: array[0..11] of ShortInt;
Active: Integer;
TakeChar: Char;
MoveCount: Integer;
end;
const
DecodeField: array [0..31] of Integer =
(0, 2, 4, 6, 9, 11, 13, 15, 16, 18, 20, 22, 25, 27, 29, 31,
32, 34, 36, 38, 41, 43, 45, 47, 48, 50, 52, 54, 57, 59, 61, 63);
brWhiteSingle = 20;
brWhiteMam = 70;
brBlackSingle = -20;
brBlackMam = -70;
brEmpty = 0;
ActiveWhite = 1;
ActiveBlack = 0;
PointsDef: array[0..31] of string =
(
'a1', 'c1', 'e1', 'g1', 'b2', 'd2', 'f2', 'h2',
'a3', 'c3', 'e3', 'g3', 'b4', 'd4', 'f4', 'h4',
'a5', 'c5', 'e5', 'g5', 'b6', 'd6', 'f6', 'h6',
'a7', 'c7', 'e7', 'g7', 'b8', 'd8', 'f8', 'h8'
);
var
DirectionTable: TDirectionTable;
StartBoard: TPosition;
Buffer: array[0..1023] of TPosition;
function GetMoves(Position: TPosition; Buf: PPosition; BufSize: Integer): Integer;
function GameOver(const Position: TPosition): string;
function GetMovesWhite(N: Integer; var Board: TPosition): Integer;
function GetMovesBlack(N: Integer; var Board: TPosition): Integer;
function GetLastMove(Position: TPosition): string;
implementation
var
Dead: array[0..31] of ShortInt;
DeadCount: Integer;
MoveWriter: Integer;
const
brWhiteDead = -10;
brBlackDead = 10;
WhiteMamLine = 28;
BlackMamLine = 3;
WasTake = ':';
WasNotTake = '-';
OrtDirection1: array [TDirection] of TDirection = (drRightUp, drLeftUp, drLeftUp, drRightUp);
OrtDirection2: array [TDirection] of TDirection = (drLeftDown, drRightDown, drRightDown, drLeftDown);
(**************************
** GetMovesWhite - получить список всех ходов за белых
** GetMovesBlack - получить список всех ходов за черных
** GetLastMove - получить последний ход в строковом представлении
**
** Поле задается:
** первые 32 элемента массива --- шашки (brWhiteSingle; brWhiteMam; brBlackSingle; brBlackMam; или нуль
** 32 элемент - счетчик ходов только дамками
** 33 элемент - кто ходит
**
** (С) Mystic, 2002.
** Этот алгоритм реализован в программе http://www.listsoft.ru/program.php?id=13904&allowunchecked=yes
** Разрешается использовать в некоммерческих целях со ссылкой на автора.
**************************)
type
TSingleMoveRec = record
PointFrom: Integer;
PointTo: Integer;
Counter: ShortInt;
WhatPut: ShortInt;
end;
// Beta tested 19.05.2002
function GetLastMove(Position: TPosition): string;
var
I: Integer;
begin
Result := PointsDef[Position.MoveStr[0]];
I := 1;
while Position.MoveStr[I] <> -1 do
begin
Result := Result + Position.TakeChar + PointsDef[Position.MoveStr[I]];
I := I + 1;
end;
end;
// Beta tested 19.05.2002
function RecurseMamTakeWhite(var N: Integer; Cell : Integer; Direction: TDirection; var Board: TPosition): Integer;
var
OrtDirection: TDirection;
NN: Integer;
I, J, NextI, NextNextI: Integer;
SaveDead: ShortInt;
begin
Result := 0;
I := Cell;
repeat
OrtDirection := OrtDirection1[Direction];
NextI := I;
repeat
NextI := DirectionTable[OrtDirection, NextI];
if NextI = -1 then Break;
if Board.Field[NextI] <> 0 then Break;
until False;
if (NextI <> -1) and (Board.Field[NextI] < 0) then
begin
NextNextI := DirectionTable[OrtDirection, NextI];
if (NextNextI <> -1) and (Board.Field[NextNextI] = 0) then
begin
Dead[DeadCount] := NextI;
SaveDead := Board.Field[NextI];
Board.Field[NextI] := brBlackDead;
DeadCount := DeadCount + 1;
Board.MoveStr[MoveWriter] := I;
MoveWriter := MoveWriter + 1;
Result := Result + RecurseMamTakeWhite(N, NextNextI, OrtDirection, Board);
Board.Field[NextI] := SaveDead;
MoveWriter := MoveWriter - 1;
DeadCount := DeadCount - 1;
end;
end;
OrtDirection := OrtDirection2[Direction];
NextI := I;
repeat
NextI := DirectionTable[OrtDirection, NextI];
if NextI = -1 then Break;
if Board.Field[NextI] <> 0 then Break;
until False;
if (NextI <> -1) and (Board.Field[NextI] < 0) then
begin
NextNextI := DirectionTable[OrtDirection, NextI];
if (NextNextI <> -1) and (Board.Field[NextNextI] = 0) then
begin
Dead[DeadCount] := NextI;
SaveDead := Board.Field[NextI];
Board.Field[NextI] := brBlackDead;
DeadCount := DeadCount + 1;
Board.MoveStr[MoveWriter] := I;
MoveWriter := MoveWriter + 1;
Result := Result + RecurseMamTakeWhite(N, NextNextI, OrtDirection, Board);
Board.Field[NextI] := SaveDead;
MoveWriter := MoveWriter - 1;
DeadCount := DeadCount - 1;
end;
end;
I := DirectionTable[Direction, I];
if I = -1 then Break;
if Board.Field[I] > 0 then Break;
if Board.Field[I] < 0 then
begin
NextI := DirectionTable[Direction, I];
if NextI = -1 then Break;
if Board.Field[NextI] = 0 then
begin
Dead[DeadCount] := I;
SaveDead := Board.Field[I];
Board.Field[I] := brBlackDead;
DeadCount := DeadCount + 1;
Board.MoveStr[MoveWriter] := Cell;
MoveWriter := MoveWriter + 1;
Result := Result + RecurseMamTakeWhite(N, NextI, Direction, Board);
Board.Field[I] := SaveDead;
MoveWriter := MoveWriter - 1;
DeadCount := DeadCount - 1;
end;
Break;
end;
until False;
if Result = 0 then
begin
Buffer[N] := Board;
for J := 0 to DeadCount-1 do
Buffer[N].Field[Dead[J]] := 0;
Buffer[N].MoveCount := 0;
Buffer[N].Active := ActiveBlack;
Buffer[N].TakeChar := WasTake;
Buffer[N].MoveStr[MoveWriter+1] := -1;
NN := N + 1;
Result := 1;
NextI := DirectionTable[Direction, Cell];
repeat
if NextI = -1 then Break;
if Board.Field[NextI] <> 0 then Break;
Buffer[NN] := Buffer[N];
Buffer[NN].Field[NextI] := brWhiteMam;
Buffer[NN].MoveStr[MoveWriter] := NextI;
NN := NN + 1;
Result := Result + 1;
NextI := DirectionTable[Direction, NextI];
until False;
Buffer[N].Field[Cell] := brWhiteMam;
Buffer[N].MoveStr[MoveWriter] := Cell;
N := NN;
end;
end;
// Beta tested 20.05.2002
function RecurseSingleTakeWhite(var N: Integer; Cell : Integer; Direction: TDirection; var Board: TPosition): Integer;
var
OrtDirection: TDirection;
NExtI, NExtNextI: Integer;
SaveDead: ShortInt;
J: Integer;
begin
Result := 0;
OrtDirection := OrtDirection1[Direction];
NextI := DirectionTable[OrtDirection, Cell];
if (NextI <> -1) and (Board.Field[NextI] < 0) then
begin
NextNextI := DirectionTable[OrtDirection, NextI];
if (NextNextI <> -1) and (Board.Field[NextNextI] = 0) then
begin
Dead[DeadCount] := NextI;
DeadCount := DeadCount + 1;
SaveDead := Board.Field[NextI];
Board.Field[NextI] := brBlackDead;
Board.MoveStr[MoveWriter] := Cell;
MoveWriter := MoveWriter + 1;
if NextNextI >= WhiteMamLine
then Result := Result + RecurseMamTakeWhite(N, NextNextI, OrtDirection, Board)
else Result := Result + RecurseSingleTakeWhite(N, NextNextI, OrtDirection, Board);
MoveWriter := MoveWriter - 1;
DeadCount := DeadCount - 1;
Board.Field[NextI] := SaveDead;
end;
end;
OrtDirection := OrtDirection2[Direction];
NextI := DirectionTable[OrtDirection, Cell];
if (NextI <> -1) and (Board.Field[NextI] < 0) then
begin
NextNextI := DirectionTable[OrtDirection, NextI];
if (NextNextI <> -1) and (Board.Field[NextNextI] = 0) then
begin
Dead[DeadCount] := NextI;
SaveDead := Board.Field[NextI];
Board.Field[NextI] := brBlackDead;
DeadCount := DeadCount + 1;
Board.MoveStr[MoveWriter] := Cell;
MoveWriter := MoveWriter + 1;
if NextNextI >= WhiteMamLine
then Result := Result + RecurseMamTakeWhite(N, NextNextI, OrtDirection, Board)
else Result := Result + RecurseSingleTakeWhite(N, NextNextI, OrtDirection, Board);
Board.Field[NextI] := SaveDead;
MoveWriter := MoveWriter - 1;
DeadCount := DeadCount - 1;
end;
end;
NextI := DirectionTable[Direction, Cell];
if (NextI <> -1) and (Board.Field[NextI] < 0) then
begin
NextNextI := DirectionTable[Direction, NextI];
if (NextNextI <> -1) and (Board.Field[NextNextI] = 0) then
begin
Dead[DeadCount] := NextI;
SaveDead := Board.Field[NextI];
Board.Field[NextI] := brBlackDead;
DeadCount := DeadCount + 1;
Board.MoveStr[MoveWriter] := Cell;
MoveWriter := MoveWriter + 1;
if NextNextI >= WhiteMamLine
then Result := Result + RecurseMamTakeWhite(N, NextNextI, Direction, Board)
else Result := Result + RecurseSingleTakeWhite(N, NextNextI, Direction, Board);
Board.Field[NextI] := SaveDead;
MoveWriter := MoveWriter - 1;
DeadCount := DeadCount - 1;
end;
end;
if Result = 0 then
begin
Buffer[N] := Board;
for J := 0 to DeadCount-1 do
Buffer[N].Field[Dead[J]] := 0;
Buffer[N].Field[Cell] := brWhiteSingle;
Buffer[N].MoveCount := 0;
Buffer[N].Active := ActiveBlack;
Buffer[N].TakeChar := WasTake;
Buffer[N].MoveStr[MoveWriter] := Cell;
Buffer[N].MoveStr[MoveWriter+1] := -1;
N := N + 1;
Result := 1;
end
end;
// Beta tested 19.05.2002
function GetMovesWhite(N: Integer; var Board: TPosition): Integer;
var
I: Integer;
Temp: Integer;
NextI, NextNextI: Integer;
SaveDead: ShortInt;
Direction: TDirection;
SingleMoves: array[0..1023] of TSingleMoveRec;
begin
Result := 0;
DeadCount := 0;
MoveWriter := 0;
for I := 0 to 31 do
begin
// Ход простой
if Board.Field[I] = brWhiteSingle then
begin
// Проверка на взятие вниз влево
NextI := DirectionTable[drLeftDown, I];
if (NextI <> -1) and (Board.Field[NextI] < 0) then
begin
NextNextI := DirectionTable[drLeftDown, NextI];
if (NextNextI <> -1) and (Board.Field[NextNextI] = 0) then
begin
if Result > 0 then Result := 0;
Board.Field[I] := 0;
Dead[DeadCount] := NextI;
SaveDead := Board.Field[NextI];
Board.Field[NextI] := brBlackDead;
DeadCount := DeadCount + 1;
Board.MoveStr[MoveWriter] := I;
MoveWriter := MoveWriter + 1;
{if NextNextI >= WhiteMamLine} // Оптимизаия --- взятие назад не может привести к дамке
{ then Result := Result - RecurseMamTakeWhite(N, NextNextI, drLeftDown, Board)}
{else} Result := Result - RecurseSingleTakeWhite(N, NextNextI, drLeftDown, Board);
Board.Field[NextI] := SaveDead;
MoveWriter := MoveWriter - 1;
DeadCount := DeadCount - 1;
Board.Field[I] := brWhiteSingle;
end;
end;
// Проверка на взятие вниз вправо
NextI := DirectionTable[drRightDown, I];
if (NextI <> -1) and (Board.Field[NextI] < 0) then
begin
NextNextI := DirectionTable[drRightDown, NextI];
if (NextNextI <> -1) and (Board.Field[NextNextI] = 0) then
begin
if Result > 0 then Result := 0;
Board.Field[I] := 0;
Dead[DeadCount] := NextI;
SaveDead := Board.Field[NextI];
Board.Field[NextI] := brBlackDead;
DeadCount := DeadCount + 1;
Board.MoveStr[MoveWriter] := I;
MoveWriter := MoveWriter + 1;
{if NextNextI >= WhiteMamLine} // Оптимизаия --- взятие назад не может привести к дамке
{ then Result := Result - RecurseMamTakeWhite(N, NextNextI, drRightDown, Board)}
{else} Result := Result - RecurseSingleTakeWhite(N, NextNextI, drRightDown, Board);
Board.Field[NextI] := SaveDead;
MoveWriter := MoveWriter - 1;
DeadCount := DeadCount - 1;
Board.Field[I] := brWhiteSingle;
end;
end;
// Ход влево вверх
NextI := DirectionTable[drLeftUp, I];
if NextI >= 0 then
begin
Temp := Board.Field[NextI];
if Temp = 0 then // Поле свободно
begin
if Result >= 0 then // Не было взятий
begin
SingleMoves[Result].PointFrom := I;
SingleMoves[Result].PointTo := NextI;
SingleMoves[Result].Counter := 0;
if NextI >= WhiteMamLine
then SingleMoves[Result].WhatPut := brWhiteMam
else SingleMoves[Result].WhatPut := brWhiteSingle;
Result := Result + 1;
end
end
else begin
if Temp < 0 then
begin
NextNextI := DirectionTable[drLeftUp, NextI];
if (NextNextI <> -1) and (Board.Field[NextNextI] = 0) then
begin
if Result > 0 then Result := 0;
Board.Field[I] := 0;
Dead[DeadCount] := NextI;
SaveDead := Board.Field[NextI];
Board.Field[NextI] := brBlackDead;
DeadCount := DeadCount + 1;
Board.MoveStr[MoveWriter] := I;
MoveWriter := MoveWriter + 1;
if NextNextI >= WhiteMamLine
then Result := Result - RecurseMamTakeWhite(N, NextNextI, drLeftUp, Board)
else Result := Result - RecurseSingleTakeWhite(N, NextNextI, drLeftUp, Board);
Board.Field[NextI] := SaveDead;
MoveWriter := MoveWriter - 1;
DeadCount := DeadCount - 1;
Board.Field[I] := brWhiteSingle;
end;
end;
end;
end;
// Ход вправо вверх
NextI := DirectionTable[drRightUp, I];
if NextI >= 0 then
begin
Temp := Board.Field[NextI];
if Temp = 0 then // Поле свободно
begin
if Result >= 0 then // Не было взятий
begin
SingleMoves[Result].PointFrom := I;
SingleMoves[Result].PointTo := NextI;
SingleMoves[Result].Counter := 0;
if NextI >= WhiteMamLine
then SingleMoves[Result].WhatPut := brWhiteMam
else SingleMoves[Result].WhatPut := brWhiteSingle;
Result := Result + 1;
end
end
else begin
if Temp < 0 then
begin
NextNextI := DirectionTable[drRightUp, NextI];
if (NextNextI <> -1) and (Board.Field[NextNextI] = 0) then
begin
if Result > 0 then Result := 0;
Board.Field[I] := 0;
Dead[DeadCount] := NextI;
SaveDead := Board.Field[NextI];
Board.Field[NextI] := brBlackDead;
DeadCount := DeadCount + 1;
Board.MoveStr[MoveWriter] := I;
MoveWriter := MoveWriter + 1;
if NextNextI >= WhiteMamLine
then Result := Result - RecurseMamTakeWhite(N, NextNextI, drRightUp, Board)
else Result := Result - RecurseSingleTakeWhite(N, NextNextI, drRightUp, Board);
Board.Field[NextI] := SaveDead;
MoveWriter := MoveWriter - 1;
DeadCount := DeadCount - 1;
Board.Field[I] := brWhiteSingle;
end;
end;
end;
end;
end
// Ход дамкой.
else if Board.Field[I] = brWhiteMam then
begin
Board.Field[I] := 0;
for Direction := Low(TDirection) to High(TDirection) do
begin
NextI := DirectionTable[Direction, I];
repeat
if NextI = -1 then Break;
Temp := Board.Field[NextI];
if Temp = 0 then
begin
if Result >= 0 then // Не было взятий
begin
SingleMoves[Result].PointFrom := I;
SingleMoves[Result].PointTo := NextI;
SingleMoves[Result].Counter := Board.MoveCount + 1;
SingleMoves[Result].WhatPut := brWhiteMam;
Result := Result + 1;
end;
NextI := DirectionTable[Direction, NextI];
end
else if Temp < brBlackDead then begin
NextNextI := DirectionTable[Direction, NextI];
if (NextNextI <> -1) and (Board.Field[NextNextI] = 0) then
begin
Dead[DeadCount] := NextI;
SaveDead := Board.Field[NextI];
Board.Field[NextI] := brBlackDead;
DeadCount := DeadCount + 1;
Board.MoveStr[MoveWriter] := I;
MoveWriter := MoveWriter + 1;
if Result > 0 then Result := 0;
Result := Result - RecurseMamTakeWhite(N, NextNextI, Direction, Board);
Board.Field[NextI] := SaveDead;
MoveWriter := MoveWriter - 1;
DeadCount := DeadCount - 1;
end;
Break;
end
else
Break;
until False;
end;
Board.Field[I] := brWhiteMam;
end;
end;
for I := 0 to Result-1 do
begin
Buffer[N] := Board;
Buffer[N].Field[SingleMoves[I].PointFrom] := 0;
Buffer[N].Field[SingleMoves[I].PointTo] := SingleMoves[I].WhatPut;
Buffer[N].MoveCount := SingleMoves[I].Counter;
Buffer[N].Active := ActiveBlack;
Buffer[N].MoveStr[0] := SingleMoves[I].PointFrom;
Buffer[N].MoveStr[1] := SingleMoves[I].PointTo;
Buffer[N].MoveStr[2] := -1;
Buffer[N].TakeChar := WasNotTake;
N := N + 1;
end;
Result := Abs(Result);
end;
// Beta tested 19.05.2002
function RecurseMamTakeBlack(var N: Integer; Cell : Integer; Direction: TDirection; var Board: TPosition): Integer;
var
OrtDirection: TDirection;
NN: Integer;
I, J, NextI, NextNextI: Integer;
SaveDead: ShortInt;
begin
Result := 0;
I := Cell;
repeat
OrtDirection := OrtDirection1[Direction];
NextI := I;
repeat
NextI := DirectionTable[OrtDirection, NextI];
if NextI = -1 then Break;
if Board.Field[NextI] <> 0 then Break;
until False;
if (NextI <> -1) and (Board.Field[NextI] > 0) then
begin
NextNextI := DirectionTable[OrtDirection, NextI];
if (NextNextI <> -1) and (Board.Field[NextNextI] = 0) then
begin
Dead[DeadCount] := NextI;
SaveDead := Board.Field[NextI];
Board.Field[NextI] := brWhiteDead;
DeadCount := DeadCount + 1;
Board.MoveStr[MoveWriter] := I;
MoveWriter := MoveWriter + 1;
Result := Result + RecurseMamTakeBlack(N, NextNextI, OrtDirection, Board);
Board.Field[NextI] := SaveDead;
MoveWriter := MoveWriter - 1;
DeadCount := DeadCount - 1;
end;
end;
OrtDirection := OrtDirection2[Direction];
NextI := I;
repeat
NextI := DirectionTable[OrtDirection, NextI];
if NextI = -1 then Break;
if Board.Field[NextI] <> 0 then Break;
until False;
if (NextI <> -1) and (Board.Field[NextI] > 0) then
begin
NextNextI := DirectionTable[OrtDirection, NextI];
if (NextNextI <> -1) and (Board.Field[NextNextI] = 0) then
begin
Dead[DeadCount] := NextI;
SaveDead := Board.Field[NextI];
Board.Field[NextI] := brWhiteDead;
DeadCount := DeadCount + 1;
Board.MoveStr[MoveWriter] := I;
MoveWriter := MoveWriter + 1;
Result := Result + RecurseMamTakeBlack(N, NextNextI, OrtDirection, Board);
Board.Field[NextI] := SaveDead;
MoveWriter := MoveWriter - 1;
DeadCount := DeadCount - 1;
end;
end;
I := DirectionTable[Direction, I];
if I = -1 then Break;
if Board.Field[I] < 0 then Break;
if Board.Field[I] > 0 then
begin
NextI := DirectionTable[Direction, I];
if NextI = -1 then Break;
if Board.Field[NextI] = 0 then
begin
Dead[DeadCount] := I;
SaveDead := Board.Field[I];
Board.Field[I] := brWhiteDead;
DeadCount := DeadCount + 1;
Board.MoveStr[MoveWriter] := Cell;
MoveWriter := MoveWriter + 1;
Result := Result + RecurseMamTakeBlack(N, NextI, Direction, Board);
Board.Field[I] := SaveDead;
MoveWriter := MoveWriter - 1;
DeadCount := DeadCount - 1;
end;
Break;
end;
until False;
if Result = 0 then
begin
Buffer[N] := Board;
for J := 0 to DeadCount-1 do
Buffer[N].Field[Dead[J]] := 0;
Buffer[N].MoveCount := 0;
Buffer[N].Active := ActiveWhite;
Buffer[N].TakeChar := WasTake;
Buffer[N].MoveStr[MoveWriter+1] := -1;
NN := N + 1;
Result := 1;
NextI := DirectionTable[Direction, Cell];
repeat
if NextI = -1 then Break;
if Board.Field[NextI] <> 0 then Break;
Buffer[NN] := Buffer[N];
Buffer[NN].Field[NextI] := brBlackMam;
Buffer[NN].MoveStr[MoveWriter] := NextI;
NN := NN + 1;
Result := Result + 1;
NextI := DirectionTable[Direction, NextI];
until False;
Buffer[N].Field[Cell] := brBlackMam;
Buffer[N].MoveStr[MoveWriter] := Cell;
N := NN;
end;
end;
// Beta tested 20.05.2002
function RecurseSingleTakeBlack(var N: Integer; Cell : Integer; Direction: TDirection; var Board: TPosition): Integer;
var
OrtDirection: TDirection;
NExtI, NExtNextI: Integer;
SaveDead: ShortInt;
J: Integer;
begin
Result := 0;
OrtDirection := OrtDirection1[Direction];
NextI := DirectionTable[OrtDirection, Cell];
if (NextI <> -1) and (Board.Field[NextI] > 0) then
begin
NextNextI := DirectionTable[OrtDirection, NextI];
if (NextNextI <> -1) and (Board.Field[NextNextI] = 0) then
begin
Dead[DeadCount] := NextI;
DeadCount := DeadCount + 1;
SaveDead := Board.Field[NextI];
Board.Field[NextI] := brWhiteDead;
Board.MoveStr[MoveWriter] := Cell;
MoveWriter := MoveWriter + 1;
if NextNextI <= BlackMamLine
then Result := Result + RecurseMamTakeBlack(N, NextNextI, OrtDirection, Board)
else Result := Result + RecurseSingleTakeBlack(N, NextNextI, OrtDirection, Board);
MoveWriter := MoveWriter - 1;
DeadCount := DeadCount - 1;
Board.Field[NextI] := SaveDead;
end;
end;
OrtDirection := OrtDirection2[Direction];
NextI := DirectionTable[OrtDirection, Cell];
if (NextI <> -1) and (Board.Field[NextI] > 0) then
begin
NextNextI := DirectionTable[OrtDirection, NextI];
if (NextNextI <> -1) and (Board.Field[NextNextI] = 0) then
begin
Dead[DeadCount] := NextI;
SaveDead := Board.Field[NextI];
Board.Field[NextI] := brWhiteDead;
DeadCount := DeadCount + 1;
Board.MoveStr[MoveWriter] := Cell;
MoveWriter := MoveWriter + 1;
if NextNextI <= BlackMamLine
then Result := Result + RecurseMamTakeBlack(N, NextNextI, OrtDirection, Board)
else Result := Result + RecurseSingleTakeBlack(N, NextNextI, OrtDirection, Board);
Board.Field[NextI] := SaveDead;
MoveWriter := MoveWriter - 1;
DeadCount := DeadCount - 1;
end;
end;
NextI := DirectionTable[Direction, Cell];
if (NextI <> -1) and (Board.Field[NextI] > 0) then
begin
NextNextI := DirectionTable[Direction, NextI];
if (NextNextI <> -1) and (Board.Field[NextNextI] = 0) then
begin
Dead[DeadCount] := NextI;
SaveDead := Board.Field[NextI];
Board.Field[NextI] := brWhiteDead;
DeadCount := DeadCount + 1;
Board.MoveStr[MoveWriter] := Cell;
MoveWriter := MoveWriter + 1;
if NextNextI <= BlackMamLine
then Result := Result + RecurseMamTakeBlack(N, NextNextI, Direction, Board)
else Result := Result + RecurseSingleTakeBlack(N, NextNextI, Direction, Board);
Board.Field[NextI] := SaveDead;
MoveWriter := MoveWriter - 1;
DeadCount := DeadCount - 1;
end;
end;
if Result = 0 then
begin
Buffer[N] := Board;
for J := 0 to DeadCount-1 do
Buffer[N].Field[Dead[J]] := 0;
Buffer[N].Field[Cell] := brBlackSingle;
Buffer[N].MoveCount := 0;
Buffer[N].Active := ActiveWhite;
Buffer[N].TakeChar := WasTake;
Buffer[N].MoveStr[MoveWriter] := Cell;
Buffer[N].MoveStr[MoveWriter+1] := -1;
N := N + 1;
Result := 1;
end
end;
// Beta tested 19.05.2002
function GetMovesBlack(N: Integer; var Board: TPosition): Integer;
var
I: Integer;
Temp: Integer;
NextI, NextNextI: Integer;
SaveDead: ShortInt;
Direction: TDirection;
SingleMoves: array[0..1023] of TSingleMoveRec;
begin
Result := 0;
DeadCount := 0;
MoveWriter := 0;
for I := 0 to 31 do
begin
// Ход простой
if Board.Field[I] = brBlackSingle then
begin
// Проверка на взятие вверх влево
NextI := DirectionTable[drLeftUp, I];
if (NextI <> -1) and (Board.Field[NextI] > 0) then
begin
NextNextI := DirectionTable[drLeftUp, NextI];
if (NextNextI <> -1) and (Board.Field[NextNextI] = 0) then
begin
if Result > 0 then Result := 0;
Board.Field[I] := 0;
Dead[DeadCount] := NextI;
SaveDead := Board.Field[NextI];
Board.Field[NextI] := brWhiteDead;
DeadCount := DeadCount + 1;
Board.MoveStr[MoveWriter] := I;
MoveWriter := MoveWriter + 1;
{if NextNextI >= WhiteMamLine} // Оптимизаия --- взятие назад не может привести к дамке
{ then Result := Result - RecurseMamTakeBlack(N, NextNextI, drLeftDown, Board)}
{else} Result := Result - RecurseSingleTakeBlack(N, NextNextI, drLeftUp, Board);
Board.Field[NextI] := SaveDead;
MoveWriter := MoveWriter - 1;
DeadCount := DeadCount - 1;
Board.Field[I] := brBlackSingle;
end;
end;
// Проверка на взятие вверх вправо
NextI := DirectionTable[drRightUp, I];
if (NextI <> -1) and (Board.Field[NextI] > 0) then
begin
NextNextI := DirectionTable[drRightUp, NextI];
if (NextNextI <> -1) and (Board.Field[NextNextI] = 0) then
begin
if Result > 0 then Result := 0;
Board.Field[I] := 0;
Dead[DeadCount] := NextI;
SaveDead := Board.Field[NextI];
Board.Field[NextI] := brWhiteDead;
DeadCount := DeadCount + 1;
Board.MoveStr[MoveWriter] := I;
MoveWriter := MoveWriter + 1;
{if NextNextI >= WhiteMamLine} // Оптимизаия --- взятие назад не может привести к дамке
{ then Result := Result - RecurseMamTakeBlack(N, NextNextI, drRightDown, Board)}
{else} Result := Result - RecurseSingleTakeBlack(N, NextNextI, drRightUp, Board);
Board.Field[NextI] := SaveDead;
MoveWriter := MoveWriter - 1;
DeadCount := DeadCount - 1;
Board.Field[I] := brBlackSingle;
end;
end;
// Ход влево вниз
NextI := DirectionTable[drLeftDown, I];
if NextI >= 0 then
begin
Temp := Board.Field[NextI];
if Temp = 0 then // Поле свободно
begin
if Result >= 0 then // Не было взятий
begin
SingleMoves[Result].PointFrom := I;
SingleMoves[Result].PointTo := NextI;
SingleMoves[Result].Counter := 0;
if NextI <= BlackMamLine
then SingleMoves[Result].WhatPut := brBlackMam
else SingleMoves[Result].WhatPut := brBlackSingle;
Result := Result + 1;
end
end
else begin
if Temp > 0 then
begin
NextNextI := DirectionTable[drLeftDown, NextI];
if (NextNextI <> -1) and (Board.Field[NextNextI] = 0) then
begin
if Result > 0 then Result := 0;
Board.Field[I] := 0;
Dead[DeadCount] := NextI;
SaveDead := Board.Field[NextI];
Board.Field[NextI] := brWhiteDead;
DeadCount := DeadCount + 1;
Board.MoveStr[MoveWriter] := I;
MoveWriter := MoveWriter + 1;
if NextNextI <= BlackMamLine
then Result := Result - RecurseMamTakeBlack(N, NextNextI, drLeftDown, Board)
else Result := Result - RecurseSingleTakeBlack(N, NextNextI, drLeftDown, Board);
Board.Field[NextI] := SaveDead;
MoveWriter := MoveWriter - 1;
DeadCount := DeadCount - 1;
Board.Field[I] := brBlackSingle;
end;
end;
end;
end;
// Ход вправо вниз
NextI := DirectionTable[drRightDown, I];
if NextI >= 0 then
begin
Temp := Board.Field[NextI];
if Temp = 0 then // Поле свободно
begin
if Result >= 0 then // Не было взятий
begin
SingleMoves[Result].PointFrom := I;
SingleMoves[Result].PointTo := NextI;
SingleMoves[Result].Counter := 0;
if NextI <= BlackMamLine
then SingleMoves[Result].WhatPut := brBlackMam
else SingleMoves[Result].WhatPut := brBlackSingle;
Result := Result + 1;
end
end
else begin
if Temp > 0 then
begin
NextNextI := DirectionTable[drRightDown, NextI];
if (NextNextI <> -1) and (Board.Field[NextNextI] = 0) then
begin
if Result > 0 then Result := 0;
Board.Field[I] := 0;
Dead[DeadCount] := NextI;
SaveDead := Board.Field[NextI];
Board.Field[NextI] := brWhiteDead;
DeadCount := DeadCount + 1;
Board.MoveStr[MoveWriter] := I;
MoveWriter := MoveWriter + 1;
if NextNextI <= BlackMamLine
then Result := Result - RecurseMamTakeBlack(N, NextNextI, drRightDown, Board)
else Result := Result - RecurseSingleTakeBlack(N, NextNextI, drRightDown, Board);
Board.Field[NextI] := SaveDead;
MoveWriter := MoveWriter - 1;
DeadCount := DeadCount - 1;
Board.Field[I] := brBlackSingle;
end;
end;
end;
end;
end
// Ход дамкой.
else if Board.Field[I] = brBlackMam then
begin
Board.Field[I] := 0;
for Direction := Low(TDirection) to High(TDirection) do
begin
NextI := DirectionTable[Direction, I];
repeat
if NextI = -1 then Break;
Temp := Board.Field[NextI];
if Temp = 0 then
begin
if Result >= 0 then // Не было взятий
begin
SingleMoves[Result].PointFrom := I;
SingleMoves[Result].PointTo := NextI;
SingleMoves[Result].Counter := Board.MoveCount + 1;
SingleMoves[Result].WhatPut := brBlackMam;
Result := Result + 1;
end;
NextI := DirectionTable[Direction, NextI];
end
else if Temp >0 then begin
NextNextI := DirectionTable[Direction, NextI];
if (NextNextI <> -1) and (Board.Field[NextNextI] = 0) then
begin
Dead[DeadCount] := NextI;
SaveDead := Board.Field[NextI];
Board.Field[NextI] := brWhiteDead;
DeadCount := DeadCount + 1;
Board.MoveStr[MoveWriter] := I;
MoveWriter := MoveWriter + 1;
if Result > 0 then Result := 0;
Result := Result - RecurseMamTakeBlack(N, NextNextI, Direction, Board);
Board.Field[NextI] := SaveDead;
MoveWriter := MoveWriter - 1;
DeadCount := DeadCount - 1;
end;
Break;
end
else
Break;
until False;
end;
Board.Field[I] := brBlackMam;
end;
end;
for I := 0 to Result-1 do
begin
Buffer[N] := Board;
Buffer[N].Field[SingleMoves[I].PointFrom] := 0;
Buffer[N].Field[SingleMoves[I].PointTo] := SingleMoves[I].WhatPut;
Buffer[N].MoveCount := SingleMoves[I].Counter;
Buffer[N].Active := ActiveWhite;
Buffer[N].MoveStr[0] := SingleMoves[I].PointFrom;
Buffer[N].MoveStr[1] := SingleMoves[I].PointTo;
Buffer[N].MoveStr[2] := -1;
Buffer[N].TakeChar := WasNotTake;
N := N + 1;
end;
Result := Abs(Result);
end;
function GetMoves(Position: TPosition; Buf: PPosition; BufSize: Integer): Integer;
var
TempPosition: TPosition;
begin
TempPosition := Position;
if Position.Active = ActiveWhite
then Result := GetMovesWhite(0, TempPosition)
else Result := GetMovesBlack(0, TempPosition);
if BufSize > 0 then
if BufSize > Result
then Move(Buffer, Buf^, Result*SizeOf(TPosition))
else Move(Buffer, Buf^, BufSize*SizeOf(TPosition));
end;
function IsMaterialDraw(const Position: TPosition): Boolean;
var
BMamCount: Integer;
BSingleCount: Integer;
WMamCount: Integer;
WSingleCount: Integer;
WMamPos: Integer;
BMamPos: Integer;
I: Integer;
function Code(WMam, BMam, WSingle, BSingle: Integer): Boolean;
begin
Result := (WMam = WMamCount)
and (BMam = BMamCount)
and (WSingle = WSingleCount)
and (BSingle = BSingleCount)
end;
function BlackAround(Pos: Integer): Boolean;
var
Direction: TDirection;
NextI: Integer;
begin
Result := False;
for Direction := Low(TDirection) to High(TDirection) do
begin
NextI := Pos;
repeat
NextI := DirectionTable[Direction, NextI];
if NextI = -1 then Break;
if Position.Field[NextI] < 0 then
begin
Result := True;
Exit;
end;
until False;
end;
end;
function WhiteAround(Pos: Integer): Boolean;
var
Direction: TDirection;
NextI: Integer;
begin
Result := False;
for Direction := Low(TDirection) to High(TDirection) do
begin
NextI := Pos;
repeat
NextI := DirectionTable[Direction, NextI];
if NextI = -1 then Break;
if Position.Field[NextI] > 0 then
begin
Result := True;
Exit;
end;
until False;
end;
end;
begin
BMamCount := 0;
BSingleCount := 0;
WMamCount := 0;
WSingleCount := 0;
WMamPos := -1; // Make compiler happy
BMamPos := -1; // Make compiler happy
for I := 0 to 31 do
begin
case Position.Field[I] of
brWhiteSingle: WSingleCount := WSingleCount + 1;
brWhiteMam:
begin
WMamCount := WMamCount + 1;
WMamPos := I;
end;
brBlackSingle: BSingleCount := BSingleCount + 1;
brBlackMam:
begin
BMamCount := BMamCount + 1;
BMamPos := I;
end;
end;
end;
if Code(1, 1, 0, 0) then Result := not BlackAround(WMamPos) else
if Code(1, 2, 0, 0) then Result := not BlackAround(WMamPos) else
if Code(2, 1, 0, 0) then Result := not WhiteAround(BMamPos) else
if Code(1, 1, 1, 0) then Result := not WhiteAround(BMamPos) else
if Code(1, 1, 0, 1) then Result := not BlackAround(WMamPos) else
Result := False;
end;
function GameOver(const Position: TPosition): string;
begin
if GetMoves(Position, nil, 0) = 0 then
begin
if Position.Active = ActiveWhite
then Result := 'Black win 0-1 (no moves)'
else Result := 'White win 1-0 (no moves)';
Exit;
end;
if IsMaterialDraw(Position) then
begin
Result := 'Draw 1/2-1/2 (material)';
Exit;
end;
if Position.MoveCount > 32 then
begin
Result := 'Draw 1/2-1/2 (16 moves rule)';
Exit;
end;
end;
// Beta - tested 19.05.2002
procedure InitDirectionTable;
var
X, Y, C: Integer;
begin
C := 0;
for Y := 0 to 7 do
for X := 0 to 7 do
begin
if (X xor Y) and $01 = 0 then // Если поле черное...
begin
if (X>0) and (Y<7)
then DirectionTable[drLeftUp, C] := (X + 8*Y + 7) div 2
else DirectionTable[drLeftUp, C] := -1;
if (X<7) and (Y<7)
then DirectionTable[drRightUp, C] := (X + 8*Y + 9) div 2
else DirectionTable[drRightUp, C] := -1;
if (X>0) and (Y>0)
then DirectionTable[drLeftDown, C] := (X + 8*Y - 9) div 2
else DirectionTable[drLeftDown, C] := -1;
if (X<7) and (Y>0)
then DirectionTable[drRightDown, C] := (X + 8*Y -7) div 2
else DirectionTable[drRightDown, C] := -1;
C := C + 1;
end;
end;
end;
// Beta tested 19.05.2002
procedure SetStartBoard;
var
I: Integer;
begin
for I := 0 to 11 do
StartBoard.Field[I] := brWhiteSingle;
for I := 20 to 31 do
StartBoard.Field[I] := brBlackSingle;
StartBoard.MoveStr[0] := -1;
StartBoard.MoveCount := 0;
StartBoard.Active := ActiveWhite;
end;
procedure Init;
begin
InitDirectionTable;
SetStartBoard;
end;
procedure Done;
begin
end;
initialization
Init;
finalization
Done;
end.
|
(*----------------------------------------------------------------------------*
* Direct3D sample from DirectX 9.0 SDK December 2006 *
* Delphi adaptation by Alexey Barkovoy (e-mail: directx@clootie.ru) *
* *
* Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 *
* *
* Latest version can be downloaded from: *
* http://www.clootie.ru *
* http://sourceforge.net/projects/delphi-dx9sdk *
*----------------------------------------------------------------------------*
* $Id: MeshFromOBJunit.pas,v 1.19 2007/02/05 22:21:10 clootie Exp $
*----------------------------------------------------------------------------*)
//--------------------------------------------------------------------------------------
// File: MeshFromOBJ.cpp
//
// This sample shows how an ID3DXMesh object can be created from mesh data stored in an
// .obj file. It's convenient to use .x files when working with ID3DXMesh objects since
// D3DX can create and fill an ID3DXMesh object directly from an .x file; however, it's
// also easy to initialize an ID3DXMesh object with data gathered from any file format
// or memory resource.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//--------------------------------------------------------------------------------------
{$I DirectX.inc}
unit MeshFromOBJunit;
interface
uses
Windows, Direct3D9, D3DX9, DXTypes, DXErr9, StrSafe, MeshLoader,
DXUT, DXUTcore, DXUTenum, DXUTmisc, DXUTgui, DXUTmesh, DXUTSettingsDlg;
{.$DEFINE DEBUG_VS} // Uncomment this line to debug vertex shaders
{.$DEFINE DEBUG_PS} // Uncomment this line to debug pixel shaders
//--------------------------------------------------------------------------------------
// Global variables
//--------------------------------------------------------------------------------------
var
g_pFont: ID3DXFont; // Font for drawing text
g_pTextSprite: ID3DXSprite; // Sprite for batching draw text calls
g_pEffect: ID3DXEffect; // D3DX effect interface
g_Camera: CModelViewerCamera; // A model viewing camera
g_bShowHelp: Boolean = True; // If true, it renders the UI control text
g_DialogResourceManager: CDXUTDialogResourceManager; // manager for shared resources of dialogs
g_SettingsDlg: CD3DSettingsDlg; // Device settings dialog
g_HUD: CDXUTDialog; // dialog for standard controls
g_SampleUI: CDXUTDialog; // dialog for sample specific controls
g_MeshLoader: CMeshLoader; // Loads a mesh from an .obj file
g_strFileSaveMessage: array[0..MAX_PATH-1] of WideChar; // Text indicating file write success/failure
//--------------------------------------------------------------------------------------
// Effect parameter handles
//--------------------------------------------------------------------------------------
var
g_hAmbient: TD3DXHandle = nil;
g_hDiffuse: TD3DXHandle = nil;
g_hSpecular: TD3DXHandle = nil;
g_hOpacity: TD3DXHandle = nil;
g_hSpecularPower: TD3DXHandle = nil;
g_hLightColor: TD3DXHandle = nil;
g_hLightPosition: TD3DXHandle = nil;
g_hCameraPosition: TD3DXHandle = nil;
g_hTexture: TD3DXHandle = nil;
g_hTime: TD3DXHandle = nil;
g_hWorld: TD3DXHandle = nil;
g_hWorldViewProjection: TD3DXHandle = nil;
//--------------------------------------------------------------------------------------
// UI control IDs
//--------------------------------------------------------------------------------------
const
IDC_STATIC = -1;
IDC_TOGGLEFULLSCREEN = 1;
IDC_TOGGLEREF = 3;
IDC_CHANGEDEVICE = 4;
IDC_SUBSET = 5;
IDC_SAVETOX = 6;
//--------------------------------------------------------------------------------------
// Forward declarations
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall;
procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall;
procedure OnLostDevice(pUserContext: Pointer); stdcall;
procedure OnDestroyDevice(pUserContext: Pointer); stdcall;
procedure InitApp;
procedure RenderText;
procedure RenderSubset(iSubset: LongWord);
procedure SaveMeshToXFile;
procedure CreateCustomDXUTobjects;
procedure DestroyCustomDXUTobjects;
implementation
//--------------------------------------------------------------------------------------
// Initialize the app
//--------------------------------------------------------------------------------------
procedure InitApp;
var
iY: Integer;
pElement: CDXUTElement;
begin
// Initialize dialogs
g_SettingsDlg.Init(g_DialogResourceManager);
g_HUD.Init(g_DialogResourceManager);
g_SampleUI.Init(g_DialogResourceManager);
g_HUD.SetCallback(OnGUIEvent); iY := 10;
g_HUD.AddButton(IDC_TOGGLEFULLSCREEN, 'Toggle full screen', 35, iY, 125, 22); Inc(iY, 24);
g_HUD.AddButton(IDC_TOGGLEREF, 'Toggle REF (F3)', 35, iY, 125, 22); Inc(iY, 24);
g_HUD.AddButton(IDC_CHANGEDEVICE, 'Change device (F2)', 35, iY, 125, 22, VK_F2);
g_SampleUI.SetCallback(OnGUIEvent); // iY := 10;
// Title font for comboboxes
g_SampleUI.SetFont(1, 'Arial', 14, FW_BOLD);
pElement:= g_SampleUI.GetDefaultElement(DXUT_CONTROL_STATIC, 0);
if Assigned(pElement) then
with pElement do
begin
iFont := 1;
dwTextFormat := DT_LEFT or DT_BOTTOM;
end;
g_SampleUI.AddStatic(IDC_STATIC, '(S)ubset', 20, 0, 105, 25);
g_SampleUI.AddComboBox(IDC_SUBSET, 20, 25, 140, 24, Ord('S'));
g_SampleUI.AddButton(IDC_SAVETOX, 'Save Mesh To X file', 20, 50, 140, 24, Ord('X'));
end;
//--------------------------------------------------------------------------------------
// Called during device initialization, this code checks the device for some
// minimum set of capabilities, and rejects those that don't pass by returning false.
//--------------------------------------------------------------------------------------
function IsDeviceAcceptable(const pCaps: TD3DCaps9; AdapterFormat, BackBufferFormat: TD3DFormat; bWindowed: Boolean; pUserContext: Pointer): Boolean; stdcall;
var
pD3D: IDirect3D9;
begin
Result:= False;
// No fallback defined by this app, so reject any device that
// doesn't support at least ps2.0
if (pCaps.PixelShaderVersion < D3DPS_VERSION(2,0)) then Exit;
// Skip backbuffer formats that don't support alpha blending
pD3D := DXUTGetD3DObject;
if FAILED(pD3D.CheckDeviceFormat(pCaps.AdapterOrdinal, pCaps.DeviceType,
AdapterFormat, D3DUSAGE_QUERY_POSTPIXELSHADER_BLENDING,
D3DRTYPE_TEXTURE, BackBufferFormat))
then Exit;
Result:= True;
end;
//--------------------------------------------------------------------------------------
// This callback function is called immediately before a device is created to allow the
// application to modify the device settings. The supplied pDeviceSettings parameter
// contains the settings that the framework has selected for the new device, and the
// application can make any desired changes directly to this structure. Note however that
// DXUT will not correct invalid device settings so care must be taken
// to return valid device settings, otherwise IDirect3D9::CreateDevice() will fail.
//--------------------------------------------------------------------------------------
{static} var s_bFirstTime: Boolean = True;
function ModifyDeviceSettings(var pDeviceSettings: TDXUTDeviceSettings; const pCaps: TD3DCaps9; pUserContext: Pointer): Boolean; stdcall;
var
pEnum: CD3DEnumeration;
pCombo: PD3DEnumDeviceSettingsCombo;
sample: TD3DMultiSampleType;
begin
// If device doesn't support HW T&L or doesn't support 1.1 vertex shaders in HW
// then switch to SWVP.
if (pCaps.DevCaps and D3DDEVCAPS_HWTRANSFORMANDLIGHT = 0) or
(pCaps.VertexShaderVersion < D3DVS_VERSION(1,1))
then pDeviceSettings.BehaviorFlags := D3DCREATE_SOFTWARE_VERTEXPROCESSING;
// Debugging vertex shaders requires either REF or software vertex processing
// and debugging pixel shaders requires REF.
{$IFDEF DEBUG_VS}
if (pDeviceSettings.DeviceType <> D3DDEVTYPE_REF) then
with pDeviceSettings do
begin
BehaviorFlags := BehaviorFlags and not D3DCREATE_HARDWARE_VERTEXPROCESSING;
BehaviorFlags := BehaviorFlags and not D3DCREATE_PUREDEVICE;
BehaviorFlags := BehaviorFlags or D3DCREATE_SOFTWARE_VERTEXPROCESSING;
end;
{$ENDIF}
{$IFDEF DEBUG_PS}
pDeviceSettings.DeviceType := D3DDEVTYPE_REF;
{$ENDIF}
// Enable anti-aliasing for HAL devices which support it
pEnum := DXUTGetEnumeration;
pCombo := pEnum.GetDeviceSettingsCombo(pDeviceSettings);
sample:= D3DMULTISAMPLE_4_SAMPLES;
if (pDeviceSettings.DeviceType = D3DDEVTYPE_HAL) and
(DynArrayContains(pCombo.multiSampleTypeList, sample, SizeOf(TD3DMultiSampleType))) then
begin
pDeviceSettings.pp.MultiSampleType := D3DMULTISAMPLE_4_SAMPLES;
pDeviceSettings.pp.MultiSampleQuality := 0;
end;
// For the first device created if its a REF device, optionally display a warning dialog box
if s_bFirstTime then
begin
s_bFirstTime := False;
if (pDeviceSettings.DeviceType = D3DDEVTYPE_REF) then DXUTDisplaySwitchingToREFWarning;
end;
Result:= True;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has been
// created, which will happen during application initialization and windowed/full screen
// toggles. This is the best location to create D3DPOOL_MANAGED resources since these
// resources need to be reloaded whenever the device is destroyed. Resources created
// here should be released in the OnDestroyDevice callback.
//--------------------------------------------------------------------------------------
function OnCreateDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
var
str: array[0..MAX_PATH-1] of WideChar;
pComboBox: CDXUTComboBox;
i: Integer;
pMat: PMaterial;
dwShaderFlags: DWORD;
vecEye, vecAt: TD3DXVector3;
begin
Result:= g_DialogResourceManager.OnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
Result:= g_SettingsDlg.OnCreateDevice(pd3dDevice);
if V_Failed(Result) then Exit;
// Initialize the font
Result := D3DXCreateFont(pd3dDevice, 15, 0, FW_BOLD, 1, FALSE, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, DEFAULT_QUALITY, DEFAULT_PITCH or FF_DONTCARE,
'Arial', g_pFont);
if V_Failed(Result) then Exit;
// Create the mesh and load it with data already gathered from a file
Result := g_MeshLoader.CreateMesh(pd3dDevice, 'media\cup.obj');
if V_Failed(Result) then Exit;
// Add the identified material subsets to the UI
pComboBox := g_SampleUI.GetComboBox(IDC_SUBSET);
pComboBox.RemoveAllItems;
pComboBox.AddItem('All', Pointer(INT_PTR(-1)));
for i := 0 to g_MeshLoader.NumMaterials - 1 do
begin
pMat := g_MeshLoader.Material[i];
pComboBox.AddItem(pMat.strName, Pointer(INT_PTR(i)));
end;
// Define DEBUG_VS and/or DEBUG_PS to debug vertex and/or pixel shaders with the
// shader debugger. Debugging vertex shaders requires either REF or software vertex
// processing, and debugging pixel shaders requires REF. The
// D3DXSHADER_FORCE_*_SOFTWARE_NOOPT flag improves the debug experience in the
// shader debugger. It enables source level debugging, prevents instruction
// reordering, prevents dead code elimination, and forces the compiler to compile
// against the next higher available software target, which ensures that the
// unoptimized shaders do not exceed the shader model limitations. Setting these
// flags will cause slower rendering since the shaders will be unoptimized and
// forced into software. See the DirectX documentation for more information about
// using the shader debugger.
dwShaderFlags := D3DXFX_NOT_CLONEABLE;
{$IFDEF DEBUG}
// Set the D3DXSHADER_DEBUG flag to embed debug information in the shaders.
// Setting this flag improves the shader debugging experience, but still allows
// the shaders to be optimized and to run exactly the way they will run in
// the release configuration of this program.
dwShaderFlags := dwShaderFlags or D3DXSHADER_DEBUG;
{$ENDIF}
{$IFDEF DEBUG_VS}
dwShaderFlags := g_dwShaderFlags or D3DXSHADER_FORCE_VS_SOFTWARE_NOOPT;
{$ENDIF}
{$IFDEF DEBUG_PS}
dwShaderFlags := g_dwShaderFlags or D3DXSHADER_FORCE_PS_SOFTWARE_NOOPT;
{$ENDIF}
// Read the D3DX effect file
Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, WideString('MeshFromOBJ.fx'));
if V_Failed(Result) then Exit;
// If this fails, there should be debug output as to
// they the .fx file failed to compile
Result:= D3DXCreateEffectFromFileW(pd3dDevice, str, nil, nil, dwShaderFlags,
nil, g_pEffect, nil);
if V_Failed(Result) then Exit;
// Cache the effect handles
g_hAmbient := g_pEffect.GetParameterBySemantic(nil, 'Ambient');
g_hDiffuse := g_pEffect.GetParameterBySemantic(nil, 'Diffuse');
g_hSpecular := g_pEffect.GetParameterBySemantic(nil, 'Specular');
g_hOpacity := g_pEffect.GetParameterBySemantic(nil, 'Opacity');
g_hSpecularPower := g_pEffect.GetParameterBySemantic(nil, 'SpecularPower');
g_hLightColor := g_pEffect.GetParameterBySemantic(nil, 'LightColor');
g_hLightPosition := g_pEffect.GetParameterBySemantic(nil, 'LightPosition');
g_hCameraPosition := g_pEffect.GetParameterBySemantic(nil, 'CameraPosition');
g_hTexture := g_pEffect.GetParameterBySemantic(nil, 'Texture');
g_hTime := g_pEffect.GetParameterBySemantic(nil, 'Time');
g_hWorld := g_pEffect.GetParameterBySemantic(nil, 'World');
g_hWorldViewProjection := g_pEffect.GetParameterBySemantic(nil, 'WorldViewProjection');
// Setup the camera's view parameters
vecEye := D3DXVector3(2.0, 1.0, 0.0);
vecAt := D3DXVector3(0.0, 0.0, -0.0);
g_Camera.SetViewParams(vecEye, vecAt);
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has been
// reset, which will happen after a lost device scenario. This is the best location to
// create D3DPOOL_DEFAULT resources since these resources need to be reloaded whenever
// the device is lost. Resources created here should be released in the OnLostDevice
// callback.
//--------------------------------------------------------------------------------------
function OnResetDevice(const pd3dDevice: IDirect3DDevice9; const pBackBufferSurfaceDesc: TD3DSurfaceDesc; pUserContext: Pointer): HRESULT; stdcall;
var
i: LongWord;
pMat: PMaterial;
strTechnique: PChar;
fAspectRatio: Single;
begin
Result:= g_DialogResourceManager.OnResetDevice;
if V_Failed(Result) then Exit;
Result:= g_SettingsDlg.OnResetDevice;
if V_Failed(Result) then Exit;
if Assigned(g_pFont) then
begin
Result:= g_pFont.OnResetDevice;
if V_Failed(Result) then Exit;
end;
if Assigned(g_pEffect) then
begin
Result:= g_pEffect.OnResetDevice;
if V_Failed(Result) then Exit;
end;
// Store the correct technique handles for each material
for i := 0 to g_MeshLoader.NumMaterials - 1 do
begin
pMat := g_MeshLoader.Material[i];
strTechnique:= '';
if (pMat.pTexture <> nil) and pMat.bSpecular then strTechnique := 'TexturedSpecular'
else if (pMat.pTexture <> nil) and not pMat.bSpecular then strTechnique := 'TexturedNoSpecular'
else if (pMat.pTexture = nil) and pMat.bSpecular then strTechnique := 'Specular'
else if (pMat.pTexture = nil) and not pMat.bSpecular then strTechnique := 'NoSpecular';
pMat.hTechnique := g_pEffect.GetTechniqueByName(strTechnique);
end;
// Create a sprite to help batch calls when drawing many lines of text
Result:= D3DXCreateSprite(pd3dDevice, g_pTextSprite);
if V_Failed(Result) then Exit;
// Setup the camera's projection parameters
fAspectRatio := pBackBufferSurfaceDesc.Width / pBackBufferSurfaceDesc.Height;
g_Camera.SetProjParams(D3DX_PI/4, fAspectRatio, 0.1, 1000.0);
g_Camera.SetWindow(pBackBufferSurfaceDesc.Width, pBackBufferSurfaceDesc.Height);
g_HUD.SetLocation(pBackBufferSurfaceDesc.Width-170, 0);
g_HUD.SetSize(170, 170);
g_HUD.Refresh;
g_SampleUI.SetLocation(pBackBufferSurfaceDesc.Width-170, pBackBufferSurfaceDesc.Height-350);
g_SampleUI.SetSize(170, 300);
g_SampleUI.Refresh;
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called once at the beginning of every frame. This is the
// best location for your application to handle updates to the scene, but is not
// intended to contain actual rendering calls, which should instead be placed in the
// OnFrameRender callback.
//--------------------------------------------------------------------------------------
procedure OnFrameMove(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
begin
// Update the camera's position based on user input
g_Camera.FrameMove(fElapsedTime);
end;
//--------------------------------------------------------------------------------------
// This callback function will be called at the end of every frame to perform all the
// rendering calls for the scene, and it will also be called if the window needs to be
// repainted. After this function has returned, DXUT will call
// IDirect3DDevice9::Present to display the contents of the next buffer in the swap chain
//--------------------------------------------------------------------------------------
procedure OnFrameRender(const pd3dDevice: IDirect3DDevice9; fTime: Double; fElapsedTime: Single; pUserContext: Pointer); stdcall;
var
m: TD3DXMatrixA16;
mWorld: TD3DXMatrixA16;
mView: TD3DXMatrixA16;
mProj: TD3DXMatrixA16;
mWorldViewProjection: TD3DXMatrixA16;
iCurSubset: LongWord;
iSubset: LongWord;
begin
// If the settings dialog is being shown, then
// render it instead of rendering the app's scene
if g_SettingsDlg.Active then
begin
g_SettingsDlg.OnRender(fElapsedTime);
Exit;
end;
// Clear the render target and the zbuffer
V(pd3dDevice.Clear(0, nil, D3DCLEAR_TARGET or D3DCLEAR_ZBUFFER, D3DCOLOR_ARGB(0, 141, 153, 191), 1.0, 0));
// Render the scene
if SUCCEEDED(pd3dDevice.BeginScene) then
begin
// Get the projection & view matrix from the camera class
mWorld := g_Camera.GetWorldMatrix^;
mView := g_Camera.GetViewMatrix^;
mProj := g_Camera.GetProjMatrix^;
// mWorldViewProjection = mWorld * mView * mProj;
D3DXMatrixMultiply(m, mView, mProj);
D3DXMatrixMultiply(mWorldViewProjection, mWorld, m);
// Update the effect's variables.
V(g_pEffect.SetMatrix(g_hWorldViewProjection, mWorldViewProjection));
V(g_pEffect.SetMatrix(g_hWorld, mWorld));
V(g_pEffect.SetFloat(g_hTime, fTime));
V(g_pEffect.SetValue(g_hCameraPosition, g_Camera.GetEyePt, SizeOf(TD3DXVector3)));
iCurSubset := UINT_PTR(g_SampleUI.GetComboBox(IDC_SUBSET).GetSelectedData);
// A subset of -1 was arbitrarily chosen to represent all subsets
if (iCurSubset = DWORD(-1)) then
begin
// Iterate through subsets, changing material properties for each
for iSubset := 0 to g_MeshLoader.NumMaterials - 1 do
RenderSubset(iSubset);
end else
RenderSubset(iCurSubset);
RenderText;
V(g_HUD.OnRender(fElapsedTime));
V(g_SampleUI.OnRender(fElapsedTime));
V(pd3dDevice.EndScene);
end;
end;
//--------------------------------------------------------------------------------------
procedure RenderSubset(iSubset: LongWord);
var
iPass, cPasses: Integer;
pMesh: ID3DXMesh;
pMaterial: MeshLoader.PMaterial;
begin
// Retrieve the ID3DXMesh pointer and current material from the MeshLoader helper
pMesh := g_MeshLoader.Mesh;
pMaterial := g_MeshLoader.Material[iSubset];
// Set the lighting variables and texture for the current material
V(g_pEffect.SetValue(g_hAmbient, @pMaterial.vAmbient, SizeOf(TD3DXVector3)));
V(g_pEffect.SetValue(g_hDiffuse, @pMaterial.vDiffuse, SizeOf(TD3DXVector3)));
V(g_pEffect.SetValue(g_hSpecular, @pMaterial.vSpecular, SizeOf(TD3DXVector3)));
V(g_pEffect.SetTexture(g_hTexture, pMaterial.pTexture));
V(g_pEffect.SetFloat(g_hOpacity, pMaterial.fAlpha));
V(g_pEffect.SetInt(g_hSpecularPower, pMaterial.nShininess));
V(g_pEffect.SetTechnique(pMaterial.hTechnique));
V(g_pEffect._Begin(@cPasses, 0));
for iPass := 0 to cPasses - 1 do
begin
V(g_pEffect.BeginPass(iPass));
// The effect interface queues up the changes and performs them
// with the CommitChanges call. You do not need to call CommitChanges if
// you are not setting any parameters between the BeginPass and EndPass.
// V( g_pEffect->CommitChanges() );
// Render the mesh with the applied technique
V(pMesh.DrawSubset(iSubset));
V(g_pEffect.EndPass);
end;
V(g_pEffect._End);
end;
//--------------------------------------------------------------------------------------
// Render the help and statistics text. This function uses the ID3DXFont interface for
// efficient text rendering.
//--------------------------------------------------------------------------------------
procedure RenderText;
var
txtHelper: CDXUTTextHelper;
pd3dsdBackBuffer: PD3DSurfaceDesc;
begin
// The helper object simply helps keep track of text position, and color
// and then it calls pFont->DrawText( m_pSprite, strMsg, -1, &rc, DT_NOCLIP, m_clr );
// If NULL is passed in as the sprite object, then it will work however the
// pFont->DrawText() will not be batched together. Batching calls will improves performance.
txtHelper := CDXUTTextHelper.Create(g_pFont, g_pTextSprite, 15);
// Output statistics
txtHelper._Begin;
txtHelper.SetInsertionPos(5, 5);
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 0.0, 1.0));
txtHelper.DrawTextLine(DXUTGetFrameStats);
txtHelper.DrawTextLine(DXUTGetDeviceStats);
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 1.0, 1.0));
txtHelper.DrawTextLine(g_strFileSaveMessage);
// Draw help
if g_bShowHelp then
begin
pd3dsdBackBuffer := DXUTGetBackBufferSurfaceDesc;
txtHelper.SetInsertionPos(10, pd3dsdBackBuffer.Height-15*5);
txtHelper.SetForegroundColor(D3DXColorFromDWord(D3DCOLOR_ARGB(200, 50, 50, 50)));
txtHelper.DrawTextLine('Controls (F1 to hide):');
txtHelper.SetInsertionPos(20, pd3dsdBackBuffer.Height-15*4);
txtHelper.DrawTextLine('Rotate model: Left mouse button'#10+
'Rotate camera: Right mouse button'#10+
'Zoom camera: Mouse wheel scroll'#10);
txtHelper.SetInsertionPos(250, pd3dsdBackBuffer.Height-15*4);
txtHelper.DrawTextLine('Hide help: F1'#10);
txtHelper.DrawTextLine('Quit: ESC'#10);
end else
begin
txtHelper.SetForegroundColor(D3DXColor(1.0, 1.0, 1.0, 1.0));
txtHelper.DrawTextLine('Press F1 for help');
end;
txtHelper._End;
txtHelper.Free;
end;
//--------------------------------------------------------------------------------------
// Before handling window messages, DXUT passes incoming windows
// messages to the application through this callback function. If the application sets
// *pbNoFurtherProcessing to TRUE, then DXUT will not process this message.
//--------------------------------------------------------------------------------------
function MsgProc(hWnd: HWND; uMsg: LongWord; wParam: WPARAM; lParam: LPARAM; out pbNoFurtherProcessing: Boolean; pUserContext: Pointer): LRESULT; stdcall;
begin
Result:= 0;
// Always allow dialog resource manager calls to handle global messages
// so GUI state is updated correctly
pbNoFurtherProcessing := g_DialogResourceManager.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
if g_SettingsDlg.IsActive then
begin
g_SettingsDlg.MsgProc(hWnd, uMsg, wParam, lParam);
Exit;
end;
// Give the dialogs a chance to handle the message first
pbNoFurtherProcessing := g_HUD.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
pbNoFurtherProcessing := g_SampleUI.MsgProc(hWnd, uMsg, wParam, lParam);
if pbNoFurtherProcessing then Exit;
// Pass all remaining windows messages to camera so it can respond to user input
if Assigned(g_Camera) then g_Camera.HandleMessages(hWnd, uMsg, wParam, lParam);
Result:= 0;
end;
//--------------------------------------------------------------------------------------
// As a convenience, DXUT inspects the incoming windows messages for
// keystroke messages and decodes the message parameters to pass relevant keyboard
// messages to the application. The framework does not remove the underlying keystroke
// messages, which are still passed to the application's MsgProc callback.
//--------------------------------------------------------------------------------------
procedure KeyboardProc(nChar: LongWord; bKeyDown, bAltDown: Boolean; pUserContext: Pointer); stdcall;
begin
if bKeyDown then
begin
case nChar of
VK_F1: g_bShowHelp := not g_bShowHelp;
end;
end;
end;
//--------------------------------------------------------------------------------------
// Handles the GUI events
//--------------------------------------------------------------------------------------
procedure OnGUIEvent(nEvent: LongWord; nControlID: Integer; pControl: CDXUTControl; pUserContext: Pointer); stdcall;
begin
case nControlID of
IDC_TOGGLEFULLSCREEN: DXUTToggleFullScreen;
IDC_TOGGLEREF: DXUTToggleREF;
IDC_CHANGEDEVICE: with g_SettingsDlg do Active := not Active;
IDC_SAVETOX: SaveMeshToXFile;
end;
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has
// entered a lost state and before IDirect3DDevice9::Reset is called. Resources created
// in the OnResetDevice callback should be released here, which generally includes all
// D3DPOOL_DEFAULT resources. See the "Lost Devices" section of the documentation for
// information about lost devices.
//--------------------------------------------------------------------------------------
procedure OnLostDevice; stdcall;
begin
g_DialogResourceManager.OnLostDevice;
g_SettingsDlg.OnLostDevice;
if Assigned(g_pFont) then g_pFont.OnLostDevice;
if Assigned(g_pEffect) then g_pEffect.OnLostDevice;
SAFE_RELEASE(g_pTextSprite);
end;
//--------------------------------------------------------------------------------------
// This callback function will be called immediately after the Direct3D device has
// been destroyed, which generally happens as a result of application termination or
// windowed/full screen toggles. Resources created in the OnCreateDevice callback
// should be released here, which generally includes all D3DPOOL_MANAGED resources.
//--------------------------------------------------------------------------------------
procedure OnDestroyDevice; stdcall;
begin
g_DialogResourceManager.OnDestroyDevice;
g_SettingsDlg.OnDestroyDevice;
SAFE_RELEASE(g_pEffect);
SAFE_RELEASE(g_pFont);
if Assigned(g_MeshLoader) then g_MeshLoader.DestroyMesh;
end;
//--------------------------------------------------------------------------------------
// Saves the mesh to X-file
//--------------------------------------------------------------------------------------
procedure SaveMeshToXFile;
var
hr: HRESULT;
numMaterials: LongWord;
pMaterials: PD3DXMaterialArray;
pStrTexture: PChar;
i: Integer;
pMat: PMaterial;
strBuf: array[0..MAX_PATH-1] of WideChar;
begin
// Fill out D3DXMATERIAL structures
numMaterials := g_MeshLoader.NumMaterials;
GetMem(pMaterials, SizeOf(TD3DXMaterial)*numMaterials);
GetMem(pStrTexture, SizeOf(Char)*MAX_PATH*numMaterials);
try
for i := 0 to g_MeshLoader.NumMaterials - 1 do
begin
pMat := g_MeshLoader.Material[i];
if (pMat <> nil) then
begin
pMaterials[i].MatD3D.Ambient.r := pMat.vAmbient.x;
pMaterials[i].MatD3D.Ambient.g := pMat.vAmbient.y;
pMaterials[i].MatD3D.Ambient.b := pMat.vAmbient.z;
pMaterials[i].MatD3D.Ambient.a := pMat.fAlpha;
pMaterials[i].MatD3D.Diffuse.r := pMat.vDiffuse.x;
pMaterials[i].MatD3D.Diffuse.g := pMat.vDiffuse.y;
pMaterials[i].MatD3D.Diffuse.b := pMat.vDiffuse.z;
pMaterials[i].MatD3D.Diffuse.a := pMat.fAlpha;
pMaterials[i].MatD3D.Specular.r := pMat.vSpecular.x;
pMaterials[i].MatD3D.Specular.g := pMat.vSpecular.y;
pMaterials[i].MatD3D.Specular.b := pMat.vSpecular.z;
pMaterials[i].MatD3D.Specular.a := pMat.fAlpha;
pMaterials[i].MatD3D.Emissive.r := 0;
pMaterials[i].MatD3D.Emissive.g := 0;
pMaterials[i].MatD3D.Emissive.b := 0;
pMaterials[i].MatD3D.Emissive.a := 0;
pMaterials[i].MatD3D.Power := pMat.nShininess;
WideCharToMultiByte(CP_ACP, 0, pMat.strTexture, -1, (pStrTexture + i*MAX_PATH), MAX_PATH, nil, nil);
pMaterials[i].pTextureFilename := (pStrTexture + i*MAX_PATH);
end;
end;
// Write to file in same directory where the .obj file was found
StringCchFormat(strBuf, MAX_PATH-1, '%s\%s', [g_MeshLoader.MediaDirectory, 'MeshFromOBJ.x']);
hr := D3DXSaveMeshToXW(strBuf, g_MeshLoader.Mesh, nil,
@pMaterials[0], nil, numMaterials,
D3DXF_FILEFORMAT_TEXT);
if SUCCEEDED(hr) then
begin
StringCchFormat(g_strFileSaveMessage, MAX_PATH-1, 'Created %s', [strBuf]);
end else
begin
DXTRACE_ERR('SaveMeshToXFile.D3DXSaveMeshToX', hr);
StringCchFormat(g_strFileSaveMessage, MAX_PATH-1, 'Error creating %s, check debug output', [strBuf]);
end;
finally
FreeMem(pMaterials);
FreeMem(pStrTexture);
end;
end;
procedure CreateCustomDXUTobjects;
begin
g_DialogResourceManager:= CDXUTDialogResourceManager.Create; // manager for shared resources of dialogs
g_SettingsDlg:= CD3DSettingsDlg.Create; // Device settings dialog
g_Camera:= CModelViewerCamera.Create; // A model viewing camera
g_HUD:= CDXUTDialog.Create; // manages the 3D UI
g_SampleUI:= CDXUTDialog.Create; // dialog for sample specific controls
g_MeshLoader:= CMeshLoader.Create; // Loads a mesh from an .obj file
end;
procedure DestroyCustomDXUTobjects;
begin
FreeAndNil(g_DialogResourceManager);
FreeAndNil(g_SettingsDlg);
FreeAndNil(g_MeshLoader);
FreeAndNil(g_Camera);
FreeAndNil(g_HUD);
FreeAndNil(g_SampleUI);
end;
end.
|
unit Dmitry.Controls.WebLinkList;
interface
uses
Generics.Collections,
System.Types,
System.SysUtils,
System.Classes,
System.Math,
Winapi.Messages,
Winapi.Windows,
Vcl.Controls,
Vcl.StdCtrls,
Vcl.Forms,
Vcl.Graphics,
Vcl.Themes,
Dmitry.Memory,
Dmitry.Controls.WebLink;
type
TWebLinkList = class(TScrollBox)
strict private
class constructor Create;
private
{ Private declarations }
FLinks: TList;
FBreakLines: TList;
FVerticalIncrement: Integer;
FHorizontalIncrement: Integer;
FLineHeight: Integer;
FPaddingTop: Integer;
FPaddingLeft: Integer;
FIsRealligning: Boolean;
FTagEx: string;
FHorCenter: Boolean;
procedure SetVerticalIncrement(const Value: Integer);
procedure SetHorizontalIncrement(const Value: Integer);
procedure SetLineHeight(const Value: Integer);
procedure SetPaddingTop(const Value: Integer);
procedure SetPaddingLeft(const Value: Integer);
procedure WMSize(var Message: TWMSize); message WM_SIZE;
protected
{ Protected declarations }
procedure WndProc(var Message: TMessage); override;
procedure Erased(var Message: TWMEraseBkgnd); message WM_ERASEBKGND;
procedure CMEnabledChanged(var Message: TMessage); message CM_ENABLEDCHANGED;
public
{ Public declarations }
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure Clear;
function AddLink(BreakLine: Boolean = False): TWebLink;
procedure AddControl(Control: TWinControl; BreakLine: Boolean = False);
procedure ReallignList;
procedure AutoHeight(MaxHeight: Integer);
procedure PerformMouseWheel(WheelDelta: NativeUInt; var Handled: Boolean);
function HasHandle(WHandle: THandle): Boolean;
published
{ Published declarations }
property VerticalIncrement: Integer read FVerticalIncrement write SetVerticalIncrement;
property HorizontalIncrement: Integer read FHorizontalIncrement write SetHorizontalIncrement;
property LineHeight: Integer read FLineHeight write SetLineHeight;
property PaddingTop: Integer read FPaddingTop write SetPaddingTop;
property PaddingLeft: Integer read FPaddingLeft write SetPaddingLeft;
property HorCenter: Boolean read FHorCenter write FHorCenter default False;
property TagEx: string read FTagEx write FTagEx;
end;
TTWebLinkListStyleHook = class(TScrollingStyleHook)
protected
procedure WMEraseBkgnd(var Message: TWMEraseBkgnd); message WM_ERASEBKGND;
procedure PaintBackground(Canvas: TCanvas); override;
public
constructor Create(AControl: TWinControl); override;
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Dm', [TWebLinkList]);
end;
{ TWebLinkList }
procedure TWebLinkList.AddControl(Control: TWinControl; BreakLine: Boolean = False);
begin
FLinks.Add(Control);
if BreakLine then
FBreakLines.Add(Control);
end;
function TWebLinkList.AddLink(BreakLine: Boolean = False): TWebLink;
begin
Result := TWebLink.Create(Self);
Result.Parent := Self;
Result.ParentColor := True;
FLinks.Add(Result);
if BreakLine then
FBreakLines.Add(Result);
end;
procedure TWebLinkList.AutoHeight(MaxHeight: Integer);
begin
DisableAutoRange;
try
Height := Min(MaxHeight, VertScrollBar.Range);
finally
EnableAutoRange;
end;
end;
procedure TWebLinkList.Clear;
var
I: Integer;
TempList: TList;
begin
TempList := TList.Create;
try
TempList.Assign(FLinks);
FLinks.Clear;
for I := 0 to TempList.Count - 1 do
TObject(TempList[I]).Free;
FBreakLines.Clear;
finally
F(TempList);
end;
end;
procedure TWebLinkList.CMEnabledChanged(var Message: TMessage);
var
I: Integer;
WL: TWinControl;
begin
for I := 0 to FLinks.Count - 1 do
begin
WL := TWinControl(FLinks[I]);
WL.Enabled := Enabled;
end;
end;
class constructor TWebLinkList.Create;
begin
if Assigned(TStyleManager.Engine) then
TStyleManager.Engine.RegisterStyleHook(TWebLinkList, TTWebLinkListStyleHook);
end;
procedure TWebLinkList.WndProc(var Message: TMessage);
begin
if (Message.Msg = WM_MOUSEWHEEL) then
begin
if Message.wParam > 0 then
Self.ScrollBy(0, -2)
else
Self.ScrollBy(0, 2);
Message.Msg := 0;
end;
inherited;
end;
constructor TWebLinkList.Create(AOwner: TComponent);
begin
inherited;
ControlStyle := ControlStyle - [csDoubleClicks] + [csParentBackground];
FIsRealligning := False;
ParentBackground := False;
FLinks := TList.Create;
FBreakLines := TList.Create;
FHorCenter := False;
end;
destructor TWebLinkList.Destroy;
begin
Clear;
F(FLinks);
F(FBreakLines);
inherited;
end;
procedure TWebLinkList.Erased(var Message: TWMEraseBkgnd);
begin
if StyleServices.IsSystemStyle then
inherited
else
Message.Result := 1;
end;
function TWebLinkList.HasHandle(WHandle: THandle): Boolean;
var
I: Integer;
begin
Result := WHandle = Handle;
if not Result then
for I := 0 to FLinks.Count - 1 do
Result := Result or (TWinControl(FLinks[I]).Handle = WHandle);
end;
procedure TWebLinkList.PerformMouseWheel(WheelDelta: NativeUInt; var Handled: Boolean);
var
Msg: Cardinal;
Code: Cardinal;
I, N: Integer;
WHandle: THandle;
begin
WHandle := WindowFromPoint(Mouse.Cursorpos);
if HasHandle(WHandle) then
begin
Handled := True;
Msg := WM_VSCROLL;
if NativeInt(WheelDelta) < 0 then
Code := SB_LINEDOWN
else
Code := SB_LINEUP;
N := Mouse.WheelScrollLines;
for I := 1 to N do
Self.Perform(Msg, Code, 0);
Self.Perform(Msg, SB_ENDSCROLL, 0);
end;
end;
procedure TWebLinkList.ReallignList;
var
ClientW: Integer;
LineHeights, LineWidths: TList<Integer>;
procedure ReallignControls(CalculateSize: Boolean);
var
I, LineIndex, LineHeight, LineStart: Integer;
OldWL, WL: TWinControl;
X, Y: Integer;
begin
Y := PaddingTop;
X := PaddingLeft;
OldWL := nil;
LineIndex := 0;
LineHeight := 0;
for I := 0 to FLinks.Count - 1 do
begin
WL := TWinControl(FLinks[I]);
if CalculateSize and (WL is TWebLink) then
TWebLink(WL).LoadImage;
if (I <> 0) and ((X + WL.Width + HorizontalIncrement > ClientW) or (FBreakLines.IndexOf(OldWL) > -1)) then
begin
//calculations
LineHeights.Add(LineHeight);
LineWidths.Add(X);
X := PaddingLeft;
LineHeight := 0;
if not (OldWL is TStaticText) then
LineHeight := LineHeight + VerticalIncrement;
if OldWL <> nil then
LineHeight := LineHeight + OldWL.Height;
Y := Y + LineHeight;
Inc(LineIndex);
end;
LineStart := 0;
if FHorCenter and not CalculateSize and (LineIndex < LineWidths.Count) then
LineStart := ClientW div 2 - LineWidths[LineIndex] div 2;
if not CalculateSize then
WL.SetBounds(X + LineStart, Y, WL.Width, WL.Height);
OldWL := WL;
X := X + WL.Width + HorizontalIncrement;
end;
LineHeights.Add(LineHeight);
LineWidths.Add(X);
end;
begin
if FIsRealligning then
Exit;
if (csReading in ComponentState) then
Exit;
if (csLoading in ComponentState) then
Exit;
FIsRealligning := True;
DisableAlign;
try
VertScrollBar.Position := 0;
ClientW := ClientWidth;
if GetWindowLong(Handle, GWL_STYLE) and WS_VSCROLL <> 0 then
ClientW := ClientW - GetSystemMetrics(SM_CXVSCROLL);
LineHeights := TList<Integer>.Create;
LineWidths := TList<Integer>.Create;
try
ReallignControls(True);
ReallignControls(False);
finally
F(LineHeights);
F(LineWidths);
end;
finally
FIsRealligning := False;
EnableAlign;
end;
end;
procedure TWebLinkList.SetHorizontalIncrement(const Value: Integer);
begin
FHorizontalIncrement := Value;
ReallignList;
end;
procedure TWebLinkList.SetLineHeight(const Value: Integer);
begin
FLineHeight := Value;
ReallignList;
end;
procedure TWebLinkList.SetPaddingLeft(const Value: Integer);
begin
FPaddingLeft := Value;
ReallignList;
end;
procedure TWebLinkList.SetPaddingTop(const Value: Integer);
begin
FPaddingTop := Value;
ReallignList;
end;
procedure TWebLinkList.SetVerticalIncrement(const Value: Integer);
begin
FVerticalIncrement := Value;
ReallignList;
end;
procedure TWebLinkList.WMSize(var Message: TWMSize);
begin
ReallignList;
end;
{ TTWebLinkListStyleHook }
constructor TTWebLinkListStyleHook.Create(AControl: TWinControl);
begin
inherited;
DoubleBuffered := True;
OverridePaint := True;
OverrideEraseBkgnd := True;
end;
procedure TTWebLinkListStyleHook.PaintBackground(Canvas: TCanvas);
begin
if StyleServices.Available then
StyleServices.DrawParentBackground(Handle, Canvas.Handle, nil, False);
end;
procedure TTWebLinkListStyleHook.WMEraseBkgnd(var Message: TWMEraseBkgnd);
begin
if StyleServices.Available then
begin
StyleServices.DrawParentBackground(Handle, Message.DC, nil, False);
Message.Result := 1;
Handled := True;
end else
inherited;
end;
end.
|
unit Odontologia.Controlador.Ciudad;
interface
uses
Data.DB,
System.SysUtils,
System.Generics.Collections,
Odontologia.Controlador.Ciudad.Interfaces,
Odontologia.Controlador.Departamento,
Odontologia.Controlador.Departamento.Interfaces,
Odontologia.Modelo,
Odontologia.Modelo.Entidades.Ciudad,
Odontologia.Modelo.Ciudad.Interfaces;
type
TControllerCiudad = class(TInterfacedObject, iControllerCiudad)
private
FModel: iModelCiudad;
FDataSource: TDataSource;
FDepartamento: iControllerDepartamento;
procedure DataChange (sender : tobject ; field : Tfield) ;
public
constructor Create;
destructor Destroy; override;
class function New : iControllerCiudad;
function DataSource(aDataSource: TDataSource): iControllerCiudad;
function Buscar : iControllerCiudad; overload;
function Buscar (aDepartamento : String) : iControllerCiudad; overload;
function Insertar : iControllerCiudad;
function Modificar : iControllerCiudad;
function Eliminar : iControllerCiudad;
function Ciudad : TDCIUDAD;
function Departamento : iControllerDepartamento;
end;
implementation
{ TControllerCiudad }
function TControllerCiudad.Buscar: iControllerCiudad;
begin
Result := Self;
FDataSource.dataset.DisableControls;
FModel.DAO.SQL.Fields('DCIUDAD.CIU_CODIGO AS CODIGO,')
.Fields('DCIUDAD.CIU_NOMBRE AS NOMBRE,')
.Fields('DCIUDAD.CIU_COD_DEPARTAMENTO AS COD_DPTO,')
.Fields('DDEPARTAMENTO.DEP_NOMBRE AS DEPARTAMENTO')
.Join('INNER JOIN DDEPARTAMENTO ON DDEPARTAMENTO.DEP_CODIGO = DCIUDAD.CIU_COD_DEPARTAMENTO ')
.Where('')
.OrderBy('NOMBRE')
.&End.Find;
FDataSource.dataset.EnableControls;
FDataSource.dataset.FieldByName('COD_DPTO').Visible := false;
FDataSource.dataset.FieldByName('NOMBRE').DisplayWidth :=50;
end;
function TControllerCiudad.Buscar(aDepartamento: String): iControllerCiudad;
begin
Result := Self;
FDataSource.dataset.DisableControls;
FModel.DAO.SQL.Fields('DCIUDAD.CIU_CODIGO AS CODIGO,')
.Fields('DCIUDAD.CIU_NOMBRE AS NOMBRE,')
.Fields('DCIUDAD.CIU_COD_DEPARTAMENTO AS COD_DPTO,')
.Fields('DDEPARTAMENTO.DEP_NOMBRE AS DEPARTAMENTO')
.Join('INNER JOIN DDEPARTAMENTO ON DDEPARTAMENTO.DEP_CODIGO = DCIUDAD.CIU_COD_DEPARTAMENTO ')
.Where('CIU_NOMBRE CONTAINING ' +QuotedStr(aDepartamento) + '')
.OrderBy('NOMBRE')
.&End.Find;
FDataSource.dataset.EnableControls;
FDataSource.dataset.FieldByName('COD_DPTO').Visible := false;
FDataSource.dataset.FieldByName('NOMBRE').DisplayWidth :=50;
end;
constructor TControllerCiudad.Create;
begin
FModel := TModel.New.Ciudad;
FDepartamento := TControllerDepartamento.New;
end;
procedure TControllerCiudad.DataChange(sender: tobject; field: Tfield);
begin
end;
function TControllerCiudad.DataSource(aDataSource: TDataSource) : iControllerCiudad;
begin
Result := Self;
FDataSource := aDataSource;
FModel.DataSource(FDataSource);
FDataSource.OnDataChange := DataChange;
end;
destructor TControllerCiudad.Destroy;
begin
inherited;
end;
function TControllerCiudad.Eliminar: iControllerCiudad;
begin
Result := Self;
FModel.DAO.Delete(FModel.Entidad);
end;
function TControllerCiudad.Ciudad: TDCIUDAD;
begin
Result := FModel.Entidad;
end;
function TControllerCiudad.Insertar: iControllerCiudad;
begin
Result := Self;
FModel.DAO.Insert(FModel.Entidad);
end;
function TControllerCiudad.Departamento: iControllerDepartamento;
begin
Result := FDepartamento;
end;
function TControllerCiudad.Modificar: iControllerCiudad;
begin
Result := Self;
FModel.DAO.Update(FModel.Entidad);
end;
class function TControllerCiudad.New: iControllerCiudad;
begin
Result := Self.Create;
end;
end.
|
unit uDBRepository;
interface
uses
System.SysUtils,
Generics.Collections,
Data.DB,
uConstants,
uDBClasses,
uMemory;
type
TSimpleEntity = class
strict private
DS: TDataSet;
protected
FUC: TUpdateCommand;
function GetUC: TUpdateCommand;
procedure InitUC; virtual; abstract;
function GetTableName: string; virtual; abstract;
procedure ReadFromQuery(Query: TSqlCommand); virtual;
function ReadInteger(FieldName: string; Default: Integer = 0): Integer;
function ReadString(FieldName: string; Default: string = ''): string;
property UC: TUpdateCommand read GetUC;
property TableName: string read GetTableName;
public
constructor Create; virtual;
destructor Destroy; override;
procedure SaveChanges;
end;
ItemQueries = class;
TJoinTableSet<T1, T2: TSimpleEntity> = class;
TDBTable<T: TSimpleEntity> = class;
TDBQuery<T: TSimpleEntity, constructor> = class;
TDBItem = class(TSimpleEntity)
strict private
FId: Integer;
FLinks: string;
procedure SetLinks(const Value: string);
protected
procedure InitUC; override;
function GetTableName: string; override;
procedure ReadFromQuery(Query: TSqlCommand); override;
public
property Id: Integer read FId;
property Links: string read FLinks write SetLinks;
end;
TDBGroupItem = class(TSimpleEntity)
end;
TDBFields<T: TSimpleEntity> = class;
DBItemFields = class sealed
public
const Id = 'Id';
const Links = 'Links';
const GroupId = 'GroupId';
end;
DBGroupFields = class sealed
public
const GroupId = 'GroupId';
end;
TDBRepository = class
strict private
FFields: TDBFields<TDBItem>;
FObjects: TList<TObject>;
protected
procedure AddObject(QueryObject: TObject);
property Fields: TDBFields<TDBItem> read FFields;
public
constructor Create; virtual;
destructor Destroy; override;
end;
TDBQueries<T: TSimpleEntity> = class
strict private
FSelectCommand: TSelectCommand;
FTable: TDBTable<T>;
protected
property Table: TDBTable<T> read FTable;
property SelectCommand: TSelectCommand read FSelectCommand write FSelectCommand;
public
constructor Create(Table: TDBTable<T>); virtual;
destructor Destroy; override;
end;
TDBTable<T: TSimpleEntity> = class
strict private
FFields: TDBFields<T>;
FQueries: TDBQueries<TDBItem>;
protected
property Fields: TDBFields<T> read FFields;
public
function Join<T1: TSimpleEntity>(Table: TDBTable<T1>): TJoinTableSet<T, T1>;
function SelectItem(): ItemQueries;
constructor Create(Fields: TDBFields<T>);
destructor Destroy; override;
end;
TJoinTable<T: TSimpleEntity> = class(TDBTable<T>)
end;
TJoinTableOn<T1, T2: TSimpleEntity> = class
public
function Eq(FiledName: string): TJoinTable<T1>;
end;
TJoinTableSet<T1, T2: TSimpleEntity> = class
public
function Onn(FiledName: string): TJoinTableOn<T1, T2>;
end;
TDBFields<T: TSimpleEntity> = class
strict private
FRepository: TDBRepository;
FFields: TList<string>;
protected
property Repository: TDBRepository read FRepository;
property Fields: TList<string> read FFields;
public
constructor Create(Repository: TDBRepository);
destructor Destroy; override;
function Add(FieldName: string): TDBFields<T>;
function SetOf(Fields: array of string): TDBFields<T>;
function Table(): TDBTable<T>;
end;
TDBItemRepository = class(TDBRepository)
private
public
function WithKey: TDBFields<TDBItem>;
function TextFields: TDBFields<TDBItem>;
function AllFields: TDBFields<TDBItem>;
end;
TDBGroupsRepository = class(TDBRepository)
public
function AllFields: TDBFields<TDBGroupItem>;
end;
TDBTableQuery<T: TSimpleEntity> = class
private
FTable: TDBTable<T>;
protected
property Table: TDBTable<T> read FTable;
public
constructor Create(Table: TDBTable<T>);
end;
TItemFetchCallBack<T> = reference to procedure(Item: T);
TDBQuery<T: TSimpleEntity, constructor> = class
private
FQueries: TDBQueries<TDBItem>;
function GetSelectCommand: TSelectCommand;
protected
property Queries: TDBQueries<TDBItem> read FQueries;
property SC: TSelectCommand read GetSelectCommand;
public
constructor Create(Queries: TDBQueries<TDBItem>);
destructor Destroy; override;
function OrderBy(FieldName: string): TDBQuery<T>;
function OrderByDesc(FieldName: string): TDBQuery<T>;
function FirstOrDefault(): T;
function ToList(): TList<T>;
procedure Fetch(OnItem: TItemFetchCallBack<T>);
end;
ItemQueries = class(TDBQueries<TDBItem>)
public
constructor Create(Table: TDBTable<TDBItem>); override;
function ById(Id: Integer): TDBQuery<TDBItem>;
destructor Destroy; override;
end;
implementation
{ TDBitemRepository }
function TDBItemRepository.AllFields: TDBFields<TDBItem>;
begin
end;
function TDBItemRepository.TextFields: TDBFields<TDBItem>;
begin
end;
function TDBItemRepository.WithKey: TDBFields<TDBItem>;
begin
Result := Fields.SetOf([DBItemFields.Id]);
end;
{ TDBTable<T> }
constructor TDBTable<T>.Create(Fields: TDBFields<T>);
begin
FFields := Fields;
FQueries := nil;
FFields.Repository.AddObject(Self);
end;
destructor TDBTable<T>.Destroy;
begin
F(FQueries);
inherited;
end;
function TDBTable<T>.Join<T1>(Table: TDBTable<T1>): TJoinTableSet<T, T1>;
begin
end;
function TDBTable<T>.SelectItem(): ItemQueries;
begin
Result := ItemQueries.Create(TDBTable<TDBItem>(Self));
end;
{ TDBFields<T> }
function TDBFields<T>.Add(FieldName: string): TDBFields<T>;
begin
if FFields.Contains(FieldName) then
raise Exception.Create('Field {0} is already in list!');
FFields.Add(FieldName);
Result := Self;
end;
constructor TDBFields<T>.Create(Repository: TDBRepository);
begin
FRepository := Repository;
FFields := TList<string>.Create;
end;
destructor TDBFields<T>.Destroy;
begin
F(FFields);
inherited;
end;
function TDBFields<T>.SetOf(Fields: array of string): TDBFields<T>;
var
I: Integer;
begin
Result := Self;
for I := 0 to Length(Fields) - 1 do
Add(Fields[I]);
end;
function TDBFields<T>.Table: TDBTable<T>;
begin
Result := TDBTable<T>.Create(Self);
end;
{ TDBGroupsRepository }
function TDBGroupsRepository.AllFields: TDBFields<TDBGroupItem>;
begin
end;
{ TJoinTableSet<T1, T2> }
function TJoinTableSet<T1, T2>.Onn(FiledName: string): TJoinTableOn<T1, T2>;
begin
end;
{ TJoinTableOn<T1, T2> }
function TJoinTableOn<T1, T2>.Eq(FiledName: string): TJoinTable<T1>;
begin
end;
{ ItemQueries }
function ItemQueries.ById(Id: Integer): TDBQuery<TDBItem>;
begin
SelectCommand.AddWhereParameter(TIntegerParameter.Create(DBItemFields.Id, Id));
Result := TDBQuery<TDBItem>.Create(Self);
end;
constructor ItemQueries.Create(Table: TDBTable<TDBItem>);
begin
inherited Create(Table);
//SelectCommand := TSelectCommand.Create(ImageTable);
end;
destructor ItemQueries.Destroy;
begin
inherited;
end;
{ TDBQuery<T> }
constructor TDBQuery<T>.Create(Queries: TDBQueries<TDBItem>);
begin
FQueries := Queries;
Queries.Table.Fields.Repository.AddObject(Self);
end;
destructor TDBQuery<T>.Destroy;
begin
inherited;
end;
procedure TDBQuery<T>.Fetch(OnItem: TItemFetchCallBack<T>);
begin
end;
function TDBQuery<T>.FirstOrDefault: T;
var
I: Integer;
begin
Result := nil;
for I := 0 to Queries.Table.Fields.Fields.Count - 1 do
SC.AddParameter(TStringParameter.Create(Queries.Table.Fields.Fields[I]));
SC.TopRecords := 1;
if SC.Execute > 0 then
begin
Result := T.Create;
Result.ReadFromQuery(SC);
end;
end;
function TDBQuery<T>.GetSelectCommand: TSelectCommand;
begin
Result := Queries.SelectCommand;
end;
function TDBQuery<T>.OrderBy(FieldName: string): TDBQuery<T>;
begin
end;
function TDBQuery<T>.OrderByDesc(FieldName: string): TDBQuery<T>;
begin
end;
function TDBQuery<T>.ToList: TList<T>;
begin
end;
{ TDBRepository }
procedure TDBRepository.AddObject(QueryObject: TObject);
begin
FObjects.Add(QueryObject);
end;
constructor TDBRepository.Create;
begin
FFields := TDBFields<TDBItem>.Create(Self);
FObjects := TList<TObject>.Create;
end;
destructor TDBRepository.Destroy;
begin
F(FFields);
FreeList(FObjects);
inherited;
end;
{ TDBTableQuery<T> }
constructor TDBTableQuery<T>.Create(Table: TDBTable<T>);
begin
FTable := Table;
end;
{ TDBQueries<T> }
constructor TDBQueries<T>.Create(Table: TDBTable<T>);
begin
FTable := Table;
Table.Fields.Repository.AddObject(Self);
end;
destructor TDBQueries<T>.Destroy;
begin
F(FSelectCommand);
inherited;
end;
{ TSimpleEntity }
constructor TSimpleEntity.Create;
begin
FUC := nil;
end;
destructor TSimpleEntity.Destroy;
begin
F(FUC);
inherited;
end;
function TSimpleEntity.GetUC: TUpdateCommand;
begin
if FUC = nil then
begin
//FUC := TUpdateCommand.Create(TableName);
InitUC;
end;
Result := FUC;
end;
procedure TSimpleEntity.ReadFromQuery(Query: TSqlCommand);
begin
DS := Query.DS;
end;
function TSimpleEntity.ReadInteger(FieldName: string; Default: Integer): Integer;
var
F: TField;
begin
F := DS.FindField(FieldName);
if F = nil then
Exit(Default);
Result := F.AsInteger;
end;
function TSimpleEntity.ReadString(FieldName, Default: string): string;
var
F: TField;
begin
F := DS.FindField(FieldName);
if F = nil then
Exit(Default);
Result := F.AsString;
end;
procedure TSimpleEntity.SaveChanges;
begin
if UC <> nil then
UC.Execute;
end;
{ TDBItem }
function TDBItem.GetTableName: string;
begin
Result := ImageTable;
end;
procedure TDBItem.InitUC;
begin
UC.AddWhereParameter(TIntegerParameter.Create(DBItemFields.Id, Id));
end;
procedure TDBItem.ReadFromQuery(Query: TSqlCommand);
begin
inherited;
FId := ReadInteger('Id');
FLinks := ReadString('Links');
end;
procedure TDBItem.SetLinks(const Value: string);
begin
FLinks := Value;
UC.AddParameter(TStringParameter.Create(DBItemFields.Links, Value));
end;
end.
|
unit VendaService;
interface
uses BasicService, System.Generics.Collections, System.SysUtils, CartaoVO,
Vcl.Forms, Vcl.ExtCtrls, Vcl.Controls, PanelHelper, Datasnap.DBClient,
PessoaVO, VendaVO, EsperaVO, System.Math, Vcl.StdCtrls;
type
TVendaService = class(TBasicService)
class procedure getCartao(Scrol: TForm);
class procedure getPessoa(Campo,Valor,Conta: string; DataSet: TClientDataSet);
class function VendaInserir(Venda: TVendaVO): Boolean;
class function VendaEmEsperaInserir(Espera: TEsperaVO): Boolean;
class procedure getVendaEmEspera(Dataset: TClientDataSet);
class procedure getVendaEmEsperaById(idOfEspera: Integer; Scrol: TScrollBox; Dataset: TClientDataSet);
class function VendaToNFCE(idOfVenda: Integer): Boolean;
class function ReimprimirNF(idOfVenda: Integer): Boolean;
class function AdicionarPessoaAVenda(idOfVenda, idOfCliente: Integer): Boolean;
class procedure SetValorFiscal(Edt: TEdit);
end;
implementation
{ TVendaService }
uses VendaRepository, Biblioteca;
class function TVendaService.AdicionarPessoaAVenda(idOfVenda,
idOfCliente: Integer): Boolean;
begin
try
Result:= True;
BeginTransaction;
TVendaRepository.AdicionarPessoaAVenda(idOfVenda,idOfCliente);
Commit;
except
Rollback;
Result:= False;
end;
end;
class procedure TVendaService.getCartao(Scrol: TForm);
var
Lst: TList<TCartaoVO>;
Panel: TPanel;
i: Integer;
begin
Lst:= TVendaRepository.getCartao;
if Assigned(Lst) then
begin
for i:= 0 to Pred(Lst.Count) do
begin
Panel:= TPanel.Create(Scrol);
Panel.Parent:= Scrol;
Panel.Align:= alNone;
Panel.Top:= IfThen(I < 6,(96 * (i)),(96 * (i - 6)));
Panel.Left:= IfThen(I < 6,2,347);
Panel.Height:= 96;
Panel.Width:= 345;
Panel.BevelInner:= bvSpace;
Panel.BevelOuter:= bvSpace;
Panel.BevelKind:= bkNone;
Panel.DragMode:= dmManual;
Panel.Name:= 'C' + IntToStr(Lst.Items[i].Id);
Panel.Caption:= EmptyStr;
Panel.OnClick:= Scrol.OnClick;
Panel.OnDblClick:= Scrol.OnDblClick;
// Panel.Cartao(Lst.Items[i]);
end;
FreeAndNil(Lst);
end;
end;
class procedure TVendaService.getPessoa(Campo, Valor, Conta: string;
DataSet: TClientDataSet);
var
Lst: TList<TPessoaVO>;
I: Integer;
begin
if not (DataSet.Active) then
DataSet.CreateDataSet;
DataSet.DisableControls;
DataSet.EmptyDataSet;
Lst:= TVendaRepository.getPessoa(Campo,Valor);
if Assigned(Lst) then
begin
for I := 0 to Pred(Lst.Count) do
begin
if ((Lst.Items[i].ContaCorrente = 'S') and (Conta = 'S')) or ((Conta = 'N') and (Lst.Items[i].Pessoa[1] in['C','F']))then
begin
DataSet.Append;
DataSet.FieldByName('ID').AsInteger:= Lst.Items[i].Id;
DataSet.FieldByName('PESSOA').AsString:= Lst.Items[i].Pessoa;
DataSet.FieldByName('NOME').AsString:= Lst.Items[i].Nome;
DataSet.FieldByName('DOC').AsString:= Lst.Items[i].Doc;
DataSet.FieldByName('LIMITE').AsFloat:= Lst.Items[i].Limite;
DataSet.FieldByName('SALDO').AsFloat:= Lst.Items[i].Saldo;
DataSet.FieldByName('LIBERAR').AsInteger:= IfThen(((Lst.Items[i].Saldo > 0) or (Abs(Lst.Items[i].Saldo) < Lst.Items[i].Limite)),1,0);
DataSet.Post;
end;
Lst.Items[i].Free;
end;
DataSet.First;
FreeAndNil(Lst);
end;
DataSet.EnableControls;
end;
class procedure TVendaService.getVendaEmEspera(Dataset: TClientDataSet);
var
lst: TList<TEsperaVO>;
I: Integer;
begin
if not (Dataset.Active) then
Dataset.CreateDataSet;
Dataset.EmptyDataSet;
lst:= TVendaRepository.getVendaEmEspera;
if Assigned(lst) then
begin
for I := 0 to Pred(lst.Count) do
begin
Dataset.Append;
Dataset.FieldByName('ID').AsInteger:= lst.Items[i].Id;
Dataset.FieldByName('ORDEN').AsInteger:= i + 1;
Dataset.FieldByName('LANCAMENTO').AsDateTime:= lst.Items[i].Lancamento;
Dataset.Post;
lst.Items[i].Free;
end;
FreeAndNil(lst);
end;
end;
class procedure TVendaService.getVendaEmEsperaById(idOfEspera: Integer;
Scrol: TScrollBox; Dataset: TClientDataSet);
var
Espera: TEsperaVO;
Panel: TPanel;
I: Integer;
begin
if not (Dataset.Active) then
Dataset.CreateDataSet;
Dataset.EmptyDataSet;
Espera:= TVendaRepository.getVendaEmEsperaById(idOfEspera);
if Assigned(Espera.Itens) then
begin
for I := 0 to Pred(Espera.Itens.Count) do
begin
Panel:= TPanel.Create(Scrol);
Panel.Parent:= Scrol;
Panel.Align:= alTop;
Panel.Height:= 96;
Panel.BevelInner:= bvSpace;
Panel.BevelOuter:= bvSpace;
Panel.BevelKind:= bkNone;
Panel.Name:= 'V' + Espera.Itens.Items[i].Codigo;
Panel.Caption:= EmptyStr;
Panel.OnClick:= Scrol.OnClick;
// Panel.ItemEmEspera(Espera.Itens.Items[i],Dataset);
end;
Espera.Atendido:= 'S';
TVendaRepository.VendaEmEspraAlterar(Espera);
FreeAndNil(Espera);
end;
end;
class function TVendaService.ReimprimirNF(idOfVenda: Integer): Boolean;
begin
try
Result:= True;
BeginTransaction;
TVendaRepository.ReimprimirNF(idOfVenda);
Commit;
except
Rollback;
Result:= False;
end;
end;
class procedure TVendaService.SetValorFiscal(Edt: TEdit);
begin
Edt.Text:= FormataFloat('V',TVendaRepository.getValorFiscal);
end;
class function TVendaService.VendaEmEsperaInserir(Espera: TEsperaVO): Boolean;
begin
Result:= True;
BeginTransaction;
try
TVendaRepository.VendaEmEsperaInserir(Espera);
TVendaRepository.VendaEmEsperaItensInserir(Espera.Id,Espera.Itens);
Commit;
except
Rollback;
Result:= False;
end;
end;
class function TVendaService.VendaInserir(Venda: TVendaVO): Boolean;
begin
Result:= True;
BeginTransaction;
try
TVendaRepository.VendaInserir(Venda);
TVendaRepository.VendaInserirItens(Venda.Id,Venda.Itens);
TVendaRepository.VendaInserirRecebimentos(Venda.Id,Venda.Recebimentos);
if Assigned(Venda.ContaReceber) then
TVendaRepository.VendaInserirContaReceber(Venda.Id,Venda.ContaReceber);
if Assigned(Venda.CartaoRecebimentos) then
TVendaRepository.VendaInserirCartaoRecebimentos(Venda.Id,Venda.CartaoRecebimentos);
TVendaRepository.VendaItensToDesconto(Venda.Id);
Commit;
except
Rollback;
Result:= False;
end;
end;
class function TVendaService.VendaToNFCE(idOfVenda: Integer): Boolean;
begin
try
Result:= True;
BeginTransaction;
TVendaRepository.VendaToNFCE(idOfVenda);
Commit;
// try
// FLoadNF:= TFLoadNF.Create(nil);
// FLoadNF.idOfVenda:= idOfVenda;
// FLoadNF.ShowModal;
// finally
// FreeAndNil(FLoadNF);
// end;
except
Rollback;
Result:= False;
end;
end;
end.
|
unit uMaths;
interface
uses uPoint;
{
Returns random num of [min;max)
}
function getRand(min, max: real): real;
{
Returns random num of range
}
function getRandPoint(minX, maxX, minY, maxY: real): Point;
{
Returns angle between line specified by 2 points and OX
}
function getAngleOf2P(x1, y1, x2, y2: real): real;
implementation
function getRand(min, max: real): real;
begin
getRand := random * (max - min) + min;
end;
function getRandPoint(minX, maxX, minY, maxY: real): Point;
var p: Point;
begin
p := Point.Create(getRand(minX, maxX), getRand(minY, maxY));
p.x := trunc(p.x * 100) / 100.0;
p.y := trunc(p.y * 100) / 100.0;
getRandPoint := p;
end;
function getAngleOf2P(x1, y1, x2, y2: real): real;
var
dx, dy, angle, corrector: real;
begin
dx := x2 - x1;
dy := y2 - y1;
angle := 0;
corrector := 0;
if dx = 0 then
begin if dy <> 0 then corrector := PI / 2; end
else angle := arctan(dy / dx);
if dx < 0 then corrector := PI;
if dy < 0 then corrector := 2 * PI - corrector;
getAngleOf2P := angle + corrector;
end;
begin
randomize;
end.
|
//=============================================================================
//调用函数说明:
// 发送文字到主程序控制台上:
// procedure MainOutMessasge(sMsg:String;nMode:integer)
// sMsg 为要发送的文本内容
// nMode 为发送模式,0为立即在控制台上显示,1为加入显示队列,稍后显示
//
// 取得0-255所代表的颜色
// function GetRGB(bt256:Byte):TColor;
// bt256 要查询数字
// 返回值 为代表的颜色
//
// 发送广播文字:
// procedure SendBroadCastMsg(sMsg:String;MsgType:TMsgType);
// sMsg 要发送的文字
// MsgType 文字类型
//=============================================================================
unit PlugMain;
interface
uses
Windows, Graphics, SysUtils, PlugManage;
procedure InitPlug(AppHandle:THandle);
procedure UnInitPlug();
function DeCodeText(sText:String):String;
function SearchIPLocal(sIPaddr:String):String;
implementation
uses QQWry, Share;
//=============================================================================
//加载插件模块时调用的初始化函数
//参数:Apphandle 为主程序句柄
//=============================================================================
procedure InitPlug(AppHandle:THandle);
begin
end;
//=============================================================================
//退出插件模块时调用的结束函数
//=============================================================================
procedure UnInitPlug();
begin
{
写上相应处理代码;
}
MainOutMessasge(sUnLoadPlug,0);
end;
//=============================================================================
//游戏日志信息处理函数
//返回值:True 代表不调用默认游戏日志处理函数,False 调用默认游戏日志处理函数
//=============================================================================
function GameDataLog(sLogMsg:String):Boolean;
begin
{
写上相应处理游戏日志代码;
}
Result:=False;
end;
//=============================================================================
//游戏文本配置信息解码函数(一般用于加解密脚本)
//参数:sText 为要解码的字符串
//返回值:返回解码后的字符串(返回的字符串长度不能超过1024字节,超过将引起错误)
//=============================================================================
function DeCodeText(sText:String):String;
begin
end;
//=============================================================================
//IP所在地查询函数
//参数:sIPaddr 为要查询的IP地址
//返回值:返回IP所在地文本信息(返回的字符串长度不能超过255字节,超过会被截短)
//=============================================================================
function SearchIPLocal(sIPaddr:String):String;
var
QQWry: TQQWry;
begin
try
QQWry:=TQQWry.Create(sIPDataFileName);
Result:=QQWry.GetIPMsg(QQWry.GetIPRecordID(sIPaddr))[2]+QQWry.GetIPMsg(QQWry.GetIPRecordID(sIPaddr))[3];
QQWry.Free;
except
Result:='No Find';
end;
end;
end.
|
unit uPctColorFch;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uParentButtonFch, mrConfigFch, DB, StdCtrls, XiButton, ExtCtrls,
cxControls, cxContainer, cxEdit, cxTextEdit, cxDBEdit, mrDBEdit,
mrSubListPanel, uMRSQLParam, uNTUpdateControl;
type
TPctColorFch = class(TParentButtonFch)
edtCode: TmrDBEdit;
slpColorSpecies: TmrSubListPanel;
procedure ConfigFchAfterStart(Sender: TObject);
procedure slpColorSpeciesGetFilter(Sender: TObject;
var Filter: TMRSQLParam);
procedure slpColorSpeciesGetForeignKeyValue(Sender: TObject;
var Filter: TMRSQLParam);
procedure slpColorSpeciesGetTransaction(Sender: TObject;
var ATransaction: TmrTransaction);
procedure slpColorSpeciesStateChange(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure ConfigFchAfterAppend(Sender: TObject);
procedure ConfigFchAfterNavigation(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
implementation
uses uDMPetCenter, uDMPet, uDMMaintenance, uParentCustomFch;
{$R *.dfm}
procedure TPctColorFch.ConfigFchAfterStart(Sender: TObject);
begin
slpColorSpecies.CreateSubList(TraceControl, DataSetControl, UpdateControl, Session, DMPet.SystemUser, 'MenuDisplay=Color;');
inherited;
end;
procedure TPctColorFch.slpColorSpeciesGetFilter(Sender: TObject;
var Filter: TMRSQLParam);
begin
inherited;
with Filter do
begin
AddKey('PC.IDColor').AsInteger := DataSet.FieldByName('IDColor').AsInteger;
KeyByName('PC.IDColor').Condition := tcEquals;
end;
end;
procedure TPctColorFch.slpColorSpeciesGetForeignKeyValue(Sender: TObject;
var Filter: TMRSQLParam);
begin
inherited;
with Filter do
begin
AddKey('IDColor').AsInteger := DataSet.FieldByName('IDColor').AsInteger;
KeyByName('IDColor').Condition := tcEquals;
end;
end;
procedure TPctColorFch.slpColorSpeciesGetTransaction(Sender: TObject;
var ATransaction: TmrTransaction);
begin
inherited;
ATransaction := Transaction;
end;
procedure TPctColorFch.slpColorSpeciesStateChange(Sender: TObject);
begin
inherited;
DataSet.Edit;
end;
procedure TPctColorFch.FormShow(Sender: TObject);
begin
inherited;
slpColorSpecies.RefreshSubList;
end;
procedure TPctColorFch.ConfigFchAfterAppend(Sender: TObject);
begin
inherited;
slpColorSpecies.RefreshSubList;
end;
procedure TPctColorFch.ConfigFchAfterNavigation(Sender: TObject);
begin
inherited;
slpColorSpecies.RefreshSubList;
end;
procedure TPctColorFch.FormDestroy(Sender: TObject);
begin
slpColorSpecies.FreeSubList;
inherited;
end;
initialization
RegisterClass(TPctColorFch);
end.
|
unit Lib.HTTPServer.StaticFiles;
interface
uses
System.SysUtils,
System.Classes,
Lib.HTTPConsts,
Lib.HTTPContent,
Lib.HTTPUtils,
Lib.HTTPServer;
type
TStaticFiles = class(TInterfacedObject,IMiddleware)
private
FHome: string;
FAliases: TStrings;
public
constructor Create(const Home: string; Aliases: TStrings);
destructor Destroy; override;
function Use(Request: TRequest; Response: TResponse): Boolean;
end;
implementation
constructor TStaticFiles.Create(const Home: string; Aliases: TStrings);
begin
FHome:=Home;
FAliases:=TStringList.Create;
FAliases.Assign(Aliases);
end;
destructor TStaticFiles.Destroy;
begin
FAliases.Free;
inherited;
end;
function TStaticFiles.Use(Request: TRequest; Response: TResponse): Boolean;
var FileName: string;
begin
Result:=False;
if Request.Method=METHOD_GET then
begin
FileName:=HTTPFindLocalFile(Request.Resource,FHome,FAliases);
if FileExists(FileName) then
begin
Response.SetResult(HTTPCODE_SUCCESS,'OK');
Response.AddContentFile(FileName);
Response.ResourceName:=HTTPExtractResourceName(Request.Resource);
Result:=True;
end;
end;
end;
end.
|
unit feli_user_event;
{$mode objfpc}
interface
uses
feli_document,
feli_collection,
fpjson;
type
FeliUserEventKeys = class
public
const
eventId = 'event_id';
createdAt = 'created_at';
end;
FeliUserEvent = class(FeliDocument)
public
eventId: ansiString;
createdAt: int64;
function toTJsonObject(secure: boolean = false): TJsonObject; override;
class function fromTJsonObject(dataObject: TJsonObject): FeliUserEvent; static;
end;
FeliUserEventCollection = class(FeliCollection)
public
procedure add(userEvent: FeliUserEvent);
class function fromFeliCollection(collection: FeliCollection): FeliUserEventCollection; static;
end;
FeliUserEventJoinedCollection = class(FeliUserEventCollection)
end;
FeliUserEventCreatedCollection = class(FeliUserEventCollection)
end;
FeliUserEventPendingCollection = class(FeliUserEventCollection)
end;
implementation
uses
feli_stack_tracer,
sysutils;
function FeliUserEvent.toTJsonObject(secure: boolean = false): TJsonObject;
var
userEvent: TJsonObject;
begin
FeliStackTrace.trace('begin', 'function FeliUserEvent.toTJsonObject(secure: boolean = false): TJsonObject;');
userEvent := TJsonObject.create();
userEvent.add(FeliUserEventKeys.eventId, eventId);
userEvent.add(FeliUserEventKeys.createdAt, createdAt);
result := userEvent;
FeliStackTrace.trace('end', 'function FeliUserEvent.toTJsonObject(secure: boolean = false): TJsonObject;');
end;
class function FeliUserEvent.fromTJsonObject(dataObject: TJsonObject): FeliUserEvent; static;
var
userEventInstance: FeliUserEvent;
tempString: ansiString;
begin
FeliStackTrace.trace('begin', 'class function FeliUserEvent.fromTJsonObject(dataObject: TJsonObject): FeliUserEvent; static;');
userEventInstance := FeliUserEvent.create();
with userEventInstance do
begin
tempString := '0';
try tempString := dataObject.getPath(FeliUserEventKeys.createdAt).asString; except on e: exception do begin end; end;
createdAt := strToInt64(tempString);
try eventId := dataObject.getPath(FeliUserEventKeys.eventId).asString; except on e: exception do begin end; end;
end;
result := userEventInstance;
FeliStackTrace.trace('end', 'class function FeliUserEvent.fromTJsonObject(dataObject: TJsonObject): FeliUserEvent; static;');
end;
procedure FeliUserEventCollection.add(userEvent: FeliUserEvent);
begin
FeliStackTrace.trace('begin', 'procedure FeliUserEventCollection.add(userEvent: FeliUserEvent);');
data.add(userEvent.toTJsonObject());
FeliStackTrace.trace('end', 'procedure FeliUserEventCollection.add(userEvent: FeliUserEvent);');
end;
class function FeliUserEventCollection.fromFeliCollection(collection: FeliCollection): FeliUserEventCollection; static;
var
feliUserEventCollectionInstance: FeliUserEventCollection;
begin
FeliStackTrace.trace('begin', 'procedure FeliUserEventCollection.add(userEvent: FeliUserEvent);');
feliUserEventCollectionInstance := FeliUserEventCollection.create();
feliUserEventCollectionInstance.data := collection.data;
result := feliUserEventCollectionInstance;
FeliStackTrace.trace('end', 'procedure FeliUserEventCollection.add(userEvent: FeliUserEvent);');
end;
end. |
unit TestUUnidadeController;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, UCondominioVO, SysUtils, DBClient, DBXJSON, UPessoasVO,
UCondominioController, DBXCommon, UUnidadeController, UUnidadeVO,
Generics.Collections, Classes, UController, DB, ConexaoBD, SQLExpr;
type
// Test methods for class TUnidadeController
TestTUnidadeController = class(TTestCase)
strict private
FUnidadeController: TUnidadeController;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestConsultarPorId;
procedure TestConsultarPorIdNaoEncontrado;
end;
implementation
procedure TestTUnidadeController.SetUp;
begin
FUnidadeController := TUnidadeController.Create;
end;
procedure TestTUnidadeController.TearDown;
begin
FUnidadeController.Free;
FUnidadeController := nil;
end;
procedure TestTUnidadeController.TestConsultarPorId;
var
ReturnValue: TUnidadeVO;
// id: Integer;
begin
ReturnValue := FUnidadeController.ConsultarPorId(4);
if(returnvalue <> nil) then
check(true,'Unidade pesquisada com sucesso!')
else
check(true,'Unidade nao encontrada!');
end;
procedure TestTUnidadeController.TestConsultarPorIdNaoEncontrado;
var
ReturnValue: TUnidadeVO;
begin
ReturnValue := FUnidadeController.ConsultarPorId(4);
if(returnvalue <> nil) then
check(true,'Unidade pesquisada com sucesso!')
else
check(true,'Unidade nao encontrada!');
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTUnidadeController.Suite);
end.
|
//
// Generated by JavaToPas v1.5 20180804 - 082355
////////////////////////////////////////////////////////////////////////////////
unit java.sql.ClientInfoStatus;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes;
type
JClientInfoStatus = interface;
JClientInfoStatusClass = interface(JObjectClass)
['{02811370-F19B-4807-ADE7-B39CF4104674}']
function _GetREASON_UNKNOWN : JClientInfoStatus; cdecl; // A: $4019
function _GetREASON_UNKNOWN_PROPERTY : JClientInfoStatus; cdecl; // A: $4019
function _GetREASON_VALUE_INVALID : JClientInfoStatus; cdecl; // A: $4019
function _GetREASON_VALUE_TRUNCATED : JClientInfoStatus; cdecl; // A: $4019
function valueOf(&name : JString) : JClientInfoStatus; cdecl; // (Ljava/lang/String;)Ljava/sql/ClientInfoStatus; A: $9
function values : TJavaArray<JClientInfoStatus>; cdecl; // ()[Ljava/sql/ClientInfoStatus; A: $9
property REASON_UNKNOWN : JClientInfoStatus read _GetREASON_UNKNOWN; // Ljava/sql/ClientInfoStatus; A: $4019
property REASON_UNKNOWN_PROPERTY : JClientInfoStatus read _GetREASON_UNKNOWN_PROPERTY;// Ljava/sql/ClientInfoStatus; A: $4019
property REASON_VALUE_INVALID : JClientInfoStatus read _GetREASON_VALUE_INVALID;// Ljava/sql/ClientInfoStatus; A: $4019
property REASON_VALUE_TRUNCATED : JClientInfoStatus read _GetREASON_VALUE_TRUNCATED;// Ljava/sql/ClientInfoStatus; A: $4019
end;
[JavaSignature('java/sql/ClientInfoStatus')]
JClientInfoStatus = interface(JObject)
['{34667BBE-A16D-4574-B9D7-252398F340E7}']
end;
TJClientInfoStatus = class(TJavaGenericImport<JClientInfoStatusClass, JClientInfoStatus>)
end;
implementation
end.
|
//------------------------------------------------------------------------------
//ItemTypes UNIT
//------------------------------------------------------------------------------
// What it does-
// Contains Item related Types
//
// Changes -
// February 25th, 2008 - RaX - Created
//
//------------------------------------------------------------------------------
unit ItemTypes;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
{RTL/VCL}
{Project}
GameTypes
;
{Third Party}
type
TItemType = (EQUIPMENT,USEABLE,MISC);
TEquipLocations =
(
HEADUPPER,
HEADMID,
HEADLOWER,
RIGHTHAND,
LEFTHAND,
CAPE,
FEET,
BODY,
ACCESSORY1,
ACCESSORY2
);//1 byte
TEquipTypes =
(
HEADGEAR, //1
SHIELD, //2
BODYARMOR, //3
SHOES, //4
GARMENT, //5
ACCESSORY, //6
SWORD, //7
TWOHANDEDSWORD, //8
DAGGER, //9
MACE, //10
TWOHANDEDMACE, //11
BOW, //12
AXE, //13
TWOHANDEDAXE, //14
SPEAR, //15
TWOHANDEDSPEAR, //16
STAFF, //17
BOOK, //18
FIST, //19
KATAR, //20
INSTRUMENT, //21
WHIP, //22
GATLINGGUN, //23
GRENADELAUNCHER, //24
REVOLVER, //25
RIFLE, //26
SHOTGUN //27
);//1 byte
function ItemTypeToByte(const AnItemType : TItemType) : Byte;
function ByteToItemType(AByte : Byte) : TItemType;
function EquipLocationsToByte(const AnEquipLocation : TEquipLocations) : Word;
function ByteToEquipLocations(AWord : Word) : TEquipLocations;
function EquipTypeToByte(const AnEquipType : TEquipTypes) : Byte;
function ByteToEquipType(AByte : Byte) : TEquipTypes;
function EquipLocationToLookType(const AnEquipLocation : TEquipLocations):TLookTypes;
implementation
function ItemTypeToByte(const AnItemType : TItemType) : Byte;
begin
case AnItemType of
EQUIPMENT :
begin
Result := 4;
end;
USEABLE :
begin
Result := 2;
end;
else
begin
Result := 3;
end;
end;
end;{ItemTypeToByte}
function ByteToItemType(AByte : Byte) : TItemType;
begin
case AByte of
4 :
begin
Result := EQUIPMENT;
end;
2 :
begin
Result := USEABLE;
end;
else
begin
Result := MISC;
end;
end;
end;{ByteToItemType}
function EquipLocationsToByte(const AnEquipLocation : TEquipLocations) : Word;
begin
case AnEquipLocation of
HEADLOWER : Result := 1;
RIGHTHAND : Result := 2;
CAPE : Result := 4;
ACCESSORY1 : Result := 8;
BODY : Result := 16;
LEFTHAND : Result := 32;
FEET : Result := 64;
ACCESSORY2 : Result := 128;
HEADUPPER : Result := 256;
HEADMID : Result := 512;
else
Result := 1;
end;
end;{EquipLocationsToByte}
function ByteToEquipLocations(AWord : Word) : TEquipLocations;
begin
case AWord of
1 : Result := HEADLOWER;
2 : Result := RIGHTHAND;
4 : Result := CAPE;
8 : Result := ACCESSORY1;
16 : Result := BODY;
32 : Result := LEFTHAND;
64 : Result := FEET;
128 : Result := ACCESSORY2;
256 : Result := HEADUPPER;
512 : Result := HEADMID;
else
Result := HEADUPPER;
end;
end;{ByteToEquipLocations}
function EquipTypeToByte(const AnEquipType : TEquipTypes) : Byte;
begin
case AnEquipType of
HEADGEAR : Result := 1;
SHIELD : Result := 2;
BODYARMOR : Result := 3;
SHOES : Result := 4;
GARMENT : Result := 5;
ACCESSORY : Result := 6;
SWORD : Result := 7;
TWOHANDEDSWORD : Result := 8;
DAGGER : Result := 9;
MACE : Result := 10;
TWOHANDEDMACE : Result := 11;
BOW : Result := 12;
AXE : Result := 13;
TWOHANDEDAXE : Result := 14;
SPEAR : Result := 15;
TWOHANDEDSPEAR : Result := 16;
STAFF : Result := 17;
BOOK : Result := 18;
FIST : Result := 19;
KATAR : Result := 20;
INSTRUMENT : Result := 21;
WHIP : Result := 22;
GATLINGGUN : Result := 23;
GRENADELAUNCHER : Result := 24;
REVOLVER : Result := 25;
RIFLE : Result := 26;
SHOTGUN : Result := 27;
else
Result := 1;
end;
end;{EquipTypeToByte}
function ByteToEquipType(AByte : Byte) : TEquipTypes;
begin
case AByte of
1 : Result := HEADGEAR;
2 : Result := SHIELD;
3 : Result := BODYARMOR;
4 : Result := SHOES;
5 : Result := GARMENT;
6 : Result := ACCESSORY;
7 : Result := SWORD;
8 : Result := TWOHANDEDSWORD;
9 : Result := DAGGER;
10 : Result := MACE;
11 : Result := TWOHANDEDMACE;
12 : Result := BOW;
13 : Result := AXE;
14 : Result := TWOHANDEDAXE;
15 : Result := SPEAR;
16 : Result := TWOHANDEDSPEAR;
17 : Result := STAFF;
18 : Result := BOOK;
19 : Result := FIST;
20 : Result := KATAR;
21 : Result := INSTRUMENT;
22 : Result := WHIP;
23 : Result := GATLINGGUN;
24 : Result := GRENADELAUNCHER;
25 : Result := REVOLVER;
26 : Result := RIFLE;
27 : Result := SHOTGUN;
else
Result := HEADGEAR;
end;
end;{ByteToEquipType}
function EquipLocationToLookType(const AnEquipLocation : TEquipLocations):TLookTypes;
begin
case AnEquipLocation of
HEADUPPER:Result := LOOK_HEAD_TOP;
HEADMID: Result := LOOK_HEAD_MID;
HEADLOWER:Result := LOOK_HEAD_BOTTOM;
RIGHTHAND:Result := LOOK_WEAPON;
LEFTHAND: Result := LOOK_SHIELD;
FEET: Result := LOOK_SHOES;
else
Result := TLookTypes(0);
end;
end;{EquipLocationToLookType}
end.
|
unit Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ComCtrls, Vcl.ToolWin, Vcl.OleCtrls,
SHDocVw, Vcl.StdCtrls, System.Net.URLClient, System.Net.HttpClient,
System.Net.HttpClientComponent, System.ImageList, Vcl.ImgList, System.JSON, ActiveX,
Vcl.AppEvnts, System.Actions, Vcl.ActnList, Vcl.Menus;
const
AppKey = 'f1039cf84261ac615fa8221e7938a42d'; // Идентификатор приложения
DisplayApp = 'page'; // Внешний вид формы мобильных приложений. Допустимые значения:
// "page" — Страница
// "popup" — Всплывающее окно
Expires_at = 604800; // Срок действия access_token в формате UNIX. Также можно указать дельту в секундах.
// Срок действия и дельта не должны превышать две недели, начиная с настоящего времени.
Nofollow = 1; // При передаче параметра nofollow=1 переадресация не происходит. URL возвращается в ответе.
// По умолчанию: 0. Минимальное значение: 0. Максимальное значение: 1.
RedirectURL = 'https://developers.wargaming.net/reference/all/wot/auth/login/'; // URL на который будет переброшен пользователь
// после того как он пройдет аутентификацию.
// По умолчанию: api.worldoftanks.ru/wot//blank/
AuthURL = 'https://api.worldoftanks.ru/wot/auth/login/?application_id=%s&display=%s&expires_at=%s&nofollow=%d'; // URL для запроса
// Коды ошибок
AUTH_CANCEL = 401; // Пользователь отменил авторизацию для приложения
AUTH_EXPIRED = 403; // Превышено время ожидания авторизации пользователя
AUTH_ERROR = 410; // Ошибка аутентификации
type
TMainForm = class(TForm)
NetClient: TNetHTTPClient;
NetRequest: TNetHTTPRequest;
Menu: TMainMenu;
FileMenu: TMenuItem;
AuthMenu: TMenuItem;
AL: TActionList;
AppEvents: TApplicationEvents;
IL: TImageList;
AuthAction: TAction;
SB: TStatusBar;
procedure FormCreate(Sender: TObject);
procedure AuthActionExecute(Sender: TObject);
private
FCodeErr: string;
FMessageErr: string;
FStatusErr: string;
Fnickname: string;
Fexpires_at: string;
FStatus: string;
Faccess_token: String;
Faccount_id: string;
FlocationRedirect: string;
FSuccessRedirectURL: string;
procedure Setaccess_token(const Value: String);
procedure Setaccount_id(const Value: string);
procedure SetCodeErr(const Value: string);
procedure Setexpires_at(const Value: string);
procedure SetMessageErr(const Value: string);
procedure Setnickname(const Value: string);
procedure SetStatus(const Value: string);
procedure SetStatusErr(const Value: string);
procedure SetlocationRedirect(const Value: string);
procedure SetSuccessRedirectURL(const Value: string);
{ Private declarations }
public
published
// Параметры redirect_uri при успешной аутентификации
property Status: string read FStatus write SetStatus;
property access_token: String read Faccess_token write Setaccess_token;
property expires_at: string read Fexpires_at write Setexpires_at;
property account_id: string read Faccount_id write Setaccount_id;
property nickname: string read Fnickname write Setnickname;
// Параметры redirect_uri при ошибке аутентификации
property StatusErr: string read FStatusErr write SetStatusErr;
property CodeErr: string read FCodeErr write SetCodeErr;
property MessageErr: string read FMessageErr write SetMessageErr;
property locationRedirect: string read FlocationRedirect write SetlocationRedirect;
property SuccessRedirectURL: string read FSuccessRedirectURL write SetSuccessRedirectURL;
end;
var
MainForm: TMainForm;
implementation
{$R *.dfm}
uses BrowserEmulationAdjuster, Auth, Globals, SConsts;
{ TMainForm }
procedure TMainForm.AuthActionExecute(Sender: TObject);
var
AuthF: TAuthForm;
begin
AuthF := TAuthForm.Create(Self);
try
AuthF.ShowModal();
finally
FreeAndNil(AuthF);
end;
end;
procedure TMainForm.FormCreate(Sender: TObject);
begin
// SuccessRedirectURL := '&status=ok&access_token=7b25dd5463330f871fc0d1652d6c6058adcd5834&nickname=Dr_Gladiator_AMEB&account_id=21664152&expires_at=1629310945';
end;
procedure TMainForm.Setaccess_token(const Value: String);
begin
Faccess_token := Value;
end;
procedure TMainForm.Setaccount_id(const Value: string);
begin
Faccount_id := Value;
end;
procedure TMainForm.SetCodeErr(const Value: string);
begin
FCodeErr := Value;
end;
procedure TMainForm.Setexpires_at(const Value: string);
begin
Fexpires_at := Value;
end;
procedure TMainForm.SetlocationRedirect(const Value: string);
begin
FlocationRedirect := Value;
end;
procedure TMainForm.SetMessageErr(const Value: string);
begin
FMessageErr := Value;
end;
procedure TMainForm.Setnickname(const Value: string);
begin
Fnickname := Value;
end;
procedure TMainForm.SetStatus(const Value: string);
begin
FStatus := Value;
end;
procedure TMainForm.SetStatusErr(const Value: string);
begin
FStatusErr := Value;
end;
procedure TMainForm.SetSuccessRedirectURL(const Value: string);
begin
FSuccessRedirectURL := Value;
end;
end.
|
(**************************************************************)
(******* BINARY SEARCH TREE ADT ********)
(**************************************************************)
TYPE
KeyType = Integer; (* the type of key in Info part *)
TreeElementType = RECORD (* the type of the user's data *)
Key : KeyType;
(* other fields as needed. *)
END; (* TreeElementType *)
TreePtrType = ^TreeNodeType;
TreeNodeType = RECORD
Info : TreeElementType; (* the user's data *)
Left : TreePtrType; (* pointer to left child *)
Right : TreePtrType (* pointer to right child *)
END; (* TreeNodeType *)
TreeType = TreePtrType;
TraversalType = (Preorder, Inorder, Postorder);
(******************************************************)
PROCEDURE CreateTree
(VAR Tree : TreeType);
(* Initializes Tree to empty state. *)
BEGIN (* CreateTree *)
Tree := NIL
END; (* CreateTree *)
(*************************************************)
PROCEDURE FindNode
( Tree : TreeType;
KeyValue : KeyType;
VAR NodePtr : TreePtrType;
VAR ParentPtr : TreePtrType);
(* Find the node that contains KeyValue; set NodePtr to *)
(* point to the node and ParentPtr to point to its parent; *)
VAR
Found : Boolean; (* KeyValue found in tree? *)
BEGIN (* FindNode *)
(* Set up to search. *)
NodePtr := Tree;
ParentPtr := NIL;
Found := False;
(* Search until no more nodes to search or until found. *)
WHILE (NodePtr <> NIL) AND NOT Found DO
IF NodePtr^.Info.Key = KeyValue
THEN Found := True
ELSE (* Advance pointers. *)
BEGIN
ParentPtr := NodePtr;
IF NodePtr^.Info.Key > KeyValue
THEN NodePtr := NodePtr^.Left
ELSE NodePtr := NodePtr^.Right
END (* advance pointers *)
END; (* FindNode *)
(********************************************************)
PROCEDURE RetrieveElement
(Tree : TreeType;
KeyValue : KeyType;
VAR Element : TreeElementType;
VAR ValueInTree : Boolean);
(* Searches the binary search tree for the element whose *)
(* key is KeyValue, and returns a copy of the element. *)
VAR
NodePtr : TreePtrType; (* pointer to node with KeyValue *)
ParentPtr : TreePtrType; (* used for FindNode interface *)
BEGIN (* RetrieveElement *)
(* Find node in tree that contains KeyValue. *)
FindNode (Tree, KeyValue, NodePtr, ParentPtr);
ValueInTree := (NodePtr <> NIL);
IF ValueInTree
THEN Element := NodePtr^.Info
END; (* RetrieveElement *)
(***********************************************************)
PROCEDURE ModifyElement
(VAR Tree : TreeType;
ModElement : TreeElementType);
(* ModElement replaces existing tree element with same key. *)
VAR
NodePtr : TreePtrType; (* pointer to node with KeyValue *)
ParentPtr : TreePtrType; (* used for FindNode interface *)
BEGIN (* ModifyElement *)
(* Find the node with the same key as ModElement.Key. *)
FindNode (Tree, ModElement.Key, NodePtr, ParentPtr);
(* NodePtr points to the tree node with same key. *)
NodePtr^.Info := ModElement
END; (* ModifyElement *)
(***************************************************************)
PROCEDURE InsertElement
(VAR Tree : TreeType;
Element : TreeElementType);
(* Add Element to the binary search tree. Assumes that no *)
(* element with the same key exists in the tree. *)
VAR
NewNode : TreePtrType; (* pointer to new node *)
NodePtr : TreePtrType; (* used for FindNode call *)
ParentPtr : TreePtrType; (* points to new node's parent *)
BEGIN (* InsertElement *)
(* Create a new node. *)
New (NewNode);
NewNode^.Left := NIL;
NewNode^.Right := NIL;
NewNode^.Info := Element;
(* Search for the insertion place. *)
FindNode (Tree, Element.Key, NodePtr, ParentPtr);
(* IF this is first node in tree, set Tree to NewNode; *)
(* otherwise, link new node to Node(ParentPtr). *)
IF ParentPtr = NIL
THEN Tree := NewNode (* first node in the tree *)
ELSE (* Add to the existing tree. *)
IF ParentPtr^.Info.Key > Element.Key
THEN ParentPtr^.Left := NewNode
ELSE ParentPtr^.Right := NewNode
END; (* InsertElement *)
(**********************************************************)
{ The following code has been commented out:
PROCEDURE InsertElement
(VAR Tree : TreeType;
Element : TreeElementType);
(* Recursive version of InsertElement operation. *)
BEGIN (* InsertElement *)
IF Tree = NIL
THEN (* Base Case: allocate new leaf Node(Tree) *)
BEGIN
New (Tree);
Tree^.Left := NIL;
Tree^.Right := NIL;
Tree^.Info := Element
END (* IF Tree = NIL *)
ELSE (* General Case: InsertElement into correct subtree *)
IF Element.Key < Tree^.Info.Key
THEN InsertElement (Tree^.Left, Element)
ELSE InsertElement (Tree^.Right, Element)
END; (* InsertElement *)
}
(**********************************************************)
PROCEDURE DeleteElement
(VAR Tree : TreeType;
KeyValue : KeyType);
(* Deletes the element containing KeyValue from the binary *)
(* search tree pointed to by Tree. Assumes that this key *)
(* value is known to exist in the tree. *)
VAR
NodePtr : TreePtrType; (* pointer to node to be deleted *)
ParentPtr : TreePtrType; (* pointer to parent of delete node *)
(********************* Nested Procedures ***********************)
PROCEDURE FindAndRemoveMax
(VAR Tree : TreePtrType;
VAR MaxPtr : TreePtrType);
BEGIN (* FindAndRemoveMax *)
IF Tree^.Right = NIL
THEN (* Base Case: maximum found *)
BEGIN
MaxPtr := Tree; (* return pointer to max node *)
Tree := Tree^.Left (* unlink max node from tree *)
END (* Base Case *)
ELSE (* General Case: find and remove from right subtree *)
FindAndRemoveMax (Tree^.Right, MaxPtr)
END; (* FindAndRemoveMax *)
(*************************************************************)
PROCEDURE DeleteNode
(VAR NodePtr : TreePtrType);
(* Deletes the node pointed to by NodePtr from the binary *)
(* search tree. NodePtr is a real pointer from the parent *)
(* node in the tree, not an external pointer. *)
VAR
TempPtr : TreePtrType; (* node to delete *)
BEGIN (* DeleteNode *)
(* Save the original pointer for freeing the node. *)
TempPtr := NodePtr;
(* Case of no children or one child: *)
IF NodePtr^.Right = NIL
THEN NodePtr := NodePtr^.Left
ELSE (* There is at least one child. *)
IF NodePtr^.Left = NIL
THEN (* There is one child. *)
NodePtr := NodePtr^.Right
ELSE (* There are two children. *)
BEGIN
(* Find and remove the replacement value from *)
(* Node(NodePtr)'s left subtree. *)
FindAndRemoveMax (NodePtr^.Left, TempPtr);
(* Replace the delete element. *)
NodePtr^.Info := TempPtr^.Info
END; (* There are two children. *)
(* Free the unneeded node. *)
Dispose (TempPtr)
END; (* DeleteNode *)
(*****************************************************************)
BEGIN (* DeleteElement *)
(* Find node containing KeyValue. *)
FindNode (Tree, KeyValue, NodePtr, ParentPtr);
(* Delete node pointed to by NodePtr. ParentPtr points *)
(* to the parent node, or is NIL if deleting root node. *)
IF NodePtr = Tree
THEN (* Delete the root node. *)
DeleteNode (Tree)
ELSE
IF ParentPtr^.Left = NodePtr
THEN (* Delete the left child node. *)
DeleteNode (ParentPtr^.Left)
ELSE (* Delete the right child node. *)
DeleteNode (ParentPtr^.Right)
END; (* DeleteElement *)
(***********************************************************)
{The following procedure has been commented out:
PROCEDURE DeleteElement
(VAR Tree : TreeType;
KeyValue : KeyType);
(* Recursive version of DeleteElement operation. *)
BEGIN (* DeleteElement *)
IF KeyValue = Tree^.Info.Key
THEN (* Base Case : delete this node *)
DeleteNode (Tree)
ELSE
IF KeyValue < Tree^.Info.Key
THEN (* General Case 1: delete node from left subtree *)
DeleteElement (Tree^.Left, KeyValue)
ELSE (* General Case 2: delete node from right subtree *)
DeleteElement (Tree^.Right, KeyValue)
END; (* DeleteElement *)
}
(****************************************************************)
PROCEDURE PrintTree
(Tree : TreeType;
TraversalOrder : TraversalType);
(* Print all the elements in the tree, in the order *)
(* specified by TraversalOrder. *)
(********************** Nested Procedures ************************)
PROCEDURE PrintNode
(Element : TreeElementType);
BEGIN (* PrintNode *)
Writeln (Element.Key);
(* other statements as needed *)
END; (* PrintNode *)
(*********************************************************)
PROCEDURE PrintInorder
(Tree : TreeType);
(* Prints out the elements in a binary search tree in *)
(* order from smallest to largest. This procedure is *)
(* a recursive solution. *)
BEGIN (* PrintInorder *)
(* Base Case: If Tree is NIL, do nothing. *)
IF Tree <>NIL
THEN
BEGIN (* General Case *)
(* Traverse left subtree to print smaller values. *)
PrintInorder(Tree^.Left);
(* Print the information in this node. *)
PrintNode(Tree^.Info);
(* Traverse right subtree to print larger values. *)
PrintInorder(Tree^.Right)
END (* General Case *)
END; (* PrintInorder *)
(***************************************************************)
PROCEDURE PrintPreorder
(Tree : TreeType);
(* Print out the elements in a binary search tree in *)
(* preorder. This procedure is a recursive solution. *)
BEGIN (* PrintPreorder *)
(* Base Case: IF Tree is NIL, do nothing. *)
IF Tree <> NIL
THEN (* General Case *)
BEGIN
(* Print the value of this node. *)
PrintNode(Tree^.Info);
(* Traverse the left subtree in preorder. *)
PrintPreorder(Tree^.Left);
(* Traverse the left subtree in preorder. *)
PrintPreorder(Tree^.Right)
END (* General Case *)
END; (* PrintPreorder *)
(***********************************************************)
PROCEDURE PrintPostorder
(Tree : TreeType);
(* Prints out the elements in a binary search tree in *)
(* postorder. This procedure is a recursive solution. *)
BEGIN (* PrintPostorder *)
(* Base Case: If Tree is NIL, do nothing. *)
IF Tree <> NIL
THEN (* General Case *)
BEGIN
(* Traverse the left subtree in postorder. *)
PrintPostorder(Tree^.Left);
(* Traverse the right subtree in postorder. *)
PrintPostorder(Tree^.Right);
(* Print the value of this node. *)
PrintNode(Tree^.Info)
END (* General Case *)
END; (* PrintPostorder *)
(********************************************************)
BEGIN (* PrintTree *)
(* Call internal print procedure according to TraversalOrder. *)
CASE TraversalOrder OF
Preorder : PrintPreorder (Tree);
Inorder : PrintInorder (Tree);
Postorder : PrintPostorder (Tree)
END (* CASE *)
END; (* PrintTree *)
(***********************************************************)
PROCEDURE DestroyTree
(VAR Tree : TreeType);
(* Removes all the elements from the binary search tree *)
(* rooted at Tree, leaving the tree empty. *)
BEGIN (* DestroyTree *)
(* Base Case: If Tree is NIL, do nothing. *)
IF Tree <> NIL
THEN (* General Case *)
BEGIN
(* Traverse the left subtree in postorder. *)
DestroyTree (Tree^.Left);
(* Traverse the right subtree in postorder. *)
DestroyTree (Tree^.Right);
(* Delete this leaf node from the tree. *)
Dispose (Tree);
END (* General Case *)
END; (* DestroyTree *)
(***********************************************************) |
unit uByScienceReportForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs,dmScienceReport, StdCtrls, Buttons, frxDesgn, frxClass, frxDBSet,
cxControls, cxContainer, cxEdit, cxTextEdit, cxMaskEdit, cxDropDownEdit,
cxCalendar, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox;
type
TReportForm = class(TForm)
Label3: TLabel;
CurDateEdit: TcxDateEdit;
FRDataSet: TfrxDBDataset;
Designer: TfrxDesigner;
OkButton: TBitBtn;
CancelButton: TBitBtn;
Label1: TLabel;
PropComboBox: TcxLookupComboBox;
Report: TfrxReport;
procedure FormCreate(Sender: TObject);
procedure OkButtonClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
private
{ Private declarations }
public
DataModule:TScienceReportDM;
DesignReport:Boolean;
end;
var
ReportForm: TReportForm;
implementation
{$R *.dfm}
procedure TReportForm.FormCreate(Sender: TObject);
begin
CurDateEdit.Date:=Date();
end;
procedure TReportForm.OkButtonClick(Sender: TObject);
begin
with DataModule.ReportDataSet do
begin
Close;
ParamByName('REPORT_DATE').Value:=CurDateEdit.Date;
ParamByName('ID_REGARD_PROP').Value:=PropComboBox.EditValue;
Open;
end;
with DataModule.ConstsQuery do
begin
Close;
Open;
end;
Report.LoadFromFile('Reports\Asup\AsupByScienceReport.fr3');
Report.Variables['CUR_DATE']:=QuotedStr(DateToStr(CurDateEdit.Date));
Report.Variables['FIRM_NAME']:=
QuotedStr(DataModule.ConstsQuery['FIRM_NAME']);
Report.Variables['PROPERTY_NAME']:=
QuotedStr(PropComboBox.EditText);
if DesignReport=True then Report.DesignReport
else Report.ShowReport;
end;
procedure TReportForm.FormShow(Sender: TObject);
begin
DataModule.RegardsPropertiesDataSet.Open;
end;
procedure TReportForm.FormClose(Sender: TObject; var Action: TCloseAction);
begin
DataModule.RegardsPropertiesDataSet.Close;
end;
end.
|
namespace CirrusTrace;
interface
type
ConsoleApp = class
public
class method Main;
end;
implementation
// Here several methods of WorkerClass will be called to show how
// its implementation was changed
class method ConsoleApp.Main;
begin
var lWorker: WorkerClass := new WorkerClass();
Console.WriteLine();
Console.WriteLine(String.Format('Result of Sum({0}, {1}) is {2}', 5, 7, lWorker.Sum(5,7)));
Console.WriteLine();
Console.WriteLine(String.Format('Result of Multiply({0}, {1}, {2}) is {3}', 5, 7, 2, lWorker.Multiply(5,7,2)));
Console.ReadLine();
end;
end.
|
unit uConfiguration;
interface
uses
uiConfig;
Type
TConfig = class(TInterfacedObject, IConfig)
private
fTypeDataBase : Integer;
public
function getTypeDataBase: Integer;
procedure setTypeDataBase(const Value: Integer);
Constructor Create;
end;
function configuration : IConfig;
implementation
uses
SysUtils, IniFiles;
var
mConfig : IConfig = Nil;
Ini : TIniFile;
function configuration : IConfig;
begin
if not Assigned( mConfig )
then
mConfig := TConfig.Create;
Result := mConfig;
end;
{ TConfig }
constructor TConfig.Create;
begin
Ini := TIniFile.Create(ExtractFilePath(ParamStr(0)) + 'Packt.ini');
end;
function TConfig.getTypeDataBase: Integer;
begin
Result := Ini.ReadInteger('PACKT','DATABASE',0);
end;
procedure TConfig.setTypeDataBase(const Value: Integer);
begin
Ini.WriteInteger('PACKT','DATABASE',Value);
fTypeDataBase := Value;
end;
end.
|
unit Unit1;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls;
type
{ TForm1 }
TForm1 = class(TForm)
btObter: TButton;
edID: TEdit;
edNome: TEdit;
lbID: TLabel;
lbNome: TLabel;
procedure btObterClick(Sender: TObject);
end;
{TCliente}
TCliente = class(TObject)
private
FId :Integer;
FNome :String;
published
property Id :Integer read FId write FId;
property Nome :String read FNome write FNome;
end;
var
Form1: TForm1;
implementation
{$R *.lfm}
uses
BrookUtils, BrookHttpClient,BrookFCLHttpClientBroker;
{ TForm1 }
procedure TForm1.btObterClick(Sender: TObject);
var
VDados: TStream;
VCliente: TCliente;
VLista: TStringList;
VHttp: TBrookHttpClient;
begin
VCliente := TCliente.Create;
VLista := TStringList.Create;
VDados := TMemoryStream.Create;
VHttp := TBrookHttpClient.Create('FclWeb');
Try
if not VHttp.Get('http://localhost/cgi-bin/cgi1.bf', VDados) then
raise Exception.Create('Não foi possível obter os dados do cliente.');
VDados.Seek(0, 0);
VLista.LoadFromStream(VDados);
BrookSafeStringsToObject(VCliente, VLista);
edID.Text:= IntToStr(VCliente.Id);
edNome.Text:= VCliente.Nome;
finally
VLista.Free;
VDados.Free;
VCliente.Free;
VHttp.Free;
end;
end;
end.
|
unit SpFoto_Classes;
interface
uses Classes,Controls,cxImage,Graphics,Messages,Types,ExtCtrls, Forms;
type TFotoFrame = class(TGraphicControl)
private
// pLeft,pTop,pWidth,pHeight:Integer;
pFrameWidth:Integer;
pIsPressed:Boolean;
pMouseStartPoint:TPoint;
pOwnStartPoint:TPoint;
pSourceImage:TcxImage;
protected
procedure DrawFrame;virtual;
procedure WMLButtonDown(var Message:TWMMouse);Message WM_LBUTTONDOWN;
procedure WMLButtonUp(var Message:TWMMouse);message WM_LBUTTONUP;
procedure WMMouseMove(var Message:TWMMouseMove);message WM_MOUSEMOVE;
procedure CMMouseLeave(var Message:TMessage);message CM_MOUSELEAVE;
public
constructor Create(AOwner:TComponent;ASourceImage:TcxImage;ALeft,ATop,AWidth,AHeight:Integer);reintroduce;
destructor Destroy;override;
function GetImage:TGraphic;
procedure Paint;override;
procedure Repaint;override;
property Canvas;
published
end;
{TSelectImage - потомок класса TcxImage. Отображает рамку, содержит и передает
изображение для сохранения}
type TSelectImage = class(TcxImage)
private
pSelWidth,pSelHeight:Integer;
XCenter,YCenter:Integer;
pRect:TRect;
pPenColor:TColor;
pBrushColor:TColor;
pPenStyle:TPenStyle;
pResultImage:TImage;
pScale:Extended;
pTotalScale:Extended;
protected
procedure pMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
procedure FormRect(AXCenter,AYCenter:Integer);
public
pBorderWidth:Integer;
procedure FitOnParent;
procedure GetSelectedImage;
procedure Paint;override;
procedure SizePlus;
procedure SizeMinus;
procedure SetSelectionParams(ASelWidth,ASelHeight:Integer);
procedure ShowActualSize;
procedure Free; reintroduce;
constructor Create(AOwner:TComponent;AResultImage:TImage;APenColor:TColor;ABrushColor:TColor;APenStyle:TPenStyle = psSolid); reintroduce;
published
property OnMouseDown;
property OnMouseWheelDown;
end;
{TElementPositions - тип, определяющий положение объектов TFrameBase отностительно
друг друга, содержит значения, соответственно:
- левый верхний;
- левый центральный;
- левый нижний;
- центральный верхний;
- центральный центральный;
- центральный нижний;
- правый верхний;
- правый центральный;
- правый нижний.}
type TElementPositions=(epLeftTop,epLeftCenter,epLeftBottom,
epCenterTop,epCenterCenter,epCenterBottom,
epRightTop,epRightCenter,epRightBottom);
{TFrameBase - базовый тип для перетаскиваемых квадратов(TFrameElement),
определяющих положение и размеры рамки}
type TFrameBase = class(TCustomControl)
public
pIsPressed:Boolean; // Была ли нажата над этим объектом кнопка мыши
pElementPos:TElementPositions; // Определяет положение элемента относительно прочих
procedure Deactivate; virtual; abstract; // Деактивация?
procedure SetCoords(X,Y:Integer); //Задает координаты объекта, где X,Y - координатры его центра
procedure Free; reintroduce;
end;
{TFrameObject - собственно рамка, состоящая из 9 объектов TFrameBase и рисунка
TcxImage (вообще это ОБЯЗАТЕЛЬНО ДОЛЖЕН БЫТЬ TSelectImage), откуда берется изображение}
type TFrameObject = class(TObject)
private
// LT,LC,LB,CT,CC,CB,RT,RC,RB:TFrameBase;
pImage:TSelectImage;
pTimer:TTimer;
public
X1,X2,Y1,Y2:Integer; // координаты левого верхнего и правого нижнего углов рамки;
procedure Free; reintroduce;
procedure StartTimer;
procedure StopTimer;
procedure UpDate(Sender:TObject);
procedure ReleaseAll; // делает все объекты TFrameBase неактивными, завершает перемещение и изменение размеров;
procedure Coordinate(dX,dY:Integer;ElementPos:TElementPositions); // координирует взаимное расположение объектов TFrameBase, основываясь на изменении позиции одного (dX;dY) и его позиции ElementPos
procedure DrawRect; // Рисует рамку (только с TSelectImage)
procedure SelectRect(AX1,AY1,AX2,AY2:Integer); // Выделяет рамку по заданным координатам верхнего левого и нижнего правого углов
constructor Create(AOwner:TSelectImage;AStartRect:TRect); reintroduce; // Создает объект на рисунке TSelectImage, рисует рамку AStartRect
end;
type TFrameElementParams = record
Owner:TComponent;
Master:TFrameObject;
Left,Top,Width,Height:Integer;
ElementPos:TElementPositions;
BorderColor,Color:TColor;
end;
type TFrameElement = class(TFrameBase)
private
Master:TFrameObject;
pColor:TColor;
pBorderColor:TColor;
pPressedCursor:TCursor;
pDefaultCursor:TCursor;
pMouseStartPoint:TPoint;
pOwnStartPoint:TPoint;
protected
procedure DrawElement;
procedure MoveWithMouse;
procedure WMLButtonDown(var Message:TWMMouse);Message WM_LBUTTONDOWN;
procedure WMLButtonUp(var Message:TWMMouse);message WM_LBUTTONUP;
procedure WMLButtonDblClk(var Message: TWMLButtonDblClk); message WM_LBUTTONDBLCLK;
public
property Cursor default crDefault;
constructor Create(AParams:TFrameElementParams);reintroduce;
procedure Deactivate; override;
procedure Paint;override;
procedure Repaint;override;
property Canvas;
published
end;
implementation
uses cxControls, Dialogs, SysUtils, Math;
constructor TFotoFrame.Create(AOwner:TComponent;ASourceImage:TcxImage;ALeft,ATop,AWidth,AHeight:Integer);
begin
inherited Create(AOwner);
//******************************************************************************
Parent:=AOwner as TWinControl;
SetBounds(ALeft,ATop,AWidth,AHeight);
pSourceImage:=ASourceImage;
pFrameWidth:=5;
end;
destructor TFotoFrame.Destroy;
begin
inherited Destroy;
end;
procedure TFotoFrame.DrawFrame;
begin
Canvas.Lock;
try
inherited Paint;
Canvas.Brush.Color:=clRed;
Canvas.Pen.Color:=clRed;
Canvas.Rectangle(0,0,Width,Height);
finally
Canvas.Unlock;
end;
end;
function TFotoFrame.GetImage:TGraphic;
var
lDest,lSource:TRect;
begin
lDest.Left:=0;
lDest.Top:=0;
lDest.Right:=Width;
lDest.Bottom:=Height;
lSource.Left:=0;
lSource.Top:=0;
lSource.Right:=Width;
lSource.Bottom:=Height;
Result:=pSourceImage.Picture.Graphic;
end;
procedure TFotoFrame.Paint;
begin
DrawFrame;
inherited Paint;
end;
procedure TFotoFrame.Repaint;
begin
inherited Paint;
end;
procedure TFotoFrame.WMLButtonDown(var Message:TWMMouse);
begin
pIsPressed:=True;
pMouseStartPoint:=Mouse.CursorPos;
pOwnStartPoint:=Point(Left,Top);
end;
procedure TFotoFrame.WMLButtonUp(var Message:TWMMouse);
begin
pIsPressed:=False;
end;
procedure TFotoFrame.WMMouseMove(var Message:TWMMouseMove);
var
lLeft,lTop:Integer;
begin
if pIsPressed then
begin
lLeft := pOwnStartPoint.X+Mouse.CursorPos.X-pMouseStartPoint.X;
lTop := pOwnStartPoint.Y+Mouse.CursorPos.Y-pMouseStartPoint.Y;
if lLeft+Width>Parent.Width then
Left:=Parent.Width-Width
else
if lLeft<0 then
Left:=0
else
Left:=lLeft;
if lTop+Height>Parent.Height then
Top:=Parent.Height-Height
else
if lTop<0 then
Top:=0
else
Top:=lTop;
{ Left := pOwnStartPoint.X+Mouse.CursorPos.X-pMouseStartPoint.X;
Top := pOwnStartPoint.Y+Mouse.CursorPos.Y-pMouseStartPoint.Y; }
end;
end;
procedure TFotoFrame.CMMouseLeave(var Message:TMessage);
begin
pIsPressed:=False;
end;
//******************************************************************************
// TFrameBase
//******************************************************************************
procedure TFrameBase.SetCoords(X,Y:Integer);
begin
Left:=X-Width div 2;
Top:=Y-Height div 2;
end;
procedure TFrameBase.Free;
begin
inherited Free;
end;
//******************************************************************************
// TFrameObject
//******************************************************************************
procedure TFrameObject.ReleaseAll;
begin
try
{ (LT as TFrameElement).Deactivate;
(LC as TFrameElement).Deactivate;
(LB as TFrameElement).Deactivate;
(CT as TFrameElement).Deactivate;
(CC as TFrameElement).Deactivate;
(CB as TFrameElement).Deactivate;
(RT as TFrameElement).Deactivate;
(RC as TFrameElement).Deactivate;
(RB as TFrameElement).Deactivate; }
finally
end;
end;
procedure TFrameObject.Coordinate(dX,dY:Integer;ElementPos:TElementPositions);
begin
case ElementPos of
epLeftTop:begin
X1:=X1+dX;
if Y1+dY>=0 then
Y1:=Y1+dY
else
Y1:=0;
end;
epLeftCenter:begin
X1:=X1+dX;
end;
epLeftBottom:begin
X1:=X1+dX; Y2:=Y2+dY;
end;
epCenterTop:begin
Y1:=Y1+dY;
end;
epCenterCenter:begin
if (X1+dX>=0) and (X2+dX<=pImage.Width) then
begin
X1:=X1+dX;
X2:=X2+dX;
end;
if (Y1+dY>=0) and (Y2+dY<=pImage.Height) then
begin
Y1:=Y1+dY;
Y2:=Y2+dY;
end;
end;
epCenterBottom:begin
Y2:=Y2+dY;
end;
epRightTop:begin
X2:=X2+dX; Y1:=Y1+dY;
end;
epRightCenter:begin
X2:=X2+dX;
end;
epRightBottom:begin
X2:=X2+dX; Y2:=Y2+dY;
end;
end;
if X1>=X2 then
if dX<0 then
X2:=X1+1
else
X1:=X2-1;
if Y1>=Y2 then
if dY<0 then
Y2:=Y1+1
else
Y1:=Y2-1;
if X1<0 then X1:=0;
if X2>pImage.Width then X2:=pImage.Width;
if Y1<0 then Y1:=0;
if Y2>pImage.Height then Y2:=pImage.Height;
{LT.SetCoords(X1,Y1);
LC.SetCoords(X1,(Y1+Y2) div 2);
LB.SetCoords(X1,Y2);
CT.SetCoords((X1+X2) div 2,Y1);
CC.SetCoords((X1+X2) div 2,(Y1+Y2) div 2);
CB.SetCoords((X1+X2) div 2,Y2);
RT.SetCoords(X2,Y1);
RC.SetCoords(X2,(Y1+Y2) div 2);
RB.SetCoords(X2,Y2);}
end;
procedure TFrameObject.DrawRect;
var r:TRect;
begin
r.Left:=X1;
r.Right:=X2;
r.Top:=Y1;
r.Bottom:=Y2;
{LT.Hide;
LC.Hide;
LB.Hide;
CT.Hide;
CC.Hide;
CB.Hide;
RT.Hide;
RC.Hide;
RB.Hide;}
(pImage as TSelectImage).SetSelectionParams(X2-X1,Y2-Y1);
(pImage as TSelectImage).FormRect((X2+X1) div 2,(Y2+Y1) div 2);
(pImage as TSelectImage).GetSelectedImage;
{ LT.Show;
LC.Show;
LB.Show;
CT.Show;
CC.Show;
CB.Show;
RT.Show;
RC.Show;
RB.Show;}
end;
procedure TFrameObject.SelectRect(AX1,AY1,AX2,AY2:Integer);
begin
X1:=AX1; Y1:=AY1;
X2:=AX2; Y2:=AY2;
Coordinate(0,0,epCenterCenter);
DrawRect;
end;
constructor TFrameObject.Create(AOwner:TSelectImage;AStartRect:TRect);
var
lParams:TFrameElementParams;
begin
inherited Create;
X1:=AStartRect.Left;
X2:=AStartRect.Right;
Y1:=AStartRect.Top;
Y2:=AStartRect.Bottom;
pImage:=AOwner;
lParams.Owner:=pImage;
lParams.Master:=Self;
lParams.Left:=0;
lParams.Top:=0;
lParams.Width:=16;
lParams.Height:=16;
lParams.BorderColor:=clBlack;
lParams.Color:=$0000DCFF;
{
lParams.ElementPos:=epLeftTop;
LT:=TFrameElement.Create(lParams);
lParams.ElementPos:=epLeftCenter;
LC:=TFrameElement.Create(lParams);
lParams.ElementPos:=epLeftBottom;
LB:=TFrameElement.Create(lParams);
lParams.ElementPos:=epCenterTop;
CT:=TFrameElement.Create(lParams);
lParams.ElementPos:=epCenterCenter;
CC:=TFrameElement.Create(lParams);
lParams.ElementPos:=epCenterBottom;
CB:=TFrameElement.Create(lParams);
lParams.ElementPos:=epRightTop;
RT:=TFrameElement.Create(lParams);
lParams.ElementPos:=epRightCenter;
RC:=TFrameElement.Create(lParams);
lParams.ElementPos:=epRightBottom;
RB:=TFrameElement.Create(lParams);
Coordinate(0,0,epCenterCenter);
}
DrawRect;
pTimer:=TTimer.Create(nil);
pTimer.OnTimer:=UpDate;
pTimer.Interval:=10;
StartTimer;
end;
procedure TFrameObject.StartTimer;
begin
try
pTimer.Enabled:=True;
finally
end;
end;
procedure TFrameObject.StopTimer;
begin
try
pTimer.Enabled:=False;
finally
end;
end;
procedure TFrameObject.UpDate(Sender:TObject);
var ChildElements:Array[0..8] of TFrameElement;
i:Integer;
begin
{ ChildElements[0]:=TFrameElement(LT);
ChildElements[1]:=TFrameElement(LC);
ChildElements[2]:=TFrameElement(LB);
ChildElements[3]:=TFrameElement(CT);
ChildElements[4]:=TFrameElement(CC);
ChildElements[5]:=TFrameElement(CB);
ChildElements[6]:=TFrameElement(RT);
ChildElements[7]:=TFrameElement(RC);
ChildElements[8]:=TFrameElement(RB);
i:=0;
while (not ChildElements[i].pIsPressed) and (i<9) do
i:=i+1;
if i<>9 then
ChildElements[i].MoveWithMouse;}
end;
procedure TFrameObject.Free;
begin
StopTimer;
pTimer.Free;
{ LT.Free;
LC.Free;
LB.Free;
CT.Free;
CC.Free;
CB.Free;
RT.Free;
RC.Free;
RB.Free;}
inherited Free;
end;
//******************************************************************************
// TFrameElement
//******************************************************************************
constructor TFrameElement.Create(AParams:TFrameElementParams);
begin
inherited Create(AParams.Owner{.Owner});
Parent:=AParams.Owner as TWinControl;
SetBounds(AParams.Left,AParams.Top,AParams.Width,AParams.Height);
Master:=AParams.Master;
pElementPos:=AParams.ElementPos;
pDefaultCursor:=crDefault;
case pElementPos of
epLeftTop,epRightBottom: pPressedCursor:=crSizeNWSE;
epLeftCenter,epRightCenter: pPressedCursor:=crSizeWE;
epLeftBottom,epRightTop: pPressedCursor:=crSizeNESW;
epCenterTop,epCenterBottom: pPressedCursor:=crSizeNS;
epCenterCenter: pPressedCursor:=crSizeAll;
end;
pColor:=AParams.Color;
pBorderColor:=AParams.BorderColor;
end;
procedure TFrameElement.WMLButtonDown(var Message:TWMMouse);
begin
Master.ReleaseAll; // Снимаем прочие функции, чтобы выполнялась только данная
pIsPressed:=True;
Cursor:=pPressedCursor;
pMouseStartPoint:=Mouse.CursorPos;
pOwnStartPoint:=Point(Left,Top);
end;
procedure TFrameElement.WMLButtonUp(var Message:TWMMouse);
begin
Deactivate;
Master.DrawRect;
end;
procedure TFrameElement.WMLButtonDblClk(var Message: TWMLButtonDblClk);
begin
pIsPressed:=False;
Master.DrawRect;
end;
procedure TFrameElement.DrawElement;
begin
Canvas.Lock;
try
inherited Paint;
Canvas.Brush.Color:=pColor;
Canvas.Pen.Color:=pBorderColor;
Canvas.Rectangle(0,0,Width,Height);
finally
Canvas.Unlock;
end;
end;
procedure TFrameElement.Deactivate;
begin
Cursor:=pDefaultCursor;
pIsPressed:=False;
end;
procedure TFrameElement.Paint;
begin
DrawElement;
inherited Paint;
end;
procedure TFrameElement.Repaint;
begin
inherited Paint;
end;
procedure TFrameElement.MoveWithMouse;
var
lLeft,lTop:Integer;
begin
if pIsPressed then
begin
lLeft := Mouse.CursorPos.X-pMouseStartPoint.X;
lTop := Mouse.CursorPos.Y-pMouseStartPoint.Y;
pMouseStartPoint:=Mouse.CursorPos;
Master.Coordinate(lLeft,lTop,pElementPos);
end;
end;
//******************************************************************************
// TSelectImage
//******************************************************************************
procedure TSelectImage.Paint;
begin
inherited Paint;
begin
Canvas.Canvas.Lock;
Canvas.Pen.Color:=pBrushColor;
Canvas.Pen.Style:=psSolid;
Canvas.Pen.Color:=pPenColor;
Canvas.Pen.Style:=pPenStyle;
Canvas.MoveTo(pRect.Left-1,pRect.Top-1);
Canvas.LineTo(pRect.Left-1,pRect.Bottom+1);
Canvas.LineTo(pRect.Right+1,pRect.Bottom+1);
Canvas.LineTo(pRect.Right+1,pRect.Top-1);
Canvas.LineTo(pRect.Left-1,pRect.Top-1);
Canvas.Canvas.Unlock;
end;
end;
constructor TSelectImage.Create(AOwner:TComponent;AResultImage:TImage;APenColor:TColor;ABrushColor:TColor;APenStyle:TPenStyle = psSolid);
begin
inherited Create(AOwner);
Parent:=AOwner as TWinControl;
pPenColor:=APenColor;
pBrushColor:=ABrushColor;
pPenStyle:=APenStyle;
XCenter:=Width div 2;
YCenter:=Height div 2;
OnMouseDown:=pMouseDown;
pResultImage:=AResultImage;
pScale:=1.5;
pTotalScale:=1;
// Избавляемся от контекстного меню и пр.
Properties.PopupMenuLayout.MenuItems:=[];
Style.HotTrack:=False;
BorderStyle:=cxcbsNone;
BorderWidth:=0;
// расстояние, на которое необх. отступать от краев канвы для получения корректного изображения
pBorderWidth:=2;
end;
procedure TSelectImage.FormRect(AXCenter,AYCenter:Integer);
begin
XCenter:=AXCenter;
YCenter:=AYCenter;
pRect.Left:=XCenter-pSelWidth div 2;
pRect.Right:=XCenter+pSelWidth div 2;
pRect.Top:=YCenter-pSelHeight div 2;
pRect.Bottom:=YCenter+pSelHeight div 2;
if pRect.Left<0 then
begin
pRect.Right:=pRect.Right-pRect.Left;
pRect.Left:=0;
end;
if pRect.Right>Width then
begin
pRect.Left:=pRect.Left-pRect.Right+Width;
pRect.Right:=Width;
end;
if pRect.Top<0 then
begin
pRect.Bottom:=pRect.Bottom-pRect.Top;
pRect.Top:=0;
end;
if pRect.Bottom>Height then
begin
pRect.Top:=pRect.Top-pRect.Bottom+Height;
pRect.Bottom:=Height;
end;
Parent.SetFocus;
Refresh; // рисуем рамку
end;
procedure TSelectImage.SetSelectionParams(ASelWidth,ASelHeight:Integer);
begin
pSelWidth:=ASelWidth;
pSelHeight:=ASelHeight;
if pSelWidth>Width then pSelWidth:=Width;
if pSelHeight>Height then pSelHeight:=Height;
pResultImage.Picture.Bitmap.Height:=ASelHeight;
pResultImage.Picture.Bitmap.Width:=ASelWidth;
end;
procedure TSelectImage.pMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
{ case Button of
mbLeft: begin
// pActive:=True;
FormRect(X,Y);
Refresh;
GetSelectedImage;
end;
end; }
end;
procedure TSelectImage.ShowActualSize;
var OldWidth, OldHeight:Integer;
begin
OldWidth:=Width;
OldHeight:=Height;
Properties.Stretch:=False;
AutoSize:=True;
Align:=alNone;
pTotalScale:=Max(Width/OldWidth,Height/OldHeight);
end;
procedure TSelectImage.FitOnParent;
begin
Properties.Stretch:=True;
AutoSize:=False;
Align:=alClient;
pTotalScale:=1;
if (Parent.ClassType=TScrollBox) then
begin
(Parent as TScrollBox).HorzScrollBar.Visible:=False;
(Parent as TScrollBox).VertScrollBar.Visible:=False;
end;
end;
procedure TSelectImage.GetSelectedImage;
var Dest:TRect;
begin
Dest.Left:=0;
Dest.Top:=0;
Dest.Right:=pSelWidth;
Dest.Bottom:=pSelHeight;
pResultImage.Canvas.CopyRect(Dest,Canvas.Canvas,pRect);
end;
procedure TSelectImage.SizePlus;
begin
Align:=alNone;
Properties.Stretch:=True;
Width:=round(Width*pScale);
Height:=round(Height*pScale);
pTotalScale:=pTotalScale*pScale;
end;
procedure TSelectImage.SizeMinus;
begin
if pTotalScale=1 then Exit;
Align:=alNone;
AutoSize:=False;
Properties.Stretch:=True;
Width:=round(Width/pScale);
Height:=round(Height/pScale);
pTotalScale:=pTotalScale/pScale;
if round(pTotalScale*100)<=100 then
FitOnParent;
end;
procedure TSelectImage.Free;
begin
inherited Free;
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: Controller do lado Cliente relacionado à tabela [COMPRA_FORNECEDOR_COTACAO]
The MIT License
Copyright: Copyright (C) 2014 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit CompraFornecedorCotacaoController;
{$MODE Delphi}
interface
uses
Classes, Dialogs, SysUtils, DB, LCLIntf, LCLType, LMessages, Forms, Controller,
VO, ZDataset, CompraFornecedorCotacaoVO, CompraCotacaoVO,
CompraCotacaoDetalheVO;
type
TCompraFornecedorCotacaoController = class(TController)
private
public
class function Consulta(pFiltro: String; pPagina: String): TZQuery;
class function ConsultaLista(pFiltro: String): TListaCompraFornecedorCotacaoVO;
class function ConsultaObjeto(pFiltro: String): TCompraFornecedorCotacaoVO;
class procedure Insere(pObjeto: TCompraFornecedorCotacaoVO);
class function Altera(pObjeto: TCompraCotacaoVO): Boolean;
class function Exclui(pId: Integer): Boolean;
end;
implementation
uses UDataModule, T2TiORM;
var
ObjetoLocal: TCompraFornecedorCotacaoVO;
class function TCompraFornecedorCotacaoController.Consulta(pFiltro: String; pPagina: String): TZQuery;
begin
try
ObjetoLocal := TCompraFornecedorCotacaoVO.Create;
Result := TT2TiORM.Consultar(ObjetoLocal, pFiltro, pPagina);
finally
ObjetoLocal.Free;
end;
end;
class function TCompraFornecedorCotacaoController.ConsultaLista(pFiltro: String): TListaCompraFornecedorCotacaoVO;
begin
try
ObjetoLocal := TCompraFornecedorCotacaoVO.Create;
Result := TListaCompraFornecedorCotacaoVO(TT2TiORM.Consultar(ObjetoLocal, pFiltro, True));
finally
ObjetoLocal.Free;
end;
end;
class function TCompraFornecedorCotacaoController.ConsultaObjeto(pFiltro: String): TCompraFornecedorCotacaoVO;
begin
try
Result := TCompraFornecedorCotacaoVO.Create;
Result := TCompraFornecedorCotacaoVO(TT2TiORM.ConsultarUmObjeto(Result, pFiltro, True));
finally
end;
end;
class procedure TCompraFornecedorCotacaoController.Insere(pObjeto: TCompraFornecedorCotacaoVO);
var
UltimoID: Integer;
begin
try
UltimoID := TT2TiORM.Inserir(pObjeto);
Consulta('ID = ' + IntToStr(UltimoID), '0');
finally
end;
end;
class function TCompraFornecedorCotacaoController.Altera(pObjeto: TCompraCotacaoVO): Boolean;
var
CompraCotacao: TCompraCotacaoVO;
CompraConfirmaFornecedorCotacao: TCompraFornecedorCotacaoVO;
Current: TCompraCotacaoDetalheVO;
i, j: Integer;
begin
try
for i := 0 to pObjeto.ListaCompraFornecedorCotacao.Count - 1 do
begin
CompraConfirmaFornecedorCotacao := pObjeto.ListaCompraFornecedorCotacao[i];
Result := TT2TiORM.Alterar(CompraConfirmaFornecedorCotacao);
// Itens de cotação do fornecedor
for j := 0 to CompraConfirmaFornecedorCotacao.ListaCompraCotacaoDetalhe.Count - 1 do
begin
Current := CompraConfirmaFornecedorCotacao.ListaCompraCotacaoDetalhe[j];
Result := TT2TiORM.Alterar(Current);
end;
end;
Result := TT2TiORM.Alterar(pObjeto);
finally
end;
end;
class function TCompraFornecedorCotacaoController.Exclui(pId: Integer): Boolean;
var
ObjetoLocal: TCompraFornecedorCotacaoVO;
begin
try
ObjetoLocal := TCompraFornecedorCotacaoVO.Create;
ObjetoLocal.Id := pId;
Result := TT2TiORM.Excluir(ObjetoLocal);
finally
FreeAndNil(ObjetoLocal)
end;
end;
initialization
Classes.RegisterClass(TCompraFornecedorCotacaoController);
finalization
Classes.UnRegisterClass(TCompraFornecedorCotacaoController);
end.
|
unit TESTORCAMENTO.Entidade.Model;
interface
uses
DB,
Classes,
SysUtils,
Generics.Collections,
/// orm
ormbr.types.blob,
ormbr.types.lazy,
ormbr.types.mapping,
ormbr.types.nullable,
ormbr.mapping.Classes,
ormbr.mapping.register,
ormbr.mapping.attributes;
type
[Entity]
[Table('TESTORCAMENTO', '')]
[PrimaryKey('CODIGO', NotInc, NoSort, False, 'Chave primária')]
TTESTORCAMENTO = class
private
{ Private declarations }
FCODIGO: String;
FIDORCAMENTO: Integer;
FDESCRICAO: nullable<String>;
FDATA_CADASTRO: TDateTime;
FULTIMA_ATUALIZACAO: TDateTime;
function getCODIGO: String;
function getDATA_CADASTRO: TDateTime;
function getULTIMA_ATUALIZACAO: TDateTime;
public
{ Public declarations }
[Restrictions([NotNull])]
[Column('CODIGO', ftString, 64)]
[Dictionary('CODIGO', 'Mensagem de validação', '', '', '', taLeftJustify)]
property CODIGO: String read getCODIGO write FCODIGO;
[Restrictions([NotNull])]
[Column('IDORCAMENTO', ftInteger)]
[Dictionary('IDORCAMENTO', 'Mensagem de validação', '', '', '', taCenter)]
property IDORCAMENTO: Integer read FIDORCAMENTO write FIDORCAMENTO;
[Column('DESCRICAO', ftString, 225)]
[Dictionary('DESCRICAO', 'Mensagem de validação', '', '', '',
taLeftJustify)]
property DESCRICAO: nullable<String> read FDESCRICAO write FDESCRICAO;
[Restrictions([NotNull])]
[Column('DATA_CADASTRO', ftDateTime)]
[Dictionary('DATA_CADASTRO', 'Mensagem de validação', 'Now', '',
'!##/##/####;1;_', taCenter)]
property DATA_CADASTRO: TDateTime read getDATA_CADASTRO write FDATA_CADASTRO;
[Restrictions([NotNull])]
[Column('ULTIMA_ATUALIZACAO', ftDateTime)]
[Dictionary('ULTIMA_ATUALIZACAO', 'Mensagem de validação', 'Now', '',
'!##/##/####;1;_', taCenter)]
property ULTIMA_ATUALIZACAO: TDateTime read getULTIMA_ATUALIZACAO
write FULTIMA_ATUALIZACAO;
end;
implementation
{ TTESTORCAMENTO }
function TTESTORCAMENTO.getCODIGO: String;
begin
if FCODIGO = EmptyStr then
FCODIGO := TGUID.NewGuid.ToString;
Result := FCODIGO;
end;
function TTESTORCAMENTO.getDATA_CADASTRO: TDateTime;
begin
if FDATA_CADASTRO = StrToDateTime('30/12/1899 00:00') then
FDATA_CADASTRO := Now;
Result := FDATA_CADASTRO;
end;
function TTESTORCAMENTO.getULTIMA_ATUALIZACAO: TDateTime;
begin
FULTIMA_ATUALIZACAO := Now;
Result := FULTIMA_ATUALIZACAO;
end;
initialization
TRegisterClass.RegisterEntity(TTESTORCAMENTO)
end.
|
unit uImageLoader;
interface
uses SysUtils, Classes, System.Generics.Collections,
FMX.Types, FMX.Objects, FMX.Controls, AsyncTask, AsyncTask.HTTP, FMX.Graphics;
type
TLoadQueueItem = record
ImageURL: String;
Bitmap: TBitmap;
end;
TLoadQueue = TList<TLoadQueueItem>;
TImageLoader = class(TObject)
private
fQueue: TLoadQueue;
fWorker: TTimer;
fActiveItem: TLoadQueueItem;
fIsWorking: Boolean;
procedure QueueWorkerOnTimer(ASender: TObject);
public
constructor Create;
destructor Destroy; override;
procedure LoadImage(ABitmap: TBitmap; AImageURL: string); overload;
property ActiveItem: TLoadQueueItem read fActiveItem;
property IsWorking: Boolean read fIsWorking;
end;
var
DefaultImageLoader: TImageLoader;
implementation
var
FCachedImages: TObjectDictionary<String, TBitmap>;
{ TImageLoader }
constructor TImageLoader.Create;
begin
inherited Create;
fQueue := TLoadQueue.Create;
fIsWorking := False;
fWorker := TTimer.Create(nil);
fWorker.Enabled := False;
fWorker.Interval := 50;
fWorker.OnTimer := QueueWorkerOnTimer;
fWorker.Enabled := True;
end;
destructor TImageLoader.Destroy;
begin
fWorker.Free;
fQueue.Free;
inherited;
end;
procedure TImageLoader.LoadImage(ABitmap: TBitmap; AImageURL: string);
var
item: TLoadQueueItem;
begin
item.ImageURL := AImageURL;
item.Bitmap := ABitmap;
fQueue.Add(item);
end;
procedure TImageLoader.QueueWorkerOnTimer(ASender: TObject);
var
lBitmap: TBitmap;
Mem: TMemoryStream;
begin
fWorker.Enabled := False;
if (fQueue.Count > 0) and (not fIsWorking) then
begin
fIsWorking := True;
fActiveItem := fQueue[0];
fQueue.Delete(0);
lBitmap := nil;
if FCachedImages.TryGetValue(fActiveItem.ImageURL, lBitmap) and (lBitmap <> nil) then
begin
Mem := TMemoryStream.Create;
lBitmap.SaveToStream(Mem);
Mem.Seek(0, 0);
// fActiveItem.Bitmap.Assign(lBitmap);
fActiveItem.Bitmap.LoadFromStream(Mem);
fIsWorking := False;
Mem.Free;
end else
begin
AsyncTask.Run(
THttpAsyncTaskBitmap.Create(fActiveItem.ImageURL),
// Finished
procedure (ATask: IAsyncTask)
var
fBitmap: TBitmap;
fMem: TMemoryStream;
begin
lBitmap := TBitmap.Create(0, 0);
fBitmap := (ATask as IHttpBitmapResponse).Bitmap;
if fBitmap <> nil then
begin
lBitmap.Assign(fBitmap);
FCachedImages.AddOrSetValue(fActiveItem.ImageURL, lBitmap);
fMem := TMemoryStream.Create;
lBitmap.SaveToStream(fMem);
fMem.Seek(0, 0);
fActiveItem.Bitmap.LoadFromStream(fMem);
fMem.Free;
end;
fIsWorking := False;
end
);
end;
end;
fWorker.Enabled := True;
end;
initialization
FCachedImages := TObjectDictionary<String, TBitmap>.Create([], 10);
DefaultImageLoader := TImageLoader.Create;
finalization
FCachedImages.Free;
DefaultImageLoader.Free;
end.
|
unit ZipInterfaceAbbrevia;
{-
********************************************************************************
******* XLSReadWriteII V3.00 *******
******* *******
******* Copyright(C) 1999,2006 Lars Arvidsson, Axolot Data *******
******* *******
******* email: components@axolot.com *******
******* URL: http://www.axolot.com *******
********************************************************************************
** Users of the XLSReadWriteII component must accept the following **
** disclaimer of warranty: **
** **
** XLSReadWriteII is supplied as is. The author disclaims all warranties, **
** expressedor implied, including, without limitation, the warranties of **
** merchantability and of fitness for any purpose. The author assumes no **
** liability for damages, direct or consequential, which may result from the **
** use of XLSReadWriteII. **
********************************************************************************
}
{$B-}
{$H+}
{$R-}
{$I XLSRWII2.inc}
interface
uses Classes, SysUtils,
ZipInterface, AbUtils, AbBase, AbBrowse, AbZBrows, AbUnzper;
//* Unzip interface that uses the free Abbrevia zip library.
//* For more info and download of Abbrevia, see ~[linkExtern URI[http://sourceforge.net/projects/tpabbrevia/]]
type TXLSReadZipAbbrevia = class(TXLSReadZip)
private
FZIP: TAbUnZipper;
public
//* ~exclude
constructor Create;
//* ~exclude
destructor Destroy; override;
//* Open the zip file on disk.
//* ~param Zipfile The zip file to be read.
procedure OpenZip(Zipfile: WideString); override;
//* Closes the zip file.
procedure CloseZip; override;
//* Reads a comressed file from the zip archive to a stream.
//* ~param Filename The file to read.
//* ~param Stream The destination stream to unzip the compressed file to.
//* ~result True if the file could be read to the stream.
function ReadFileToStream(Filename: WideString; Stream: TStream): boolean; override;
end;
implementation
{ TXLSReadZipAbbrevia }
procedure TXLSReadZipAbbrevia.CloseZip;
begin
FZIP.CloseArchive;
end;
constructor TXLSReadZipAbbrevia.Create;
begin
FZIP := TAbUnZipper.Create(Nil);
end;
destructor TXLSReadZipAbbrevia.Destroy;
begin
FZIP.Free;
inherited;
end;
procedure TXLSReadZipAbbrevia.OpenZip(Zipfile: WideString);
begin
// ForceType and ArchiveType must be set, as Abbrevia otherwise not will
// recognize the file as a zip archive, as the extension is .ODS
FZIP.ForceType := True;
FZIP.ArchiveType := atZip;
FZIP.FileName := Zipfile;
end;
function TXLSReadZipAbbrevia.ReadFileToStream(Filename: WideString; Stream: TStream): boolean;
begin
try
FZIP.ExtractToStream(Filename,Stream);
Result := True;
except
Result := False;
end;
end;
end.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.