text
stringlengths
14
6.51M
{$i deltics.IO.text.inc} unit Deltics.IO.Text.Unicode; interface uses Deltics.StringTypes, Deltics.IO.Text.TextReader, Deltics.IO.Text.Interfaces, Deltics.IO.Text.Types; type TUnicodeReader = class(TTextReader, IUnicodeReader) // ITextReader protected function get_EOF: Boolean; override; function get_Location: TCharLocation; override; // IUnicodeReader protected function IsWhitespace(const aChar: WideChar): Boolean; procedure MoveBack; function NextChar: WideChar; function NextCharAfter(const aFilter: TWideCharFilterFn): WideChar; function NextCharSkippingWhitespace: WideChar; function PeekChar: WideChar; function PeekCharSkippingWhitespace: WideChar; function ReadLine: UnicodeString; procedure Skip(const aNumChars: Integer); procedure SkipWhitespace; procedure SkipChar; private fPrevChar: WideChar; fActiveEOF: TEofMethod; fActiveReader: TWideCharReaderMethod; fLocation: TCharLocation; fPrevLocation: TCharLocation; fActiveLocation: PCharLocation; function _InheritedEOF: Boolean; function _NotEOF: Boolean; function _ReadPrevChar: WideChar; function _ReadNextChar: WideChar; procedure DecodeUtf8(const aInputBuffer: Pointer; const aInputBytes: Integer; const aDecodeBuffer: Pointer; const aMaxDecodedBytes: Integer; var aInputBytesDecoded: Integer; var aDecodedBytes: Integer); procedure DecodeUtf16(const aInputBuffer: Pointer; const aInputBytes: Integer; const aDecodeBuffer: Pointer; const aMaxDecodedBytes: Integer; var aInputBytesDecoded: Integer; var aDecodedBytes: Integer); protected property EOF: TEofMethod read fActiveEOF; property Location: PCharLocation read fActiveLocation; property ReadChar: TWideCharReaderMethod read fActiveReader; public procedure AfterConstruction; override; end; implementation uses SysUtils, Deltics.Exceptions, Deltics.Memory, Deltics.ReverseBytes, Deltics.StringEncodings, Deltics.Unicode; type TEncoding = Deltics.StringEncodings.TEncoding; TByteArray = array of Byte; TWordArray = array of Word; procedure TUnicodeReader.AfterConstruction; begin inherited; fActiveEOF := _InheritedEOF; fActiveReader := _ReadNextChar; fActiveLocation := @fLocation; case SourceEncoding.Codepage of cpUtf16 : SetDecoder(DecodeUtf16); cpUtf16LE : SetDecoder(NIL); cpUtf8 : SetDecoder(DecodeUtf8); else raise ENotSupported.Create('UnicodeReader does not support reading from sources with encoding ' + IntToStr(SourceEncoding.Codepage)); end; fLocation.Line := 1; end; (* procedure TUtf8TextReader.DecodeMBCS; begin end; var i: Integer; dp: Integer; s: ANSIString; b: Byte; wc: array of WideChar; wcLen: Integer; begin SetLength(fUtf8, fUtf8Size + (3 * fBufferSize)); dp := fUtf8Pos; i := 0; while (i < fBufferSize) do begin b := Byte(fBuffer[i]); if (b < $80) then begin fUtf8[dp] := Utf8Char(b); Inc(dp); Inc(i); CONTINUE; end; s := ''; while (b >= $80) do begin s := s + ANSIChar(b); Inc(i); if (i = fBufferSize) then begin if (fBufferSize < fBlockSize) then BREAK; ReadBlock; if (fBufferSize > 0) then begin SetLength(fUtf8, dp + (3 * fBufferSize)); i := 0; end; end; b := Byte(fBuffer[i]); end; SetLength(wc, Length(s) * 2); wcLen := MultiByteToWideChar(fCodePage, 0, @s[1], Length(s), @wc[0], Length(wc)); Move(wc[0], fUtf8[dp], wcLen * 2); Inc(dp, wcLen); end; SetLength(fUtf8, dp); fUtf8Size := dp; end; *) (* function TUtf8TextReader.DecodeUTF16BE: Integer; type PByte = array of Byte; TWordArray = array of Word; var i: Integer; dp: Integer; wc: Word; begin if NOT Assigned(fData) then GetMem(fData, fBufferSize); dp := 0; for i := 0 to Pred(fBufferSize) div 2 do begin wc := Swap(TWordArray(fBuffer)[i]); case wc of $0000..$007f : begin PByte(fData)[dp] := Byte(wc); Inc(dp); end; $0080..$07ff : begin PByte(fData)[dp] := Byte($c0 or (wc shr 6)); PByte(fData)[dp + 1] := Byte($80 or (wc and $3f)); Inc(dp, 2); end; $0800..$ffff : begin PByte(fData)[dp] := Byte($e0 or (wc shr 12)); PByte(fData)[dp + 1] := Byte($80 or ((wc shr 6) and $3f)); PByte(fData)[dp + 2] := Byte($80 or (wc and $3f)); Inc(dp, 3); end; //TODO: Correctly decode surrogate pairs end; end; result := dp; end; function TUtf8TextReader.DecodeUTF16LE: Integer; type PByte = array of Byte; TWordArray = array of Word; var i: Integer; dp: Integer; wc: Word; begin if NOT Assigned(fData) then GetMem(fData, fBufferSize); dp := 0; for i := 0 to Pred(fBufferLimit) div 2 do begin wc := TWordArray(fBuffer)[i]; case wc of $0000..$007f : begin PByte(fData)[dp] := Byte(wc); Inc(dp); end; $0080..$07ff : begin PByte(fData)[dp] := Byte($c0 or (wc shr 6)); PByte(fData)[dp + 1] := Byte($80 or (wc and $3f)); Inc(dp, 2); end; $0800..$ffff : begin PByte(fData)[dp] := Byte($e0 or (wc shr 12)); PByte(fData)[dp + 1] := Byte($80 or ((wc shr 6) and $3f)); PByte(fData)[dp + 2] := Byte($80 or (wc and $3f)); Inc(dp, 3); end; //TODO: Correctly decode surrogate pairs end; end; result := dp; end; *) procedure TUnicodeReader.DecodeUtf16(const aInputBuffer: Pointer; const aInputBytes: Integer; const aDecodeBuffer: Pointer; const aMaxDecodedBytes: Integer; var aInputBytesDecoded: Integer; var aDecodedBytes: Integer); begin Memory.Copy(aInputBuffer, aInputBytes, aDecodeBuffer); ReverseBytes(PWord(aDecodeBuffer), aInputBytes div 2); aInputBytesDecoded := aInputBytes; aDecodedBytes := aInputBytes; end; procedure TUnicodeReader.DecodeUtf8(const aInputBuffer: Pointer; const aInputBytes: Integer; const aDecodeBuffer: Pointer; const aMaxDecodedBytes: Integer; var aInputBytesDecoded: Integer; var aDecodedBytes: Integer); var inBuf: PUtf8Char; outBuf: PWideChar; inChars: Integer; outChars: Integer; begin inBuf := PUtf8Char(aInputBuffer); outBuf := PWideChar(aDecodeBuffer); inChars := aInputBytes; outChars := aMaxDecodedBytes div 2; Unicode.Utf8ToUtf16(inBuf, inChars, outBuf, outChars); aInputBytesDecoded := aInputBytes - inChars; aDecodedBytes := aMaxDecodedBytes - (outChars * 2); end; function TUnicodeReader.get_EOF: Boolean; begin result := fActiveEOF; end; function TUnicodeReader.get_Location: TCharLocation; begin result := Location^; end; procedure TUnicodeReader.MoveBack; begin fActiveEOF := _NotEOF; fActiveReader := _ReadPrevChar; fActiveLocation := @fPrevLocation; end; function TUnicodeReader.NextChar: WideChar; begin result := ReadChar; end; function TUnicodeReader.IsWhitespace(const aChar: WideChar): Boolean; begin result := ((Word(aChar) and $ff00) = 0) and (AnsiChar(aChar) in [#9, #10, #11, #12, #13, #32]); end; function TUnicodeReader.NextCharAfter(const aFilter: TWideCharFilterFn): WideChar; begin while NOT EOF do begin result := ReadChar; if NOT aFilter(result) then EXIT; end; // If we reach this point then EOF is TRUE and we found nothing but whitespace result := #0; end; function TUnicodeReader.NextCharSkippingWhitespace: WideChar; begin result := NextCharAfter(IsWhitespace); end; function TUnicodeReader.PeekChar: WideChar; begin result := NextChar; MoveBack; end; function TUnicodeReader.PeekCharSkippingWhitespace: WideChar; begin result := NextCharSkippingWhitespace; MoveBack; end; function TUnicodeReader.ReadLine: UnicodeString; var currentLine: Integer; c: WideChar; begin result := ''; currentLine := Location.Line; while (Location.Line = currentLine) and NOT EOF do begin c := NextChar; case Word(c) of 10..12 : CONTINUE; 13 : begin c := NextChar; if c <> #10 then MoveBack; end; else result := result + c; end; end; end; function TUnicodeReader._InheritedEOF: Boolean; begin result := inherited EOF; end; function TUnicodeReader._NotEOF: Boolean; begin result := FALSE; end; function TUnicodeReader._ReadNextChar: WideChar; begin result := WideChar(ReadWord); Memory.Copy(@fLocation, sizeof(TCharLocation), @fPrevLocation); if Word(result) < $0080 then // IsAscii begin case Word(result) of 10 : if Word(fPrevChar) <> 13 then begin Inc(fLocation.Line); fLocation.Character := 0; end; 11..13 : begin Inc(fLocation.Line); fLocation.Character := 0; end; else Inc(fLocation.Character); end; end else if (Word(result) >= $dc00) and (Word(result) <= $dfff) then // IsLoSurrogate Inc(fLocation.Character); fActiveLocation := @fLocation; fPrevChar := result; end; function TUnicodeReader._ReadPrevChar: WideChar; begin result := fPrevChar; fActiveEOF := _InheritedEOF; fActiveReader := _ReadNextChar; fActiveLocation := @fLocation; end; procedure TUnicodeReader.Skip(const aNumChars: Integer); var i: Integer; begin for i := 1 to aNumChars do SkipChar; end; procedure TUnicodeReader.SkipChar; begin NextChar; end; procedure TUnicodeReader.SkipWhitespace; begin NextCharSkippingWhitespace; if NOT EOF then MoveBack; end; (* function TUtf8TextReader.NextRealChar(var aWhitespace: String): Utf8Char; var remaining: integer; begin aWhitespace := ''; remaining := MakeDataAvailable; while NOT fEOF do begin result := fUtf8[fUtf8Pos]; IncPos(remaining); if NOT (result in fWhitespace) then EXIT; aWhitespace := aWhitespace + STR.FromUtf8(result); end; // If we reach this point then EOF is TRUE - we found nothing but whitespace result := #0; end; procedure TUtf8TextReader.SkipWhitespace(var aWhitespace: String); var l: Integer; c: Utf8Char; s: Utf8String; remaining: integer; begin l := 0; s := ''; remaining := MakeDataAvailable; while NOT fEOF do begin c := fUtf8[fUtf8Pos]; IncPos(remaining); if (c in fWhitespace) then begin Inc(l); if (l > Length(s)) then SetLength(s, Length(s) + 256); s[l] := c; end else begin SetLength(s, l); aWhitespace := STR.FromUtf8(s); MoveBack; EXIT; end; end; // If we reach this point then EOF is TRUE - we found nothing but whitespace end; function TUtf8TextReader.PeekRealChar(var aWhitespace: String): Utf8Char; begin result := NextRealChar(aWhitespace); MoveBack; end; function TUtf8TextReader.NextWideChar(var aWhitespace: String): WideChar; begin while NOT fEOF do begin result := NextWideChar; if NOT (ANSIChar(result) in fWhitespace) then EXIT; aWhitespace := aWhitespace + result; end; result := #0; end; *) end.
unit HotelsTypesForm; interface uses Forms, Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData, cxEdit, DB, cxDBData, cxGridLevel, cxClasses, cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, TB2Dock, TB2Toolbar, ComCtrls, Classes, Controls, ActnList, TB2Item; type TTypesForm = class(TForm) cxGrid1DBTableView1: TcxGridDBTableView; cxGrid1Level1: TcxGridLevel; cxGrid1: TcxGrid; cxGrid1DBTableView1name: TcxGridDBColumn; cxGrid1DBTableView1type_id: TcxGridDBColumn; TBDock1: TTBDock; TBToolbar1: TTBToolbar; StatusBar1: TStatusBar; ActionList: TActionList; Ins: TAction; Copy: TAction; Edit: TAction; Del: TAction; TBItem1: TTBItem; TBItem2: TTBItem; TBItem3: TTBItem; TBItem4: TTBItem; TBSubmenuItem1: TTBSubmenuItem; TBSeparatorItem1: TTBSeparatorItem; TBItem5: TTBItem; TBItem6: TTBItem; TBItem7: TTBItem; TBItem8: TTBItem; TBSeparatorItem2: TTBSeparatorItem; TBItem9: TTBItem; ReFrash: TAction; private { Private declarations } public { Public declarations } end; function GetTypesForm: Integer; implementation uses HotelsDataModule, HotelsMainForm; {$R *.dfm} function GetTypesForm: Integer; var Form: TTypesForm; begin Form := TTypesForm.Create(Application); try Result := Form.ShowModal; finally Form.Free; end; end; end.
{ complete compress } program compressprog (input, output); const ENDFILE = -1; NEWLINE = 10; { ASCII value } TILDE = 126; type character = -1..127; { ASCII, plus ENDFILE } { getc -- get one character from standard input } function getc (var c : character) : character; var ch : char; begin if (eof) then c := ENDFILE else if (eoln) then begin readln; c := NEWLINE end else begin read(ch); c := ord(ch) end; getc := c end; { putc -- put one character on standard output } procedure putc (c : character); begin if (c = NEWLINE) then writeln else write(chr(c)) end; { min -- compute minimum of two integers } function min(x, y : integer) : integer; begin if (x < y) then min := x else min := y end; { compress -- compress standard input } procedure compress; const WARNING = TILDE; { ~ } var c, lastc : character; n : integer; { putrep -- put out representation of run of n 'c's } procedure putrep (N : integer; c : character); const MAXREP = 26; { assuming 'A'..'Z' } THRESH = 4; begin while (n >= THRESH) or ((c = WARNING) and (n > 0)) do begin putc(WARNING); putc(min(n, MAXREP) - 1 + ord('A')); putc(c); n := n - MAXREP end; for n := n downto 1 do putc(c) end; begin n := 1; lastc := getc(lastc); while (lastc <> ENDFILE) do begin if (getc(c) = ENDFILE) then begin if (n > 1) or (lastc = WARNING) then putrep(n, lastc) else putc(lastc) end else if (c = lastc) then n := n + 1 else if (n > 1) or (lastc = WARNING) then begin putrep(n, lastc); n := 1 end else putc(lastc); lastc := c end end; begin { main program } compress end.
{ Convert LIGH record with mesh to 1) STAT: duplicate mesh to a new STAT record and duplicate all references and point them to that STAT 2) MISC: convert LIGH record to MISC (LIGH is removed, references redirected to the newly created MISC) } unit UserScript; var baserecord: IInterface; //============================================================================ function Initialize: integer; var i: integer; begin i := MessageDlg('Copy light records to STAT [YES] or MISC [NO]?', mtConfirmation, [mbYes, mbNo, mbCancel], 0); if i = mrYes then begin // LoadScreenHelmetDaedric [STAT:0010FCCE] baserecord := RecordByFormID(FileByIndex(0), $0010FCCE, True) end else if i = mrNo then begin // BasicPlate01 "Plate" [MISC:000E2617] baserecord := RecordByFormID(FileByIndex(0), $000E2617, True) end else begin Result := 1; Exit; end; if not Assigned(baserecord) then begin AddMessage('Can not find base record'); Result := 1; Exit; end; end; //============================================================================ function Process(e: IInterface): integer; var r, ref: IInterface; oldid, newid: string; i, formid: integer; begin if Signature(e) <> 'LIGH' then Exit; if not ElementExists(e, 'Model') then Exit; r := wbCopyElementToFile(baserecord, GetFile(e), True, True); if not Assigned(r) then begin AddMessage('Can not copy base record as new'); Result := 1; Exit; end; oldid := GetElementEditValues(e, 'EDID'); newid := StringReplace(oldid, 'light', '', [rfReplaceAll, rfIgnoreCase]); if SameText(oldid, newid) then newid := newid + 'LIGH'; SetElementEditValues(r, 'EDID', newid); SetElementEditValues(r, 'Model\MODL', GetElementEditValues(e, 'Model\MODL')); if Signature(r) = 'MISC' then begin SetElementEditValues(r, 'FULL', GetElementEditValues(e, 'EDID')); SetElementEditValues(r, 'DATA\Value', '1'); SetElementEditValues(r, 'DATA\Weight', '1'); formid := GetLoadOrderFormID(e); RemoveNode(e); SetLoadOrderFormID(r, formid); end else begin // remove mesh from LIGH RemoveElement(e, 'Model'); // copy references for STAT for i := 0 to ReferencedByCount(e) - 1 do begin // copy reference and point to STAT ref := wbCopyElementToFile(ReferencedByIndex(e, i), GetFile(e), True, True); SetElementEditValues(ref, 'NAME', Name(r)); // remove scale from LIGH reference since it has no mesh now RemoveElement(ReferencedByIndex(e, i), 'XSCL'); end; end; end; end.
unit uRTTIDemoClass; interface type TRTTIDemoClass = class private FPrivateField: string; FPublicProperty: string; FIndexedProperty: array of string; procedure PrivateMethod; procedure SetPublicProperty(const Value: string); function GetIndexedProperty(aIndex: integer): string; procedure SetIndexedProperty(aIndex: integer; const Value: string); protected procedure ProtectedMethod; public PublicField: Double; constructor Create; procedure PublicMethod; function SomeFunction: string; procedure PublicMethodWithParams(aString: string; aExtended: Extended); property PublicProperty: string read FPublicProperty write SetPublicProperty; property IndexedProperty[aIndex: integer]: string read GetIndexedProperty write SetIndexedProperty; end; type {$M-} {$RTTI EXPLICIT METHODS([vcPublic]) PROPERTIES([vcPublic]) FIELDS([vcPublic])} TPublicStuffOnly = class(TObject) private PrivateField: double; FPublicPropertyField: string; FPublishedPropertyField: string; procedure PrivateMethod; protected ProtectedField: string; procedure ProtectedMethod; public PublicField: integer; procedure PublicMethod; property PublicProperty: string read FPublicPropertyField write FPublicPropertyField; published {$M-} PublishedField: TObject; function PublishedMethod(aParam: string): integer; property PublishedProperty: string read FPublishedPropertyField write FPublishedPropertyField; {$M+} end; implementation { TRTTIDemoClass } constructor TRTTIDemoClass.Create; begin SetLength(FIndexedProperty, 2); end; function TRTTIDemoClass.GetIndexedProperty(aIndex: integer): string; begin Result := FIndexedProperty[aIndex]; WriteLn('Value of ', Result, ' retrieved from GetIndexedProperty'); end; procedure TRTTIDemoClass.PrivateMethod; begin WriteLn('This is a private method'); end; procedure TRTTIDemoClass.ProtectedMethod; begin WriteLn('This is a protected method'); end; procedure TRTTIDemoClass.PublicMethod; begin WriteLn('This is a public method called "PublicMethod"'); end; procedure TRTTIDemoClass.PublicMethodWithParams(aString: string; aExtended: Extended); begin WriteLn('You passed in "', aString, '" and "', aExtended, '"'); end; procedure TRTTIDemoClass.SetIndexedProperty(aIndex: integer; const Value: string); begin FIndexedProperty[aIndex] := Value; // WriteLn('Index ', aIndex, ' set to ', Value); end; procedure TRTTIDemoClass.SetPublicProperty(const Value: string); begin // WriteLn('Value of PublicProperty set to ', Value); FPublicProperty := Value; end; function TRTTIDemoClass.SomeFunction: string; begin Result := 'This is the result of the SomeFunction method'; end; { TPublicStuffOnly } procedure TPublicStuffOnly.PrivateMethod; begin end; procedure TPublicStuffOnly.ProtectedMethod; begin end; procedure TPublicStuffOnly.PublicMethod; begin end; function TPublicStuffOnly.PublishedMethod(aParam: string): integer; begin end; end.
{ ******************************************************************************* Title: T2Ti ERP Description: Unit de controle Base - Cliente. The MIT License Copyright: Copyright (C) 2015 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com @author Albert Eije (t2ti.com@gmail.com) @version 1.0 ******************************************************************************* } unit Controller; interface uses Classes, DBXJson, SessaoUsuario, SysUtils, Forms, Windows, DB, DBClient, dialogs, JsonVO, VO, Rtti, Atributos, StrUtils, TypInfo, Generics.Collections, Biblioteca, T2TiORM; type TController = class(TPersistent) private class var ObjetoColumnDisplayVO: TVO; class var NomeClasseController: String; class function MontarParametros(pParametros: array of TValue): String; class procedure BuscarObjetoColumnDisplay(pObjeto: TVO; pNomeClasse: String); public class var FDataSet: TClientDataSet; class var ObjetoConsultado: TVO; class var ListaObjetoConsultado: TObjectList<TVO>; class var RetornoBoolean: Boolean; class function GetDataSet: TClientDataSet; virtual; class procedure SetDataSet(pDataSet: TClientDataSet); virtual; class function ServidorAtivo: Boolean; class procedure ExecutarMetodo(pNomeClasseController: String; pNomeMetodo: String; pParametros: array of TValue; pMetodoRest: String = ''; pTipoRetorno: String = ''); class function BuscarLista(pNomeClasseController: String; pNomeMetodo: String; pParametros: array of TValue; pMetodoRest: String = ''): TObjectList<TVO>; class function BuscarObjeto(pNomeClasseController: String; pNomeMetodo: String; pParametros: array of TValue; pMetodoRest: String = ''): TVO; class function BuscarArquivo(pNomeClasseController: String; pNomeMetodo: String; pParametros: array of TValue; pMetodoRest: String = ''): String; class procedure PreencherObjectListFromCDS<O: class>(pListaObjetos: TObjectList<O>; pDataSet: TClientDataSet); class procedure TratarRetorno<O: class>(pListaObjetos: TObjectList<O>); overload; class procedure TratarRetorno<O: class>(pListaObjetos: TObjectList<O>; pLimparDataSet: Boolean; pPreencherGridInterna: Boolean = False; pDataSet: TClientDataset = Nil); overload; class procedure TratarRetorno<O: class>(pObjeto: O); overload; class procedure TratarRetorno(pRetornoBoolean: Boolean); overload; protected class function Sessao: TSessaoUsuario; end; TClassController = class of TController; implementation uses Conversor; { TController } class function TController.GetDataSet: TClientDataSet; begin Result := nil; // Implementar nas classes filhas end; class function TController.Sessao: TSessaoUsuario; begin Result := TSessaoUsuario.Instance; end; class procedure TController.SetDataSet(pDataSet: TClientDataSet); begin // end; class procedure TController.BuscarObjetoColumnDisplay(pObjeto: TVO; pNomeClasse: String); var Contexto: TRttiContext; Tipo: TRttiType; Propriedade: TRttiProperty; Atributo: TCustomAttribute; ObjetoPai: TVO; begin try if Assigned(ObjetoColumnDisplayVO) then Exit; Contexto := TRttiContext.Create; Tipo := Contexto.GetType(pObjeto.ClassType); for Propriedade in Tipo.GetProperties do begin // Percorre atributos for Atributo in Propriedade.GetAttributes do begin // Verifica se o atributo é um atributo de associação para muitos - passa direto, não vamos pegar um campo dentro de uma lista if Atributo is TManyValuedAssociation then begin Continue; end; // Verifica se o atributo é um atributo de associação para uma classe if Atributo is TAssociation then begin if Propriedade.PropertyType.TypeKind = tkClass then begin if Propriedade.PropertyType.QualifiedName = pNomeClasse then begin ObjetoColumnDisplayVO := Propriedade.GetValue(TObject(pObjeto)).AsObject as TVO; Exit; end else begin ObjetoPai := Propriedade.GetValue(TObject(pObjeto)).AsObject as TVO; if Assigned(ObjetoPai) then BuscarObjetoColumnDisplay(ObjetoPai, pNomeClasse); end; end; end; end; end; finally end; end; class procedure TController.TratarRetorno<O>(pListaObjetos: TObjectList<O>; pLimparDataSet: Boolean; pPreencherGridInterna: Boolean; pDataSet: TClientDataset); var I: Integer; ObjetoVO: O; Contexto: TRttiContext; Tipo, TipoInterno: TRttiType; Propriedade, PropriedadeInterna: TRttiProperty; Atributo, AtributoInterno: TCustomAttribute; DataSetField: TField; DataSet: TClientDataSet; ObjetoAssociado: TVO; NomeCampoObjetoAssociado: String; NomeClasseObjetoColumnDisplay, NomeCampoObjetoColumnDisplay: String; RttiInstanceType: TRttiInstanceType; begin if not pPreencherGridInterna then begin if Sessao.Camadas = 2 then begin ListaObjetoConsultado := TObjectList<TVO>(pListaObjetos); end; RttiInstanceType := Contexto.FindType(NomeClasseController) as TRttiInstanceType; DataSet := TClientDataSet(RttiInstanceType.GetMethod('GetDataSet').Invoke(RttiInstanceType.MetaclassType, []).AsObject); if not Assigned(DataSet) then Exit; end else begin if not Assigned(pDataSet) then Exit else DataSet := pDataSet; end; try DataSet.DisableControls; if pLimparDataset then DataSet.EmptyDataSet; try Contexto := TRttiContext.Create; Tipo := Contexto.GetType(TClass(O)); for I := 0 to pListaObjetos.Count - 1 do begin ObjetoVO := O(pListaObjetos[i]); try DataSet.Append; for Propriedade in Tipo.GetProperties do begin for Atributo in Propriedade.GetAttributes do begin // Preenche o valor do campo ID if Atributo is TId then begin DataSetField := DataSet.FindField((Atributo as TId).NameField); if Assigned(DataSetField) then begin DataSetField.Value := Propriedade.GetValue(TObject(ObjetoVO)).AsVariant; end; end // Preenche o valor dos campos que sejam TColumnDisplay else if Atributo is TColumnDisplay then begin ObjetoColumnDisplayVO := Nil; // Atribui o valor encontrado ao campo que será exibido na grid DataSetField := DataSet.FindField((Atributo as TColumnDisplay).Name); if Assigned(DataSetField) then begin // Nome da classe do objeto que será procurado no objeto principal NomeClasseObjetoColumnDisplay := (Atributo as TColumnDisplay).QualifiedName; // Se o nome for "UNIDADE_PRODUTO.SIGLA" vai pegar o "SIGLA" para procurar pelo valor desse campo no VO NomeCampoObjetoColumnDisplay := Copy((Atributo as TColumnDisplay).Name, Pos('.', (Atributo as TColumnDisplay).Name) + 1, Length((Atributo as TColumnDisplay).Name)); // Chama o procedimento para encontrar o objeto vinculado BuscarObjetoColumnDisplay(TVO(ObjetoVO), NomeClasseObjetoColumnDisplay); if Assigned(ObjetoColumnDisplayVO) then begin TipoInterno := Contexto.GetType(ObjetoColumnDisplayVO.ClassType); for PropriedadeInterna in TipoInterno.GetProperties do begin for AtributoInterno in PropriedadeInterna.GetAttributes do begin if AtributoInterno is TColumn then begin if (AtributoInterno as TColumn).Name = NomeCampoObjetoColumnDisplay then begin DataSetField.Value := PropriedadeInterna.GetValue(TObject(ObjetoColumnDisplayVO)).AsVariant; end; end; end; end; end; end; end // Preenche o valor dos campos que sejam TColumn else if Atributo is TColumn then begin DataSetField := DataSet.FindField((Atributo as TColumn).Name); if Assigned(DataSetField) then begin if Propriedade.PropertyType.TypeKind in [tkEnumeration] then DataSetField.AsBoolean := Propriedade.GetValue(TObject(ObjetoVO)).AsBoolean else DataSetField.Value := Propriedade.GetValue(TObject(ObjetoVO)).AsVariant; if DataSetField.DataType = ftDateTime then begin if DataSetField.AsDateTime = 0 then DataSetField.Clear; end; end; end end; end; finally end; DataSet.Post; end; finally Contexto.Free; end; DataSet.Open; DataSet.First; finally DataSet.EnableControls; end; end; class procedure TController.TratarRetorno<O>(pListaObjetos: TObjectList<O>); begin TratarRetorno<O>(pListaObjetos, True); end; class procedure TController.TratarRetorno<O>(pObjeto: O); begin ObjetoConsultado := TVO(pObjeto); end; class procedure TController.TratarRetorno(pRetornoBoolean: Boolean); begin RetornoBoolean := pRetornoBoolean; end; class procedure TController.PreencherObjectListFromCDS<O>(pListaObjetos: TObjectList<O>; pDataSet: TClientDataSet); var I: Integer; ObjetoVO: TVO; RttiInstanceType: TRttiInstanceType; ObjetoLocalRtti: TValue; Contexto: TRttiContext; Tipo: TRttiType; Field: TRttiField; Value: TValue; begin if pDataSet.IsEmpty then Exit; try Contexto := TRttiContext.Create; Tipo := Contexto.GetType(TClass(O)); pDataSet.DisableControls; pDataSet.First; while not pDataSet.Eof do begin if (pDataSet.FieldByName('PERSISTE').AsString = 'S') or (pDataSet.FieldByName('ID').AsInteger = 0) then begin try // Cria objeto RttiInstanceType := (Contexto.FindType(TClass(O).QualifiedClassName) as TRttiInstanceType); ObjetoLocalRtti := RttiInstanceType.GetMethod('Create').Invoke(RttiInstanceType.MetaclassType,[]); ObjetoVO := TVO(ObjetoLocalRtti.AsObject); finally end; for I := 0 to pDataSet.Fields.Count - 1 do begin Value := TValue.FromVariant(pDataSet.Fields[I].Value); Tipo.GetField('F'+pDataSet.Fields[I].FieldName).SetValue(ObjetoVO, Value); end; pListaObjetos.Add(ObjetoVO); end; pDataSet.Next; end; pDataSet.First; pDataSet.EnableControls; finally Contexto.Free; end; end; class function TController.ServidorAtivo: Boolean; var Url: String; begin Result := False; try Sessao.HTTP.Get(Sessao.Url); Result := True; except Result := False; end; end; class procedure TController.ExecutarMetodo(pNomeClasseController, pNomeMetodo: String; pParametros: array of TValue; pMetodoRest: String; pTipoRetorno: String); var Contexto: TRttiContext; RttiInstanceType: TRttiInstanceType; Url, StringJson: String; StreamResposta: TStringStream; StreamEnviado: TStringStream; ObjetoResposta, ObjetoRespostaPrincipal: TJSONObject; ParResposta: TJSONPair; ArrayResposta: TJSONArray; ObjetoLocal: TVO; i: Integer; begin try FormatSettings.DecimalSeparator := '.'; try NomeClasseController := pNomeClasseController; if Sessao.Camadas = 2 then begin RttiInstanceType := Contexto.FindType(pNomeClasseController) as TRttiInstanceType; RttiInstanceType.GetMethod(pNomeMetodo).Invoke(RttiInstanceType.MetaclassType, pParametros); FreeAndNil(ListaObjetoConsultado); end else if Sessao.Camadas = 3 then begin try StreamResposta := TStringStream.Create; if pMetodoRest = 'GET' then begin Url := Sessao.Url + Sessao.IdSessao + '/' + pNomeClasseController + '/' + pNomeMetodo + '/' + pTipoRetorno + '/' + MontarParametros(pParametros); Sessao.HTTP.Get(Url, StreamResposta); end else if pMetodoRest = 'DELETE' then begin Url := Sessao.Url + Sessao.IdSessao + '/' + pNomeClasseController + '/' + pNomeMetodo + '/' + pTipoRetorno + '/' + MontarParametros(pParametros); Sessao.HTTP.Delete(Url, StreamResposta); end else if pMetodoRest = 'POST' then begin Url := Sessao.Url + Sessao.IdSessao + '/' + pNomeClasseController + '/' + pNomeMetodo + '/' + pTipoRetorno + '/'; StringJson := TVO(pParametros[0].AsObject).ToJsonString; StreamEnviado := TStringStream.Create(TEncoding.UTF8.GetBytes(StringJson)); Sessao.HTTP.Post(Url, StreamEnviado, StreamResposta); end else if pMetodoRest = 'PUT' then begin Url := Sessao.Url + Sessao.IdSessao + '/' + pNomeClasseController + '/' + pNomeMetodo + '/' + pTipoRetorno + '/'; StringJson := TVO(pParametros[0].AsObject).ToJsonString; StreamEnviado := TStringStream.Create(TEncoding.UTF8.GetBytes(StringJson)); Sessao.HTTP.Put(Url, StreamEnviado, StreamResposta); end; ObjetoRespostaPrincipal := TJSONObject.Create; ObjetoRespostaPrincipal.Parse(StreamResposta.Bytes, 0); ParResposta := ObjetoRespostaPrincipal.Get(0); ArrayResposta := TJSONArray(TJSONArray(ParResposta.JsonValue).Get(0)); // se o array que retornou contém um erro, gera uma exceção if ArrayResposta.Size > 0 then begin if ArrayResposta.Get(0).ToString = '"ERRO"' then begin raise Exception.Create(ArrayResposta.Get(1).ToString); end; end; // Faz o tratamento de acordo com o tipo de retorno if pTipoRetorno = 'Objeto' then begin ObjetoResposta := TJSONObject.ParseJsonValue(TEncoding.UTF8.GetBytes(ArrayResposta.Get(0).ToString), 0) as TJSONObject; ObjetoConsultado := TJsonVO.JSONToObject<TVO>(ObjetoResposta); ObjetoResposta.Free; end else if pTipoRetorno = 'Lista' then begin ListaObjetoConsultado := TObjectList<TVO>.Create; for i := 0 to ArrayResposta.Size - 1 do begin ObjetoResposta := TJSONObject.ParseJsonValue(TEncoding.UTF8.GetBytes(ArrayResposta.Get(i).ToString), 0) as TJSONObject; ObjetoLocal := TJsonVO.JSONToObject<TVO>(ObjetoResposta); ListaObjetoConsultado.Add(ObjetoLocal); ObjetoResposta.Free; end; RttiInstanceType := Contexto.FindType(pNomeClasseController) as TRttiInstanceType; RttiInstanceType.GetMethod('TratarListaRetorno').Invoke(RttiInstanceType.MetaclassType, [ListaObjetoConsultado]); end else if pTipoRetorno = 'Boolean' then begin if ArrayResposta.ToString = '[true]' then RetornoBoolean := True else RetornoBoolean := False; end; finally StreamResposta.Free; StreamEnviado.Free; ObjetoRespostaPrincipal.Free; end; end; except on E: Exception do Application.MessageBox(PChar('Ocorreu um erro durante a execução do método. Informe a mensagem ao Administrador do sistema.' + #13 + #13 + E.Message), 'Erro do sistema', MB_OK + MB_ICONERROR); end; finally FormatSettings.DecimalSeparator := ','; Contexto.Free; end; end; class function TController.BuscarLista(pNomeClasseController, pNomeMetodo: String; pParametros: array of TValue; pMetodoRest: String): TObjectList<TVO>; var Contexto: TRttiContext; RttiInstanceType: TRttiInstanceType; Url, StringJson: String; StreamResposta: TStringStream; ObjetoResposta, ObjetoRespostaPrincipal: TJSONObject; ParResposta: TJSONPair; ArrayResposta: TJSONArray; ObjetoLocal: TVO; i: Integer; begin try FormatSettings.DecimalSeparator := '.'; try NomeClasseController := pNomeClasseController; if Sessao.Camadas = 2 then begin RttiInstanceType := Contexto.FindType(pNomeClasseController) as TRttiInstanceType; Result := TObjectList<TVO>(RttiInstanceType.GetMethod(pNomeMetodo).Invoke(RttiInstanceType.MetaclassType, pParametros).AsObject); end else if Sessao.Camadas = 3 then begin try StreamResposta := TStringStream.Create; if pMetodoRest = 'GET' then begin Url := Sessao.Url + Sessao.IdSessao + '/' + pNomeClasseController + '/' + pNomeMetodo + '/Lista/' + MontarParametros(pParametros); Sessao.HTTP.Get(Url, StreamResposta); end; ObjetoRespostaPrincipal := TJSONObject.Create; ObjetoRespostaPrincipal.Parse(StreamResposta.Bytes, 0); ParResposta := ObjetoRespostaPrincipal.Get(0); ArrayResposta := TJSONArray(TJSONArray(ParResposta.JsonValue).Get(0)); // se o array que retornou contém um erro, gera uma exceção if ArrayResposta.Size > 0 then begin if ArrayResposta.Get(0).ToString = '"ERRO"' then begin raise Exception.Create(ArrayResposta.Get(1).ToString); end; end; Result := TObjectList<TVO>.Create; for i := 0 to ArrayResposta.Size - 1 do begin ObjetoResposta := TJSONObject.ParseJsonValue(TEncoding.UTF8.GetBytes(ArrayResposta.Get(i).ToString), 0) as TJSONObject; ObjetoLocal := TJsonVO.JSONToObject<TVO>(ObjetoResposta); Result.Add(ObjetoLocal); ObjetoResposta.Free; end; finally StreamResposta.Free; ObjetoRespostaPrincipal.Free; end; end; except on E: Exception do Application.MessageBox(PChar('Ocorreu um erro durante a execução do método. Informe a mensagem ao Administrador do sistema.' + #13 + #13 + E.Message), 'Erro do sistema', MB_OK + MB_ICONERROR); end; finally FormatSettings.DecimalSeparator := ','; Contexto.Free; end; end; class function TController.BuscarObjeto(pNomeClasseController, pNomeMetodo: String; pParametros: array of TValue; pMetodoRest: String): TVO; var Contexto: TRttiContext; RttiInstanceType: TRttiInstanceType; Url, StringJson: String; StreamResposta: TStringStream; ObjetoResposta, ObjetoRespostaPrincipal: TJSONObject; ParResposta: TJSONPair; ArrayResposta: TJSONArray; begin try FormatSettings.DecimalSeparator := '.'; try NomeClasseController := pNomeClasseController; if Sessao.Camadas = 2 then begin RttiInstanceType := Contexto.FindType(pNomeClasseController) as TRttiInstanceType; Result := TVO(RttiInstanceType.GetMethod(pNomeMetodo).Invoke(RttiInstanceType.MetaclassType, pParametros).AsObject); end else if Sessao.Camadas = 3 then begin try StreamResposta := TStringStream.Create; if pMetodoRest = 'GET' then begin Url := Sessao.Url + Sessao.IdSessao + '/' + pNomeClasseController + '/' + pNomeMetodo + '/Objeto/' + MontarParametros(pParametros); Sessao.HTTP.Get(Url, StreamResposta); end; ObjetoRespostaPrincipal := TJSONObject.Create; ObjetoRespostaPrincipal.Parse(StreamResposta.Bytes, 0); ParResposta := ObjetoRespostaPrincipal.Get(0); ArrayResposta := TJSONArray(TJSONArray(ParResposta.JsonValue).Get(0)); if ArrayResposta.Size > 0 then begin // se o array que retornou contém um erro, gera uma exceção if ArrayResposta.Get(0).ToString = '"ERRO"' then begin raise Exception.Create(ArrayResposta.Get(1).ToString); end; // se o array que retornou contém um null, retorna nil if ArrayResposta.Get(0).ToString = 'null' then begin Result := Nil; end else begin try // Faz o tratamento de acordo com o tipo de retorno ObjetoResposta := TJSONObject.ParseJsonValue(TEncoding.UTF8.GetBytes(ArrayResposta.Get(0).ToString), 0) as TJSONObject; Result := TJsonVO.JSONToObject<TVO>(ObjetoResposta); finally ObjetoResposta.Free; end; end; end; finally StreamResposta.Free; ObjetoRespostaPrincipal.Free; end; end; except on E: Exception do Application.MessageBox(PChar('Ocorreu um erro durante a execução do método. Informe a mensagem ao Administrador do sistema.' + #13 + #13 + E.Message), 'Erro do sistema', MB_OK + MB_ICONERROR); end; finally FormatSettings.DecimalSeparator := ','; Contexto.Free; end; end; class function TController.BuscarArquivo(pNomeClasseController, pNomeMetodo: String; pParametros: array of TValue; pMetodoRest: String): String; var I: Integer; Contexto: TRttiContext; RttiInstanceType: TRttiInstanceType; Url, StringJson: String; ArquivoStream, StreamResposta: TStringStream; ObjetoResposta, ObjetoRespostaPrincipal: TJSONObject; ParResposta: TJSONPair; ArrayResposta: TJSONArray; ArquivoBytes: Tbytes; ArrayStringsArquivo: TStringList; ArquivoBytesString, TipoArquivo, CaminhoSalvarArquivo, NomeArquivo: String; begin try FormatSettings.DecimalSeparator := '.'; try NomeClasseController := pNomeClasseController; if Sessao.Camadas = 2 then begin RttiInstanceType := Contexto.FindType(pNomeClasseController) as TRttiInstanceType; Result := RttiInstanceType.GetMethod(pNomeMetodo).Invoke(RttiInstanceType.MetaclassType, pParametros).AsString; end else if Sessao.Camadas = 3 then begin try StreamResposta := TStringStream.Create; ArquivoStream := TStringStream.Create; if pMetodoRest = 'GET' then begin Url := Sessao.Url + Sessao.IdSessao + '/' + pNomeClasseController + '/' + pNomeMetodo + '/Arquivo/' + MontarParametros(pParametros); Sessao.HTTP.Get(Url, StreamResposta); end; ObjetoRespostaPrincipal := TJSONObject.Create; ObjetoRespostaPrincipal.Parse(StreamResposta.Bytes, 0); ParResposta := ObjetoRespostaPrincipal.Get(0); ArrayResposta := TJSONArray(TJSONArray(ParResposta.JsonValue).Get(0)); // se o array que retornou contém um erro, gera uma exceção if ArrayResposta.Size > 0 then begin if ArrayResposta.Get(0).ToString = '"ERRO"' then begin raise Exception.Create(ArrayResposta.Get(1).ToString); end; end; // Faz o tratamento do arquivo if ArrayResposta.Get(0).ToString <> '"RESPOSTA"' then begin // na posicao zero temos o arquivo enviado ArquivoBytesString := (ArrayResposta as TJSONArray).Get(0).ToString; // retira as aspas do JSON System.Delete(ArquivoBytesString, Length(ArquivoBytesString), 1); System.Delete(ArquivoBytesString, 1, 1); // Nome do arquivo NomeArquivo := (ArrayResposta as TJSONArray).Get(1).ToString; // retira as aspas do JSON System.Delete(NomeArquivo, Length(NomeArquivo), 1); System.Delete(NomeArquivo, 1, 1); CaminhoSalvarArquivo := ExtractFilePath(Application.ExeName) + 'Temp\'; if not DirectoryExists(CaminhoSalvarArquivo) then ForceDirectories(CaminhoSalvarArquivo); CaminhoSalvarArquivo := CaminhoSalvarArquivo + NomeArquivo; // na posicao um temos o tipo de arquivo enviado TipoArquivo := (ArrayResposta as TJSONArray).Get(2).ToString; // retira as aspas do JSON System.Delete(TipoArquivo, Length(TipoArquivo), 1); System.Delete(TipoArquivo, 1, 1); // salva o arquivo enviado em disco de forma temporaria ArrayStringsArquivo := TStringList.Create; Split(',', ArquivoBytesString, ArrayStringsArquivo); SetLength(ArquivoBytes, ArrayStringsArquivo.Count); for I := 0 to ArrayStringsArquivo.Count - 1 do begin ArquivoBytes[I] := StrToInt(ArrayStringsArquivo[I]); end; ArquivoStream := TStringStream.Create(ArquivoBytes); ArquivoStream.SaveToFile(CaminhoSalvarArquivo); Result := CaminhoSalvarArquivo; end; finally StreamResposta.Free; ArquivoStream.Free; ObjetoResposta.Free; ObjetoRespostaPrincipal.Free; FreeAndNil(ArrayStringsArquivo); end; end; except on E: Exception do Application.MessageBox(PChar('Ocorreu um erro durante a execução do método. Informe a mensagem ao Administrador do sistema.' + #13 + #13 + E.Message), 'Erro do sistema', MB_OK + MB_ICONERROR); end; finally FormatSettings.DecimalSeparator := ','; Contexto.Free; end; end; class function TController.MontarParametros(pParametros: array of TValue): String; var Parametro: String; I: Integer; begin Result := ''; for I := 0 to Length(pParametros) - 1 do begin Parametro := pParametros[I].ToString; Parametro := StringReplace(Parametro, '%', '*', [rfReplaceAll]); Parametro := StringReplace(Parametro, '"', '\"', [rfReplaceAll]); if Parametro <> '' then begin Result := Result + Parametro + '|'; end; end; if Result <> '' then begin // Remove a última barra Result := Copy(Result, 1, Length(Result) - 1); end; end; end.
(************************************* Ext2D Engine *************************************) (* Модуль : E2DInput.pas *) (* Автор : Есин Владимир *) (* Создан : 21.10.06 *) (* Информация : Модуль содежит функции для работы с клавиатурой и мышью. *) (* Изменения : нет изменений. *) (****************************************************************************************) unit E2DInput; interface uses E2DTypes, Windows; { Функция для создания обьектов DirectInput. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_CreateInput : E2D_Result; stdcall; export; { Функция для создания устройства клавиатуры. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_AddKeyboard : E2D_Result; stdcall; export; { Функция для создания устройства мыши. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_AddMouse : E2D_Result; stdcall; export; { Функция для обновления данных клавиатуры. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_UpdateKeyboard : E2D_Result; stdcall; export; { Функция для обновления данных мыши. Возвращаемое значение : если функция выполнилась успешно - E2DERR_OK, если неудачно - код ошибки. } function E2D_UpdateMouse : E2D_Result; stdcall; export; { Функция для получения информации о том, нажата ли клавиша на клавиатуре. Параметры : Key : код клавиши, информацию о которой необходимо получить. Возвращаемое значение : если клавиша нажата - True, если нет - False. } function E2D_IsKeyboardKeyDown(Key : Byte) : Boolean; stdcall; export; { Процедура для получения позиции курсора. Параметры : CursorPos : переменная для сохранения позиции курсора. } procedure E2D_GetCursorPosition(var CursorPos : TPoint); stdcall; export; { Процедура для получения приращения позиции курсора. Параметры : CursorDeltas : переменная для сохранения приращений позиции курсора. } procedure E2D_GetCursorDelta(var CursorDeltas : TPoint); stdcall; export; { Функция для получения информации о том, нажата ли кнопка мыши. Параметры : Button : кнопка, информацию о которой необходимо получить. Возвращаемое значение : если клавиша нажата - True, если нет - False. } function E2D_IsMouseButtonDown(Button : E2D_TMouseButton) : Boolean; stdcall; export; implementation uses E2DConsts, { Для констант ошибок } E2DVars, { Для переменных ввода } DirectInput8; { Для функций DirectInput } function E2D_CreateInput; begin { E2D_CreateInput } // Создаем главный обьект DirectInput. if DirectInput8Create(HInstance, DIRECTINPUT_VERSION, IID_IDirectInput8, DI_Main, nil) <> DI_OK then begin { if } // Если не получилось помещаем код ошибки в результат Result := E2DERR_INPUT_CREATEDI; // и выходим из функции. Exit; end; { if } // Делаем результат успешным. Result := E2DERR_OK; end; { E2D_CreateInput } function E2D_AddKeyboard; begin { E2D_AddKeyboard } // Создаем устройство клавиатуры. if DI_Main.CreateDevice(GUID_SysKeyboard, DID_Keyboard, nil) <> DI_OK then begin { if } // Если не получилось помещаем код ошибки в результат Result := E2DERR_INPUT_CREATEDEV; // и выходим из функции. Exit; end; { if } // Задаем формат данных клавиатуры. if DID_Keyboard.SetDataFormat(c_dfDIKeyboard) <> DI_OK then begin { if } // Если не получилось помещаем код ошибки в результат, Result := E2DERR_INPUT_SETDATAFMT; // удаляем клавиатуру DID_Keyboard := nil; // и выходим из функции. Exit; end; { if } // Задаем уровень кооперации. if DID_Keyboard.SetCooperativeLevel(Window_Handle, DISCL_EXCLUSIVE or DISCL_FOREGROUND) <> DI_OK then begin { if } // Если не получилось помещаем код ошибки в результат, Result := E2DERR_SYSTEM_SETCOOPLVL; // удаляем клавиатуру DID_Keyboard := nil; // и выходим из функции. Exit; end; { if } // Захватываем клавиатуру. if DID_Keyboard.Acquire <> DI_OK then begin { if } // Если не получилось помещаем код ошибки в результат, Result := E2DERR_INPUT_CANTACQR; // удаляем клавиатуру DID_Keyboard := nil; // и выходим из функции. Exit; end; { if } // Делаем результат успешным. Result := E2DERR_OK; end; { E2D_AddKeyboard } function E2D_AddMouse; begin { E2D_AddMouse } // Создаем устройство мыши. if DI_Main.CreateDevice(GUID_SysMouse, DID_Mouse, nil) <> DI_OK then begin { if } // Если не получилось помещаем код ошибки в результат Result := E2DERR_INPUT_CREATEDEV; // и выходим из функции. Exit; end; { if } // Задаем формат данных мыши. if DID_Mouse.SetDataFormat(c_dfDIMouse2) <> DI_OK then begin { if } // Если не получилось помещаем код ошибки в результат, Result := E2DERR_INPUT_SETDATAFMT; // удаляем мышь DID_Mouse := nil; // и выходим из функции. Exit; end; { if } // Задаем уровень кооперации. if DID_Mouse.SetCooperativeLevel(Window_Handle, DISCL_EXCLUSIVE or DISCL_FOREGROUND) <> DI_OK then begin { if } // Если не получилось помещаем код ошибки в результат, Result := E2DERR_SYSTEM_SETCOOPLVL; // удаляем мышь DID_Mouse := nil; // и выходим из функции. Exit; end; { if } // Захватываем мышь. if DID_Mouse.Acquire <> DI_OK then begin { if } // Если не получилось помещаем код ошибки в результат, Result := E2DERR_INPUT_CANTACQR; // удаляем мышь DID_Mouse := nil; // и выходим из функции. Exit; end; { if } // Делаем результат успешным. Result := E2DERR_OK; end; { E2D_AddMouse } function E2D_UpdateKeyboard; var res : HRESULT; begin { E2D_UpdateKeyboard } // Обнуляем структуру. ZeroMemory(@Keyboard_Data, SizeOf(Keyboard_Data)); // Получаем данные с клавиатуры. res := DID_Keyboard.GetDeviceState(SizeOf(Keyboard_Data), @Keyboard_Data); // Проверяем результат выполнения. if res <> DI_OK then // Если не получилось проверяем результат выполнения. if res = DIERR_INPUTLOST then begin repeat // Если необходимо захватываем клавиатуру res := DID_Keyboard.Acquire; until // до тех пор, пока не добьемся успеха. res = DI_OK; end else begin // Если не получилось помещаем код ошибки в результат Result := E2DERR_INPUT_GETSTATE; // и выходим из функции. Exit; end; // Делаем результат успешным. Result := E2DERR_OK; end; { E2D_UpdateKeyboard } function E2D_UpdateMouse; var res : HRESULT; begin { E2D_UpdateMouse } // Обнуляем структуру. ZeroMemory(@Mouse_Data, SizeOf(Mouse_Data)); // Получаем данные с мыши. res := DID_Mouse.GetDeviceState(SizeOf(Mouse_Data), @Mouse_Data); // Проверяем результат выполнения. if res <> DI_OK then // Если не получилось проверяем результат выполнения. if res = DIERR_INPUTLOST then begin repeat // Если необходимо захватываем мышь res := DID_Mouse.Acquire; until // до тех пор, пока не добьемся успеха. res = DI_OK; end else begin // Если не получилось помещаем код ошибки в результат Result := E2DERR_INPUT_GETSTATE; // и выходим из функции. Exit; end else begin // Если получилось сохраняем приращение по горизонтали Cursor_dX := Mouse_Data.lX; // и вертикали. Cursor_dY := Mouse_Data.lY; {$WARNINGS OFF} // Проверяем, не вышли ли за левую границу экрана. if Cursor_X + Cursor_dX < 0 then // Если вышли устанавливаем новое значение. Cursor_X := 0 else // Если не вышли проверяем, не вышли ли за правую границу экрана. if Cursor_X + Cursor_dX >= Screen_Width then // Если вышли устанавливаем новое значение. Cursor_X := Screen_Width - 1 else // Если не вышли сохраняем позицию курсора по горизонтали. Cursor_X := Cursor_X + Cursor_dX; // Проверяем, не вышли ли за верхнюю границу экрана. if Cursor_Y + Cursor_dY < 0 then // Если вышли устанавливаем новое значение. Cursor_Y := 0 else // Если не вышли проверяем, не вышли ли за нижнюю границу экрана. if Cursor_Y + Cursor_dY >= Screen_Height then // Если вышли устанавливаем новое значение. Cursor_Y := Screen_Height - 1 else // Если не вышли сохраняем позицию курсора по вертикали. Cursor_Y := Cursor_Y + Cursor_dY; {$WARNINGS ON} end; // Делаем результат успешным. Result := E2DERR_OK; end; { E2D_UpdateMouse } function E2D_IsKeyboardKeyDown; begin { E2D_IsKeyboardKeyDown } // Помещаем в результат нажата ли клавиша. Result := (Keyboard_Data[Key] = 128); end; { E2D_IsKeyboardKeyDown } procedure E2D_GetCursorPosition; begin { E2D_GetCursorPosition } // Сохраняем позицию курсора по горизонтали CursorPos.X := Cursor_X; // и вертикали. CursorPos.Y := Cursor_Y; end; { E2D_GetCursorPosition } procedure E2D_GetCursorDelta; begin { E2D_GetCursorDelta } // Сохраняем приращение позиции курсора по горизонтали CursorDeltas.X := Cursor_dX; // и вертикали. CursorDeltas.Y := Cursor_dY; end; { E2D_GetCursorDelta } function E2D_IsMouseButtonDown; begin { E2D_IsMouseButtonDown } // Помещаем в результат нажата ли кнопка. Result := (Mouse_Data.rgbButtons[Button] = 128); end; { E2D_IsMouseButtonDown } end.
{------------------------------------ 功能说明:平台配置工具,类似windows的regedit.exe 创建日期:2008/11/15 作者:wzw 版权:wzw -------------------------------------} unit uMain; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Menus, ComCtrls, ExtCtrls, RegIntf, StdCtrls, ImgList, StdVcl, AxCtrls; type PNodeInfo = ^RNodeInfo; RNodeInfo = record Key: String; end; Tfrm_Main = class(TForm) tv_Reg: TTreeView; MainMenu1: TMainMenu; N1: TMenuItem; N2: TMenuItem; Splitter1: TSplitter; statu_Msg: TStatusBar; N3: TMenuItem; N4: TMenuItem; ImgList: TImageList; pMenu_Key: TPopupMenu; pMenu_Value: TPopupMenu; N5: TMenuItem; N8: TMenuItem; N9: TMenuItem; N10: TMenuItem; N11: TMenuItem; N6: TMenuItem; N12: TMenuItem; N13: TMenuItem; N14: TMenuItem; N16: TMenuItem; N17: TMenuItem; N19: TMenuItem; N20: TMenuItem; N18: TMenuItem; lv_Value: TListView; N7: TMenuItem; N15: TMenuItem; N21: TMenuItem; N22: TMenuItem; procedure FormCreate(Sender: TObject); procedure N2Click(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure N4Click(Sender: TObject); procedure tv_RegDeletion(Sender: TObject; Node: TTreeNode); procedure tv_RegChange(Sender: TObject; Node: TTreeNode); procedure tv_RegMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); procedure N5Click(Sender: TObject); procedure N18Click(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure N8Click(Sender: TObject); procedure N12Click(Sender: TObject); procedure N14Click(Sender: TObject); procedure N16Click(Sender: TObject); procedure N9Click(Sender: TObject); procedure N10Click(Sender: TObject); procedure N11Click(Sender: TObject); procedure N20Click(Sender: TObject); procedure lv_ValueDblClick(Sender: TObject); procedure N15Click(Sender: TObject); procedure N21Click(Sender: TObject); procedure N22Click(Sender: TObject); private Reg: IRegistry; procedure EumKeyInTree(PTreeNode: TtreeNode; const Key: string); procedure EumKeyValue(Node: TtreeNode); function GetNodeKey(Node: TtreeNode): string; procedure FillPrentKeyToList(Node: TtreeNode; aList: TStrings); procedure AddKey(Node: TtreeNode); procedure DeleteKey(Node: TtreeNode); procedure AddValue(Node: TtreeNode); procedure EditValue(CurListItem: TListItem); procedure DeleteValue(CurListItem: TListItem); public end; var frm_Main: Tfrm_Main; implementation uses SysSvc, editValue, newKey, ModuleMgr, About, MenuEditor, ToolEditor; {$R *.dfm} procedure Tfrm_Main.AddKey(node: TtreeNode); var Key, KeyName: String; nodeInfo: PNodeInfo; idx: Integer; pNode, newNode: TtreeNode; begin frm_newKey := Tfrm_newKey.Create(nil); try FillPrentKeyToList(tv_reg.Selected, frm_newKey.cb_ParentKey.Items); if assigned(tv_reg.Selected) then frm_newKey.cb_ParentKey.ItemIndex := frm_newKey.cb_ParentKey.Items.IndexOf(tv_reg.Selected.text) else frm_newKey.cb_ParentKey.ItemIndex := 0; if frm_newKey.ShowModal = mrOK then begin pNode := nil; KeyName := frm_newKey.edt_KeyName.Text; idx := frm_newKey.cb_ParentKey.ItemIndex; if idx = 0 then Key := KeyName else begin pNode := TtreeNode(frm_newKey.cb_ParentKey.Items.Objects[idx]); nodeInfo := PNodeInfo(pNode.data); key := nodeInfo^.Key + '\' + KeyName; end; if Reg.OpenKey(key, True) then begin//刷新 newNode := tv_reg.Items.AddChild(pNode, KeyName); newNode.ImageIndex := 0; newNode.SelectedIndex := 1; new(nodeInfo); nodeInfo^.Key := Key; newNode.Data := nodeInfo; newNode.Selected := True; end; end; finally frm_newKey.Free; end; end; procedure Tfrm_Main.AddValue(Node: TtreeNode); var key, aName, Value: string; begin if assigned(Node) then begin frm_editValue := Tfrm_editValue.Create(nil); try if frm_editValue.ShowModal = mrOk then begin aName := frm_editValue.edt_Name.Text; Value := frm_editValue.edt_Value.Text; key := PNodeInfo(Node.Data)^.Key; if Reg.OpenKey(key, False) then begin try Reg.WriteString(aName, Value); EumKeyValue(tv_reg.Selected);//刷新 except on E: Exception do showmessageFmt('添加值出错,错误:%s', [E.Message]); end; end else showmessage('打开节点出错,未知原因!'); end; finally frm_editValue.Free; end; end else showmessage('请先在左边树型选择节点!'); end; procedure Tfrm_Main.DeleteKey(node: TtreeNode); var key: string; begin if assigned(node) then begin if Application.MessageBox('确定删除当前节点吗?', '删除节点', 1) = 1 then begin key := PNodeInfo(node.Data)^.Key; if Reg.DeleteKey(key) then begin//刷新 node.Delete; end else showmessage('删除失败,未知道原因!'); end; end; end; procedure Tfrm_Main.DeleteValue(CurListItem: TListItem); var key, aName: string; begin if assigned(CurListItem) then begin if application.MessageBox('确定要删除当前值吗?', '删除数值', 1) = 1 then begin key := PNodeInfo(CurListItem.Data)^.Key; aName := CurListItem.Caption; if Reg.OpenKey(key, False) then begin if Reg.DeleteValue(aName) then begin CurListItem.Delete; end else showmessage('删除值出错,未知原因!'); end else showmessage('打开节点时出错,未知原因!'); end; end else showmessage('请选择一个值才能删除!'); end; procedure Tfrm_Main.EditValue(CurListItem: TListItem); var key, aName, Value: string; begin if not assigned(CurListItem) then begin showmessage('请选择一个值才能编辑!'); exit; end; frm_editValue := Tfrm_editValue.Create(nil); try frm_editValue.edt_Name.Text := CurListItem.Caption; frm_editValue.edt_Name.ReadOnly := True; frm_editValue.edt_Name.Color := clBtnFace; frm_editValue.edt_Value.Text := CurListItem.SubItems[0]; if frm_editValue.ShowModal = mrOk then begin aName := frm_editValue.edt_Name.Text; Value := frm_editValue.edt_Value.Text; key := PNodeInfo(CurListItem.Data)^.Key; if Reg.OpenKey(key, False) then begin try Reg.WriteString(aName, Value); EumKeyValue(tv_reg.Selected);//刷新 except on E: Exception do showmessageFmt('编辑值保存时出错,错误:%s', [E.Message]); end; end else showmessage('打开节点出错,未知原因!'); end; finally frm_editValue.Free; end; end; procedure Tfrm_Main.EumKeyInTree(PTreeNode: TtreeNode; const Key: string); var aList: TStrings; newNode: TtreeNode; i: integer; NodeInfo: PNodeInfo; Curkey: string; begin aList := TStringList.Create; try if Reg.OpenKey(Key, False) then begin Reg.GetKeyNames(aList); for i := 0 to aList.Count - 1 do begin newNode := tv_reg.Items.AddChild(PTreeNode, aList[i]); newNode.ImageIndex := 0; newNode.SelectedIndex := 1; Curkey := Key + '\' + aList[i]; new(NodeInfo); NodeInfo^.Key := Curkey; newNode.Data := NodeInfo; EumKeyInTree(newNode, CurKey); end; end; finally aList.Free; end; end; procedure Tfrm_Main.EumKeyValue(Node: TtreeNode); var key: string; aList: TStrings; i: integer; Value, ValueName: Widestring; newItem: TListItem; begin if Node = Nil then Exit; lv_Value.Items.BeginUpdate; lv_Value.Items.Clear; aList := TStringList.Create; try key := GetNodeKey(Node); if Reg.OpenKey(Key, False) then begin Reg.GetValueNames(aList); for i := 0 to aList.count - 1 do begin newItem := lv_Value.Items.Add; ValueName := aList[i]; newItem.Caption := ValueName; newItem.ImageIndex := 2; Reg.ReadString(ValueName, value); newItem.SubItems.Add(value); newItem.Data := node.Data; end; end; finally lv_Value.Items.EndUpdate; aList.Free; end; end; procedure Tfrm_Main.FillPrentKeyToList(node: TtreeNode; aList: TStrings); var pNode, tmpNode: TtreeNode; i: integer; begin aList.Clear; aList.Add('<无>'); if assigned(node) then begin pNode := node.Parent; if assigned(pNode) then begin for i := 0 to pNode.Count - 1 do begin tmpNode := pNode.Item[i]; aList.AddObject(tmpNode.Text, tmpNode); end; end else begin for i := 0 to tv_reg.Items.count - 1 do begin tmpNode := tv_reg.Items[i]; if tmpNode.Level = 0 then aList.AddObject(tmpNode.Text, tmpNode); end; end; end; end; procedure Tfrm_Main.FormClose(Sender: TObject; var Action: TCloseAction); begin Reg.SaveData; end; procedure Tfrm_Main.FormCreate(Sender: TObject); begin //在treeView列出所有注册表项 Reg := SysService as IRegistry; tv_reg.Items.BeginUpdate; try EumKeyInTree(nil, ''); finally tv_reg.Items.EndUpdate; end; end; procedure Tfrm_Main.FormDestroy(Sender: TObject); begin Reg := Nil; end; function Tfrm_Main.GetNodeKey(Node: TtreeNode): string; var NodeInfo: PNodeINfo; begin if assigned(Node) then begin NodeInfo := PNodeInfo(Node.Data); Result := NodeInfo^.Key; end; end; procedure Tfrm_Main.lv_ValueDblClick(Sender: TObject); begin if assigned(lv_Value.Selected) then EditValue(lv_Value.Selected); end; procedure Tfrm_Main.N10Click(Sender: TObject); begin EditValue(lv_Value.Selected); end; procedure Tfrm_Main.N11Click(Sender: TObject); begin DeleteValue(lv_Value.Selected); end; procedure Tfrm_Main.N12Click(Sender: TObject); begin Reg.SaveData; tv_reg.Items.BeginUpdate; try tv_reg.Items.Clear; EumKeyInTree(nil, ''); finally tv_reg.Items.EndUpdate; end; end; procedure Tfrm_Main.N14Click(Sender: TObject); begin AddKey(tv_reg.Selected); end; procedure Tfrm_Main.N16Click(Sender: TObject); begin DeleteKey(tv_reg.Selected); end; procedure Tfrm_Main.N18Click(Sender: TObject); begin Reg.SaveData; end; procedure Tfrm_Main.N20Click(Sender: TObject); begin EumKeyValue(tv_reg.Selected); end; procedure Tfrm_Main.N2Click(Sender: TObject); begin Close; end; procedure Tfrm_Main.N4Click(Sender: TObject); begin AboutBox := TAboutBox.Create(nil); try AboutBox.ShowModal; finally AboutBox.Free; end; end; procedure Tfrm_Main.N5Click(Sender: TObject); begin AddKey(tv_reg.Selected); end; procedure Tfrm_Main.N8Click(Sender: TObject); begin DeleteKey(tv_reg.Selected); end; procedure Tfrm_Main.N9Click(Sender: TObject); begin AddValue(tv_Reg.Selected); end; procedure Tfrm_Main.tv_RegChange(Sender: TObject; Node: TTreeNode); begin if Assigned(Node.Data) then begin statu_Msg.SimpleText := GetNodeKey(Node); EumKeyValue(Node); end; end; procedure Tfrm_Main.tv_RegDeletion(Sender: TObject; Node: TTreeNode); begin if Assigned(Node.Data) then begin Dispose(PNodeInfo(Node.Data)); Node.Data := nil; end; end; procedure Tfrm_Main.tv_RegMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); var p: Tpoint; node: TtreeNode; begin if Button = mbRight then begin GetCursorPos(P); //hit:=tv_reg.GetHitTestInfoAt(x,y); //if htOnItem in hit then //hit<>(hit-[htOnItem,htOnIcon]) //begin //end; node := tv_reg.GetNodeAt(x, y); if assigned(node) then node.Selected := True; pMenu_Key.Popup(p.X, p.Y); end; end; procedure Tfrm_Main.N15Click(Sender: TObject); begin frm_ModuleMgr := Tfrm_ModuleMgr.Create(nil); frm_ModuleMgr.ShowModal; frm_ModuleMgr.Free; end; procedure Tfrm_Main.N21Click(Sender: TObject); begin Frm_MenuEditor := TFrm_MenuEditor.Create(nil, self.Reg); Frm_MenuEditor.ShowModal; Frm_MenuEditor.Free; end; procedure Tfrm_Main.N22Click(Sender: TObject); begin frm_ToolEditor := Tfrm_ToolEditor.Create(nil, self.Reg); frm_ToolEditor.ShowModal; frm_ToolEditor.Free; end; initialization finalization end.
{ Module of routines for comparing strings with each other. } module string_compare; define string_compare_opts; define string_compare; %include 'string2.ins.pas'; { ******************************************************************************** * * Function STRING_COMPARE_OPTS (S1, S2, OPTS) * * Determine the relative dictionary positions of two strings. The function * value will be -1 if S1 comes before S2, 0 if both strings are identical, and * +1 if S1 comes after S2. The ASCII collating sequence is used. Upper case * letters are collated immediately before their lower case versions. For * example, the following characters are in order: A, a, B, b, C, c. * * OPTS allows some control over the collating sequence from that described * above. OPTS can be combinations of the following flags, although some flags * are mutually exclusive with others. Results are undefined if mutually * exclusive flags are used. The flags are: * * STRING_COMP_NCASE_K - Upper and lower case letters are equal. * * STRING_COMP_LCASE_K - A lower case letter comes immediately before * the upper case of the same letter, for example: a, A, b, B, c, C. The * default is for upper case letters to come immediately before its lower * case counterpart. * * STRING_COMP_NUM_K - Numeric fields are compare by their numeric value, * not by the character string collating sequence. A numeric field is one * or more successive decimal digits (0-9). If both strings have such a * field up to a point where they are still equal, then the strings are * compared based on the integer value of the numeric fields. This means * that leading zeros are ignored. If the numeric field from both strings * has the same value but are different lengths, then the shorter is * considered to be before the longer. Without this flag, the ascending * order of some example strings is: * * a0003, a004, a04, a10, a2 * * With this flag, the ascending order is: * * a2, a0003, a04, a004, a10 } function string_compare_opts ( {compares strings, collate sequence control} in s1: univ string_var_arg_t; {input string 1} in s2: univ string_var_arg_t; {input string 2} in opts: string_comp_t) {option flags for collating seqence, etc} :sys_int_machine_t; {-1 = (s1<s2), 0 = (s1=s2), 1 = (s1>s2)} val_param; var p1, p2: string_index_t; {parse index for each string} c1, c2: char; {characters from S1 and S2, respectively} p1n, p2n: string_index_t; {parse index into numeric field} uc1, uc2: char; {upper case copies of C1 and C2} nlen1, nlen2: sys_int_machine_t; {length of numeric fields from strings 1 and 2} rlen1, rlen2: sys_int_machine_t; {remaining length of numeric fields} label nonum, before, after; begin p1 := 1; {start parsing each string at its start} p2 := 1; while (p1 <= s1.len) and (p2 <= s2.len) do begin {abort if at end of one string} if string_comp_num_k in opts then begin {need to compare numeric fields numerically} nlen1 := 0; {init length of numeric field from string 1} p1n := p1; {save parse index at start of numeric field} repeat {search forware for end of numeric field} c1 := s1.str[p1]; {fetch this character} p1 := p1 + 1; {advance to next character} if (c1 < '0') or (c1 > '9') then exit; {this character is not a digit ?} nlen1 := nlen1 + 1; {count one more digit in numeric field} until p1 > s1.len; nlen2 := 0; {init length of numeric field from string 2} p2n := p2; {save parse index at start of numeric field} repeat {search forware for end of numeric field} c2 := s2.str[p2]; {fetch this character} p2 := p2 + 1; {advance to next character} if (c2 < '0') or (c2 > '9') then exit; {this character is not a digit ?} nlen2 := nlen2 + 1; {count one more digit in numeric field} until p2 > s2.len; if (nlen1 = 0) or (nlen2 = 0) {no numeric fields to compare ?} then goto nonum; { * The current position in each string is the start of a numeric field, * and numeric interpretation of numeric fields is enabled. NLEN1 and * NLEN2 is the length of the numeric field in each string. Both are * guaranteed to be at least 1. P1 and P2 contain the indexes of where * to continue comparing the strings should the numeric fields be * equal. P1 and P2 may indicate the first character past the end of * their strings. P1N and P2N are the parse indexes to the start of * numeric fields. } rlen1 := nlen1; repeat {strip leading 0s from numeric field 1} if s1.str[p1n] <> '0' then exit; p1n := p1n + 1; rlen1 := rlen1 - 1; until rlen1 = 0; rlen2 := nlen2; repeat {strip leading 0s from numeric field 2} if s2.str[p2n] <> '0' then exit; p2n := p2n + 1; rlen2 := rlen2 - 1; until rlen2 = 0; if rlen1 < rlen2 then goto before; {compare based on number of non-zero digits} if rlen1 > rlen2 then goto after; while rlen1 > 0 do begin {compare the digits} c1 := s1.str[p1n]; {fetch each character} c2 := s2.str[p2n]; if c1 < c2 then goto before; {check for definite mismatch} if c1 > c2 then goto after; p1n := p1n + 1; {characters are equal, advance to next} p2n := p2n + 1; rlen1 := rlen1 - 1; {once less digit position to compare} end; if nlen1 < nlen2 then goto before; {numeric fields equal, compare field sizes} if nlen1 > nlen2 then goto after; next; {numeric fields totally equal, continue afterwards} end else begin {no numeric comparison} c1 := s1.str[p1]; {fetch character from string 1} p1 := p1 + 1; c2 := s2.str[p2]; {fetch character from string 2} p2 := p2 + 1; end ; nonum: {skip here if not comparing numeric fields} { * C1 and C2 are the characters fetched from each string to compare. P1 and P2 * are the indexes of the next characters. } if c1 = c2 then next; {no difference, go on to next char} uc1 := c1; {make upper case char from string 1} if (uc1 >= 'a') and (uc1 <= 'z') then uc1 := chr(ord(uc1) - ord('a') + ord('A')); uc2 := c2; {make upper case char from string 2} if (uc2 >= 'a') and (uc2 <= 'z') then uc2 := chr(ord(uc2) - ord('a') + ord('A')); if uc1 < uc2 then goto before; if uc1 > uc2 then goto after; if string_comp_ncase_k in opts then next; {case-insensitive ?} if string_comp_lcase_k in opts then begin {lower case letter before upper same ?} if c1 > c2 then goto before; goto after; end; if c1 < c2 then goto before; goto after; end; {back to compare next char in both strings} { * The strings are equal up to the length of the shortest string. } if s1.len < s2.len then goto before; {shorter strings come first} if s1.len > s2.len then goto after; string_compare_opts := 0; {indicate strings are truly identical} return; before: {s1 comes before s2} string_compare_opts := -1; return; after: {s1 comes after s2} string_compare_opts := 1; end; { ******************************************************************************** * * Function STRING_COMPARE (S1, S2) * * Determine the relative dictionary positions of two strings. The * function value will be -1 if S1 comes before S2, 0 if both strings * are identical, and +1 if S1 comes after S2. The ASCII collating * sequence is used. Upper case letters are collated immediately before * their lower case versions. For example, the following characters * are in order: A, a, B, b, C, c. } function string_compare ( {compares string relative dictionary positions} in s1: univ string_var_arg_t; {input string 1} in s2: univ string_var_arg_t) {input string 2} :sys_int_machine_t; {-1 = (s1<s2), 0 = (s1=s2), 1 = (s1>s2)} begin string_compare := string_compare_opts (s1, s2, []); end;
unit unit_pas2c64_types; {$mode delphi} interface // // primitive types supported in pas2c64: // ------------------------------------------- // Integer (16-Bit signed integers) // Word (16-Bit unsigned integer) // Single (32-Bit floating point number) // Boolean (True or False; internally represented by $ff and $00 respectively) // String (255 maximum characters length strings) // type TInt16 = Smallint; // 16-Bit signed integer TString255 = String[255]; // strings are max 255 characters TPrimitiveType = ( ptInteger, ptWord, ptSingle, ptBoolean, ptString ); // // primitive types can be of a certain class: // * a constant (128, $ff, -3.5e-2, 'hello world') // * a variable in memory // * a function result type TPrimitiveClass = ( pcConstant, pcVariable, pcFunction ); PPrimitiveTypeValue = ^TPrimitiveTypeValue; TPrimitiveTypeValue = packed record ValueStr: String; // string representation of this primitive value (if applicable) PrimitiveClass: TPrimitiveClass; case PrimitiveType : TPrimitiveType of ptInteger : (vInteger : TInt16); ptWord : (vWord : Word); ptSingle : (vSingle : Single); ptBoolean : (vBoolean : Boolean); ptString : (vString : TString255); end; function PrimitiveTypeToStr(const aPrimitiveType: TPrimitiveType): String; function StrToPrimitiveType(const aStr: String; out aPrimitiveType: TPrimitiveType): Boolean; function PrimitiveClassToStr(const aPrimitiveClass: TPrimitiveClass): String; function StrToPrimitiveClass(const aStr: String; out aPrimitiveClass: TPrimitiveClass): Boolean; function NewIntegerPrimitiveTypeConstant(const aValue: Integer): TPrimitiveTypeValue; function NewWordPrimitiveTypeConstant (const aValue: Word): TPrimitiveTypeValue; function NewSinglePrimitiveTypeConstant (const aValue: Single): TPrimitiveTypeValue; function NewBooleanPrimitiveTypeConstant(const aValue: Boolean): TPrimitiveTypeValue; function NewStringPrimitiveTypeConstant (const aValue: String): TPrimitiveTypeValue; implementation uses SysUtils; const cPrimitiveTypeStr: array[TPrimitiveType] of String = ( 'integer', 'word', 'single', 'boolean', 'string' ); cPrimitiveClassStr: array[TPrimitiveClass] of String = ( 'constant', 'variable', 'function' ); function PrimitiveTypeToStr(const aPrimitiveType: TPrimitiveType): String; // converts a primitive type to a string begin Result := cPrimitiveTypeStr[aPrimitiveType]; end; function StrToPrimitiveType(const aStr: String; out aPrimitiveType: TPrimitiveType): Boolean; // converts a string to a primitive type, and returns false if it failed var pt: TPrimitiveType; begin Result := False; for pt := Low(TPrimitiveType) to High(TPrimitiveType) do if LowerCase(cPrimitiveTypeStr[pt]) = LowerCase(aStr) then begin Result := True; aPrimitiveType := pt; Exit; end; end; function PrimitiveClassToStr(const aPrimitiveClass: TPrimitiveClass): String; // converts a primitive class to a string begin Result := cPrimitiveClassStr[aPrimitiveClass]; end; function StrToPrimitiveClass(const aStr: String; out aPrimitiveClass: TPrimitiveClass): Boolean; // converts a string to a primitive class, and returns false if it failed var pc: TPrimitiveClass; begin Result := False; for pc := Low(TPrimitiveClass) to High(TPrimitiveClass) do if LowerCase(cPrimitiveClassStr[pc]) = LowerCase(aStr) then begin Result := True; aPrimitiveClass := pc; Exit; end; end; function NewIntegerPrimitiveTypeConstant(const aValue: Integer): TPrimitiveTypeValue; begin Result.PrimitiveClass := pcConstant; Result.PrimitiveType := ptInteger; Result.vInteger := aValue; Result.ValueStr := IntToStr(aValue); end; function NewWordPrimitiveTypeConstant (const aValue: Word): TPrimitiveTypeValue; begin Result.PrimitiveClass := pcConstant; Result.PrimitiveType := ptWord; Result.vWord := aValue; Result.ValueStr := IntToStr(aValue); end; function NewSinglePrimitiveTypeConstant (const aValue: Single): TPrimitiveTypeValue; begin Result.PrimitiveClass := pcConstant; Result.PrimitiveType := ptSingle; Result.vSingle := aValue; Result.ValueStr := FloatToStr(aValue); end; function NewBooleanPrimitiveTypeConstant(const aValue: Boolean): TPrimitiveTypeValue; const cBooleanToStr: array[Boolean] of String = ( 'False', 'True' ); begin Result.PrimitiveClass := pcConstant; Result.PrimitiveType := ptBoolean; Result.vBoolean := aValue; Result.ValueStr := cBooleanToStr[aValue]; end; function NewStringPrimitiveTypeConstant (const aValue: String): TPrimitiveTypeValue; begin Result.PrimitiveClass := pcConstant; Result.PrimitiveType := ptString; Result.vString := aValue; Result.ValueStr := aValue; end; end.
{ ******************************************************************************* Title: T2Ti ERP Description: Janela Cadastro de Cheque The MIT License Copyright: Copyright (C) 2015 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com</p> t2ti.com@gmail.com @author Albert Eije (T2Ti.COM) @version 2.0 ******************************************************************************* } unit UCheque; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UTelaCadastro, DB, DBClient, Menus, StdCtrls, ExtCtrls, Buttons, Grids, DBGrids, JvExDBGrids, JvDBGrid, JvDBUltimGrid, ComCtrls, ChequeVO, ChequeController, Tipos, Atributos, Constantes, LabeledCtrls, JvToolEdit, Mask, JvExMask, JvBaseEdits, Math, StrUtils, Controller; type [TFormDescription(TConstantes.MODULO_CADASTROS, 'Cheque')] TFCheque = class(TFTelaCadastro) BevelEdits: TBevel; EditTalonarioCheque: TLabeledEdit; EditDataStatus: TLabeledDateEdit; EditIdTalonarioCheque: TLabeledCalcEdit; EditNumero: TLabeledCalcEdit; ComboboxStatusCheque: TLabeledComboBox; procedure FormCreate(Sender: TObject); procedure EditIdTalonarioChequeKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } public { Public declarations } procedure GridParaEdits; override; // Controles CRUD function DoInserir: Boolean; override; function DoEditar: Boolean; override; function DoExcluir: Boolean; override; function DoSalvar: Boolean; override; end; var FCheque: TFCheque; implementation uses ULookup, Biblioteca, UDataModule, TalonarioChequeVO, TalonarioChequeController; {$R *.dfm} {$REGION 'Infra'} procedure TFCheque.FormCreate(Sender: TObject); begin ClasseObjetoGridVO := TChequeVO; ObjetoController := TChequeController.Create; inherited; end; {$ENDREGION} {$REGION 'Controles CRUD'} function TFCheque.DoInserir: Boolean; begin Result := inherited DoInserir; if Result then begin EditIdTalonarioCheque.SetFocus; end; end; function TFCheque.DoEditar: Boolean; begin Result := inherited DoEditar; if Result then begin EditIdTalonarioCheque.SetFocus; end; end; function TFCheque.DoExcluir: Boolean; begin if inherited DoExcluir then begin try TController.ExecutarMetodo('ChequeController.TChequeController', 'Exclui', [IdRegistroSelecionado], 'DELETE', 'Boolean'); Result := TController.RetornoBoolean; except Result := False; end; end else begin Result := False; end; if Result then TController.ExecutarMetodo('ChequeController.TChequeController', 'Consulta', [Trim(Filtro), Pagina.ToString, False], 'GET', 'Lista'); end; function TFCheque.DoSalvar: Boolean; begin Result := inherited DoSalvar; if Result then begin try if not Assigned(ObjetoVO) then ObjetoVO := TChequeVO.Create; TChequeVO(ObjetoVO).IdTalonarioCheque := EditIdTalonarioCheque.AsInteger; TChequeVO(ObjetoVO).Numero := EditNumero.AsInteger; TChequeVO(ObjetoVO).StatusCheque := Copy(ComboboxStatusCheque.Text, 1, 1); TChequeVO(ObjetoVO).DataStatus := EditDataStatus.Date; if StatusTela = stInserindo then begin TController.ExecutarMetodo('ChequeController.TChequeController', 'Insere', [TChequeVO(ObjetoVO)], 'PUT', 'Lista'); end else if StatusTela = stEditando then begin if TChequeVO(ObjetoVO).ToJSONString <> StringObjetoOld then begin TController.ExecutarMetodo('ChequeController.TChequeController', 'Altera', [TChequeVO(ObjetoVO)], 'POST', 'Boolean'); end else Application.MessageBox('Nenhum dado foi alterado.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION); end; except Result := False; end; end; end; {$ENDREGION} {$REGION 'Controle de Grid'} procedure TFCheque.GridParaEdits; begin inherited; if not CDSGrid.IsEmpty then begin ObjetoVO := TChequeVO(TController.BuscarObjeto('ChequeController.TChequeController', 'ConsultaObjeto', ['ID=' + IdRegistroSelecionado.ToString], 'GET')); end; if Assigned(ObjetoVO) then begin EditIdTalonarioCheque.AsInteger := TChequeVO(ObjetoVO).IdTalonarioCheque; EditTalonarioCheque.Text := TChequeVO(ObjetoVO).TalonarioChequeTalao; EditNumero.AsInteger := TChequeVO(ObjetoVO).Numero; ComboboxStatusCheque.ItemIndex := AnsiIndexStr(TChequeVO(ObjetoVO).StatusCheque, ['E', 'B', 'U', 'C', 'N']); EditDataStatus.Date := TChequeVO(ObjetoVO).DataStatus; // Serializa o objeto para consultar posteriormente se houve alterações FormatSettings.DecimalSeparator := '.'; StringObjetoOld := ObjetoVO.ToJSONString; FormatSettings.DecimalSeparator := ','; end; end; {$ENDREGION} {$REGION 'Campos Transientes'} procedure TFCheque.EditIdTalonarioChequeKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var Filtro: String; begin if Key = VK_F1 then begin if EditIdTalonarioCheque.Value <> 0 then Filtro := 'ID = ' + EditIdTalonarioCheque.Text else Filtro := 'ID=0'; try EditIdTalonarioCheque.Clear; EditTalonarioCheque.Clear; if not PopulaCamposTransientes(Filtro, TTalonarioChequeVO, TTalonarioChequeController) then PopulaCamposTransientesLookup(TTalonarioChequeVO, TTalonarioChequeController); if CDSTransiente.RecordCount > 0 then begin EditIdTalonarioCheque.Text := CDSTransiente.FieldByName('ID').AsString; EditTalonarioCheque.Text := CDSTransiente.FieldByName('TALAO').AsString; end else begin Exit; EditIdTalonarioCheque.SetFocus; end; finally CDSTransiente.Close; end; end; end; {$ENDREGION} end.
Program Aluno_Nota_10; { Array de inteiros com capacidade de 10 notas } Var i : integer; notas : array[1..10] of integer; Begin { Lendo 10 notas } for i := 1 to 10 do Begin Write('Digite a nota ', i, ': '); Readln(notas[i]); End; { Reutilizando a variável i para o segundo loop } for i := 1 to 10 do Begin if ( notas[i] = 10 ) then Begin Writeln('O aluno ', i, ' tem nota maxima'); End; End; End.
unit AsyncHttpServer.Response; interface uses System.SysUtils, AsyncIO, AsyncHttpServer.Headers; type HttpStatus = ( StatusNoStatus = 0, StatusOK = 200, StatusCreated = 201, StatusAccepted = 202, StatusNoContent = 204, StatusMultipleChoices = 300, StatusMovedPermanently = 301, StatusMovedTemporarily = 302, StatusNotModified = 304, StatusBadRequest = 400, StatusUnauthorized = 401, StatusForbidden = 403, StatusNotFound = 404, StatusInternalServerError = 500, StatusNotImplemented = 501, StatusBadGateway = 502, StatusServiceUnavailable = 503 ); HttpStatusHelper = record helper for HttpStatus function ToString(): string; end; HttpResponse = record Status: HttpStatus; Headers: HttpHeaders; Content: TBytes; ContentStream: AsyncStream; // get a StreamBuffer containing the response, including Content // ContentStream needs to be handled separately if assigned // TODO - use array of MemoryBuffer once that's supported function ToBuffer(): StreamBuffer; end; function StandardResponse(const Status: HttpStatus): HttpResponse; implementation uses System.Classes, Generics.Collections; type TStreamHelper = class helper for TStream procedure WriteASCIIData(const s: string); end; { TStreamHelper } procedure TStreamHelper.WriteASCIIData(const s: string); var b: TBytes; begin b := TEncoding.ASCII.GetBytes(s); Self.WriteBuffer(b, Length(b)); end; { HttpStatusHelper } function HttpStatusHelper.ToString: string; begin case Self of StatusOK: result := 'OK'; StatusCreated: result := 'Created'; StatusAccepted: result := 'Accepted'; StatusNoContent: result := 'No Content'; StatusMultipleChoices: result := 'Multiple Choices'; StatusMovedPermanently: result := 'Moved Permanently'; StatusMovedTemporarily: result := 'Moved Temporarily'; StatusNotModified: result := 'Not Modified'; StatusBadRequest: result := 'Bad Request'; StatusUnauthorized: result := 'Unauthorized'; StatusForbidden: result := 'Forbidden'; StatusNotFound: result := 'Not Found'; StatusInternalServerError: result := 'Internal ServerError'; StatusNotImplemented: result := 'Not Implemented'; StatusBadGateway: result := 'Bad Gateway'; StatusServiceUnavailable: result := 'Service Unavailable'; else raise EArgumentException.Create('Invalid HTTP status'); end; end; function StandardResponse(const Status: HttpStatus): HttpResponse; var s: string; begin if (Status = StatusNotModified) then begin // no entity body for this one result.Status := Status; result.Content := nil; result.ContentStream := nil; result.Headers := nil; end else begin s := Status.ToString; s := '<html>' + '<title>' + s + '</title>' + '<body><h1>' + IntToStr(Ord(Status)) + ' ' + s + '</h1></body>' + '</html>'; result.Status := Status; result.Content := TEncoding.ASCII.GetBytes(s); result.ContentStream := nil; result.Headers := nil; result.Headers.Value['Content-Length'] := IntToStr(Length(result.Content)); result.Headers.Value['Content-Type'] := 'text/html'; end; end; { HttpResponse } function HttpResponse.ToBuffer: StreamBuffer; var i: integer; begin // so currently this is very sub-optimal // however without scattered buffer support it's the best we can do result := StreamBuffer.Create(); result.Stream.WriteASCIIData('HTTP/1.0 ' + IntToStr(Ord(Status)) + ' ' + Status.ToString + #13#10); for i := 0 to High(Headers) do begin result.Stream.WriteASCIIData(Headers[i].Name); result.Stream.WriteASCIIData(': '); result.Stream.WriteASCIIData(Headers[i].Value); result.Stream.WriteASCIIData(#13#10); // CRLF end; result.Stream.WriteASCIIData(#13#10); // CRLF if (Length(Content) > 0) then begin result.Stream.WriteBuffer(Content, Length(Content)); end; end; end.
unit ULocalBackupWatch; interface uses UChangeInfo, UFileWatcher, SysUtils, UMyUtil, Classes, SyncObjs, DateUtils; type {$Region ' 本地路径 监听器 ' } // 路径是否存在 监听 TLocalBackupSourceExistThread = class( TWatchPathExistThread ) protected procedure WatchPathNotEixst( WatchPath : string );override; procedure WatchPathExist( WatchPath : string );override; end; // 本地备份文件 变化检测器 TMyLocalBackupSourceWatcher = class public LocalBackupSourceExistThread : TLocalBackupSourceExistThread; public constructor Create; procedure StopWatch; destructor Destroy; override; public procedure AddWatchExistPath( FullPath : string; IsExist : Boolean ); procedure RemoveWatchExistPath( FullPath : string ); end; {$EndRegion} {$Region ' 目标路径 监听器 ' } // 监听线程 TLocalBackupDesPathWatchThread = class( TThread ) private PathLock : TCriticalSection; ExistPathList : TStringList; NotExistPathList : TStringList; UnModifyPathList : TStringList; public constructor Create; destructor Destroy; override; protected procedure Execute; override; private procedure CheckPathExist; procedure CheckPathNotExist; procedure CheckPathUnmodify; private procedure DesExistChange( Path : string; IsExist : Boolean ); procedure DesCanModify( Path : string ); end; {$Region ' 监听 修改 ' } // 父类 TLocalBackupDesPathWatcherChange = class( TChangeInfo ) public Path : string; public PathLock : TCriticalSection; ExistPathList : TStringList; NotExistPathList : TStringList; UnModifyPathList : TStringList; public constructor Create( _Path : string ); procedure Update;override; end; // 添加 存在 TLocalBackupDesPathWatcherAddExist = class( TLocalBackupDesPathWatcherChange ) public procedure Update;override; end; // 添加 不存在 TLocalBackupDesPathWatcherAddNotExist = class( TLocalBackupDesPathWatcherChange ) public procedure Update;override; end; // 添加 不可修改 TLocalBackupDesPathWatcherAddUnmodify = class( TLocalBackupDesPathWatcherChange ) public procedure Update;override; end; // 删除 TLocalBackupDesPathWatcherRemove = class( TLocalBackupDesPathWatcherChange ) public procedure Update;override; end; {$EndRegion} // 监听对象 TMyLocalBackupDesWatcher = class( TMyChangeInfo ) public LocalBackupDesPathWatchThread : TLocalBackupDesPathWatchThread; public constructor Create; procedure StopWatch; end; {$EndRegion} var // 源路径 MyLocalBackupSourceWatcher : TMyLocalBackupSourceWatcher; // 目标路径 MyLocalBackupDesWatcher : TMyLocalBackupDesWatcher; implementation uses ULocalBackupControl, ULocalBackupInfo, UMyBackupInfo, USettingInfo; { TMyLocalBackupFileWatcher } procedure TMyLocalBackupSourceWatcher.AddWatchExistPath(FullPath: string; IsExist : Boolean); begin LocalBackupSourceExistThread.AddWatchPath( FullPath, IsExist ); end; constructor TMyLocalBackupSourceWatcher.Create; begin LocalBackupSourceExistThread := TLocalBackupSourceExistThread.Create; LocalBackupSourceExistThread.Resume; end; destructor TMyLocalBackupSourceWatcher.Destroy; begin inherited; end; procedure TMyLocalBackupSourceWatcher.RemoveWatchExistPath(FullPath: string); begin LocalBackupSourceExistThread.RemoveWatchPath( FullPath ); end; procedure TMyLocalBackupSourceWatcher.StopWatch; begin // 停止 监听 LocalBackupSourceExistThread.Free; end; { TLocalBackupSourceExistThread } procedure TLocalBackupSourceExistThread.WatchPathExist(WatchPath: string); var LocalBackupSourceSetExistHandle : TLocalBackupSourceSetExistHandle; begin LocalBackupSourceSetExistHandle := TLocalBackupSourceSetExistHandle.Create( WatchPath ); LocalBackupSourceSetExistHandle.SetIsExist( True ); LocalBackupSourceSetExistHandle.Update; LocalBackupSourceSetExistHandle.Free; end; procedure TLocalBackupSourceExistThread.WatchPathNotEixst(WatchPath: string); var LocalBackupSourceSetExistHandle : TLocalBackupSourceSetExistHandle; begin LocalBackupSourceSetExistHandle := TLocalBackupSourceSetExistHandle.Create( WatchPath ); LocalBackupSourceSetExistHandle.SetIsExist( False ); LocalBackupSourceSetExistHandle.Update; LocalBackupSourceSetExistHandle.Free; end; { TLocalBackupDesPathWatcherChange } constructor TLocalBackupDesPathWatcherChange.Create(_Path: string); begin Path := _Path; end; procedure TLocalBackupDesPathWatcherChange.Update; begin PathLock := MyLocalBackupDesWatcher.LocalBackupDesPathWatchThread.PathLock; ExistPathList := MyLocalBackupDesWatcher.LocalBackupDesPathWatchThread.ExistPathList; NotExistPathList := MyLocalBackupDesWatcher.LocalBackupDesPathWatchThread.NotExistPathList; UnModifyPathList := MyLocalBackupDesWatcher.LocalBackupDesPathWatchThread.UnModifyPathList; end; { TLocalBackupDesPathWatcherAddExist } procedure TLocalBackupDesPathWatcherAddExist.Update; begin inherited; PathLock.Enter; if ExistPathList.IndexOf( Path ) < 0 then ExistPathList.Add( Path ); PathLock.Leave; end; { TLocalBackupDesPathWatcherAddNotExist } procedure TLocalBackupDesPathWatcherAddNotExist.Update; begin inherited; PathLock.Enter; if NotExistPathList.IndexOf( Path ) < 0 then NotExistPathList.Add( Path ); PathLock.Leave; end; { TLocalBackupDesPathWatcherAddUnmodify } procedure TLocalBackupDesPathWatcherAddUnmodify.Update; begin inherited; PathLock.Enter; if UnModifyPathList.IndexOf( Path ) < 0 then UnModifyPathList.Add( Path ); PathLock.Leave; end; { TDesWritableThread } procedure TLocalBackupDesPathWatchThread.DesExistChange(Path: string; IsExist: Boolean); var LocalBackupDesExistHandle : TLocalBackupDesExistHandle; begin LocalBackupDesExistHandle := TLocalBackupDesExistHandle.Create( Path ); LocalBackupDesExistHandle.SetIsExist( IsExist ); LocalBackupDesExistHandle.Update; LocalBackupDesExistHandle.Free; end; procedure TLocalBackupDesPathWatchThread.CheckPathExist; var i : Integer; Path : string; begin PathLock.Enter; for i := ExistPathList.Count - 1 downto 0 do begin Path := ExistPathList[i]; // 没有变化 跳过 if MyDesPathUtil.getIsExist( Path ) then Continue; // 路径变化 ExistPathList.Delete(i); NotExistPathList.Add( Path ); // 调用外部变化 DesExistChange( Path, False ); end; PathLock.Leave; end; procedure TLocalBackupDesPathWatchThread.CheckPathNotExist; var i : Integer; Path : string; begin PathLock.Enter; for i := NotExistPathList.Count - 1 downto 0 do begin Path := NotExistPathList[i]; // 没有变化 跳过 if not MyDesPathUtil.getIsExist( Path ) then Continue; // 路径变化 NotExistPathList.Delete(i); ExistPathList.Add( Path ); // 调用外部变化 DesExistChange( Path, True ); end; PathLock.Leave; end; procedure TLocalBackupDesPathWatchThread.CheckPathUnmodify; var i : Integer; Path : string; begin PathLock.Enter; for i := UnModifyPathList.Count - 1 downto 0 do begin Path := UnModifyPathList[i]; // 没有变化 跳过 if not MyDesPathUtil.getIsModify( Path ) then Continue; // 路径变化 UnModifyPathList.Delete(i); // 调用外部变化 DesCanModify( Path ); end; PathLock.Leave; end; constructor TLocalBackupDesPathWatchThread.Create; begin inherited Create( True ); PathLock := TCriticalSection.Create; ExistPathList := TStringList.Create; NotExistPathList := TStringList.Create; UnModifyPathList := TStringList.Create; end; procedure TLocalBackupDesPathWatchThread.DesCanModify(Path: string); var BackupDesIsModifyHandle : TLocalBackupDesModifyHandle; begin BackupDesIsModifyHandle := TLocalBackupDesModifyHandle.Create( Path ); BackupDesIsModifyHandle.SetIsModify( True ); BackupDesIsModifyHandle.Update; BackupDesIsModifyHandle.Free; end; destructor TLocalBackupDesPathWatchThread.Destroy; begin Terminate; Resume; WaitFor; UnModifyPathList.Free; NotExistPathList.Free; ExistPathList.Free; PathLock.Free; inherited; end; procedure TLocalBackupDesPathWatchThread.Execute; var StartTime : TDateTime; begin while not Terminated do begin StartTime := Now; if not Terminated and ( SecondsBetween( Now, StartTime ) < 1 ) then Sleep(100); if Terminated then Break; // 检测变化 CheckPathExist; CheckPathNotExist; CheckPathUnmodify; end; inherited; end; { TLocalBackupDesPathWatcherRemove } procedure TLocalBackupDesPathWatcherRemove.Update; var i : Integer; begin inherited; PathLock.Enter; i := ExistPathList.IndexOf( Path ); if i >= 0 then ExistPathList.Delete(i); i := NotExistPathList.IndexOf( Path ); if i >= 0 then NotExistPathList.Delete(i); i := UnModifyPathList.IndexOf( Path ); if i >= 0 then UnModifyPathList.Delete(i); PathLock.Leave; end; { TMyLocalBackupDesExistWatcher } constructor TMyLocalBackupDesWatcher.Create; begin inherited; LocalBackupDesPathWatchThread := TLocalBackupDesPathWatchThread.Create; LocalBackupDesPathWatchThread.Resume; end; procedure TMyLocalBackupDesWatcher.StopWatch; begin StopThread; LocalBackupDesPathWatchThread.Free; end; end.
unit Main; interface uses System.SysUtils, System.Classes, Vcl.Controls, Vcl.Forms, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.Buttons, Vcl.Dialogs, MapTypes, MapControl, Loader; type TForm1 = class(TForm) Panel1: TPanel; ZoomInButton: TButton; PanDownButton: TButton; PanUpButton: TButton; PanRightButton: TButton; PanLeftButton: TButton; ZoomAllButton: TButton; ZoomOutButton: TButton; comboPropertyValues: TComboBox; LoadButton: TButton; MapControl1: TMapControl; Zoom1x1: TButton; StatusBar1: TStatusBar; ZoommingButton: TSpeedButton; PanningButton: TSpeedButton; PageControl1: TPageControl; TabSheet1: TTabSheet; TabSheet2: TTabSheet; MapControl2: TMapControl; Panel2: TPanel; Panel3: TPanel; comboPropertyNames: TComboBox; comboLayers: TComboBox; dialogOpenProject: TOpenDialog; procedure LoadButtonClick(Sender: TObject); procedure ZoomInButtonClick(Sender: TObject); procedure ZoomOutButtonClick(Sender: TObject); procedure ZoomAllButtonClick(Sender: TObject); procedure comboPropertyValuesChange(Sender: TObject); procedure PanDownButtonClick(Sender: TObject); procedure PanLeftButtonClick(Sender: TObject); procedure PanRightButtonClick(Sender: TObject); procedure PanUpButtonClick(Sender: TObject); procedure Zoom1x1Click(Sender: TObject); // used by both MapControls procedure MapControlMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); procedure ZoommingButtonClick(Sender: TObject); procedure PanningButtonClick(Sender: TObject); procedure PageControl1Change(Sender: TObject); procedure FormDestroy(Sender: TObject); procedure comboPropertyNamesChange(Sender: TObject); procedure comboLayersChange(Sender: TObject); private { Private declarations } FProject: TProject; procedure ActivateModel; function IsModelActive: boolean; function CurrentMapControl: TMapControl; procedure UpdateGUI; procedure UpdateLayersCombo; procedure UpdatePropertyNamesCombo; procedure UpdatePropertyValuesCombo(const APropertyName: string); end; var Form1: TForm1; implementation uses GDIPAPI, Properties; {$R *.dfm} procedure TForm1.LoadButtonClick(Sender: TObject); begin if dialogOpenProject.Execute then begin LoadButton.Enabled := False; FProject := TProject.Create(dialogOpenProject.FileName); PageControl1.Visible := True; Screen.Cursor := crHourglass; try FProject.Load; MapControl1.Win := FProject.ModelWin; MapControl1.ZoomAll; MapControl2.Win := FProject.LayoutWin; MapControl2.ZoomAll; ActivateModel; finally Screen.Cursor := crDefault; end; end; end; procedure TForm1.MapControlMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin if not (CurrentMapControl.HasData) then Exit; StatusBar1.Panels[0].Text := {'PixelXY: ' + }IntToStr(X) + ',' + IntToStr(Y); StatusBar1.Panels[1].Text := {' WorldXY: ' +} FloatToStrF(CurrentMapControl.WorldPos.Y, ffFixed, 10, 3) + ',' + FloatToStrF(CurrentMapControl.WorldPos.X, ffFixed, 10, 3); end; procedure TForm1.ZoomInButtonClick(Sender: TObject); begin CurrentMapControl.ZoomIn; end; procedure TForm1.ZoomOutButtonClick(Sender: TObject); begin CurrentMapControl.ZoomOut; end; procedure TForm1.Zoom1x1Click(Sender: TObject); begin CurrentMapControl.Zoom1x1; end; procedure TForm1.ZoomAllButtonClick(Sender: TObject); begin CurrentMapControl.ZoomAll; end; procedure TForm1.ActivateModel; begin PageControl1.ActivePageIndex := 0; UpdateGUI; end; procedure TForm1.comboPropertyValuesChange(Sender: TObject); var propName, propValue: string; Style: TDrawStyle; layIndex: Integer; begin layIndex := comboLayers.ItemIndex; propName := comboPropertyNames.Text; propValue := comboPropertyValues.Text; // populate style manager by rules Layer == Color, but first clear with CurrentMapControl do begin (Data.Features[layIndex] as TLayer).ClearStyles; Style.PenColor := aclRed; Style.BrushColor := aclLightCoral; (Data.Features[layIndex] as TLayer).AddStyle(propName, propValue, style); end; CurrentMapControl.Repaint; end; procedure TForm1.comboLayersChange(Sender: TObject); begin UpdatePropertyNamesCombo; end; procedure TForm1.comboPropertyNamesChange(Sender: TObject); begin UpdatePropertyValuesCombo(comboPropertyNames.Text); end; function TForm1.CurrentMapControl: TMapControl; begin if IsModelActive then Result := MapControl1 else Result := MapControl2; end; procedure TForm1.FormDestroy(Sender: TObject); begin FProject.Free; end; procedure TForm1.UpdateGUI; begin UpdateLayersCombo; comboPropertyNames.Clear; comboPropertyValues.Clear; // tools ZoommingButton.Down := mcsZooming in CurrentMapControl.Tool; PanningButton.Down := mcsPanning in CurrentMapControl.Tool; end; procedure TForm1.UpdateLayersCombo; var count: Integer; F: TFeature; begin count := 1; comboLayers.Clear; for F in CurrentMapControl.Data.Features do begin comboLayers.Items.Add('L' + IntToStr(count)); count := count + 1; end; end; procedure TForm1.UpdatePropertyNamesCombo; var layIndex: Integer; begin layIndex := comboLayers.ItemIndex; comboPropertyNames.Clear; comboPropertyValues.Clear; comboPropertyNames.Items.Assign( (CurrentMapControl.Data.Features[layIndex] as TLayer).Model.GetPropertyNames); end; procedure TForm1.UpdatePropertyValuesCombo(const APropertyName: string); var layIndex: Integer; begin layIndex := comboLayers.ItemIndex; comboPropertyValues.Clear; comboPropertyValues.Items.Assign( (CurrentMapControl.Data.Features[layIndex] as TLayer).Model.GetPropertyValues(APropertyName)); end; function TForm1.IsModelActive: boolean; begin Result := PageControl1.ActivePageIndex = 0; end; procedure TForm1.PageControl1Change(Sender: TObject); begin UpdateGUI; end; procedure TForm1.PanDownButtonClick(Sender: TObject); begin CurrentMapControl.PanDown; end; procedure TForm1.PanLeftButtonClick(Sender: TObject); begin CurrentMapControl.PanLeft; end; procedure TForm1.PanningButtonClick(Sender: TObject); begin PanningButton.Down := True; CurrentMapControl.Tool := [mcsPanning]; end; procedure TForm1.PanRightButtonClick(Sender: TObject); begin CurrentMapControl.PanRight; end; procedure TForm1.PanUpButtonClick(Sender: TObject); begin CurrentMapControl.PanUp; end; procedure TForm1.ZoommingButtonClick(Sender: TObject); begin ZoommingButton.Down := True; CurrentMapControl.Tool := [mcsZooming]; end; end.
unit unit_pas2c64_operators; {$mode delphi} interface uses SysUtils, unit_pas2c64_types, unit_pas2c64_CodeGenerator; type OperatorException = class(Exception); TOperatorType = ( otNeg, otNot, otMul, otDiv, otSub, otAdd, otIntDiv, otIntMod, otAnd, otOr, otXor, otShl, otShr ); TOperator = class private FOperatorType: TOperatorType; FOperandCount: Integer; protected procedure Error(const aErrorMsg: String); public constructor Create(const aOperatorType: TOperatorType; const aOperandCount: Integer); function Simplify(const a,b: TPrimitiveTypeValue; out r: TPrimitiveTypeValue): Boolean; virtual; abstract; procedure EmitCode(const aCodeGen: TCodeGenerator_C64); virtual; abstract; property OperatorType: TOperatorType read FOperatorType; property OperandCount: Integer read FOperandCount; end; TNegOperator = class(TOperator) public constructor Create; reintroduce; function Simplify(const a,b: TPrimitiveTypeValue; out r: TPrimitiveTypeValue): Boolean; override; procedure EmitCode(const aCodeGen: TCodeGenerator_C64); override; end; TNotOperator = class(TOperator) public constructor Create; reintroduce; function Simplify(const a,b: TPrimitiveTypeValue; out r: TPrimitiveTypeValue): Boolean; override; procedure EmitCode(const aCodeGen: TCodeGenerator_C64); override; end; TAddOperator = class(TOperator) public constructor Create; reintroduce; function Simplify(const a,b: TPrimitiveTypeValue; out r: TPrimitiveTypeValue): Boolean; override; procedure EmitCode(const aCodeGen: TCodeGenerator_C64); override; end; TSubOperator = class(TOperator) public constructor Create; reintroduce; function Simplify(const a,b: TPrimitiveTypeValue; out r: TPrimitiveTypeValue): Boolean; override; procedure EmitCode(const aCodeGen: TCodeGenerator_C64); override; end; implementation constructor TOperator.Create(const aOperatorType: TOperatorType; const aOperandCount: Integer); begin inherited Create; FOperatorType := aOperatorType; FOperandCount := aOperandCount; end; procedure TOperator.Error(const aErrorMsg: String); begin raise OperatorException.Create(aErrorMsg); end; // // concrete operator classes // constructor TNegOperator.Create; begin inherited Create(otNeg,1); end; function TNegOperator.Simplify(const a,b: TPrimitiveTypeValue; out r: TPrimitiveTypeValue): Boolean; begin Result := False; if not (b.PrimitiveType in [ptWord,ptInteger,ptSingle]) then Error('Unary subtract operation: Incompatible type "'+PrimitiveTypeToStr(b.PrimitiveType)+'"'); if b.PrimitiveClass <> pcConstant then Exit; // only evaluate constants case b.PrimitiveType of ptWord : r := NewWordPrimitiveTypeConstant ((b.vWord xor $ffff) + 1); ptInteger : r := NewIntegerPrimitiveTypeConstant(-b.vInteger); ptBoolean : r := NewBooleanPrimitiveTypeConstant(-b.vSingle); end; Result := True; end; procedure TNegOperator.EmitCode(const aCodeGen: TCodeGenerator_C64); begin end; constructor TNotOperator.Create; begin inherited Create(otNot,1); end; function TNotOperator.Simplify(const a,b: TPrimitiveTypeValue; out r: TPrimitiveTypeValue): Boolean; begin Result := False; if not (b.PrimitiveType in [ptWord,ptInteger,ptBoolean]) then Error('Not operation: Incompatible type "'+PrimitiveTypeToStr(b.PrimitiveType)+'"'); if b.PrimitiveClass <> pcConstant then Exit; // only evaluate constants case b.PrimitiveType of ptWord : r := NewWordPrimitiveTypeConstant (not b.vWord); ptInteger : r := NewIntegerPrimitiveTypeConstant(not b.vInteger); ptBoolean : r := NewBooleanPrimitiveTypeConstant(not b.vBoolean); end; Result := True; end; procedure TNotOperator.EmitCode(const aCodeGen: TCodeGenerator_C64); begin end; constructor TAddOperator.Create; begin inherited Create(otAdd,2); end; function TAddOperator.Simplify(const a,b: TPrimitiveTypeValue; out r: TPrimitiveTypeValue): Boolean; begin Result := False; if not(a.PrimitiveType in [ptWord,ptInteger,ptBoolean]) and not(b.PrimitiveType in [ptWord,ptInteger,ptBoolean])then Error('Not operation: Incompatible type(s) - "'+PrimitiveTypeToStr(b.PrimitiveType)+'"'); if (a.PrimitiveClass <> pcConstant) or (b.PrimitiveClass <> pcConstant) then Exit; // only evaluate constants case b.PrimitiveType of ptWord : r := NewWordPrimitiveTypeConstant (a.vWord + b.vWord); ptInteger : r := NewIntegerPrimitiveTypeConstant(not b.vInteger); ptBoolean : r := NewBooleanPrimitiveTypeConstant(not b.vBoolean); end; Result := True; end; procedure TAddOperator.EmitCode(const aCodeGen: TCodeGenerator_C64); begin end; constructor TSubOperator.Create; begin inherited Create(otSub,2); end; function TSubOperator.Simplify(const a,b: TPrimitiveTypeValue; out r: TPrimitiveTypeValue): Boolean; begin Result := False; end; procedure TSubOperator.EmitCode(const aCodeGen: TCodeGenerator_C64); begin end; end.
program testmod01(output); begin writeln('Should be 19: ', 131962 mod 309); {because mod takes precedence over the unary minus, this is read -1 * (23373077 mod 727)} writeln('Should be -27: ',-23373077 mod 727); {this forces the mod to be of a negative number, testing 6.7.2.2 of the iso standard} writeln('Should be 1: ', (-5) mod 2); end.
{ All the routines to implement a dumb sphere object. } module type1_sphere; define type1_sphere_class_make; %include 'ray_type1_2.ins.pas'; type sphere_data_p_t = ^sphere_data_t; sphere_data_t = record {data record pointed to by object block} visprop_p: type1_visprop_p_t; {pointer to visual properties block} center: vect_3d_fp1_t; {XYZ coordinates of center point} radius: single; {sphere radius} radius2: single; {sphere radius squared} end; sphere_hit_geom_p_t = ^sphere_hit_geom_t; sphere_hit_geom_t = record {saved data from intersection check} base: type1_hit_geom_t; {mandatory part of hit geometry save area} ray_point: vect_3d_t; {ray origin point in object's space} ray_vect: vect_3d_t; {ray unit vector in object's space} end; { ******************************************************************************** * * Local subroutine TYPE1_SPHERE_CREATE (OBJECT, CREA, STAT) * * Fill in the new object in OBJECT. CREA is the user data parameters for this * object. STAT is the standard system error return code. } procedure type1_sphere_create ( {create new primitive with custom data} in out object: ray_object_t; {object to be filled in} in gcrea_p: univ_ptr; {data for creating this object instance} out stat: sys_err_t); {completion status code} val_param; var crea_p: type1_sphere_crea_data_p_t; {pointer to creation data in our format} data_p: sphere_data_p_t; {pointer to internal object data} begin sys_error_none (stat); {init to no error} crea_p := gcrea_p; {get pointer to create data in our format} util_mem_grab ( {allocate data block for new object} sizeof(data_p^), ray_mem_p^, false, data_p); object.data_p := data_p; {set pointer to object data block} data_p^.visprop_p := crea_p^.visprop_p; {copy pointer to visual properties block} data_p^.center.x := crea_p^.center.x; {copy coordinate of sphere center} data_p^.center.y := crea_p^.center.y; data_p^.center.z := crea_p^.center.z; data_p^.radius := crea_p^.radius; {copy sphere radius} data_p^.radius2 := sqr(crea_p^.radius); {save radius squared for speedup} end; { ******************************************************************************** * * Local function TYPE1_SPHERE_INTERSECT_CHECK ( * GRAY, OBJECT, GPARMS, HIT_INFO, SHADER) * * Check ray and object for an intersection. If so, return TRUE, and save any * partial results in HIT_INFO. These partial results may be used later to get * detailed information about the intersection geometry. } function type1_sphere_intersect_check ( {check for ray/object intersection} in out gray: univ ray_base_t; {input ray descriptor} in var object: ray_object_t; {input object to intersect ray with} in gparms_p: univ_ptr; {pointer to run time TYPEn-specific params} out hit_info: ray_hit_info_t; {handle to routines and data to get hit color} out shader: ray_shader_t) {pointer to shader to resolve color here} :boolean; {TRUE if ray does hit object} val_param; var ray_p: type1_ray_p_t; {pointer to ray in our format} parms_p: type1_object_parms_p_t; {pointer to runtime parameters in our format} dp: sphere_data_p_t; {pointer to object unique data block} close_l: real; {ray length to closest point to center} close_d2: real; {closest ray-center distance squared} ofs: real; {delta from close point to intersects} hit_l: real; {ray length to hit point} hit_geom_p: sphere_hit_geom_p_t; {pointer to hit geometry block} label no_hit, hit; begin ray_p := univ_ptr(addr(gray)); {make pointer to ray, our format} dp := object.data_p; {make local pointer to object data, our format} parms_p := gparms_p; {make pointer to runtime parameters, our format} close_l := {make ray length to closest approach} (ray_p^.vect.x * (dp^.center.x - ray_p^.point.x)) + (ray_p^.vect.y * (dp^.center.y - ray_p^.point.y)) + (ray_p^.vect.z * (dp^.center.z - ray_p^.point.z)); if (close_l + dp^.radius) < ray_p^.min_dist {whole object before valid interval ?} then goto no_hit; if (close_l - dp^.radius) > ray_p^.max_dist {whole object after valid interval ?} then goto no_hit; close_d2 := {make square of center to ray distance} sqr(dp^.center.x - (ray_p^.point.x + close_l*ray_p^.vect.x)) + sqr(dp^.center.y - (ray_p^.point.y + close_l*ray_p^.vect.y)) + sqr(dp^.center.z - (ray_p^.point.z + close_l*ray_p^.vect.z)); if close_d2 > dp^.radius2 {ray not intersect object at all ?} then goto no_hit; ofs := {close point to hit points distance} sqrt(dp^.radius2 - close_d2); { * Try first intersect point in the ray direction. } hit_l := close_l - ofs; {ray distance to first intersect point} if (hit_l >= ray_p^.min_dist) and {hit point within valid range ?} (hit_l <= ray_p^.max_dist) then begin hit_info.enter := true; {ray is entering object, not leaving} goto hit; {go process the hit} end; { * Try second intersect point in the ray direction. } hit_l := close_l + ofs; {ray distance to second intersect point} if (hit_l >= ray_p^.min_dist) and {hit point within valid range ?} (hit_l <= ray_p^.max_dist) then begin hit_info.enter := false; {ray is leaving object, not entering} goto hit; {go process the hit} end; { * The ray did not hit the object at all. In this case, we don't have to put * anything into HIT_INFO. } no_hit: type1_sphere_intersect_check := false; {indicate no hit} return; { * The ray did hit the object. We therefore must completely fill in HIT_INFO. * We also therefore must allocate and fill in our own private hit geometry * block. This is allocated from array MEM, defined in the RAY_TYPE1_2.INS.PAS * include file. } hit: ray_p^.max_dist := hit_l; {only closer hits are allowed from now on} hit_info.object_p := addr(object); {return handle to object that got hit} hit_info.distance := hit_l; {fill in ray distance to hit point} hit_geom_p := univ_ptr(addr(mem[next_mem])); {get pointer to hit geom block} next_mem := next_mem + sizeof(hit_geom_p^); {update index to next free mem} next_mem := (next_mem + 3) & ~3; {round up to next multiple of 4 bytes} if next_mem > mem_block_size then begin {not enough room for HIT_GEOM block ?} writeln ('Insufficient space in array MEM (RAY_TYPE1_2.INS.PAS).'); sys_bomb; {save traceback info and abort} end; hit_info.shader_parms_p := hit_geom_p; {fill in pointer to hit geometry save area} hit_geom_p^.base.liparm_p := parms_p^.liparm_p; {from run-time parameters} if dp^.visprop_p <> nil {check where to get visprop pointer from} then hit_geom_p^.base.visprop_p := dp^.visprop_p {get it from object data} else hit_geom_p^.base.visprop_p := parms_p^.visprop_p; {from run-time parameters} hit_geom_p^.ray_point := ray_p^.point; {save ray origin point in our coor space} hit_geom_p^.ray_vect := ray_p^.vect; {save ray unit vector in our coor space} shader := parms_p^.shader; {shader comes from run time parameters} type1_sphere_intersect_check := true; {indicate there was an intersection} end; { ******************************************************************************** * * Local subroutine TYPE1_SPHERE_INTERSECT_GEOM (HIT_INFO, FLAGS, GEOM_INFO) * * Return specific geometric information about a ray/object intersection in * GEOM_INFO. In HIT_INFO are any useful results left by the ray/object * intersection check calculation. FLAGS identifies what specific geometric * information is being requested. } procedure type1_sphere_intersect_geom ( {return detailed geometry of intersection} in hit_info: ray_hit_info_t; {data saved by INTERSECT_CHECK} in flags: ray_geom_flags_t; {bit mask list of what is being requested} out geom_info: ray_geom_info_t); {filled in geometric info} val_param; var hit_geom_p: sphere_hit_geom_p_t; {pointer to hit geometry block} data_p: sphere_data_p_t; {pointer to object specific data} begin geom_info.flags := []; {init what info we returned indicator} hit_geom_p := {pointer to HIT_GEOM block} sphere_hit_geom_p_t(hit_info.shader_parms_p); data_p := {pointer to object-specific data} sphere_data_p_t(hit_info.object_p^.data_p); with {define abbreviations} hit_geom_p^:hit_geom, {object specific hit geometry block} data_p^:data {object specific data block} do begin { * Return intersection point coordinates. } if ray_geom_point in flags then begin geom_info.flags := {inidicate intersect point returned} geom_info.flags + [ray_geom_point]; geom_info.point.x := hit_geom.ray_point.x + (hit_info.distance * hit_geom.ray_vect.x); geom_info.point.y := hit_geom.ray_point.y + (hit_info.distance * hit_geom.ray_vect.y); geom_info.point.z := hit_geom.ray_point.z + (hit_info.distance * hit_geom.ray_vect.z); end; { * Return unit normal vector of surface at intersection point. } if ray_geom_unorm in flags then begin geom_info.flags := {indicate unit normal returned} geom_info.flags + [ray_geom_unorm]; if ray_geom_point in flags {check for hit point already computed} then begin {hit point already sitting in GEOM_INFO} geom_info.unorm.x := (geom_info.point.x - data.center.x) / data.radius; geom_info.unorm.y := (geom_info.point.y - data.center.y) / data.radius; geom_info.unorm.z := (geom_info.point.z - data.center.z) / data.radius; end {done if intersect point pre-computed} else begin {hit point not already pre-computed} geom_info.unorm.x := (hit_geom.ray_point.x + (hit_info.distance * hit_geom.ray_vect.x) - data.center.x) / data.radius; geom_info.unorm.y := (hit_geom.ray_point.y + (hit_info.distance * hit_geom.ray_vect.y) - data.center.y) / data.radius; geom_info.unorm.z := (hit_geom.ray_point.z + (hit_info.distance * hit_geom.ray_vect.z) - data.center.z) / data.radius; end {done with hit point not pre-computed} ; {done with pre-computed descision} end; {done returning unit surface normal} end; {done using abbreviations} end; { ******************************************************************************** * * Local subroutine TYPE1_SPHERE_INTERSECT_BOX (BOX, OBJECT, HERE, ENCLOSED) * * Find the intersection status between this object and a paralellpiped. HERE * is returned as TRUE if the intersect check routine for this object could * ever return TRUE for ray within the box volume. ENCLOSED is returned as * true if the object completely encloses the box. } procedure type1_sphere_intersect_box ( {find object/box intersection status} in box: ray_box_t; {descriptor for a paralellpiped volume} in object: ray_object_t; {object to intersect with the box} out here: boolean; {TRUE if ISECT_CHECK could be true in box} out enclosed: boolean); {TRUE if solid obj, and completely encloses box} val_param; var data_p: sphere_data_p_t; {pointer to object specific data} cv: vect_3d_t; {vector from box corner to sphere center} i, j, k: sys_int_machine_t; {loop counters} cd: array[1..3] of real; {dist from each base plane to sphere center} v1, v2, v3: vect_3d_t; {scratch 3D vectors} cirv: vect_3d_t; {vector from corner to circle center} r2: real; {circle radius squared} pm: real; {scale factor to project R2 perp to slice} pr2: real; {squared circle radius after projection} m, m2: real; {scratch scale factors} dot: real; {result of dot product} some_in, some_out: boolean; {box verticies status for in/out sphere} label all_outside, is_here; begin data_p := {pointer to object-specific data} sphere_data_p_t(object.data_p); with {define abbreviations} data_p^:data {object specific data block} do begin { * Abbreviations are: * DATA - Data block for this specific object. } cv.x := data.center.x - box.point.x; {make vector from box corner to sphere center} cv.y := data.center.y - box.point.y; cv.z := data.center.z - box.point.z; for i := 1 to 3 do begin {once for each set of paralell faces} cd[i] := {perp dist from base plane to sphere center} cv.x*box.edge[i].unorm.x + cv.y*box.edge[i].unorm.y + cv.z*box.edge[i].unorm.z; if cd[i] < -data.radius {completely behind this plane ?} then goto all_outside; if cd[i] > data.radius+box.edge[i].width {completely in front of front face ?} then goto all_outside; end; {back and do next set of paralell faces} { * The sphere definately exists somewhere in each of the three slices of space * between the planes of opposite faces. This means the trivial reject test * failed. CD has been set to the perpendicular distance from the base plane * (the plane the box corner point is on) of each slice to the sphere center. * * Now check the in/out status of the box corner points, and set the flags * SOME_IN and SOME_OUT. If all the corner points are inside the sphere, then * the box is completely enclosed, and we can return immediately. } some_in := false; {init the inside/outside flags} some_out := false; if sqr(cv.x)+sqr(cv.y)+sqr(cv.z) > data.radius2 {check box origin point} then some_out := true else some_in := true; v1.x := box.edge[1].edge.x - cv.x; v1.y := box.edge[1].edge.y - cv.y; v1.z := box.edge[1].edge.z - cv.z; if sqr(v1.x)+sqr(v1.y)+sqr(v1.z) > data.radius2 {check point at V1} then some_out := true else some_in := true; v2.x := box.edge[2].edge.x - cv.x; v2.y := box.edge[2].edge.y - cv.y; v2.z := box.edge[2].edge.z - cv.z; if sqr(v2.x)+sqr(v2.y)+sqr(v2.z) > data.radius2 {check point at V2} then some_out := true else some_in := true; v3.x := box.edge[3].edge.x - cv.x; v3.y := box.edge[3].edge.y - cv.y; v3.z := box.edge[3].edge.z - cv.z; if sqr(v3.x)+sqr(v3.y)+sqr(v3.z) > data.radius2 {check point at V3} then some_out := true else some_in := true; if sqr(v1.x+box.edge[2].edge.x) {check point at V1,V2} + sqr(v1.y+box.edge[2].edge.y) + sqr(v1.z+box.edge[2].edge.z) > data.radius2 then some_out := true else some_in := true; if sqr(v1.x+box.edge[3].edge.x) {check point at V1,V3} + sqr(v1.y+box.edge[3].edge.y) + sqr(v1.z+box.edge[3].edge.z) > data.radius2 then some_out := true else some_in := true; if sqr(v2.x+box.edge[3].edge.x) {check point at V2,V3} + sqr(v2.y+box.edge[3].edge.y) + sqr(v2.z+box.edge[3].edge.z) > data.radius2 then some_out := true else some_in := true; if sqr(v1.x+box.edge[2].edge.x+box.edge[3].edge.x) {check point at V1,V2,V3} + sqr(v1.y+box.edge[2].edge.y+box.edge[3].edge.y) + sqr(v1.z+box.edge[2].edge.z+box.edge[3].edge.z) > data.radius2 then some_out := true else some_in := true; if not some_out then begin {box entirely within sphere ?} here := false; {no surface within box for rays to hit} enclosed := true; {object completely encloses box} return; end; if some_in then goto is_here; {surface definately passes thru box ?} { * None of the verticies of the box are inside the sphere. Now determine * whether any part of the sphere is inside any part of the box. First find a * reasonably small sphere that completely encloses the box. If this extent * sphere does not intersect the object sphere, then we can do a trivial * reject. This is a rather common case when the box is much smaller than the * sphere. } if {obj sphere and extent sphere not intersect ?} ( sqr(cv.x - 0.5*( {distance between sphere centers squared} box.edge[1].edge.x + box.edge[2].edge.x + box.edge[3].edge.x)) +sqr(cv.y - 0.5*( box.edge[1].edge.y + box.edge[2].edge.y + box.edge[3].edge.y)) +sqr(cv.z - 0.5*( box.edge[1].edge.z + box.edge[2].edge.z + box.edge[3].edge.z)) ) > sqr(data.radius {sum of the radiuses squared} + 0.5*(box.edge[1].width + box.edge[2].width + box.edge[3].width)) then goto all_outside; {sphere definately not intersect box} { * All the easy checks failed to determine whether the sphere intersects the * box. We must now do a rigorous intersection. Start by finding a slice that * does not contain the sphere center (if there isn't one, then sphere * obviously hits the box). Then find the circle of intersection between the * sphere and the closest plane for that slice. A different slice is then * found that does not contain the circle center (again, if there isn't one, * then the sphere hits the box). The line segment of intersection between the * circle and the nearest slice plane is then checked for interesection with * the third remaining slice. Intersection of the line segement and the third * slice is a necessary and sufficient condition for the sphere intersecting * the box. } for i := 1 to 3 do begin {look for slice with sphere center outside} if (cd[i] >= 0.0) and (cd[i] <= box.edge[i].width) then next; {inside this slice ?} if cd[i] <= 0.0 {which side of slice is sphere on ?} then begin {sphere is on the base plane side of this slice} cirv.x := {vector from box corner to circle center} cv.x - box.edge[i].unorm.x*cd[i]; cirv.y := cv.y - box.edge[i].unorm.y*cd[i]; cirv.z := cv.z - box.edge[i].unorm.z*cd[i]; r2 := data.radius2 - sqr(cd[i]); {squared radius of circle} end else begin {sphere is not on base plane side of this slice} m := cd[i] - box.edge[i].width; {distance from front plane to sphere center} cirv.x := {vector from box corner to circle center} cv.x - box.edge[i].unorm.x*m; cirv.y := cv.y - box.edge[i].unorm.y*m; cirv.z := cv.z - box.edge[i].unorm.z*m; r2 := data.radius2 - sqr(m); {squared radius of circle} end ; { * CIRV is the vector from the box corner the center of a circle. R2 is the * radius of the circle squared. Now intersect this circle with any one of the * two remaining slices that also does not contain the circle center. } for j := 1 to 3 do begin {look for slice not containing circle center} if j = i then next; {don't use slice used to make circle} m := {distance from base plane to circle center} cirv.x*box.edge[j].unorm.x + cirv.y*box.edge[j].unorm.y + cirv.z*box.edge[j].unorm.z; if (m >= 0.0) and (m <= box.edge[j].width) {circle center in this slice ?} then next; {punt slice containing circle center} dot := {dot product of two plane unit vectors} box.edge[i].unorm.x*box.edge[j].unorm.x + box.edge[i].unorm.y*box.edge[j].unorm.y + box.edge[i].unorm.z*box.edge[j].unorm.z; pm := 1.0 - sqr(dot); {factor for projecting R2 perp to slice} pr2 := r2*pm; {make R2 projected perpendicular to this slice} if pr2 < 1.0E-16 then goto all_outside; {circle too small or paralell to slice ?} if m > 0.0 then begin {circle is not on base plane side of slice ?} m := m - box.edge[j].width; {make distance from front plane to cir center} end; if pr2 < sqr(m) then goto all_outside; {circle not hit this slice ?} m2 := dot/pm; {factor for making V1} v1.x := cirv.x - m*( {vector from corner to line segment center} box.edge[j].unorm.x + m2*(dot*box.edge[j].unorm.x - box.edge[i].unorm.x)); v1.y := cirv.y - m*( box.edge[j].unorm.y + m2*(dot*box.edge[j].unorm.y - box.edge[i].unorm.y)); v1.z := cirv.z - m*( box.edge[j].unorm.z + m2*(dot*box.edge[j].unorm.z - box.edge[i].unorm.z)); r2 := r2 - sqr(m*pm); {half length of line segment squared} m2 := 1.0/sqrt(pm); {factor for unitizing V2} v2.x := m2*( {make unit vector along line segment} box.edge[j].unorm.y*box.edge[i].unorm.z - box.edge[j].unorm.z*box.edge[i].unorm.y); v2.y := m2*( box.edge[j].unorm.z*box.edge[i].unorm.x - box.edge[j].unorm.x*box.edge[i].unorm.z); v2.z := m2*( box.edge[j].unorm.x*box.edge[i].unorm.y - box.edge[j].unorm.y*box.edge[i].unorm.x); { * V1 is the vector from the box corner to the center of the line segment. V2 * is a unit vector along the line segment. R2 is half the length of the line * segment squared. Now see if any part of this line segment intersects the * remaining slice. If so, the sphere intersects the box, and otherwise it * doesn't. } k := 6-i-j; {make number of remaining slice} m := {distance from base plane to center of segment} v1.x*box.edge[k].unorm.x + v1.y*box.edge[k].unorm.y + v1.z*box.edge[k].unorm.z; if (m >= 0.0) and (m <= box.edge[k].width) {segment center point in slice ?} then goto is_here; {at least one point definately in all slices} if m > 0.0 {segment not on base plane side of slice ?} then m := m - box.edge[k].width; {make segment center distance to slice plane} if sqr(m) <= {segment hits the plane ?} r2*sqr( {perp projected segment radius squared} v2.x*box.edge[k].unorm.x + v2.y*box.edge[k].unorm.y + v2.z*box.edge[k].unorm.z) then goto is_here {sphere definately hits box} else goto all_outside; {sphere definately not hits box} end; {keep looking for slice without circle center} goto is_here; {circle center is in both remaining slices} end; {keep looking for slice without sphere center} { * Jump to here if some part of the sphere's surface passes thru the box. The * case of the box completely inside the sphere must already have been * eliminated. } is_here: {jump here on sphere suface is in box} here := true; {rays can hit sphere inside the box volume} enclosed := false; {box is not wholly enclosed by sphere} return; { * Jump to here on discovering that the box and sphere are completely disjoint. } all_outside: here := false; {no rays will hit sphere in box volume} enclosed := false; {box is not inside sphere} end; {done using abbreviations} end; {end of subroutine} { ******************************************************************************** * * Subroutine TYPE1_SPHERE_CLASS_MAKE (CLASS) * * Fill in the routines block for this class of objects. } procedure type1_sphere_class_make ( {fill in object class descriptor} out class: ray_object_class_t); {block to fill in} val_param; begin class.create := addr(type1_sphere_create); class.intersect_check := addr(type1_sphere_intersect_check); class.hit_geom := addr(type1_sphere_intersect_geom); class.intersect_box := addr(type1_sphere_intersect_box); class.add_child := nil; end;
unit uCadreFun; interface uses Classes, SysUtils, System.Variants, uSysDataBase; type TCadreFun = class(TComponent) private { private declarations } FSysDataBase: TSysDataBase; protected { protected declarations } public { public declarations } constructor Create; virtual; destructor Destroy; override; procedure CreateNewCadre(ASysId: string);//创建一个新干部信息, 确保各个表有数据 published { published declarations } end; var g_CadreFun: TCadreFun; function GetCadreFun:TCadreFun; implementation function GetCadreFun:TCadreFun; begin if not Assigned(g_CadreFun) then g_CadreFun := TCadreFun.Create; Result := g_CadreFun; end; { TCadreFun } constructor TCadreFun.Create; begin FSysDataBase := uSysDataBase.GetSysDataBase; end; destructor TCadreFun.Destroy; begin inherited; end; procedure TCadreFun.CreateNewCadre(ASysId: string); var LSql: string; LMaxOrderNo: Integer; begin LSql := 'select * from cadre_info where sys_id = ' + QuotedStr(ASysId); if not FSysDataBase.DataIsExists(LSql) then begin LMaxOrderNo := FSysDataBase.GetFieldMaxValue('cadre_info', 'order_no') + 1; LSql := 'insert into cadre_info(sys_id, name, order_no) values(' + QuotedStr(ASysId) + ', ''NEW'', ''' + IntToStr(LMaxOrderNo) + ''')'; FSysDataBase.ExecSQL(LSql); end; LSql := 'select * from cadre_info_extend where sys_id = ' + QuotedStr(ASysId); if not FSysDataBase.DataIsExists(LSql) then begin LSql := 'insert into cadre_info_extend(sys_id) values(' + QuotedStr(ASysId) + ')'; FSysDataBase.ExecSQL(LSql); end; end; end.
unit AutoRun; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, ExtCtrls, ImgList, ComCtrls, Registry, Menus, ShlObj; type TAutoRunForm = class(TForm) Image1: TImage; InfoLabel: TLabel; AutoRunExitButton: TButton; Bevel: TBevel; AutoRunPageControl: TPageControl; RegistryTab_1: TTabSheet; RegistryTab_2: TTabSheet; RegistryList_1: TListView; RegistryTab_3: TTabSheet; AutoRunTab: TTabSheet; RegistryList_2: TListView; RegistryList_3: TListView; DelRegistryButton: TButton; AutoRunList: TListView; AutoRunMenu: TPopupMenu; Delete: TMenuItem; procedure AutoRunExitButtonClick(Sender: TObject); procedure RegistryTab_1Show(Sender: TObject); procedure RegistryTab_2Show(Sender: TObject); procedure RegistryTab_3Show(Sender: TObject); procedure DelRegistryButtonClick(Sender: TObject); procedure AutoRunTabShow(Sender: TObject); procedure FormShow(Sender: TObject); procedure DeleteClick(Sender: TObject); private { Private declarations } public { Public declarations } end; const KEY_WOW64_64KEY = $0100; var AutoRunForm: TAutoRunForm; RegAutoRun : TRegistry; RegInfo : TRegKeyInfo; RegList : TStringList; RegItem : TListItem; RegCount, DelRegIndex, index : integer; implementation uses avEngine; {$R *.dfm} procedure TAutoRunForm.AutoRunExitButtonClick(Sender: TObject); begin Close; end; function GetAutoRunFolder : string; var s: string; begin SetLength(s, MAX_PATH); if not SHGetSpecialFolderPath(0, PChar(s), CSIDL_STARTUP, true) then s := ''; result := PChar(s); end; procedure TAutoRunForm.RegistryTab_1Show(Sender: TObject); begin try RegistryList_1.Items.Clear; RegList := TStringList.Create; RegAutoRun := TRegistry.Create(KEY_ALL_ACCESS OR KEY_WOW64_64KEY); RegAutoRun.RootKey := HKEY_LOCAL_MACHINE; RegAutoRun.OpenKey('Software\Microsoft\Windows\CurrentVersion\Run', False); RegAutoRun.GetValueNames(RegList); for index := 0 to RegList.Count-1 do with RegistryList_1 do begin RegItem := Items.Add; RegItem.Caption := RegList.Strings[index]; RegItem.SubItems.Add(RegAutoRun.ReadString(RegList.Strings[index])); end; finally RegAutoRun.Free; RegList.Free; end; end; procedure TAutoRunForm.RegistryTab_2Show(Sender: TObject); begin try RegistryList_2.Items.Clear; RegList := TStringList.Create; RegAutoRun := TRegistry.Create(KEY_ALL_ACCESS OR KEY_WOW64_64KEY); RegAutoRun.RootKey := HKEY_LOCAL_MACHINE; RegAutoRun.OpenKey('\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Run', False); RegAutoRun.GetValueNames(RegList); for index := 0 to RegList.Count-1 do with RegistryList_2 do begin RegItem := Items.Add; RegItem.Caption := RegList.Strings[index]; RegItem.SubItems.Add(RegAutoRun.ReadString(RegList.Strings[index])); end; finally RegAutoRun.Free; RegList.Free; end; end; procedure TAutoRunForm.RegistryTab_3Show(Sender: TObject); begin try RegistryList_3.Items.Clear; RegList := TStringList.Create; RegAutoRun := TRegistry.Create(KEY_ALL_ACCESS OR KEY_WOW64_64KEY); RegAutoRun.RootKey := HKEY_CURRENT_USER; RegAutoRun.OpenKey('Software\Microsoft\Windows\CurrentVersion\Run', False); RegAutoRun.GetValueNames(RegList); for index := 0 to RegList.Count-1 do with RegistryList_3 do begin RegItem := Items.Add; RegItem.Caption := RegList.Strings[index]; RegItem.SubItems.Add(RegAutoRun.ReadString(RegList.Strings[index])); end; finally RegAutoRun.Free; RegList.Free; end; end; procedure TAutoRunForm.DelRegistryButtonClick(Sender: TObject); begin case AutoRunPageControl.ActivePageIndex of 0 : begin try if RegistryList_1.ItemFocused.Selected then if MessageBox(0,'Удалить выбранный элемент?', 'AV Scanner', MB_YESNO or MB_ICONQUESTION or MB_DEFBUTTON2) = mrYes then begin DelRegIndex := RegistryList_1.ItemFocused.Index; try RegAutoRun := TRegistry.Create(KEY_ALL_ACCESS OR KEY_WOW64_64KEY); RegAutoRun.RootKey := HKEY_LOCAL_MACHINE; RegAutoRun.OpenKey('Software\Microsoft\Windows\CurrentVersion\Run', False); if RegAutoRun.DeleteValue(RegistryList_1.Items.Item[DelRegIndex].Caption) then begin MessageBox(0,'Объект автозапуска удален', 'AV Scanner', MB_OK or MB_ICONINFORMATION); AutoRunForm.RegistryTab_1Show(Sender); end else begin MessageBox(0,'Ошибка удаления объекта', 'AV Scanner', MB_OK or MB_ICONINFORMATION); AutoRunForm.RegistryTab_1Show(Sender); end; finally RegAutoRun.Free; end; end; except end; end; 1 : begin try if RegistryList_2.ItemFocused.Selected then if MessageBox(0,'Удалить выбранный элемент', 'AV Scanner', MB_YESNO or MB_ICONQUESTION or MB_DEFBUTTON2) = mrYes then begin DelRegIndex := RegistryList_2.ItemFocused.Index; try RegAutoRun := TRegistry.Create(KEY_ALL_ACCESS OR KEY_WOW64_64KEY); RegAutoRun.RootKey := HKEY_LOCAL_MACHINE; RegAutoRun.OpenKey('\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Run', False); if RegAutoRun.DeleteValue(RegistryList_2.Items.Item[DelRegIndex].Caption) then begin MessageBox(0,'Объект автозапуска удален', 'AV Scanner', MB_OK or MB_ICONINFORMATION); AutoRunForm.RegistryTab_2Show(Sender); end else begin MessageBox(0,'Ошибка удаления объекта', 'AV Scanner', MB_OK or MB_ICONINFORMATION); AutoRunForm.RegistryTab_1Show(Sender); end; finally RegAutoRun.Free; end; end; except end; end; 2 : begin try if RegistryList_3.ItemFocused.Selected then if MessageBox(0,'Удалить выбранный элемент', 'AV Scanner', MB_YESNO or MB_ICONQUESTION or MB_DEFBUTTON2) = mrYes then begin DelRegIndex := RegistryList_3.ItemFocused.Index; try RegAutoRun := TRegistry.Create(KEY_ALL_ACCESS OR KEY_WOW64_64KEY); RegAutoRun.RootKey := HKEY_CURRENT_USER; RegAutoRun.OpenKey('\Software\Microsoft\Windows\CurrentVersion\Run', False); if RegAutoRun.DeleteValue(RegistryList_3.Items.Item[DelRegIndex].Caption) then begin MessageBox(0,'Объект автозапуска удален', 'AV Scanner', MB_OK or MB_ICONINFORMATION); AutoRunForm.RegistryTab_3Show(Sender); end else begin MessageBox(0,'Ошибка удаления объекта', 'AV Scanner', MB_OK or MB_ICONINFORMATION); AutoRunForm.RegistryTab_1Show(Sender); end; finally RegAutoRun.Free; end; end; except end; end; 3 : begin try if AutoRunList.ItemFocused.Selected then if MessageBox(0,'Удалить выбранный элемент', 'AV Scanner', MB_YESNO or MB_ICONQUESTION or MB_DEFBUTTON2) = mrYes then begin DelRegIndex := AutoRunList.ItemFocused.Index; if DeleteFile(GetAutoRunFolder + '\' + AutoRunList.Items.Item[DelRegIndex].Caption) then begin MessageBox(0,'Объект автозапуска удален', 'AV Scanner', MB_OK or MB_ICONINFORMATION); AutoRunForm.AutoRunTabShow(Sender); end else begin MessageBox(0,'Ошибка удаления объекта', 'AV Scanner', MB_OK or MB_ICONINFORMATION); AutoRunForm.AutoRunTabShow(Sender); end; end; except end; end; end; end; procedure ShowAutoRunFolder(AutoRunDir : String); var SearchRec: TSearchRec; begin AutoRunForm.AutoRunList.Items.Clear; if FindFirst(AutoRunDir + '\*.*', faAnyFile, SearchRec) = 0 then repeat if (SearchRec.Name <> '.') and (SearchRec.Name <> '..') and (SearchRec.Name <> 'desktop.ini') then AutoRunForm.AutoRunList.Items.Add.Caption := SearchRec.name; until FindNext(SearchRec) <> 0; FindClose(SearchRec); end; procedure TAutoRunForm.AutoRunTabShow(Sender: TObject); begin ShowAutoRunFolder(GetAutoRunFolder); end; procedure TAutoRunForm.FormShow(Sender: TObject); begin if GetBitWin = WIN_32 then RegistryTab_2.TabVisible := false; end; procedure TAutoRunForm.DeleteClick(Sender: TObject); begin DelRegistryButtonClick(Sender); end; end.
{$mode objfpc} {$assertions on} {$include include/targetos.inc} unit GLUtils; interface uses {$ifdef API_OPENGL} GL, GLext, {$endif} {$ifdef API_OPENGLES} GLES30, {$endif} SysUtils; procedure GLAssert(messageString: string = 'OpenGL error'); inline; function GLEnumToStr(enum: GLenum): string; implementation function GLEnumToStr(enum: GLenum): string; begin case enum of GL_DEPTH_BUFFER_BIT: result := 'GL_DEPTH_BUFFER_BIT'; GL_STENCIL_BUFFER_BIT: result := 'GL_STENCIL_BUFFER_BIT'; GL_COLOR_BUFFER_BIT: result := 'GL_COLOR_BUFFER_BIT'; GL_POINTS: result := 'GL_POINTS'; GL_LINES: result := 'GL_LINES'; GL_LINE_LOOP: result := 'GL_LINE_LOOP'; GL_LINE_STRIP: result := 'GL_LINE_STRIP'; GL_TRIANGLES: result := 'GL_TRIANGLES'; GL_TRIANGLE_STRIP: result := 'GL_TRIANGLE_STRIP'; GL_TRIANGLE_FAN: result := 'GL_TRIANGLE_FAN'; GL_SRC_COLOR: result := 'GL_SRC_COLOR'; GL_ONE_MINUS_SRC_COLOR: result := 'GL_ONE_MINUS_SRC_COLOR'; GL_SRC_ALPHA: result := 'GL_SRC_ALPHA'; GL_ONE_MINUS_SRC_ALPHA: result := 'GL_ONE_MINUS_SRC_ALPHA'; GL_DST_ALPHA: result := 'GL_DST_ALPHA'; GL_ONE_MINUS_DST_ALPHA: result := 'GL_ONE_MINUS_DST_ALPHA'; GL_DST_COLOR: result := 'GL_DST_COLOR'; GL_ONE_MINUS_DST_COLOR: result := 'GL_ONE_MINUS_DST_COLOR'; GL_SRC_ALPHA_SATURATE: result := 'GL_SRC_ALPHA_SATURATE'; GL_FUNC_ADD: result := 'GL_FUNC_ADD'; GL_BLEND_EQUATION: result := 'GL_BLEND_EQUATION'; //GL_BLEND_EQUATION_RGB: // result := 'GL_BLEND_EQUATION_RGB'; GL_BLEND_EQUATION_ALPHA: result := 'GL_BLEND_EQUATION_ALPHA'; GL_FUNC_SUBTRACT: result := 'GL_FUNC_SUBTRACT'; GL_FUNC_REVERSE_SUBTRACT: result := 'GL_FUNC_REVERSE_SUBTRACT'; GL_BLEND_DST_RGB: result := 'GL_BLEND_DST_RGB'; GL_BLEND_SRC_RGB: result := 'GL_BLEND_SRC_RGB'; GL_BLEND_DST_ALPHA: result := 'GL_BLEND_DST_ALPHA'; GL_BLEND_SRC_ALPHA: result := 'GL_BLEND_SRC_ALPHA'; GL_CONSTANT_COLOR: result := 'GL_CONSTANT_COLOR'; GL_ONE_MINUS_CONSTANT_COLOR: result := 'GL_ONE_MINUS_CONSTANT_COLOR'; GL_CONSTANT_ALPHA: result := 'GL_CONSTANT_ALPHA'; GL_ONE_MINUS_CONSTANT_ALPHA: result := 'GL_ONE_MINUS_CONSTANT_ALPHA'; GL_BLEND_COLOR: result := 'GL_BLEND_COLOR'; GL_ARRAY_BUFFER: result := 'GL_ARRAY_BUFFER'; GL_ELEMENT_ARRAY_BUFFER: result := 'GL_ELEMENT_ARRAY_BUFFER'; GL_ARRAY_BUFFER_BINDING: result := 'GL_ARRAY_BUFFER_BINDING'; GL_ELEMENT_ARRAY_BUFFER_BINDING: result := 'GL_ELEMENT_ARRAY_BUFFER_BINDING'; GL_STREAM_DRAW: result := 'GL_STREAM_DRAW'; GL_STATIC_DRAW: result := 'GL_STATIC_DRAW'; GL_DYNAMIC_DRAW: result := 'GL_DYNAMIC_DRAW'; GL_BUFFER_SIZE: result := 'GL_BUFFER_SIZE'; GL_BUFFER_USAGE: result := 'GL_BUFFER_USAGE'; GL_CURRENT_VERTEX_ATTRIB: result := 'GL_CURRENT_VERTEX_ATTRIB'; GL_FRONT: result := 'GL_FRONT'; GL_BACK: result := 'GL_BACK'; GL_FRONT_AND_BACK: result := 'GL_FRONT_AND_BACK'; GL_TEXTURE_2D: result := 'GL_TEXTURE_2D'; GL_CULL_FACE: result := 'GL_CULL_FACE'; GL_BLEND: result := 'GL_BLEND'; GL_DITHER: result := 'GL_DITHER'; GL_STENCIL_TEST: result := 'GL_STENCIL_TEST'; GL_DEPTH_TEST: result := 'GL_DEPTH_TEST'; GL_SCISSOR_TEST: result := 'GL_SCISSOR_TEST'; GL_POLYGON_OFFSET_FILL: result := 'GL_POLYGON_OFFSET_FILL'; GL_SAMPLE_ALPHA_TO_COVERAGE: result := 'GL_SAMPLE_ALPHA_TO_COVERAGE'; GL_SAMPLE_COVERAGE: result := 'GL_SAMPLE_COVERAGE'; GL_INVALID_ENUM: result := 'GL_INVALID_ENUM'; GL_INVALID_VALUE: result := 'GL_INVALID_VALUE'; GL_INVALID_OPERATION: result := 'GL_INVALID_OPERATION'; GL_OUT_OF_MEMORY: result := 'GL_OUT_OF_MEMORY'; GL_CW: result := 'GL_CW'; GL_CCW: result := 'GL_CCW'; GL_LINE_WIDTH: result := 'GL_LINE_WIDTH'; GL_ALIASED_POINT_SIZE_RANGE: result := 'GL_ALIASED_POINT_SIZE_RANGE'; GL_ALIASED_LINE_WIDTH_RANGE: result := 'GL_ALIASED_LINE_WIDTH_RANGE'; GL_CULL_FACE_MODE: result := 'GL_CULL_FACE_MODE'; GL_FRONT_FACE: result := 'GL_FRONT_FACE'; GL_DEPTH_RANGE: result := 'GL_DEPTH_RANGE'; GL_DEPTH_WRITEMASK: result := 'GL_DEPTH_WRITEMASK'; GL_DEPTH_CLEAR_VALUE: result := 'GL_DEPTH_CLEAR_VALUE'; GL_DEPTH_FUNC: result := 'GL_DEPTH_FUNC'; GL_STENCIL_CLEAR_VALUE: result := 'GL_STENCIL_CLEAR_VALUE'; GL_STENCIL_FUNC: result := 'GL_STENCIL_FUNC'; GL_STENCIL_FAIL: result := 'GL_STENCIL_FAIL'; GL_STENCIL_PASS_DEPTH_FAIL: result := 'GL_STENCIL_PASS_DEPTH_FAIL'; GL_STENCIL_PASS_DEPTH_PASS: result := 'GL_STENCIL_PASS_DEPTH_PASS'; GL_STENCIL_REF: result := 'GL_STENCIL_REF'; GL_STENCIL_VALUE_MASK: result := 'GL_STENCIL_VALUE_MASK'; GL_STENCIL_WRITEMASK: result := 'GL_STENCIL_WRITEMASK'; GL_STENCIL_BACK_FUNC: result := 'GL_STENCIL_BACK_FUNC'; GL_STENCIL_BACK_FAIL: result := 'GL_STENCIL_BACK_FAIL'; GL_STENCIL_BACK_PASS_DEPTH_FAIL: result := 'GL_STENCIL_BACK_PASS_DEPTH_FAIL'; GL_STENCIL_BACK_PASS_DEPTH_PASS: result := 'GL_STENCIL_BACK_PASS_DEPTH_PASS'; GL_STENCIL_BACK_REF: result := 'GL_STENCIL_BACK_REF'; GL_STENCIL_BACK_VALUE_MASK: result := 'GL_STENCIL_BACK_VALUE_MASK'; GL_STENCIL_BACK_WRITEMASK: result := 'GL_STENCIL_BACK_WRITEMASK'; GL_VIEWPORT: result := 'GL_VIEWPORT'; GL_SCISSOR_BOX: result := 'GL_SCISSOR_BOX'; GL_COLOR_CLEAR_VALUE: result := 'GL_COLOR_CLEAR_VALUE'; GL_COLOR_WRITEMASK: result := 'GL_COLOR_WRITEMASK'; GL_UNPACK_ALIGNMENT: result := 'GL_UNPACK_ALIGNMENT'; GL_PACK_ALIGNMENT: result := 'GL_PACK_ALIGNMENT'; GL_MAX_TEXTURE_SIZE: result := 'GL_MAX_TEXTURE_SIZE'; GL_MAX_VIEWPORT_DIMS: result := 'GL_MAX_VIEWPORT_DIMS'; GL_SUBPIXEL_BITS: result := 'GL_SUBPIXEL_BITS'; GL_RED_BITS: result := 'GL_RED_BITS'; GL_GREEN_BITS: result := 'GL_GREEN_BITS'; GL_BLUE_BITS: result := 'GL_BLUE_BITS'; GL_ALPHA_BITS: result := 'GL_ALPHA_BITS'; GL_DEPTH_BITS: result := 'GL_DEPTH_BITS'; GL_STENCIL_BITS: result := 'GL_STENCIL_BITS'; GL_POLYGON_OFFSET_UNITS: result := 'GL_POLYGON_OFFSET_UNITS'; GL_POLYGON_OFFSET_FACTOR: result := 'GL_POLYGON_OFFSET_FACTOR'; GL_TEXTURE_BINDING_2D: result := 'GL_TEXTURE_BINDING_2D'; GL_SAMPLE_BUFFERS: result := 'GL_SAMPLE_BUFFERS'; GL_SAMPLES: result := 'GL_SAMPLES'; GL_SAMPLE_COVERAGE_VALUE: result := 'GL_SAMPLE_COVERAGE_VALUE'; GL_SAMPLE_COVERAGE_INVERT: result := 'GL_SAMPLE_COVERAGE_INVERT'; GL_NUM_COMPRESSED_TEXTURE_FORMATS: result := 'GL_NUM_COMPRESSED_TEXTURE_FORMATS'; GL_COMPRESSED_TEXTURE_FORMATS: result := 'GL_COMPRESSED_TEXTURE_FORMATS'; GL_DONT_CARE: result := 'GL_DONT_CARE'; GL_FASTEST: result := 'GL_FASTEST'; GL_NICEST: result := 'GL_NICEST'; GL_GENERATE_MIPMAP_HINT: result := 'GL_GENERATE_MIPMAP_HINT'; GL_BYTE: result := 'GL_BYTE'; GL_UNSIGNED_BYTE: result := 'GL_UNSIGNED_BYTE'; GL_SHORT: result := 'GL_SHORT'; GL_UNSIGNED_SHORT: result := 'GL_UNSIGNED_SHORT'; GL_INT: result := 'GL_INT'; GL_UNSIGNED_INT: result := 'GL_UNSIGNED_INT'; GL_FLOAT: result := 'GL_FLOAT'; {$ifdef API_OPENGLES} GL_FIXED: result := 'GL_FIXED'; {$endif} GL_DEPTH_COMPONENT: result := 'GL_DEPTH_COMPONENT'; GL_ALPHA: result := 'GL_ALPHA'; GL_RGB: result := 'GL_RGB'; GL_RGBA: result := 'GL_RGBA'; GL_LUMINANCE: result := 'GL_LUMINANCE'; GL_LUMINANCE_ALPHA: result := 'GL_LUMINANCE_ALPHA'; GL_UNSIGNED_SHORT_4_4_4_4: result := 'GL_UNSIGNED_SHORT_4_4_4_4'; GL_UNSIGNED_SHORT_5_5_5_1: result := 'GL_UNSIGNED_SHORT_5_5_5_1'; GL_UNSIGNED_SHORT_5_6_5: result := 'GL_UNSIGNED_SHORT_5_6_5'; GL_FRAGMENT_SHADER: result := 'GL_FRAGMENT_SHADER'; GL_VERTEX_SHADER: result := 'GL_VERTEX_SHADER'; GL_MAX_VERTEX_ATTRIBS: result := 'GL_MAX_VERTEX_ATTRIBS'; {$ifdef API_OPENGLES} GL_MAX_VERTEX_UNIFORM_VECTORS: result := 'GL_MAX_VERTEX_UNIFORM_VECTORS'; GL_MAX_VARYING_VECTORS: result := 'GL_MAX_VARYING_VECTORS'; {$endif} GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS: result := 'GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS'; GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS: result := 'GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS'; GL_MAX_TEXTURE_IMAGE_UNITS: result := 'GL_MAX_TEXTURE_IMAGE_UNITS'; {$ifdef API_OPENGLES} GL_MAX_FRAGMENT_UNIFORM_VECTORS: result := 'GL_MAX_FRAGMENT_UNIFORM_VECTORS'; {$endif} GL_SHADER_TYPE: result := 'GL_SHADER_TYPE'; GL_DELETE_STATUS: result := 'GL_DELETE_STATUS'; GL_LINK_STATUS: result := 'GL_LINK_STATUS'; GL_VALIDATE_STATUS: result := 'GL_VALIDATE_STATUS'; GL_ATTACHED_SHADERS: result := 'GL_ATTACHED_SHADERS'; GL_ACTIVE_UNIFORMS: result := 'GL_ACTIVE_UNIFORMS'; GL_ACTIVE_UNIFORM_MAX_LENGTH: result := 'GL_ACTIVE_UNIFORM_MAX_LENGTH'; GL_ACTIVE_ATTRIBUTES: result := 'GL_ACTIVE_ATTRIBUTES'; GL_ACTIVE_ATTRIBUTE_MAX_LENGTH: result := 'GL_ACTIVE_ATTRIBUTE_MAX_LENGTH'; GL_SHADING_LANGUAGE_VERSION: result := 'GL_SHADING_LANGUAGE_VERSION'; GL_CURRENT_PROGRAM: result := 'GL_CURRENT_PROGRAM'; GL_NEVER: result := 'GL_NEVER'; GL_LESS: result := 'GL_LESS'; GL_EQUAL: result := 'GL_EQUAL'; GL_LEQUAL: result := 'GL_LEQUAL'; GL_GREATER: result := 'GL_GREATER'; GL_NOTEQUAL: result := 'GL_NOTEQUAL'; GL_GEQUAL: result := 'GL_GEQUAL'; GL_ALWAYS: result := 'GL_ALWAYS'; GL_KEEP: result := 'GL_KEEP'; GL_REPLACE: result := 'GL_REPLACE'; GL_INCR: result := 'GL_INCR'; GL_DECR: result := 'GL_DECR'; GL_INVERT: result := 'GL_INVERT'; GL_INCR_WRAP: result := 'GL_INCR_WRAP'; GL_DECR_WRAP: result := 'GL_DECR_WRAP'; GL_VENDOR: result := 'GL_VENDOR'; GL_RENDERER: result := 'GL_RENDERER'; GL_VERSION: result := 'GL_VERSION'; GL_EXTENSIONS: result := 'GL_EXTENSIONS'; GL_NEAREST: result := 'GL_NEAREST'; GL_LINEAR: result := 'GL_LINEAR'; GL_NEAREST_MIPMAP_NEAREST: result := 'GL_NEAREST_MIPMAP_NEAREST'; GL_LINEAR_MIPMAP_NEAREST: result := 'GL_LINEAR_MIPMAP_NEAREST'; GL_NEAREST_MIPMAP_LINEAR: result := 'GL_NEAREST_MIPMAP_LINEAR'; GL_LINEAR_MIPMAP_LINEAR: result := 'GL_LINEAR_MIPMAP_LINEAR'; GL_TEXTURE_MAG_FILTER: result := 'GL_TEXTURE_MAG_FILTER'; GL_TEXTURE_MIN_FILTER: result := 'GL_TEXTURE_MIN_FILTER'; GL_TEXTURE_WRAP_S: result := 'GL_TEXTURE_WRAP_S'; GL_TEXTURE_WRAP_T: result := 'GL_TEXTURE_WRAP_T'; GL_TEXTURE: result := 'GL_TEXTURE'; GL_TEXTURE_CUBE_MAP: result := 'GL_TEXTURE_CUBE_MAP'; GL_TEXTURE_BINDING_CUBE_MAP: result := 'GL_TEXTURE_BINDING_CUBE_MAP'; GL_TEXTURE_CUBE_MAP_POSITIVE_X: result := 'GL_TEXTURE_CUBE_MAP_POSITIVE_X'; GL_TEXTURE_CUBE_MAP_NEGATIVE_X: result := 'GL_TEXTURE_CUBE_MAP_NEGATIVE_X'; GL_TEXTURE_CUBE_MAP_POSITIVE_Y: result := 'GL_TEXTURE_CUBE_MAP_POSITIVE_Y'; GL_TEXTURE_CUBE_MAP_NEGATIVE_Y: result := 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Y'; GL_TEXTURE_CUBE_MAP_POSITIVE_Z: result := 'GL_TEXTURE_CUBE_MAP_POSITIVE_Z'; GL_TEXTURE_CUBE_MAP_NEGATIVE_Z: result := 'GL_TEXTURE_CUBE_MAP_NEGATIVE_Z'; GL_MAX_CUBE_MAP_TEXTURE_SIZE: result := 'GL_MAX_CUBE_MAP_TEXTURE_SIZE'; GL_TEXTURE0: result := 'GL_TEXTURE0'; GL_TEXTURE1: result := 'GL_TEXTURE1'; GL_TEXTURE2: result := 'GL_TEXTURE2'; GL_TEXTURE3: result := 'GL_TEXTURE3'; GL_TEXTURE4: result := 'GL_TEXTURE4'; GL_TEXTURE5: result := 'GL_TEXTURE5'; GL_TEXTURE6: result := 'GL_TEXTURE6'; GL_TEXTURE7: result := 'GL_TEXTURE7'; GL_TEXTURE8: result := 'GL_TEXTURE8'; GL_TEXTURE9: result := 'GL_TEXTURE9'; GL_TEXTURE10: result := 'GL_TEXTURE10'; GL_TEXTURE11: result := 'GL_TEXTURE11'; GL_TEXTURE12: result := 'GL_TEXTURE12'; GL_TEXTURE13: result := 'GL_TEXTURE13'; GL_TEXTURE14: result := 'GL_TEXTURE14'; GL_TEXTURE15: result := 'GL_TEXTURE15'; GL_TEXTURE16: result := 'GL_TEXTURE16'; GL_TEXTURE17: result := 'GL_TEXTURE17'; GL_TEXTURE18: result := 'GL_TEXTURE18'; GL_TEXTURE19: result := 'GL_TEXTURE19'; GL_TEXTURE20: result := 'GL_TEXTURE20'; GL_TEXTURE21: result := 'GL_TEXTURE21'; GL_TEXTURE22: result := 'GL_TEXTURE22'; GL_TEXTURE23: result := 'GL_TEXTURE23'; GL_TEXTURE24: result := 'GL_TEXTURE24'; GL_TEXTURE25: result := 'GL_TEXTURE25'; GL_TEXTURE26: result := 'GL_TEXTURE26'; GL_TEXTURE27: result := 'GL_TEXTURE27'; GL_TEXTURE28: result := 'GL_TEXTURE28'; GL_TEXTURE29: result := 'GL_TEXTURE29'; GL_TEXTURE30: result := 'GL_TEXTURE30'; GL_TEXTURE31: result := 'GL_TEXTURE31'; GL_ACTIVE_TEXTURE: result := 'GL_ACTIVE_TEXTURE'; GL_REPEAT: result := 'GL_REPEAT'; GL_CLAMP_TO_EDGE: result := 'GL_CLAMP_TO_EDGE'; GL_MIRRORED_REPEAT: result := 'GL_MIRRORED_REPEAT'; GL_FLOAT_VEC2: result := 'GL_FLOAT_VEC2'; GL_FLOAT_VEC3: result := 'GL_FLOAT_VEC3'; GL_FLOAT_VEC4: result := 'GL_FLOAT_VEC4'; GL_INT_VEC2: result := 'GL_INT_VEC2'; GL_INT_VEC3: result := 'GL_INT_VEC3'; GL_INT_VEC4: result := 'GL_INT_VEC4'; GL_BOOL: result := 'GL_BOOL'; GL_BOOL_VEC2: result := 'GL_BOOL_VEC2'; GL_BOOL_VEC3: result := 'GL_BOOL_VEC3'; GL_BOOL_VEC4: result := 'GL_BOOL_VEC4'; GL_FLOAT_MAT2: result := 'GL_FLOAT_MAT2'; GL_FLOAT_MAT3: result := 'GL_FLOAT_MAT3'; GL_FLOAT_MAT4: result := 'GL_FLOAT_MAT4'; GL_SAMPLER_2D: result := 'GL_SAMPLER_2D'; GL_SAMPLER_CUBE: result := 'GL_SAMPLER_CUBE'; GL_VERTEX_ATTRIB_ARRAY_ENABLED: result := 'GL_VERTEX_ATTRIB_ARRAY_ENABLED'; GL_VERTEX_ATTRIB_ARRAY_SIZE: result := 'GL_VERTEX_ATTRIB_ARRAY_SIZE'; GL_VERTEX_ATTRIB_ARRAY_STRIDE: result := 'GL_VERTEX_ATTRIB_ARRAY_STRIDE'; GL_VERTEX_ATTRIB_ARRAY_TYPE: result := 'GL_VERTEX_ATTRIB_ARRAY_TYPE'; GL_VERTEX_ATTRIB_ARRAY_NORMALIZED: result := 'GL_VERTEX_ATTRIB_ARRAY_NORMALIZED'; GL_VERTEX_ATTRIB_ARRAY_POINTER: result := 'GL_VERTEX_ATTRIB_ARRAY_POINTER'; GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING: result := 'GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING'; {$ifdef API_OPENGLES} GL_IMPLEMENTATION_COLOR_READ_TYPE: result := 'GL_IMPLEMENTATION_COLOR_READ_TYPE'; GL_IMPLEMENTATION_COLOR_READ_FORMAT: result := 'GL_IMPLEMENTATION_COLOR_READ_FORMAT'; {$endif} GL_COMPILE_STATUS: result := 'GL_COMPILE_STATUS'; GL_INFO_LOG_LENGTH: result := 'GL_INFO_LOG_LENGTH'; GL_SHADER_SOURCE_LENGTH: result := 'GL_SHADER_SOURCE_LENGTH'; {$ifdef API_OPENGLES} GL_SHADER_COMPILER: result := 'GL_SHADER_COMPILER'; GL_SHADER_BINARY_FORMATS: result := 'GL_SHADER_BINARY_FORMATS'; GL_NUM_SHADER_BINARY_FORMATS: result := 'GL_NUM_SHADER_BINARY_FORMATS'; GL_LOW_FLOAT: result := 'GL_LOW_FLOAT'; GL_MEDIUM_FLOAT: result := 'GL_MEDIUM_FLOAT'; GL_HIGH_FLOAT: result := 'GL_HIGH_FLOAT'; GL_LOW_INT: result := 'GL_LOW_INT'; GL_MEDIUM_INT: result := 'GL_MEDIUM_INT'; GL_HIGH_INT: result := 'GL_HIGH_INT'; {$endif} GL_FRAMEBUFFER: result := 'GL_FRAMEBUFFER'; GL_RENDERBUFFER: result := 'GL_RENDERBUFFER'; GL_RGBA4: result := 'GL_RGBA4'; GL_RGB5_A1: result := 'GL_RGB5_A1'; {$ifdef API_OPENGLES} GL_RGB565: result := 'GL_RGB565'; {$endif} GL_DEPTH_COMPONENT16: result := 'GL_DEPTH_COMPONENT16'; //GL_STENCIL_INDEX: // result := 'GL_STENCIL_INDEX'; //GL_STENCIL_INDEX8: // result := 'GL_STENCIL_INDEX8'; GL_RENDERBUFFER_WIDTH: result := 'GL_RENDERBUFFER_WIDTH'; GL_RENDERBUFFER_HEIGHT: result := 'GL_RENDERBUFFER_HEIGHT'; GL_RENDERBUFFER_INTERNAL_FORMAT: result := 'GL_RENDERBUFFER_INTERNAL_FORMAT'; GL_RENDERBUFFER_RED_SIZE: result := 'GL_RENDERBUFFER_RED_SIZE'; GL_RENDERBUFFER_GREEN_SIZE: result := 'GL_RENDERBUFFER_GREEN_SIZE'; GL_RENDERBUFFER_BLUE_SIZE: result := 'GL_RENDERBUFFER_BLUE_SIZE'; GL_RENDERBUFFER_ALPHA_SIZE: result := 'GL_RENDERBUFFER_ALPHA_SIZE'; GL_RENDERBUFFER_DEPTH_SIZE: result := 'GL_RENDERBUFFER_DEPTH_SIZE'; GL_RENDERBUFFER_STENCIL_SIZE: result := 'GL_RENDERBUFFER_STENCIL_SIZE'; GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE: result := 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE'; GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME: result := 'GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME'; GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL: result := 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL'; GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE: result := 'GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE'; GL_COLOR_ATTACHMENT0: result := 'GL_COLOR_ATTACHMENT0'; GL_DEPTH_ATTACHMENT: result := 'GL_DEPTH_ATTACHMENT'; GL_STENCIL_ATTACHMENT: result := 'GL_STENCIL_ATTACHMENT'; GL_FRAMEBUFFER_COMPLETE: result := 'GL_FRAMEBUFFER_COMPLETE'; GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT: result := 'GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT'; GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT: result := 'GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT'; {$ifdef API_OPENGLES} GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS: result := 'GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS'; {$endif} GL_FRAMEBUFFER_UNSUPPORTED: result := 'GL_FRAMEBUFFER_UNSUPPORTED'; GL_FRAMEBUFFER_BINDING: result := 'GL_FRAMEBUFFER_BINDING'; GL_RENDERBUFFER_BINDING: result := 'GL_RENDERBUFFER_BINDING'; GL_MAX_RENDERBUFFER_SIZE: result := 'GL_MAX_RENDERBUFFER_SIZE'; GL_INVALID_FRAMEBUFFER_OPERATION: result := 'GL_INVALID_FRAMEBUFFER_OPERATION'; otherwise exit(HexStr(enum, 4)); end; result += ' ($'+HexStr(enum, 4)+')'; end; procedure GLAssert(messageString: string = 'OpenGL error'); var error: GLenum; begin error := glGetError(); Assert(error = GL_NO_ERROR, messageString+' '+GLEnumToStr(error)); end; end.
unit unit_pelaporan; {unit ini berisi prosedur tentang pelaporan pada program perpustakaan} interface uses unit_csv, unit_type; {prosedur untuk meminjam buku} procedure peminjaman_(var buku, peminjaman: textfile; var tabelbuku, tabelpeminjaman : tabel_data; nama_pengunjung : string); {prosedur untuk mengembalikan buku} procedure pengembalian_(var peminjaman, pengembalian, buku : textfile; var tabel_peminjaman, tabel_pengembalian, tabel_buku : tabel_data; nama_pengunjung : string); {proseduru untuk melaporkan buku yang hilang} procedure laporhilang(var hilang : textfile; var tabelhilang : tabel_data; nama_pengunjung : string); implementation {fungsi untuk menghitung hari berdasarkan tanggal} function hitung_hari(tanggal : string) : longint; {KAMUS LOKAL} var hari, bulan, tahun : longint; isKabisat : boolean; {ALGORITMA} begin {Inisialisasi hari, bulan, dan Tanggal} hari := StrToInt(tanggal[1] + tanggal[2]); bulan := StrToInt(tanggal[4] + tanggal[5]); tahun := StrToInt(tanggal[7] + tanggal[8] + tanggal[9] + tanggal[10]); {convert tahun menjadi hari} tahun := ((tahun -1) * 365 + (tahun-1) div 4 - (tahun-1) div 100 + (tahun-1) div 400); if ((tahun mod 4 = 0) and (tahun mod 100 <> 0)) or (tahun mod 400 = 0) then begin isKabisat := True; end else begin isKabisat := False; end; {convert bulan menjadi hari} case bulan of 1 : begin bulan := 0; end; 2 : begin bulan := 31 ; end; 3 : begin bulan := 31 + 28; end; 4 : begin bulan := 31 + 28 + 31; end; 5 : begin bulan := 31 + 28 + 31 + 30; end; 6 : begin bulan := 31 + 28 + 31 + 30 + 31; end; 7 : begin bulan := 31 + 28 + 31 + 30 + 31 + 30; end; 8 : begin bulan := 31 + 28 + 31 + 30 + 31 + 30 + 31; end; 9 : begin bulan := 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31; end; 10 : begin bulan := 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30; end; 11: begin bulan := 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31; end; 12 : begin bulan := 31 + 28 + 31 + 30 + 31 + 30 + 31 + 31 + 30 + 31 + 30; end; end; hitung_hari := hari + bulan + tahun; if (isKabisat) and (bulan > 2) then begin hitung_hari := hitung_hari + 1; end; end; function is_bulan_31(bulan : integer) : boolean; {DESKRIPSI FUNGSI} {Fungsi yang menentukan apakah bulan itu memilki 31 hari atau tidak} {ALGORITMA} begin if ((bulan <= 7) and (bulan mod 2 = 1)) or ((bulan > 7) and (bulan mod 2 = 0)) then begin is_bulan_31 := true; end else begin is_bulan_31 := false; end; end; function is_bulan_30(bulan : integer) : boolean; {DESKRIPSI FUNGSI} {Fungsi yang menentukan apakah bulan itu memilki 30 hari atau tidak} {ALGORITMA} begin if ((bulan <= 7) and (bulan mod 2 = 0) and (bulan <> 2)) or ((bulan > 7) and (bulan mod 2 = 1)) then begin is_bulan_30 := true; end else begin is_bulan_30 := false; end; end; function tanggal_pengembalian(tanggal : string) : string; {DEKSRIPSI FUNGSI} {fungsi untuk mengembalikan tanggal pengembalian = tanggal pinjam + 7 hari} {KAMUS LOKAL} var hasil : string; hasil_akhir, temp: string; hari, bulan, tahun, i : integer; banyak_slash : integer; kabisat : boolean; {ALGORITMA} begin {Memisah hari,bulan dan tanggal} hari := StrToInt(tanggal[1] + tanggal[2]); bulan := StrToInt(tanggal[4] + tanggal[5]); tahun := StrToInt(tanggal[7] + tanggal[8] + tanggal[9] + tanggal[10]); {Mengecek apakah tahun kabisat atau tidak} if ((tahun mod 4 = 0) and (tahun mod 100 <> 0)) or (tahun mod 400 = 0) then begin kabisat := true; end else begin kabisat := false; end; {Cek semua kasus untuk menambahkan hari sebanyak 7 pada tanggal} if (hari <= 21) or ((hari <= 22) and (bulan = 2) and (kabisat)) or ((hari <= 24) and (is_bulan_31(bulan)) ) or ((hari <= 23) and (is_bulan_30(bulan))) then begin hasil := IntToStr(hari+7) + '/' + IntToStr(bulan) + '/' + IntToStr(tahun); end else if (bulan = 2) and (hari > 21) and not kabisat then begin hasil := IntToStr((hari+7) - 28) + '/' + IntToStr(bulan + 1) + '/' + IntToStr(tahun); end else if (bulan = 2) and (hari > 22) and kabisat then begin hasil := IntToStr((hari+7) - 29) + '/' + IntToStr(bulan + 1) + '/' + IntToStr(tahun); end else if (bulan = 12) and (hari > 24) then begin hasil := IntToStr((hari+7) mod 31) + '/' + IntToStr(1) + '/' + IntToStr(tahun+1); end else if (is_bulan_30(bulan)) and (hari > 23) then begin hasil := IntToStr((hari+7) mod 30) + '/' + IntToStr(bulan + 1) + '/' + IntToStr(tahun); end else if (is_bulan_31(bulan)) and (hari > 24) then begin hasil := IntToStr((hari+7) mod 31) + '/' + IntToStr(bulan + 1) + '/' + IntToStr(tahun); end; {Parse tanggal dengan delimiter ','} banyak_slash := 0; {set hasil_akhir dengan temp menjadi kosong} hasil_akhir := ''; temp := ''; for i := 1 to length(hasil) do begin temp := temp + hasil[i]; if (hasil[i] = '/') then begin inc(banyak_slash); {Jika ternyata panjang temp kurang dari 3 maka tambahkan 0 didepan} if (banyak_slash <= 2) and (length(temp) < 3) then begin temp := '0' + temp; end; hasil_akhir := hasil_akhir + temp; temp := ''; end; end; {Jika kekurangan 0 (leading zeroes) pada tahun maka tambahkan '0' di awal sampai tahun menjadi 4 digit} if (length(temp) < 4) then begin for i := 1 to 4-length(temp) do begin temp := '0' + temp; end; end; hasil_akhir := hasil_akhir + temp; tanggal_pengembalian := hasil_akhir; end; procedure peminjaman_(var buku, peminjaman: textfile; var tabelbuku, tabelpeminjaman : tabel_data; nama_pengunjung : string); {DESKRIPSI PROSEDUR} {prosedur untuk peminjaman buku yang dilakukan oleh pengunjung yang sudah login} {KAMUS LOKAL} var barisb : integer; {baris tabelbuku} i, id: integer; tanggal: string; arraybuku : array_of_buku; {buat array of buku} arraypeminjaman : array_of_peminjaman; {buat array of peminjaman} banyak_peminjaman : integer; found : boolean; {variabel untuk mengecek apakah ada buku atau tidak} {ALGORITMA} begin {mencari baris dan kolom tiap tabel} barisb := cari_baris(tabelbuku); arraybuku := buat_array_buku(tabelbuku); arraypeminjaman := buat_array_peminjaman(tabelpeminjaman); write('Masukkan id buku yang ingin dipinjam : '); readln(id); write('Masukkan tanggal hari ini : '); readln(tanggal); found := false; {mencari id buku pada arraybuku} for i := 1 to barisb do begin if (arraybuku[i].id_buku = id) then begin {buku ditemukan} found := true; {cek berapa banyak buku yang tersisa} if (arraybuku[i].id_buku = 0) then begin writeln('Buku ', arraybuku[i].judul_buku, ' sedang habis!'); writeln('Coba lain kali'); end else begin writeln('Buku ', arraybuku[i].judul_buku, ' berhasil dipinjam!'); {mengurangi jumlah buku yang dipinjam sebanyak satu} inc(arraybuku[i].jumlah_buku, -1); writeln('Tersisa ', arraybuku[i].jumlah_buku, ' buku ', arraybuku[i].judul_buku); {menambahkan data ke file peminjaman} banyak_peminjaman := length(arraypeminjaman); setlength(arraypeminjaman, banyak_peminjaman + 1); arraypeminjaman[banyak_peminjaman].username := nama_pengunjung; arraypeminjaman[banyak_peminjaman].id_buku := id; arraypeminjaman[banyak_peminjaman].tanggal_peminjaman := tanggal; arraypeminjaman[banyak_peminjaman].tanggal_batas_pengembalian := tanggal_pengembalian(tanggal); arraypeminjaman[banyak_peminjaman].status_pengembalian := 'belum'; masukkan_array_buku(arraybuku, tabelbuku); masukkan_array_peminjaman(arraypeminjaman, tabelpeminjaman); writeln('Terima kasih sudah meminjam.'); end; end; end; if not found then begin writeln('ID buku tidak ditemukan.'); end; end; procedure pengembalian_(var peminjaman, pengembalian, buku : textfile; var tabel_peminjaman, tabel_pengembalian, tabel_buku : tabel_data; nama_pengunjung : string); {DESKRIPSI PROSEDUR} {Prosedur untuk mengupdate data jika pengguna mengembalikan buku} {KAMUS LOKAL} var id : integer; barism, i, j: integer; {baris pada tabel_peminjaman} barisb : integer; {baris pada tabel_buku} nama_buku, tanggal, tanggalb : string; arraybuku : array_of_buku; arraypeminjaman : array_of_peminjaman; arraypengembalian : array_of_pengembalian; banyakpengembalian : integer; pos : integer; {baris di mana id buku beada di tabel_buku} found : boolean; {boolen untuk mengecek apakah ada atau tidak data peminjaman-nya} {ALGORITMA} begin write('Masukkan id buku yang ingin dikembalikan: '); readln(id); {Mencari baris dan kolom} barism := cari_baris(tabel_peminjaman); barisb := cari_baris(tabel_buku); {Memasukkan tabel hasil parse ke dalam array of type} arraypengembalian := buat_array_pengembalian(tabel_pengembalian); arraybuku := buat_array_buku(tabel_buku); arraypeminjaman := buat_array_peminjaman(tabel_peminjaman); found := false; {Mencari data yang sesuai pada tabel_peminjaman} for i := 1 to barism do begin {kolom pertama merupakan data username dan kolom kedua merupakan data id} if (arraypeminjaman[i].username = nama_pengunjung) and (arraypeminjaman[i].id_buku = id) then begin {data peminjaman ditemukan} found := true; {mencari nama id buku sekaligus dibaris berapa id buku tersebut berada pada tabel_buku} for j := 1 to barisb do begin if (arraybuku[j].id_buku = id) then begin pos := j; nama_buku := arraybuku[j].judul_buku; end; end; {Menampilkan data peminjaman} writeln('Data peminjaman:'); writeln('Username: ', nama_pengunjung); writeln('Judul buku: ', nama_buku); writeln('Tanggal peminjaman: ', arraypeminjaman[i].tanggal_peminjaman); writeln('Tanggal batas pengembalian: ', arraypeminjaman[i].tanggal_batas_pengembalian); writeln(); write('Masukkan tanggal hari ini: '); readln(tanggal); tanggalb := arraypeminjaman[i].tanggal_batas_pengembalian; {Cek apakah sudah telat atau belum} {Cek lebih besar mana tahunnya} if hitung_hari(tanggal) > hitung_hari(tanggalb) then begin writeln('Anda terlambat mengembalikan buku.'); writeln('Anda terkena denda ', 2000 * (hitung_hari(tanggal) - hitung_hari(tanggalb)),'.'); end else begin arraypeminjaman[i].status_pengembalian := 'sudah'; {update bahwa pengunjung sudah mengembalikan} //tabel_peminjaman[i][5] := 'sudah'; inc(arraybuku[pos].jumlah_buku, 1); {menambah buku yang sudah dibalikkan pada data buku} {Menambahkan data ke history pengembalian} banyakpengembalian := length(arraypengembalian); SetLength(arraypengembalian, banyakpengembalian + 1); arraypengembalian[banyakpengembalian].username := nama_pengunjung; arraypengembalian[banyakpengembalian].id_buku := id; arraypengembalian[banyakpengembalian].tanggal_pengembalian := tanggal; writeln('Terima kasih sudah meminjam.'); masukkan_array_buku(arraybuku, tabel_buku); masukkan_array_peminjaman(arraypeminjaman, tabel_peminjaman); masukkan_array_pengembalian(arraypengembalian, tabel_pengembalian); end; end; end; if not found then begin writeln('Data peminjaman tidak ditemukan.'); end; end; procedure laporhilang(var hilang : textfile; var tabelhilang : tabel_data; nama_pengunjung : string); {DESKRIPSI PROSEDUR} {Prosedur untuk menambahkan data ke kehilangan.csv saat pengunjung yang sudah login melaporkan bukunnya yang hilang} {KAMUS LOKAL} var id : integer; judul, tanggal : string; arraylaporan : array_of_laporan; banyaklaporan : integer; {ALGORITMA} begin write('Masukkan id buku : '); readln(id); write('Masukkan judul buku : '); readln(judul); write('Masukkan tanggal pelaporan : '); readln(tanggal); {Masukkan tabel hasil parse ke dalam array of laporan} arraylaporan := buat_array_laporan(tabelhilang); {Tambahkan data ke kehilangan.csv} banyaklaporan := length(arraylaporan); setLength(arraylaporan, banyaklaporan + 1); arraylaporan[banyaklaporan].username := nama_pengunjung; arraylaporan[banyaklaporan].id_buku := id; arraylaporan[banyaklaporan].tanggal_laporan := tanggal; masukkan_array_laporan(arraylaporan, tabelhilang); writeln('Laporan berhasil diterima'); save_data(hilang, tabelhilang); end; end.
unit AppManager; interface uses Classes, syncobjs, RunApp; type AM_TString = AnsiString; TApplicationManager = class private RunAppList : TList; CriticalSection : TCriticalSection; procedure DeleteAppFromList(Sender : TObject); function GetEditAppCount : integer; procedure Lock; procedure UnLock; public constructor Create; destructor Destroy; procedure RunApplication(CmdLine,FileName : AM_TString; DocID,VerID : integer; EditMode,SaveMode : boolean); property EditAppCount: integer read GetEditAppCount; end; implementation uses Dialogs; constructor TApplicationManager.Create; begin inherited Create; RunAppList:= TList.Create; end; destructor TApplicationManager.Destroy; begin RunAppList.free; inherited Destroy; end; procedure TApplicationManager.RunApplication(CmdLine,FileName : AM_TString; DocID,VerID : integer; EditMode,SaveMode : boolean); var RunApp : TRunApplication; i : integer; begin // search for identical application for i:= 0 to RunAppList.Count-1 do if (TRunApplication(RunAppList.Items[i]).FileName = FileName) and (TRunApplication(RunAppList.Items[i]).EditMode = EditMode) then begin MessageDlg('Приложение уже открыто',mtInformation,[mbOk],0); exit; end; RunApp:= TRunApplication.Create(CmdLine,FileName,DocID,VerID,EditMode,SaveMode); RunAppList.Add(RunApp); RunApp.OnTerminate:= DeleteAppFromList; end; procedure TApplicationManager.DeleteAppFromList(Sender : TObject); var i : integer; begin // Lock; for i:= 0 to RunAppList.Count-1 do if RunAppList.Items[i] = Sender then RunAppList.Delete(i); // UnLock; end; function TApplicationManager.GetEditAppCount : integer; var i : integer; begin Result:= 0; for i:= 0 to RunAppList.Count-1 do if TRunApplication(RunAppList.Items[i]).EditMode then inc(Result); end; procedure TApplicationManager.Lock; begin {$ifdef WIN32} CriticalSection.Enter; {$endif} end; procedure TApplicationManager.UnLock; begin {$ifdef WIN32} CriticalSection.Leave; {$endif} end; end.
unit fMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Memo.Types, FMX.Menus, System.Actions, FMX.ActnList, FMX.StdActns, FMX.StdCtrls, FMX.Controls.Presentation, FMX.ScrollBox, FMX.Memo, FMX.Objects; type TForm1 = class(TForm) mmo: TMemo; ActionList1: TActionList; ToolBar1: TToolBar; FileExit1: TFileExit; MainMenu1: TMainMenu; mnuFichier: TMenuItem; mnuFichierQuitter: TMenuItem; mnuMac: TMenuItem; mnuFichierOuvrir: TMenuItem; mnuFichierEnregistrer: TMenuItem; mnuFichierSeparateur: TMenuItem; btnNouveau: TButton; btnOuvrir: TButton; btnEnregistrer: TButton; btnFermer: TButton; svgOuvrir: TPath; svgEnregistrer: TPath; svgFermer: TPath; svgNew: TPath; mnuFichierFermer: TMenuItem; mnuFichierNouveau: TMenuItem; actNouveauFichier: TAction; actChargerFichier: TAction; actEnregistrerFichier: TAction; actFermerFichier: TAction; StyleBook1: TStyleBook; OpenDialog1: TOpenDialog; SaveDialog1: TSaveDialog; procedure FormCreate(Sender: TObject); procedure actNouveauFichierExecute(Sender: TObject); procedure actFermerFichierExecute(Sender: TObject); procedure actChargerFichierExecute(Sender: TObject); procedure actEnregistrerFichierExecute(Sender: TObject); procedure mmoChangeTracking(Sender: TObject); private FNomDuFichierOuvert: string; FFichierModifier: boolean; procedure SetNomDuFichierOuvert(const Value: string); procedure SetFichierModifier(const Value: boolean); { Déclarations privées } protected procedure ChangerTitreDeFenetre; property NomDuFichierOuvert: string read FNomDuFichierOuvert write SetNomDuFichierOuvert; property FichierModifier: boolean read FFichierModifier write SetFichierModifier; public { Déclarations publiques } end; var Form1: TForm1; implementation {$R *.fmx} uses System.IOUtils; procedure TForm1.actChargerFichierExecute(Sender: TObject); begin if OpenDialog1.Execute and (OpenDialog1.FileName <> '') and tfile.Exists(OpenDialog1.FileName) then begin NomDuFichierOuvert := OpenDialog1.FileName; mmo.Lines.LoadFromFile(NomDuFichierOuvert); FichierModifier := false; end; mmo.SetFocus; end; procedure TForm1.actEnregistrerFichierExecute(Sender: TObject); begin if (mmo.Lines.Count < 1) or ((mmo.Lines.Count = 1) and (mmo.Lines[0].isempty)) then begin mmo.SetFocus; FichierModifier := false; exit; end; if NomDuFichierOuvert.isempty and SaveDialog1.Execute and (SaveDialog1.FileName <> '') then NomDuFichierOuvert := SaveDialog1.FileName; if not NomDuFichierOuvert.isempty then begin mmo.Lines.SaveToFile(NomDuFichierOuvert, tencoding.UTF8); FichierModifier := false; end; mmo.SetFocus; end; procedure TForm1.actFermerFichierExecute(Sender: TObject); begin // TODO : à compléter end; procedure TForm1.actNouveauFichierExecute(Sender: TObject); begin NomDuFichierOuvert := ''; mmo.Lines.Clear; FichierModifier := false; mmo.SetFocus; end; procedure TForm1.ChangerTitreDeFenetre; begin caption := TPath.GetFileNameWithoutExtension(FNomDuFichierOuvert); if FFichierModifier then caption := caption + '(*)'; end; procedure TForm1.FormCreate(Sender: TObject); begin {$IF not Defined(MACOS)} // tout sauf macOS mnuMac.Visible := false; {$ELSE} // sur macOS mnuFichierSeparateur.Visible := false; mnuFichierQuitter.Visible := false; {$ENDIF} OpenDialog1.InitialDir := TPath.GetDocumentsPath; SaveDialog1.InitialDir := TPath.GetDocumentsPath; NomDuFichierOuvert := ''; actFermerFichier.Visible := false; end; procedure TForm1.mmoChangeTracking(Sender: TObject); begin if not FFichierModifier then FichierModifier := true; end; procedure TForm1.SetFichierModifier(const Value: boolean); begin if FFichierModifier <> Value then begin FFichierModifier := Value; ChangerTitreDeFenetre; end; end; procedure TForm1.SetNomDuFichierOuvert(const Value: string); begin FNomDuFichierOuvert := Value; ChangerTitreDeFenetre; end; end.
unit untController; interface uses MVCFramework, MVCFramework.Commons, MVCFramework.Serializer.Commons; type [MVCPath('/api')] TMyController = class(TMVCController) public [MVCPath] [MVCHTTPMethod([httpGET])] procedure Index; [MVCPath('/login')] [MVCHTTPMethod([httpGET])] procedure Login; [MVCPath('/validCall')] [MVCHTTPMethod([httpGET])] procedure ValidCall; protected procedure OnBeforeAction(Context: TWebContext; const AActionName: string; var Handled: Boolean); override; procedure OnAfterAction(Context: TWebContext; const AActionName: string); override; end; implementation uses System.SysUtils, MVCFramework.Logger, System.StrUtils, System.JSON, untTokenHelper, Web.HTTPApp, System.DateUtils; procedure TMyController.Index; begin //use Context property to access to the HTTP request and response Render('Hello DelphiMVCFramework World'); end; procedure TMyController.Login; var JO: TJSONObject; NC: TCookie; begin JO := TJSONObject.Create; JO.AddPair('UserID', '1'); JO.AddPair('FullName', 'Nirav Kaku'); JO.AddPair('Database', 'abccorp'); NC := Context.Response.Cookies.Add; // NC.Secure := True; NC.Expires := IncHour(Now); // NC.Domain := 'localhost'; NC.Name := 'authtoken'; NC.Value := untTokenHelper.GetTokenFromData(JO.ToJSON, untTokenHelper.TheKey); Render('Logged In'); JO.Free; end; procedure TMyController.OnAfterAction(Context: TWebContext; const AActionName: string); begin { Executed after each action } inherited; end; procedure TMyController.OnBeforeAction(Context: TWebContext; const AActionName: string; var Handled: Boolean); begin { Executed before each action if handled is true (or an exception is raised) the actual action will not be called } inherited; end; procedure TMyController.ValidCall; var JO : TJSONObject; CD : string; D : string; begin CD := Context.Request.Cookie('authtoken'); D := untTokenHelper.GetDataFromToken(CD, untTokenHelper.TheKey); if D <> 'Invalid token' then begin JO := TJSONObject.ParseJSONValue(D) as TJSONObject; Render( JO.GetValue('UserID').Value + ',' + JO.GetValue('FullName').Value + ',' + JO.GetValue('Database').Value); end else Render('Invalid login'); end; end.
unit hcVersionList; interface uses Classes; type TVersionRec = record Major, Minor, Release, Build :SmallInt; end; ThcSortOrder = (soAscending,soDescending); ThcVersionList = class(TStringList) public procedure Sort; override; end; function ParseVersionInfo(const VersInfo :string) :TVersionRec; function CompareVersion(Version1, Version2 :TVersionRec) :Integer; implementation uses StrUtils, SysUtils; function ParseVersionInfo(const VersInfo :string) :TVersionRec; { Method to parse version strings in the format Major.Minor.Release.Build into a version record for comparison purposes. If the version string does not contain all values ie: Build then the method assigns 0. In this manner even one of the VersInfo passed is shorter than expected it can still be compared to a complete version string. } var nStart, nEnd :Integer; begin //parse version string into Record since string compare will not work nStart := 1; nEnd := PosEx('.',VersInfo,nStart); if nEnd = 0 then raise Exception.CreateFmt('VersionInfo (%s) is not in expected format!',[VersInfo]); Result.Major := StrToInt(Copy(VersInfo,nStart,nEnd-nStart)); nStart := nEnd + 1; nEnd := PosEx('.',VersInfo,nStart); if nEnd > 0 then Result.Minor := StrToInt(Copy(VersInfo,nStart,nEnd-nStart)) else begin nEnd := Length(VersInfo); Result.Minor := StrToInt(Copy(VersInfo,nStart,nEnd)); Result.Release := 0; Result.Build := 0; exit; end; nStart := nEnd + 1; nEnd := PosEx('.',VersInfo,nStart); if nEnd > 0 then Result.Release := StrToInt(Copy(VersInfo,nStart,nEnd-nStart)) else begin nEnd := Length(VersInfo); Result.Minor := StrToInt(Copy(VersInfo,nStart,nEnd)); Result.Release := 0; Result.Build := 0; exit; end; nStart := nEnd + 1; nEnd := Length(VersInfo); if nEnd > 0 then Result.Build := StrToInt(Copy(VersInfo,nStart,nEnd-nStart)) else begin nEnd := Length(VersInfo); Result.Minor := StrToInt(Copy(VersInfo,nStart,nEnd)); Result.Build := 0; end; end; function CompareVersion(Version1, Version2 :TVersionRec) :Integer; begin //compare for Ascending sort result Result := Version1.Major - Version2.Major; if Result = 0 then //items are equal so continue to compare begin Result := Version1.Minor - Version2.Minor; if Result = 0 then //items are equal so continue to compare begin Result := Version1.Release - Version2.Release; if Result = 0 then //items are equal so continue to compare begin Result := Version1.Build - Version2.Build; end; end; end; end; function StringListCompareVersions(List: TStringList; Index1, Index2: Integer): Integer; { function to parse and compare the VersionInfo strings for 2 items } var Item1VerRec, Item2VerRec :TVersionRec; begin Item1VerRec := ParseVersionInfo(List[Index1]); Item2VerRec := ParseVersionInfo(List[Index2]); Result := CompareVersion(Item1VerRec,Item2VerRec); end; procedure ThcVersionList.Sort; begin CustomSort(StringListCompareVersions); end; end.
Unit InternetFetcher; { Copyright (c) 2001-2013, Kestral Computing Pty Ltd (http://www.kestral.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } Interface Uses AdvBuffers, AdvObjects; Type TInternetFetcherMethod = (imfGet, imfPost); TInternetFetcher = Class (TAdvObject) Private FURL: String; FBuffer: TAdvBuffer; FUsername: String; FPassword: String; FMethod: TInternetFetcherMethod; procedure SetBuffer(const Value: TAdvBuffer); procedure SetPassword(const Value: String); procedure SetUsername(const Value: String); Public Constructor Create; Override; Destructor Destroy; Override; Property URL : String read FURL write FURL; Property Buffer : TAdvBuffer read FBuffer write SetBuffer; Function CanFetch : Boolean; Procedure Fetch; Property Username : String read FUsername write SetUsername; Property Password : String read FPassword write SetPassword; Property Method : TInternetFetcherMethod read FMethod write FMethod; End; Implementation Uses StringSupport, SysUtils, Classes, IdURi, IdFTP, IdHTTP, IdSSLOpenSSL; { TInternetFetcher } function TInternetFetcher.CanFetch: Boolean; begin result := StringStartsWith(url, 'file:') Or StringStartsWith(url, 'http:') or StringStartsWith(url, 'https:') or StringStartsWith(url, 'ftp:'); end; constructor TInternetFetcher.Create; begin inherited; FBuffer := TAdvBuffer.create; FMethod := imfGet; end; destructor TInternetFetcher.Destroy; begin FBuffer.Free; inherited; end; procedure TInternetFetcher.Fetch; var oUri : TIdURI; oHTTP: TIdHTTP; oMem : TMemoryStream; oSSL : TIdSSLIOHandlerSocketOpenSSL; oFtp : TIdFTP; begin if StringStartsWith(url, 'file:') Then FBuffer.LoadFromFileName(Copy(url, 6, $FFFF)) else Begin oUri := TIdURI.Create(url); Try if oUri.Protocol = 'http' Then Begin oHTTP := TIdHTTP.Create(nil); Try oHTTP.HandleRedirects := true; oHTTP.URL.URI := url; oMem := TMemoryStream.Create; try if FMethod = imfPost then oHTTP.Post(url, oMem) else oHTTP.Get(url, oMem); oMem.position := 0; FBuffer.Capacity := oMem.Size; oMem.read(Fbuffer.Data^, oMem.Size); Finally oMem.Free; End; Finally oHTTP.Free; End; End Else if oUri.Protocol = 'https' Then Begin oHTTP := TIdHTTP.Create(nil); Try oSSL := TIdSSLIOHandlerSocketOpenSSL.Create(Nil); Try oHTTP.IOHandler := oSSL; oSSL.SSLOptions.Mode := sslmClient; oSSL.SSLOptions.Method := sslvTLSv1_2; oHTTP.URL.URI := url; oMem := TMemoryStream.Create; try if FMethod = imfPost then oHTTP.Post(url, oMem) else oHTTP.Get(url, oMem); oMem.position := 0; FBuffer.Capacity := oMem.Size; oMem.read(Fbuffer.Data^, oMem.Size); Finally oMem.Free; End; Finally oSSL.Free; End; Finally oHTTP.Free; End; End Else if oUri.Protocol = 'ftp' then begin oFtp := TIdFTP.Create(nil); Try oFTP.Host := oUri.Host; if username = '' then oFTP.Username := 'anonymous' else oFTP.Username := username; oFTP.Password := password; oFTP.Connect; oFTP.Passive := true; oFTP.ChangeDir(oURI.Path); oMem := TMemoryStream.Create; try oFTP.Get(oURI.Document, oMem); oMem.position := 0; FBuffer.Capacity := oMem.Size; oMem.read(Fbuffer.Data^, oMem.Size); Finally oMem.Free; End; Finally oFtp.Free; End; End Else Raise Exception.Create('Protocol '+oUri.Protocol+' not supported'); Finally oUri.Free; End; End; end; procedure TInternetFetcher.SetBuffer(const Value: TAdvBuffer); begin FBuffer.Free; FBuffer := Value; end; procedure TInternetFetcher.SetPassword(const Value: String); begin FPassword := Value; end; procedure TInternetFetcher.SetUsername(const Value: String); begin FUsername := Value; end; End.
{Implementar un programa que lea 200 artículos de una juguetería. De cada artículo se lee: código, descripción, año de fabricación, edad recomendada y precio. Informar la cantidad de artículos que superan el promedio de precios. } program ejercicio1; const fin = 200; type rango = 2000..2020; edades = 0..18; cadena50 = string [50]; articulo = record cod: integer; desc: cadena50; anioF: rango; edad: edades; precio: real; end; articulos = array [1..fin] of articulo; var v: articulos; prom: real; procedure CargarJuguetes (var v: articulos; var prom: real); procedure LeerArticulo (var a: articulo); begin write ('Codigo: '); readln (a.cod); write ('Descripcion: '); readln (a.desc); write ('Anio de fabricacion: '); readln (a.anioF); write ('Edad: '); readln (a.edad); write ('Precio: '); readln (a.precio); writeln; end; var i: integer; a: articulo; suma: real; begin suma:= 0; For i:= 1 to fin do begin LeerArticulo (a); v[i] := a; //LeerArticulo ( v[i] ); suma:= suma + v[i].precio; end; prom:= suma/fin; end; procedure Informar (v: articulos; prom: real); var cant, i: integer; begin cant:= 0; for i:= 1 to fin do if (v[i].precio > prom) then cant:= cant+1; writeln ('Cantidad de articulos cuyo precio supera el promedio: ', cant); end; begin CargarJuguetes (v, prom); Informar (v, prom); end.
unit MemDBF; //////////////////////////////////////////////////////////////////////////////// // // Author: Jaap Baak // https://github.com/transportmodelling/Utils // //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// interface //////////////////////////////////////////////////////////////////////////////// Uses SysUtils,Data.DB,FireDac.Comp.Client,DBF; Type TDBFMemDataSet = record Class Procedure Read(const DBFFileName: String; const MemDataSet: TFDMemTable); static; end; //////////////////////////////////////////////////////////////////////////////// implementation //////////////////////////////////////////////////////////////////////////////// Class Procedure TDBFMemDataSet.Read(const DBFFileName: String; const MemDataSet: TFDMemTable); begin var DBFReader := TDBFReader.Create(DBFFileName); try // Read fields MemDataSet.FieldDefs.Clear; for var Field := 0 to DBFReader.FieldCount-1 do case DBFReader.FieldTypes[Field] of 'C': MemDataSet.FieldDefs.Add(DBFReader.FieldNames[Field],ftString,DBFReader.FieldLength[Field]); 'D': MemDataSet.FieldDefs.Add(DBFReader.FieldNames[Field],ftDate); 'L': MemDataSet.FieldDefs.Add(DBFReader.FieldNames[Field],ftBoolean); 'F','N': if DBFReader.DecimalCount[Field] = 0 then MemDataSet.FieldDefs.Add(DBFReader.FieldNames[Field],ftInteger) else MemDataSet.FieldDefs.Add(DBFReader.FieldNames[Field],ftFloat) end; MemDataSet.CreateDataSet; // Read data for var Rec := 0 to DBFReader.RecordCount-1 do if DBFReader.NextRecord then begin MemDataSet.Append; for var Field := 0 to DBFReader.FieldCount-1 do MemDataSet.Fields[Field].Value := DBFReader[Field]; end else raise exception.Create('Error reading DBF-file'); MemDataSet.First; finally DBFReader.Free; end; end; end.
unit ucUSUARIO; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ucCADASTRO, FMTBcd, SqlExpr, Provider, DB, DBClient, Grids, DBGrids, Buttons, ExtCtrls, StdCtrls, ComCtrls, ToolWin, DBCtrls, dbcgrids, Menus, StrUtils; type TcUSUARIO = class(TcCADASTRO) LabelIncluir: TLabel; LabelAlterar: TLabel; LabelExcluir: TLabel; LabelImprimir: TLabel; gPerm: TDBCtrlGrid; DBTextEnt: TDBText; DBCheckBoxInc: TDBCheckBox; DBCheckBoxAlt: TDBCheckBox; DBCheckBoxExc: TDBCheckBox; DBCheckBoxImp: TDBCheckBox; dPerm: TDataSource; tPerm: TClientDataSet; sPerm: TDataSetProvider; qPerm: TSQLQuery; LabelEntidade: TLabel; procedure FormCreate(Sender: TObject); procedure FormShow(Sender: TObject); procedure PageControl1Change(Sender: TObject); procedure _DataSetAfterOpen(DataSet: TDataSet); procedure _DataSetNewRecord(DataSet: TDataSet); procedure _DataSetAfterScroll(DataSet: TDataSet); procedure tPermNewRecord(DataSet: TDataSet); procedure FTpPrivilegioOnClick(Sender: TObject); procedure ToolButtonGravarClick(Sender: TObject); procedure LabelIncluirClick(Sender: TObject); procedure DBTextEntClick(Sender: TObject); private protected FNmLogin : TEdit; FTpPrivilegio : TComboBox; procedure CarregaPrivilegio; procedure GravaPrivilegio; public end; implementation {$R *.dfm} uses ucFUNCAO, ucDADOS, ucMENU, ucCOMP, ucITEM, ucXML, ucFORM; procedure TcUSUARIO.FormCreate(Sender: TObject); begin inherited; cModoFormulario := mfAlteracaoSomente; _TabMan := 'ADM_USUARIO'; _KeyMan := 'NM_LOGIN'; _ValMan := 'NM_USUARIO'; end; procedure TcUSUARIO.FormShow(Sender: TObject); begin inherited; // FNmLogin := TEdit(FindComponent('NM_LOGIN')); FTpPrivilegio := TComboBox(FindComponent('TP_PRIVILEGIO')); if FTpPrivilegio <> nil then FTpPrivilegio.OnClick := FTpPrivilegioOnClick; end; procedure TcUSUARIO.PageControl1Change(Sender: TObject); begin inherited; CarregaPrivilegio; end; procedure TcUSUARIO._DataSetAfterOpen(DataSet: TDataSet); begin DataSet.FieldByName('CD_SENHA').Visible := False; inherited; end; procedure TcUSUARIO._DataSetNewRecord(DataSet: TDataSet); begin inherited; putitem(DataSet, 'CD_SENHA', cripto('123MUDAR')); end; procedure TcUSUARIO.CarregaPrivilegio; var MyStringList : TStringList; vSql : String; I : Integer; begin LabelEntidade.Visible := (FTpPrivilegio.Text = 'Operador'); LabelIncluir.Visible := LabelEntidade.Visible; LabelAlterar.Visible := LabelEntidade.Visible; LabelExcluir.Visible := LabelEntidade.Visible; LabelImprimir.Visible := LabelEntidade.Visible; gPerm.Visible := LabelEntidade.Visible; if (FNmLogin.Text <> '') and (LabelEntidade.Visible) then begin vSql := 'select * '+ 'from ADM_NIVEL a '+ 'where TP_SITUACAO = 1 ' + 'and NM_LOGIN = ''' + FNmLogin.Text + ''' '; with tPerm do begin Close; qPerm.SQL.Text := vSql; Open; if (IsEmpty) then begin MyStringList := TStringList.Create; dDADOS._Conexao.GetTableNames(MyStringList); for I:=0 to MyStringList.Count-1 do begin if (Copy(MyStringList[I],1,4) = 'GER_') then begin Append; putitem(tPerm, 'NM_LOGIN', FNmLogin.Text); putitem(tPerm, 'CD_ENTIDADE', MyStringList[I]); putitem(tPerm, 'IN_INCLUIR', 'F'); putitem(tPerm, 'IN_ALTERAR', 'F'); putitem(tPerm, 'IN_EXCLUIR', 'F'); putitem(tPerm, 'IN_IMPRIMIR', 'F'); Post; end; end; end; end; end; end; procedure TcUSUARIO.GravaPrivilegio; begin if not tPerm.IsEmpty then tPerm.ApplyUpdates(0); end; procedure TcUSUARIO._DataSetAfterScroll(DataSet: TDataSet); begin inherited; CarregaPrivilegio; end; procedure TcUSUARIO.tPermNewRecord(DataSet: TDataSet); begin inherited; putitem(DataSet, 'TP_SITUACAO', 1); end; procedure TcUSUARIO.FTpPrivilegioOnClick(Sender: TObject); begin CarregaPrivilegio; end; procedure TcUSUARIO.ToolButtonGravarClick(Sender: TObject); begin inherited; GravaPrivilegio; end; procedure TcUSUARIO.LabelIncluirClick(Sender: TObject); begin inherited; with tPerm do begin DisableControls; First; while not EOF do begin with TLabel(Sender) do begin if Tag in [1, 2] then putitem(tPerm, 'IN_INCLUIR', IfThen(item('IN_INCLUIR', tPerm) = 'F', 'T', 'F')); if Tag in [1, 3] then putitem(tPerm, 'IN_ALTERAR', IfThen(item('IN_ALTERAR', tPerm) = 'F', 'T', 'F')); if Tag in [1, 4] then putitem(tPerm, 'IN_EXCLUIR', IfThen(item('IN_EXCLUIR', tPerm) = 'F', 'T', 'F')); if Tag in [1, 5] then putitem(tPerm, 'IN_IMPRIMIR', IfThen(item('IN_IMPRIMIR', tPerm) = 'F', 'T', 'F')); end; Next; end; First; EnableControls; end; end; procedure TcUSUARIO.DBTextEntClick(Sender: TObject); begin inherited; with tPerm do begin Edit; putitem(tPerm, 'IN_INCLUIR', IfThen(item('IN_INCLUIR', tPerm) = 'F', 'T', 'F')); putitem(tPerm, 'IN_ALTERAR', IfThen(item('IN_ALTERAR', tPerm) = 'F', 'T', 'F')); putitem(tPerm, 'IN_EXCLUIR', IfThen(item('IN_EXCLUIR', tPerm) = 'F', 'T', 'F')); putitem(tPerm, 'IN_IMPRIMIR', IfThen(item('IN_IMPRIMIR', tPerm) = 'F', 'T', 'F')); Post; end; end; end.
unit StratClientStratonVerifyingForm; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, CheckLst, ExtCtrls, Buttons, Variants, Straton; type TfrmVerifyStratons = class(TForm) pnlButtons: TPanel; btnOK: TButton; rgrpSearch: TRadioGroup; gbxSearch: TGroupBox; edtSearch: TEdit; sbtnSynonyms: TSpeedButton; pnlCommon: TPanel; pnlAll: TPanel; pnlStratons: TPanel; Label1: TLabel; edtStratons: TEdit; rgrpSplit: TRadioGroup; chlbxAllStratons: TCheckListBox; sbtnReload: TSpeedButton; procedure chlbxAllStratonsClickCheck(Sender: TObject); procedure rgrpSplitClick(Sender: TObject); procedure chlbxAllStratonsKeyPress(Sender: TObject; var Key: Char); procedure rgrpSearchClick(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure FormCreate(Sender: TObject); procedure sbtnReloadClick(Sender: TObject); procedure FormDestroy(Sender: TObject); private { Private declarations } FFoundStratons, FCheckedStratons: TSimpleStratons; FSplitter: char; procedure SetSplitter(Value:char); procedure SetNames; function GetCheckedStratons: TSimpleStratons; public { Public declarations } property Splitter: char read FSplitter write SetSplitter; property FoundStratons: TSimpleStratons read FFoundStratons; property CheckedStratons: TSimpleStratons read GetCheckedStratons; procedure ReloadStratons; procedure LoadFoundStratons; end; var frmVerifyStratons: TfrmVerifyStratons; implementation uses ClientCommon, Facade, BaseObjects; {$R *.DFM} procedure TfrmVerifyStratons.SetNames; var i: integer; begin if (Splitter = '') or (Splitter = ',') then case rgrpSplit.ItemIndex of 0: Splitter := '+'; 1: Splitter := '-'; end; edtStratons.Clear; with chlbxAllStratons do for i := Items.Count - 1 downto 0 do if Checked[i] then edtStratons.Text := edtStratons.Text + FSplitter + (Items.Objects[i] as TSimpleStraton).Name; edtStratons.Text := copy(edtStratons.Text, 2, Length(edtStratons.Text)); end; procedure TfrmVerifyStratons.LoadFoundStratons; var i, iIndex: integer; begin edtStratons.Clear; for i := 0 to chlbxAllStratons.Items.Count - 1 do chlbxAllStratons.Checked[i] := false; if FSplitter = '' then FSplitter := ','; if Assigned(FFoundStratons) then begin for i := 0 to FFoundStratons.Count - 1 do begin iIndex := chlbxAllStratons.Items.IndexOfObject(FFoundStratons.Items[i]); if iIndex > -1 then begin chlbxAllStratons.Checked[iIndex] := true; chlbxAllStratons.ItemIndex := iIndex; end; end; end; SetNames; end; procedure TfrmVerifyStratons.SetSplitter(Value: char); begin if FSplitter <> Value then begin edtStratons.Text := StringReplace(edtStratons.Text,FSplitter,Value, [rfReplaceAll]); FSplitter := Value; if FSplitter = '+' then rgrpSplit.ItemIndex := 0 else if FSplitter = '-' then rgrpSplit.ItemIndex := 1 end; end; procedure TfrmVerifyStratons.chlbxAllStratonsClickCheck(Sender: TObject); //var Obj: TSimpleStraton; var i: integer; begin with chlbxAllStratons do if not Checked[ItemIndex] then for i := 0 to Items.Count - 1 do if Checked[i] then ItemIndex := i; SetNames; end; procedure TfrmVerifyStratons.rgrpSplitClick(Sender: TObject); begin Splitter := ','; case rgrpSplit.ItemIndex of 0: Splitter := '+'; 1: Splitter := '-'; end; SetNames; end; procedure TfrmVerifyStratons.chlbxAllStratonsKeyPress(Sender: TObject; var Key: Char); var i: integer; sKey: string; sFilter: string; begin sKey := AnsiUpperCase(Key); if sKey <> ' ' then begin with chlbxAllStratons do if sKey[1] in ['A'.. 'Z', 'А' .. 'Я', '1' ..'9', '0', '*', '-'] then begin sFilter := AnsiUpperCase(edtSearch.Text) + sKey; for i := 0 to Items.Count - 1 do if ((rgrpSearch.ItemIndex = 0) and (pos(sFilter, AnsiUpperCase(TSimpleStraton(Items.Objects[i]).Name)) = 1)) or ((rgrpSearch.ItemIndex = 1) and (pos(sFilter, AnsiUpperCase(TSimpleStraton(Items.Objects[i]).Definition)) = 1)) then begin chlbxAllStratons.ItemIndex := i; break; end; //rgrpSearch.Caption := 'Искать по (текущая строка поиска ' + sFilter + ')'; end else begin if Items.Count > 0 then ItemIndex := 0 else ItemIndex := -1; //edtSearch.Text := ''; //rgrpSearch.Caption := 'Искать по '; end; end; end; procedure TfrmVerifyStratons.rgrpSearchClick(Sender: TObject); begin rgrpSearch.Caption := 'Искать по '; end; procedure TfrmVerifyStratons.FormClose(Sender: TObject; var Action: TCloseAction); begin edtSearch.Clear; //FoundStratons := nil; {for i := 0 to chlbxAllStratons.Items.Count - 1 do chlbxAllStratons.Checked[i] := false;} end; procedure TfrmVerifyStratons.FormCreate(Sender: TObject); begin FFoundStratons := TSimpleStratons.Create; FFoundStratons.OwnsObjects := false; ReloadStratons; end; procedure TfrmVerifyStratons.sbtnReloadClick(Sender: TObject); begin ReloadStratons; sbtnReload.Down := not sbtnReload.Down; end; procedure TfrmVerifyStratons.FormDestroy(Sender: TObject); begin FreeAndNil(FFoundStratons); FreeAndNil(FCheckedStratons); end; procedure TfrmVerifyStratons.ReloadStratons; var i: integer; begin chlbxAllStratons.Items.BeginUpdate; with TMainFacade.GetInstance.AllSimpleStratons do for i := 0 to Count - 1 do chlbxAllStratons.Items.AddObject(Items[i].List(loFull), Items[i]); LoadFoundStratons; chlbxAllStratons.Items.EndUpdate; end; function TfrmVerifyStratons.GetCheckedStratons: TSimpleStratons; var i: integer; begin if not Assigned(FCheckedStratons) then begin FCheckedStratons := TSimpleStratons.Create; FCheckedStratons.OwnsObjects := false; end; FCheckedStratons.Clear; for i := 0 to chlbxAllStratons.Count - 1 do if chlbxAllStratons.Checked[i] then FCheckedStratons.Add(chlbxAllStratons.Items.Objects[i], false, false); Result := FCheckedStratons; end; end.
unit Formatter; { To format a TDocument HTML document into an HTML string: var formatter: TBaseFormatter; formatter := THtmlFormatter.Create; try szHtml := formatter.GetText(doc); finally formatter.Free; end; To format a TDocument HTML document into just the text: var formatter: TBaseFormatter; formatter := TTextFormatter.Create; try szText := formatter.GetText(doc); finally formatter.Free; end; } interface uses DomCore; type TStringBuilder = class private FCapacity: Integer; FLength: Integer; FValue: TDomString; public constructor Create(ACapacity: Integer); function EndWithWhiteSpace: Boolean; function TailMatch(const Tail: TDomString): Boolean; function ToString: TDomString; //todo: override procedure AppendText(const TextStr: TDomString); property Length: Integer read FLength; end; TBaseFormatter = class private procedure ProcessNode(Node: TNode); protected FDocument: TDocument; FStringBuilder: TStringBuilder; FDepth: Integer; FWhatToShow: Cardinal; FExpandEntities: Boolean; FPreserveWhiteSpace: Boolean; FInAttributes: Boolean; procedure AppendNewLine; procedure AppendParagraph; procedure AppendText(const TextStr: TDomString); virtual; procedure ProcessDocument; virtual; procedure ProcessDocumentTypeNode(DocType: TDocumentType); virtual; procedure ProcessElement(Element: TElement); virtual; procedure ProcessAttribute(Attr: TAttr); virtual; procedure ProcessAttributes(Element: TElement); virtual; procedure ProcessCDataSection(CDataSection: TCDataSection); virtual; procedure ProcessComment(Comment: TComment); virtual; // procedure ProcessEntityReference(EntityReference: TEntityReference); virtual; removed in HTML5 // procedure ProcessNotation(Notation: TNotation); virtual; removed in HTML5 procedure ProcessProcessingInstruction(ProcessingInstruction: TProcessingInstruction); virtual; procedure ProcessTextNode(TextNode: TTextNode); virtual; public constructor Create; function getText(document: TDocument): TDomString; end; THtmlFormatter = class(TBaseFormatter) private FIndent: Integer; function OnlyTextContent(Element: TElement): Boolean; protected procedure ProcessAttribute(Attr: TAttr); override; procedure ProcessComment(Comment: TComment); override; procedure ProcessElement(Element: TElement); override; procedure ProcessTextNode(TextNode: TTextNode); override; public constructor Create; class function GetHTML(Document: TDocument): TDomString; property Indent: Integer read FIndent write FIndent; end; { This TextFormatter class gives results different from: - doc.innerText - doc.textContent It gives its own thing; which really limits how useful it is. - innerText is aware of presentation - like using CSS to all UPPERCASE the text In which case the resulting innerText will be UPPERCASEd - textContent } TTextFormatter = class(TBaseFormatter) protected FInsideAnchor: Boolean; function GetAnchorText(Node: TElement): TDomString; virtual; function GetImageText(Node: TElement): TDomString; virtual; procedure AppendText(const TextStr: TDomString); override; procedure ProcessElement(Element: TElement); override; procedure ProcessTextNode(TextNode: TTextNode); override; public constructor Create; class function GetText(Document: TDocument): TDomString; end; //Get a text represetation of the DOM tree function DumpDOM(const Node: TNode): TDOMString; implementation uses SysUtils, Entities, HtmlTags; const CRLF: TDomString = #13#10; PARAGRAPH_SEPARATOR: TDomString = #13#10#13#10; ViewAsBlockTags: THtmlTagSet = [ ADDRESS_TAG, BLOCKQUOTE_TAG, CAPTION_TAG, CENTER_TAG, DD_TAG, DIV_TAG, DL_TAG, DT_TAG, FIELDSET_TAG, FORM_TAG, FRAME_TAG, H1_TAG, H2_TAG, H3_TAG, H4_TAG, H5_TAG, H6_TAG, HR_TAG, IFRAME_TAG, LI_TAG, NOFRAMES_TAG, NOSCRIPT_TAG, OL_TAG, P_TAG, PRE_TAG, TABLE_TAG, TD_TAG, TH_TAG, TITLE_TAG, UL_TAG ]; // WhatToShow flags (https://dom.spec.whatwg.org/#interface-nodefilter) SHOW_ALL = $FFFFFFFF; SHOW_ELEMENT = $00000001; SHOW_ATTRIBUTE = $00000002; SHOW_TEXT = $00000004; SHOW_CDATA_SECTION = $00000008; // SHOW_ENTITY_REFERENCE = $00000010; //legacy SHOW_ENTITY = $00000020; //legacy SHOW_PROCESSING_INSTRUCTION = $00000040; SHOW_COMMENT = $00000080; SHOW_DOCUMENT = $00000100; SHOW_DOCUMENT_TYPE = $00000200; SHOW_DOCUMENT_FRAGMENT = $00000400; SHOW_NOTATION = $00000800; //legacy function IsWhiteSpace(W: WideChar): Boolean; begin Result := Ord(W) in WhiteSpace end; function normalizeWhiteSpace(const TextStr: TDomString): TDomString; var I, J, Count: Integer; begin SetLength(Result, Length(TextStr)); J := 0; Count := 0; for I := 1 to Length(TextStr) do begin if IsWhiteSpace(TextStr[I]) then begin Inc(Count); Continue end; if Count <> 0 then begin Count := 0; Inc(J); Result[J] := ' ' end; Inc(J); Result[J] := TextStr[I] end; if Count <> 0 then begin Inc(J); Result[J] := ' ' end; SetLength(Result, J) end; function Spaces(Count: Integer): TDomString; var I: Integer; begin SetLength(Result, Count); for I := 1 to Count do Result[I] := ' ' end; function TrimLeftSpaces(const S: TDomString): TDomString; var I: Integer; begin I := 1; while (I <= Length(S)) and (Ord(S[I]) = SP) do Inc(I); Result := Copy(S, I, Length(S) - I + 1) end; constructor TStringBuilder.Create(ACapacity: Integer); begin inherited Create; FCapacity := ACapacity; SetLength(FValue, FCapacity) end; function TStringBuilder.EndWithWhiteSpace: Boolean; begin Result := IsWhiteSpace(FValue[FLength]) end; function TStringBuilder.TailMatch(const Tail: TDomString): Boolean; var TailLen, I: Integer; begin Result := false; TailLen := System.Length(Tail); if TailLen > FLength then Exit; for I := 1 to TailLen do if FValue[FLength - TailLen + I] <> Tail[I] then Exit; Result := true end; function TStringBuilder.ToString: TDomString; begin SetLength(FValue, FLength); Result := FValue end; procedure TStringBuilder.AppendText(const TextStr: TDomString); var TextLen, I: Integer; begin if (FLength + System.Length(TextStr)) > FCapacity then begin FCapacity := 2 * FCapacity; SetLength(FValue, FCapacity) end; TextLen := System.Length(TextStr); for I := 1 to TextLen do FValue[FLength + I] := TextStr[I]; Inc(FLength, TextLen) end; constructor TBaseFormatter.Create; begin inherited Create; FWhatToShow := SHOW_ALL; end; procedure TBaseFormatter.ProcessNode(Node: TNode); begin case Node.nodeType of ELEMENT_NODE: ProcessElement(Node as TElement); DOCUMENT_TYPE_NODE: if (FWhatToShow and SHOW_DOCUMENT_TYPE) <> 0 then ProcessDocumentTypeNode(Node as TDocumentType); TEXT_NODE: if (FWhatToShow and SHOW_TEXT) <> 0 then ProcessTextNode(Node as TTextNode); CDATA_SECTION_NODE: if (FWhatToShow and SHOW_CDATA_SECTION) <> 0 then ProcessCDataSection(Node as TCDataSection); // ENTITY_REFERENCE_NODE: if (FWhatToShow and SHOW_ENTITY_REFERENCE) <> 0 then ProcessEntityReference(Node as TEntityReference); removed in html5 PROCESSING_INSTRUCTION_NODE: if (FWhatToShow and SHOW_PROCESSING_INSTRUCTION) <> 0 then ProcessProcessingInstruction(Node as TProcessingInstruction); COMMENT_NODE: if (FWhatToShow and SHOW_COMMENT) <> 0 then ProcessComment(Node as TComment); // NOTATION_NODE: if (FWhatToShow and SHOW_NOTATION) <> 0 then ProcessNotation(Node as Notation); removed in HTML5 else //Unknown node type end end; procedure TBaseFormatter.AppendNewLine; begin if FStringBuilder.Length > 0 then begin if not FStringBuilder.TailMatch(CRLF) then FStringBuilder.AppendText(CRLF) end end; procedure TBaseFormatter.AppendParagraph; begin if FStringBuilder.Length > 0 then begin if not FStringBuilder.TailMatch(CRLF) then FStringBuilder.AppendText(PARAGRAPH_SEPARATOR) else if not FStringBuilder.TailMatch(PARAGRAPH_SEPARATOR) then FStringBuilder.AppendText(CRLF) end end; procedure TBaseFormatter.AppendText(const TextStr: TDomString); begin FStringBuilder.AppendText(TextStr) end; procedure TBaseFormatter.ProcessAttribute(Attr: TAttr); var I: Integer; begin for I := 0 to Attr.childNodes.length - 1 do ProcessNode(Attr.childNodes.item(I)) end; procedure TBaseFormatter.ProcessAttributes(Element: TElement); var I: Integer; begin if (FWhatToShow and SHOW_ATTRIBUTE) = 0 then Exit; FInAttributes := True; try for I := 0 to Element.attributes.length - 1 do ProcessAttribute(Element.attributes.item(I) as TAttr); finally FInAttributes := False end; end; procedure TBaseFormatter.ProcessCDataSection(CDataSection: TCDataSection); begin // TODO end; procedure TBaseFormatter.ProcessComment(Comment: TComment); begin AppendText('<!--'); AppendText(Comment.data); AppendText('-->') end; procedure TBaseFormatter.ProcessDocument; var i: Integer; begin if not Assigned(FDocument) then Exit; FDepth := 0; for i := 0 to FDocument.ChildNodes.Length-1 do ProcessNode(FDocument.ChildNodes.Item(i)); end; procedure TBaseFormatter.ProcessDocumentTypeNode(DocType: TDocumentType); begin AppendText('<!DOCTYPE'); AppendText(' '); AppendText(DocType.name); if Doctype.publicId <> '' then begin AppendText(' PUBLIC "'); AppendText(DocType.publicId); AppendText('"'); end; if DocType.systemId <> '' then begin AppendText(' "'); AppendText(DocType.systemId); AppendText('"'); end; AppendText('>'); end; procedure TBaseFormatter.ProcessElement(Element: TElement); var I: Integer; begin Inc(FDepth); for I := 0 to Element.childNodes.length - 1 do ProcessNode(Element.childNodes.item(I)); Dec(FDepth) end; //procedure TBaseFormatter.ProcessEntityReference(EntityReference: TEntityReference); //begin //Removed in HTML5 //end; { procedure TBaseFormatter.ProcessNotation(Notation: TNotation); begin // TODO end; } procedure TBaseFormatter.ProcessProcessingInstruction(ProcessingInstruction: TProcessingInstruction); begin // TODO end; procedure TBaseFormatter.ProcessTextNode(TextNode: TTextNode); begin AppendText(TextNode.data) end; function TBaseFormatter.getText(document: TDocument): TDomString; begin FDocument := document; FStringBuilder := TStringBuilder.Create(65530); try ProcessDocument; Result := FStringBuilder.ToString finally FStringBuilder.Free end end; constructor THtmlFormatter.Create; begin inherited Create; FIndent := 2 end; class function THtmlFormatter.GetHTML(Document: TDocument): TDomString; var formatter: TBaseFormatter; begin formatter := THtmlFormatter.Create; try Result := formatter.getText(Document); finally formatter.Free; end; end; function THtmlFormatter.OnlyTextContent(Element: TElement): Boolean; var Node: TNode; I: Integer; begin Result := false; for I := 0 to Element.childNodes.length - 1 do begin Node := Element.childNodes.item(I); if not (Node.nodeType in [TEXT_NODE]) then Exit end; Result := true end; procedure THtmlFormatter.ProcessAttribute(Attr: TAttr); begin if Attr.hasChildNodes then begin AppendText(' ' + Attr.name + '="'); inherited ProcessAttribute(Attr); AppendText('"') end else AppendText(' ' + Attr.name + '="' + Attr.Value + '"') end; procedure THtmlFormatter.ProcessComment(Comment: TComment); begin AppendNewLine; AppendText(Spaces(FIndent * FDepth)); inherited ProcessComment(Comment) end; procedure THtmlFormatter.ProcessElement(Element: TElement); var HtmlTag: THtmlTag; begin HtmlTag := HtmlTagList.GetTagByName(Element.tagName); AppendNewLine; AppendText(Spaces(FIndent * FDepth)); AppendText('<' + Element.tagName); ProcessAttributes(Element); if Element.hasChildNodes then begin AppendText('>'); if HtmlTag.Number in PreserveWhiteSpaceTags then FPreserveWhiteSpace := true; inherited ProcessElement(Element); FPreserveWhiteSpace := false; if not OnlyTextContent(Element) then begin AppendNewLine; AppendText(Spaces(FIndent * FDepth)) end; AppendText('</' + Element.tagName + '>') end else AppendText(' />') end; procedure THtmlFormatter.ProcessTextNode(TextNode: TTextNode); var TextStr: TDomString; begin if FPreserveWhiteSpace then AppendText(TextNode.data) else begin TextStr := normalizeWhiteSpace(TextNode.data); if TextStr <> ' ' then AppendText(TextStr) end; end; constructor TTextFormatter.Create; begin inherited Create; FWhatToShow := SHOW_ELEMENT or SHOW_TEXT; FExpandEntities := True end; function TTextFormatter.GetAnchorText(Node: TElement): TDomString; var Attr: TAttr; begin Result := ''; if Node.hasAttribute('href') then begin Attr := Node.getAttributeNode('href'); Result := ' '; if UrlSchemes.GetScheme(Attr.value) = '' then Result := Result + 'http://'; Result := Result + Attr.value end end; function TTextFormatter.GetImageText(Node: TElement): TDomString; begin if Node.hasAttribute('alt') then Result := Node.getAttributeNode('alt').value else Result := '' end; class function TTextFormatter.GetText(Document: TDocument): TDomString; var formatter: TBaseFormatter; begin formatter := TTextFormatter.Create; try Result := formatter.getText(Document); finally formatter.Free; end; end; procedure TTextFormatter.AppendText(const TextStr: TDomString); begin if (FStringBuilder.Length = 0) or FStringBuilder.EndWithWhiteSpace then inherited AppendText(TrimLeftSpaces(TextStr)) else inherited AppendText(TextStr) end; procedure TTextFormatter.ProcessElement(Element: TElement); var HtmlTag: THtmlTag; begin HtmlTag := HtmlTagList.GetTagByName(Element.tagName); if HtmlTag.Number in ViewAsBlockTags then AppendParagraph; case HtmlTag.Number of A_TAG: FInsideAnchor := true; LI_TAG: AppendText('* ') end; if HtmlTag.Number in PreserveWhiteSpaceTags then FPreserveWhiteSpace := true; inherited ProcessElement(Element); FPreserveWhiteSpace := false; case HtmlTag.Number of BR_TAG: AppendNewLine; A_TAG: begin AppendText(GetAnchorText(Element)); FInsideAnchor := false end; IMG_TAG: begin if FInsideAnchor then AppendText(GetImageText(Element)) end end; if HtmlTag.Number in ViewAsBlockTags then AppendParagraph end; procedure TTextFormatter.ProcessTextNode(TextNode: TTextNode); begin if FPreserveWhiteSpace then AppendText(TextNode.data) else AppendText(normalizeWhiteSpace(TextNode.data)) end; function DumpDOM(const Node: TNode): string; function DumpNode(const Node: TNode; Prefix: string): string; var i: Integer; sChild: string; attrNode: TAttr; s: string; const // middlePrefix: string = #$251C#$2500#$2500+' '; // '|--- ' // finalPrefix: string = #$2570#$2500#$2500+' '; // '\--- ' // nestedPrefix: string = #$2502' '; // '| ' middlePrefix: string = #$251C#$2500; // '|-' finalPrefix: string = #$2570#$2500; // '\-' nestedPrefix: string = #$2502' '; // '| ' begin if (Node = nil) then begin Result := ''; Exit; end; case Node.NodeType of DOCUMENT_TYPE_NODE: s := 'DOCTYPE: '+Node.NodeName; ELEMENT_NODE: begin s := Node.NodeName; if node.HasAttributes then begin for i := 0 to node.Attributes.Length-1 do begin attrNode := node.Attributes.Item(i) as TAttr; //For an attribute (TAttr) node: // node.NodeName === attr.Name // node.NodeValue === attr.Value // node.Attributes === null s := s+' '+attrNode.NodeName+'="'+attrNode.NodeValue+'"'; end; end end; TEXT_NODE: begin s := Node.NodeValue; s := StringReplace(s, #13#10, #$23CE, [rfReplaceAll]); //U+23CE RETURN SYMBOL s := StringReplace(s, #13, #$23CE, [rfReplaceAll]); //U+23CE RETURN SYMBOL s := StringReplace(s, #10, #$23CE, [rfReplaceAll]); //U+23CE RETURN SYMBOL s := StringReplace(s, ' ', #$2423, [rfReplaceAll]); //U+2423 OPEN BOX s := Node.NodeName+': "'+s+'"'; end; else s := Node.NodeName; if Node.NodeValue <> '' then s := s+': '+Node.NodeValue; end; Result := s; for i := 0 to Node.ChildNodes.Length-1 do begin Result := Result+CRLF+ prefix; if i < Node.ChildNodes.Length-1 then begin Result := Result + middlePrefix; sChild := DumpNode(Node.ChildNodes[i], prefix+nestedPrefix); end else begin Result := Result + finalPrefix; sChild := DumpNode(Node.ChildNodes[i], prefix+' '); end; Result := Result+sChild; end; end; begin Result := DumpNode(Node, ''); end; end.
unit CreateDBLink; interface uses System.SysUtils, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, CreateObjectDialog, Vcl.StdCtrls, BCControls.ComboBox, BCControls.Edit, Vcl.ImgList, SynEditHighlighter, SynHighlighterSQL, Vcl.ActnList, Vcl.ComCtrls, Vcl.ToolWin, JvExComCtrls, SynEdit, Vcl.ExtCtrls, JvComCtrls, BCControls.PageControl, BCControls.ToolBar, BCDialogs.Dlg, System.Actions, BCControls.ImageList; type TCreateDBLinkDialog = class(TCreateObjectBaseDialog) AvailabilityLabel: TLabel; LinkNameEdit: TBCEdit; LinkNameLabel: TLabel; PasswordEdit: TBCEdit; PasswordLabel: TLabel; PrivateRadioButton: TRadioButton; PublicRadioButton: TRadioButton; ServiceNameComboBox: TBCComboBox; ServiceNameLabel: TLabel; SettingsTabSheet: TTabSheet; UserNameEdit: TBCEdit; UserNameLabel: TLabel; procedure FormDestroy(Sender: TObject); procedure Formshow(Sender: TObject); protected function CheckFields: Boolean; override; procedure CreateSQL; override; procedure GetServiceNames; procedure Initialize; override; end; function CreateDBLinkDialog: TCreateDBLinkDialog; implementation {$R *.dfm} uses Lib, BCCommon.StyleUtils, BCCommon.Messages, BCCommon.Lib; var FCreateDBLinkDialog: TCreateDBLinkDialog; function CreateDBLinkDialog: TCreateDBLinkDialog; begin if not Assigned(FCreateDBLinkDialog) then Application.CreateForm(TCreateDBLinkDialog, FCreateDBLinkDialog); Result := FCreateDBLinkDialog; SetStyledFormSize(TDialog(Result)); end; procedure TCreateDBLinkDialog.FormDestroy(Sender: TObject); begin inherited; FCreateDBLinkDialog := nil; end; procedure TCreateDBLinkDialog.Formshow(Sender: TObject); begin inherited; LinkNameEdit.SetFocus; end; function TCreateDBLinkDialog.CheckFields: Boolean; begin Result := False; if Trim(LinkNameEdit.Text) = '' then begin ShowErrorMessage('Set link name.'); LinkNameEdit.SetFocus; Exit; end; if Trim(UserNameEdit.Text) = '' then begin ShowErrorMessage('Set user name.'); UserNameEdit.SetFocus; Exit; end; if Trim(PasswordEdit.Text) = '' then begin ShowErrorMessage('Set password.'); PasswordEdit.SetFocus; Exit; end; if Trim(ServiceNameComboBox.Text) = '' then begin ShowErrorMessage('Set service name.'); ServiceNameComboBox.SetFocus; Exit; end; Result := True; end; procedure TCreateDBLinkDialog.GetServiceNames; var StringList: TStringList; begin ServiceNameComboBox.Clear; StringList := Lib.GetServerlist; ServiceNameComboBox.Items := StringList; StringList.Free; end; procedure TCreateDBLinkDialog.Initialize; begin inherited; GetServiceNames; end; procedure TCreateDBLinkDialog.CreateSQL; var Availability: string; begin SourceSynEdit.Lines.Clear; SourceSynEdit.Lines.BeginUpdate; Availability := ''; if PublicRadioButton.Checked then Availability := 'PUBLIC '; SourceSynEdit.Text := Format('CREATE %sDATABASE LINK %s', [Availability, LinkNameEdit.Text]) + CHR_ENTER; SourceSynEdit.Text := SourceSynEdit.Text + Format(' CONNECT TO %s', [UserNameEdit.Text]) + CHR_ENTER; SourceSynEdit.Text := SourceSynEdit.Text + Format(' IDENTIFIED BY "%s"', [PasswordEdit.Text]) + CHR_ENTER; SourceSynEdit.Text := SourceSynEdit.Text + Format(' USING ''%s'';', [ServiceNameComboBox.Text]); SourceSynEdit.Lines.EndUpdate; end; end.
unit AureliusParamItem; interface uses ParamManager, Aurelius.Engine.ObjectManager, System.Classes ,ParamModel ; type TAureliusParamItem = class(TParamItem) private FObjectManager: TObjectManager; function GetCompanyParam(const ParamName: string; CompanyID: Variant): TParam; function GetGlobalParam(const ParamName: string): TParam; function GetUserCompanyParam(const ParamName: string; CompanyID, UserID: Variant): TParam; function GetUserParam(const ParamName: string; UserID: Variant): TParam; procedure Insert(const ParamName: string; CompanyID, UserID, Value: Variant); procedure SetCompanyParam(const ParamName, CompanyID: string; Value: Variant); procedure SetGlobalParam(const ParamName: string; Value: Variant); procedure SetUserCompanyParam(const ParamName, UserID, CompanyID: string; Value: Variant); procedure SetUserParam(const ParamName, UserID: string; Value: Variant); procedure SetValue(Param: TParam; const ParamName: string; CompanyID, UserID, Value: Variant); procedure Update(Param: TParam; Value: Variant); protected function CustomGetValue(const ParamName: string; CompanyID: Variant): Variant; override; procedure CustomSetValue(const ParamName: string; Value: Variant); override; public constructor Create(ParamManager: TParamManager; ObjectManager: TObjectManager); reintroduce; procedure LoadFromStream(Stream: TStream); override; procedure SaveToStream(Stream: TStream); override; end; implementation uses Aurelius.Criteria.Base, Aurelius.Criteria.Linq, System.Variants, System.SysUtils, Aurelius.Types.Nullable; constructor TAureliusParamItem.Create(ParamManager: TParamManager; ObjectManager: TObjectManager); begin inherited Create(ParamManager); FObjectManager := ObjectManager; end; function TAureliusParamItem.CustomGetValue(const ParamName: string; CompanyID: Variant): Variant; var Param: TParam; begin Param := nil; FObjectManager.Clear; case SystemScope of ssGlobal: Param := GetGlobalParam(ParamName); ssCompany: Param := GetCompanyParam(ParamName, CompanyID); ssUser: Param := GetUserParam(ParamName, GuidToString(ParamManager.UserID)); ssUserCompany: Param := GetUserCompanyParam(ParamName, CompanyID, GuidToString(ParamManager.UserID)); end; if Param = nil then Result := DefaultValue else begin if Param.Valore.HasValue then Result := Param.Valore else Result := Null; end; end; procedure TAureliusParamItem.CustomSetValue(const ParamName: string; Value: Variant); begin FObjectManager.Clear; case SystemScope of ssGlobal: SetGlobalParam(ParamName, Value); ssCompany: SetCompanyParam(ParamName, ParamManager.CompanyID, Value); ssUser: SetUserParam(ParamName, GuidToString(ParamManager.UserID), Value); ssUserCompany: SetUserCompanyParam(ParamName, GuidToString(ParamManager.UserID), ParamManager.CompanyID, Value); end; end; function TAureliusParamItem.GetCompanyParam(const ParamName: string; CompanyID: Variant): TParam; begin Result := FObjectManager.Find<TParam>.Add( TLinq.Eq('Nome', ParamName) and TLinq.Eq('Company', CompanyID) and TLinq.IsNull('User_Id') ).UniqueResult end; function TAureliusParamItem.GetGlobalParam(const ParamName: string): TParam; begin Result := FObjectManager.Find<TParam>.Add( TLinq.Eq('Nome', ParamName) and TLinq.IsNull('Company') and TLinq.IsNull('User_Id') ).UniqueResult; end; function TAureliusParamItem.GetUserCompanyParam(const ParamName: string; CompanyID, UserID: Variant): TParam; begin Result := FObjectManager.Find<TParam>.Add( TLinq.Eq('Nome', ParamName) and TLinq.Eq('Company', CompanyID) and TLinq.Eq('User_Id', UserID) ).UniqueResult; end; function TAureliusParamItem.GetUserParam(const ParamName: string; UserID: Variant): TParam; begin Result := FObjectManager.Find<TParam>.Add( TLinq.Eq('Nome', ParamName) and TLinq.Eq('User_Id', UserID) and TLinq.IsNull('Company') ).UniqueResult end; procedure TAureliusParamItem.Insert(const ParamName: string; CompanyID, UserID, Value: Variant); var Param: TParam; begin Param := TParam.Create; try Param.Nome := ParamName; if Value <> Null then Param.Valore := Value; if CompanyID <> Null then Param.Company := CompanyID; if UserID <> Null then Param.User_Id := UserID; except Param.Free; raise; end; FObjectManager.Save(Param); end; procedure TAureliusParamItem.SetCompanyParam(const ParamName, CompanyID: string; Value: Variant); var Param: TParam; begin Param := GetCompanyParam(ParamName, CompanyID); SetValue(Param, ParamName, CompanyID, Null, Value); end; procedure TAureliusParamItem.SetGlobalParam(const ParamName: string; Value: Variant); var Param: TParam; begin Param := GetGlobalParam(ParamName); SetValue(Param, ParamName, Null, Null, Value) end; procedure TAureliusParamItem.SetUserCompanyParam(const ParamName, UserID, CompanyID: string; Value: Variant); var Param: TParam; begin Param := GetUserCompanyParam(ParamName, CompanyID, UserID); SetValue(Param, ParamName, CompanyID, UserID, Value); end; procedure TAureliusParamItem.SetUserParam(const ParamName, UserID: string; Value: Variant); var Param: TParam; begin Param := GetUserParam(ParamName, UserID); SetValue(Param, ParamName, Null, UserID, Value); end; procedure TAureliusParamItem.SetValue(Param: TParam; const ParamName: string; CompanyID, UserID, Value: Variant); begin if Param <> nil then Update(Param, Value) else Insert(ParamName, CompanyID, UserID, Value); FObjectManager.Flush; end; procedure TAureliusParamItem.Update(Param: TParam; Value: Variant); begin if Value = Null then Param.Valore := SNull else Param.Valore := Value; end; procedure TAureliusParamItem.LoadFromStream(Stream: TStream); var Param: TParam; begin Param := GetGlobalParam(ParamName); if Param<>nil then begin Stream.Position := 0; Param.Data.LoadFromStream(Stream); FObjectManager.Flush; end; end; procedure TAureliusParamItem.SaveToStream(Stream: TStream); var Param: TParam; begin Param := GetGlobalParam(ParamName); if Param<>nil then begin Stream.Position := 0; Param.Data.SaveToStream(Stream); end; end; end.
unit FMain; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, System.Math, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Objects, FMX.StdCtrls, FMX.ExtCtrls, FMX.Controls.Presentation, Grijjy.FaceDetection; type TFormMain = class(TForm) ToolBar: TToolBar; LabelImage: TLabel; PopupBoxImage: TPopupBox; PaintBox: TPaintBox; procedure PopupBoxImageChange(Sender: TObject); procedure PaintBoxPaint(Sender: TObject; Canvas: TCanvas); private { Private declarations } FFaceDetector: IgoFaceDetector; FFaces: TArray<TgoFace>; FBitmap: TBitmap; private procedure ProcessImage(const AResourceName: String); public { Public declarations } destructor Destroy; override; end; var FormMain: TFormMain; implementation {$R *.fmx} { TFormMain } destructor TFormMain.Destroy; begin FBitmap.Free; inherited; end; procedure TFormMain.PaintBoxPaint(Sender: TObject; Canvas: TCanvas); var SrcRect, DstRect, Rect: TRectF; Scale, DstWidth, DstHeight: Single; Face: TgoFace; procedure PaintEye(const APosition: TPointF; const AColor: TAlphaColor); var P: TPointF; R: TRectF; Radius: Single; begin { Exit if eye position is not available } if (APosition.X = 0) and (APosition.Y = 0) then Exit; P.X := APosition.X * Scale; P.Y := APosition.Y * Scale; P.Offset(DstRect.TopLeft); Radius := Face.EyesDistance * Scale * 0.2; R := RectF(P.X - Radius, P.Y - Radius, P.X + Radius, P.Y + Radius); Canvas.Stroke.Color := AColor; Canvas.DrawEllipse(R, 1); end; begin { Paint bitmap to fit the paint box while preserving aspect ratio. } SrcRect := RectF(0, 0, FBitmap.Width, FBitmap.Height); Scale := Min(PaintBox.Width / FBitmap.Width, PaintBox.Height / FBitmap.Height); DstWidth := Round(FBitmap.Width * Scale); DstHeight := Round(FBitmap.Height * Scale); DstRect.Left := Floor(0.5 * (PaintBox.Width - DstWidth)); DstRect.Top := Floor(0.5 * (PaintBox.Height - DstHeight)); DstRect.Width := DstWidth; DstRect.Height := DstHeight; Canvas.DrawBitmap(FBitmap, SrcRect, DstRect, 1); Canvas.Stroke.Kind := TBrushKind.Solid; Canvas.Stroke.Thickness := 2; { Paint each face with its features } for Face in FFaces do begin { Paint bounds around entire face } Rect := Face.Bounds; Rect.Left := Floor(Rect.Left * Scale); Rect.Top := Floor(Rect.Top * Scale); Rect.Right := Ceil(Rect.Right * Scale); Rect.Bottom := Ceil(Rect.Bottom * Scale); Rect.Offset(DstRect.TopLeft); Canvas.Stroke.Color := TAlphaColors.Lime; Canvas.DrawRect(Rect, 4, 4, AllCorners, 1); { Paint the eyes } PaintEye(Face.LeftEyePosition, TAlphaColors.Magenta); PaintEye(Face.RightEyePosition, TAlphaColors.Cyan); end; end; procedure TFormMain.PopupBoxImageChange(Sender: TObject); begin ProcessImage(PopupBoxImage.Text); end; procedure TFormMain.ProcessImage(const AResourceName: String); var Stream: TResourceStream; begin { Create bitmap and face detector if needed. } if (FBitmap = nil) then FBitmap := TBitmap.Create; if (FFaceDetector = nil) then { Create a face detector using high accuracy and a maximum detection of 10 faces. } FFaceDetector := TgoFaceDetector.Create(TgoFaceDetectionAccuracy.High, 10); { Load test bitmap from resource } Stream := TResourceStream.Create(HInstance, AResourceName, RT_RCDATA); try FBitmap.LoadFromStream(Stream); finally Stream.Free; end; { Detect faces in bitmap } FFaces := FFaceDetector.DetectFaces(FBitmap); { Show bitmap and detected features } PaintBox.Repaint; end; end.
{----------------------------------------------------------------------------- The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http:{www.mozilla.org/MPL/MPL-1.1.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is: JvMessageControl.pas, released on 2004-10-10 The Initial Developer of the Original Code is André Snepvangers [ASnepvangers att users.sourceforge.net] Portions created by André Snepvangers are Copyright (C) 2004 André Snepvangers. All Rights Reserved. Contributor(s): You may retrieve the latest version of this file at the Project JEDI's JVCL home page, located at http:{jvcl.sourceforge.net Known Issues: It is still possible to move the component in IDE outside the parent. It could also be called as a feature. Object Treeview shows the correct parent. -----------------------------------------------------------------------------} // $Id: JvMessageControl.pas 12337 2009-06-11 10:42:10Z ahuser $ unit JvMessageControl; {$I jvcl.inc} interface uses {$IFDEF UNITVERSIONING} JclUnitVersioning, {$ENDIF UNITVERSIONING} SysUtils, Classes, Windows, Messages, Controls, Forms, JvControlComponent; type TJvMessageControl = class(TJvCustomControlComponent) private FSavedWinProc: TWndMethod; FOnMessage: TWndMethod; protected procedure SetParent(const Value: TWinControl); override; procedure ControlWinProc(var Message: TMessage); public destructor Destroy; override; published property Active; property OnMessage: TWndMethod read FOnMessage write FOnMessage; property Parent; end; {$IFDEF UNITVERSIONING} const UnitVersioning: TUnitVersionInfo = ( RCSfile: '$URL: https://jvcl.svn.sourceforge.net/svnroot/jvcl/branches/JVCL3_47_PREPARATION/run/JvMessageControl.pas $'; Revision: '$Revision: 12337 $'; Date: '$Date: 2009-06-11 12:42:10 +0200 (jeu. 11 juin 2009) $'; LogPath: 'JVCL\run' ); {$ENDIF UNITVERSIONING} implementation procedure TJvMessageControl.ControlWinProc(var Message: TMessage); begin if Active and Assigned(FOnMessage) then { user message/event handler installed ? } FOnMessage(Message); if Message.Result = 0 then FSavedWinProc(Message); { do the original stuff } end; procedure TJvMessageControl.SetParent(const Value: TWinControl); var WasActive: Boolean; begin if Value <> Parent then begin WasActive := Active; Active := False; if Assigned(Parent) then Parent.WindowProc := FSavedWinProc; inherited SetParent(Value); if Assigned(Parent) then begin FSavedWinProc := Parent.WindowProc; Parent.WindowProc := ControlWinProc; { intercept messages } end; Active := WasActive; end; end; destructor TJvMessageControl.Destroy; begin if Assigned(Parent) and not (csDestroying in Parent.ComponentState) then Parent.WindowProc := FSavedWinProc; inherited Destroy; end; {$IFDEF UNITVERSIONING} initialization RegisterUnitVersion(HInstance, UnitVersioning); finalization UnregisterUnitVersion(HInstance); {$ENDIF UNITVERSIONING} end.
unit GerarClasseView; interface uses System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants, FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls, FMX.Controls.Presentation, FMX.Edit; type TGerarClasseFrm = class(TForm) EdtTabela: TEdit; EdtCaminhoArquivo: TEdit; BtnGerarClasse: TButton; CbxImplemetarGettersSetters: TCheckBox; EdtHeranca: TEdit; EdtUsesInterface: TEdit; EdtUsesImplementation: TEdit; procedure BtnGerarClasseClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var GerarClasseFrm: TGerarClasseFrm; implementation uses GerarClasseController; {$R *.fmx} procedure TGerarClasseFrm.BtnGerarClasseClick(Sender: TObject); var oGerarClasse: TGerarClasse; begin oGerarClasse := TGerarClasse.Create(ExtractFilePath(ParamStr(0))+ 'Config.ini'); try oGerarClasse.Heranca := EdtHeranca.Text; oGerarClasse.UsesInterface := EdtUsesInterface.Text; oGerarClasse.UsesImplementation := EdtUsesImplementation.Text; oGerarClasse.GerarGettersAndSetters := CbxImplemetarGettersSetters.IsChecked; if oGerarClasse.GerarClasse(EdtTabela.Text) then ShowMessage('Classe gerada com sucesso!') else ShowMessage('Erro ao gerar classe.'); oGerarClasse.SalvarArquivo(EdtCaminhoArquivo.Text); finally FreeAndNil(oGerarClasse); end; end; end.
{----------------------------------- 功能说明:权限包导出的菜单 创建日期:2010/05/15 作者:wzw 版权:wzw -------------------------------------} unit uAuthorityPlugin; interface uses SysUtils, Classes, Graphics, MainFormIntf, MenuRegIntf, uTangramModule, SysModule, RegIntf; type TAuthorityPlugin = class(TModule) private procedure RoleMgrClick(Sender: TObject); procedure UserMgrClick(Sender: TObject); protected public constructor Create; override; destructor Destroy; override; procedure Init; override; procedure final; override; procedure Notify(Flags: Integer; Intf: IInterface; Param: Integer); override; class procedure RegisterModule(Reg: IRegistry); override; class procedure UnRegisterModule(Reg: IRegistry); override; class procedure RegMenu(Reg: IMenuReg); class procedure UnRegMenu(Reg: IMenuReg); end; implementation uses SysSvc, MenuEventBinderIntf, uUserMgr, uRoleMgr, uConst; const InstallKey = 'SYSTEM\LOADMODULE\SYS'; ValueKey = 'Module=%s;load=True'; Key_RoleMgr = 'ID_79DF059E-63F3-4C06-829D-888A53B1A471'; Key_UserMgr = 'ID_D0F119E7-3404-4213-91A7-7790B9CDD7FB'; { TCustomMenu } constructor TAuthorityPlugin.Create; var EventReg: IMenuEventBinder; begin inherited; EventReg := SysService as IMenuEventBinder; //绑定事件 EventReg.RegMenuEvent(Key_RoleMgr, self.RoleMgrClick); EventReg.RegMenuEvent(Key_UserMgr, self.UserMgrClick); end; destructor TAuthorityPlugin.Destroy; begin inherited; end; procedure TAuthorityPlugin.final; begin inherited; end; procedure TAuthorityPlugin.Init; begin inherited; end; procedure TAuthorityPlugin.Notify(Flags: Integer; Intf: IInterface; Param: Integer); begin if Flags = Flags_RegAuthority then begin TFrmRoleMgr.RegistryAuthority; TfrmUserMgr.RegistryAuthority; end; end; class procedure TAuthorityPlugin.RegisterModule(Reg: IRegistry); var ModuleFullName, ModuleName, Value: string; begin //注册菜单 self.RegMenu(Reg as IMenuReg); //注册包 if Reg.OpenKey(InstallKey, True) then begin ModuleFullName := SysUtils.GetModuleName(HInstance); ModuleName := ExtractFileName(ModuleFullName); Value := Format(ValueKey, [ModuleFullName]); Reg.WriteString(ModuleName, Value); Reg.SaveData; end; end; class procedure TAuthorityPlugin.RegMenu(Reg: IMenuReg); begin Reg.RegMenu(Key_RoleMgr, '系统管理\权限\角色管理'); Reg.RegMenu(Key_UserMgr, '系统管理\权限\用户管理'); end; class procedure TAuthorityPlugin.UnRegisterModule(Reg: IRegistry); var ModuleName: string; begin //取消注册菜单 self.UnRegMenu(Reg as IMenuReg); //取消注册包 if Reg.OpenKey(InstallKey) then begin ModuleName := ExtractFileName(SysUtils.GetModuleName(HInstance)); if Reg.DeleteValue(ModuleName) then Reg.SaveData; end; end; class procedure TAuthorityPlugin.UnRegMenu(Reg: IMenuReg); begin Reg.UnRegMenu(Key_RoleMgr); Reg.UnRegMenu(Key_UserMgr); end; procedure TAuthorityPlugin.RoleMgrClick(Sender: TObject); begin (SysService as IFormMgr).CreateForm(TfrmRoleMgr); end; procedure TAuthorityPlugin.UserMgrClick(Sender: TObject); begin (SysService as IFormMgr).CreateForm(TfrmUserMgr); end; initialization RegisterModuleClass(TAuthorityPlugin); finalization end.
unit uCefUIFunc; interface uses System.SysUtils, System.SyncObjs, System.Types, // uCEFInterfaces, uCEFTypes, uCEFMiscFunctions, uCEFConstants, uCEFChromium, // uCefScriptBase, uCefWebActionBase, uCefUtilFunc, uCefUtilType; const DIR_UP = 1; DIR_DOWN = -1; SCROLL_STEP_DEF = 100; WaitResultStr: array[TWaitResult] of string = ('wrSignaled', 'wrTimeout', 'wrAbandoned', 'wrError', 'wrIOCompletion'); function CefUISendRenderMessage(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const A: ICefProcessMessage): ICefListValue; function CefUIElementIdExists(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const AId: string): Boolean; overload; function CefUIElementIdExists(const AAction: TCefScriptBase; const AId: string): Boolean; overload; function CefUIElementExists(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const ATag, AId, AName, AClass, AAttrName, AAttrValueRegExpr, ATextRegExpr: string): ICefListValue; overload; function CefUIElementExists(const AAction: TCefScriptBase; const ATag, AId, AName, AClass, AAttrName, AAttrValueRegExpr, ATextRegExpr: string): ICefListValue; overload; function CefUIElementExists(const AAction: TCefScriptBase; const AElement: TElementParams): ICefListValue; overload; function CefUIGetElementsAttr(const AAction: TCefScriptBase; const AElement: TElementParams): ICefListValue; function CefUIElementSetValuaById(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const AId, AValue: string): Boolean; overload; function CefUIElementSetValuaById(const AAction: TCefScriptBase; const AId, AValue: string): Boolean; overload; function CefUIElementSetValuaByName(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const AName, AValue: string): Boolean; function CefUIElementSetAttrByName(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const AName, AAttr, AValue: string): Boolean; function CefUIGetWindowRect(const ABrowser: ICefBrowser; const AAbortEvent: TEvent): TRect; overload; function CefUIGetWindowRect(const AAction: TCefScriptBase): TRect; overload; function CefUIGetBodyRect(const ABrowser: ICefBrowser; const AAbortEvent: TEvent): TRect; function CefUIGetElementRect(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const AElem: TElementParams): TRect; overload; function CefUIGetElementRect(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const ATag, AId, AName, AClass, AAttrName, AAttrValueRegExpr, ATextRegExpr: string): TRect; overload; function CefUIGetElementRect(const AAction: TCefScriptBase; const AElem: TElementParams): TRect; overload; function CefUIScrollToElement(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const ATimeout, AStep: Integer; const ATag, AId, AName, AClass, AAttrName, AAttrValueRegExpr, ATextRegExpr: string; const ATry: Integer): Boolean; overload; function CefUIScrollToElement(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const ASpeed: TCefUISpeed; const ATag, AId, AName, AClass, AAttrName, AAttrValueRegExpr, ATextRegExpr: string): Boolean; overload; function CefUIScrollToElement(const AAction: TCefScriptBase; const ASpeed: TCefUISpeed; const ATag, AId, AName, AClass, AAttrName, AAttrValueRegExpr, ATextRegExpr: string): Boolean; overload; function CefUIScrollToElement(const AAction: TCefScriptBase; const ASpeed: TCefUISpeed; const AElement: TElementParams): Boolean; overload; function CefUIScrollToElement(const AAction: TCefScriptBase; const AElement: TElementParams): Boolean; overload; function CefUIMouseSetToPoint(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const AMousePos: PPoint; const AToPoint: TPoint; const ATimeout: Integer): Boolean; overload; function CefUIMouseSetToPoint(const AAction: TCefScriptBase; const AToPoint: TPoint; const ATimeout: Integer): Boolean; overload; function CefUIMouseMoveToElement(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; var APoint: TPoint; const ATimeout, AStep: Integer; const AToCenter: Boolean; const ATag, AId, AName, AClass, AAttrName, AAttrValueRegExpr, ATextRegExpr: string): Boolean; overload; function CefUIMouseMoveToElement(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; var APoint: TPoint; const ASpeed: TCefUISpeed; const AToCenter: Boolean; const ATag, AId, AName, AClass, AAttrName, AAttrValueRegExpr, ATextRegExpr: string): Boolean; overload; function CefUIMouseMoveToElement(const AAction: TCefScriptBase; const ASpeed: TCefUISpeed; const AToCenter: Boolean; const ATag, AId, AName, AClass, AAttrName, AAttrValueRegExpr, ATextRegExpr: string): Boolean; overload; function CefUIMouseMoveToElement(const AAction: TCefScriptBase; const ASpeed: TCefUISpeed; const AElement: TElementParams): Boolean; overload; function CefUIMouseMoveToElement(const AAction: TCefScriptBase; const AElement: TElementParams): Boolean; overload; procedure CefUIMouseClick(const ABrowser: ICefBrowser; const APoint: TPoint; const ATimeout: Integer; const AAbortEvent: TEvent); overload; procedure CefUIMouseClick(const AAction: TCefScriptBase); overload; procedure CefUIFocusClickAndCallbackAsync(const AFocus: Boolean; const ABrowser: ICefBrowser; const AArg: ICefListValue); procedure CefSendKeyEvent(const ABrowser: ICefBrowser; AKeyCode: Integer; const AAbordEvent: TEvent; const ATimeout: Integer); overload; procedure CefSendKeyEvent(const ABrowser: TChromium; AKeyCode: Integer); overload; procedure CefUIKeyPress(const ABrowser: ICefBrowser; const AArg: ICefListValue); procedure CefUIKeyPressAsync(const ABrowser: ICefBrowser; const AArg: ICefListValue); function CefUIDoScroll(const ACursor: TPoint; const AStep, ACount: Integer; const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const ATimeout: Integer): Boolean; function CefUIScroll(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const ACursor: TPoint; const ATimeout, AStep, ADir, ATry: Integer): Boolean; overload; function CefUIScroll(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const ACursor: TPoint; const ASpeed: TCefUISpeed; const ADir: Integer): Boolean; overload; function CefUIScroll(const AAction: TCefScriptBase; const ASpeed: TCefUISpeed; const ADir: Integer): Boolean; overload; function CefUIGetElementText(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const AElement: TElementParams): string; overload; function CefUIGetElementText(const AAction: TCefScriptBase; const AElement: TElementParams): string; overload; function CefUISetElementValue(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const AElement: TElementParams; const AValue: string): Boolean; overload; function CefUISetElementValue(const AAction: TCefScriptBase; const AElement: TElementParams; const AValue: string): Boolean; overload; function CefUISetSelectValue(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const AElement: TElementParams; const AValue: string): Boolean; overload; function CefUISetSelectValue(const AAction: TCefScriptBase; const AElement: TElementParams; const AValue: string): Boolean; overload; function CefUITypeText(const AAction: TCefScriptBase; const AText: string; const AElement: TElementParams): Boolean; function CefUIGetElementAttrValue(const AAction: TCefScriptBase; const AElement: TElementParams; const AAttrName: string): string; function CefUIGetElementOuterHtml(const AAction: TCefScriptBase; const AElement: TElementParams): string; function CefUIGetElementInnerText(const AAction: TCefScriptBase; const AElement: TElementParams): string; function CefUIGetElementAsMarkup(const AAction: TCefScriptBase; const AElement: TElementParams): string; implementation //{$DEFINE LOG_XY} //{$DEFINE MOUSE_CURSOR} uses {$IFDEF LOG_XY} uMainForm, {$ENDIF} // Winapi.Windows, System.Math, Vcl.Forms, // uCEFApplication, // uGlobalFunctions, // uCefUtilConst, uCefWaitEventList, uCefUiSendEventThread; const CLICK_PAUSE_DEF = 0; // cef80 set 0, иначе не нажимается function CefUISendRenderMessage(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const A: ICefProcessMessage): ICefListValue; var event: TCefWaitEventItem; args: ICefListValue; res: TWaitResult; fired: THandleObject; firedS: string; begin event := CefWaitEventAdd(); try args := A.ArgumentList; args.SetInt(IDX_EVENT, event.ID); CefLog('uifunc', 111, 1, Format('msgSend to render bid:%d thrd:%d eid:%d tick:%d args:%s', [ABrowser.Identifier, GetCurrentThreadId, event.ID, event.Tick, CefListValueToJsonStr(args)])); ABrowser.MainFrame.SendProcessMessage(PID_RENDERER, A); fired := nil; res := SleepEvents(event.Event, AAbortEvent, CEF_EVENT_WAIT_TIMEOUT, fired); firedS := '?'; if fired = AAbortEvent then firedS := 'abortEvent' else if fired = event.Event then firedS := 'waitEvent'; CefLog('uifunc', 121, 1, Format('event %s %s bid:%d thrd:%d eid:%d time:%d args:%s', [WaitResultStr[res], firedS, ABrowser.Identifier, GetCurrentThreadId, event.ID, event.TickDif, CefListValueToJsonStr(event.Res)])); if res = wrSignaled then begin if fired = event.Event then begin Exit(event.Res) end else if (AAbortEvent <> nil) and (fired = AAbortEvent) then begin Exit(nil) end else begin raise ECefError.Create('CefUISendRenderMessage() unknow event signaled ' + fired.ClassName) end; end else begin raise ECefRenderError.CreateFmt('render wait error %s %s bid:%d time:%d', [WaitResultStr[res], firedS, ABrowser.Identifier, event.TickDif]) end; finally CefWaitEventDelete(event) end; end; function CefUIElementIdExists(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const AId: string): Boolean; var msg: ICefProcessMessage; arg, res: ICefListValue; begin msg := CefAppMessageType(VAL_TEST_ID_EXISTS, arg); arg.SetString(IDX_ID, AId); res := CefUISendRenderMessage(ABrowser, AAbortEvent, msg); if Assigned(res) then Result := res.GetBool(IDX_RESULT) else Result := False end; function CefUIElementIdExists(const AAction: TCefScriptBase; const AId: string): Boolean; begin Result := CefUIElementIdExists(AAction.Chromium.Browser, AAction.AbortEvent, AId) end; function CefUIElementExists(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const ATag, AId, AName, AClass, AAttrName, AAttrValueRegExpr, ATextRegExpr: string): ICefListValue; var msg: ICefProcessMessage; arg, res: ICefListValue; begin msg := CefAppMessageType(VAL_TEST_ELEMENT_EXISTS, arg); arg.SetString(IDX_TAG, ATag); arg.SetString(IDX_ID, AId); arg.SetString(IDX_NAME, AName); arg.SetString(IDX_CLASS, AClass); arg.SetString(IDX_ATTR, AAttrName); arg.SetString(IDX_VALUE, AAttrValueRegExpr); arg.SetString(IDX_TEXT, ATextRegExpr); res := CefUISendRenderMessage(ABrowser, AAbortEvent, msg); if Assigned(res) then begin if res.GetType(IDX_RESULT) = VTYPE_LIST then Exit(res.GetList(IDX_RESULT).Copy()) end; Result := nil end; function CefUIElementExists(const AAction: TCefScriptBase; const ATag, AId, AName, AClass, AAttrName, AAttrValueRegExpr, ATextRegExpr: string): ICefListValue; begin Result := CefUIElementExists(AAction.Chromium.Browser, AAction.AbortEvent, ATag, AId, AName, AClass, AAttrName, AAttrValueRegExpr, ATextRegExpr) end; function CefUIElementExists(const AAction: TCefScriptBase; const AElement: TElementParams): ICefListValue; begin Result := CefUIElementExists(AAction, AElement.Tag, AElement.Id, AElement.Name, AElement.Class_, AElement.AttrName, AElement.AttrValue, AElement.Text) end; function CefUIElementSetValuaById(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const AId, AValue: string): Boolean; var msg: ICefProcessMessage; arg, res: ICefListValue; begin msg := CefAppMessageType(VAL_SET_VALUE_BY_ID, arg); arg.SetString(IDX_ID, AID); arg.SetString(IDX_VALUE, AValue); res := CefUISendRenderMessage(ABrowser, AAbortEvent, msg); if Assigned(res) then Result := res.GetBool(IDX_RESULT) else Result := False end; function CefUIElementSetValuaById(const AAction: TCefScriptBase; const AId, AValue: string): Boolean; begin Result := CefUIElementSetValuaById(AAction.Chromium.Browser, AAction.AbortEvent, AId, AValue) end; function CefUIElementSetValuaByName(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const AName, AValue: string): Boolean; var msg: ICefProcessMessage; arg, res: ICefListValue; begin msg := CefAppMessageType(VAL_SET_VALUE_BY_NAME, arg); arg.SetString(IDX_NAME, AName); arg.SetString(IDX_VALUE, AValue); res := CefUISendRenderMessage(ABrowser, AAbortEvent, msg); if Assigned(res) then Result := res.GetBool(IDX_RESULT) else Result := False end; function CefUIElementSetAttrByName(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const AName, AAttr, AValue: string): Boolean; var msg: ICefProcessMessage; arg, res: ICefListValue; begin msg := CefAppMessageType(VAL_SET_ATTR_BY_NAME, arg); arg.SetString(IDX_NAME, AName); arg.SetString(IDX_ATTR, AAttr); arg.SetString(IDX_VALUE, AValue); res := CefUISendRenderMessage(ABrowser, AAbortEvent, msg); if Assigned(res) then Result := res.GetBool(IDX_RESULT) else Result := False end; function CefUISetElementValue(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const AElement: TElementParams; const AValue: string): Boolean; var msg: ICefProcessMessage; arg, res: ICefListValue; begin msg := CefAppMessageType(VAL_SET_ELEMENT_VALUE, arg); AElement.SaveToCefListValue(arg); arg.SetString(IDX_VALUE2, AValue); res := CefUISendRenderMessage(ABrowser, AAbortEvent, msg); if Assigned(res) then Result := res.GetBool(IDX_RESULT) else Result := False end; function CefUISetElementValue(const AAction: TCefScriptBase; const AElement: TElementParams; const AValue: string): Boolean; begin Result := CefUISetElementValue(AAction.Chromium.Browser, AAction.AbortEvent, AElement, AValue) end; function ArgsToRect(const A: ICefListValue): TRect; begin Result.Left := A.GetInt(IDX_LEFT); Result.Right := A.GetInt(IDX_RIGHT); Result.Top := A.GetInt(IDX_TOP); Result.Bottom := A.GetInt(IDX_BOTTOM); end; function CefUIGetWindowRect(const ABrowser: ICefBrowser; const AAbortEvent: TEvent): TRect; var msg: ICefProcessMessage; arg, res: ICefListValue; begin msg := CefAppMessageType(VAL_GET_WINDOW_RECT, arg); res := CefUISendRenderMessage(ABrowser, AAbortEvent, msg); if Assigned(res) then begin Result := ArgsToRect(res); end else Result := TRect.Empty end; function CefUIGetWindowRect(const AAction: TCefScriptBase): TRect; begin Result := CefUIGetWindowRect(AAction.Chromium.Browser, AAction.AbortEvent) end; function CefUIGetBodyRect(const ABrowser: ICefBrowser; const AAbortEvent: TEvent): TRect; var msg: ICefProcessMessage; arg, res: ICefListValue; begin msg := CefAppMessageType(VAL_GET_BIDY_RECT, arg); res := CefUISendRenderMessage(ABrowser, AAbortEvent, msg); if Assigned(res) then begin Result := ArgsToRect(res); end else Result := TRect.Empty end; function RectToDevice(const A: TRect): TRect; var f: Double; begin f := GlobalCEFApp.DeviceScaleFactor; if f <> 1 then begin Result.Left := LogicalToDevice(A.Left, f); Result.Top := LogicalToDevice(A.Top, f); Result.Right := LogicalToDevice(A.Right, f); Result.Bottom := LogicalToDevice(A.Bottom, f); end else begin Result := A; end; end; function CefUIGetElementRect(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const AElem: TElementParams): TRect; var msg: ICefProcessMessage; arg, res: ICefListValue; begin msg := CefAppMessageTypeElem(VAL_GET_ELEMENT_RECT, AElem, arg); res := CefUISendRenderMessage(ABrowser, AAbortEvent, msg); if Assigned(res) then begin // Result := RectToDevice(ArgsToRect(res)); Result := ArgsToRect(res); end else Result := TRect.Empty end; function CefUIGetElementRect(const AAction: TCefScriptBase; const AElem: TElementParams): TRect; begin Result := CefUIGetElementRect(AAction.Chromium.Browser, AAction.AbortEvent, AElem) end; function CefUIGetElementRect(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const ATag, AId, AName, AClass, AAttrName, AAttrValueRegExpr, ATextRegExpr: string): TRect; begin Result := CefUIGetElementRect(ABrowser, AAbortEvent, ElemFilt(ATag, AId, AName, AClass, AAttrName, AAttrValueRegExpr, ATextRegExpr)) end; function CefUIDoScroll(const ACursor: TPoint; const AStep, ACount: Integer; const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const ATimeout: Integer): Boolean; var mouseEvent: TCefMouseEvent; j: Integer; begin if ACount < 1 then Exit(True); mouseEvent.x := ACursor.X; mouseEvent.y := ACursor.Y; mouseEvent.modifiers := EVENTFLAG_NONE; for j := 1 to Acount do begin ABrowser.Host.SendMouseWheelEvent(@mouseEvent, 0, AStep); if MainThreadID = GetCurrentThreadId then begin Application.ProcessMessages; Sleep(ATimeout) end else begin if Assigned(AAbortEvent) then if SleepEvents(AAbortEvent, nil, ATimeout) <> wrTimeout then Exit(False) end; end; Result := not Assigned(AAbortEvent) or (SleepEvents(AAbortEvent, nil, SCROLL_WAIT) = wrTimeout) end; function CefUIScrollToElement(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const ATimeout, AStep: Integer; const ATag, AId, AName, AClass, AAttrName, AAttrValueRegExpr, ATextRegExpr: string; const ATry: Integer): Boolean; const PADDING = 50; var elem, window: TRect; dif, step, count: Integer; begin if ATry >= 9 then Exit(True); window := CefUIGetWindowRect(ABrowser, AAbortEvent); if window.IsEmpty then Exit(False); elem := CefUIGetElementRect(ABrowser, AAbortEvent, ATag, AId, AName, AClass, AAttrName, AAttrValueRegExpr, ATextRegExpr); if elem.IsEmpty then Exit(False); //ABrowser.Host.SendMouseMoveEvent(nil, True); step := Abs(AStep); // to up if (elem.Top - PADDING) < 0 then begin dif := Abs(elem.Top - PADDING); count := Round(dif / step); end else //down if (elem.Bottom + PADDING) > window.Height then begin dif := (elem.Bottom + PADDING) - window.Height; count := Round(dif / step); step := -1 * step end else begin Exit(True) end; Result := CefUIDoScroll(TPoint.Zero, step, count, ABrowser, AAbortEvent, ATimeout); if Result then Result := CefUIScrollToElement(ABrowser, AAbortEvent, ATimeout, AStep, ATag, AId, AName, AClass, AAttrName, AAttrValueRegExpr, ATextRegExpr, ATry + 1) end; function CefUIScrollToElement(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const ASpeed: TCefUISpeed; const ATag, AId, AName, AClass, AAttrName, AAttrValueRegExpr, ATextRegExpr: string): Boolean; var time: Integer; begin time := SpeedToPause(ASpeed); Result := CefUIScrollToElement(ABrowser, AAbortEvent, time, SCROLL_STEP_DEF, ATag, AId, AName, AClass, AAttrName, AAttrValueRegExpr, ATextRegExpr, 0) end; function CefUIScrollToElement(const AAction: TCefScriptBase; const ASpeed: TCefUISpeed; const ATag, AId, AName, AClass, AAttrName, AAttrValueRegExpr, ATextRegExpr: string): Boolean; begin Result := CefUIScrollToElement(AAction.Chromium.Browser, AAction.AbortEvent, ASpeed, ATag, AId, AName, AClass, AAttrName, AAttrValueRegExpr, ATextRegExpr) end; function CefUIScrollToElement(const AAction: TCefScriptBase; const ASpeed: TCefUISpeed; const AElement: TElementParams): Boolean; begin Result := (not AElement.IsEmpty) and CefUIScrollToElement(AAction, ASpeed, AElement.Tag, AElement.Id, AElement.Name, AElement.Class_, AElement.AttrName, AElement.AttrValue, AElement.Text) end; function CefUIScrollToElement(const AAction: TCefScriptBase; const AElement: TElementParams): Boolean; begin Result := CefUIScrollToElement(AAction, AAction.Controller.Speed, AElement.Tag, AElement.Id, AElement.Name, AElement.Class_, AElement.AttrName, AElement.AttrValue, AElement.Text) end; procedure CefUIMouseSetPointVisual(const ABrowser: ICefBrowser; AToPoint: TPoint); begin {$IFDEF MOUSE_CURSOR} ABrowser.MainFrame.ExecuteJavaScript('mymouse00 = document.getElementById(''mymouse00''); mymouse00.style.left = "'+IntToStr(AToPoint.X+2)+'px"; mymouse00.style.top = "'+IntToStr(AToPoint.Y+2)+'px";', '', 0); {$ENDIF} end; function CefUIMouseSetToPoint(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const AMousePos: PPoint; const AToPoint: TPoint; const ATimeout: Integer): Boolean; var mouseEvent: TCefMouseEvent; lpoint: TPoint; begin if Assigned(AMousePos) then begin AMousePos^.X := AToPoint.x; AMousePos^.Y := AToPoint.y; end; lpoint := AToPoint; DeviceToLogical(lpoint, GlobalCEFApp.DeviceScaleFactor); mouseEvent.x := lpoint.X; mouseEvent.y := lpoint.Y; mouseEvent.modifiers := EVENTFLAG_NONE; {$IFDEF LOG_XY}MainForm.Log.Warning('*set point: ' + lpoint.x.ToString + ':' + lpoint.y.ToString);{$ENDIF} ABrowser.Host.SendMouseMoveEvent(@mouseEvent, False); CefUIMouseSetPointVisual(ABrowser, lpoint); if ATimeout > 0 then begin if SleepEvents(AAbortEvent, nil, ATimeout) <> wrTimeout then Exit(False) end; Exit(True) end; function CefUIMouseSetToPoint(const AAction: TCefScriptBase; const AToPoint: TPoint; const ATimeout: Integer): Boolean; begin Result := CefUIMouseSetToPoint(AAction.Chromium.Browser, AAction.AbortEvent, @AAction.Controller.Cursor, AToPoint, ATimeout) end; function CefUIMouseMoveToElement(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; var APoint: TPoint; const ATimeout, AStep: Integer; const AToCenter: Boolean; const ATag, AId, AName, AClass, AAttrName, AAttrValueRegExpr, ATextRegExpr: string): Boolean; var elem: TRect; ElemCenter: TPoint; lx,ly: Integer; // xs,ys, xf,yf: Integer; stepCount: Integer; xb, yb: Boolean; xk, yk, len, xp, yp: Extended; begin elem := CefUIGetElementRect(ABrowser, AAbortEvent, ATag, AId, AName, AClass, AAttrName, AAttrValueRegExpr, ATextRegExpr); if elem.IsEmpty then Exit(False); ElemCenter := elem.CenterPoint; // направление True - назад xb := ElemCenter.X < APoint.X; yb := ElemCenter.y < APoint.y; // Первая точка прямой //xs := Min(ElemCenter.X, APoint.X); //ys := Min(ElemCenter.Y, APoint.Y); // Последняя точка прятой //xf := Max(ElemCenter.X, APoint.X); //yf := Max(ElemCenter.Y, APoint.Y); // длинная прямой по осям lx := abs(ElemCenter.X-APoint.X); ly := abs(ElemCenter.Y-APoint.Y); // длинна прямой len := Sqrt(IntPower(lx, 2) + IntPower(ly, 2)); // кол-во шагов stepCount := Round(len / AStep); if stepCount < 1 then stepCount := 1; // длина шага по прямой //step := len / stepCount; // длина шага по осям xk := lx / stepCount; yk := ly / stepCount; // если в обратную торону if xb then xk := -1 * xk; if yb then yk := -1 * yk; // текущее положение xp := APoint.X; yp := APoint.Y; while True do begin xp := xp + xk; yp := yp + yk; CefUIMouseSetToPoint(ABrowser, AAbortEvent, @APoint, TPoint.Create(Round(xp), Round(yp)), ATimeout); if Abs(ElemCenter.X - APoint.X) <= 2 then if Abs(ElemCenter.Y - APoint.Y) <= 2 then Exit(True); end; Exit(False); end; function CefUIMouseSetToElement(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; var APoint: TPoint; const ATimeout, AStep: Integer; const AToCenter: Boolean; const ATag, AId, AName, AClass, AAttrName, AAttrValueRegExpr, ATextRegExpr: string): Boolean; var elem: TRect; ElemCenter: TPoint; begin elem := CefUIGetElementRect(ABrowser, AAbortEvent, ATag, AId, AName, AClass, AAttrName, AAttrValueRegExpr, ATextRegExpr); if elem.IsEmpty then Exit(False); if AToCenter then ElemCenter := elem.CenterPoint else ElemCenter := TPoint.Create(elem.Left + 2, elem.Top + 2); CefUIMouseSetToPoint(ABrowser, AAbortEvent, @APoint, ElemCenter, ATimeout); if Abs(ElemCenter.X - APoint.X) <= 2 then if Abs(ElemCenter.Y - APoint.Y) <= 2 then Exit(True); Exit(False); end; function CefUIMouseMoveToElement(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; var APoint: TPoint; const ASpeed: TCefUISpeed; const AToCenter: Boolean; const ATag, AId, AName, AClass, AAttrName, AAttrValueRegExpr, ATextRegExpr: string): Boolean; var pause: Integer; begin pause := SpeedToPause(ASpeed); Result := CefUIMouseSetToElement(ABrowser, AAbortEvent, APoint, pause, 2, AToCenter, ATag, AId, AName, AClass, AAttrName, AAttrValueRegExpr, ATextRegExpr) end; function CefUIMouseMoveToElement(const AAction: TCefScriptBase; const ASpeed: TCefUISpeed; const AToCenter: Boolean; const ATag, AId, AName, AClass, AAttrName, AAttrValueRegExpr, ATextRegExpr: string): Boolean; begin Result := CefUIMouseMoveToElement(AAction.Chromium.Browser, AAction.AbortEvent, AAction.Controller.Cursor, ASpeed, AToCenter, ATag, AId, AName, AClass, AAttrName, AAttrValueRegExpr, ATextRegExpr) end; function CefUIMouseMoveToElement(const AAction: TCefScriptBase; const ASpeed: TCefUISpeed; const AElement: TElementParams): Boolean; begin Result := CefUIMouseMoveToElement(AAction, ASpeed, AElement.Center, AElement.Tag, AElement.Id, AElement.Name, AElement.Class_, AElement.AttrName, AElement.AttrValue, AElement.Text) end; function CefUIMouseMoveToElement(const AAction: TCefScriptBase; const AElement: TElementParams): Boolean; begin Result := CefUIMouseMoveToElement(AAction, AAction.Controller.Speed, AElement.Center, AElement.Tag, AElement.Id, AElement.Name, AElement.Class_, AElement.AttrName, AElement.AttrValue, AElement.Text) end; procedure CefUIMouseClick(const ABrowser: ICefBrowser; const APoint: TPoint; const ATimeout: Integer; const AAbortEvent: TEvent); var mouseEvent: TCefMouseEvent; lpoint: TPoint; begin lpoint := APoint; DeviceToLogical(lpoint, GlobalCEFApp.DeviceScaleFactor); mouseEvent.x := lpoint.X; mouseEvent.y := lpoint.Y; mouseEvent.modifiers := EVENTFLAG_NONE; {$IFDEF LOG_XY} MainForm.Log.Warning('*mouse_down: ' + lpoint.x.ToString + ':' + lpoint.y.ToString); {$ENDIF} ABrowser.Host.SendMouseClickEvent(@mouseEvent, MBT_LEFT, False, 1); if ATimeout > 0 then begin SleepEvents(AAbortEvent, nil, ATimeout); end; {$IFDEF LOG_XY} MainForm.Log.Warning('*mouse_up: ' + lpoint.x.ToString + ':' + lpoint.y.ToString); {$ENDIF} ABrowser.Host.SendMouseClickEvent(@mouseEvent, MBT_LEFT, True, 1); end; procedure CefUIMouseClick(const AAction: TCefScriptBase); begin CefUIMouseClick(AAction.Chromium.Browser, AAction.Controller.Cursor, CLICK_PAUSE_DEF, AAction.AbortEvent) end; type TClickTask = class(TCefSendEventTaskItem) private FFocus: Boolean; protected procedure Execute; override; public function SetFocus(const AFocus: Boolean): TClickTask; end; { TClickTask } function TClickTask.SetFocus(const AFocus: Boolean): TClickTask; begin FFocus := AFocus; Result := Self end; procedure TClickTask.Execute; var p: TPoint; x,y,id: Integer; begin x := FArgs.GetInt(IDX_CLICK_X); y := FArgs.GetInt(IDX_CLICK_Y); id := FArgs.GetInt(IDX_CLICK_CALLBACKID); p := TPoint.Create(x, y); CefUIMouseSetToPoint(FBrowser, FOwner.AbortEvent, nil, p, (CLICK_PAUSE_DEF div 10)+1); if not FOwner.IsAborted then begin if FFocus then begin {$IFDEF LOG_XY} MainForm.Log.Warning('*SendFocusEvent!'); {$ENDIF} // FBrowser.Host.SendFocusEvent(True); фокус переключает на окно - пока выключу end; CefUIMouseClick(FBrowser, p, CLICK_PAUSE_DEF, FOwner.AbortEvent); // if not FOwner.IsAborted then begin CefExecJsCallback(FBrowser, id); end; end; end; procedure CefUIFocusClickAndCallbackAsync(const AFocus: Boolean; const ABrowser: ICefBrowser; const AArg: ICefListValue); begin CefSendEventThreadTaskAdd(TClickTask.Create(ABrowser, AArg).SetFocus(AFocus)) end; procedure CefSendKeyEvent(const ABrowser: ICefBrowser; AKeyCode: Integer; const AAbordEvent: TEvent; const ATimeout: Integer); procedure sleep_(ms: Integer); begin if ms > 0 then if AAbordEvent = nil then Sleep(ms) else SleepEvents(AAbordEvent, nil, ms) end; var event: TCefKeyEvent; VkCode: Byte; scanCode: UINT; begin // AKeyCode := VK_ESCAPE; FillMemory(@event, SizeOf(event), 0); event.is_system_key := 0; event.modifiers := 0; event.focus_on_editable_field := ord(True); VkCode := LOBYTE(VkKeyScan(Char(AkeyCode))); scanCode := MapVirtualKey(VkCode, MAPVK_VK_TO_VSC); event.native_key_code := (scanCode shl 16) or // key scan code 1; // key repeat count event.windows_key_code := VkCode; {$IFDEF LOG_XY} {$ENDIF} event.kind := KEYEVENT_RAWKEYDOWN; {$IFDEF LOG_XY} MainForm.Log.Warning('*key_down: ' + VkCode.ToString); {$ENDIF} ABrowser.Host.SendKeyEvent(@event); sleep_(ATimeout div 2); event.windows_key_code := AKeyCode; event.kind := KEYEVENT_CHAR; {$IFDEF LOG_XY} MainForm.Log.Warning('*key_char: ' + VkCode.ToString); {$ENDIF} ABrowser.Host.SendKeyEvent(@event); sleep_(ATimeout); event.windows_key_code := VkCode; // bits 30 and 31 should be always 1 for WM_KEYUP event.native_key_code := event.native_key_code or Integer($C0000000); event.kind := KEYEVENT_KEYUP; {$IFDEF LOG_XY} MainForm.Log.Warning('*key_up: ' + VkCode.ToString); {$ENDIF} ABrowser.Host.SendKeyEvent(@event); end; procedure CefSendKeyEvent(const ABrowser: TChromium; AKeyCode: Integer); begin CefSendKeyEvent(ABrowser.Browser, AKeyCode, nil, CLICK_PAUSE_DEF) end; procedure CefUIKeyPress(const ABrowser: ICefBrowser; const AArg: ICefListValue); var key: Integer; begin key := AArg.GetInt(IDX_VALUE); CefSendKeyEvent(ABrowser, key, nil, CLICK_PAUSE_DEF) end; type TKeyboardTask = class(TCefSendEventTaskItem) procedure Execute; override; end; { TKeyboardTask } procedure TKeyboardTask.Execute; var key, id: Integer; begin id := FArgs.GetInt(IDX_KEY_CALLBACKID); key := FArgs.GetInt(IDX_KEY_CODE); CefSendKeyEvent(FBrowser, key, FOwner.AbortEvent, CLICK_PAUSE_DEF); if not FOwner.IsAborted then begin CefExecJsCallback(FBrowser, id); end; end; procedure CefUIKeyPressAsync(const ABrowser: ICefBrowser; const AArg: ICefListValue); begin CefSendEventThreadTaskAdd(TKeyboardTask.Create(ABrowser, AArg)); end; function CefUIScroll(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const ACursor: TPoint; const ATimeout, AStep, ADir, ATry: Integer): Boolean; var window, body: TRect; dir, step, count: Integer; begin if ATry >= 5 then Exit(True); body := CefUIGetBodyRect(ABrowser, AAbortEvent); if body.IsEmpty then Exit(False); window := CefUIGetWindowRect(ABrowser, AAbortEvent); if window.IsEmpty then Exit(False); step := Abs(AStep); dir := ADir; if dir = 0 then begin dir := IfElse(window.Top = 0, DIR_DOWN, DIR_UP) end; // DIR_UP if dir > 0 then begin count := window.Top div step; end else begin // DOWN count := (body.Height - window.Bottom) div step; step := -1 * step; end; Result := CefUIDoScroll(ACursor, step, count, ABrowser, AAbortEvent, ATimeout); if Result then Result := CefUIScroll(ABrowser, AAbortEvent, ACursor, ATimeout, AStep, dir, ATry+1) end; function CefUIScroll(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const ACursor: TPoint; const ASpeed: TCefUISpeed; const ADir: Integer): Boolean; begin Result := CefUIScroll(ABrowser, AAbortEvent, ACursor, SpeedToPause(ASpeed), SCROLL_STEP_DEF, ADir, 0) end; function CefUIScroll(const AAction: TCefScriptBase; const ASpeed: TCefUISpeed; const ADir: Integer): Boolean; begin Result := CefUIScroll(AAction.Chromium.Browser, AAction.AbortEvent, AAction.Controller.Cursor, ASpeed, ADir) end; function CefUIGetElementText(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const AElement: TElementParams): string; var msg: ICefProcessMessage; arg, res: ICefListValue; begin msg := CefAppMessageType(VAL_GET_ELEMENT_TEXT, arg); AElement.SaveToCefListValue(arg); res := CefUISendRenderMessage(ABrowser, AAbortEvent, msg); if Assigned(res) then begin Result := res.GetString(IDX_RESULT); Exit; end; Result := '' end; function CefUIGetElementText(const AAction: TCefScriptBase; const AElement: TElementParams): string; begin Result := CefUIGetElementText(AAction.Chromium.Browser, AAction.AbortEvent, AElement) end; function CefUISetSelectValue(const ABrowser: ICefBrowser; const AAbortEvent: TEvent; const AElement: TElementParams; const AValue: string): Boolean; var msg: ICefProcessMessage; arg, res: ICefListValue; begin msg := CefAppMessageTypeElem(VAL_SET_SELECT_VALUE, AElement, AValue, arg); res := CefUISendRenderMessage(ABrowser, AAbortEvent, msg); if Assigned(res) then Result := res.GetBool(IDX_RESULT) else Result := False end; function CefUISetSelectValue(const AAction: TCefScriptBase; const AElement: TElementParams; const AValue: string): Boolean; begin Result := CefUISetSelectValue(AAction.Chromium.Browser, AAction.AbortEvent, AElement, AValue) end; function CefUIGetElementsAttr(const AAction: TCefScriptBase; const AElement: TElementParams): ICefListValue; var msg: ICefProcessMessage; res: ICefListValue; begin msg := CefAppMessageTypeElem(VAL_GET_ELEMENTS_ATTR, AElement); res := CefUISendRenderMessage(AAction.Chromium.Browser, AAction.AbortEvent, msg); if Assigned(res) then if res.GetType(IDX_RESULT) = VTYPE_LIST then Exit(res.GetList(IDX_RESULT).Copy()); Result := nil end; function CefUITypeText(const AAction: TCefScriptBase; const AText: string; const AElement: TElementParams): Boolean; var br: TChromium; ch: Char; slp: Integer; begin br := AAction.Chromium; // br.SendFocusEvent(False); фокус переключает на окно - пока выключу if CefUIScrollToElement(AAction, AElement) then begin if CefUIMouseMoveToElement(AAction, AElement) then begin CefUIMouseClick(AAction); slp := AAction.Controller.Pause; for ch in AText do begin CefSendKeyEvent(br, Ord(ch)); if SleepEvents(AAction.AbortEvent, nil, slp) <> wrTimeout then Exit(False) end; Exit(True) end; end; Exit(False) end; function CefUIGetElementAttrValue(const AAction: TCefScriptBase; const AElement: TElementParams; const AAttrName: string): string; var res: ICefListValue; dic: ICefDictionaryValue; begin res := CefUIElementExists(AAction, AElement); if Assigned(res) then begin dic := res.GetDictionary(IDX_ATTR); if Assigned(dic) then begin Result := dic.GetString(AAttrName); Exit; end; end; Exit('') end; function CefUIGetElementResultString(const AVal: Integer; const AAction: TCefScriptBase; const AElement: TElementParams): string; var msg: ICefProcessMessage; arg, res: ICefListValue; begin msg := CefAppMessageType(AVal, arg); AElement.SaveToCefListValue(arg); res := CefUISendRenderMessage(AAction.Chromium.Browser, AAction.AbortEvent, msg); if Assigned(res) then begin if res.GetType(IDX_RESULT) = VTYPE_STRING then Exit(res.GetString(IDX_RESULT)) end; Result := '' end; function CefUIGetElementOuterHtml(const AAction: TCefScriptBase; const AElement: TElementParams): string; begin Result := CefUIGetElementResultString(VAL_OUTERHTML, AAction, AElement); end; function CefUIGetElementInnerText(const AAction: TCefScriptBase; const AElement: TElementParams): string; begin Result := CefUIGetElementResultString(VAL_INNERTEXT, AAction, AElement); end; function CefUIGetElementAsMarkup(const AAction: TCefScriptBase; const AElement: TElementParams): string; begin Result := CefUIGetElementResultString(VAL_ASMARKUP, AAction, AElement) end; end.
unit Frame.OrderEdit; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.Async, FireDAC.DApt, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, FireDAC.UI.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Phys, FireDAC.Phys.IB, FireDAC.Phys.IBDef, FireDAC.VCLUI.Wait, Vcl.StdCtrls, Vcl.Mask, Vcl.DBCtrls, Vcl.ExtCtrls, Vcl.ComCtrls, Wrapper.Vcl.DBDatePicker; type TFrameOrderEdit = class(TFrame) DataSource1: TDataSource; DataSource2: TDataSource; GridPanel1: TGridPanel; GroupBox1: TGroupBox; Label1: TLabel; Label2: TLabel; Label3: TLabel; DBEdit1: TDBEdit; DBEdit2: TDBEdit; DBLookupComboBox1: TDBLookupComboBox; GroupBox2: TGroupBox; GroupBox3: TGroupBox; Label7: TLabel; DBEdit7: TDBEdit; btnCalcFreight: TButton; DateTimePicker1: TDateTimePicker; grbxCommands: TGroupBox; btnClose: TButton; tmrReady: TTimer; CheckBox1: TCheckBox; CheckBox2: TCheckBox; DateTimePicker2: TDateTimePicker; CheckBox3: TCheckBox; DateTimePicker3: TDateTimePicker; btnEdit: TButton; btnPost: TButton; btnCancel: TButton; btnRefresh: TButton; procedure btnCancelClick(Sender: TObject); procedure btnCloseClick(Sender: TObject); procedure btnEditClick(Sender: TObject); procedure btnPostClick(Sender: TObject); procedure btnRefreshClick(Sender: TObject); procedure DataSource1DataChange(Sender: TObject; Field: TField); procedure FrameResize(Sender: TObject); procedure tmrReadyTimer(Sender: TObject); private OrderID: integer; // {{ Переключиться на UTF-8 }} - Przełącza zapisywanie plików PAS na UTF-8 // TODO: Usuń zalezność od FDConnection CurrentConnection: TFDConnection; isClosing: Boolean; OrderDateWrapper: TDBDatePickerWrapper; RequiredDateWrapper: TDBDatePickerWrapper; ShippedDateWrapper: TDBDatePickerWrapper; prevDataSetState: TDataSetState; procedure UpdateNavigationButtonsState; public { Public declarations } class procedure ShowFrame(AContainer: TWinControl; AConnection: TFDConnection; OrderID: integer); end; implementation {$R *.dfm} procedure TFrameOrderEdit.btnCancelClick(Sender: TObject); begin DataSource1.DataSet.Cancel; end; procedure TFrameOrderEdit.btnCloseClick(Sender: TObject); begin isClosing := True; end; procedure TFrameOrderEdit.btnEditClick(Sender: TObject); begin DataSource1.DataSet.Edit; end; procedure TFrameOrderEdit.btnPostClick(Sender: TObject); begin DataSource1.DataSet.Post; end; procedure TFrameOrderEdit.btnRefreshClick(Sender: TObject); begin DataSource1.DataSet.Refresh; end; class procedure TFrameOrderEdit.ShowFrame(AContainer: TWinControl; AConnection: TFDConnection; OrderID: integer); var frm: TFrameOrderEdit; begin frm := TFrameOrderEdit.Create(AContainer); frm.OrderID := OrderID; frm.CurrentConnection := AConnection; frm.AlignWithMargins := True; frm.Align := alClient; frm.Parent := AContainer; repeat Application.HandleMessage; until frm.isClosing or Application.Terminated; frm.Free; end; procedure TFrameOrderEdit.DataSource1DataChange(Sender: TObject; Field: TField); begin if prevDataSetState <> DataSource1.DataSet.State then begin UpdateNavigationButtonsState; prevDataSetState := DataSource1.DataSet.State; end; if Assigned(OrderDateWrapper) then OrderDateWrapper.DataSourceOnChange(Sender, Field); if Assigned(RequiredDateWrapper) then RequiredDateWrapper.DataSourceOnChange(Sender, Field); if Assigned(ShippedDateWrapper) then ShippedDateWrapper.DataSourceOnChange(Sender, Field); end; procedure TFrameOrderEdit.FrameResize(Sender: TObject); begin if (self.ClientWidth > 800) and (GridPanel1.Align = alTop) then begin GridPanel1.Align := alNone; GridPanel1.Width := 800; GridPanel1.Left := GridPanel1.Margins.Left; GridPanel1.Width := ClientWidth - GridPanel1.Margins.Left - GridPanel1.Margins.Right; GridPanel1.Anchors := [akTop]; end else if (self.ClientWidth < 800) and (GridPanel1.Align = alNone) then begin GridPanel1.Align := alTop; GridPanel1.Anchors := [akLeft,akTop]; end; end; procedure TFrameOrderEdit.tmrReadyTimer(Sender: TObject); var // TODO: Usuń zalezność od TFDQuery (powinien wystarczyć TDataSet) fdq1: TFDQuery; fdq2: TFDQuery; begin tmrReady.Enabled := False; // -------------------------------------------------------------- GridPanel1.AlignWithMargins := True; GridPanel1.Align := alTop; // -------------------------------------------------------------- // Zbuduj, podepnij i otwórz query dla bierzącego zamówienia (OrderID) fdq1 := TFDQuery.Create(self); fdq1.Connection := CurrentConnection; fdq1.Open('select OrderID,CustomerID, EmployeeID, OrderDate, ' + 'RequiredDate, ShippedDate, Freight from {id Orders} where ' + 'OrderID = :OrderID', [OrderID]); // -------------------------------------------------------------- // Zbuduj, podepnij i otwórz query dla listy pracowników fdq2 := TFDQuery.Create(self); fdq2.Connection := CurrentConnection; fdq2.Open('select EmployeeID, FirstName||'' ''||LastName||'' ' + ' (ID:''||EmployeeID||'')'' as EmployeeName from {id Employees} ' + ' order by EmployeeID'); // -------------------------------------------------------------- DataSource1.DataSet := fdq1; DataSource2.DataSet := fdq2; // -------------------------------------------------------------- // Konfiguracja OrderDateWrapper: TDBDatePickerWrapper OrderDateWrapper := TDBDatePickerWrapper.Create(DateTimePicker1); OrderDateWrapper.SetDBDatePickerControls(CheckBox1, DateTimePicker1); OrderDateWrapper.ConnectToDataSource(DataSource1, 'OrderDate'); RequiredDateWrapper := TDBDatePickerWrapper.Create(DateTimePicker2); RequiredDateWrapper.SetDBDatePickerControls(CheckBox2, DateTimePicker2); RequiredDateWrapper.ConnectToDataSource(DataSource1, 'RequiredDate'); ShippedDateWrapper := TDBDatePickerWrapper.Create(DateTimePicker2); ShippedDateWrapper.SetDBDatePickerControls(CheckBox3, DateTimePicker3); ShippedDateWrapper.ConnectToDataSource(DataSource1, 'ShippedDate'); end; procedure TFrameOrderEdit.UpdateNavigationButtonsState; var State: TDataSetState; begin State := DataSource1.DataSet.State; if State = dsBrowse then begin btnEdit.Enabled := True; btnPost.Enabled := False; btnCancel.Enabled := False; btnRefresh.Enabled := True; end else if State in [dsEdit, dsInsert, dsSetKey] then begin btnEdit.Enabled := False; btnPost.Enabled := True; btnCancel.Enabled := True; btnRefresh.Enabled := True; end else begin btnEdit.Enabled := False; btnPost.Enabled := False; btnCancel.Enabled := False; btnRefresh.Enabled := False; end; end; end.
unit NewsEditForm; interface uses Forms, PluginManagerIntf, cxLookAndFeelPainters, cxMemo, cxDBEdit, cxDropDownEdit, cxLookupEdit, cxDBLookupEdit, cxDBLookupComboBox, cxCheckBox, cxSpinEdit, cxTimeEdit, cxMaskEdit, cxCalendar, Controls, StdCtrls, cxControls, cxContainer, cxEdit, cxTextEdit, Classes, ActnList, cxButtons, ExtCtrls; type TEditForm = class(TForm) Panel1: TPanel; btnOK: TcxButton; Cancel: TcxButton; Panel2: TPanel; ActionList: TActionList; OK: TAction; Action2: TAction; title: TcxDBTextEdit; Label1: TLabel; Label2: TLabel; creation_date: TcxDBDateEdit; Label3: TLabel; creation_time: TcxDBTimeEdit; _published: TcxDBCheckBox; category_id: TcxDBLookupComboBox; Label4: TLabel; Label5: TLabel; author: TcxDBTextEdit; text: TcxDBMemo; Label6: TLabel; btnEditText: TcxButton; Label7: TLabel; announcement: TcxDBMemo; Label8: TLabel; name: TcxDBMaskEdit; procedure OKExecute(Sender: TObject); procedure btnEditTextClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure titlePropertiesEditValueChanged(Sender: TObject); private FPluginManager: IPluginManager; FPath: String; procedure SetPluginManager(const Value: IPluginManager); public property PluginManager: IPluginManager read FPluginManager write SetPluginManager; end; function GetEditForm(APluginManager: IPluginManager): Integer; implementation uses NewsDM, HTMLEditorIntf, SysUtils, DB, DBClient, DeviumLib; {$R *.dfm} function GetEditForm; var Form: TEditForm; begin Form := TEditForm.Create(Application); try Form.PluginManager := APluginManager; Result := Form.ShowModal; finally Form.Free; end; end; procedure TEditForm.OKExecute(Sender: TObject); begin btnOK.SetFocus; ModalResult := mrOK; end; procedure TEditForm.SetPluginManager(const Value: IPluginManager); begin FPluginManager := Value; end; procedure TEditForm.btnEditTextClick(Sender: TObject); var Editor: IHTMLEditor; s: String; RemotePath, LocalPath: String; FilesList: TStringList; begin if FPluginManager.GetPlugin(IHTMLEditor, Editor) then begin s := text.Text; //---------------- LocalPath := DM.GetLocalPath(DM.News); RemotePath := DM.GetRemotePath(LocalPath); //---------------- Editor.RemotePath := RemotePath; Editor.LocalPath := LocalPath; FilesList := TStringList.Create; try Editor.FilesList := FilesList; if Editor.Execute(s) then begin text.DataBinding.Field.Value := s; if Trim(DM.News.FieldValues['images']) <> Trim(FilesList.Text) then DM.News.FieldValues['images'] := Trim(FilesList.Text); end; finally FilesList.Free; end; end; end; procedure TEditForm.FormCreate(Sender: TObject); begin FPath := ExtractFilePath(ParamStr(0)); end; procedure TEditForm.titlePropertiesEditValueChanged(Sender: TObject); begin name.DataBinding.Field.Value := TransLiterStr(Title.Text); end; end.
{Ä Fido Pascal Conference ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ PASCAL Ä Msg : 423 of 533 From : Daniel Schlenzig 2:241/5400.10 23 Apr 93 14:42 To : Stephen Cheok Subj : STARFIELD ÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄÄ Hi Stephen, > Hmm.. does anyone have an example of a starfield routine in > Turbo Pascal.. or can be used with Turbo Pascal.. using the > ASSEMBLER.. I want to try to make one.. but I need some help with > it. Thanx... Here is one: } program stars; const maxstars = 50; var star : array[0..maxstars] of word; speed : array[0..maxstars] of byte; i : word; procedure create; begin for i := 0 to maxstars do begin star[i] := random(320) + random(200) * 320; speed[i] := random(3) + 1; if mem[$a000:star[i]] = 0 then mem[$a000:star[i]] := 100; end; end; Procedure moveit; assembler; asm xor bp,bp mov ax,0a000h mov es,ax lea bx,star lea si,speed mov cx,320 @l1: mov di,[bx] mov al,es:[di] cmp al,100 jne @j1 xor al,al stosb @j1: mov al,[si] xor ah,ah add [bx],ax mov ax,bx xor dx,dx div cx mul cx mov dx,bx sub dx,ax cmp dx,319 jle @j3 sub [bx],cx @j3: mov di,[bx] mov al,es:[di] or al,al jnz @j2 mov al,100 stosb @j2: add bx,2 inc si inc bp cmp bp,maxstars jle @l1 end; begin asm mov ax,13h int 10h call create @l1: mov dx,3dah @r1: in al,dx test al,8 je @r1 call moveit in al,60h cmp al,1 jne @l1; end; end. Well, it can be done faster, but it' s enough to learn from :-) cu Daniel --- GEcho 1.00 * Origin: Don't panic! (2:241/5400.10)
unit HJYLoggers; interface uses Windows, SysUtils, Classes, HJYSyncObjs; type TSilentFileStream = class(TFileStream) private FHandleValid: Boolean; public constructor Create(const FileName: string; Mode: Word); overload; constructor Create(const FileName: string); overload; property HandleValid: Boolean read FHandleValid; end; THJYCustomLogger = class(TObject) private FCS: THJYCriticalSection; FMaxSize: Int64; protected FFileName: string; procedure DoLog(const Text: string); virtual; abstract; public constructor Create(const AFileName: string); destructor Destroy; override; procedure Log(const Msg: string; const Name: string = ''; const Sep: string = ''); property MaxSize: Int64 read FMaxSize write FMaxSize; end; THJYRealtimeLogger = class(THJYCustomLogger) protected procedure DoLog(const Text: string); override; end; THJYBufferedLogger = class(THJYCustomLogger) private FBuffer: string; FLoaded: Boolean; procedure LoadFromFile; procedure SaveToFile; protected procedure DoLog(const Text: string); override; function BufferDecode(const Raw: RawByteString): UTF8String; virtual; function BufferEncode(const Buffer: UTF8String): RawByteString; virtual; public destructor Destroy; override; procedure UpdateFile; end; procedure RealtimeLog(const AMsg: string; const AName: string = ''; const ASep: string = ''); procedure BufferedLog(const AMsg: string; const AName: string = ''; const ASep: string = ''); implementation const soFromBeginning = 0; soFromCurrent = 1; soFromEnd = 2; CDefaultSep = '=========================================='; CHeaderWithNameFmt = '[%s] %s'; CBodyFmt = '%s'#13#10'%s'#13#10'%s'#13#10; function GetLogFileName(APrefix: string = ''): string; var lvPath: string; begin lvPath := ExtractFilePath(ParamStr(0)) + 'Logs\'; if not DirectoryExists(lvPath) then ForceDirectories(lvPath); Result := lvPath + APrefix + FormatDateTime('YYYYMM', Now) + '.log'; end; procedure RealtimeLog(const AMsg: string; const AName: string = ''; const ASep: string = ''); var lLogger: THJYRealtimeLogger; lvFileName: string; begin lvFileName := GetLogFileName('RealtimeLog'); lLogger := THJYRealtimeLogger.Create(lvFileName); try lLogger.Log(AMsg, AName, ASep); finally lLogger.Free; end; end; procedure BufferedLog(const AMsg: string; const AName: string = ''; const ASep: string = ''); var lLogger: THJYBufferedLogger; lvFileName: string; begin lvFileName := GetLogFileName('BufferedLog'); lLogger := THJYBufferedLogger.Create(lvFileName); try lLogger.Log(AMsg, AName, ASep); finally lLogger.Free; end; end; { TSilentFileStream } constructor TSilentFileStream.Create(const FileName: string; Mode: Word); begin if Mode = fmCreate then PInteger(@Handle)^ := FileCreate(FileName) else PInteger(@Handle)^ := FileOpen(FileName, Mode); FHandleValid := Cardinal(Handle) <> INVALID_HANDLE_VALUE; end; constructor TSilentFileStream.Create(const FileName: string); begin if FileExists(FileName) then Create(FileName, fmOpenReadWrite) else Create(FileName, fmCreate); end; { THJYCustomLogger } constructor THJYCustomLogger.Create(const AFileName: string); begin FCS := THJYCriticalSection.Create; FFileName := AFileName; end; destructor THJYCustomLogger.Destroy; begin FCS.Free; inherited; end; procedure THJYCustomLogger.Log(const Msg: string; const Name: string = ''; const Sep: string = ''); var Text: string; begin Text := DateTimeToStr(Now); if Name <> '' then Text := Format(CHeaderWithNameFmt, [Name, Text]); if Sep = '' then Text := Format(CBodyFmt, [Text, Msg, CDefaultSep]) else Text := Format(CBodyFmt, [Text, Msg, Sep]); FCS.Enter; try DoLog(Text); finally FCS.Leave; end; end; { THJYRealtimeLogger } procedure THJYRealtimeLogger.DoLog(const Text: string); var LText: UTF8String; begin with TSilentFileStream.Create(FFileName) do begin try if HandleValid then begin if (Seek(0, soFromEnd) > MaxSize) and (MaxSize > 0) then Size := 0; LText := UTF8Encode(Text); Write(Pointer(LText)^, Length(LText)); end; finally Free; end; end; end; { THJYBufferedLogger } destructor THJYBufferedLogger.Destroy; begin if FLoaded then SaveToFile; inherited; end; function THJYBufferedLogger.BufferDecode(const Raw: RawByteString): UTF8String; begin Result := UTF8String(Raw); end; function THJYBufferedLogger.BufferEncode(const Buffer: UTF8String): RawByteString; begin Result := RawByteString(Buffer); end; procedure THJYBufferedLogger.DoLog(const Text: string); begin if not FLoaded then LoadFromFile; if (MaxSize > 0) and (Length(FBuffer) > MaxSize) then FBuffer := ''; FBuffer := FBuffer + Text; end; procedure THJYBufferedLogger.LoadFromFile; var LText: RawByteString; begin with TSilentFileStream.Create(FFileName) do begin try if HandleValid then begin SetLength(LText, Size); Read(Pointer(LText)^, Length(LText)); end else LText := ''; finally Free; end; end; FBuffer := UTF8ToString(BufferDecode(LText)); FLoaded := True; end; procedure THJYBufferedLogger.SaveToFile; var LText: RawByteString; begin LText := BufferEncode(UTF8Encode(FBuffer)); with TSilentFileStream.Create(FFileName) do begin try if HandleValid then begin Size := Length(LText); Seek(0, soFromBeginning); Write(Pointer(LText)^, Length(LText)); end; finally Free; end; end; end; procedure THJYBufferedLogger.UpdateFile; begin FCS.Enter; try if not FLoaded then LoadFromFile; SaveToFile; finally FCS.Leave; end; end; end.
program SortProject; uses DateUnit; procedure ShellSort(var d: DateToSort; var n, rearr, compar: integer); var MC: array[1..9] of integer; m, i, j: integer; buff: Date; begin MC[9] := 1; MC[8] := 4; MC[7] := 10; //Marcin Ciura's gap sequence MC[6] := 23; MC[5] := 57; MC[4] := 132; //is believed to be the fastest MC[3] := 301; MC[2] := 701; MC[1] := 1750; rearr := 0; compar := 0; for m := 1 to 9 do begin if MC[m] < n then for i := MC[m] to n do begin buff := d[i]; j := i; while (j > MC[m]) AND DateIsBigger(d[j - MC[m]], buff, compar) do begin d[j] := d[j - MC[m]]; j := j - MC[m]; inc(rearr); end; d[j] := buff; end; end; end; procedure BinaryInsertionSort(var d: DateToSort; var n, rearr, compar: integer); var i,j,lf,rg,mid: integer; begin compar:=0; rearr:=0; for i:=2 to n do begin lf:=1; rg:=i; while lf<rg do begin mid:=lf+(rg-lf) div 2; if DateIsBigger(d[mid],d[i],compar) then rg:=mid else lf:=mid+1; end; if (i<>lf) then Insert(d,i,lf,rearr); end; end; var outputShell, outputBinar: text; d: DateToSort; n: integer; //actual length dataType: array[1..5] of string; //'Inc','Dec','IncDec','Random1','Random2' rearrShell, comparShell, rearrBinar, comparBinar: array[1..5] of integer; //vectors of rearrangements and comparissons i, j, k: integer; begin dataType[1] := 'Inc'; dataType[2] := 'Dec'; dataType[3] := 'IncDec'; dataType[4] := 'Random1'; dataType[5] := 'Random2'; n := 1; CreateDir(testDirName); GenerateTestData(); assign(outputShell, 'OutputShell.txt'); rewrite(outputShell); assign(outputBinar, 'OutputBinar.txt'); rewrite(outputBinar); writeln(outputShell,' Shell Sort'); writeln(outputShell,'----------------------------------------------------------------------'); writeln(outputShell,'| n | Parameter | Sequence | Average |'); writeln(outputShell,'| | | Inc Dec InDe Rnd1 Rnd2 | value |'); writeln(outputShell,'----------------------------------------------------------------------'); writeln(outputBinar,' Binary Incertion Sort'); writeln(outputBinar,'----------------------------------------------------------------------'); writeln(outputBinar,'| n | Parameter | Sequence | Average |'); writeln(outputBinar,'| | | Inc Dec InDe Rnd1 Rnd2 | value |'); writeln(outputBinar,'----------------------------------------------------------------------'); for i := 1 to 3 do begin n := n * 10; for j := 1 to 5 do begin DateInput(d, basename + n + dataType[j], n); ShellSort(d,n,rearrShell[j],comparShell[j]); //DateOutput(outputDirName+'/ShOut'+n+dataType[j]+'.txt',d,n); DateInput(d, basename + n + dataType[j], n); BinaryInsertionSort(d,n,rearrBinar[j],comparBinar[j]); //DateOutput(outputDirName+'/BiOut'+n+dataType[j]+'.txt',d,n); end; writeln(outputShell,'|',n:5,'| Shifts |',rearrShell[1]:7,rearrShell[2]:7,rearrShell[3]:7,rearrShell[4]:7,rearrShell[5]:7,' |', ((rearrShell[1]+rearrShell[2]+rearrShell[3]+rearrShell[4]+rearrShell[5]) div 5):9,' |'); writeln(outputShell,'| | Comparisons |',comparShell[1]:7,comparShell[2]:7,comparShell[3]:7,comparShell[4]:7,comparShell[5]:7,' |', ((comparShell[1]+comparShell[2]+comparShell[3]+comparShell[4]+comparShell[5]) div 5):9,' |'); writeln(outputShell,'----------------------------------------------------------------------'); writeln(outputBinar,'|',n:5,'| Insertions |',rearrBinar[1]:7,rearrBinar[2]:7,rearrBinar[3]:7,rearrBinar[4]:7,rearrBinar[5]:7,' |', ((rearrBinar[1]+rearrBinar[2]+rearrBinar[3]+rearrBinar[4]+rearrBinar[5]) div 5):9,' |'); writeln(outputBinar,'| | Comparisons |',comparBinar[1]:7,comparBinar[2]:7,comparBinar[3]:7,comparBinar[4]:7,comparBinar[5]:7,' |', ((comparBinar[1]+comparBinar[2]+comparBinar[3]+comparBinar[4]+comparBinar[5]) div 5):9,' |'); writeln(outputBinar,'----------------------------------------------------------------------'); end; close(outputShell); close(outputBinar); end.
UNIT bmp; (*! This UNIT provides a library to access and manipulate bitmap images provided in Microsoft .bmp file format. * * Copyright (c) University of Glasgow * Author Paul Cockshott This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. *) interface (*! The module exports an image type as a 3 dimensional array of pixels in which the first dimension identifies the colour plane, the second dimension indicates the row and the third dimension indicates the column of the pixel *) type image(maxplane,maxrow,maxcol:integer)= array[0..maxplane,0..maxrow,0..maxcol]of real; plane(maxrow,maxcol:integer)= array[0..maxrow,0..maxcol]of real; pimage=^image; filename = string[79]; PROCEDURE storebmpfile(s:string;var im:image) ; (*! This PROCEDURE will store an image \textsf{im} as a Microsoft .bmp file with name \textsf{s} *) FUNCTION loadbmpfile(s:filename;var im:pimage):boolean ; (*! This FUNCTION returns true if it has sucessfully loaded the bmp file \textsf{s}. The image pointer \textsf{im} is initialised to point to an image on the heap. The program should explicity discard the image after use by calling \textsf{dispose}. *) PROCEDURE adjustcontrast(f:real; var src,dest:image); (*! This PROCEDURE takes a real number as a parameter and adjusts the contrast of an image to by that factor. If \textsf{f}=2 then contrast is doubled, if \textsf{f}=0.5 contrast is halved. *) FUNCTION real2byte(r:real):byte; FUNCTION byte2real(b:byte):real; implementation type (*! The following data structures are defined by Microsoft for their bitmap files (.BMP) *) bitmapfileheader=packed record bftype:array [1..2] of byte; bfsize:integer; res1:array[0..3] of byte; bfoffbits:integer; END ; (*! A BitmapInfoHeader is the internal data structure used by microsoft Windows to handle device indepEND ent bitmaps, (DIBs). We only need this structure to interpret the data in a BMP file. *) TBitmapInfoHeader = record biSize: integer; biWidth: integer; biHeight: integer; biPlanes: Word; biBitCount: Word; biCompression: integer; biSizeImage: integer; biXPelsPerMeter: integer; biYPelsPerMeter: integer; biClrUsed: integer; biClrImportant: integer; END ; (*! This datastructure can optionally include a colour table, but this library does not support reading .bmp files with colour tables *) TBitmapInfo = record bmiHeader: TBitmapInfoHeader; END ; (*! The start of a .bmp file has a file header followed by information about the bitmap itself. *) bmpfile=packed record fileheader: bitmapfileheader; filedata:tbitmapinfo; END ; pbmpfile=^bmpfile; (*! This data type is the format in which lines of pixels are stored in .bmp files. It is used internally in the UNIT BMP to load and store images to files. This process involves translating between internal and external representations. *) imageline(mincol,maxcol,minplane,maxplane:integer)= array[mincol..maxcol,minplane..maxplane] of byte; PROCEDURE initbmpheader(var header:bmpfile;var im:image); (*! This PROCEDURE has the task of initialising a Window's BMP file header in a way conformant with the dimensions of the image passed as a parameter *) BEGIN (*! \paragraph{FileHeader} BMP files have the letters BM at the start followed by a 32 bit integer giving the file size, 4 reserved bytes and then a 32 bit integer giving the offset into the file at which the bitmap data starts. *) header.fileheader.bftype[1]:=ord('B'); header.fileheader.bftype[2]:=ord('M'); header.fileheader.bfsize:=sizeof(bmpfile)+ (im.maxcol+1)* (im.maxplane+1)* (im.maxrow+1); header.fileheader.res1:=0; header.fileheader.bfoffbits:=sizeof(bmpfile); (*! \paragraph{Bitmap info} Next comes a bitmap info header which gives details about the bitmap itself. The fields of this are as follows: \paragraph{bisize} this gives the size of the entire bitmap info header as a 32 bit integer. \paragraph{biwidth} this 32 bit integer gives the number of columns in the image, which can be determined from the bounds of the pixel array provided. \paragraph{biheight} another 32 bit integer which gives the number of scan lines in the image, which can again be determined from the bounds of the image array. \paragraph{biplanes} This gives the number of planes in the image as a 16 bit integer. This defaults to 1. \paragraph{bibitcount} Gives the var im:imagenumber of bits per pixel, we only support 8 and 24 bit versions at present. \paragraph{bicompression} The meaning of this field is not clear, it seems to be 0 in most files. \paragraph{biXPelsPerMeter, biYPelsPerMeter} These specify the printable spacing of pixels, I use the value \$ec4 that I observe in a number of bmp files. \paragraph{biClrUsed, biClrImportant} these fields are only used in images with colour maps, set them to zero for now. *) with header.filedata.bmiheader do BEGIN bisize:=sizeof(tbitmapinfo); biwidth:=im.maxcol+1 ; biheight:=im.maxrow+1 ; biplanes:= 1; bibitcount:=8 * (im.maxplane +1); bicompression:=0; biXPelsPerMeter:=$ec4; biYPelsPerMeter:=$ec4; biClrUsed:=0; biClrImportant:=0; END ; END ; PROCEDURE storebmpfile(s:string;var im:image) ; (*! This FUNCTION writes an image in vector pascal format to a microsoft {\tt .BMP} file. It is designed only to work with 1 or 3 plane images. *) type lines(rows,cols,planes:integer)=array[0..rows,0..cols,0..planes] of byte; var f:file ; fsize,i,index,j,k,m,row,res:integer; pf:bmpfile; la: ^lines;b:byte; BEGIN assign(f,s); rewrite(f); initbmpheader(pf,im); { setup header} blockwrite(f,pf,sizeof(bmpfile),res); {write it} new(la ,im.maxrow,im.maxcol,im.maxplane ); {get buffer} (*! Convert the data from the planar signed fixed point format used in Vector Pascal to the interleaved unsigned byte format used in Windows. *) la^:= perm[2,0,1] real2byte(im); (*! Compute the size of a line and write each line. We have to make sure each line occupies an integral number of 32 bit words. *) fsize:=(im.maxplane+1) *(im.maxcol+1); if (fsize mod 4)<>0 then fsize:= fsize+4-(fsize mod 4); { make integral number of words on a line } for i:= im.maxrow downto 0 do blockwrite(f,la^[i,0,0],fsize,res); {write data} dispose(la); { free buffer} close(f); END ; FUNCTION loadbmpfile(s:filename;var im:pimage):boolean ; type byteimage(maxrow,maxcol,maxpix:integer)=array[0..maxrow,0..maxcol,0..maxpix] of byte; var f:file of byte; fsize,i,index,j,k,m,row,res:integer; la: ^byteimage; pf:bmpfile;bb:byte; BEGIN loadbmpfile:=false; assign(f,s); reset(f); if ioresult <>0 then BEGIN loadbmpfile:=false ; writeln('cant open ',s,ioresult) ; END else BEGIN fsize:=filesize(f); i:=sizeof(bmpfile); blockread(f,pf,i,res); with pf.filedata.bmiheader do BEGIN { writeln('read header');} new(im,2,biheight-1,biwidth-1); new(la,biheight-1,biwidth-1,2); { writeln('created array la',biheight-1,biwidth-1,2);{} if bibitcount=8 then BEGIN loadbmpfile:=false; writeln(' 8 bit bmp files not supported'); END else if bibitcount=24 then BEGIN fsize:=(im^.maxplane+1) *(im^.maxcol+1); if (fsize mod 4)<>0 then fsize:= fsize+4-(fsize mod 4); { make integral number of words on a line } for i:= im^.maxrow downto 0 do BEGIN { writeln('read row',i);}{$r-} bb:=la^[i,0,0]; { writeln('got byte');} blockread(f,la^[i,0,0],fsize,res); {read data} END ; { writeln('permute ');} im^:= perm[1,2,0]byte2real(la^); loadbmpfile:=true; END ; dispose(la); close(f); END ; END ; END ; type line (high:integer)=array[0..high] of pixel; PROCEDURE adjustcontrast(f:real; var src,dest:image); var l:^line;r:real; BEGIN dest:=src*f ; END ; FUNCTION real2byte(r:real):byte; var temp:pixel; BEGIN temp:=r; real2byte:=pixel2byte(temp); END ; FUNCTION byte2real(b:byte):real; var temp:pixel; BEGIN temp:=byte2pixel(b); byte2real:=temp; END ; BEGIN END .
UNIT FileIO; {$I-,X+,O-,F-} INTERFACE USES Dos; { Exist Function } TYPE FileRec = Record Handle : Word; LockFile : Boolean; Mode : Byte; FilePos : LongInt; Open : Boolean; End; FUNCTION Reset(S:String; VAR F:FileRec; Mode:Byte):Integer; FUNCTION Rewrite(S:String; VAR F:FileRec; Mode:Byte):Integer; FUNCTION Close(VAR F:FileRec):Integer; FUNCTION LockFile(VAR F:FileRec; Start,Stop:LongInt; LockType:Byte):Integer; FUNCTION Flush(VAR F:FileRec):Integer; FUNCTION Truncate(VAR F:FileRec):Integer; FUNCTION BlockRead(VAR F:FileRec; S,O:Word; Bytes:Integer; VAR Read:Integer):Integer; FUNCTION BlockWrite(VAR F:FileRec; S,O:Word; Bytes:Integer):Integer; FUNCTION Seek(VAR F:FileRec; Loc:LongInt):Integer; FUNCTION SeekEof(VAR F:FileRec):Integer; FUNCTION FileSize(VAR F:FileRec):LongInt; FUNCTION FilePos(VAR F:FileRec):LongInt; PROCEDURE SetLock(VAR F:FileRec; Lock:Boolean); FUNCTION DeleteRec(VAR F:FileRec; RecNum,RecSize:Integer):Boolean; FUNCTION Erase(F:String):Boolean; CONST NoLock = 2; EntireLock = 2; { 16 or 2 } DenyWrite = 2; { 48 or 1 } DenyRead = 2; { 32 } RandomLock = 2; Lock = 0; Unlock = 1; IMPLEMENTATION CONST Tries:Integer=0; TYPE LongIntArr=Array[1..2] of Word; FUNCTION Cflag(VAR Regs:Registers):Boolean; Begin Cflag:=(Regs.Flags AND 1>0); End; Function Exist(Filename:string):boolean; {returns true if file exists} var Inf: SearchRec; begin FindFirst(Filename,AnyFile,Inf); Exist := (DOSError = 0); end; {Func Exist} FUNCTION Reset(S:String; VAR F:FileRec; Mode:Byte):Integer; VAR Regs:Registers; Begin Reset:=$FF; If Not Exist(S) then Exit; { Keeps Lans from Locking Up } F.Handle:=0; F.LockFile:=(Mode<>NoLock); F.Mode:=Mode; F.FilePos:=0; F.Open:=False; Repeat Regs.Ah:=$3D; Regs.Al:=Mode; S[Length(S)+1]:=#0; Regs.Ds:=Seg(S); Regs.Dx:=Ofs(S)+1; MsDos(Regs); Until Not ((Cflag(Regs)) and (Regs.Ax=$05)); If Cflag(Regs) then Reset:=Regs.Ax else Begin F.Handle:=Regs.Ax; F.Open:=True; Reset:=0; End; End; FUNCTION Rewrite(S:String; VAR F:FileRec; Mode:Byte):Integer; VAR Regs:Registers; I:Integer; Begin F.Handle:=0; F.LockFile:=(Mode<>NoLock); F.Mode:=Mode; F.FilePos:=0; F.Open:=False; Repeat Regs.Ah:=$3C; Regs.Cx:=$00; Regs.Ds:=Seg(S); Regs.Dx:=Ofs(S)+1; S[Length(S)+1]:=#0; MsDos(Regs); Until Not ((Cflag(Regs)) and (Regs.Ax=$05)); If Cflag(Regs) then Rewrite:=Regs.Ax else Begin F.Handle:=Regs.Ax; F.Open:=True; Close(F); Rewrite:=Reset(S,F,Mode); End; End; FUNCTION Close(VAR F:FileRec):Integer; VAR Regs:Registers; Begin If Not F.Open then Begin Close:=127; Exit; End; Repeat Regs.Ah:=$3E; Regs.Bx:=F.Handle; Intr($21,Regs); MsDos(Regs); Until Not ((Cflag(Regs)) and (Regs.Ax=$05)); if Cflag(Regs) then Close:=Regs.Ax else Begin Close:=0; F.Open:=False; End; End; FUNCTION LockFile(VAR F:FileRec; Start,Stop:LongInt; LockType:Byte):Integer; VAR Regs:Registers; Begin If Not F.Open then Begin LockFile:=127; Exit; End; Repeat Regs.Ah:=$5C; Regs.Al:=LockType; Regs.Bx:=F.Handle; Regs.Cx:=LongIntArr(Start)[1]; Regs.Dx:=LongIntArr(Start)[2]; Regs.Si:=LongIntArr(Stop)[1]; Regs.Di:=LongIntArr(Stop)[2]; MsDos(Regs); Until Not ((Cflag(Regs)) and (Regs.Ax=$05)); If Cflag(Regs) then LockFile:=Regs.Ax else LockFile:=0; End; FUNCTION Flush(VAR F:FileRec):Integer; VAR Regs:Registers; Begin If Not F.Open then Begin Flush:=127; Exit; End; repeat Regs.Ah:=$68; Regs.Bx:=F.Handle; MsDos(Regs); Until Not ((Cflag(Regs)) and (Regs.Ax=$05)); If Cflag(Regs) then Flush:=Regs.Ax else Flush:=0; End; FUNCTION Truncate(VAR F:FileRec):Integer; Begin End; FUNCTION BlockRead(VAR F:FileRec; S,O:Word; Bytes:Integer; VAR Read:Integer):Integer; CONST Error:Boolean=False; VAR Regs:Registers; Begin If Not F.Open then Begin BlockRead:=127; Exit; End; If F.LockFile then LockFile(F,F.FilePos,F.FilePos+Bytes,Lock); Repeat Regs.Ah:=$3F; Regs.Bx:=F.Handle; Regs.Cx:=Bytes; Regs.Ds:=S; Regs.Dx:=O; MsDos(Regs); Until Not ((Cflag(Regs)) and (Regs.Ax=$05)); If F.LockFile then LockFile(F,F.FilePos,F.FilePos+Bytes,UnLock); If Error then Exit; Read:=0; If Cflag(Regs) then BlockRead:=Regs.Ax else Begin Read:=Regs.Ax; F.FilePos:=F.FilePos+Regs.Ax; BlockRead:=0; End; End; FUNCTION BlockWrite(VAR F:FileRec; S,O:Word; Bytes:Integer):Integer; VAR Regs:Registers; Begin If Not F.Open then Begin BlockWrite:=127; Exit; End; If F.LockFile then LockFile(F,F.FilePos,F.FilePos+Bytes,Lock); Repeat Regs.Ah:=$40; Regs.Bx:=F.Handle; Regs.Cx:=Bytes; Regs.Ds:=S; Regs.Dx:=O; MsDos(Regs); Until Not ((Cflag(Regs)) and (Regs.Ax=$05)); If F.LockFile then LockFile(F,F.FilePos,F.FilePos+Bytes,UnLock); If Cflag(Regs) then BlockWrite:=Regs.Ax else Begin BlockWrite:=0; F.FilePos:=F.FilePos+Regs.Ax; End; End; FUNCTION Seek(VAR F:FileRec; Loc:LongInt):Integer; VAR Regs:Registers; Begin If Not F.Open then Begin Seek:=127; Exit; End; Repeat Regs.Ah:=$42; Regs.Al:=$00; Regs.Bx:=F.Handle; Regs.Cx:=Word(Loc shl 16); Regs.Dx:=Word(Loc); MsDos(Regs); Until Not ((Cflag(Regs)) and (Regs.Ax=$05)); If Cflag(Regs) then Seek:=Regs.Ax else Begin Seek:=0; F.FilePos:=(Regs.Dx shl 16) or Regs.Ax; End; End; FUNCTION SeekEof(VAR F:FileRec):Integer; VAR Regs:Registers; Begin If Not F.Open then Begin SeekEof:=127; Exit; End; Repeat Regs.Ah:=$42; Regs.Al:=$02; Regs.Bx:=F.Handle; Regs.Cx:=0; Regs.Dx:=0; MsDos(Regs); Until Not ((Cflag(Regs)) and (Regs.Ax=$05)); If Cflag(Regs) then SeekEof:=Regs.Ax else Begin F.FilePos:=LongInt((Regs.Dx shl 16) or Regs.Ax); SeekEof:=0; End; End; FUNCTION FileSize(VAR F:FileRec):LongInt; VAR Loc:LongInt; Regs:Registers; Begin If Not F.Open then Begin FileSize:=$FFFFFFFF; Exit; End; Loc:=F.FilePos; Repeat Regs.Ah:=$42; Regs.Al:=$02; Regs.Bx:=F.Handle; Regs.Cx:=0; Regs.Dx:=0; MsDos(Regs); Until Not ((Cflag(Regs)) and (Regs.Ax=$05)); If Cflag(Regs) then Begin FileSize:=$FFFFFFFF; Seek(F,Loc); End else Begin FileSize:=LongInt((Regs.Dx shl 16) or Regs.Ax); Seek(F,Loc); End; End; FUNCTION FilePos(VAR F:FileRec):LongInt; Begin FilePos:=F.FilePos; End; PROCEDURE SetLock(VAR F:FileRec; Lock:Boolean); Begin F.LockFile:=Lock; End; FUNCTION DeleteRec(VAR F:FileRec; RecNum,RecSize:Integer):Boolean; VAR Position:LongInt; P:Pointer; L,I:Integer; Err:Boolean; Begin DeleteRec:=False; If not F.Open then Exit; Position:=F.FilePos; GetMem(P,RecSize); Err:=False; If Not (RecNum-1=FileSize(F) div RecSize) then For I:=RecNum to (FileSize(F) div RecSize) do Begin If Seek(F,I*RecSize)<>0 then Err:=True; If BlockRead(F,Seg(P^),Ofs(P^),RecSize,L)<>0 then Err:=True; If L<>RecSize then Err:=True; If Seek(F,(I-1)*RecSize)<>0 then Err:=True; If BlockWrite(F,Seg(P^),Ofs(P^),RecSize)<>0 then Err:=True; If Err then Exit; End; FreeMem(P,RecSize); If Err then Exit; If Seek(F,FileSize(F)-RecSize)<>0 then Exit; If Truncate(F)<>0 then Exit; If Seek(F,Position)<>0 then Exit; DeleteRec:=True; End; FUNCTION Erase(F:String):Boolean; VAR Regs:Registers; Begin Regs.Ah:=$41; Regs.Ds:=Seg(F); Regs.Dx:=Ofs(F)+1; F[Length(F)+1]:=#0; Intr($21,Regs); Erase:=Cflag(Regs); End; End.
(* @abstract(Contient des fonctions utilises dans la manipulation des vecteurs) ------------------------------------------------------------------------------------------------------------- @created(2017-11-25) @author(J.Delauney (BeanzMaster)) @author(Peter Dyson (Dicepd)) Historique : @br @unorderedList( @item(Last Update : 13/03/2018 ) @item(12/03/2018 : Creation ) ) ------------------------------------------------------------------------------------------------------------- @bold(Notes) : ------------------------------------------------------------------------------------------------------------- @bold(Dependance) : BZMath, BZVectorMath, BZVectorMathEx ------------------------------------------------------------------------------------------------------------- @bold(Credits :)@br @unorderedList( @item(FPC/Lazarus) @item(GLScene) @item(All authors of papers and web links) ) ------------------------------------------------------------------------------------------------------------- @bold(LICENCE) : MPL / GPL ------------------------------------------------------------------------------------------------------------- *) unit BZVectorMathUtils; //============================================================================== {$mode objfpc}{$H+} {$i ..\bzscene_options.inc} //----------------------------- {$INLINE ON} {$MODESWITCH ADVANCEDRECORDS} //----------------------------- //----------------------- DATA ALIGNMENT --------------------------------------- {$ALIGN 16} {$CODEALIGN CONSTMIN=16} {$CODEALIGN LOCALMIN=16} {$CODEALIGN VARMIN=16} //------------------------------------------------------------------------------ //============================================================================== interface uses Classes, SysUtils, BZMath, BZVectorMath; {%region%----[ Inline Vector Helpers functions ]--------------------------------} { Creation d'un point 3D affine } function AffineVectorMake(const x, y, z : Single) : TBZAffineVector;overload; { Creation d'un point 3D affine depuis un point homogène } function AffineVectorMake(const v : TBZVector) : TBZAffineVector;overload; { Creation d'un point 2D en valeurs flottantes } function vec2(vx,vy:single):TBZVector2f; { Creation d'un point homogène en valeurs flottantes } function vec4(vx,vy,vz,vw:single):TBZVector4f;overload; { Creation d'un point homogène en fonction d'une valeur de type single } function vec4(vx:single):TBZVector4f; overload; { Creation d'un point homogène en fonction des paramètres (W = 0.0) } function PointVec4(vx,vy,vz:single):TBZVector4f;overload; { Creation d'un point affine dans un vecteur homogène en fonction d'une valeur de type single (W = 1.0) } function PointVec4(vx:single):TBZVector4f;overload; //function PointVec4(Const anAffineVector: TBZVector3f):TBZVector4f; overload; { Creation d'un point 2D en valeur entière } function vec2i(vx,vy:Integer) : TBZVector2i; {%endregion%} {%region%-----[ Inline Algebra and Trigonometric functions for vectors ]--------} //--- For TBZVector2f --------------------------------------------------------- { Retourne les valeur tronquées d'un vecteur 2D en virgule flottante, dans un vecteur de type TBZVector2i } function Trunc(Constref v:TBZVector2f):TBZVector2i; overload; { Retourne les valeur arrondies d'un vecteur 2D en virgule flottante dans un vecteur de type TBZVector2i } function Round(Constref v:TBZVector2f):TBZVector2i; overload; { Retourne les valeur arrondies d'un vecteur 2D en virgule flottante, tendant vers l'infini négatif dans un vecteur de type TBZVector2i } function Floor(Constref v:TBZVector2f):TBZVector2i; overload; { Retourne les valeur arrondies d'un vecteur 2D en virgule flottante, tendant vers l'infini positif dans un vecteur de type TBZVector2i } //function Ceil(Constref v:TBZVector2f):TBZVector2i; overload; { Retourne la partie fractionnaire de chaque valeur contenues dans le vecteur 2D en virgule flottante } function Fract(Constref v:TBZVector2f):TBZVector2f; overload; //function Length(v:TBZVector2f):Single;overload; //function Distance(v1,v2:TBZVector2f):Single; //function Normalize(v:TBZVector2f):TBZVector2f; //function fma(v,m,a:TBZVector2f): TBZVector2f; overload; //function fma(v:TBZVector2f; m,a:Single): TBZVector2f; overload; //function fma(v,m:TBZVector2f;a:Single): TBZVector2f; overload; //function fma(v:TBZVector2f;m:Single; a:TBZvector2f): TBZVector2f; overload; //function faceforward //function SmoothStep; //function Step; //function Saturate; //--- Trigonometrics functions { Retourne la racine carré d'un point 2D en virgule flottante } function Sqrt(Constref v:TBZVector2f):TBZVector2f; overload; { Retourne la racine carré inverse d'un point 2D en virgule flottante } function InvSqrt(Constref v:TBZVector2f):TBZVector2f; overload; { Retourne le sinus de chaque valeur d'un point 2D en virgule flottante } function Sin(v:TBZVector2f):TBZVector2f; overload; { Retourne le cosinus de chaque valeur d'un point 2D en virgule flottante } function Cos(v:TBZVector2f):TBZVector2f; overload; { Retourne le sinus et le cosinus d'une valeur de type Single dans un vecteur 2D en virgule flottante } function SinCos(x:Single):TBZvector2f; overload; { Retourne le sinus et le cosinus respectif des valeurs contenues dans vecteur 2D en virgule flottante } function SinCos(v:TBZVector2f):TBZvector2f; overload; // function Exp; // function Ln; //--- For TBZVector4f --------------------------------------------------------- { Retourne la partie fractionnaire de chaque valeur contenues dans le vecteur 4D en virgule flottante } function Fract(Constref v:TBZVector4f):TBZVector4f; overload; //function Trunc(v:TBZVector4f):TBZVector4i; overload; //function Round(v:TBZVector4f):TBZVector4i; overload; //function Floor(v:TBZVector4f):TBZVector4i; overload; //function Fract(v:TBZVector4f):TBZVector4i; overload; //function Sqrt(v:TBZVector2f):TBZVector4f; overload; //function InvSqrt(v:TBZVector2f):TBZVector4f; overload; //function Sin(v:TBZVector4f):TBZVector4f; overload; //function Cos(v:TBZVector4f):TBZVector4f; overload; // retun SinCos, SinCos (x and z = sin, y and w = cos) //function SinCos(v:TBZVector4f):TBZVector4f; overload; {%endregion%} {%region%-----[ Misc Inline utilities functions for vectors ]-------------------} { Retourne @True si deux vecteur de type TBZVector sont colinéaire } function VectorIsColinear(constref v1, v2: TBZVector) : Boolean; //function PlaneContains(const Location, Normal: TBZVector; const TestBSphere: TBZBoundingSphere): TBZSpaceContains; { Calculates the barycentric coordinates for the point p on the triangle defined by the vertices v1, v2 and v3. That is, solves p = u * v1 + v * v2 + (1-u-v) * v3 for u,v. Returns true if the point is inside the triangle, false otherwise. NOTE: This function assumes that the point lies on the plane defined by the triangle. If this is not the case, the function will not work correctly! } //function BarycentricCoordinates(const v1, v2, v3, p: TBZAffineVector; var u, v: single): boolean; { Computes the triangle's area. } //function TriangleArea(const p1, p2, p3 : TBZAffineVector) : Single; overload; { Computes the polygons's area. Points must be coplanar. Polygon needs not be convex. } //function PolygonArea(const p : PAffineVectorArray; nSides : Integer) : Single; overload; { Computes a 2D triangle's signed area. Only X and Y coordinates are used, Z is ignored. } //function TriangleSignedArea(const p1, p2, p3 : TBZAffineVector) : Single; overload; { Computes a 2D polygon's signed area. Only X and Y coordinates are used, Z is ignored. Polygon needs not be convex. } //function PolygonSignedArea(const p : PAffineVectorArray; nSides : Integer) : Single; overload; { Generates a random point on the unit sphere. Point repartition is correctly isotropic with no privilegied direction. } //function RandomPointOnSphere:TBZVector; {%endregion%} implementation //-----[ INCLUDE IMPLEMENTATION ]----------------------------------------------- {$ifdef USE_ASM} {$ifdef CPU64} {$ifdef UNIX} {$IFDEF USE_ASM_AVX} {$I vectormath_utils_native_imp.inc} {$I vectormath_utils_avx_imp.inc} {$ELSE} {$I vectormath_utils_native_imp.inc} {$I vectormath_utils_sse_imp.inc} {$ENDIF} {$else} // win64 {$IFDEF USE_ASM_AVX} {$I vectormath_utils_native_imp.inc} {$I vectormath_utils_avx_imp.inc} {$ELSE} {$I vectormath_utils_native_imp.inc} {$I vectormath_utils_sse_imp.inc} {$ENDIF} {$endif} //unix {$else} // CPU32 {$IFDEF USE_ASM_AVX} {$I vectormath_utils_native_imp.inc} {$I vectormath_utils_avx_imp.inc} {$ELSE} {$I vectormath_utils_native_imp.inc} {$I vectormath_utils_sse_imp.inc} {$ENDIF} {$endif} {$else} // pascal {$I vectormath_utils_native_imp.inc} {$endif} end.
unit List_MemberInfo; interface {$I InfraReflection.Inc} uses {$IFDEF USE_GXDEBUG}DBugIntf, {$ENDIF} InfraBasicList, InfraCommonIntf, InfraCommon; type _ITERABLELIST_BASE_ = TBaseElement; _ITERABLELIST_INTF_ = IMemberInfoList; _ITEM_INTF_ = IMemberInfo; _ITERATOR_INTF_ = IInfraIterator; {$I ..\Templates\InfraTempl_IntfList.inc} function NewMemberInfoIterator(MemberTypes: TMemberTypes): IMemberInfoIterator; function NewMethodInfoIterator(MethodType: TMethodType): IMethodInfoIterator; function NewPropertyInfoIterator: IPropertyInfoIterator; end; TMemberInfoIterator = class(TInterfacedObject, IMemberInfoIterator) private FCurrentIndex: integer; FList: _ITERABLELIST_INTF_; FMemberTypes: TMemberTypes; protected function CurrentItem: _ITEM_INTF_; procedure First; virtual; function IsDone: Boolean; virtual; procedure Next; virtual; public constructor Create(const List: _ITERABLELIST_INTF_; MemberTypes: TMemberTypes); end; TMethodInfoIterator = class(TInterfacedObject, IMethodInfoIterator) private FCurrentIndex: integer; FMethodType: TMethodType; FList: _ITERABLELIST_INTF_; protected function CurrentItem: IMethodInfo; procedure First; virtual; function IsDone: Boolean; virtual; procedure Next; virtual; public constructor Create(const List: _ITERABLELIST_INTF_; MethodType: TMethodType); end; TPropertyInfoIterator = class(TInterfacedObject, IPropertyInfoIterator) private FCurrentIndex: integer; FList: _ITERABLELIST_INTF_; protected function CurrentItem: IPropertyInfo; procedure First; virtual; function IsDone: Boolean; virtual; procedure Next; virtual; public constructor Create(const List: _ITERABLELIST_INTF_); end; TMemberInfoList = class(_ITERABLELIST_); implementation uses SysUtils; { TMemberInfoList } {$I ..\Templates\InfraTempl_IntfList.inc} function _ITERABLELIST_.NewMemberInfoIterator( MemberTypes: TMemberTypes): IMemberInfoIterator; begin Result := TMemberInfoIterator.Create(Self, MemberTypes); end; function _ITERABLELIST_.NewMethodInfoIterator(MethodType: TMethodType): IMethodInfoIterator; begin Result := TMethodInfoIterator.Create(Self, MethodType); end; function _ITERABLELIST_.NewPropertyInfoIterator: IPropertyInfoIterator; begin Result := TPropertyInfoIterator.Create(Self); end; destructor _ITERABLELIST_.Destroy; begin FreeAndNil(FItems); inherited; end; { TMemberInfoIterator } constructor TMemberInfoIterator.Create(const List: _ITERABLELIST_INTF_; MemberTypes: TMemberTypes); begin inherited Create; FMemberTypes := MemberTypes; FList := List; First; end; function TMemberInfoIterator.CurrentItem: _ITEM_INTF_; begin if Assigned(FList) and not IsDone then Result := FList[fCurrentIndex] else Result := nil; end; procedure TMemberInfoIterator.First; begin fCurrentIndex := -1; Next; end; function TMemberInfoIterator.IsDone: Boolean; begin Result := (fCurrentIndex = FList.Count); end; procedure TMemberInfoIterator.Next; begin Inc(fCurrentIndex); if not IsDone then begin while (fCurrentIndex < FList.Count) do begin if (FList[fCurrentIndex] as IMemberInfo).MemberType in FMemberTypes then Break; Inc(fCurrentIndex); end; end; end; { TMethodInfoIterator } constructor TMethodInfoIterator.Create(const List: _ITERABLELIST_INTF_; MethodType: TMethodType); begin inherited Create; FMethodType := MethodType; FList := List; First; end; function TMethodInfoIterator.CurrentItem: IMethodInfo; begin if Assigned(FList) and not IsDone then Result := FList[fCurrentIndex] as IMethodInfo else Result := nil; end; procedure TMethodInfoIterator.First; begin fCurrentIndex := -1; Next; end; function TMethodInfoIterator.IsDone: Boolean; begin Result := (fCurrentIndex = FList.Count); end; procedure TMethodInfoIterator.Next; var MemberInfo: IMemberInfo; begin Inc(fCurrentIndex); if not IsDone then begin while (fCurrentIndex < FList.Count) do begin MemberInfo := FList[fCurrentIndex]; if (MemberInfo.MemberType = mtConstructor) and (FMethodType in [mtJustConstructors, mtBoth]) then Break else if (MemberInfo.MemberType = mtMethod) and (FMethodType in [mtJustMethods, mtBoth]) then Break; Inc(fCurrentIndex); end; end; end; { TPropertyInfoIterator } constructor TPropertyInfoIterator.Create(const List: _ITERABLELIST_INTF_); begin inherited Create; FList := List; First; end; function TPropertyInfoIterator.CurrentItem: IPropertyInfo; begin if Assigned(FList) and not IsDone then Result := FList[fCurrentIndex] as IPropertyInfo else Result := nil; end; procedure TPropertyInfoIterator.First; begin fCurrentIndex := -1; Next; end; function TPropertyInfoIterator.IsDone: Boolean; begin Result := (fCurrentIndex = FList.Count); end; procedure TPropertyInfoIterator.Next; begin Inc(fCurrentIndex); if not IsDone then begin while (fCurrentIndex < FList.Count) do begin if (FList[fCurrentIndex] as IMemberInfo).MemberType = mtProperty then Break; Inc(fCurrentIndex); end; end; end; end.
{----------------------------------------------------------------------------- The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.mozilla.org/MPL/MPL-1.1.html Software distributed under the License is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for the specific language governing rights and limitations under the License. The Original Code is: JvTFAlarm.PAS, released on 2003-08-01. The Initial Developer of the Original Code is Unlimited Intelligence Limited. Portions created by Unlimited Intelligence Limited are Copyright (C) 1999-2002 Unlimited Intelligence Limited. All Rights Reserved. Contributor(s): Mike Kolter (original code) You may retrieve the latest version of this file at the Project JEDI's JVCL home page, located at http://jvcl.delphi-jedi.org Known Issues: -----------------------------------------------------------------------------} // $Id: JvTFAlarm.pas 13104 2011-09-07 06:50:43Z obones $ unit JvTFAlarm; {$I jvcl.inc} interface uses {$IFDEF UNITVERSIONING} JclUnitVersioning, {$ENDIF UNITVERSIONING} SysUtils, Classes, Controls, ExtCtrls, {$IFDEF BCB} JvTypes, {$ENDIF BCB} JvTFManager; type TJvTFAlarm = class; TJvTFAlarmInfo = class(TObject) private FAppt: TJvTFAppt; FSnoozeMins: Integer; FDismiss: Boolean; FNextAlarmTime: TTime; protected property NextAlarmTime: TTime read FNextAlarmTime write FNextAlarmTime; public constructor Create(AAppt: TJvTFAppt); virtual; property Appt: TJvTFAppt read FAppt; property SnoozeMins: Integer read FSnoozeMins write FSnoozeMins; property Dismiss: Boolean read FDismiss write FDismiss; end; TJvTFAlarmList = class(TStringList) private FOwner: TJvTFAlarm; public procedure Clear; override; function GetAlarmForAppt(AAppt: TJvTFAppt): TJvTFAlarmInfo; function GetAlarmForApptID(const ID: string): TJvTFAlarmInfo; function IndexOfAppt(AAppt: TJvTFAppt): Integer; procedure AddAppt(AAppt: TJvTFAppt); procedure DeleteAppt(AAppt: TJvTFAppt); property Owner: TJvTFAlarm read FOwner write FOwner; end; TJvTFAlarmEvent = procedure(Sender: TObject; AAppt: TJvTFAppt; var SnoozeMins: Integer; var Dismiss: Boolean) of object; {$IFDEF RTL230_UP} [ComponentPlatformsAttribute(pidWin32 or pidWin64)] {$ENDIF RTL230_UP} TJvTFAlarm = class(TJvTFComponent) private FResources: TStringList; FTimer: TTimer; FCurrentDate: TDate; FAlarmList: TJvTFAlarmList; FOnAlarm: TJvTFAlarmEvent; FDefaultSnoozeMins: Integer; function GetResources: TStrings; procedure SetResources(Value: TStrings); function GetTimerInterval: Integer; procedure SetTimerInterval(Value: Integer); function GetEnabled: Boolean; procedure SetEnabled(Value: Boolean); procedure InternalTimer(Sender: TObject); protected procedure DestroyApptNotification(AAppt: TJvTFAppt); override; procedure ConnectSchedules; virtual; procedure DisconnectSchedules; virtual; procedure TimerCheck; virtual; procedure AlarmCheck; virtual; procedure Loaded; override; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Resources: TStrings read GetResources write SetResources; property TimerInterval: Integer read GetTimerInterval write SetTimerInterval default 30000; property Enabled: Boolean read GetEnabled write SetEnabled default True; property DefaultSnoozeMins: Integer read FDefaultSnoozeMins write FDefaultSnoozeMins default 5; property OnAlarm: TJvTFAlarmEvent read FOnAlarm write FOnAlarm; end; {$IFDEF UNITVERSIONING} const UnitVersioning: TUnitVersionInfo = ( RCSfile: '$URL: https://jvcl.svn.sourceforge.net/svnroot/jvcl/branches/JVCL3_47_PREPARATION/run/JvTFAlarm.pas $'; Revision: '$Revision: 13104 $'; Date: '$Date: 2011-09-07 08:50:43 +0200 (mer. 07 sept. 2011) $'; LogPath: 'JVCL\run' ); {$ENDIF UNITVERSIONING} implementation uses JvTFUtils; //=== { TJvTFAlarm } ========================================================= constructor TJvTFAlarm.Create(AOwner: TComponent); begin inherited Create(AOwner); FDefaultSnoozeMins := 5; FCurrentDate := Date; FResources := TStringList.Create; FTimer := TTimer.Create(Self); FTimer.Interval := 30000; FTimer.Enabled := True; FTimer.OnTimer := InternalTimer; FAlarmList := TJvTFAlarmList.Create; FAlarmList.Owner := Self; end; destructor TJvTFAlarm.Destroy; begin DisconnectSchedules; FTimer.Free; FResources.Free; FAlarmList.Create; FAlarmList.Free; inherited Destroy; end; procedure TJvTFAlarm.Loaded; begin inherited Loaded; ConnectSchedules; end; procedure TJvTFAlarm.AlarmCheck; var I, J, SnoozeMins: Integer; Dismiss: Boolean; Sched: TJvTFSched; Appt: TJvTFAppt; AlarmInfo: TJvTFAlarmInfo; AlarmTime: TTime; begin // 1. Roll through all schedules and add an alarm for each appt with a start // time that is less than the current time. (Duplicate appts will be ignored.) // 2. Roll through the alarm list and fire an OnAlarm event when appropriate. // 1. for I := 0 to ScheduleCount - 1 do begin Sched := Schedules[I]; for J := 0 to Sched.ApptCount - 1 do begin Appt := Sched.Appts[J]; AlarmTime := Appt.StartTime - Appt.AlarmAdvance * ONE_MINUTE; if (AlarmTime < Frac(Time)) and Appt.AlarmEnabled then FAlarmList.AddAppt(Appt); end; end; // 2. for I := 0 to FAlarmList.Count - 1 do begin AlarmInfo := TJvTFAlarmInfo(FAlarmList.Objects[I]); if not AlarmInfo.Dismiss and (AlarmInfo.NextAlarmTime < Frac(Time)) then begin SnoozeMins := AlarmInfo.SnoozeMins; Dismiss := False; if Assigned(FOnAlarm) then begin FOnAlarm(Self, AlarmInfo.Appt, SnoozeMins, Dismiss); AlarmInfo.SnoozeMins := SnoozeMins; AlarmInfo.Dismiss := Dismiss; end; AlarmInfo.NextAlarmTime := Time + SnoozeMins * ONE_MINUTE; end; end; end; procedure TJvTFAlarm.ConnectSchedules; var I: Integer; CurrentSchedules: TStringList; Schedule: TJvTFSched; begin CurrentSchedules := TStringList.Create; try FTimer.Enabled := False; // request all appropriate schedules. Store in temporary list so that // we can release all schedules no longer needed. for I := 0 to Resources.Count - 1 do begin Schedule := RetrieveSchedule(Resources[I], Date); CurrentSchedules.AddObject('', Schedule); end; // Now release all schedules no longer needed. (Cross check CurrentSchedules // against Schedules list.) for I := 0 to ScheduleCount - 1 do begin Schedule := Schedules[I]; if CurrentSchedules.IndexOfObject(Schedule) = -1 then ReleaseSchedule(Schedule.SchedName, Schedule.SchedDate); end; finally CurrentSchedules.Free; FTimer.Enabled := True; end; end; procedure TJvTFAlarm.DestroyApptNotification(AAppt: TJvTFAppt); begin FAlarmList.DeleteAppt(AAppt); inherited DestroyApptNotification(AAppt); end; procedure TJvTFAlarm.DisconnectSchedules; begin ReleaseSchedules; end; function TJvTFAlarm.GetEnabled: Boolean; begin Result := FTimer.Enabled; end; function TJvTFAlarm.GetTimerInterval: Integer; begin Result := FTimer.Interval; end; function TJvTFAlarm.GetResources: TStrings; begin Result := FResources; end; procedure TJvTFAlarm.InternalTimer(Sender: TObject); begin if Trunc(Date) <> Trunc(FCurrentDate) then begin FCurrentDate := Date; ConnectSchedules; end; TimerCheck; end; procedure TJvTFAlarm.SetEnabled(Value: Boolean); begin FTimer.Enabled := Value; end; procedure TJvTFAlarm.SetResources(Value: TStrings); begin FResources.Assign(Value); ConnectSchedules; end; procedure TJvTFAlarm.SetTimerInterval(Value: Integer); begin FTimer.Interval := Value; end; procedure TJvTFAlarm.TimerCheck; begin AlarmCheck; end; //=== { TJvTFAlarmInfo } ===================================================== constructor TJvTFAlarmInfo.Create(AAppt: TJvTFAppt); begin inherited Create; FAppt := AAppt; end; //=== { TJvTFAlarmList } ===================================================== procedure TJvTFAlarmList.AddAppt(AAppt: TJvTFAppt); var AlarmInfo: TJvTFAlarmInfo; begin if Assigned(AAppt) and (IndexOfAppt(AAppt) = -1) then begin AlarmInfo := TJvTFAlarmInfo.Create(AAppt); AlarmInfo.SnoozeMins := Owner.DefaultSnoozeMins; AlarmInfo.NextAlarmTime := AAppt.StartTime - AAppt.AlarmAdvance * ONE_MINUTE; AddObject(AAppt.ID, AlarmInfo); end; end; procedure TJvTFAlarmList.Clear; var I: Integer; begin for I := 0 to Count - 1 do Objects[I].Free; inherited Clear; end; procedure TJvTFAlarmList.DeleteAppt(AAppt: TJvTFAppt); var I: Integer; begin I := IndexOfAppt(AAppt); if I > -1 then begin Objects[I].Free; Delete(I); end; end; function TJvTFAlarmList.GetAlarmForAppt(AAppt: TJvTFAppt): TJvTFAlarmInfo; begin Result := GetAlarmForApptID(AAppt.ID); end; function TJvTFAlarmList.GetAlarmForApptID(const ID: string): TJvTFAlarmInfo; var I: Integer; begin Result := nil; I := IndexOf(ID); if I > -1 then Result := TJvTFAlarmInfo(Objects[I]); end; function TJvTFAlarmList.IndexOfAppt(AAppt: TJvTFAppt): Integer; begin Result := IndexOf(AAppt.ID); end; {$IFDEF UNITVERSIONING} initialization RegisterUnitVersion(HInstance, UnitVersioning); finalization UnregisterUnitVersion(HInstance); {$ENDIF UNITVERSIONING} end.
unit EcranTribu; interface { Affichage de l'écran et appel des fonctions & procédures associées } procedure afficher(); implementation uses Variables, GestionEcran, OptnAffichage, EcranAccueil, EcranElevage, EcranMilitaire; { Actions effectuées lors d'un passage au tour suivant } procedure tourSuivant; begin { On passe au jour suivant } setTribu_numJour(getTribu().numJour + 1); { Calcul du savoir/j à partir du savoir/j absolu } setElevage_savoirJour(getElevage().savoirJourAbsolu - getElevage().population); { Augmentation du savoir acquis (croissance) } setElevage_savoirAcquis(getElevage().savoirAcquis + getElevage().savoirJour); { Les points de recrutement sont rechargés } setTribu_ptsRecrutement(getTribu().ptsRecrutementJour); { Si une construction est en cours, on augmente le total d'équations résolues (travail) } if getElevage().construction = True then setElevage_equationsResolues( getElevage().equationsResolues + getElevage().equationsJour); { Vérification des états d'avancement de la croissance et de la construction } majConstruction(); majCroissance(); { Enfin, on affiche de nouveau l'écran } afficher(); end; { Récupère le choix du joueur et détermine l'action à effectuer } procedure choisir; 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 } if (choix = '1') then begin EcranElevage.afficher(); end; if (choix = '2') then begin EcranMilitaire.afficher(); end; if (choix = '9') then tourSuivant(); if (choix = '0') then begin EcranAccueil.verifQuitter(); end { Valeur saisie invalide } else begin setMessage('Action non reconnue'); afficher(); end; end; { Affichage de l'écran et appel des fonctions & procédures associées } procedure afficher; begin effacerEcran(); { Partie supérieure de l'écran } afficherEnTete(); dessinerCadreXY(0,6, 119,28, simple, 15,0); afficherTitre('ECRAN DE GESTION DE LA TRIBU', 6); { Corps de l'écran } deplacerCurseurXY(3,10); writeln('Liste des Élevages :'); deplacerCurseurXY(3,11); writeln('¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯'); afficherElevage(4,13); { Choix disponibles } deplacerCurseurXY(3,22); writeln('1 - Gérer l''Élevage : ', getElevage().nom); deplacerCurseurXY(3,23); writeln('2 - Gestion militaire et diplomatique'); deplacerCurseurXY(3,25); writeln('9 - Fin de tour'); deplacerCurseurXY(3,26); writeln('0 - Quitter la partie'); { Partie inférieure de l'écran } afficherMessage(); afficherCadreAction(); choisir(); end; end.
{ ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(ORMBr Framework.) @created(20 Jul 2016) @author(Isaque Pinheiro <isaquepsp@gmail.com>) @author(Skype : ispinheiro) ORM Brasil é um ORM simples e descomplicado para quem utiliza Delphi. } unit ormbr.command.selecter; interface uses SysUtils, Rtti, DB, ormbr.command.abstract, dbebr.factory.interfaces, dbcbr.mapping.classes, dbcbr.mapping.explorer; type TCommandSelecter = class(TDMLCommandAbstract) private FPageSize: Integer; FPageNext: Integer; FSelectCommand: string; public constructor Create(AConnection: IDBConnection; ADriverName: TDriverName; AObject: TObject); override; procedure SetPageSize(const APageSize: Integer); function GenerateSelectAll(const AClass: TClass): string; function GeneratorSelectWhere(const AClass: TClass; const AWhere, AOrderBy: string): string; function GenerateSelectID(const AClass: TClass; const AID: Variant): string; function GenerateSelectOneToOne(const AOwner: TObject; const AClass: TClass; const AAssociation: TAssociationMapping): string; function GenerateSelectOneToMany(const AOwner: TObject; const AClass: TClass; const AAssociation: TAssociationMapping): string; function GenerateNextPacket: string; overload; function GenerateNextPacket(const AClass: TClass; const APageSize, APageNext: Integer): string; overload; function GenerateNextPacket(const AClass: TClass; const AWhere, AOrderBy: String; const APageSize, APageNext: Integer): string; overload; end; implementation { TCommandSelecter } constructor TCommandSelecter.Create(AConnection: IDBConnection; ADriverName: TDriverName; AObject: TObject); begin inherited Create(AConnection, ADriverName, AObject); FSelectCommand := ''; FResultCommand := ''; FPageSize := -1; FPageNext := 0; end; function TCommandSelecter.GenerateNextPacket: string; begin FPageNext := FPageNext + FPageSize; FResultCommand := FGeneratorCommand.GeneratorPageNext(FSelectCommand, FPageSize, FPageNext); Result := FResultCommand; end; procedure TCommandSelecter.SetPageSize(const APageSize: Integer); begin FPageSize := APageSize; end; function TCommandSelecter.GenerateSelectAll(const AClass: TClass): string; begin FPageNext := 0; FSelectCommand := FGeneratorCommand.GeneratorSelectAll(AClass, FPageSize, -1); FResultCommand := FGeneratorCommand.GeneratorPageNext(FSelectCommand, FPageSize, FPageNext); Result := FResultCommand; end; function TCommandSelecter.GenerateSelectOneToMany(const AOwner: TObject; const AClass: TClass; const AAssociation: TAssociationMapping): string; begin FResultCommand := FGeneratorCommand.GenerateSelectOneToOneMany(AOwner, AClass, AAssociation); Result := FResultCommand; end; function TCommandSelecter.GenerateSelectOneToOne(const AOwner: TObject; const AClass: TClass; const AAssociation: TAssociationMapping): string; begin FResultCommand := FGeneratorCommand.GenerateSelectOneToOne(AOwner, AClass, AAssociation); Result := FResultCommand; end; function TCommandSelecter.GeneratorSelectWhere(const AClass: TClass; const AWhere, AOrderBy: string): string; var LWhere: String; begin FPageNext := 0; LWhere := StringReplace(AWhere,'%', '$', [rfReplaceAll]); FSelectCommand := FGeneratorCommand.GeneratorSelectWhere(AClass, LWhere, AOrderBy, FPageSize); FResultCommand := FGeneratorCommand.GeneratorPageNext(FSelectCommand, FPageSize, FPageNext); FResultCommand := StringReplace(FResultCommand, '$', '%', [rfReplaceAll]); Result := FResultCommand; end; function TCommandSelecter.GenerateSelectID(const AClass: TClass; const AID: Variant): string; begin FPageNext := 0; FSelectCommand := FGeneratorCommand.GeneratorSelectAll(AClass, -1, AID); FResultCommand := FSelectCommand; Result := FResultCommand; end; function TCommandSelecter.GenerateNextPacket(const AClass: TClass; const APageSize, APageNext: Integer): string; begin FSelectCommand := FGeneratorCommand.GeneratorSelectAll(AClass, APageSize, -1); FResultCommand := FGeneratorCommand.GeneratorPageNext(FSelectCommand, APageSize, APageNext); Result := FResultCommand; end; function TCommandSelecter.GenerateNextPacket(const AClass: TClass; const AWhere, AOrderBy: String; const APageSize, APageNext: Integer): string; var LWhere: String; LCommandSelect: String; begin LWhere := StringReplace(AWhere,'%', '$', [rfReplaceAll]); LCommandSelect := FGeneratorCommand.GeneratorSelectWhere(AClass, LWhere, AOrderBy, APageSize); FResultCommand := FGeneratorCommand.GeneratorPageNext(LCommandSelect, APageSize, APageNext); FResultCommand := StringReplace(FResultCommand, '$', '%', [rfReplaceAll]); Result := FResultCommand; end; end.
{*********************************************************} { } { XML Data Binding } { } { Generated on: 25/06/2010 14:19:13 } { Generated from: C:\REP\ICM_Legend\ICMConfig.xml } { } {*********************************************************} unit ICMConfig; interface uses xmldom, XMLDoc, XMLIntf; type { Forward Decls } IXMLICMConfigType = interface; IXMLLegendEntriesType = interface; IXMLLegendEntryType = interface; IXMLGroupNamesType = interface; { IXMLICMConfigType } IXMLICMConfigType = interface(IXMLNode) ['{9BEDDA4E-97F7-4AC5-B43E-D1F990D22C7E}'] { Property Accessors } function Get_LegendEntries: IXMLLegendEntriesType; { Methods & Properties } property LegendEntries: IXMLLegendEntriesType read Get_LegendEntries; end; { IXMLLegendEntriesType } IXMLLegendEntriesType = interface(IXMLNodeCollection) ['{58D105A0-3EF2-4E97-9378-40A031992999}'] { Property Accessors } function Get_LegendEntry(Index: Integer): IXMLLegendEntryType; { Methods & Properties } function Add: IXMLLegendEntryType; function Insert(const Index: Integer): IXMLLegendEntryType; property LegendEntry[Index: Integer]: IXMLLegendEntryType read Get_LegendEntry; default; end; { IXMLLegendEntryType } IXMLLegendEntryType = interface(IXMLNode) ['{1C190970-9E4B-4F26-9CEE-A3CBC50C04BA}'] { Property Accessors } function Get_URL: WideString; function Get_LayoutItemName: WideString; function Get_Group_FieldName: WideString; function Get_Name_FieldName: WideString; function Get_Caption: WideString; function Get_GroupNames: IXMLGroupNamesType; procedure Set_LayoutItemName(Value: WideString); procedure Set_URL(Value: WideString); procedure Set_Group_FieldName(Value: WideString); procedure Set_Name_FieldName(Value: WideString); procedure Set_Caption(Value: WideString); { Methods & Properties } property LayoutItemName: WideString read Get_LayoutItemName write Set_LayoutItemName; property URL: WideString read Get_URL write Set_URL; property Group_FieldName: WideString read Get_Group_FieldName write Set_Group_FieldName; property Name_FieldName: WideString read Get_Name_FieldName write Set_Name_FieldName; property Caption: WideString read Get_Caption write Set_Caption; property GroupNames: IXMLGroupNamesType read Get_GroupNames; end; { IXMLGroupNamesType } IXMLGroupNamesType = interface(IXMLNodeCollection) ['{EE538099-4123-4341-BFE8-97C4C73896BE}'] { Property Accessors } function Get_Name(Index: Integer): WideString; { Methods & Properties } function Add(const Name: WideString): IXMLNode; function Insert(const Index: Integer; const Name: WideString): IXMLNode; property Name[Index: Integer]: WideString read Get_Name; default; end; { Forward Decls } TXMLICMConfigType = class; TXMLLegendEntriesType = class; TXMLLegendEntryType = class; TXMLGroupNamesType = class; { TXMLICMConfigType } TXMLICMConfigType = class(TXMLNode, IXMLICMConfigType) protected { IXMLICMConfigType } function Get_LegendEntries: IXMLLegendEntriesType; public procedure AfterConstruction; override; end; { TXMLLegendEntriesType } TXMLLegendEntriesType = class(TXMLNodeCollection, IXMLLegendEntriesType) protected { IXMLLegendEntriesType } function Get_LegendEntry(Index: Integer): IXMLLegendEntryType; function Add: IXMLLegendEntryType; function Insert(const Index: Integer): IXMLLegendEntryType; public procedure AfterConstruction; override; end; { TXMLLegendEntryType } TXMLLegendEntryType = class(TXMLNode, IXMLLegendEntryType) protected { IXMLLegendEntryType } function Get_LayoutItemName: WideString; function Get_URL: WideString; function Get_Group_FieldName: WideString; function Get_Name_FieldName: WideString; function Get_Caption: WideString; function Get_GroupNames: IXMLGroupNamesType; procedure Set_LayoutItemName(Value: WideString); procedure Set_URL(Value: WideString); procedure Set_Group_FieldName(Value: WideString); procedure Set_Name_FieldName(Value: WideString); procedure Set_Caption(Value: WideString); public procedure AfterConstruction; override; end; { TXMLGroupNamesType } TXMLGroupNamesType = class(TXMLNodeCollection, IXMLGroupNamesType) protected { IXMLGroupNamesType } function Get_Name(Index: Integer): WideString; function Add(const Name: WideString): IXMLNode; function Insert(const Index: Integer; const Name: WideString): IXMLNode; public procedure AfterConstruction; override; end; { Global Functions } function GetICMConfig(Doc: IXMLDocument): IXMLICMConfigType; function LoadICMConfig(const FileName: WideString): IXMLICMConfigType; function NewICMConfig: IXMLICMConfigType; const TargetNamespace = ''; implementation { Global Functions } function GetICMConfig(Doc: IXMLDocument): IXMLICMConfigType; begin Result := Doc.GetDocBinding('ICMConfig', TXMLICMConfigType, TargetNamespace) as IXMLICMConfigType; end; function LoadICMConfig(const FileName: WideString): IXMLICMConfigType; begin Result := LoadXMLDocument(FileName).GetDocBinding('ICMConfig', TXMLICMConfigType, TargetNamespace) as IXMLICMConfigType; end; function NewICMConfig: IXMLICMConfigType; begin Result := NewXMLDocument.GetDocBinding('ICMConfig', TXMLICMConfigType, TargetNamespace) as IXMLICMConfigType; end; { TXMLICMConfigType } procedure TXMLICMConfigType.AfterConstruction; begin RegisterChildNode('LegendEntries', TXMLLegendEntriesType); inherited; end; function TXMLICMConfigType.Get_LegendEntries: IXMLLegendEntriesType; begin Result := ChildNodes['LegendEntries'] as IXMLLegendEntriesType; end; { TXMLLegendEntriesType } procedure TXMLLegendEntriesType.AfterConstruction; begin RegisterChildNode('LegendEntry', TXMLLegendEntryType); ItemTag := 'LegendEntry'; ItemInterface := IXMLLegendEntryType; inherited; end; function TXMLLegendEntriesType.Get_LegendEntry(Index: Integer): IXMLLegendEntryType; begin Result := List[Index] as IXMLLegendEntryType; end; function TXMLLegendEntriesType.Add: IXMLLegendEntryType; begin Result := AddItem(-1) as IXMLLegendEntryType; end; function TXMLLegendEntriesType.Insert(const Index: Integer): IXMLLegendEntryType; begin Result := AddItem(Index) as IXMLLegendEntryType; end; { TXMLLegendEntryType } procedure TXMLLegendEntryType.AfterConstruction; begin RegisterChildNode('GroupNames', TXMLGroupNamesType); inherited; end; function TXMLLegendEntryType.Get_URL: WideString; begin Result := ChildNodes['URL'].Text; end; procedure TXMLLegendEntryType.Set_URL(Value: WideString); begin ChildNodes['URL'].NodeValue := Value; end; function TXMLLegendEntryType.Get_LayoutItemName: WideString; begin Result := ChildNodes['LayoutItemName'].Text; end; procedure TXMLLegendEntryType.Set_LayoutItemName(Value: WideString); begin ChildNodes['LayoutItemName'].NodeValue := Value; end; function TXMLLegendEntryType.Get_Group_FieldName: WideString; begin Result := ChildNodes['Group_FieldName'].Text; end; procedure TXMLLegendEntryType.Set_Group_FieldName(Value: WideString); begin ChildNodes['Group_FieldName'].NodeValue := Value; end; function TXMLLegendEntryType.Get_Name_FieldName: WideString; begin Result := ChildNodes['Name_FieldName'].Text; end; procedure TXMLLegendEntryType.Set_Name_FieldName(Value: WideString); begin ChildNodes['Name_FieldName'].NodeValue := Value; end; function TXMLLegendEntryType.Get_Caption: WideString; begin Result := ChildNodes['Caption'].Text; end; procedure TXMLLegendEntryType.Set_Caption(Value: WideString); begin ChildNodes['Caption'].NodeValue := Value; end; function TXMLLegendEntryType.Get_GroupNames: IXMLGroupNamesType; begin Result := ChildNodes['GroupNames'] as IXMLGroupNamesType; end; { TXMLGroupNamesType } procedure TXMLGroupNamesType.AfterConstruction; begin ItemTag := 'Name'; ItemInterface := IXMLNode; inherited; end; function TXMLGroupNamesType.Get_Name(Index: Integer): WideString; begin Result := List[Index].Text; end; function TXMLGroupNamesType.Add(const Name: WideString): IXMLNode; begin Result := AddItem(-1); Result.NodeValue := Name; end; function TXMLGroupNamesType.Insert(const Index: Integer; const Name: WideString): IXMLNode; begin Result := AddItem(Index); Result.NodeValue := Name; end; end.
unit PetrolRegionDataPoster; interface uses DBGate, BaseObjects, PersistentObjects; type TPetrolRegionDataPoster = class(TImplementedDataPoster) public function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; constructor Create; override; end; TNewPetrolRegionDataPoster = class(TImplementedDataPoster) public function GetFromDB(AFilter: string; AObjects: TIdObjects): integer; override; function PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; function DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; override; constructor Create; override; end; implementation uses PetrolRegion, DB, Facade, SysUtils; { TPetrolRegionDataPoster } constructor TPetrolRegionDataPoster.Create; begin inherited; Options := [soSingleDataSource, soGetKeyValue]; DataSourceString := 'tbl_petroliferous_region_dict'; KeyFieldNames := 'PETROL_REGION_ID'; FieldNames := 'PETROL_REGION_ID, VCH_REGION_FULL_NAME, VCH_REGION_SHORT_NAME, NUM_REGION_TYPE, MAIN_REGION_ID'; AccessoryFieldNames := 'PETROL_REGION_ID, VCH_REGION_FULL_NAME, VCH_REGION_SHORT_NAME, NUM_REGION_TYPE, MAIN_REGION_ID'; AutoFillDates := false; Sort := 'VCH_REGION_FULL_NAME'; end; function TPetrolRegionDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := 0; end; function TPetrolRegionDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; s: TPetrolRegion; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin s := AObjects.Add as TPetrolRegion; s.ID := ds.FieldByName('PETROL_REGION_ID').AsInteger; s.Name := trim(ds.FieldByName('VCH_REGION_FULL_NAME').AsString); s.ShortName := trim(ds.FieldByName('VCH_REGION_SHORT_NAME').AsString); s.MainPetrolRegionID := ds.FieldByName('MAIN_REGION_ID').AsInteger; case ds.FieldByName('NUM_REGION_TYPE').AsInteger of 1: s.RegionType := prtNGP; 2: s.RegionType := prtNGO; 3: s.RegionType := prtNGR; end; ds.Next; end; ds.First; end; end; function TPetrolRegionDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := 0; end; { TNewPetrolRegionDataPoster } constructor TNewPetrolRegionDataPoster.Create; begin inherited; Options := [soSingleDataSource, soGetKeyValue]; DataSourceString := 'TBL_NEW_PETROL_REGION_DICT'; KeyFieldNames := 'PETROL_REGION_ID'; FieldNames := 'PETROL_REGION_ID, VCH_REGION_FULL_NAME, NUM_REGION_TYPE, MAIN_REGION_ID, OLD_REGION_ID'; AccessoryFieldNames := 'PETROL_REGION_ID, VCH_REGION_FULL_NAME, NUM_REGION_TYPE, MAIN_REGION_ID, OLD_REGION_ID'; AutoFillDates := false; Sort := 'VCH_REGION_FULL_NAME'; end; function TNewPetrolRegionDataPoster.DeleteFromDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := 0; end; function TNewPetrolRegionDataPoster.GetFromDB(AFilter: string; AObjects: TIdObjects): integer; var ds: TDataSet; s: TNewPetrolRegion; begin Result := inherited GetFromDB(AFilter, AObjects); ds := TMainFacade.GetInstance.DBGates.Add(Self); if not ds.Eof then begin ds.First; while not ds.Eof do begin s := AObjects.Add as TNewPetrolRegion; s.ID := ds.FieldByName('PETROL_REGION_ID').AsInteger; s.Name := trim(ds.FieldByName('VCH_REGION_FULL_NAME').AsString); if not ds.FieldByName('MAIN_REGION_ID').IsNull then s.MainPetrolRegionID := ds.FieldByName('MAIN_REGION_ID').AsInteger else s.MainPetrolRegionID := -1; case ds.FieldByName('NUM_REGION_TYPE').AsInteger of 1: s.RegionType := prtNGP; 2: s.RegionType := prtNGO; 3: s.RegionType := prtNGR; end; ds.Next; end; ds.First; end; end; function TNewPetrolRegionDataPoster.PostToDB(AObject: TIDObject; ACollection: TIDObjects): integer; begin Result := 0; end; end.
unit MainFormU; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, Grids, DBGrids, DB, DBClient, NLDDataSetListener, StdCtrls; type TMainForm = class(TForm) ClientDataSet1: TClientDataSet; DataSource1: TDataSource; DBGrid1: TDBGrid; Memo1: TMemo; procedure ClientDataSet1BeforePost(DataSet: TDataSet); private FListener: TNLDFieldListener; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; end; var MainForm: TMainForm; implementation {$R *.dfm} { TForm4 } constructor TMainForm.Create(AOwner: TComponent); begin inherited; FListener := TNLDFieldListener.Create(nil); FListener.DataSource := DataSource1; FListener.DataField := 'Company'; end; destructor TMainForm.Destroy; begin FreeAndNil(FListener); inherited Destroy; end; procedure TMainForm.ClientDataSet1BeforePost(DataSet: TDataSet); begin Memo1.Lines.Add(FListener.OldValue) end; end.
unit fmID3; { -------------------------------------------------------------------------------- ID3 v1.1 record editor form -------------------------------------------------------------------------------- yyyy.mm.dd ini description 2003.08.23 cdt initial creation -------------------------------------------------------------------------------- } interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls, Spin, cmxMP3; type TfrmID3 = class(TForm) btnOK: TButton; bntCancel: TButton; edtTitle: TEdit; edtArtist: TEdit; edtAlbum: TEdit; edtComment: TEdit; lblTitle: TLabel; lblArtist: TLabel; lblAlbum: TLabel; lblComment: TLabel; speTrack: TSpinEdit; lblTrack: TLabel; speYear: TSpinEdit; lblYear: TLabel; cboGenre: TComboBox; lblGenre: TLabel; procedure FormShow(Sender: TObject); procedure bntCancelClick(Sender: TObject); procedure btnOKClick(Sender: TObject); private fMP3: TcmxMP3; public property MP3 : TcmxMP3 read fMP3 write fMP3; end; // TfrmID3 // accessor function function ShowID3(aMP3 : TcmxMP3) : TModalResult; implementation {$R *.dfm} //------------------------------------------------------------------------------ function ShowID3(aMP3 : TcmxMP3) : TModalResult; var frmID3 : TfrmID3; begin // create form frmID3 := TfrmID3.Create( nil ); try // pass MP3 object to work with frmID3.MP3 := aMP3; // show the form and return modeal result Result := frmID3.ShowModal; finally // release (free) the form frmID3.Release; end; // try finally end; // ShowID3 //------------------------------------------------------------------------------ procedure TfrmID3.FormShow(Sender: TObject); var i, intMax : integer; begin // fill dialog fields edtTitle.Text := MP3.Title; edtArtist.Text := MP3.Artist; edtAlbum.Text := MP3.Album; edtComment.Text := MP3.Comment; speYear.Value := StrToIntDef( MP3.Year,0 ); speTrack.Value := MP3.Track; // fill genre combo cboGenre.Clear; intMax := MP3.MaxGenreID; for i := 0 to intMax do begin cboGenre.Items.Add( MP3.GenreText[ i ] ); end; // for // set index value cboGenre.ItemIndex := MP3.GenreNdx; end; // FormShow //------------------------------------------------------------------------------ procedure TfrmID3.bntCancelClick(Sender: TObject); begin // return Cancel from ShowModal ModalResult := mrCancel; end; // bntCancelClick //------------------------------------------------------------------------------ procedure TfrmID3.btnOKClick(Sender: TObject); begin // call method to modify the ID3 record MP3.ChgID3( edtTitle.Text,edtArtist.Text,edtAlbum.Text,edtComment.Text ,speYear.Value,speTrack.Value,cboGenre.ItemIndex ); // return OK from ShowModal ModalResult := mrOK; end; // btnOKClick //------------------------------------------------------------------------------ end.
{******************************************************************************* Title: T2Ti ERP Description: VO relacionado à tabela [R06] The MIT License Copyright: Copyright (C) 2010 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 R06VO; interface uses VO, Atributos, Classes, Constantes, Generics.Collections, SysUtils, R07VO; type [TEntity] [TTable('ECF_R06')] TR06VO = class(TVO) private FID: Integer; FID_OPERADOR: Integer; FID_IMPRESSORA: Integer; FID_ECF_CAIXA: Integer; FSERIE_ECF: String; FCOO: Integer; FGNF: Integer; FGRG: Integer; FCDC: Integer; FDENOMINACAO: String; FDATA_EMISSAO: TDateTime; FHORA_EMISSAO: String; FLOGSS: String; FNOME_CAIXA: String; FID_GERADO_CAIXA: Integer; FDATA_SINCRONIZACAO: TDateTime; FHORA_SINCRONIZACAO: String; FListaR07VO: TObjectList<TR07VO>; public constructor Create; override; destructor Destroy; override; [TId('ID')] [TGeneratedValue(sAuto)] [TFormatter(ftZerosAEsquerda, taCenter)] property Id: Integer read FID write FID; [TColumn('ID_OPERADOR', 'Id Operador', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdOperador: Integer read FID_OPERADOR write FID_OPERADOR; [TColumn('ID_IMPRESSORA', 'Id Impressora', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdImpressora: Integer read FID_IMPRESSORA write FID_IMPRESSORA; [TColumn('ID_ECF_CAIXA', 'Id Ecf Caixa', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property IdEcfCaixa: Integer read FID_ECF_CAIXA write FID_ECF_CAIXA; [TColumn('SERIE_ECF', 'Serie Ecf', 160, [ldGrid, ldLookup, ldCombobox], False)] property SerieEcf: String read FSERIE_ECF write FSERIE_ECF; [TColumn('COO', 'Coo', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property Coo: Integer read FCOO write FCOO; [TColumn('GNF', 'Gnf', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property Gnf: Integer read FGNF write FGNF; [TColumn('GRG', 'Grg', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property Grg: Integer read FGRG write FGRG; [TColumn('CDC', 'Cdc', 80, [ldGrid, ldLookup, ldCombobox], False)] [TFormatter(ftZerosAEsquerda, taCenter)] property Cdc: Integer read FCDC write FCDC; [TColumn('DENOMINACAO', 'Denominacao', 16, [ldGrid, ldLookup, ldCombobox], False)] property Denominacao: String read FDENOMINACAO write FDENOMINACAO; [TColumn('DATA_EMISSAO', 'Data Emissao', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataEmissao: TDateTime read FDATA_EMISSAO write FDATA_EMISSAO; [TColumn('HORA_EMISSAO', 'Hora Emissao', 64, [ldGrid, ldLookup, ldCombobox], False)] property HoraEmissao: String read FHORA_EMISSAO write FHORA_EMISSAO; [TColumn('LOGSS', 'Log', 8, [], False)] property HashRegistro: String read FLOGSS write FLOGSS; [TColumn('NOME_CAIXA', 'Nome Caixa', 64, [ldGrid, ldLookup, ldCombobox], False)] property NomeCaixa: String read FNOME_CAIXA write FNOME_CAIXA; [TColumn('ID_GERADO_CAIXA', 'Id Gerado Caixa', 80, [ldGrid, ldLookup, ldCombobox], False)] property IdGeradoCaixa: Integer read FID_GERADO_CAIXA write FID_GERADO_CAIXA; [TColumn('DATA_SINCRONIZACAO', 'Data Sinronizacao', 80, [ldGrid, ldLookup, ldCombobox], False)] property DataSincronizacao: TDateTime read FDATA_SINCRONIZACAO write FDATA_SINCRONIZACAO; [TColumn('HORA_SINCRONIZACAO', 'Hora Sincronizacao', 64, [ldGrid, ldLookup, ldCombobox], False)] property HoraSincronizacao: String read FHORA_SINCRONIZACAO write FHORA_SINCRONIZACAO; [TManyValuedAssociation('ID_R06', 'ID')] property ListaR07VO: TObjectList<TR07VO> read FListaR07VO write FListaR07VO; end; implementation constructor TR06VO.Create; begin inherited; FListaR07VO := TObjectList<TR07VO>.Create; end; destructor TR06VO.Destroy; begin FreeAndNil(FListaR07VO); inherited; end; initialization Classes.RegisterClass(TR06VO); finalization Classes.UnRegisterClass(TR06VO); end.
unit cxVTEditors; interface uses Windows, SysUtils, Controls, VTEditors, VirtualTrees, cxEdit, cxTextEdit, cxDropDownEdit,cxCheckComboBox, cxLookAndFeelPainters; type TcxCustomEditLink = class(TCustomEditLink) end; TcxCustomTextEditLink = class(TcxCustomEditLink) protected function GetHookableWindowProc: TWndMethod; override; procedure SetHookableWindowProc(const Value: TWndMethod); override; procedure SetBounds(R: TRect); override; end; TcxTextEditLink = class(TcxCustomTextEditLink) protected {private} telProperties: TcxTextEditProperties; function telGetProperties: TcxTextEditProperties; procedure telSetProperties(const Value: TcxTextEditProperties); procedure KeyPress(Sender: TObject; var Key: Char); protected function CreateEditControl: TWinControl; override; function GetEditText: WideString; override; procedure SetEditText(const Value: WideString); override; procedure PrepareEditControl; override; function IsMultiLine: Boolean; override; procedure AfterBeginEdit; override; public destructor Destroy; override; published property Properties: TcxTextEditProperties read telGetProperties write telSetProperties; end; TcxCustomMaskEditLink = class(TcxCustomTextEditLink) end; TcxCustomDropDownEditLink = class(TcxCustomMaskEditLink) end; TcxCustomComboBoxLink = class(TcxCustomDropDownEditLink) end; TcxComboEditLink = class(TcxCustomComboBoxLink) protected {private} celProperties: TcxComboBoxProperties; function celGetProperties: TcxComboBoxProperties; procedure celSetProperties(const Value: TcxComboBoxProperties); procedure KeyPress(Sender: TObject; var Key: Char); protected function CreateEditControl: TWinControl; override; function GetEditText: WideString; override; procedure SetEditText(const Value: WideString); override; procedure PrepareEditControl; override; function IsMultiLine: Boolean; override; procedure AfterBeginEdit; override; public destructor Destroy; override; published property Properties: TcxComboBoxProperties read celGetProperties write celSetProperties; end; TcxCustomCheckComboBoxLink = class(TcxCustomComboBoxLink) end; TcxCheckComboEditLink = class(TcxCustomCheckComboBoxLink) protected {private} ccelProperties: TcxCheckComboBoxProperties; function ccelGetProperties: TcxCheckComboBoxProperties; procedure ccelSetProperties(const Value: TcxCheckComboBoxProperties); procedure KeyPress(Sender: TObject; var Key: Char); protected function CreateEditControl: TWinControl; override; function GetEditText: WideString; override; procedure SetEditText(const aValue: WideString); override; procedure PrepareEditControl; override; function IsMultiLine: Boolean; override; procedure AfterBeginEdit; override; public destructor Destroy; override; published property Properties: TcxCheckComboBoxProperties read ccelGetProperties write ccelSetProperties; end; implementation type TcxCustomEditHacker = class(TcxCustomEdit); TcxCustomTextEditHacker = class(TcxCustomTextEdit); { TcxComboEditLink } procedure TcxComboEditLink.AfterBeginEdit; begin inherited; TcxComboBox(EditControl).SelectAll; end; function TcxComboEditLink.celGetProperties: TcxComboBoxProperties; begin if not Assigned(celProperties) then celProperties := TcxComboBoxProperties.Create(Self); Result := celProperties; end; procedure TcxComboEditLink.celSetProperties(const Value: TcxComboBoxProperties); begin if not Assigned(celProperties) then celProperties := TcxComboBoxProperties.Create(Self); celGetProperties.Assign(Value); end; function TcxComboEditLink.CreateEditControl: TWinControl; begin Result := TcxComboBox.Create(nil, True); end; destructor TcxComboEditLink.Destroy; begin FreeAndNil(celProperties); inherited; end; function TcxComboEditLink.GetEditText: WideString; begin Result := TcxComboBox(EditControl).Text; end; function TcxComboEditLink.IsMultiLine: Boolean; begin Result := True; end; procedure TcxComboEditLink.KeyPress(Sender: TObject; var Key: Char); begin if Key in [#13, #27] then Key := #0; // Eliminate beep end; procedure TcxComboEditLink.PrepareEditControl; begin inherited; with TcxComboBox(EditControl) do begin if Assigned(celProperties) then Properties := celProperties; OnKeyPress := KeyPress; end; end; procedure TcxComboEditLink.SetEditText(const Value: WideString); begin TcxComboBox(EditControl).Text := Value; end; { TcxCustomTextEditLink } function TcxCustomTextEditLink.GetHookableWindowProc: TWndMethod; begin Result := TcxCustomTextEditHacker(EditControl).InnerTextEdit.Control.WindowProc end; procedure TcxCustomTextEditLink.SetBounds(R: TRect); begin if not FStopping then begin with R do begin // Set the edit's bounds but make sure there's a minimum width and the right border does not // extend beyond the parent's left/right border. Dec(Left, FTree.TextMargin); if Left < 0 then Left := 0; Dec(Right); if Right - Left < 30 then Right := Left + 30; if Right > FTree.ClientWidth then Right := FTree.ClientWidth; FEdit.BoundsRect := R; R.Left := FTree.TextMargin * 2; R.Top := -1; R.Right := 0; R.Bottom := 0; TcxCustomTextEditHacker(EditControl).ContentParams.Offsets := R; end; end; end; procedure TcxCustomTextEditLink.SetHookableWindowProc(const Value: TWndMethod); begin TcxCustomTextEditHacker(EditControl).InnerTextEdit.Control.WindowProc := Value; end; { TcxCheckComboEditLink } procedure TcxCheckComboEditLink.AfterBeginEdit; begin inherited; with TcxCheckComboBox(EditControl) do DroppedDown := True; end; function TcxCheckComboEditLink.ccelGetProperties: TcxCheckComboBoxProperties; begin if not Assigned(ccelProperties) then ccelProperties := TcxCheckComboBoxProperties.Create(Self); Result := ccelProperties; end; procedure TcxCheckComboEditLink.ccelSetProperties(const Value: TcxCheckComboBoxProperties); begin if not Assigned(ccelProperties) then ccelProperties := TcxCheckComboBoxProperties.Create(Self); ccelProperties.Assign(ccelProperties); end; function TcxCheckComboEditLink.CreateEditControl: TWinControl; begin Result := TcxCheckComboBox.Create(nil, True); end; destructor TcxCheckComboEditLink.Destroy; begin FreeAndNil(ccelProperties); inherited; end; function TcxCheckComboEditLink.GetEditText: WideString; var i : Integer; begin with TcxCheckComboBox(EditControl) do begin Result := StringOfChar('0', Properties.Items.Count); for i := 0 to Pred(Properties.Items.Count) do if States[i] = cbsChecked then Result[Succ(i)] := '1'; end; end; function TcxCheckComboEditLink.IsMultiLine: Boolean; begin Result := True; end; procedure TcxCheckComboEditLink.KeyPress(Sender: TObject; var Key: Char); begin if Key in [#13, #27] then Key := #0; // Eliminate beep end; procedure TcxCheckComboEditLink.PrepareEditControl; begin inherited; with TcxCheckComboBox(EditControl) do begin if Assigned(ccelProperties) then Properties := ccelProperties; OnKeyPress := KeyPress; end; end; procedure TcxCheckComboEditLink.SetEditText(const aValue: WideString); var i : Integer; begin with TcxCheckComboBox(EditControl) do for i := 0 to Pred(Properties.Items.Count) do if (Succ(i) <= Length(aValue)) and (aValue[Succ(i)] = '1') then States[i] := cbsChecked else States[i] := cbsUnchecked; end; { TcxTextEditLink } procedure TcxTextEditLink.AfterBeginEdit; begin inherited; TcxTextEdit(EditControl).SelectAll; end; function TcxTextEditLink.CreateEditControl: TWinControl; begin Result := TcxTextEdit.Create(nil, True); end; destructor TcxTextEditLink.Destroy; begin FreeAndNil(telProperties); inherited; end; function TcxTextEditLink.GetEditText: WideString; begin Result := TcxTextEdit(EditControl).Text; end; function TcxTextEditLink.IsMultiLine: Boolean; begin Result := True; end; procedure TcxTextEditLink.KeyPress(Sender: TObject; var Key: Char); begin if Key in [#13, #27] then Key := #0; // Eliminate beep end; procedure TcxTextEditLink.PrepareEditControl; begin inherited; with TcxTextEdit(EditControl) do begin if Assigned(telProperties) then Properties := telProperties; OnKeyPress := KeyPress; end; end; procedure TcxTextEditLink.SetEditText(const Value: WideString); begin TcxTextEdit(EditControl).Text := Value; end; function TcxTextEditLink.telGetProperties: TcxTextEditProperties; begin if not Assigned(telProperties) then telProperties := TcxTextEditProperties.Create(Self); Result := telProperties; end; procedure TcxTextEditLink.telSetProperties(const Value: TcxTextEditProperties); begin if not Assigned(telProperties) then telProperties := TcxTextEditProperties.Create(Self); telGetProperties.Assign(Value); end; end.
{*******************************************************} { } { NTS Aero UI Library } { Created by GooD-NTS ( good.nts@gmail.com ) } { http://ntscorp.ru/ Copyright(c) 2011 } { License: Mozilla Public License 1.1 } { } {*******************************************************} unit UI.Aero.RecentList; interface {$I '../../Common/CompilerVersion.Inc'} uses {$IFDEF HAS_UNITSCOPE} System.SysUtils, System.Classes, Winapi.Windows, Winapi.Messages, Winapi.UxTheme, Winapi.GDIPOBJ, Vcl.Graphics, Vcl.Controls, Vcl.Imaging.pngimage, {$ELSE} Windows, Messages, SysUtils, Classes, Controls, Graphics, Winapi.GDIPOBJ, Themes, UxTheme, PNGImage, {$ENDIF} NTS.Code.Common.Types, UI.Aero.Core.CustomControl, UI.Aero.Globals, UI.Aero.Core.BaseControl; type TItemHoverState = (hsNone, hsFull, hsButton); TAeroRecentList = class; TRecentListCollection = class; TRecentListItem = class(TCollectionItem) private fFileName: String; fName: TCaption; fHover: TItemHoverState; fIsPin: BooLean; fEnabled: BooLean; procedure SetHover(const Value: TItemHoverState); procedure SetIsPin(const Value: BooLean); procedure SetName(const Value: TCaption); procedure SetEnabled(const Value: BooLean); Public Constructor Create(Collection: TCollection); OverRide; procedure Pin; procedure UnPin; Published Property Name: TCaption Read fName Write SetName; Property Hover: TItemHoverState Read fHover Write SetHover Default hsNone; Property FileName: String Read fFileName Write fFileName; Property IsPin: BooLean Read fIsPin Write SetIsPin; Property Enabled: BooLean Read fEnabled Write SetEnabled; end; TRecentListCollection = class(TCollection) Private fOwner: TAeroRecentList; function GetItem(Index: Integer): TRecentListItem; procedure SetItem(Index: Integer; const Value: TRecentListItem); Public Constructor Create(AOwner: TAeroRecentList); Virtual; Function Owner: TAeroRecentList; function Add: TRecentListItem; OverLoad; function Add(AFileName: String;AIsPin: Boolean = False): TRecentListItem; OverLoad; Property Items[Index: Integer]: TRecentListItem read GetItem write SetItem; default; end; TItemClickArea = ( caBody, caFolder, caPin ); TItemClickEvent = procedure (Sender: TAeroRecentList; Index: Integer; ClickArea: TItemClickArea) of Object; TAeroRecentList = Class(TAeroBaseControl) public class var ImageFile_Pin: String; public class var ImageFile_UnPin: String; public class var ImageFile_Backgound: String; public class var ImageFile_Folder: String; private class constructor Create; Private fItems: TRecentListCollection; fHoverItem: Integer; IsPinHover: BooLean; IsFolderHover: Boolean; imgPin: TPNGImage; imgUnPin: TPNGImage; imgFolder: TPNGImage; bgIMg: TPNGImage; fItemClick: TItemClickEvent; fStateId: Integer; fCurrentIndex: Integer; procedure SetItems(const Value: TRecentListCollection); Protected function GetThemeClassName: PWideChar; OverRide; procedure RenderProcedure_Vista(const ACanvas: TCanvas); OverRide; procedure RenderProcedure_XP(const ACanvas: TCanvas); OverRide; procedure DrawItem(const ACanvas: TCanvas;Item: TRecentListItem;ItemTop: Integer); procedure MouseMove(Shift: TShiftState; X: Integer; Y: Integer); OverRide; procedure Click; override; procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; procedure WMContextMenu(var Message: TWMContextMenu); message WM_CONTEXTMENU; function GetClientRect: TRect; override; Public Constructor Create(AOwner: TComponent); OverRide; Destructor Destroy; OverRide; function CurrentIndex: Integer; Published property Caption; property Hint; property Color Default clWhite; property Items: TRecentListCollection Read fItems Write SetItems; property OnItemClick: TItemClickEvent Read fItemClick Write fItemClick; End; implementation uses UI.Aero.Core, Math; { TRecentListItem } Constructor TRecentListItem.Create(Collection: TCollection); begin Inherited Create(Collection); fEnabled:= True; fName:= 'RecentListItem'+IntToStr(Index); end; procedure TRecentListItem.Pin; begin end; procedure TRecentListItem.UnPin; begin end; procedure TRecentListItem.SetEnabled(const Value: BooLean); begin fEnabled:= Value; end; procedure TRecentListItem.SetHover(const Value: TItemHoverState); begin fHover:= Value; end; procedure TRecentListItem.SetIsPin(const Value: BooLean); begin fIsPin:= Value; end; procedure TRecentListItem.SetName(const Value: TCaption); begin fName:= Value; end; { TRecentListCollection } Constructor TRecentListCollection.Create(AOwner: TAeroRecentList); begin Inherited Create(TRecentListItem); fOwner:= AOwner; end; function TRecentListCollection.Owner: TAeroRecentList; begin Result:= fOwner; end; function TRecentListCollection.Add: TRecentListItem; begin Result:= TRecentListItem(Inherited Add); end; function TRecentListCollection.Add(AFileName: String; AIsPin: Boolean): TRecentListItem; begin Result:= Add; Result.fFileName:= AFileName; Result.fName:= ExtractFileName(AFileName); Result.fIsPin:= AIsPin; end; function TRecentListCollection.GetItem(Index: Integer): TRecentListItem; begin Result:= TRecentListItem(Inherited GetItem(Index)); end; procedure TRecentListCollection.SetItem(Index: Integer; const Value: TRecentListItem); begin Inherited SetItem(Index, Value); end; { TAeroRecentList } class constructor TAeroRecentList.Create; begin if Assigned(RegisterComponentsProc) then begin TAeroRecentList.ImageFile_Pin:= GetEnvironmentVariable('NTS_LIB_ROOT')+'\NTS UI Aero\Resources\Images\pin.png'; TAeroRecentList.ImageFile_UnPin:= GetEnvironmentVariable('NTS_LIB_ROOT')+'\NTS UI Aero\Resources\Images\unpin.png'; TAeroRecentList.ImageFile_Backgound:= GetEnvironmentVariable('NTS_LIB_ROOT')+'\NTS UI Aero\Resources\Images\menu_bg.png'; TAeroRecentList.ImageFile_Folder:= GetEnvironmentVariable('NTS_LIB_ROOT')+'\NTS UI Aero\Resources\Images\folder.png'; end else begin TAeroRecentList.ImageFile_Pin:= '???ERROR_PATH***'; TAeroRecentList.ImageFile_UnPin:= '???ERROR_PATH***'; TAeroRecentList.ImageFile_Backgound:= '???ERROR_PATH***'; TAeroRecentList.ImageFile_Folder:= '???ERROR_PATH***'; end; end; constructor TAeroRecentList.Create(AOwner: TComponent); begin inherited Create(AOwner); fItemClick:= nil; imgPin := TPNGImage.Create; imgPin.LoadFromFile(TAeroRecentList.ImageFile_Pin); imgUnPin := TPNGImage.Create; imgUnPin.LoadFromFile(TAeroRecentList.ImageFile_UnPin); imgFolder := TPNGImage.Create; imgFolder.LoadFromFile(TAeroRecentList.ImageFile_Folder); bgIMg := TPNGImage.Create; if (TAeroRecentList.ImageFile_Backgound <> '') and FileExists(TAeroRecentList.ImageFile_Backgound) then bgIMg.LoadFromFile(TAeroRecentList.ImageFile_Backgound); Color := clWhite; fItems := TRecentListCollection.Create(Self); fHoverItem := -1; IsPinHover := False; IsFolderHover := False; fStateId := LIS_SELECTED; fCurrentIndex:= -1; end; function TAeroRecentList.CurrentIndex: Integer; begin Result:= fCurrentIndex; end; Destructor TAeroRecentList.Destroy; begin bgIMg.Free; imgPin.Free; imgUnPin.Free; imgFolder.Free; fItems.Free; Inherited Destroy; end; function TAeroRecentList.GetClientRect(): TRect; begin Result:= Inherited GetClientRect(); Result.Left:= Result.Left+8; Result.Right:= Result.Right-8; end; function TAeroRecentList.GetThemeClassName: PWideChar; begin if AeroCore.RunWindowsVista then Result:= 'Explorer::ListView' else Result:= VSCLASS_LISTVIEW; end; procedure TAeroRecentList.Click; begin Inherited Click; if (fHoverItem <> -1) then begin if IsPinHover then begin Items[fHoverItem].fIsPin:= not Items[fHoverItem].fIsPin; Invalidate; if Assigned(fItemClick) then fItemClick(Self,fHoverItem,caPin); end else if IsFolderHover then begin if Assigned(fItemClick) and Items[fHoverItem].Enabled then fItemClick(Self,fHoverItem,caFolder); end else if Assigned(fItemClick) and Items[fHoverItem].Enabled then fItemClick(Self,fHoverItem,caBody); end; end; procedure TAeroRecentList.CMMouseLeave(var Message: TMessage); begin Inherited; if fStateId = LIS_SELECTED then begin fHoverItem:= -1; IsPinHover:= False; IsFolderHover:= False; Invalidate; end; end; procedure TAeroRecentList.MouseMove(Shift: TShiftState; X, Y: Integer); var OldIsPinHover: Boolean; OldHoverItem, Temp: Integer; // OldIsFolderHover: Boolean; begin Inherited MouseMove(Shift,X,Y); OldHoverItem:= fHoverItem; OldIsPinHover:= IsPinHover; OldIsFolderHover:= IsFolderHover; IsPinHover:= InRange(X,ClientWidth-32,ClientWidth); IsFolderHover:= InRange(X,ClientWidth-64,ClientWidth-32); if Y <= 24 then fHoverItem:= -1 else begin Temp:= (Y-24) div 21; if Temp < Items.Count then fHoverItem:= Temp else fHoverItem:= -1; end; if (OldHoverItem <> fHoverItem) or (OldIsPinHover <> IsPinHover) or (IsFolderHover <> OldIsFolderHover) then Invalidate; end; procedure TAeroRecentList.RenderProcedure_XP(const ACanvas: TCanvas); begin RenderProcedure_Vista(ACanvas); end; procedure TAeroRecentList.RenderProcedure_Vista(const ACanvas: TCanvas); const capFormat = (DT_LEFT OR DT_VCENTER OR DT_SINGLELINE); verFormat = (DT_RIGHT OR DT_VCENTER OR DT_SINGLELINE); procedure BevelLine(C: TColor; X1, Y1, X2, Y2: Integer); begin with ACanvas do begin Pen.Color:= C; MoveTo(X1, Y1); LineTo(X2, Y2); end; end; var I, ItemTop: Integer; OldBkMode: integer; capRect: TRect; begin ACanvas.Brush.Color:= Self.Color; ACanvas.FillRect( Rect(0,0,Width,Height) ); ACanvas.Draw(-(bgIMg.Width-Self.Width),Self.Height-bgIMg.Height,bgIMg); ACanvas.Font.Color:= clNavy; ACanvas.Font.Style:= [fsBold]; capRect:= ClientRect; capRect:= Bounds(capRect.Left+8,capRect.Top+0,ClientWidth,20); OldBkMode:= SetBkMode(ACanvas.Handle,1); DrawText(ACanvas.Handle,PChar(Caption),-1,capRect,capFormat); SetBkMode(ACanvas.Handle,OldBkMode); // ACanvas.Font.Color:= clBlack; ACanvas.Font.Style:= []; capRect:= ClientRect; capRect:= Bounds(0,0,ClientWidth,20); OldBkMode:= SetBkMode(ACanvas.Handle,1); DrawText(ACanvas.Handle,PChar(Hint),-1,capRect,verFormat); SetBkMode(ACanvas.Handle,OldBkMode); // capRect:= ClientRect; BevelLine(clBtnShadow, capRect.Left, capRect.Top+20, ClientWidth, 20); BevelLine(cl3DLight, capRect.Left, capRect.Top+21, ClientWidth, 21); ItemTop:= 24; for I:=0 to fItems.Count-1 do begin DrawItem(ACanvas, fItems[I], ItemTop); ItemTop:= ItemTop+21; end; end; procedure TAeroRecentList.DrawItem(const ACanvas: TCanvas; Item: TRecentListItem;ItemTop: Integer); const capFormat = (DT_LEFT OR DT_VCENTER OR DT_SINGLELINE); pathFormat = (DT_LEFT OR DT_VCENTER OR DT_SINGLELINE OR DT_PATH_ELLIPSIS); var OldBkMode: integer; itRect: TRect; begin if fHoverItem = Item.Index then begin if IsPinHover then itRect:= Bounds(ClientWidth-32,ItemTop,32,21) else if IsFolderHover then itRect:= Bounds(ClientWidth-64,ItemTop,32,21) else if Item.Enabled then itRect:= Bounds(ClientRect.Left,ItemTop,ClientWidth-8,21) else itRect:= Bounds(0,0,0,0); DrawThemeBackground(ThemeData,ACanvas.Handle,LVP_LISTITEM,fStateId,itRect,nil); end; if Item.Enabled then ACanvas.Font.Color:= clBlack else ACanvas.Font.Color:= clSilver; ACanvas.Font.Style:= []; if Item.Index <= 8 then begin ACanvas.Font.Style:= [fsUnderline]; itRect:= Bounds(ClientRect.Left+8,ItemTop,22,21); OldBkMode:= SetBkMode(ACanvas.Handle,1); DrawText(ACanvas.Handle,PChar(IntToStr(Item.Index+1)),-1,itRect,capFormat); SetBkMode(ACanvas.Handle,OldBkMode); ACanvas.Font.Style:= []; itRect:= Bounds(ClientRect.Left+22,ItemTop,ClientWidth-94,21); end else itRect:= Bounds(ClientRect.Left+22,ItemTop,ClientWidth-94,21); OldBkMode:= SetBkMode(ACanvas.Handle,1); DrawText(ACanvas.Handle,PChar(Item.Name),-1,itRect,capFormat); SetBkMode(ACanvas.Handle,OldBkMode); itRect.Left:= itRect.Left+ACanvas.TextExtent(Item.Name).cx+4; if Item.fIsPin then ACanvas.Draw(ClientWidth-24,ItemTop+2,imgUnPin) else ACanvas.Draw(ClientWidth-24,ItemTop+2,imgPin); // Folders path UI 2010 if (fHoverItem = Item.Index) then begin ACanvas.Draw(ClientWidth-56,ItemTop+2,imgFolder); end; ACanvas.Font.Style:= []; if (fHoverItem = Item.Index) and not IsPinHover then begin if IsFolderHover then ACanvas.Font.Color:= clMaroon else ACanvas.Font.Color:= clNavy end else ACanvas.Font.Color:= clSilver; OldBkMode:= SetBkMode(ACanvas.Handle,1); DrawText(ACanvas.Handle,PChar('('+ExtractFilePath(Item.fFileName)+')'),-1,itRect,pathFormat); SetBkMode(ACanvas.Handle,OldBkMode); end; procedure TAeroRecentList.SetItems(const Value: TRecentListCollection); begin fItems:= Value; end; procedure TAeroRecentList.WMContextMenu(var Message: TWMContextMenu); begin if (fHoverItem <> -1) and not IsPinHover and not IsFolderHover then begin fStateId:= LIS_SELECTEDNOTFOCUS; Invalidate; fCurrentIndex:= fHoverItem; Inherited; fStateId:= LIS_SELECTED; Invalidate; MouseMove([],Message.XPos,Message.YPos); end; end; end.
unit LuaDebug; {This unit will hold the debug_ specific lua functions, not related to lua debugging} {$mode delphi} interface uses Classes, SysUtils, newkernelhandler, debug, DebugHelper, DebuggerInterfaceAPIWrapper, lua, lualib, lauxlib, LuaHandler{$ifdef darwin},macport{$endif}; procedure initializeLuaDebug; implementation function debug_setLastBranchRecording(L: PLua_State): integer; cdecl; var parameters: integer; newstate: boolean; begin OutputDebugString('debug_setLastBranchRecording'); result:=0; parameters:=lua_gettop(L); {$ifdef windows} if parameters=1 then begin newstate:=lua_toboolean(L, -1); DBKDebug_SetStoreLBR(newstate); end; {$endif} lua_pop(L, parameters); end; function debug_getMaxLastBranchRecord(L: PLua_State): integer; cdecl; var max: integer; begin result:=1; if CurrentDebuggerInterface<>nil then max:=CurrentDebuggerInterface.GetLastBranchRecords(nil) else max:=-1; lua_pop(L, lua_gettop(L)); lua_pushinteger(L, max); end; function debug_getLastBranchRecord(L: PLua_State): integer; cdecl; type TQwordArray=array [0..0] of qword; PQwordArray=^Tqwordarray; var parameters: integer; value: ptruint; max: integer; index: integer; lbrbuf: PQwordArray; begin result:=0; parameters:=lua_gettop(L); if parameters=1 then begin index:=lua_tointeger(L, -1); lua_pop(L, parameters); if CurrentDebuggerInterface<>nil then begin max:=CurrentDebuggerInterface.GetLastBranchRecords(nil); getmem(lbrbuf, max*sizeof(qword)); try max:=CurrentDebuggerInterface.GetLastBranchRecords(lbrbuf); if index<=max then lua_pushinteger(L, lbrbuf[index]); result:=1; finally FreeMemAndNil(lbrbuf); end; end; end else lua_pop(L, parameters); end; function debug_getXMMPointer(L: PLua_State): integer; cdecl; var c: ptruint; xmmreg: integer; parameters: integer; begin result:=1; c:=0; parameters:=lua_gettop(L); if parameters=1 then begin xmmreg:=lua_tointeger(L, -1); if (debuggerthread<>nil) and (debuggerthread.CurrentThread<>nil) then c:=ptruint(@debuggerthread.CurrentThread.context.{$ifdef cpu64}FltSave.{$else}ext.{$endif}XmmRegisters[xmmreg]); end; lua_pop(L, lua_gettop(L)); lua_pushinteger(L, c); end; procedure initializeLuaDebug; begin lua_register(LuaVM, 'debug_setLastBranchRecording', debug_setLastBranchRecording); lua_register(LuaVM, 'debug_getMaxLastBranchRecord', debug_getMaxLastBranchRecord); lua_register(LuaVM, 'debug_getLastBranchRecord', debug_getLastBranchRecord); lua_register(LuaVM, 'debug_getXMMPointer', debug_getXMMPointer); end; end.
unit DataUnit; interface uses System.Classes, System.ImageList, FMX.Controls, FMX.ImgList, FMX.Types; type TDataForm = class(TDataModule) Museum: TImageList; Backgrounds: TImageList; Icons: TImageList; Sequence: TImageList; Other: TImageList; Images: TImageList; Switchers: TImageList; progress: TImageList; procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); end; var DataForm: TDataForm; Styles:TStyleBook; implementation {%CLASSGROUP 'FMX.Controls.TControl'} {$R *.dfm} uses System.SysUtils, System.IOUtils, windows, FMX.Ani, FMX.Forms, FMX.Dialogs, FMX.Styles, ImageManager, GameData, DesignManager, TextManager, SoundManager, ResourcesManager, winMessages, uLoading; const fName = 'TkachenkoSketch4F.ttf'; procedure TDataForm.DataModuleCreate(Sender: TObject); var f: TLoadingForm; begin f:=TLoadingForm.Create(self); f.Show; try f.setCount(6, 'Initialization'); GD:=TGameData.Create; DM:=TDesignManager.Create; IM:=TImageManager.Create; SM:=TSoundManager.Create; TM:=TTextManager.Create; f.up('Loading: Museum'); IM.add(rMuseum); f.up('Loading: Sequences'); IM.add(rSequences); f.up('Loading: Switchers'); IM.add(rSwitchers); f.up('Loading: Images'); IM.add(rImages); f.up('Loading: Other'); IM.add(rOther); finally f.Close; end; end; procedure TDataForm.DataModuleDestroy(Sender: TObject); begin GD.LoadSavedRamp; DM.Free; IM.Free; GD.Free; SM.Free; TM.Free; RemoveFontResourceEx(PChar(TPath.Combine(getPath(pTexts), fName)), FR_NOT_ENUM, nil); sendMsg(cClose, 'Done.'); end; end.
{******************************************************} { rsFlyOverButton V1.3 } { Copyright 1997 RealSoft Development } { support: www.realsoftdev.com } {******************************************************} unit rsFlyovr; interface {$I REALSOFT.INC} uses SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls, Forms, Dialogs, Extctrls, Buttons, Menus, stdctrls ; type TButtonState = (bsActive, bsInActive, bsDisabled, bsDown, bsGroupDown); TFOBOption = (foAutoPopMenu, foAutoClear, foAutoSize, foTransparent, foAlwaysActive, foGroupAllowUp, foCancel, foDefault, foDrawBorder, foDrawDown, foAutoHoldDown, foBlackLine); TFOBOptions = set of TFOBOption; {$IFDEF WIN32} {$WARNINGS OFF} {$ENDIF} TrsFlyOverButton = class(TGraphicControl) private FState : TButtonState; FOptions : TFOBOptions; FGlyphA : TBitmap; FGlyphI : TBitmap; FGlyphD : TBitmap; FLayout : TButtonLayout; FSpacing : smallint; FMargin : smallint; FTimer : TTimer; FGroupID : smallint; FModalRes : TModalResult; FPopped : Boolean; FMouseIn : boolean; FOnFlyOver : TNotifyEvent; FOnPopup : TNotifyEvent; FOnHoldDown : TNotifyEvent; FButFocus : TButton ; procedure SetGlyph(Index: integer; AValue : TBitmap); procedure SetLayout(AValue: TButtonLayout); procedure SetSpacing(AValue: smallint); procedure SetMargin(AValue: smallint); procedure SetGroupID (AValue: smallint); procedure SetOptions (AValue: TFOBOptions); procedure SetState (AValue: TButtonState); function ValidGlyph(C : char) : TBitmap; procedure CalcRect(var ImgRect : TRect; var TxtRect : TRect); procedure DrawButton(ACanvas: TCanvas); procedure DrawFrame(Down: Boolean); procedure ClearFrame; procedure TimerFlag(Sender: TObject); protected procedure Paint; override; procedure Loaded; override; procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER; procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE; procedure WMLButtonDown(var Message: TWMLButtonDown); message WM_LBUTTONDOWN; procedure WMLButtonUp(var Message: TWMLButtonUp); message WM_LBUTTONUP; procedure CMDialogKey(var Message: TCMDialogKey); message CM_DIALOGKEY; procedure CMDialogChar(var Message: TCMDialogChar); message CM_DIALOGCHAR; procedure CMTextChanged(var Message: TMessage); message CM_TEXTCHANGED; procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; procedure Invalidate; override; procedure Click; override; procedure Down; procedure Popup; property State : TButtonState read FState write SetState; published property Options : TFOBOptions read FOptions write SetOptions; property GlyphActive : TBitmap index 1 read FGlyphA write SetGlyph; property GlyphInActive : TBitmap index 2 read FGlyphI write SetGlyph; property GlyphDisabled : TBitmap index 3 read FGlyphD write SetGlyph; property Spacing : smallint read FSpacing write SetSpacing default 2; property Margin : smallint read FMargin write SetMargin default 2; property Layout : TButtonLayout read FLayout write SetLayout default blGlyphTop; property GroupID : smallint read FGroupID write SetGroupID default 0; property ModalResult : TModalResult read FModalRes write FModalRes default mrNone; property Caption; property PopUpMenu; property Color; property Font; property Enabled; property ParentFont; property ParentShowHint; property ShowHint; property Hint; property Visible; property OnClick; property OnDblClick; property OnMouseDown; property OnMouseMove; property OnMouseUp; property OnFlyOver : TNotifyEvent read FOnFlyOver write FOnFlyOver; property OnPopup : TNotifyEvent read FOnPopup write FOnPopup; property OnHoldDown : TNotifyEvent read FOnHoldDown write FOnHoldDown; end; {$IFDEF WIN32} {$WARNINGS ON} {$ENDIF} procedure Register; implementation Uses RSEdit ; procedure Register; begin RegisterComponents('RSD', [TrsFlyOverButton]); end; {$IFDEF DEMO} function DelphiRunning : boolean; begin if((FindWindow('TApplication','Delphi') = 0) and (FindWindow('TApplication','Delphi 2.0') = 0) and (FindWindow('TApplication','Delphi 3') = 0) and (FindWindow('TApplication','Delphi 4') = 0)) or (FindWindow('TPropertyInspector',nil) = 0) or (FindWindow('TAppBuilder',nil) = 0) then result:= false else result:= true; end; {$ENDIF} function UnAccel(S: String) : String; var S2: string; x: smallint; begin S2:= ''; for x:= 1 to Length(S) do if (x<Length(S)) and ((S[x]='&') and (S[x+1]='&')) or (S[x]<>'&') then S2:= S2 + S[x]; result:= S2; end; procedure DrawTrans(DestCanvas: TCanvas; X,Y: smallint; SrcBitmap: TBitmap; AColor: TColor); var ANDBitmap, ORBitmap: TBitmap; CM: TCopyMode; Src: TRect; begin ANDBitmap:= nil; ORBitmap:= nil; try ANDBitmap:= TBitmap.Create; ORBitmap:= TBitmap.Create; Src := Bounds(0,0, SrcBitmap.Width, SrcBitmap.Height); with ORBitmap do begin Width:= SrcBitmap.Width; Height:= SrcBitmap.Height; Canvas.Brush.Color := clBlack; Canvas.CopyMode := cmSrcCopy; Canvas.BrushCopy(Src, SrcBitmap, Src, AColor); end; with ANDBitmap do begin Width:= SrcBitmap.Width; Height:= SrcBitmap.Height; Canvas.Brush.Color := clWhite; Canvas.CopyMode := cmSrcInvert; Canvas.BrushCopy(Src, SrcBitmap, Src, AColor); end; with DestCanvas do begin CM := CopyMode; CopyMode := cmSrcAnd; Draw(X,Y, ANDBitmap); CopyMode := cmSrcPaint; Draw(X,Y, ORBitmap); CopyMode := CM; end; finally ANDBitmap.Free; ORBitmap.Free; end; end; constructor TrsFlyOverButton.Create(AOwner: TComponent); begin inherited Create(AOwner); ControlStyle := [csClickEvents, csCaptureMouse, csSetCaption]; FGlyphA := TBitmap.Create; FGlyphI := TBitmap.Create; FGlyphD := TBitmap.Create; FState := bsInActive; Width := 50; Height := 40; Color := clBtnFace; FSpacing := 2; FMargin := 2; FLayout := blGlyphTop; FOptions := [foAutoClear, foGroupAllowUp, foTransparent, foDrawBorder, foDrawDown, foAutoPopmenu]; FGroupID:= 0; FTimer:= NIL; FModalRes:= mrNone; FButFocus := TButton.Create(Self) ; FButFocus.Parent := TWinControl(AOwner) ; FButFocus.Left := Left ; FButFocus.Top := Top ; FButFocus.Width := 1 ; FButFocus.Height := 1 ; end; destructor TrsFlyOverButton.Destroy; begin FGlyphA.Free; FGlyphI.Free; FGlyphD.Free; if FTimer <> NIL then begin FTimer.Free; FTimer:= NIL; end; inherited Destroy; end; procedure TrsFlyOverButton.Loaded; begin inherited Loaded; {$IFDEF DEMO} if not DelphiRunning then {for trial version only} showmessage('This program is using an unregistered copy of the TrsFlyOverButton' + #13 + 'component from RealSoft. Please register at www.realsoftdev.com' + #13 + 'or call (949) 831-7879.'); {$ENDIF} end; procedure TrsFlyOverButton.Invalidate; begin if not FGlyphA.Empty then ControlStyle:= ControlStyle - [csOpaque]; inherited Invalidate; end; procedure TrsFlyOverButton.Paint; begin if (not Visible) and (not (csDesigning in Componentstate)) then begin inherited Paint; Exit; end; with inherited Canvas do begin if (csDesigning in ComponentState) then begin DrawFrame(false); end; {if not enabled, change state before painting} if (not Enabled) or (not Parent.Enabled) then FState:= bsDisabled else if FState = bsDisabled then FState:= bsInActive; {fix state} if (not FMousein) and (not FPopped) and (foAlwaysActive in FOptions) and (Enabled) and (Parent.Enabled) and (FState <> bsGroupDown) then FState:= bsInActive; DrawButton(Canvas); end; end; function TrsFlyOverButton.ValidGlyph(C : char) : TBitmap; begin Result:= FGlyphA; if not (foAutoClear in FOptions) then Exit; case C of 'I': if not FGlyphI.Empty then Result:= FGlyphI; 'D': if not FGlyphD.Empty then Result:= FGlyphD; end; end; procedure TrsFlyOverButton.CalcRect(var ImgRect : TRect; var TxtRect : TRect); var IH, IW, TH, TW : smallint; begin IH:= ImgRect.Bottom - ImgRect.Top; IW:= ImgRect.Right - ImgRect.Left; TH:= TxtRect.Bottom - TxtRect.Top; TW:= TxtRect.Right - TxtRect.Left; case FLayout of blGlyphTop: begin ImgRect.Left:= (Width - IW) div 2; ImgRect.Right:= ImgRect.Left + IW; ImgRect.Top:= FMargin; ImgRect.Bottom:= ImgRect.Top + IH; TxtRect.Left:= (Width - TW) div 2; TxtRect.Right:= TxtRect.Left + TW; if IH > 0 then TxtRect.Top:= ImgRect.Bottom + FSpacing else TxtRect.Top:= (Height - TH) div 2; TxtRect.Bottom:= TxtRect.Top + TH; end; blGlyphBottom: begin ImgRect.Left:= (Width - IW) div 2; ImgRect.Right:= ImgRect.Left + IW; ImgRect.Top:= Height - (FMargin + IH); ImgRect.Bottom:= ImgRect.Top + IH; TxtRect.Left:= (Width - TW) div 2; TxtRect.Right:= TxtRect.Left + TW; if IH > 0 then TxtRect.Top:= ImgRect.Top - (FSpacing + TH) else TxtRect.Top:= (Height - TH) div 2; TxtRect.Bottom:= TxtRect.Top + TH; end; blGlyphLeft: begin ImgRect.Top:= (Height - IH) div 2; ImgRect.Bottom:= ImgRect.Top + IH; ImgRect.Left:= FMargin; ImgRect.Right:= ImgRect.Left + IW; TxtRect.Top:= (Height - TH) div 2; TxtRect.Bottom:= TxtRect.Top + TH; if IW > 0 then TxtRect.Left:= ImgRect.Right + FSpacing else TxtRect.Left:= (Width - TW) div 2; TxtRect.Right:= TxtRect.Left + TW; end; blGlyphRight: begin ImgRect.Top:= (Height - IH) div 2; ImgRect.Bottom:= ImgRect.Top + IH; ImgRect.Left:= Width - (FMargin + IW); ImgRect.Right:= ImgRect.Left + IW; TxtRect.Top:= (Height - TH) div 2; TxtRect.Bottom:= TxtRect.Top + TH; if IW > 0 then TxtRect.Left:= ImgRect.Left - (FSpacing + TW) else TxtRect.Left:= (Width - TW) div 2; TxtRect.Right:= TxtRect.Left + TW; end; end; end; procedure TrsFlyOverButton.DrawButton(ACanvas: TCanvas); var B,I,T : TRect; TmpBMP : TBitmap; TRColor : TColor; TxtBuf : array[0..255] of char; ACaption : String[255]; tmpstate : TButtonState; begin ACaption:= UnAccel(Caption); StrPCopy(TxtBuf, Caption); tmpstate:= FState; if (foAlwaysActive in FOptions) and (tmpstate = bsInActive) then tmpstate:= bsActive; ACanvas.Font.Assign(Font); with ACanvas do begin Brush.Style:= bsClear; case tmpstate of {** Draw Active **} bsActive: begin TmpBMP:= ValidGlyph('A'); if foDrawBorder in FOptions then DrawFrame(false); B:= Rect(0,0,TmpBMP.Width,TmpBMP.Height); I:= B; T:= Rect(0,0,TextWidth(ACaption), TextHeight(ACaption)); CalcRect(I,T); if (TmpBmp.Height < 1) or (TmpBmp.Width < 1) then TRColor:= clOlive else TRColor:= TmpBmp.Canvas.Pixels[0,TmpBmp.Height-1]; if foTransparent in FOptions then DrawTrans(ACanvas, I.Left, I.Top, TmpBMP, TRColor) else Draw(I.Left, I.Top, Tmpbmp); DrawText(Canvas.Handle, TxtBuf, StrLen(TxtBuf), T, DT_SINGLELINE); end; {** Draw Down **} bsDown, bsGroupDown: begin TmpBMP:= ValidGlyph('A'); if foDrawBorder in FOptions then DrawFrame(true); B:= Rect(0,0,TmpBMP.Width,TmpBMP.Height); I:= B; T:= Rect(0,0,TextWidth(ACaption), TextHeight(ACaption)); CalcRect(I,T); if foDrawDown in FOptions then begin OffsetRect(I,1,1); OffsetRect(T,1,1); end; if (TmpBmp.Height < 1) or (TmpBmp.Width < 1) then TRColor:= clOlive else TRColor:= TmpBmp.Canvas.Pixels[0,TmpBmp.Height-1]; if foTransparent in FOptions then DrawTrans(ACanvas, I.Left, I.Top, TmpBMP, TRColor) else Draw(I.Left, I.Top, Tmpbmp); DrawText(Canvas.Handle, TxtBuf, StrLen(TxtBuf), T, DT_SINGLELINE); end; {** Draw InActive **} bsInActive: begin TmpBMP:= ValidGlyph('I'); if (foAutoSize in FOptions) and (TmpBMP.Width > 8) and (TmpBMP.Height > 8) then begin Width:= TmpBMP.Width + 4; Height:= TmpBMP.Height + 4; end; B:= Rect(0,0,TmpBMP.Width,TmpBMP.Height); I:= B; T:= Rect(0,0,TextWidth(ACaption), TextHeight(ACaption)); CalcRect(I,T); if (TmpBmp.Height < 1) or (TmpBmp.Width < 1) then TRColor:= clOlive else TRColor:= TmpBmp.Canvas.Pixels[0,TmpBmp.Height-1]; if foTransparent in FOptions then DrawTrans(ACanvas, I.Left, I.Top, TmpBMP, TRColor) else Draw(I.Left, I.Top, Tmpbmp); DrawText(Canvas.Handle, TxtBuf, StrLen(TxtBuf), T, DT_SINGLELINE); end; {** Draw Disabled **} bsDisabled: begin TmpBMP:= ValidGlyph('D'); if (foAlwaysActive in FOptions) and (foDrawBorder in FOptions) then DrawFrame(false); B:= Rect(0,0,TmpBMP.Width,TmpBMP.Height); I:= B; T:= Rect(0,0,TextWidth(ACaption), TextHeight(ACaption)); CalcRect(I,T); if (TmpBmp.Height < 1) or (TmpBmp.Width < 1) then TRColor:= clOlive else TRColor:= TmpBmp.Canvas.Pixels[0,TmpBmp.Height-1]; if foTransparent in FOptions then DrawTrans(ACanvas, I.Left, I.Top, TmpBMP, TRColor) else Draw(I.Left, I.Top, Tmpbmp); Font.Color:= clbtnShadow; DrawText(Canvas.Handle, TxtBuf, StrLen(TxtBuf), T, DT_SINGLELINE); OffsetRect(T,1,1); Font.Color:= clbtnHighlight; DrawText(Canvas.Handle, TxtBuf, StrLen(TxtBuf), T, DT_SINGLELINE); end; end; end; end; procedure TrsFlyOverButton.DrawFrame(Down: Boolean); begin with Canvas do begin if Down then begin if foBlackline in FOptions then Pen.Color:= clBlack else Pen.Color:= clBtnShadow; MoveTo(0,0); LineTo(ClientRect.Right-1,0); MoveTo(0,0); LineTo(0,ClientRect.Bottom-1); Pen.Color:= clBtnHighlight; MoveTo(ClientRect.Right-1,1); LineTo(ClientRect.Right-1,ClientRect.Bottom); MoveTo(1,ClientRect.Bottom-1); LineTo(ClientRect.Right-1,ClientRect.Bottom-1); end else begin Pen.Color:= clBtnHighlight; MoveTo(0,0); LineTo(ClientRect.Right-1,0); MoveTo(0,0); LineTo(0,ClientRect.Bottom-1); if foBlackline in FOptions then Pen.Color:= clBlack else Pen.Color:= clBtnShadow; MoveTo(ClientRect.Right-1,1); LineTo(ClientRect.Right-1,ClientRect.Bottom); MoveTo(1,ClientRect.Bottom-1); LineTo(ClientRect.Right-1,ClientRect.Bottom-1); end; end; end; procedure TrsFlyOverButton.ClearFrame; begin with Canvas do begin Pen.Color:= clBtnFace; MoveTo(0,0); LineTo(ClientRect.Right-1,0); MoveTo(0,0); LineTo(0,ClientRect.Bottom-1); MoveTo(ClientRect.Right-1,1); LineTo(ClientRect.Right-1,ClientRect.Bottom); MoveTo(1,ClientRect.Bottom-1); LineTo(ClientRect.Right-1,ClientRect.Bottom-1); end; end; procedure TrsFlyOverButton.CMTextChanged(var Message: TMessage); begin inherited; invalidate; end; procedure TrsFlyOverButton.CMFontChanged(var Message: TMessage); begin inherited; invalidate; end; procedure TrsFlyOverButton.CMDialogChar(var Message: TCMDialogChar); begin with Message do if IsAccel(CharCode, Caption) and Enabled and (Parent.Enabled) then begin if PopupMenu <> nil then Perform(WM_LBUTTONDOWN,0,0) else Click; Result := 1; end else inherited; end; procedure TrsFlyOverButton.CMMouseEnter(var Message: TMessage); Var Comp : TComponent ; begin inherited; Comp := Screen.ActiveControl ; If ( Comp Is TrsSuperEdit ) Then TrsSuperEdit(Comp).ValidateData ; FMouseIn:= true; if (FState = bsDisabled) or (not Enabled) or (not Parent.Enabled) then Exit; if Assigned(FOnFlyOver) then FOnFlyOver(Self); if (FState = bsGroupDown) then Exit; FState:= bsActive; if (foAlwaysActive in FOptions) then Exit; if foAutoClear in FOptions then Invalidate else Paint; end; procedure TrsFlyOverButton.CMMouseLeave(var Message: TMessage); begin inherited; FMouseIn:= false; if (FState = bsDisabled) or (not Enabled) or (not Parent.Enabled) then Exit; if (FState = bsGroupDown) then Exit; FState:= bsInActive; if foAutoClear in FOptions then Invalidate else ClearFrame; end; procedure TrsFlyOverButton.WMLButtonDown(var Message: TWMLButtonDown); begin inherited; {Timer for HoldDown event} if Assigned(FOnHoldDown) or (foAutoHoldDown in FOptions) then begin if FTimer <> NIL then begin FTimer.Free; FTimer:= NIL; end; FTimer:= TTimer.Create(Self); FTimer.Interval:= 100; FTimer.OnTimer:= TimerFlag; FTimer.Enabled:= true; end; {draw button down} Down; Popup; end; procedure TrsFlyOverButton.WMLButtonUp(var Message: TWMLButtonUp); Var Comp : TWinControl ; begin inherited; Comp := Screen.ActiveControl ; FButFocus.SetFocus ; try Comp.SetFocus ; except end; if FTimer <> NIL then begin FTimer.Free; FTimer:= NIL; end; if (FState = bsGroupDown) then Exit; if FMouseIn then FState:= bsActive else FState:= bsInActive; with Canvas do begin Brush.Style:= bsSolid; Brush.Color:= Color; FillRect(ClientRect) end; Invalidate; end; procedure TrsFlyOverButton.SetGlyph(Index: integer; AValue : TBitmap); begin case Index of 1: FGlyphA.Assign(AValue); 2: FGlyphI.Assign(AValue); 3: FGlyphD.Assign(AValue); end; Invalidate; end; procedure TrsFlyOverButton.SetOptions (AValue: TfobOptions); begin FOptions:= AValue; Invalidate; end; procedure TrsFlyOverButton.SetLayout(AValue: TButtonLayout); begin if AValue <> FLayout then begin FLayout := AValue; Invalidate; end; end; procedure TrsFlyOverButton.SetSpacing(AValue: Smallint); begin if AValue <> FSpacing then begin FSpacing := AValue; Invalidate; end; end; procedure TrsFlyOverButton.SetMargin(AValue: Smallint); begin if AValue <> FMargin then begin FMargin := AValue; Invalidate; end; end; procedure TrsFlyOverButton.SetGroupID (AValue: smallint); begin FGroupID:= AValue; Invalidate; end; procedure TrsFlyOverButton.SetState (AValue: TButtonState); begin FState:= AValue; Invalidate; end; procedure TrsFlyOverButton.Click; var F: TWinControl; begin inherited Click; {Modal result} F:= GetParentForm(Self); if F <> NIL then if FModalRes <> mrNone then begin (F as TForm).ModalResult:= FModalRes; end; end; procedure TrsFlyOverButton.CMDialogKey(var Message: TCMDialogKey); begin with Message do if (((CharCode = VK_RETURN) and (foDefault in FOptions)) or ((CharCode = VK_ESCAPE) and (foCancel in FOptions))) and (KeyDataToShiftState(Message.KeyData) = []) then begin Click; Popup; Result := 1; end else inherited; end; procedure TrsFlyOverButton.TimerFlag(Sender: TObject); begin if foAutoHoldDown in FOptions then Click; if Assigned(FOnHoldDown) then FOnHoldDown(Self); end; procedure TrsFlyOverButton.Popup; var pt: TPoint; begin if (foAutoPopMenu in FOptions) and (FGroupID < 1) then {setup popup menu} if PopupMenu <> NIL then begin State:= bsDown; FPopped:= true; pt.X:= Left-1; pt.Y:= Top + Height; pt:= Parent.ClienttoScreen(pt); PopupMenu.PopupComponent:= Self; {call event handler} if Assigned(FOnPopup) then FOnPopup(Self); {do popping} PopupMenu.PopUp(Pt.X, pt.Y); FPopped:= false; {reset button} State:= bsInActive; end; end; procedure TrsFlyOverButton.Down; var x: smallint; begin {change state to down} if (FState <> bsDown) and (FState <> bsGroupDown) then State:= bsDown; {Group Mode} if FGroupID > 0 then begin if (FState = bsGroupDown) and (foGroupAllowUp in FOptions) then begin {reset button} State:= bsInActive; end else begin for x:= 0 to Parent.ControlCount-1 do if (Parent.Controls[x] is TrsFlyOverButton) and (not (Parent.Controls[x] = Self)) then if ((Parent.Controls[x] as TrsFlyOverButton).GroupID > 0) and ((Parent.Controls[x] as TrsFlyOverButton).GroupID = FGroupID) and ((Parent.Controls[x] as TrsFlyOverButton).State = bsGroupDown) then (Parent.Controls[x] as TrsFlyOverButton).State:= bsInActive; State:= bsGroupDown end; end; end; end.
unit MCP_Zahid_Etap; interface uses Model, Utils, Data.DB, IBQuery, DataModule; type TMCP_Zahid_EtapRecord = class(TRecordInfo) protected function GetFields(QFields: TFields): TMyList<TFieldInfo>; override; function GetItems(QFields: TFields): TMyList<TRecordInfo>; override; function GetDisplayText(QFields: TFields): String; override; end; TMCP_Zahid_OrgRecord = class(TRecordInfo) protected function GetFields(QFields: TFields): TMyList<TFieldInfo>; override; function GetItems(QFields: TFields): TMyList<TRecordInfo>; override; function GetDisplayText(QFields: TFields): String; override; end; TMCP_Zahid_RikRecord = class(TRecordInfo) protected function GetFields(QFields: TFields): TMyList<TFieldInfo>; override; function GetItems(QFields: TFields): TMyList<TRecordInfo>; override; function GetDisplayText(QFields: TFields): String; override; end; implementation { TMCP_Zahid_EtapRecord } function TMCP_Zahid_EtapRecord.GetDisplayText(QFields: TFields): String; begin Result := QFields.FieldByName('S_ETAP_ID').AsString; end; function TMCP_Zahid_EtapRecord.GetFields(QFields: TFields): TMyList<TFieldInfo>; begin Result := TMyList<TFieldInfo>.Create; Result.Add(TFieldInfo.Create(QFields.FieldByName('S_ETAP_ID').AsString, QFields.FieldByName('S_ETAP_ID1').AsString, 'Етап')); Result.Add(TFieldInfo.Create(QFields.FieldByName('REZULTAT').AsString, QFields.FieldByName('REZULTAT1').AsString, 'Результат')); Result.Add(TFieldInfo.Create(QFields.FieldByName('SUMA').AsString, QFields.FieldByName('SUMA1').AsString, 'Сума')); end; function TMCP_Zahid_EtapRecord.GetItems(QFields: TFields): TMyList<TRecordInfo>; begin Result := TMyList<TRecordInfo>.Create; end; { TMCP_Zahid_OrgRecord } function TMCP_Zahid_OrgRecord.GetDisplayText(QFields: TFields): String; { передается обьедененная таблица } var s_org_query: TIBQuery; begin s_org_query := MCPDataModule.SelectS_OrgQuery; s_org_query.ParamByName('s_org_id').AsInteger := QFields.FieldByName('s_org_id').AsInteger; s_org_query.Open; Result := s_org_query.FieldByName('NAME').AsString; s_org_query.Close; end; function TMCP_Zahid_OrgRecord.GetFields(QFields: TFields): TMyList<TFieldInfo>; begin Result := TMyList<TFieldInfo>.Create; Result.Add(TFieldInfo.Create(QFields.FieldByName('s_org_id').AsString, QFields.FieldByName('s_org_id1').AsString, 'Id організації')); Result.Add(TFieldInfo.Create(QFields.FieldByName('nomer_pp').AsString, QFields.FieldByName('nomer_pp1').AsString, 'Номер ПП')); end; function TMCP_Zahid_OrgRecord.GetItems(QFields: TFields): TMyList<TRecordInfo>; begin Result := TMyList<TRecordInfo>.Create; end; { TMCP_Zahid_RikRecord } function TMCP_Zahid_RikRecord.GetDisplayText(QFields: TFields): String; var s_rik_query: TIBQuery; begin s_rik_query := MCPDataModule.SelectS_RikQuery; s_rik_query.ParamByName('s_rik_id').AsInteger := QFields.FieldByName('s_rik_id').AsInteger; s_rik_query.Open; Result := s_rik_query.FieldByName('NAME').AsString; s_rik_query.Close; end; function TMCP_Zahid_RikRecord.GetFields(QFields: TFields): TMyList<TFieldInfo>; begin Result := TMyList<TFieldInfo>.Create; Result.Add(TFieldInfo.Create(QFields.FieldByName('s_rik_id').AsString, QFields.FieldByName('s_rik_id1').AsString, 'Id організації')); end; function TMCP_Zahid_RikRecord.GetItems(QFields: TFields): TMyList<TRecordInfo>; begin Result := TMyList<TRecordInfo>.Create; end; end.
unit Objects; interface uses Classes, SysUtils, Graphics, Vcl.Dialogs, Math; type TBitList = array [0 .. 10] of TBitmap; TBasic = class private x: Integer; y: Integer; public constructor Create(x0, y0: Integer); overload; procedure setX(x0: Integer); procedure setY(y0: Integer); function getX: Integer; function getY: Integer; end; TStatics = class(TBasic) private bitmap: TBitmap; public constructor Create(x0, y0: Integer; bitmap0: TBitmap); procedure setBitmap(bitmap0: TBitmap); function getBitmap: TBitmap; end; TAnimated = class(TBasic) private maxFrame: Integer; current: Integer; bitmap: TBitList; public constructor Create(x0, y0: Integer; bitmap0: TBitList; maxFrame0: Integer); procedure nextFrame; procedure setBitmap(bitmap0: TBitList); function getBitmap: TBitmap; end; TTube = class private x0: Integer; x1: Integer; y0: Integer; y1: Integer; bitmap: TBitList; public constructor Create(x, y: Integer; bitmap0: TBitList); function getBitmap(curr: Integer): TBitmap; function getXTop: Integer; function getYTop: Integer; function getXBottom: Integer; function getYBottom: Integer; procedure move; procedure setX(x: Integer); procedure setY; end; TPlayer = class(TAnimated) private gravity: Integer; isFalling: boolean; public faild: boolean; constructor Create(x0, y0: Integer; bitmap0: TBitList; maxFrame: Integer); procedure move; procedure jump; procedure falling; end; implementation { TBasic } constructor TBasic.Create(x0, y0: Integer); begin x := x0; y := y0; end; function TBasic.getX: Integer; begin result := x; end; function TBasic.getY: Integer; begin result := y; end; procedure TBasic.setX(x0: Integer); begin x := x0; end; procedure TBasic.setY(y0: Integer); begin y := y0; end; { TStatics } constructor TStatics.Create(x0, y0: Integer; bitmap0: TBitmap); begin x := x0; y := y0; bitmap := bitmap0; end; function TStatics.getBitmap: TBitmap; begin result := bitmap; end; procedure TStatics.setBitmap(bitmap0: TBitmap); begin bitmap := bitmap0; end; { TAnimated } constructor TAnimated.Create(x0, y0: Integer; bitmap0: TBitList; maxFrame0: Integer); begin x := x0; y := y0; bitmap := bitmap0; maxFrame := maxFrame0; current := 0; end; function TAnimated.getBitmap: TBitmap; begin result := bitmap[current]; end; procedure TAnimated.nextFrame; begin if current >= maxFrame then current := 0 else current := current + 1; end; procedure TAnimated.setBitmap(bitmap0: TBitList); begin bitmap := bitmap0; end; { TPlayer } constructor TPlayer.Create(x0, y0: Integer; bitmap0: TBitList; maxFrame: Integer); begin inherited; gravity := 5; isFalling := True; faild := False; end; procedure TPlayer.falling; begin if (y + 24) >= 400 then begin y := (400 - 24); faild := True; end else faild := False; end; procedure TPlayer.jump; begin gravity := -8; end; procedure TPlayer.move; begin if gravity < 5 then gravity := gravity + 1; y := y + gravity; end; { TTube } constructor TTube.Create(x, y: Integer; bitmap0: TBitList); begin x1 := x; y1 := y; y0 := y1 - 420; x0 := x; bitmap := bitmap0; end; function TTube.getBitmap(curr: Integer): TBitmap; // Top = 0, Bottom = 1 begin if curr = 0 then result := bitmap[0]; if curr = 1 then result := bitmap[1]; end; function TTube.getXBottom: Integer; begin result := x1; end; function TTube.getYBottom: Integer; begin result := y1; end; function TTube.getXTop: Integer; begin result := x0; end; function TTube.getYTop: Integer; begin result := y0; end; procedure TTube.move; var i: Integer; begin if x0 = 288 then begin Randomize; i := RandomRange(150, 300); y0 := i - 420; y1 := i; end; if x0 <= -52 then x0 := 288 else x0 := x0 - 6; x1 := x0; end; procedure TTube.setX(x: Integer); begin x0 := x; end; procedure TTube.setY; var i: Integer; begin Randomize; i := RandomRange(150, 300); y0 := i - 420; y1 := i; end; end.
unit about_form; {############################################################################# '# Name: about_form.pas '# Developed By: The Uniform Server Development Team '# Web: http://www.uniformserver.com '# Mike Gleaves V1.1.1 25-04-2014 '# '# '#############################################################################} {$mode objfpc}{$H+} interface uses Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls, StdCtrls, default_config_vars; type { TAbout } TAbout = class(TForm) Bevel1: TBevel; Image1: TImage; Label1: TLabel; Label2: TLabel; Label4: TLabel; procedure FormCreate(Sender: TObject); private { private declarations } public { public declarations } end; var About: TAbout; implementation {$R *.lfm} { TAbout } procedure TAbout.FormCreate(Sender: TObject); var str1:string; str2:string; begin about.Caption := 'About'; // About str1:=''; str1:= str1 + 'UniServer Zero XIV '+ USC_AppVersion +sLineBreak; str1:= str1 + 'UniController XIV ' + UNICONTROLLER_VERSION; Label1.Caption := str1; str2:=''; str2:= str2 + 'UniController coded in Pascal and compiled with Lazarus 2.0.10' +sLineBreak; str2:= str2 + 'Product: Uniform Server Zero XIV ' +sLineBreak; str2:= str2 + 'Release status: UniController XIV version '+UNICONTROLLER_VERSION +sLineBreak+sLineBreak; str2 := str2 + 'People who have contributed to Uniform Server:' + sLineBreak; str2 := str2 + 'Developers:' +sLineBreak; str2 := str2 + '- Olajide Olaolorun (olajideolaolorun)' +sLineBreak; str2 := str2 + '- Mike Gleaves (Ric)' +sLineBreak; str2 := str2 + '- Bob Strand (BobS)'+sLineBreak; str2 := str2 + '- Sudeep DSouza (SudeepJD)'+sLineBreak; str2 := str2 + '- Davide Bonsangue (BrainStorm)'+sLineBreak+sLineBreak; Label2.Caption := str2; end; end.
unit Unit_FileExchangeServer; { ****************************************************************************** File Exchange Server Demo Indy 10.5.5 It just shows how to send/receive Record/Buffer/File. No error handling. by BdLm minor bug : "Cannot get file from client, Unknown error occured " ignore this bug, just wrong info in memo :-) ********************************************************************************} interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, IdContext, StdCtrls, IdBaseComponent, IdComponent, IdCustomTCPServer, IdTCPServer, IdSync, Unit_Indy_Classes, Unit_Indy_Functions, Vcl.Imaging.jpeg, Vcl.ExtCtrls; type TFileExchangeServerForm = class(TForm) IdTCPServer1: TIdTCPServer; CheckBox1: TCheckBox; Memo1: TMemo; Button1: TButton; FileNameEdit: TEdit; Label1: TLabel; btn_LoadFile: TButton; aOpenDialog: TOpenDialog; procedure FormCreate(Sender: TObject); procedure CheckBox1Click(Sender: TObject); procedure ClientConnected; procedure ClientDisconnected; procedure IdTCPServer1Execute(AContext: TIdContext); procedure IdTCPServer1Connect(AContext: TIdContext); procedure IdTCPServer1Disconnect(AContext: TIdContext); procedure FormDestroy(Sender: TObject); procedure Button1Click(Sender: TObject); procedure btn_LoadFileClick(Sender: TObject); private procedure ShowCannotGetFileErrorMessage; procedure ShowCannotSendFileErrorMessage; procedure FileReceived; { Private declarations } public { Public declarations } end; var FileExchangeServerForm: TFileExchangeServerForm; MyErrorMessage: string; implementation {$R *.dfm} uses Unit_DelphiCompilerversionDLG; procedure TFileExchangeServerForm.btn_LoadFileClick(Sender: TObject); begin if aOpenDialog.Execute then begin FileNameEdit.Text := aOpenDialog.FileName; end; end; procedure TFileExchangeServerForm.Button1Click(Sender: TObject); begin OKRightDlgDelphi.Show; end; procedure TFileExchangeServerForm.CheckBox1Click(Sender: TObject); begin IdTCPServer1.Active := CheckBox1.Checked; end; procedure TFileExchangeServerForm.ClientConnected; begin Memo1.Lines.Add('A Client connected'); end; procedure TFileExchangeServerForm.ClientDisconnected; begin Memo1.Lines.Add('A Client disconnected'); end; procedure TFileExchangeServerForm.FormCreate(Sender: TObject); begin IdTCPServer1.Bindings.Add.IP := '127.0.0.1'; IdTCPServer1.Bindings.Add.Port := 6000; end; procedure TFileExchangeServerForm.FormDestroy(Sender: TObject); begin IdTCPServer1.Active := False; end; procedure TFileExchangeServerForm.IdTCPServer1Connect(AContext: TIdContext); begin TIdNotify.NotifyMethod(ClientConnected); end; procedure TFileExchangeServerForm.IdTCPServer1Disconnect(AContext: TIdContext); begin TIdNotify.NotifyMethod(ClientDisconnected); end; procedure TFileExchangeServerForm.IdTCPServer1Execute(AContext: TIdContext); var LSize: LongInt; file1 : String; dummyStr : string; begin Memo1.Lines.Add('Server starting .... ' ); AContext.Connection.IOHandler.ReadTimeout := 9000; dummyStr := AContext.Connection.IOHandler.ReadLn; file1:= FileNameEdit.Text; if ( ServerSendFile(AContext, file1) = False ) then begin TIdNotify.NotifyMethod(ShowCannotGetFileErrorMessage); Exit; end else begin Memo1.Lines.Add('Server done, client file -> ' + file1); end; TIdNotify.NotifyMethod(FileReceived); end; procedure TFileExchangeServerForm.FileReceived; begin Memo1.Lines.Add('File received' ); end; procedure TFileExchangeServerForm.ShowCannotGetFileErrorMessage; begin Memo1.Lines.Add('Cannot get file from client, Unknown error occured'); end; procedure TFileExchangeServerForm.ShowCannotSendFileErrorMessage; begin Memo1.Lines.Add('Cannot send file to client, Unknown error occured'); end; end.
{******************************************************************************} { } { Neon: Serialization Library for Delphi } { Copyright (c) 2018-2019 Paolo Rossi } { https://github.com/paolo-rossi/neon-library } { } {******************************************************************************} { } { 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 Demo.Forms.Serialization.Complex; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ExtCtrls, System.Generics.Collections, Demo.Forms.Serialization.Base, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Stan.StorageBin, Data.DB, FireDAC.Comp.DataSet, FireDAC.Comp.Client, Vcl.Imaging.pngimage; type TfrmSerializationComplex = class(TfrmSerializationBase) btnSerComplexObject: TButton; btnSerDictionary: TButton; btnSerFilterObject: TButton; btnSerGenericList: TButton; btnSerGenericObjectList: TButton; btnSerSimpleObject: TButton; btnSerStreamable: TButton; btnStreamableProp: TButton; btnDesComplexObject: TButton; btnDesDictionary: TButton; btnDesFilterObject: TButton; btnDesGenericList: TButton; btnDesGenericObjectList: TButton; btnDesSimpleObject: TButton; btnDesStreamable: TButton; btnDesStreamableProp: TButton; procedure btnDesComplexObjectClick(Sender: TObject); procedure btnDesDictionaryClick(Sender: TObject); procedure btnDesFilterObjectClick(Sender: TObject); procedure btnDesGenericListClick(Sender: TObject); procedure btnDesGenericObjectListClick(Sender: TObject); procedure btnDesSimpleObjectClick(Sender: TObject); procedure btnDesStreamableClick(Sender: TObject); procedure btnDesStreamablePropClick(Sender: TObject); procedure btnSerComplexObjectClick(Sender: TObject); procedure btnSerDictionaryClick(Sender: TObject); procedure btnSerFilterObjectClick(Sender: TObject); procedure btnSerGenericListClick(Sender: TObject); procedure btnSerGenericObjectListClick(Sender: TObject); procedure btnSerSimpleObjectClick(Sender: TObject); procedure btnSerStreamableClick(Sender: TObject); procedure btnStreamablePropClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var frmSerializationComplex: TfrmSerializationComplex; implementation uses Demo.Neon.Entities; {$R *.dfm} procedure TfrmSerializationComplex.btnDesComplexObjectClick(Sender: TObject); var LPerson: TPerson; begin LPerson := TPerson.Create; try DeserializeObject(LPerson, memoSerialize.Lines, frmConfiguration.BuildSerializerConfig); SerializeObject(LPerson, memoDeserialize.Lines, frmConfiguration.BuildSerializerConfig); finally LPerson.Free; end; end; procedure TfrmSerializationComplex.btnDesDictionaryClick(Sender: TObject); var LMap: TObjectDictionary<TAddress, TNote>; begin LMap := TObjectDictionary<TAddress, TNote>.Create([doOwnsKeys, doOwnsValues]); try DeserializeObject(LMap, memoSerialize.Lines, frmConfiguration.BuildSerializerConfig); SerializeObject(LMap, memoDeserialize.Lines, frmConfiguration.BuildSerializerConfig); finally LMap.Free; end; end; procedure TfrmSerializationComplex.btnDesFilterObjectClick(Sender: TObject); var LObj: TFilterClass; begin LObj := TFilterClass.Create; try DeserializeObject(LObj, memoSerialize.Lines, frmConfiguration.BuildSerializerConfig); SerializeObject(LObj, memoDeserialize.Lines, frmConfiguration.BuildSerializerConfig); finally LObj.Free; end; end; procedure TfrmSerializationComplex.btnDesGenericListClick(Sender: TObject); var LList: TList<Double>; begin LList := TList<Double>.Create; try DeserializeObject(LList, memoSerialize.Lines, frmConfiguration.BuildSerializerConfig); SerializeObject(LList, memoDeserialize.Lines, frmConfiguration.BuildSerializerConfig); finally LList.Free; end; end; procedure TfrmSerializationComplex.btnDesGenericObjectListClick(Sender: TObject); var LList: TAddressBook; begin LList := TAddressBook.Create; try DeserializeObject(LList, memoSerialize.Lines, frmConfiguration.BuildSerializerConfig); SerializeObject(LList, memoDeserialize.Lines, frmConfiguration.BuildSerializerConfig); finally LList.Free; end; end; procedure TfrmSerializationComplex.btnDesSimpleObjectClick(Sender: TObject); var LSimple: TCaseClass; begin LSimple := TCaseClass.Create; try DeserializeObject(LSimple, memoSerialize.Lines, frmConfiguration.BuildSerializerConfig); SerializeObject(LSimple, memoDeserialize.Lines, frmConfiguration.BuildSerializerConfig); finally LSimple.Free; end; end; procedure TfrmSerializationComplex.btnDesStreamableClick(Sender: TObject); var LStreamable: TStreamableSample; begin LStreamable := TStreamableSample.Create; try DeserializeObject(LStreamable, memoSerialize.Lines, frmConfiguration.BuildSerializerConfig); SerializeObject(LStreamable, memoDeserialize.Lines, frmConfiguration.BuildSerializerConfig); finally LStreamable.Free; end; end; procedure TfrmSerializationComplex.btnDesStreamablePropClick(Sender: TObject); var LStreamable: TStreamableComposition; begin LStreamable := TStreamableComposition.Create; try DeserializeObject(LStreamable, memoSerialize.Lines, frmConfiguration.BuildSerializerConfig); SerializeObject(LStreamable, memoDeserialize.Lines, frmConfiguration.BuildSerializerConfig); finally LStreamable.Free; end; end; procedure TfrmSerializationComplex.btnSerComplexObjectClick(Sender: TObject); var LPerson: TPerson; begin LPerson := TPerson.Create; try LPerson.Name := 'Paolo'; LPerson.Surname := 'Rossi'; LPerson.AddAddress('Piacenza', 'Italy'); LPerson.AddAddress('Parma', 'Italy'); LPerson.Note.Date := Now; LPerson.Note.Text := 'Note Text'; LPerson.Map.Add('first', TNote.Create(Now, 'First Object')); LPerson.Map.Add('second', TNote.Create(Now, 'Second Object')); LPerson.Map.Add('third', TNote.Create(Now, 'Third Object')); LPerson.Map.Add('fourth', TNote.Create(Now, 'Fourth Object')); SerializeObject(LPerson, memoSerialize.Lines, frmConfiguration.BuildSerializerConfig); finally LPerson.Free; end; end; procedure TfrmSerializationComplex.btnSerDictionaryClick(Sender: TObject); var LMap: TObjectDictionary<TAddress, TNote>; begin LMap := TObjectDictionary<TAddress, TNote>.Create([doOwnsKeys, doOwnsValues]); try LMap.Add(TAddress.Create('Piacenza', 'Italy'), TNote.Create(Now, 'Lorem ipsum dolor sit amet')); LMap.Add(TAddress.Create('Dublin', 'Ireland'), TNote.Create(Now + 0.2, 'Fusce in libero posuere')); SerializeObject(LMap, memoSerialize.Lines, frmConfiguration.BuildSerializerConfig); finally LMap.Free; end; end; procedure TfrmSerializationComplex.btnSerFilterObjectClick(Sender: TObject); var LSimple: TFilterClass; begin LSimple := TFilterClass.DefaultValues; try SerializeObject(LSimple, memoSerialize.Lines, frmConfiguration.BuildSerializerConfig); finally LSimple.Free; end; end; procedure TfrmSerializationComplex.btnSerGenericListClick(Sender: TObject); var LList: TList<Double>; begin LList := TList<Double>.Create; try LList.Add(34.9); LList.Add(10.0); SerializeObject(LList, memoSerialize.Lines, frmConfiguration.BuildSerializerConfig); finally LList.Free; end; end; procedure TfrmSerializationComplex.btnSerGenericObjectListClick(Sender: TObject); var LBook: TAddressBook; begin LBook := TAddressBook.Create; try LBook.Add('Verona', 'Italy'); LBook.Add('Napoli', 'Italy'); LBook.NoteList.Add('Note 1'); LBook.NoteList.Add('Note 2'); LBook.NoteList.Add('Note 3'); SerializeObject(LBook, memoSerialize.Lines, frmConfiguration.BuildSerializerConfig); finally LBook.Free; end; end; procedure TfrmSerializationComplex.btnSerSimpleObjectClick(Sender: TObject); var LSimple: TCaseClass; begin LSimple := TCaseClass.DefaultValues; try SerializeObject(LSimple, memoSerialize.Lines, frmConfiguration.BuildSerializerConfig); finally LSimple.Free; end; end; procedure TfrmSerializationComplex.btnSerStreamableClick(Sender: TObject); var LStreamable: TStreamableSample; begin LStreamable := TStreamableSample.Create; try LStreamable.AsString := 'Paolo'; SerializeObject(LStreamable, memoSerialize.Lines, frmConfiguration.BuildSerializerConfig); finally LStreamable.Free; end; end; procedure TfrmSerializationComplex.btnStreamablePropClick(Sender: TObject); var LStreamable: TStreamableComposition; begin LStreamable := TStreamableComposition.Create; try LStreamable.InValue := 233; LStreamable.Stream.AsString := 'Paolo'; SerializeObject(LStreamable, memoSerialize.Lines, frmConfiguration.BuildSerializerConfig); finally LStreamable.Free; end; end; end.
unit acThumbForm; interface uses Windows, Messages, SysUtils, {$IFDEF DELPHI6}Variants, {$ENDIF} Classes, Graphics, Controls, Forms, Dialogs; const WC_MAGNIFIER = 'Magnifier'; sMagnificationDll = 'Magnification.dll'; type TMagTransform = packed record v: packed array[0..2, 0..2] of Single; end; THWNDArray = packed array[0..1] of HWND; PHWNDArray = ^THWNDArray; type TMagnifierOwner = class; TMagnifierWindow = class private FHandle: HWND; FWndStyle: Cardinal; FWidth: Integer; FTop: Integer; FLeft: Integer; FHeight: Integer; FMagFactor: Byte; FVisible: Boolean; FParent: TMagnifierOwner; procedure SetMagFactor(const Value: Byte); procedure SetVisible(const Value: Boolean); public PosUpdating : boolean; property Handle: HWND read FHandle; property MagFactor: Byte read FMagFactor write SetMagFactor; property Visible: Boolean read FVisible write SetVisible; constructor Create(Parent: TMagnifierOwner); destructor Destroy; override; procedure Refresh; procedure UpdateSource; end; TMagnifierOwner = class(TForm) procedure WMMove(var m:TMessage); message WM_MOVE; procedure FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); public cL : integer; cT : integer; cR : integer; cB : integer; ParentForm : TForm; MagnWnd : TMagnifierWindow; constructor Create(AOwner:TComponent); override; procedure CreateParams(var Params: TCreateParams); override; destructor Destroy; override; procedure UpdatePosition(Full : boolean = True); procedure UpdateRgn; end; var MagnifierOwner: TMagnifierOwner; acMagInitialize: function () : BOOL; stdcall; acMagUninitialize: function () : BOOL; stdcall; acMagSetWindowSource: function (hwnd: HWND; rect: TRect) : BOOL; stdcall; acMagSetWindowTransform: function (hwnd: HWND; out Transform: TMagTransform) : BOOL; stdcall; acMagSetWindowFilterList: function (hwnd: HWND; dwFilterMode: DWORD; count: Integer; pHWND: PHWNDArray) : BOOL; stdcall; implementation uses sSkinProvider, acMagn, math, sConst, sGraphUtils; {$R *.dfm} constructor TMagnifierOwner.Create(AOwner: TComponent); begin inherited; ParentForm := TForm(AOwner); // SetLayeredWindowAttributes(Handle, clNone, 255, LWA_ALPHA); with TacMagnForm(AOwner).ContentMargins do begin cL := Left; cR := Right; cT := Top; cB := Bottom; end; Left := ParentForm.Left + cL; Top := ParentForm.Top + cT; Width := TacMagnForm(AOwner).MagnSize.cx - cL - cR; Height := TacMagnForm(AOwner).MagnSize.cy - cT - cB; if not HandleAllocated then Exit; MagnWnd := TMagnifierWindow.Create(Self); MagnWnd.MagFactor := TacMagnForm(ParentForm).Caller.Scaling; UpdatePosition(True); end; procedure TMagnifierOwner.CreateParams(var Params: TCreateParams); begin inherited; Params.ExStyle := Params.ExStyle or WS_EX_TOOLWINDOW or WS_EX_NOACTIVATE or WS_EX_LAYERED or WS_EX_TRANSPARENT or WS_EX_TOPMOST; end; destructor TMagnifierOwner.Destroy; begin inherited; if Assigned(MagnWnd) then FreeAndNil(MagnWnd); end; procedure TMagnifierOwner.WMMove(var m: TMessage); begin if Assigned(MagnWnd) then MagnWnd.UpdateSource; end; constructor TMagnifierWindow.Create(Parent: TMagnifierOwner); begin if not Assigned(acMagInitialize) then Exit; if not acMagInitialize then {$IFDEF DELPHI6UP} RaiseLastOSError{$ENDIF}; FVisible := False; PosUpdating := False; FParent := Parent; FLeft := 0; FTop := 0; FWidth := Parent.ClientWidth; FHeight := Parent.ClientHeight; SetLayeredWindowAttributes(Handle, 0, MaxByte, ULW_ALPHA); FWndStyle := WS_CHILD or WS_VISIBLE or WS_CLIPSIBLINGS; FHandle := CreateWindow(WC_MAGNIFIER, 'acMagWnd', FWndStyle, FLeft, FTop, FWidth, FHeight, FParent.Handle, 0, HInstance, nil); if FHandle = 0 then {$IFDEF DELPHI6UP} RaiseLastOSError{$ENDIF}; end; destructor TMagnifierWindow.Destroy; begin DestroyWindow(FHandle); if not acMagUninitialize then {$IFDEF DELPHI6UP} RaiseLastOSError{$ENDIF}; inherited; end; procedure TMagnifierWindow.SetMagFactor(const Value: Byte); var matrix: TMagTransform; begin FMagFactor := Value; FillMemory(@matrix, sizeof(matrix), 0); matrix.v[0][0] := FMagFactor; matrix.v[1][1] := FMagFactor; matrix.v[2][2] := 1; if not acMagSetWindowTransform(FHandle, matrix) then {$IFDEF DELPHI6UP} RaiseLastOSError{$ENDIF}; end; procedure TMagnifierWindow.SetVisible(const Value: Boolean); const ShowCmd: array[Boolean] of Cardinal = (SW_HIDE, SW_SHOW); begin FVisible := Value; ShowWindow(FHandle, ShowCmd[FVisible]); if FVisible then UpdateSource; end; procedure TMagnifierWindow.Refresh; begin // InvalidateRect(FHandle, nil, True); end; procedure TMagnifierWindow.UpdateSource; var SourceRect: TRect; warray : THWNDArray; begin if PosUpdating then Exit; PosUpdating := True; SourceRect := Rect(FLeft, FTop, FLeft + FWidth, FTop + FHeight); InflateRect(SourceRect, ((FWidth div FMagFactor) - FWidth) div 2, ((FHeight div FMagFactor) - FHeight) div 2); SourceRect.TopLeft := FParent.ClientToScreen(SourceRect.TopLeft); SourceRect.BottomRight := FParent.ClientToScreen(SourceRect.BottomRight); SetWindowPos(FHandle, HWND_TOPMOST, 0, 0, FWidth, FHeight, SWP_NOREDRAW or SWP_NOMOVE or SWP_NOACTIVATE or SWP_NOREDRAW or SWP_NOSENDCHANGING or SWP_NOOWNERZORDER or SWP_NOZORDER); warray[0] := FParent.ParentForm.Handle; warray[1] := FParent.Handle; acMagSetWindowFilterList(FHandle, 0, 2, @warray); if not acMagSetWindowSource(FHandle, SourceRect) then {$IFDEF DELPHI6UP} RaiseLastOSError{$ENDIF}; Visible := True; Refresh; PosUpdating := False; end; procedure TMagnifierOwner.FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer); begin ReleaseCapture; Perform(WM_SYSCOMMAND, $F012, 0) end; procedure TMagnifierOwner.UpdatePosition(Full : boolean = True); const TestOffset = 0; begin if Full then begin InitDwm(Handle, True); with MagnWnd do begin FWidth := max(TacMagnForm(ParentForm).MinSize, ParentForm.Width) - cL - cR; FHeight := max(TacMagnForm(ParentForm).MinSize, ParentForm.Height) - cT - cB; end; SetWindowPos(Handle, ParentForm.Handle, ParentForm.Left + cL + TestOffset, ParentForm.Top + cT, MagnWnd.FWidth, MagnWnd.FHeight, SWP_NOACTIVATE or SWP_NOREDRAW or SWP_SHOWWINDOW or SWP_NOSENDCHANGING or SWP_NOOWNERZORDER); UpdateRgn; MagnWnd.UpdateSource; end else begin SetWindowPos(Handle, 0, ParentForm.Left + cL + TestOffset, ParentForm.Top + cT, 0, 0, SWP_NOSIZE or SWP_NOACTIVATE or SWP_NOREDRAW or SWP_NOZORDER or SWP_NOSENDCHANGING or SWP_NOOWNERZORDER); end; end; procedure TMagnifierOwner.UpdateRgn; begin if TacMagnForm(ParentForm).Caller.Style = amsLens then SetWindowRgn(Handle, CreateRoundRectRgn(0, 0, Width, Height, 262, 262), False); end; end.
unit uTestSimulacao; interface uses DUnitX.TestFramework, System.SysUtils, uSimulacao, uDadosUsuario; type [TestFixture] TestTSimulacao = class public [Setup] procedure Setup; [TearDown] procedure TearDown; [TestCase('Test1', '5000,14/02/1973,15/03/1993,M,N,223,15/01/2040,525,10.5')] [TestCase('Test2', '2500,14/02/1973,13/03/1993,M,N,223,13/02/2040,237.5,9.5')] procedure TestRealizarSimulacao(pSalario: Currency; pDataNascimento: TDateTime; pDataPrimeiraContribuicao: TDateTime; pSexo: Char; pTipoAposentadoria: Char; pQtdeContribuicoes: Integer; pDataUltimaContribuicao: TDateTime; pValorMensal: Currency; pPercentual: Double); private FDadosUsuario: TDadosUsuario; FSimulacao: TSimulacao; procedure PreencherRecord(pSalario: Currency; pDataNascimento: TDateTime; pDataPrimeiraContribuicao: TDateTime; pSexo: Char; pTipoAposentadoria: Char); end; implementation procedure TestTSimulacao.Setup; begin FSimulacao := TSimulacao.Create; FDadosUsuario.InicializarValores; end; procedure TestTSimulacao.TearDown; begin if Assigned(FSimulacao) then FreeAndNil(FSimulacao); end; procedure TestTSimulacao.TestRealizarSimulacao(pSalario: Currency; pDataNascimento: TDateTime; pDataPrimeiraContribuicao: TDateTime; pSexo, pTipoAposentadoria: Char; pQtdeContribuicoes: Integer; pDataUltimaContribuicao: TDateTime; pValorMensal: Currency; pPercentual: Double); begin PreencherRecord(pSalario, pDataNascimento, pDataPrimeiraContribuicao, pSexo, pTipoAposentadoria); FSimulacao.RealizarSimulacao(FDadosUsuario); Assert.AreEqual(FSimulacao.QtdeContribuicoes, pQtdeContribuicoes); Assert.AreEqual(FSimulacao.DataUltimaContribuicao, pDataUltimaContribuicao); Assert.AreEqual(FSimulacao.ValorMensal, pValorMensal); Assert.AreEqual(FSimulacao.Percentual, pPercentual); end; procedure TestTSimulacao.PreencherRecord(pSalario: Currency; pDataNascimento: TDateTime; pDataPrimeiraContribuicao: TDateTime; pSexo, pTipoAposentadoria: Char); begin FDadosUsuario.Salario := pSalario; FDadosUsuario.DataNascimento := pDataNascimento; FDadosUsuario.DataPrimeiraContribuicao := pDataPrimeiraContribuicao; FDadosUsuario.Sexo := pSexo; FDadosUsuario.TipoAposentadoria := pTipoAposentadoria; end; initialization TDUnitX.RegisterTestFixture(TestTSimulacao); end.
unit uFrmPrincipal; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, uDM, Vcl.ExtCtrls, Data.DB, Vcl.Grids, Vcl.DBGrids, Vcl.StdCtrls, Vcl.WinXCtrls, Vcl.Buttons, uProdutosDAO, FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Param, FireDAC.Stan.Error, FireDAC.DatS, FireDAC.Phys.Intf, FireDAC.DApt.Intf, FireDAC.Comp.DataSet, FireDAC.Comp.Client, FireDAC.DApt, uComum, IniFiles, uCestaDAO; type TFrmPrincipal = class(TForm) PanelPrincipal: TPanel; PanelTitulo: TPanel; PanelConteudo: TPanel; DSProdutos: TDataSource; EdtDespesas: TEdit; LDespesas: TLabel; SBAddCesta: TSpeedButton; SBRemoverCesta: TSpeedButton; SBOpenCesta: TSpeedButton; SVCesta: TSplitView; DBGridCestas: TDBGrid; DSCesta: TDataSource; LMargemLucro: TLabel; EdtMargemLucro: TEdit; SBNovoProduto: TSpeedButton; SBEditarProduto: TSpeedButton; DBGridProdutos: TDBGrid; FDMTProdutos: TFDMemTable; FDMTProdutosID: TIntegerField; FDMTProdutosNome: TStringField; FDMTProdutosDescricao: TStringField; FDMTProdutosCustoCompra: TFloatField; FDMTCesta: TFDMemTable; FDMTCestaID: TIntegerField; FDMTCestaNome: TStringField; FDMTCestaCustoCompra: TFloatField; FDMTCestaMargemLucro: TFloatField; FDMTCestaQuantidade: TFloatField; FDMTCestaPrecoVenda: TFloatField; SpeedButton1: TSpeedButton; Label1: TLabel; LTotal: TLabel; SBGravarCesta: TSpeedButton; procedure FormCreate(Sender: TObject); procedure SBAddCestaClick(Sender: TObject); procedure EdtDespesasKeyPress(Sender: TObject; var Key: Char); procedure EdtDespesasExit(Sender: TObject); procedure FormClose(Sender: TObject; var Action: TCloseAction); procedure SBOpenCestaClick(Sender: TObject); procedure EdtMargemLucroExit(Sender: TObject); procedure EdtMargemLucroKeyPress(Sender: TObject; var Key: Char); procedure SBNovoProdutoClick(Sender: TObject); procedure SBEditarProdutoClick(Sender: TObject); procedure SpeedButton1Click(Sender: TObject); procedure SBRemoverCestaClick(Sender: TObject); procedure SBGravarCestaClick(Sender: TObject); private ProdutosDAO: TProdutosDAO; CestaDao: TCestaDAO; Comum: TComum; procedure ListarProdutos; procedure ProcessaCesta; public ID: Integer; procedure LimpaCampos; end; var FrmPrincipal: TFrmPrincipal; implementation uses uFrmValores, uFrmProduto; {$R *.dfm} procedure TFrmPrincipal.ListarProdutos; begin try ProdutosDAO.getProdutos(); except on e: exception do raise exception.Create(e.Message); end; end; procedure TFrmPrincipal.LimpaCampos; begin EdtDespesas.Text := '0,00'; EdtMargemLucro.Text := '0,00'; LTotal.Caption := '0,00'; FDMTCesta.EmptyDataSet; end; procedure TFrmPrincipal.ProcessaCesta; var despesasRateio, precoVenda, totalCesta: Currency; begin totalCesta := 0; if not FDMTCesta.IsEmpty then if Trim(EdtDespesas.Text) <> '0,00' then despesasRateio := StrToCurr(Comum.RemoveEditMoeda(EdtDespesas.Text)) / FDMTCesta.RecNo else despesasRateio := 400 / FDMTCesta.RecNo; FDMTCesta.First; while not FDMTCesta.Eof do begin FDMTCesta.Edit; FDMTCestaMargemLucro.AsCurrency := StrToCurr(Comum.RemoveEditMoeda(EdtMargemLucro.Text)); precoVenda := FDMTCestaCustoCompra.AsCurrency + despesasRateio; if FDMTCestaMargemLucro.AsCurrency > 0 then precoVenda := precoVenda * (FDMTCestaQuantidade.AsCurrency + FDMTCestaMargemLucro.AsCurrency / 100); FDMTCestaPrecoVenda.AsCurrency := precoVenda; totalCesta := totalCesta + precoVenda; FDMTCesta.Post; FDMTCesta.Next; end; LTotal.Caption := FormatFloat('#,0.00', totalCesta); end; procedure TFrmPrincipal.SBAddCestaClick(Sender: TObject); begin try FrmValores := TFrmValores.Create(Self); FrmValores.ShowModal; finally FreeAndNil(FrmValores); ProcessaCesta; DBGridCestas.Refresh; end; end; procedure TFrmPrincipal.SBEditarProdutoClick(Sender: TObject); begin try ID := FDMTProdutosID.AsInteger; FrmProduto := TFrmProduto.Create(nil); FrmProduto.PanelProduto.Caption := 'Produto ' + FDMTProdutosID.AsString; FrmProduto.ShowModal; finally FreeAndNil(FrmProduto); ProcessaCesta; ListarProdutos; end; end; procedure TFrmPrincipal.SBGravarCestaClick(Sender: TObject); var IDCesta: String; begin ProcessaCesta; IDCesta := CestaDao.GravaCesta(); if IDCesta <> '' then CestaDao.GravaCestaItens(IDCesta); ShowMessage('Compra realizada com sucesso!'); LimpaCampos; end; procedure TFrmPrincipal.SBNovoProdutoClick(Sender: TObject); begin try ID := 0; FrmProduto := TFrmProduto.Create(nil); FrmProduto.PanelProduto.Caption := 'Novo produto'; FrmProduto.ShowModal; finally FreeAndNil(FrmProduto); ProcessaCesta; ListarProdutos; end; end; procedure TFrmPrincipal.SBOpenCestaClick(Sender: TObject); begin ProcessaCesta; SVCesta.Open; end; procedure TFrmPrincipal.SBRemoverCestaClick(Sender: TObject); begin FDMTCesta.Delete; ProcessaCesta; end; procedure TFrmPrincipal.SpeedButton1Click(Sender: TObject); begin SVCesta.Close; end; procedure TFrmPrincipal.EdtDespesasExit(Sender: TObject); begin Comum.ExitEditMoeda(EdtDespesas); ProcessaCesta; end; procedure TFrmPrincipal.EdtDespesasKeyPress(Sender: TObject; var Key: Char); begin Comum.FormatEditMoeda(EdtDespesas, Key, 20); end; procedure TFrmPrincipal.EdtMargemLucroExit(Sender: TObject); begin Comum.ExitEditMoeda(EdtMargemLucro); ProcessaCesta; end; procedure TFrmPrincipal.EdtMargemLucroKeyPress(Sender: TObject; var Key: Char); begin Comum.FormatEditMoeda(EdtMargemLucro, Key, 20); end; procedure TFrmPrincipal.FormClose(Sender: TObject; var Action: TCloseAction); begin FreeAndNil(FDMTProdutos); FreeAndNil(FDMTCesta); end; procedure TFrmPrincipal.FormCreate(Sender: TObject); var arquivoINI: TIniFile; begin DM := TDM.Create(Self); // arquivoINI := TIniFile.Create(ExtractFilePath(Application.ExeName) + 'conexao.ini'); // DM.FDConnection.Params.Add('Server='+arquivoINI.ReadString('conexao','SERVIDOR', '')); // DM.FDConnection.Params.UserName := arquivoINI.ReadString('conexao','USUARIO', ''); // DM.FDConnection.Params.Password := arquivoINI.ReadString('conexao','SENHA', ''); // DM.FDConnection.Params.Add('Port=' + arquivoINI.ReadString('conexao','PORTA', '')); // DM.FDConnection.Params.Database :=arquivoINI.ReadString('conexao','BANCO', ''); Comum := TComum.Create; ProdutosDAO := TProdutosDAO.Create; FDMTProdutos.CreateDataSet; FDMTCesta.CreateDataSet; ListarProdutos; ID := 0; end; end.
{ ThreadedTimer found in "Delphi Developer's Journal" of May 1996 Vol. 2 No. 5 } unit ThdTimer; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs; type TThreadedTimer = class; TTimerThread = class(TThread) OwnerTimer: TThreadedTimer; procedure Execute; override; end; TThreadedTimer = class(TComponent) private FEnabled: boolean; FInterval: word; FOnTimer: TNotifyEvent; FTimerThread: TTimerThread; FThreadPriority: TThreadPriority; protected procedure UpdateTimer; procedure SetEnabled(value: boolean); procedure SetInterval(value: word); procedure SetOnTimer(value: TNotifyEvent); procedure SetThreadPriority(value: TThreadPriority); procedure Timer; dynamic; public constructor Create(AOwner: TComponent); override; destructor Destroy; override; published property Enabled: boolean read FEnabled write SetEnabled default true; property Interval: word read FInterval write SetInterval default 1000; property Priority: TThreadPriority read FThreadPriority write SetThreadPriority default tpNormal; property OnTimer: TNotifyEvent read FOnTimer write FOnTimer; end; procedure Register; implementation procedure TTimerThread.Execute; begin Priority := OwnerTimer.FThreadPriority; repeat SleepEx(OwnerTimer.FInterval, False); Synchronize(OwnerTimer.Timer); until Terminated; end; constructor TThreadedTimer.Create(AOwner: TComponent); begin inherited Create(AOwner); FEnabled := True; FInterval := 1000; FThreadPriority := tpNormal; FTimerThread := TTimerThread.Create(False); FTimerThread.OwnerTimer := Self; end; destructor TThreadedTimer.Destroy; begin FEnabled := False; UpdateTimer; FTimerThread.Free; inherited Destroy; end; procedure TThreadedTimer.UpdateTimer; begin if not FTimerThread.Suspended then FTimerThread.Suspend; if (FInterval <> 0) and FEnabled then if FTimerThread.Suspended then FTimerThread.Resume; end; procedure TThreadedTimer.SetEnabled(value: boolean); begin if value <> FEnabled then begin FEnabled := value; UpdateTimer; end; end; procedure TThreadedTimer.SetInterval(value: Word); begin if value <> FInterval then begin FInterval := value; UpdateTimer; end; end; procedure TThreadedTimer.SetOnTimer(value: TNotifyEvent); begin FOnTimer := value; UpdateTimer; end; procedure TThreadedTimer.SetThreadPriority(value: TThreadPriority); begin if value <> FThreadPriority then begin FThreadPriority := value; UpdateTimer; end; end; procedure TThreadedTimer.Timer; begin if Assigned(FOnTimer) then FOnTimer(Self); end; procedure Register; begin RegisterComponents('!', [TThreadedTimer]); end; end.
unit uConstantes; interface const coDelimitadorCampos = ';'; coSincronizado = 1; coDesincronizado = 0; implementation end.
unit FExercicio1_Arrays; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, FExercicio_Base, StdCtrls, ExtCtrls; type TFormExercicio1_Arrays = class(TFormExercicio_base) grpInserir: TGroupBox; edtNome: TLabeledEdit; btnInserir: TButton; grpLista: TGroupBox; grpOperacoes: TGroupBox; btnRemoverPrimeiro: TButton; btnRemoverUltimo: TButton; btnContar: TButton; btnSair: TButton; btnExibir: TButton; lstNomes: TListBox; procedure btnInserirClick(Sender: TObject); procedure btnExibirClick(Sender: TObject); procedure btnRemoverPrimeiroClick(Sender: TObject); procedure btnRemoverUltimoClick(Sender: TObject); procedure btnContarClick(Sender: TObject); procedure btnSairClick(Sender: TObject); procedure edtNomeKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } aNomes: array of string; procedure PopularLista(str: String); procedure RemoverUltimo; public { Public declarations } end; var FormExercicio1_Arrays: TFormExercicio1_Arrays; implementation {$R *.dfm} procedure TFormExercicio1_Arrays.btnInserirClick(Sender: TObject); begin inherited; PopularLista(edtNome.Text); end; procedure TFormExercicio1_Arrays.btnRemoverPrimeiroClick(Sender: TObject); var i: Integer; begin inherited; for i := Low(aNomes) to High(aNomes) do aNomes[i] := aNomes[i+1]; RemoverUltimo; end; procedure TFormExercicio1_Arrays.btnRemoverUltimoClick(Sender: TObject); begin inherited; RemoverUltimo; end; procedure TFormExercicio1_Arrays.btnContarClick(Sender: TObject); begin inherited; ShowMessage(format('Existe(m) %d nome(s) na lista',[Length(aNomes)])); end; procedure TFormExercicio1_Arrays.btnSairClick(Sender: TObject); begin inherited; Close; end; procedure TFormExercicio1_Arrays.btnExibirClick(Sender: TObject); var Lista: TStringList; i: Integer; begin inherited; Lista := TStringList.Create; for i := Low(aNomes) to High(aNomes) do Lista.Add(aNomes[i]); Lista.Sort; lstNomes.Clear; lstNomes.Items.AddStrings(Lista); end; procedure TFormExercicio1_Arrays.edtNomeKeyDown( Sender: TObject; var Key: Word; Shift: TShiftState); begin inherited; if key = 13 then PopularLista(edtNome.Text); end; procedure TFormExercicio1_Arrays.PopularLista(str: String); begin if Trim(str) = '' then Exit; SetLength(aNomes, Length(aNomes) + 1); aNomes[Length(aNomes)-1] := str; edtNome.Clear; edtNome.SetFocus; end; procedure TFormExercicio1_Arrays.RemoverUltimo; begin if Length(aNomes) > 0 then SetLength(aNomes, High(aNomes)); end; end.
unit BitmapData; // // 位图数据处理,主要用于位图的找图找色 // 作者:yeye55 2009年5月29日 // // 版权 2009,由 yeye55 拥有,保留所有权利。 // 本文件中的代码是免费程序,无需任何授权或许可即可用于个人和商业目的。使用者一切后果自负。 // // 如果你转载了本文件中的代码,请注明代码出处和代码作者; // 如果你修改了本文件中的代码,请注明修改位置和修改作者。 // // 本文件最早在http://www.programbbs.com/bbs/上发布 // interface uses Windows, Classes, SysUtils, Graphics; const BD_COLORLESS = -1; // 无色 BD_BITCOUNT = 24; // 图象位数 BD_BYTECOUNT = BD_BITCOUNT shr 3; // 每象素占用字节数 BD_LINEWIDTH = 32; // 每行数据对齐宽度(位) type // 字节数组 TByteAry = array [0 .. 0] of Byte; PByteAry = ^TByteAry; // 颜色变化范围,R、G、B三个通道的绝对差值 TBDColorRange = record R: Integer; G: Integer; B: Integer; end; TBDColor = Integer; // BGR格式颜色 // 转换函数 function BGR(B, G, R: Byte): TBDColor; function RGBtoBGR(C: TColor): TBDColor; function BGRtoRGB(C: TBDColor): TColor; // 比较颜色 function BDCompareColor(C1, C2: TBDColor; const Range: TBDColorRange): Boolean; type TBDBitmapData = class; // 位图数据 // 枚举子图回调函数,查找多个子图时回调,返回是否继续枚举, // Left:找到子图的左边距; // Top:找到子图的顶边距; // Bmp:找到子图数据; // lParam:调用时设置的参数。 TBDEnumImageProc = function(Left, Top: Integer; Bmp: TBDBitmapData; lParam: Integer): Boolean; // 枚举颜色回调函数,查找多个颜色时回调,返回是否继续枚举, // Left:找到颜色的左边距; // Top:找到颜色的顶边距; // Color:找到的颜色; // lParam:调用时设置的参数。 TBDEnumColorProc = function(Left, Top: Integer; Color: TBDColor; lParam: Integer): Boolean; // 位图数据 TBDBitmapData = class private FName: String; // 位图名称 FWidth: Integer; // 位图宽度(象素) FHeight: Integer; // 位图高度(象素) FBackColor: TBDColor; // 背景颜色(BGR格式) FLineWidth: Integer; // 对齐后每行数据宽度(字节) FSpareWidth: Integer; // 对齐后每行数据多余宽度(字节) FSize: Integer; // 位图数据长度 FBufSize: Integer; // 缓冲区实际长度 FBits: PByteAry; // 位图数据缓冲区 function InitData(AWidth, AHeight: Integer): Boolean; function GetPixels(Left, Top: Integer): TBDColor; procedure SetPixels(Left, Top: Integer; Value: TBDColor); public Error: String; constructor Create(const AName: String = ''); destructor Destroy; override; procedure Clear; function LoadFromStream(Stream: TStream; ABackColor: TBDColor = BD_COLORLESS): Boolean; function SaveToStream(Stream: TStream): Boolean; function LoadFromFile(const FileName: string; ABackColor: TBDColor = BD_COLORLESS): Boolean; function SaveToFile(const FileName: string): Boolean; function LoadFromBitmap(Bitmap: TBitmap): Boolean; function SaveToBitmap(Bitmap: TBitmap): Boolean; function CopyFormScreen(Left: Integer = -1; Top: Integer = -1; AWidth: Integer = -1; AHeight: Integer = -1): Boolean; function CopyFormCursor: Boolean; function Compare(Bmp: TBDBitmapData; Left: Integer = 0; Top: Integer = 0) : Boolean; overload; function Compare(Bmp: TBDBitmapData; const Range: TBDColorRange; Left: Integer = 0; Top: Integer = 0): Boolean; overload; //function FindImage(Bmp: TBDBitmapData; var Left, Top: Integer): TPoint; overload; function FindImage(Bmp: TBDBitmapData; var Left, Top: Integer): Boolean; overload; function FindImage(Bmp: TBDBitmapData; const Range: TBDColorRange; var Left, Top: Integer): Boolean; overload; function FindCenterImage(Bmp: TBDBitmapData; var Left, Top: Integer) : Boolean; overload; function FindCenterImage(Bmp: TBDBitmapData; const Range: TBDColorRange; var Left, Top: Integer): Boolean; overload; function EnumImage(Bmp: TBDBitmapData; EnumImageProc: TBDEnumImageProc; lParam: Integer = 0): Boolean; overload; function EnumImage(Bmp: TBDBitmapData; const Range: TBDColorRange; EnumImageProc: TBDEnumImageProc; lParam: Integer = 0): Boolean; overload; function FindColor(Color: TBDColor; var Left, Top: Integer) : Boolean; overload; function FindColor(Color: TBDColor; const Range: TBDColorRange; var Left, Top: Integer): Boolean; overload; function FindCenterColor(Color: TBDColor; var Left, Top: Integer) : Boolean; overload; function FindCenterColor(Color: TBDColor; const Range: TBDColorRange; var Left, Top: Integer): Boolean; overload; function EnumColor(Color: TBDColor; EnumColorProc: TBDEnumColorProc; lParam: Integer = 0): Boolean; overload; function EnumColor(Color: TBDColor; const Range: TBDColorRange; EnumColorProc: TBDEnumColorProc; lParam: Integer = 0): Boolean; overload; property Name: String read FName write FName; // 位图名称 property Width: Integer read FWidth; // 位图宽度(象素) property Height: Integer read FHeight; // 位图高度(象素) property BackColor: TBDColor read FBackColor write FBackColor; // 背景颜色(BGR格式) property LineWidth: Integer read FLineWidth; // 对齐后每行数据宽度(字节) property SpareWidth: Integer read FSpareWidth; // 对齐后每行数据多余宽度(字节) property Size: Integer read FSize; // 位图数据长度 property Bits: PByteAry read FBits; // 位图数据缓冲区 property Pixels[Left, Top: Integer]: TBDColor read GetPixels write SetPixels; default; end; implementation type // 矩阵遍历方向 TAspect = (asLeft, asRight, asUp, asDown); const // 移动坐标差,用于矩阵遍历 MoveVal: array [asLeft .. asDown] of TPoint = ((X: - 1; Y: 0), // asLeft (X: 1; Y: 0), // asRight (X: 0; Y: - 1), // asUp (X: 0; Y: 1) // asDown ); var ScreenWidth: Integer; ScreenHeight: Integer; IconWidth: Integer; IconHeight: Integer; // 根据B、G、R三个通道的值生成一个BGR格式颜色。 function BGR(B, G, R: Byte): TBDColor; begin result := (B or (G shl 8) or (R shl 16)); end; // RGB颜色格式转换到BGR颜色格式。 function RGBtoBGR(C: TColor): TBDColor; begin result := ((C and $FF0000) shr 16) or (C and $00FF00) or ((C and $0000FF) shl 16); end; // BGR颜色格式转换到RGB颜色格式。 function BGRtoRGB(C: TBDColor): TColor; begin result := ((C and $FF0000) shr 16) or (C and $00FF00) or ((C and $0000FF) shl 16); end; // 根据颜色范围Range比较颜色C1和C2,返回C1和C2是否相似, // C1,C2:BGR格式颜色; // Range:为颜色变化范围。 function BDCompareColor(C1, C2: TBDColor; const Range: TBDColorRange): Boolean; var C: Integer; begin result := false; // B C := (C1 and $FF) - (C2 and $FF); if (C > Range.B) or (C < -Range.B) then exit; // G C := ((C1 and $FF00) shr 8) - ((C2 and $FF00) shr 8); if (C > Range.G) or (C < -Range.G) then exit; // R C := ((C1 and $FF0000) shr 16) - ((C2 and $FF0000) shr 16); if (C > Range.R) or (C < -Range.R) then exit; // result := true; end; { TBDBitmapData } // 位图数据 constructor TBDBitmapData.Create(const AName: String); begin self.FName := AName; self.FWidth := 0; self.FHeight := 0; self.FBackColor := BD_COLORLESS; self.FLineWidth := 0; self.FSize := 0; self.FBufSize := 0; self.FBits := nil; self.Error := ''; end; destructor TBDBitmapData.Destroy; begin self.Clear; end; // 根据当前的AWidth和AHeight初始化数据,分配内存,返回是否成功, // 如果失败将设置self.Error说明情况, // AWidth:位图的宽度; // AHeight:位图的高度。 function TBDBitmapData.InitData(AWidth, AHeight: Integer): Boolean; var Align: Integer; begin self.Error := ''; result := true; if (self.FWidth = AWidth) and (self.FHeight = AHeight) then exit; // 计算对齐后的每行数据宽度 self.FWidth := AWidth; self.FHeight := AHeight; Align := BD_LINEWIDTH - 1; self.FLineWidth := (((self.FWidth * BD_BITCOUNT) + Align) and ($7FFFFFFF - Align)) shr 3; self.FSpareWidth := self.FLineWidth - (self.FWidth * BD_BYTECOUNT); self.FSize := self.FLineWidth * self.FHeight; // 分配内存 if self.FSize <= self.FBufSize then exit; if self.FBits <> nil then FreeMem(self.FBits); try GetMem(self.FBits, self.FSize); except on EOutOfMemory do begin self.FSize := 0; self.FBufSize := 0; self.FBits := nil; self.Error := '内存不足!'; result := false; exit; end; end; self.FBufSize := self.FSize; end; // 获取指定位置象素的颜色值, // Left:象素的左边距; // Top:象素的顶边距。 function TBDBitmapData.GetPixels(Left, Top: Integer): TBDColor; begin if (Left < 0) or (Left >= self.FWidth) or (Top < 0) or (Top >= self.FHeight) then begin result := 0; exit; end; result := ((PInteger(@(self.FBits[((self.FHeight - Top - 1) * self.FLineWidth) + (Left * BD_BYTECOUNT)])))^ and $FFFFFF); end; // 设置指定位置象素的颜色值, // Left:象素的左边距; // Top:象素的顶边距; // Value:BGR格式颜色。 procedure TBDBitmapData.SetPixels(Left, Top: Integer; Value: TBDColor); var Off: Integer; begin if (Left < 0) or (Left >= self.FWidth) or (Top < 0) or (Top >= self.FHeight) then exit; Off := ((self.FHeight - Top - 1) * self.FLineWidth) + (Left * BD_BYTECOUNT); // B self.FBits[Off] := Byte(Value and $FF); // G self.FBits[Off + 1] := Byte((Value and $FF00) shr 8); // R self.FBits[Off + 2] := Byte((Value and $FF0000) shr 16); end; // 清除当前的位图数据。 procedure TBDBitmapData.Clear; begin self.FWidth := 0; self.FHeight := 0; self.FBackColor := BD_COLORLESS; self.FLineWidth := 0; self.FSize := 0; self.FBufSize := 0; if self.FBits <> nil then begin FreeMem(self.FBits); self.FBits := nil; end; self.Error := ''; end; // 从数据流中导入位图数据,返回是否成功, // 如果失败将设置self.Error说明情况, // 数据流中的数据必需是24位BMP格式文件数据, // Stream:数据流; // ABackColor:位图的背景颜色,可省略。 function TBDBitmapData.LoadFromStream(Stream: TStream; ABackColor: TBDColor): Boolean; var FileHeader: TBitmapFileHeader; InfoHeader: TBitmapInfoHeader; begin if Stream = nil then begin self.Error := '没有指定数据流!'; result := false; exit; end; // 读取文件头 Stream.Read(FileHeader, SizeOf(TBitmapFileHeader)); Stream.Read(InfoHeader, SizeOf(TBitmapInfoHeader)); with FileHeader, InfoHeader do begin // 确定位图格式 if (bfType <> $4D42) or (biSize <> SizeOf(TBitmapInfoHeader)) or (biBitCount <> BD_BITCOUNT) or (biCompression <> BI_RGB) then begin self.Error := '错误的数据格式!'; result := false; exit; end; // 数据初始化 self.FBackColor := ABackColor; if not self.InitData(biWidth, biHeight) then begin result := false; exit; end; end; // 读入数据 result := Stream.Read((self.FBits)^, self.FSize) = self.FSize; if result then self.Error := '' else self.Error := '读取的数据不完整!'; end; // 将当前的位图数据导出到数据流中,返回是否成功, // 如果失败将设置self.Error说明情况, // 数据按24位BMP文件数据格式导出到数据流中, // Stream:数据流。 function TBDBitmapData.SaveToStream(Stream: TStream): Boolean; var FileHeader: TBitmapFileHeader; InfoHeader: TBitmapInfoHeader; HeaderLen, n: Integer; begin if Stream = nil then begin self.Error := '没有指定数据流!'; result := false; exit; end; // 初始化文件头 HeaderLen := SizeOf(TBitmapFileHeader) + SizeOf(TBitmapInfoHeader); with FileHeader, InfoHeader do begin bfType := $4D42; bfSize := self.FSize + HeaderLen; bfReserved1 := 0; bfReserved2 := 0; bfOffBits := HeaderLen; biSize := SizeOf(TBitmapInfoHeader); biWidth := self.FWidth; biHeight := self.FHeight; biPlanes := 1; biBitCount := BD_BITCOUNT; biCompression := BI_RGB; biSizeImage := self.FSize; biXPelsPerMeter := $EC4; biYPelsPerMeter := $EC4; biClrUsed := 0; biClrImportant := 0; end; // 写入数据 n := 0; n := n + Stream.Write(FileHeader, SizeOf(TBitmapFileHeader)); n := n + Stream.Write(InfoHeader, SizeOf(TBitmapInfoHeader)); n := n + Stream.Write((self.FBits)^, self.FSize); result := n = (self.FSize + HeaderLen); if result then self.Error := '' else self.Error := '写入的数据不完整!'; end; // 从文件中导入位图数据,返回是否成功, // 如果失败将设置self.Error说明情况, // 文件必需是24位BMP格式文件, // FileName:BMP文件名; // ABackColor:位图的背景颜色,可省略。 function TBDBitmapData.LoadFromFile(const FileName: string; ABackColor: TBDColor): Boolean; var Stream: TFileStream; begin Stream := TFileStream.Create(FileName, fmOpenRead); result := self.LoadFromStream(Stream, ABackColor); Stream.Free; end; // 将当前的位图数据导出到文件中,返回是否成功, // 如果失败将设置self.Error说明情况, // 数据按24位BMP文件数据格式导出到文件中, // FileName:BMP文件名。 function TBDBitmapData.SaveToFile(const FileName: string): Boolean; var Stream: TFileStream; begin Stream := TFileStream.Create(FileName, fmCreate); result := self.SaveToStream(Stream); Stream.Free; end; // 从一个TBitmap对象中导入数据,返回是否成功,位图的背景颜色由 // TBitmap.Transparent和TBitmap.TransparentColor决定, // 如果失败将设置self.Error说明情况, // Bitmap:TBitmap对象。 function TBDBitmapData.LoadFromBitmap(Bitmap: TBitmap): Boolean; var Stream: TMemoryStream; ABackColor: TBDColor; begin if Bitmap = nil then begin self.Error := '没有指定位图!'; result := false; exit; end; if Bitmap.Transparent then ABackColor := RGBtoBGR(Bitmap.TransparentColor) else ABackColor := BD_COLORLESS; Stream := TMemoryStream.Create; Bitmap.SaveToStream(Stream); Stream.Position := 0; result := self.LoadFromStream(Stream, ABackColor); Stream.Free; end; // 将当前的位图数据导出到一个TBitmap对象中,返回是否成功,根据当前 // 的背景颜色设置TBitmap.Transparent和TBitmap.TransparentColor成员, // 如果失败将设置self.Error说明情况, // Bitmap:TBitmap对象。 function TBDBitmapData.SaveToBitmap(Bitmap: TBitmap): Boolean; var Stream: TMemoryStream; begin if Bitmap = nil then begin self.Error := '没有指定位图!'; result := false; exit; end; Stream := TMemoryStream.Create; result := self.SaveToStream(Stream); if not result then begin Stream.Free; exit; end; Stream.Position := 0; Bitmap.LoadFromStream(Stream); if self.FBackColor <> BD_COLORLESS then begin Bitmap.TransparentColor := BGRtoRGB(self.FBackColor); Bitmap.Transparent := true; end else Bitmap.Transparent := false; Stream.Free; end; // 从屏幕上的指定范围中截图,并导入数据,返回是否成功, // 如果失败将设置self.Error说明情况, // Left:截图的左边距,可省略; // Top:截图的顶边距,可省略; // AWidth:截图的宽度,可省略; // AHeight:截图的高度,可省略。 function TBDBitmapData.CopyFormScreen(Left, Top, AWidth, AHeight: Integer): Boolean; var Wnd: HWND; DC, MemDC: HDC; Bitmap, OldBitmap: HBITMAP; BitInfo: TBitmapInfo; begin // 参数调整 if (Left < 0) or (Left >= ScreenWidth) then Left := 0; if (Top < 0) or (Top >= ScreenHeight) then Top := 0; if AWidth <= 0 then AWidth := ScreenWidth - Left; if AHeight <= 0 then AHeight := ScreenHeight - Top; // 数据初始化 self.FBackColor := BD_COLORLESS; if not self.InitData(AWidth, AHeight) then begin result := false; exit; end; // 截图 Wnd := GetDesktopWindow(); DC := GetWindowDC(Wnd); MemDC := CreateCompatibleDC(DC); Bitmap := CreateCompatibleBitmap(DC, self.FWidth, self.FHeight); OldBitmap := SelectObject(MemDC, Bitmap); result := BitBlt(MemDC, 0, 0, self.FWidth, self.FHeight, DC, Left, Top, SRCCOPY); Bitmap := SelectObject(MemDC, OldBitmap); if not result then begin DeleteDC(MemDC); DeleteObject(Bitmap); ReleaseDC(Wnd, DC); self.Error := '截图失败!'; exit; end; // 位图信息初始化 with BitInfo.bmiHeader do begin biSize := SizeOf(TBitmapInfoHeader); biWidth := self.FWidth; biHeight := self.FHeight; biPlanes := 1; biBitCount := BD_BITCOUNT; biCompression := BI_RGB; biSizeImage := 0; biXPelsPerMeter := 0; biYPelsPerMeter := 0; biClrUsed := 0; biClrImportant := 0; end; // 提取数据 result := GetDIBits(DC, Bitmap, 0, self.FHeight, Pointer(self.FBits), BitInfo, DIB_RGB_COLORS) <> 0; if result then self.Error := '' else self.Error := '提取数据失败!'; DeleteDC(MemDC); DeleteObject(Bitmap); ReleaseDC(Wnd, DC); end; // 截取鼠标指针的位图,并导入数据,返回是否成功, // 如果失败将设置self.Error说明情况, // 如果鼠标指针是动画指针,默认截取第一帧画面。 function TBDBitmapData.CopyFormCursor: Boolean; var Wnd: HWND; DC, MemDC: HDC; Bitmap, OldBitmap: HBITMAP; CurInfo: TCursorInfo; BitInfo: TBitmapInfo; begin // 数据初始化 self.FBackColor := BD_COLORLESS; self.InitData(IconWidth, IconHeight); // 获取鼠标指针信息 FillChar(CurInfo, SizeOf(TCursorInfo), 0); CurInfo.cbSize := SizeOf(TCursorInfo); if not GetCursorInfo(CurInfo) then begin self.Error := '获取鼠标指针信息失败!'; result := false; exit; end; // 截取鼠标指针位图 Wnd := GetDesktopWindow(); DC := GetWindowDC(Wnd); MemDC := CreateCompatibleDC(DC); Bitmap := CreateCompatibleBitmap(DC, self.FWidth, self.FHeight); OldBitmap := SelectObject(MemDC, Bitmap); result := DrawIconEx(MemDC, 0, 0, CurInfo.hCursor, 0, 0, 0, 0, DI_IMAGE); Bitmap := SelectObject(MemDC, OldBitmap); if not result then begin DeleteDC(MemDC); DeleteObject(Bitmap); ReleaseDC(Wnd, DC); self.Error := '截取鼠标指针位图失败!'; exit; end; // 位图信息初始化 with BitInfo.bmiHeader do begin biSize := SizeOf(TBitmapInfoHeader); biWidth := self.FWidth; biHeight := self.FHeight; biPlanes := 1; biBitCount := BD_BITCOUNT; biCompression := BI_RGB; biSizeImage := 0; biXPelsPerMeter := 0; biYPelsPerMeter := 0; biClrUsed := 0; biClrImportant := 0; end; // 提取数据 result := GetDIBits(DC, Bitmap, 0, self.FHeight, Pointer(self.FBits), BitInfo, DIB_RGB_COLORS) <> 0; if result then self.Error := '' else self.Error := '提取数据失败!'; DeleteDC(MemDC); DeleteObject(Bitmap); ReleaseDC(Wnd, DC); end; // 在当前位图的指定位置比较Bmp位图,返回是否一致, // 无论是否一致都不会修改self.Error, // Bmp位图面幅要小于等于当前位图的面幅,Bmp位图不能超出当前位图, // Bmp:位图数据; // Left:比较时的左边距,可省略; // Top:比较时的顶边距,可省略。 function TBDBitmapData.Compare(Bmp: TBDBitmapData; Left, Top: Integer): Boolean; var X, Y, Off1, Off2: Integer; C1, C2: TBDColor; begin if ((Left + Bmp.FWidth) > self.FWidth) or ((Top + Bmp.FHeight) > self.FHeight) then begin result := false; exit; end; Off1 := ((self.FHeight - Bmp.FHeight - Top) * self.FLineWidth) + (Left * BD_BYTECOUNT); Off2 := 0; result := true; for Y := 0 to Bmp.FHeight - 1 do begin for X := 0 to Bmp.FWidth - 1 do begin C1 := ((PInteger(@(self.FBits[Off1])))^ and $FFFFFF); C2 := ((PInteger(@(Bmp.FBits[Off2])))^ and $FFFFFF); if (C1 <> self.FBackColor) and (C2 <> Bmp.FBackColor) and (C1 <> C2) then begin result := false; break; end; Off1 := Off1 + 3; Off2 := Off2 + 3; end; if not result then break; Off1 := Off1 + (self.FLineWidth - Bmp.FLineWidth) + Bmp.FSpareWidth; Off2 := Off2 + Bmp.FSpareWidth; end; end; // 在当前位图的指定位置模糊比较Bmp位图,返回是否一致, // 无论是否一致都不会修改self.Error, // Bmp位图面幅要小于等于当前位图的面幅,Bmp位图不能超出当前位图, // Bmp:位图数据; // Range:为颜色变化范围 // Left:比较时的左边距,可省略; // Top:比较时的顶边距,可省略。 function TBDBitmapData.Compare(Bmp: TBDBitmapData; const Range: TBDColorRange; Left, Top: Integer): Boolean; var X, Y, Off1, Off2: Integer; C1, C2: TBDColor; begin if ((Left + Bmp.FWidth) > self.FWidth) or ((Top + Bmp.FHeight) > self.FHeight) then begin result := false; exit; end; Off1 := ((self.FHeight - Bmp.FHeight - Top) * self.FLineWidth) + (Left * BD_BYTECOUNT); Off2 := 0; result := true; for Y := 0 to Bmp.FHeight - 1 do begin for X := 0 to Bmp.FWidth - 1 do begin C1 := ((PInteger(@(self.FBits[Off1])))^ and $FFFFFF); C2 := ((PInteger(@(Bmp.FBits[Off2])))^ and $FFFFFF); if (C1 <> self.FBackColor) and (C2 <> Bmp.FBackColor) and (not BDCompareColor(C1, C2, Range)) then begin result := false; break; end; Off1 := Off1 + 3; Off2 := Off2 + 3; end; if not result then break; Off1 := Off1 + (self.FLineWidth - Bmp.FLineWidth) + Bmp.FSpareWidth; Off2 := Off2 + Bmp.FSpareWidth; end; end; // 从当前位图中查找与Bmp一致的子图,返回是否找到, // 无论是否找到都不会修改self.Error, // 按从左到右,从上到下的顺序查找, // 找到返回true,设置Left和Top为找到子图的位置, // 没找到返回false,设置Left和Top为-1。 // Bmp:子图数据; // Left:找到子图的左边距; // Top:找到子图的顶边距。 function TBDBitmapData.FindImage(Bmp: TBDBitmapData; var Left, Top: Integer): Boolean; var X, Y: Integer; begin result := false; X := 0; for Y := 0 to self.FHeight - Bmp.FHeight - 1 do begin for X := 0 to self.FWidth - Bmp.FWidth - 1 do begin if self.Compare(Bmp, X, Y) then begin result := true; break; end; end; if result then break; end; if result then begin Left := X; Top := Y; end else begin Left := -1; Top := -1; end; end; // 从当前位图中模糊查找与Bmp一致的子图,返回是否找到, // 无论是否找到都不会修改self.Error, // 按从左到右,从上到下的顺序查找, // 找到返回true,设置Left和Top为找到的位置, // 没找到返回false,设置Left和Top为-1。 // Bmp:子图数据; // Range:为颜色变化范围; // Left:找到子图的左边距; // Top:找到子图的顶边距。 function TBDBitmapData.FindImage(Bmp: TBDBitmapData; const Range: TBDColorRange; var Left, Top: Integer): Boolean; var X, Y: Integer; begin result := false; X := 0; for Y := 0 to self.FHeight - Bmp.FHeight - 1 do begin for X := 0 to self.FWidth - Bmp.FWidth - 1 do begin if self.Compare(Bmp, Range, X, Y) then begin result := true; break; end; end; if result then break; end; if result then begin Left := X; Top := Y; end else begin Left := -1; Top := -1; end; end; // 从当前位图中查找与Bmp一致的子图,返回是否找到, // 无论是否找到都不会修改self.Error, // 以(Left,Top)为基点,从中心向四周查找, // 找到返回true,设置Left和Top为找到子图的位置, // 没找到返回false,设置Left和Top为-1。 // Bmp:子图数据; // Left:找到子图的左边距; // Top:找到子图的顶边距。 function TBDBitmapData.FindCenterImage(Bmp: TBDBitmapData; var Left, Top: Integer): Boolean; var Aspect: TAspect; VisitCount, Count, i: Integer; begin result := false; VisitCount := 0; Aspect := asUp; Count := 1; while VisitCount < (self.FWidth * self.FHeight) do begin for i := 0 to Count - 1 do begin if (Left >= 0) and (Left < self.FWidth) and (Top >= 0) and (Top < self.FHeight) then begin if self.Compare(Bmp, Left, Top) then begin result := true; break; end; VisitCount := VisitCount + 1; end; Left := Left + MoveVal[Aspect].X; Top := Top + MoveVal[Aspect].Y; end; if result then break; case Aspect of asLeft: begin Aspect := asUp; Count := Count + 1; end; asRight: begin Aspect := asDown; Count := Count + 1; end; asUp: begin Aspect := asRight; end; asDown: begin Aspect := asLeft; end; end; end; if not result then begin Left := -1; Top := -1; end; end; // 从当前位图中模糊查找与Bmp一致的子图,返回是否找到, // 无论是否找到都不会修改self.Error, // 以(Left,Top)为基点,从中心向四周查找, // 找到返回true,设置Left和Top为找到子图的位置, // 没找到返回false,设置Left和Top为-1。 // Bmp:子图数据; // Range:为颜色变化范围; // Left:找到子图的左边距; // Top:找到子图的顶边距。 function TBDBitmapData.FindCenterImage(Bmp: TBDBitmapData; const Range: TBDColorRange; var Left, Top: Integer): Boolean; var Aspect: TAspect; VisitCount, Count, i: Integer; begin result := false; VisitCount := 0; Aspect := asUp; Count := 1; while VisitCount < (self.FWidth * self.FHeight) do begin for i := 0 to Count - 1 do begin if (Left >= 0) and (Left < self.FWidth) and (Top >= 0) and (Top < self.FHeight) then begin if self.Compare(Bmp, Range, Left, Top) then begin result := true; break; end; VisitCount := VisitCount + 1; end; Left := Left + MoveVal[Aspect].X; Top := Top + MoveVal[Aspect].Y; end; if result then break; case Aspect of asLeft: begin Aspect := asUp; Count := Count + 1; end; asRight: begin Aspect := asDown; Count := Count + 1; end; asUp: begin Aspect := asRight; end; asDown: begin Aspect := asLeft; end; end; end; if not result then begin Left := -1; Top := -1; end; end; // 从当前位图中查找所有与Bmp一致的子图,返回是否找到, // 无论是否找到都不会修改self.Error, // 按从左到右,从上到下的顺序查找, // 每找到一个子图,就调用回调函数EnumImageProc,如果EnumImageProc // 返回false就停止查找,结束函数, // Bmp:子图数据; // EnumImageProc:回调函数; // lParam:调用回调函数时发出的参数,可省略。 function TBDBitmapData.EnumImage(Bmp: TBDBitmapData; EnumImageProc: TBDEnumImageProc; lParam: Integer): Boolean; var X, Y: Integer; Res: Boolean; begin result := false; Res := true; for Y := 0 to self.FHeight - Bmp.FHeight - 1 do begin for X := 0 to self.FWidth - Bmp.FWidth - 1 do begin if self.Compare(Bmp, X, Y) then begin result := true; Res := EnumImageProc(X, Y, Bmp, lParam); if not Res then break; end; end; if not Res then break; end; end; // 从当前位图中模糊查找所有与Bmp一致的子图,返回是否找到, // 无论是否找到都不会修改self.Error, // 按从左到右,从上到下的顺序查找, // 每找到一个子图,就调用回调函数EnumImageProc,如果EnumImageProc // 返回false就停止查找,结束函数, // Bmp:子图数据; // Range:为颜色变化范围; // EnumImageProc:回调函数; // lParam:调用回调函数时发出的参数,可省略。 function TBDBitmapData.EnumImage(Bmp: TBDBitmapData; const Range: TBDColorRange; EnumImageProc: TBDEnumImageProc; lParam: Integer): Boolean; var X, Y: Integer; Res: Boolean; begin result := false; Res := true; for Y := 0 to self.FHeight - Bmp.FHeight - 1 do begin for X := 0 to self.FWidth - Bmp.FWidth - 1 do begin if self.Compare(Bmp, Range, X, Y) then begin result := true; Res := EnumImageProc(X, Y, Bmp, lParam); if not Res then break; end; end; if not Res then break; end; end; // 从当前位图中查找指定的颜色,忽略self.FBackColor设置,返回是否找到, // 无论是否找到都不会修改self.Error, // 按从左到右,从上到下的顺序查找, // 找到返回true,设置Left和Top为找到颜色的位置, // 没找到返回false,设置Left和Top为-1。 // Color:BGR格式颜色; // Left:找到颜色的左边距; // Top:找到颜色的顶边距。 function TBDBitmapData.FindColor(Color: TBDColor; var Left, Top: Integer): Boolean; var X, Y, LineOff, Off: Integer; begin result := false; LineOff := self.FSize; X := 0; for Y := 0 to self.FHeight - 1 do begin LineOff := LineOff - self.FLineWidth; Off := LineOff; for X := 0 to self.FWidth - 1 do begin result := ((PInteger(@(self.FBits[Off])))^ and $FFFFFF) = Color; if result then break; Off := Off + 3; end; if result then break; end; if result then begin Left := X; Top := Y; end else begin Left := -1; Top := -1; end; end; // 从当前位图中模糊查找指定的颜色,忽略self.FBackColor设置,返回是否找到, // 无论是否找到都不会修改self.Error, // 按从左到右,从上到下的顺序查找, // 找到返回true,设置Left和Top为找到颜色的位置, // 没找到返回false,设置Left和Top为-1。 // Color:BGR格式颜色; // Range:为颜色变化范围; // Left:找到颜色的左边距; // Top:找到颜色的顶边距。 function TBDBitmapData.FindColor(Color: TBDColor; const Range: TBDColorRange; var Left, Top: Integer): Boolean; var X, Y, LineOff, Off: Integer; begin result := false; LineOff := self.FSize; X := 0; for Y := 0 to self.FHeight - 1 do begin LineOff := LineOff - self.FLineWidth; Off := LineOff; for X := 0 to self.FWidth - 1 do begin result := BDCompareColor(((PInteger(@(self.FBits[Off])))^ and $FFFFFF), Color, Range); if result then break; Off := Off + 3; end; if result then break; end; if result then begin Left := X; Top := Y; end else begin Left := -1; Top := -1; end; end; // 从当前位图中查找指定的颜色,忽略self.FBackColor设置,返回是否找到, // 无论是否找到都不会修改self.Error, // 以(Left,Top)为基点,从中心向四周查找, // 找到返回true,设置Left和Top为找到颜色的位置, // 没找到返回false,设置Left和Top为-1。 // Color:BGR格式颜色; // Left:找到颜色的左边距; // Top:找到颜色的顶边距。 function TBDBitmapData.FindCenterColor(Color: TBDColor; var Left, Top: Integer): Boolean; var Aspect: TAspect; VisitCount, Count, i: Integer; begin result := false; VisitCount := 0; Aspect := asUp; Count := 1; while VisitCount < (self.FWidth * self.FHeight) do begin for i := 0 to Count - 1 do begin if (Left >= 0) and (Left < self.FWidth) and (Top >= 0) and (Top < self.FHeight) then begin if self.GetPixels(Left, Top) = Color then begin result := true; break; end; VisitCount := VisitCount + 1; end; Left := Left + MoveVal[Aspect].X; Top := Top + MoveVal[Aspect].Y; end; if result then break; case Aspect of asLeft: begin Aspect := asUp; Count := Count + 1; end; asRight: begin Aspect := asDown; Count := Count + 1; end; asUp: begin Aspect := asRight; end; asDown: begin Aspect := asLeft; end; end; end; if not result then begin Left := -1; Top := -1; end; end; // 从当前位图中模糊查找指定的颜色,忽略self.FBackColor设置,返回是否找到, // 无论是否找到都不会修改self.Error, // 以(Left,Top)为基点,从中心向四周查找, // 找到返回true,设置Left和Top为找到颜色的位置, // 没找到返回false,设置Left和Top为-1。 // Color:BGR格式颜色; // Range:为颜色变化范围; // Left:找到颜色的左边距; // Top:找到颜色的顶边距。 function TBDBitmapData.FindCenterColor(Color: TBDColor; const Range: TBDColorRange; var Left, Top: Integer): Boolean; var Aspect: TAspect; VisitCount, Count, i: Integer; begin result := false; VisitCount := 0; Aspect := asUp; Count := 1; while VisitCount < (self.FWidth * self.FHeight) do begin for i := 0 to Count - 1 do begin if (Left >= 0) and (Left < self.FWidth) and (Top >= 0) and (Top < self.FHeight) then begin if BDCompareColor(self.GetPixels(Left, Top), Color, Range) then begin result := true; break; end; VisitCount := VisitCount + 1; end; Left := Left + MoveVal[Aspect].X; Top := Top + MoveVal[Aspect].Y; end; if result then break; case Aspect of asLeft: begin Aspect := asUp; Count := Count + 1; end; asRight: begin Aspect := asDown; Count := Count + 1; end; asUp: begin Aspect := asRight; end; asDown: begin Aspect := asLeft; end; end; end; if not result then begin Left := -1; Top := -1; end; end; // 从当前位图中查找所有指定的颜色,忽略self.FBackColor设置,返回是否找到, // 无论是否找到都不会修改self.Error, // 按从左到右,从上到下的顺序查找, // 每找到一个颜色,就调用回调函数EnumColorProc,如果EnumColorProc // 返回false就停止查找,结束函数, // Color:BGR格式颜色; // EnumColorProc:回调函数; // lParam:调用回调函数时发出的参数,可省略。 function TBDBitmapData.EnumColor(Color: TBDColor; EnumColorProc: TBDEnumColorProc; lParam: Integer): Boolean; var X, Y, LineOff, Off: Integer; Res: Boolean; C: TBDColor; begin result := false; LineOff := self.FSize; Res := true; for Y := 0 to self.FHeight - 1 do begin LineOff := LineOff - self.FLineWidth; Off := LineOff; for X := 0 to self.FWidth - 1 do begin C := ((PInteger(@(self.FBits[Off])))^ and $FFFFFF); result := C = Color; if result then begin Res := EnumColorProc(X, Y, C, lParam); if not Res then break; end; Off := Off + 3; end; if not Res then break; end; end; // 从当前位图中模糊查找所有指定的颜色,忽略self.FBackColor设置,返回是否找到, // 无论是否找到都不会修改self.Error, // 按从左到右,从上到下的顺序查找, // 每找到一个颜色,就调用回调函数EnumColorProc,如果EnumColorProc // 返回false就停止查找,结束函数, // Color:BGR格式颜色; // Range:为颜色变化范围; // EnumColorProc:回调函数; // lParam:调用回调函数时发出的参数,可省略。 function TBDBitmapData.EnumColor(Color: TBDColor; const Range: TBDColorRange; EnumColorProc: TBDEnumColorProc; lParam: Integer): Boolean; var X, Y, LineOff, Off: Integer; Res: Boolean; C: TBDColor; begin result := false; LineOff := self.FSize; Res := true; for Y := 0 to self.FHeight - 1 do begin LineOff := LineOff - self.FLineWidth; Off := LineOff; for X := 0 to self.FWidth - 1 do begin C := ((PInteger(@(self.FBits[Off])))^ and $FFFFFF); result := BDCompareColor(C, Color, Range); if result then begin Res := EnumColorProc(X, Y, C, lParam); if not Res then break; end; Off := Off + 3; end; if not Res then break; end; end; // 单元初始化 initialization begin ScreenWidth := GetSystemMetrics(SM_CXSCREEN); ScreenHeight := GetSystemMetrics(SM_CYSCREEN); IconWidth := GetSystemMetrics(SM_CXICON); IconHeight := GetSystemMetrics(SM_CYICON); end; end.
{ 文件名:uData.pas 说 明:数据操作单元 编写人:刘景威 日 期:2008-05-16 更 新: } unit uData; interface uses Classes, Windows, SysUtils, DB, ADODB, Variants, ImgList, Controls, DateUtils, ComObj, Forms, FR_Class, FR_DSet, FR_DBSet, Printers; type TdmPer = class(TDataModule) acPer: TADOConnection; aqStaff: TADOQuery; dsStaff: TDataSource; aqStafr: TADOQuery; aqStat: TADOQuery; ilTree: TImageList; aqTemp: TADOQuery; aqDict: TADOQuery; aqDept: TADOQuery; ilTool: TImageList; frds: TfrDBDataSet; frStaff: TfrReport; aqLeaver: TADOQuery; frdsr: TfrDBDataSet; frLeave: TfrReport; aqStaffid: TAutoIncField; aqStaffstaffNo: TWideStringField; aqStaffstaffName: TWideStringField; aqStaffstaffPY: TWideStringField; aqStaffsex: TWideStringField; aqStaffbirth: TDateTimeField; aqStaffage: TIntegerField; aqStafffolk: TWideStringField; aqStaffmarriage: TWideStringField; aqStaffpolitics: TWideStringField; aqStaffinPartyDate: TDateTimeField; aqStaffidCardNo: TWideStringField; aqStaffinWorkDate: TDateTimeField; aqStaffculture: TWideStringField; aqStaffschool: TWideStringField; aqStaffspecial: TWideStringField; aqStaffgraduateDate: TDateTimeField; aqStaffnativePlace: TWideStringField; aqStaffnpAddr: TWideStringField; aqStaffrecordNo: TWideStringField; aqStaffregDate: TDateTimeField; aqStaffreger: TWideStringField; aqStaffphotoStr: TWideStringField; aqStaffdeptName: TWideStringField; aqStaffduty: TWideStringField; aqStaffworkKind: TWideStringField; aqStafftechnic: TWideStringField; aqStaffworkState: TIntegerField; aqStaffinDutyDate: TDateTimeField; aqStafftoStaffDate: TDateTimeField; aqStaffleftDate: TDateTimeField; aqStaffbankName: TWideStringField; aqStaffpayNo: TWideStringField; aqStaffannuityNo: TWideStringField; aqStaffmedicareNo: TWideStringField; aqStaffmobile: TWideStringField; aqStafftel: TWideStringField; aqStaffemail: TWideStringField; aqStaffcityTel: TWideStringField; aqStaffpostAddr: TWideStringField; aqStaffpostCode: TWideStringField; aqStaffqqCode: TWideStringField; aqStaffselfBio: TMemoField; aqStafffamily: TMemoField; aqStaffworkExper: TMemoField; aqStaffapRecord: TMemoField; aqStafftrainRecord: TMemoField; aqStaffothers: TMemoField; aqStaffmodifyDate: TDateTimeField; aqStaffno: TIntegerField; aqLeave: TADOQuery; aqStaffbirthGreg: TDateTimeField; aqStaffmoveRecord: TMemoField; aqGet: TADOQuery; procedure DataModuleCreate(Sender: TObject); procedure DataModuleDestroy(Sender: TObject); procedure acPerAfterConnect(Sender: TObject); procedure aqStaffCalcFields(DataSet: TDataSet); procedure aqStaffworkStateGetText(Sender: TField; var Text: String; DisplayText: Boolean); procedure aqStaffworkStateSetText(Sender: TField; const Text: String); procedure frStaffGetValue(const ParName: String; var ParValue: Variant); private { Private declarations } public { Public declarations } //调整表结构,向旧版本兼容... procedure AdjustTable; //计算生日相关 procedure DealBirth; //查询相关 function OpenQuery(AADOQuery: TADOQuery; const ASqlStr: string): Boolean; function ExecSQL(const ASqlStr: string): Integer; procedure OpenDept; procedure OpenDict; procedure OpenStaff; //为实现待销假员工高亮显示而特设 procedure OpenLeave; procedure OpenStat(const AWhr, AGrpStr: string; AKindType: Integer); function GetFieldValue(const ASqlStr, AFieldName: string): Variant; //处理奖惩、培训记录入主表中 procedure DealAPRecord; procedure DealTrainRecord; procedure DealMoveRecord; //打印 procedure PrintCurrent; procedure PrintAll; procedure SetPrint; procedure PrintLeave(const ASqlStr: string); overload; procedure PrintLeave(const ALeaveId: Integer); overload; //压缩数据库 procedure CompactAccess(const ADBName: string; JetId: string = '4.0'); //压缩 function CompressData(AHandle: THandle): Boolean; //是否可以显示事件提醒 function GetCanAwake: Boolean; end; var dmPer: TdmPer; implementation uses uGlobal, uLunar, uApp; {$R *.dfm} { TdmPer } procedure TdmPer.DataModuleCreate(Sender: TObject); begin if acPer.Connected then acPer.Close; acPer.ConnectionString := 'Provider=Microsoft.Jet.OLEDB.4.0;Data Source=' + App.DataPath + ';Persist Security Info=False;Jet OLEDB:Database Password=780927+790621'; acPer.Open(); //处理表结构 AdjustTable(); DealBirth(); //更新请假状态 ExecSQL('UPDATE [staffs] SET workState=0 WHERE workState=2 AND NOT EXISTS (SELECT id FROM [leave] WHERE staffId=staffs.id AND isLeave=TRUE)'); //然后再打开数据集 if not aqStaff.Active then OpenStaff; if not aqLeave.Active then OpenLeave; end; procedure TdmPer.DataModuleDestroy(Sender: TObject); begin if acPer.Connected then acPer.Close; end; procedure TdmPer.acPerAfterConnect(Sender: TObject); begin if not aqLeave.Active then OpenLeave(); end; procedure TdmPer.AdjustTable; var sl: TStrings; begin //从2.2.5之前版本升级到2.2.5,admin表中lgCount不再用,加入lgTime来标记 sl := TStringList.Create; try acPer.GetFieldNames('admin', sl); if sl.IndexOf('lgTime') = -1 then begin //加入lgTime字段,且设其默认值为Now() ExecSQL('ALTER TABLE [admin] ADD COLUMN lgTime DateTime DEFAULT Now()'); //去除原lgCount字段 ExecSQL('ALTER TABLE [admin] DROP COLUMN lgCount'); end; finally sl.Free; end; end; procedure TdmPer.DealBirth; var sDate: string; begin sDate := FormatDateTime('yyyy-mm', Date()); if App.LastDate <> sDate then begin App.LastDate := sDate; //重算年龄值 ExecSQL('UPDATE [staffs] SET age=DateDiff("yyyy", birth, Date()) WHERE NOT birth IS NULL'); //计算生日对应今年之阳历 OpenQuery(aqTemp, 'SELECT id, birth, birthGreg FROM [staffs]'); if aqTemp.RecordCount > 0 then begin aqTemp.First; while not aqTemp.Eof do begin if not aqTemp.FieldByName('birth').IsNull then begin aqTemp.Edit; aqTemp.FieldByName('birthGreg').AsDateTime := ToGreg(aqTemp.FieldByName('birth').AsDateTime); aqTemp.Post; end; aqTemp.Next; end; aqTemp.UpdateBatch(); end; end; end; function TdmPer.OpenQuery(AADOQuery: TADOQuery; const ASqlStr: string): Boolean; begin with AADOQuery do begin try if Active then Close; Connection := acPer; Filtered := False; LockType := ltBatchOptimistic; SQL.Clear; SQL.Text := ASqlStr; Open; Result := True; except Result := False; end; end; end; function TdmPer.ExecSQL(const ASqlStr: string): Integer; begin Result := 0; if not acPer.Connected or (Trim(ASqlStr) = '') then Exit; acPer.Execute(ASqlStr, Result); end; procedure TdmPer.OpenStaff; var sSql: string; begin if App.StateIndex = 0 then sSql := 'SELECT * FROM [staffs] ORDER BY staffNo' else if App.StateIndex = 1 then sSql := 'SELECT * FROM [staffs] WHERE workState <> 1 ORDER BY staffNo' else sSql := 'SELECT * FROM [staffs] WHERE workState=1 ORDER BY staffNo'; OpenQuery(aqStaff, sSql); end; procedure TdmPer.OpenLeave; begin OpenQuery(aqLeave, 'SELECT * FROM [leave] ORDER BY id DESC'); end; procedure TdmPer.OpenDept; begin OpenQuery(aqDept, 'SELECT * FROM [dept] ORDER BY sortNo'); end; procedure TdmPer.OpenDict; begin OpenQuery(aqDict, 'SELECT * FROM [dict] ORDER BY sortNo'); end; //统计所需过程 Access不支持GROUP BY ALL查询语句 procedure TdmPer.OpenStat(const AWhr, AGrpStr: string; AKindType: Integer); var sSql: string; begin //sSql := 'SELECT '+ AGrpStr +', Count(id) AS [staCount] FROM [staffs] WHERE ' // + AWhr + ' GROUP BY '+ AGrpStr; //以下代码,解决Access不支持GROUP BY ALL问题 sSql := 'SELECT sortNo, kindName, sc.staCount FROM [dict] LEFT JOIN ' + '(SELECT ' + AGrpStr + ', Count(staffs.id) as [staCount] FROM [staffs] WHERE ' + AWhr + ' GROUP BY ' + AGrpStr + ') sc ' + 'ON dict.kindName=sc.' + AGrpStr + ' WHERE dict.kindType=' + IntToStr(AKindType) + ' UNION ' + 'SELECT 1000, ''未指定'' AS kindName, Count(id) AS staCount FROM [staffs] WHERE ' + AWhr + ' AND (' + AGrpStr + ' IS NULL OR NOT EXISTS ' + '(SELECT id FROM [dict] WHERE kindType=' + IntToStr(AKindType) + ' AND kindName=' + AGrpStr + '))'; //弃用下面IN语句,是因为EXISTS效率大于IN //'SELECT 1, ''未指定'' AS kindName, Count(id) AS staCount FROM [staffs] WHERE ' + AWhr + ' AND (' + AGrpStr + ' IS NULL OR ' + AGrpStr + ' NOT IN ' + //'(SELECT kindName FROM [dict] WHERE kindType=' + IntToStr(AKindType) + '))'; OpenQuery(aqStat, sSql); end; function TdmPer.GetFieldValue(const ASqlStr, AFieldName: string): Variant; begin if OpenQuery(aqGet, ASqlStr) and not aqGet.Eof and not aqGet.FieldByName(AFieldName).IsNull then Result := aqGet.FieldByName(AFieldName).AsVariant else Result := ''; end; procedure TdmPer.DealAPRecord; var sAP: string; i, curId: Integer; begin OpenQuery(aqTemp, 'SELECT * FROM [ap] ORDER BY staffId, apDate'); if aqTemp.Eof then Exit; ExecSQL('UPDATE [staffs] SET apRecord='''''); aqTemp.First; for i := 0 to aqTemp.RecordCount - 1 do begin //取值 curId := aqTemp.FieldByName('staffId').AsInteger; sAP := sAP + '奖惩日期:' +aqTemp.FieldByName('apDate').AsString + ';类别:' + aqTemp.FieldByName('apType').AsString + ';原因:' + aqTemp.FieldByName('reason').AsString + ';结果:' + aqTemp.FieldByName('result').AsString + ';处理部门:' + aqTemp.FieldByName('operDept').AsString + ';备注信息:' + aqTemp.FieldByName('des').AsString + #13#10; aqTemp.Next; //入库 if (curId <> aqTemp.FieldByName('staffId').AsInteger) or aqTemp.Eof then begin ExecSQL('UPDATE [staffs] SET apRecord=''' + sAp + ''' WHERE id=' + IntToStr(curId)); sAP := ''; end; end; end; procedure TdmPer.DealTrainRecord; var sTrain: string; i, curId: Integer; begin OpenQuery(aqTemp, 'SELECT * FROM [train] ORDER BY staffId, trDate'); if aqTemp.Eof then Exit; ExecSQL('UPDATE [staffs] SET trainRecord='''''); aqTemp.First; for i := 0 to aqTemp.RecordCount - 1 do begin //取值 curId := aqTemp.FieldByName('staffId').AsInteger; sTrain := sTrain + '培训名称:' + aqTemp.FieldByName('trName').AsString + ';日期:' + aqTemp.FieldByName('trDate').AsString + ';地点:' + aqTemp.FieldByName('trSite').AsString + ';讲师:' + aqTemp.FieldByName('trainer').AsString + ';内容:' + aqTemp.FieldByName('content').AsString + ';备注信息:' + aqTemp.FieldByName('des').AsString + #13#10; aqTemp.Next; //入库 if (curId <> aqTemp.FieldByName('staffId').AsInteger) or aqTemp.Eof then begin ExecSQL('UPDATE [staffs] SET trainRecord=''' + sTrain + ''' WHERE id=' + IntToStr(curId)); sTrain := ''; end; end; end; procedure TdmPer.DealMoveRecord; var sMove: string; i, curId: Integer; begin OpenQuery(aqTemp, 'SELECT * FROM [move] ORDER BY staffId, moveDate'); if aqTemp.Eof then Exit; ExecSQL('UPDATE [staffs] SET moveRecord='''''); aqTemp.First; for i := 0 to aqTemp.RecordCount - 1 do begin //取值 curId := aqTemp.FieldByName('staffId').AsInteger; sMove := sMove + '调动日期:' + aqTemp.FieldByName('moveDate').AsString + ';' + '备注信息:' + aqTemp.FieldByName('newTech').AsString + #13#10 + '调动前' + App.ViewSet.DeptStr + ':' + aqTemp.FieldByName('oldDept').AsString + ';调动前' + App.ViewSet.DutyStr + ':' + aqTemp.FieldByName('oldDuty').AsString + ';调动前' + App.ViewSet.TypeStr + ':' + aqTemp.FieldByName('oldKind').AsString + ';调动前' + App.ViewSet.TechnicStr + ':' + aqTemp.FieldByName('oldTech').AsString + #13#10 + '调动后' + App.ViewSet.DeptStr + ':' + aqTemp.FieldByName('newDept').AsString + ';调动后' + App.ViewSet.DutyStr + ':' + aqTemp.FieldByName('newDuty').AsString + ';调动后' + App.ViewSet.TypeStr + ':' + aqTemp.FieldByName('newKind').AsString + ';调动后' + App.ViewSet.TechnicStr + ':' + aqTemp.FieldByName('newTech').AsString + #13#10; aqTemp.Next; //入库 if (curId <> aqTemp.FieldByName('staffId').AsInteger) or aqTemp.Eof then begin ExecSQL('UPDATE [staffs] SET moveRecord=''' + sMove + ''' WHERE id=' + IntToStr(curId)); sMove := ''; end; end; end; procedure TdmPer.aqStaffCalcFields(DataSet: TDataSet); begin aqStaff.FieldByName('no').AsInteger := Abs(aqStaff.RecNo); end; procedure TdmPer.aqStaffworkStateGetText(Sender: TField; var Text: String; DisplayText: Boolean); begin if Sender.DataSet.RecordCount = 0 then Exit; if Sender.AsInteger = 1 then Text := '离职' else if Sender.AsInteger = 2 then Text := '请假' else Text := '在职'; end; procedure TdmPer.aqStaffworkStateSetText(Sender: TField; const Text: String); begin if Text = '离职' then Sender.AsInteger := 1 else Sender.AsInteger := 0; end; procedure TdmPer.PrintCurrent; begin OpenQuery(aqStafr, 'SELECT * FROM [staffs] WHERE id=' + aqStaff.FieldByName('id').AsString); SetPrint(); end; procedure TdmPer.PrintAll; begin aqStafr.Clone(aqStaff, ltReadOnly); aqStafr.Requery(); if aqStaff.Filtered then FilterData(aqStafr, aqStaff.Filter); SetPrint(); end; procedure TdmPer.SetPrint; var fs, fv: TfrBandView; i, Index: Integer; meoCap: TfrMemoView; procedure DealBound(const ABandName: string); begin if fv <> nil then fv.ChildBand := ABandName; fv := TfrBandView(frStaff.FindObject(ABandName)); if fs.ChildBand = '' then fs.ChildBand := ABandName; end; begin fs := TfrBandView(frStaff.FindObject('bvStaff')); fv := nil; TfrBandView(frStaff.FindObject('bvStaff')).ChildBand := ''; TfrBandView(frStaff.FindObject('bvBasic')).ChildBand := ''; TfrBandView(frStaff.FindObject('bvContact')).ChildBand := ''; TfrBandView(frStaff.FindObject('bvSelf')).ChildBand := ''; TfrBandView(frStaff.FindObject('bvFami')).ChildBand := ''; TfrBandView(frStaff.FindObject('bvExper')).ChildBand := ''; TfrBandView(frStaff.FindObject('bvAP')).ChildBand := ''; TfrBandView(frStaff.FindObject('bvTrain')).ChildBand := ''; TfrBandView(frStaff.FindObject('bvMove')).ChildBand := ''; TfrBandView(frStaff.FindObject('bvOther')).ChildBand := ''; with App.PrintSet do begin //基本信息 if PrintBase then DealBound('bvBasic'); if PrintDept then DealBound('bvDept'); if PrintContact then DealBound('bvContact'); if PrintSelf then DealBound('bvSelf'); if PrintFami then DealBound('bvFami'); if PrintExper then DealBound('bvExper'); if PrintAP then DealBound('bvAP'); if PrintTrain then DealBound('bvTrain'); if PrintMove then DealBound('bvMove'); if PrintOther then DealBound('bvOther'); end; //项目名称赋值...此标识为处理[任职状态]而设 Index := 1; with App.GridSet do for i := 1 to FieldLabels.Count - 1 do begin if i = 25 then Continue; meoCap := TfrMemoView(frStaff.FindObject('Label' + IntToStr(Index))); if meoCap <> nil then meoCap.Memo.Text := FieldLabels[i]; Inc(Index); end; //照片路径;赋值须再加双引号 frStaff.Dictionary.Variables['photoPath'] := QuotedStr(App.Path + 'photos\'); //打印 if App.ParamSet.DoPrint then begin if Printer.Printers.Count = 0 then begin MessageBox(Application.MainForm.Handle, '您的系统中没有可用的打印机,请安装打印机先', '提示', MB_OK + MB_ICONINFORMATION); Exit; end; frStaff.PrepareReport; frStaff.PrintPreparedReportDlg; end else frStaff.ShowReport; end; procedure TdmPer.PrintLeave(const ASqlStr: string); begin if ASqlStr = '' then Exit; OpenQuery(aqLeaver, ASqlStr); if App.ParamSet.DoPrint then begin if Printer.Printers.Count = 0 then begin MessageBox(Application.MainForm.Handle, '您的系统中没有可用的打印机,请安装打印机先', '提示', MB_OK + MB_ICONINFORMATION); Exit; end; frLeave.PrepareReport; frLeave.PrintPreparedReportDlg; end else frLeave.ShowReport; end; procedure TdmPer.PrintLeave(const ALeaveId: Integer); begin PrintLeave('SELECT * FROM [leave] WHERE id=' + IntToStr(ALeaveId)); end; procedure TdmPer.frStaffGetValue(const ParName: String; var ParValue: Variant); begin if ParName = 'company' then begin ParValue := App.Company.Name; if App.RegType = rtUnReged then ParValue := ParValue + ' - 未注册版'; end; end; procedure TdmPer.CompactAccess(const ADBName: string; JetId: string); var vData: Variant; begin if not FileExists(ADBName) then Exit; if FileExists(ADBName + '.tmp') then DeleteFile(ADBName + '.tmp'); vData := CreateOleObject('JRO.JetEngine'); vData.CompactDataBase('Provider=Microsoft.Jet.OLEDB.' + JetId + ';Jet OLEDB:DataBase Password=780927+790621;Data Source=' + ADBName , 'Provider=Microsoft.Jet.OLEDB.' + JetId + ';Jet OLEDB:DataBase Password=780927+790621;Data Source=' + ADBName + '.tmp'); DeleteFile(ADBName); RenameFile(ADBName + '.tmp', ADBName); end; function TdmPer.CompressData(AHandle: THandle): Boolean; var sOldSize, sNewSize: string; begin if acPer.Connected then acPer.Close; try try sOldSize := FormatFloat('0.## KB', GetFileSize(App.DataPath)); CompactAccess(App.DataPath); sNewSize := FormatFloat('0.## KB', GetFileSize(App.DataPath)); Result := True; MessageBox(AHandle, PAnsiChar('数据库压缩修复操作成功。' + #13#10 + '压缩前大小:' + sOldSize + ',压缩后大小:' + sNewSize), '提示', MB_OK + MB_ICONINFORMATION); Log.Write(App.UserID + '对数据库进行压缩修复操作'); except on E: Exception do begin Log.Write(App.UserID + '压缩数据库失败,信息:' + E.Message); MessageBox(AHandle, PAnsiChar('数据库压缩修复失败,请确定数据库不在使用中。' + #13#10 + '信息:' + E.Message), '提示', MB_OK + MB_ICONWARNING); Result := False; end; end; finally acPer.Connected := True; PostMessage(AHandle, WM_DATACOMPRESSED, 0, 0); end; end; function TdmPer.GetCanAwake: Boolean; var sSql: string; begin Result := False; if not App.ParamSet.AwakeSet.Enabled then Exit; //生日人数 if not App.ParamSet.AwakeSet.BirthGreg then sSql := 'SELECT id FROM [staffs] WHERE workState <> 1 AND (' + //当年 'DateAdd("yyyy", DatePart("yyyy", Date()) - DatePart("yyyy", iif(birth IS NULL, 0, birth)), iif(birth IS NULL, 0, birth)) - Date() BETWEEN 0 AND ' + IntToStr(App.ParamSet.AwakeSet.BirthDay) + ' OR ' + //跨年 'DateAdd("yyyy", DatePart("yyyy", Date() + ' + IntToStr(App.ParamSet.AwakeSet.BirthDay) + ') - DatePart("yyyy", iif(birth IS NULL, 0, birth)), iif(birth IS NULL, 0, birth)) - Date() BETWEEN 0 AND ' + IntToStr(App.ParamSet.AwakeSet.BirthDay) + ')' else sSql := 'SELECT id FROM [staffs] WHERE workState <> 1 AND (' + //当年 'DateAdd("yyyy", DatePart("yyyy", Date()) - DatePart("yyyy", iif(birthGreg IS NULL, 0, birthGreg)), iif(birthGreg IS NULL, 0, birthGreg)) - Date() BETWEEN 0 AND ' + IntToStr(App.ParamSet.AwakeSet.BirthDay) + ' OR ' + //跨年 'DateAdd("yyyy", DatePart("yyyy", Date() + ' + IntToStr(App.ParamSet.AwakeSet.BirthDay) + ') - DatePart("yyyy", iif(birthGreg IS NULL, 0, birthGreg)), iif(birthGreg IS NULL, 0, birthGreg)) - Date() BETWEEN 0 AND ' + IntToStr(App.ParamSet.AwakeSet.BirthDay) + ')'; OpenQuery(aqTemp, sSql); Result := not aqTemp.Eof; if Result then Exit; //合同到期人数 sSql := 'SELECT id FROM [contract] WHERE endDate BETWEEN #' + DateToStr(Date()) + '# AND #' + DateToStr(IncDay(Date(), App.ParamSet.AwakeSet.ContractDay)) + '#'; OpenQuery(aqTemp, sSql); Result := not aqTemp.Eof; if Result then Exit; //近期转正员工 sSql := 'SELECT id FROM [staffs] WHERE workState <> 1 AND toStaffDate BETWEEN #' + DateToStr(Date()) + '# AND #' + DateToStr(IncDay(Date(), App.ParamSet.AwakeSet.StaffDay)) + '#'; OpenQuery(aqTemp, sSql); Result := not aqTemp.Eof; end; end.
{ DBE Brasil é um Engine de Conexão simples e descomplicado for Delphi/Lazarus Copyright (c) 2016, Isaque Pinheiro All rights reserved. GNU Lesser General Public License Versão 3, 29 de junho de 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> A todos é permitido copiar e distribuir cópias deste documento de licença, mas mudá-lo não é permitido. Esta versão da GNU Lesser General Public License incorpora os termos e condições da versão 3 da GNU General Public License Licença, complementado pelas permissões adicionais listadas no arquivo LICENSE na pasta principal. } { @abstract(DBEBr Framework) @created(20 Jul 2016) @author(Isaque Pinheiro <https://www.isaquepinheiro.com.br>) } unit dbebr.driver.firedac.mongodb; interface uses Classes, SysUtils, StrUtils, JSON.Types, JSON.Readers, JSON.BSON, JSON.Builders, Variants, Data.DB, // FireDAC FireDAC.Stan.Intf, FireDAC.Stan.Option, FireDAC.Stan.Error, FireDAC.UI.Intf, FireDAC.Phys.Intf, FireDAC.Stan.Def, FireDAC.Stan.Pool, FireDAC.Stan.Async, FireDAC.Phys, FireDAC.Phys.MongoDB, FireDAC.Phys.MongoDBDef, FireDAC.Phys.MongoDBWrapper, FireDAC.VCLUI.Wait, FireDAC.Stan.Param, FireDAC.DatS, FireDAC.DApt.Intf, FireDAC.Phys.MongoDBDataSet, FireDAC.Comp.Client, FireDAC.Comp.UI, // DBEBr dbebr.driver.connection, dbebr.factory.interfaces; type // Classe de conexão concreta com FireDAC TDriverMongoFireDAC = class(TDriverConnection) protected FConnection: TFDConnection; // FSQLScript : TFDMongoQuery; FMongoEnv: TMongoEnv; FMongoConnection: TMongoConnection; procedure CommandUpdateExecute(const ACommandText: String; const AParams: TParams); procedure CommandInsertExecute(const ACommandText: String; const AParams: TParams); procedure CommandDeleteExecute(const ACommandText: String; const AParams: TParams); public constructor Create(const AConnection: TComponent; const ADriverName: TDriverName); override; destructor Destroy; override; procedure Connect; override; procedure Disconnect; override; procedure ExecuteDirect(const ASQL: string); override; procedure ExecuteDirect(const ASQL: string; const AParams: TParams); override; procedure ExecuteScript(const ASQL: string); override; procedure AddScript(const ASQL: string); override; procedure ExecuteScripts; override; function IsConnected: Boolean; override; function InTransaction: Boolean; override; function CreateQuery: IDBQuery; override; function CreateResultSet(const ASQL: string): IDBResultSet; override; function ExecuteSQL(const ASQL: string): IDBResultSet; override; end; TDriverQueryMongoFireDAC = class(TDriverQuery) private FConnection: TFDConnection; FFDMongoQuery: TFDMongoQuery; FMongoConnection: TMongoConnection; FMongoEnv: TMongoEnv; protected procedure SetCommandText(ACommandText: string); override; function GetCommandText: string; override; public constructor Create(AConnection: TFDConnection; AMongoConnection: TMongoConnection; AMongoEnv: TMongoEnv); destructor Destroy; override; procedure ExecuteDirect; override; function ExecuteQuery: IDBResultSet; override; end; TDriverResultSetMongoFireDAC = class(TDriverResultSet<TFDMongoQuery>) public constructor Create(ADataSet: TFDMongoQuery); override; destructor Destroy; override; function NotEof: Boolean; override; function GetFieldValue(const AFieldName: string): Variant; overload; override; function GetFieldValue(const AFieldIndex: Integer): Variant; overload; override; function GetFieldType(const AFieldName: string): TFieldType; overload; override; function GetField(const AFieldName: string): TField; override; end; implementation uses ormbr.utils; { TDriverMongoFireDAC } constructor TDriverMongoFireDAC.Create(const AConnection: TComponent; const ADriverName: TDriverName); begin inherited; FConnection := AConnection as TFDConnection; FDriverName := ADriverName; FMongoConnection := TMongoConnection(FConnection.CliObj); FMongoEnv := FMongoConnection.Env; // FSQLScript := TFDMongoQuery.Create(nil); // try // FSQLScript.Connection := FConnection; // FSQLScript.DatabaseName := FConnection.Params.Database; // except // FSQLScript.Free; // raise; // end; end; destructor TDriverMongoFireDAC.Destroy; begin FConnection := nil; // FSQLScript.Free; inherited; end; procedure TDriverMongoFireDAC.Disconnect; begin inherited; FConnection.Connected := False; end; procedure TDriverMongoFireDAC.ExecuteDirect(const ASQL: string); begin inherited; raise Exception.Create('Command [ExecuteDirect()] not supported for NoSQL MongoDB database!'); // FConnection.ExecSQL(ASQL); end; procedure TDriverMongoFireDAC.ExecuteDirect(const ASQL: string; const AParams: TParams); var LCommand: string; begin LCommand := TUtilSingleton .GetInstance .ParseCommandNoSQL('command', ASQL); if LCommand = 'insert' then CommandInsertExecute(ASQL, Aparams) else if LCommand = 'update' then CommandUpdateExecute(ASQL, AParams) else if LCommand = 'delete' then CommandDeleteExecute(ASQL, AParams); end; procedure TDriverMongoFireDAC.ExecuteScript(const ASQL: string); begin inherited; // FSQLScript.QMatch := ASQL; // FSQLScript.Execute; raise Exception .Create('Command [ExecuteScript()] not supported for NoSQL MongoDB database!'); end; procedure TDriverMongoFireDAC.ExecuteScripts; begin inherited; raise Exception .Create('Command [ExecuteScripts()] not supported for NoSQL MongoDB database!'); // if Length(FSQLScript.QMatch) > 0 then // begin // try // FSQLScript.Execute; // finally // FSQLScript.QMatch := ''; // end; // end; end; function TDriverMongoFireDAC.ExecuteSQL(const ASQL: string): IDBResultSet; var LDBQuery: IDBQuery; begin LDBQuery := TDriverQueryMongoFireDAC.Create(FConnection, FMongoConnection, FMongoEnv); LDBQuery.CommandText := ASQL; Result := LDBQuery.ExecuteQuery; end; procedure TDriverMongoFireDAC.AddScript(const ASQL: string); begin inherited; // FSQLScript.QMatch := ASQL; raise Exception .Create('Command [AddScript()] not supported for NoSQL MongoDB database!'); end; procedure TDriverMongoFireDAC.CommandDeleteExecute(const ACommandText: String; const AParams: TParams); var LMongoSelector: TMongoSelector; LUtil: IUtilSingleton; begin LMongoSelector := TMongoSelector.Create(FMongoEnv); LUtil := TUtilSingleton.GetInstance; try LMongoSelector.Match(LUtil.ParseCommandNoSQL('json', ACommandText)); // LMongoSelector.FinalMatchBSON.AsJSON; FMongoConnection[FConnection.Params.Database] [LUtil.ParseCommandNoSQL('collection', ACommandText)] .Remove(LMongoSelector); finally LMongoSelector.Free; end; end; procedure TDriverMongoFireDAC.CommandInsertExecute(const ACommandText: String; const AParams: TParams); var LMongoInsert: TMongoInsert; LUtil: IUtilSingleton; begin LMongoInsert := TMongoInsert.Create(FMongoEnv); LUtil := TUtilSingleton.GetInstance; try LMongoInsert .Values(LUtil.ParseCommandNoSQL('json', ACommandText)); // LMongoInsert.FinalValuesBSON.AsJSON; FMongoConnection[FConnection.Params.Database] [LUtil.ParseCommandNoSQL('collection', ACommandText)] .Insert(LMongoInsert) finally LMongoInsert.Free; end; end; procedure TDriverMongoFireDAC.CommandUpdateExecute(const ACommandText: String; const AParams: TParams); var LMongoUpdate: TMongoUpdate; LUtil: IUtilSingleton; begin LMongoUpdate := TMongoUpdate.Create(FMongoEnv); LUtil := TUtilSingleton.GetInstance; try LMongoUpdate .Match(LUtil.ParseCommandNoSQL('filter', ACommandText)); LMongoUpdate .Modify(LUtil.ParseCommandNoSQL('json', ACommandText)); // LMongoUpdate.FinalModifyBSON.AsJSON; FMongoConnection[FConnection.Params.Database] [LUtil.ParseCommandNoSQL('collection', ACommandText)] .Update(LMongoUpdate); finally LMongoUpdate.Free; end; end; procedure TDriverMongoFireDAC.Connect; begin inherited; FConnection.Connected := True; end; function TDriverMongoFireDAC.InTransaction: Boolean; begin Result := FConnection.InTransaction; end; function TDriverMongoFireDAC.IsConnected: Boolean; begin inherited; Result := FConnection.Connected; end; function TDriverMongoFireDAC.CreateQuery: IDBQuery; begin Result := TDriverQueryMongoFireDAC.Create(FConnection, FMongoConnection, FMongoEnv); end; function TDriverMongoFireDAC.CreateResultSet(const ASQL: string): IDBResultSet; var LDBQuery: IDBQuery; begin LDBQuery := TDriverQueryMongoFireDAC.Create(FConnection, FMongoConnection, FMongoEnv); LDBQuery.CommandText := ASQL; Result := LDBQuery.ExecuteQuery; end; { TDriverDBExpressQuery } constructor TDriverQueryMongoFireDAC.Create(AConnection: TFDConnection; AMongoConnection: TMongoConnection; AMongoEnv: TMongoEnv); begin FConnection := AConnection; FMongoConnection := AMongoConnection; FMongoEnv := AMongoEnv; if AConnection = nil then Exit; FFDMongoQuery := TFDMongoQuery.Create(nil); try FFDMongoQuery.Connection := AConnection; FFDMongoQuery.DatabaseName := AConnection.Params.Database; except FFDMongoQuery.Free; raise; end; end; destructor TDriverQueryMongoFireDAC.Destroy; begin FConnection := nil; FFDMongoQuery.Free; inherited; end; function TDriverQueryMongoFireDAC.ExecuteQuery: IDBResultSet; var LResultSet: TFDMongoQuery; LLimit, LSkip: Integer; LUtil: IUtilSingleton; begin LResultSet := TFDMongoQuery.Create(nil); LResultSet.CachedUpdates := True; LUtil := TUtilSingleton.GetInstance; try LResultSet.Connection := FFDMongoQuery.Connection; LResultSet.DatabaseName := FFDMongoQuery.Connection.Params.Database; LResultSet.CollectionName := LUtil.ParseCommandNoSQL('collection', FFDMongoQuery.QMatch); LResultSet.QMatch := LUtil.ParseCommandNoSQL('filter', FFDMongoQuery.QMatch); LResultSet.QSort := LUtil.ParseCommandNoSQL('sort', FFDMongoQuery.QMatch); LLimit := StrToIntDef(LUtil.ParseCommandNoSQL('limit', FFDMongoQuery.QMatch), 0); LSkip := StrToIntDef(LUtil.ParseCommandNoSQL('skip', FFDMongoQuery.QMatch), 0); if LLimit > 0 then LResultSet.Query.Limit(LLimit); if LSkip > 0 then LResultSet.Query.Skip(LSkip); LResultSet.QProject := '{_id:0}'; LResultSet.Open; // LResultSet.Query.FinalQueryBSON.AsJSON; except LResultSet.Free; raise; end; Result := TDriverResultSetMongoFireDAC.Create(LResultSet); if LResultSet.RecordCount = 0 then Result.FetchingAll := True; end; function TDriverQueryMongoFireDAC.GetCommandText: string; begin Result := FFDMongoQuery.QMatch; end; procedure TDriverQueryMongoFireDAC.SetCommandText(ACommandText: string); begin inherited; FFDMongoQuery.QMatch := ACommandText; end; procedure TDriverQueryMongoFireDAC.ExecuteDirect; begin // FFDMongoQuery.Execute; raise Exception .Create('Command [ExecuteDirect()] not supported for NoSQL MongoDB database!'); end; { TDriverResultSetMongoFireDAC } constructor TDriverResultSetMongoFireDAC.Create(ADataSet: TFDMongoQuery); begin FDataSet := ADataSet; inherited; end; destructor TDriverResultSetMongoFireDAC.Destroy; begin FDataSet.Free; inherited; end; function TDriverResultSetMongoFireDAC.GetFieldValue( const AFieldName: string): Variant; var LField: TField; begin LField := FDataSet.FieldByName(AFieldName); Result := GetFieldValue(LField.Index); end; function TDriverResultSetMongoFireDAC.GetFieldType( const AFieldName: string): TFieldType; begin Result := FDataSet.FieldByName(AFieldName).DataType; end; function TDriverResultSetMongoFireDAC.GetFieldValue( const AFieldIndex: Integer): Variant; begin if AFieldIndex > FDataSet.FieldCount - 1 then Exit(Variants.Null); if FDataSet.Fields[AFieldIndex].IsNull then Result := Variants.Null else Result := FDataSet.Fields[AFieldIndex].Value; end; function TDriverResultSetMongoFireDAC.GetField( const AFieldName: string): TField; begin Result := FDataSet.FieldByName(AFieldName); end; function TDriverResultSetMongoFireDAC.NotEof: Boolean; begin if not FFirstNext then FFirstNext := True else FDataSet.Next; Result := not FDataSet.Eof; end; end.
{ ******************************************************************************* Title: T2Ti ERP Description: Janela de Lançamento Padrão do Módulo Contabilidade The MIT License Copyright: Copyright (C) 2016 T2Ti.COM Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. The author may be contacted at: t2ti.com@gmail.com</p> @author Albert Eije (t2ti.com@gmail.com) @version 2.0 ******************************************************************************* } unit UContabilLancamentoPadrao; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, UTelaCadastro, DB, DBClient, Menus, StdCtrls, ExtCtrls, Buttons, Grids, DBGrids, JvExDBGrids, JvDBGrid, JvDBUltimGrid, ComCtrls, ContabilLancamentoPadraoVO, ContabilLancamentoPadraoController, Tipos, Atributos, Constantes, LabeledCtrls, Mask, JvExMask, JvToolEdit, JvMaskEdit, JvExStdCtrls, JvEdit, JvValidateEdit, JvBaseEdits, Controller; type [TFormDescription(TConstantes.MODULO_CONTABILIDADE, 'Lançamento Padrão')] TFContabilLancamentoPadrao = class(TFTelaCadastro) BevelEdits: TBevel; EditDescricao: TLabeledEdit; MemoHistorico: TLabeledMemo; EditContaDebito: TLabeledEdit; EditIdContaDebito: TLabeledCalcEdit; EditContaCredito: TLabeledEdit; EditIdContaCredito: TLabeledCalcEdit; procedure FormCreate(Sender: TObject); procedure EditIdContaDebitoKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); procedure EditIdContaCreditoKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); private { Private declarations } public { Public declarations } procedure GridParaEdits; override; procedure ControlaBotoes; override; procedure ControlaPopupMenu; override; // Controles CRUD function DoInserir: Boolean; override; function DoEditar: Boolean; override; function DoExcluir: Boolean; override; function DoSalvar: Boolean; override; end; var FContabilLancamentoPadrao: TFContabilLancamentoPadrao; implementation uses ULookup, Biblioteca, UDataModule, ContabilContaVO, ContabilContaController; {$R *.dfm} {$REGION 'Controles Infra'} procedure TFContabilLancamentoPadrao.FormCreate(Sender: TObject); begin ClasseObjetoGridVO := TContabilLancamentoPadraoVO; ObjetoController := TContabilLancamentoPadraoController.Create; inherited; end; procedure TFContabilLancamentoPadrao.ControlaBotoes; begin inherited; BotaoImprimir.Visible := False; end; procedure TFContabilLancamentoPadrao.ControlaPopupMenu; begin inherited; MenuImprimir.Visible := False; end; {$ENDREGION} {$REGION 'Controles CRUD'} function TFContabilLancamentoPadrao.DoInserir: Boolean; begin Result := inherited DoInserir; if Result then begin EditDescricao.SetFocus; end; end; function TFContabilLancamentoPadrao.DoEditar: Boolean; begin Result := inherited DoEditar; if Result then begin EditDescricao.SetFocus; end; end; function TFContabilLancamentoPadrao.DoExcluir: Boolean; begin if inherited DoExcluir then begin try TController.ExecutarMetodo('ContabilLancamentoPadraoController.TContabilLancamentoPadraoController', 'Exclui', [IdRegistroSelecionado], 'DELETE', 'Boolean'); Result := TController.RetornoBoolean; except Result := False; end; end else begin Result := False; end; if Result then TController.ExecutarMetodo('ContabilLancamentoPadraoController.TContabilLancamentoPadraoController', 'Consulta', [Trim(Filtro), Pagina.ToString, False], 'GET', 'Lista'); end; function TFContabilLancamentoPadrao.DoSalvar: Boolean; begin Result := inherited DoSalvar; if Result then begin try if not Assigned(ObjetoVO) then ObjetoVO := TContabilLancamentoPadraoVO.Create; TContabilLancamentoPadraoVO(ObjetoVO).IdEmpresa := Sessao.Empresa.Id; TContabilLancamentoPadraoVO(ObjetoVO).Descricao := EditDescricao.Text; TContabilLancamentoPadraoVO(ObjetoVO).Historico := MemoHistorico.Text; TContabilLancamentoPadraoVO(ObjetoVO).IdContaDebito := EditIdContaDebito.AsInteger; TContabilLancamentoPadraoVO(ObjetoVO).IdContaCredito := EditIdContaCredito.AsInteger; if StatusTela = stInserindo then begin TController.ExecutarMetodo('ContabilLancamentoPadraoController.TContabilLancamentoPadraoController', 'Insere', [TContabilLancamentoPadraoVO(ObjetoVO)], 'PUT', 'Lista'); end else if StatusTela = stEditando then begin if TContabilLancamentoPadraoVO(ObjetoVO).ToJSONString <> StringObjetoOld then begin TController.ExecutarMetodo('ContabilLancamentoPadraoController.TContabilLancamentoPadraoController', 'Altera', [TContabilLancamentoPadraoVO(ObjetoVO)], 'POST', 'Boolean'); end else Application.MessageBox('Nenhum dado foi alterado.', 'Mensagem do Sistema', MB_OK + MB_ICONINFORMATION); end; except Result := False; end; end; end; {$ENDREGION} {$REGION 'Controle de Grid'} procedure TFContabilLancamentoPadrao.GridParaEdits; var ContabilContaVO: TContabilContaVO; begin inherited; if not CDSGrid.IsEmpty then begin ObjetoVO := TContabilLancamentoPadraoVO(TController.BuscarObjeto('ContabilLancamentoPadraoController.TContabilLancamentoPadraoController', 'ConsultaObjeto', ['ID=' + IdRegistroSelecionado.ToString], 'GET')); end; if Assigned(ObjetoVO) then begin EditDescricao.Text := TContabilLancamentoPadraoVO(ObjetoVO).Descricao; MemoHistorico.Text := TContabilLancamentoPadraoVO(ObjetoVO).Historico; EditIdContaDebito.AsInteger := TContabilLancamentoPadraoVO(ObjetoVO).IdContaDebito; if EditIdContaDebito.AsInteger > 0 then begin ContabilContaVO := TContabilContaVO(TController.BuscarObjeto('ContabilContaController.TContabilContaController', 'ConsultaObjeto', ['ID=' + EditIdContaDebito.ToString], 'GET')); if Assigned(ContabilContaVO) then EditContaDebito.Text := ContabilContaVO.Descricao; end; EditIdContaCredito.AsInteger := TContabilLancamentoPadraoVO(ObjetoVO).IdContaCredito; if EditIdContaCredito.AsInteger > 0 then begin ContabilContaVO := TContabilContaVO(TController.BuscarObjeto('ContabilContaController.TContabilContaController', 'ConsultaObjeto', ['ID=' + EditIdContaCredito.ToString], 'GET')); if Assigned(ContabilContaVO) then EditContaCredito.Text := ContabilContaVO.Descricao; end; // Serializa o objeto para consultar posteriormente se houve alterações FormatSettings.DecimalSeparator := '.'; StringObjetoOld := ObjetoVO.ToJSONString; FormatSettings.DecimalSeparator := ','; end; end; {$ENDREGION} {$REGION 'Campos Transientes'} procedure TFContabilLancamentoPadrao.EditIdContaCreditoKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var Filtro: String; begin if Key = VK_F1 then begin if EditIdContaCredito.Value <> 0 then Filtro := 'ID = ' + EditIdContaCredito.Text else Filtro := 'ID=0'; try EditIdContaCredito.Clear; EditContaCredito.Clear; if not PopulaCamposTransientes(Filtro, TContabilContaVO, TContabilContaController) then PopulaCamposTransientesLookup(TContabilContaVO, TContabilContaController); if CDSTransiente.RecordCount > 0 then begin EditIdContaCredito.Text := CDSTransiente.FieldByName('ID').AsString; EditContaCredito.Text := CDSTransiente.FieldByName('DESCRICAO').AsString; end else begin Exit; EditDescricao.SetFocus; end; finally CDSTransiente.Close; end; end; end; procedure TFContabilLancamentoPadrao.EditIdContaDebitoKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState); var Filtro: String; begin if Key = VK_F1 then begin if EditIdContaDebito.Value <> 0 then Filtro := 'ID = ' + EditIdContaDebito.Text else Filtro := 'ID=0'; try EditIdContaDebito.Clear; EditContaDebito.Clear; if not PopulaCamposTransientes(Filtro, TContabilContaVO, TContabilContaController) then PopulaCamposTransientesLookup(TContabilContaVO, TContabilContaController); if CDSTransiente.RecordCount > 0 then begin EditIdContaDebito.Text := CDSTransiente.FieldByName('ID').AsString; EditContaDebito.Text := CDSTransiente.FieldByName('DESCRICAO').AsString; end else begin Exit; EditIdContaCredito.SetFocus; end; finally CDSTransiente.Close; end; end; end; {$ENDREGION} end.
unit main; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, RegExpr, StdCtrls; type TFunction = record name: ansistring; text: ansistring; cyclomaticComplexity: integer; MyersCyclomaticComplexity: integer; end; TArrFunction = array of TFunction; TFMain = class(TForm) BtnOpenFile: TButton; Start: TMemo; Result: TMemo; ChooseFile: TOpenDialog; LCode: TLabel; LResult: TLabel; BtnGetResult: TButton; procedure BtnOpenFileClick(Sender: TObject); procedure FormCreate(Sender: TObject); procedure BtnGetResultClick(Sender: TObject); private { Private declarations } public { Public declarations } end; var FMain: TFMain; input: ansistring; functions: TArrFunction; countFunctions: integer; implementation {$R *.dfm} function isCorrect(var input: ansistring): boolean; var counterBrakes, counterParenthesis,index: integer; begin counterBrakes := 0; counterParenthesis := 0; for index := 1 to length(input) do case input[index] of '(': inc(counterParenthesis); ')': dec(counterParenthesis); '{': inc(counterBrakes); '}': dec(counterBrakes); end; if (counterParenthesis = 0) and (counterBrakes = 0) then result := true else result := false; end; procedure readFromFile(filename: ansistring; var input: ansistring); var tempString : ansistring; inputFile: TextFile; begin input := ''; AssignFile(inputFile,filename); if FileExists (filename) then Reset(inputFile) else begin Rewrite (inputFile); closeFile (inputFile); Reset(inputFile); end; while not EoF(inputFile) do begin readln (inputFile,tempString); input:= input +#13#10+ tempString; end; closeFile (inputFile); FMain.Start.Text := input; FMain.Start.Visible := true; end; procedure deleteText(var input: ansistring); var regularText: TRegExpr; begin regularText := TRegExpr.Create; regularText.InputString := input; try regularText.Expression := '\''.*?\''|\".*?\"'; input := regularText.Replace(input,'',false); finally regularText.Free; end; FMain.Result.Text := input; end; procedure deleteComments(var input: ansistring); var regularComment: TRegExpr; begin regularComment := TRegExpr.Create; regularComment.InputString := input; try regularComment.Expression := '\/\*.*?\*\/|\/{2,}.*?[\r][\n]'; input := regularComment.Replace(input,'',false); finally regularComment.Free; end; end; function setCyclomaticComplexity(var input: ansistring): integer; var cyclComplexity: integer; regularPredicates: TRegExpr; begin cyclComplexity := 1; regularPredicates := TRegExpr.Create; regularPredicates.InputString := input; try regularPredicates.Expression := '([\s \} \)](if|case|foreach|while|for|elseif)[\s \{ \(])|\?'; if (regularPredicates.Exec) then repeat inc(cyclComplexity); until not (regularPredicates.ExecNext); finally regularPredicates.Free; end; result := cyclComplexity; end; function findTextBetweenBrakes(var input: ansistring; var positionFirst: integer): ansistring; var positionLast,countSeparator: integer; tempString: ansistring; begin countSeparator := 0; //счетчик "незакрытых" открывающих фигурных скобок positionLast := positionFirst; while input[positionLast]<> '}' do begin if input[positionLast] ='{' then inc(countSeparator); if (input[positionLast+1] = '}') and (countSeparator <> 1) then begin inc(positionLast); Dec(countSeparator); end; inc(positionLast); end; tempString := copy(input,positionFirst,positionLast-positionFirst+1); result := tempString; end; procedure fillFunctions(var input: ansistring; var functions: TArrFunction; var countFunctions: integer); var positionFirst: integer; regularFunction: TRegExpr; begin regularFunction := TRegExpr.Create; regularFunction.InputString := input; try regularFunction.Expression := '(int|char|void|float|double) \**?([a-zA-Z_]*) ?\([\w \*,\[\]]*\)\s*\{'; if (regularFunction.Exec) then begin repeat begin inc(countFunctions); SetLength(functions, countFunctions); functions[countFunctions-1].name := regularFunction.Match[2] + ' '; positionFirst := Pos(regularFunction.Match[0],input)+length(regularFunction.Match[0])-1; //позиция открывающей фигурной скобки functions[countFunctions-1].text := findTextBetweenBrakes(input,positionFirst); input := StringReplace(input, functions[countFunctions-1].text, '', []); end; until not (regularFunction.ExecNext); end; finally regularFunction.Free; end; end; function findTextBetweenParenthesis(var input: ansistring; var positionFirst: integer): ansistring; var positionLast,countSeparator,index,helpVariable: integer; tempString: ansistring; begin tempString := ''; //helpVariable := positionFirst; countSeparator := 0; //счетчик "незакрытых" открывающих скобок //positionFirst := pos('(',input); positionLast := positionFirst; while input[positionLast]<> ')' do begin if input[positionLast] ='(' then inc(countSeparator); if (input[positionLast+1] = ')') and (countSeparator <> 1) then begin inc(positionLast); Dec(countSeparator); end; inc(positionLast); end; tempString := copy(input,positionFirst,positionLast-positionFirst+1); //delete(input,positionFirst,positionLast-positionFirst+1); // for index := helpVariable to positionLast-helpVariable+1 do // input[index] := 'a'; result := tempString; end; function setMyersCCForOneCase(var input: ansistring): integer; var MyersCC: integer; regPredicate: TRegExpr; begin MyersCC := 1; regPredicate := TRegExpr.Create; regPredicate.InputString := input; try regPredicate.Expression := '[\s|\)](&&|\|\|)[\s\(]'; if (regPredicate.Exec) then repeat inc(MyersCC) until not (regPredicate.ExecNext) finally regPredicate.Free; end; result := MyersCC; end; function setMyersCC(var input: ansistring): integer; var MyersCComplexity, positionFirst: integer; tempString: ansistring; regularIfWhileFor, regularCaseQuestion: TRegExpr; begin MyersCComplexity := 1; regularCaseQuestion := TRegExpr.Create; regularCaseQuestion.InputString := input; try regularCaseQuestion.Expression := '(case[\s \{ \(]|\?)'; if (regularCaseQuestion.Exec) then repeat inc(MyersCComplexity); until not (regularCaseQuestion.ExecNext); finally regularCaseQuestion.Free; end; regularIfWhileFor := TRegExpr.Create; regularIfWhileFor.InputString := input; try regularIfWhileFor.Expression := '(elseif|foreach|while|for|if)[\s\{\(]'; if regularIfWhileFor.Exec then repeat begin positionFirst := regularIfWhileFor.MatchPos[0]; tempString := findTextBetweenParenthesis(input,positionFirst); inc(MyersCComplexity,setMyersCCForOneCase(tempString)); end; until not (regularIfWhileFor.ExecNext); finally regularIfWhileFor.Free; end; result := MyersCComplexity; end; procedure getResult(var input: ansistring); var cyclComplexity, index, MyersCyclComplexity: integer; begin deleteText(input); deleteComments(input); fillFunctions(input,functions,countFunctions); cyclComplexity := 1; cyclComplexity := setCyclomaticComplexity(input); FMain.Result.Text := 'Цикломатическое число Маккейба: ' + inttostr(cyclComplexity); MyersCyclComplexity := setMyersCC(input); FMain.Result.Lines.Add('Цикломатическое число Майерса: (' + inttostr(cyclComplexity) + ','+intToStr(MyersCyclComplexity)+')') ; for index := 0 to countFunctions-1 do begin FMain.Result.Lines.Add(functions[index].name + ':'); functions[index].cyclomaticComplexity := setCyclomaticComplexity(functions[index].text); FMain.Result.Lines.Add(' Маккейб: ' + intToStr(functions[index].cyclomaticComplexity)) ; functions[index].MyersCyclomaticComplexity := setMyersCC(functions[index].text); FMain.Result.Lines.Add(' Майерс: (' + inttostr(functions[index].cyclomaticComplexity) + ','+intToStr(functions[index].MyersCyclomaticComplexity)+')') ; end; end; procedure TFMain.BtnOpenFileClick(Sender: TObject); begin Fmain.Start.Visible := false; Fmain.result.Visible := false; FMain.LCode.Visible := false; FMain.LResult.Visible := false; FMain.Start.Clear; FMain.result.Clear; if ChooseFile.Execute then begin readFromFile(ChooseFile.FileName,input); FMain.BtnGetResult.Enabled := true; end; Fmain.Start.Visible := true; FMain.LCode.Visible := true; end; procedure TFMain.FormCreate(Sender: TObject); begin Fmain.Start.Visible := false; Fmain.Result.Visible := false; end; procedure TFMain.BtnGetResultClick(Sender: TObject); var index: integer; begin input := FMain.Start.Text; FMain.Result.Clear; for index := 0 to countFunctions-1 do begin functions[index].name := ''; functions[index].text := ''; functions[index].cyclomaticComplexity := 0; functions[index].MyersCyclomaticComplexity := 0; end; countfunctions := 0; if (input = '') then FMain.Result.Text := 'Исходный файл пуст!' else begin deleteText(input); deleteComments(input); if not(isCorrect(input)) then FMain.Result.Text := 'Исходный файл содержит неравное количество открывающих '+ #13#10+'и закрывающих скобок!' else getResult(input); end; FMain.LResult.Visible := true; FMain.Result.Visible := true; end; end.
type vertex = record adj:array of boolean; end; graph = array of vertex; position = record row:integer; column:integer; end; node = record p: position; next: ^node; end; queue = record head: ^node; tail: ^node; end; obstrArray = array of position; //queues procedure init(var q: queue); begin q.head := nil; q.tail := nil; end; procedure enqueue(var q: queue; p: position); var n: ^node; begin new(n); n^.p := p; n^.next := nil; if q.head = nil then begin q.head := n; q.tail := n; end else begin q.tail^.next := n; // append to tail q.tail := n; end; end; function dequeue(var q: queue): position; var p: ^node; begin dequeue := q.head^.p; p := q.head; q.head := q.head^.next; dispose(p); if q.head = nil then q.tail := nil; end; function isEmpty(q: queue): boolean; begin exit(q.head = nil); end; procedure fill_graph(var g:graph; var start,destination:position; var obstructions:obstrArray); var row,column:integer; s:string; p:position; begin setLength(obstructions,0); setLength(g, 8); for row := 0 to 7 do begin setLength(g[row].adj, 8); end; for row := 0 to 7 do begin readln(s); for column:=1 to length(s) do begin if s[column]='x' then begin p.row:=row; p.column:=column-1; setLength(obstructions, length(obstructions)+1); obstructions[high(obstructions)]:=p; g[row].adj[column-1]:=true end else if s[column]='v' then begin start.row:=row; start.column:=column-1; end else if s[column]='c' then begin destination.row:=row; destination.column:=column-1; end; end; end; end; procedure print_graph(g:graph); var row,column:integer; begin for row := 0 to 7 do begin for column := 0 to 7 do begin write(g[row].adj[column],' '); end; writeln; end; end; function can_reach(const g:graph; start,destination:position; obstructions:array of position):integer; var moves:integer=7; distance:array of array of integer; q:queue; height:integer=7; width:integer=7; i, j:integer; dist_counter:integer=1; visited:array of array of boolean; p,t:position; row,column:integer; { function is_obstruction(start,destination:position):boolean; var i:integer; begin for i := 0 to high(obstructions) do begin if (obstructions[i].row >= start.row) and (obstructions[i].column ) and (obstructions[i].column = p.column) then exit(true); end; writeln(false); exit(false); end; } function valid(row, column:integer):boolean; begin exit((row>=0) and (row<=7) and (column>=0) and (column<=7)); end; function no_obstruction_in_column(start,destination:position):boolean; var i:integer; begin { write('start.row: ', start.row, ' start:column: ', start.column, ' destination. row: ', destination.row, ' destination.column: ', destination.column); } if start.row < destination.row then begin for i := start.row to destination.row do begin if g[i].adj[start.column]=true then begin { writeln(false); } exit(false); end; end; { writeln(true); } exit(true); end else begin for i := start.row downto destination.row do begin if g[i].adj[start.column]=true then begin { writeln(false); } exit(false); end; end; { writeln(true); } exit(true); end; end; function no_obstruction_in_row(start,destination:position):boolean; var i:integer; begin //write('start.row: ', start.row, ' start:column: ', start.column, ' destination. row: ', destination.row, ' destination.column: ', destination.column); if start.column < destination.column then begin for i := start.column to destination.column do begin if g[start.row].adj[i]=true then begin { writeln(false); } exit(false); end; end; { writeln(true); } exit(true); end else begin for i := start.column downto destination.column do begin if g[start.row].adj[i]=true then begin { writeln(false); } exit(false); end; end; { writeln(true); } exit(true); end; end; begin init(q); setLength(distance, 8, 8); setLength(visited, 8, 8); for i:=0 to high(distance) do for j:=0 to high(distance[0]) do distance[i,j]:=-1; enqueue(q, start); visited[start.row, start.column]:=true; distance[start.row, start.column]:=0; while not isEmpty(q) do begin p:=dequeue(q); // row+ for i:= 7 downto 1 do begin row := p.row + i; column := p.column; t.row := row; t.column:= column; if valid(row, column) and (not visited[row][column]) and no_obstruction_in_column(p,t) then begin t.row := row; t.column := column; enqueue(q,t); visited[row][column]:=true; distance[row][column]:=distance[p.row][p.column]+1; end; end; // row - for i:= 7 downto 1 do begin row := p.row + (-1)*i; column := p.column; t.row := row; t.column:= column; if valid(row, column) and (not visited[row][column]) and no_obstruction_in_column(p,t) then begin t.row := row; t.column := column; enqueue(q,t); visited[row][column]:=true; distance[row][column]:=distance[p.row][p.column]+1; end; end; //column + for i:= 7 downto 1 do begin row := p.row ; column := p.column+i; t.row := row; t.column:= column; if valid(row, column) and (not visited[row][column]) and no_obstruction_in_row(p,t) then begin t.row := row; t.column := column; enqueue(q,t); visited[row][column]:=true; distance[row][column]:=distance[p.row][p.column]+1; end; end; //column - for i:= 7 downto 1 do begin row := p.row; column := p.column+ (-1)*i; t.row := row; t.column:= column; if valid(row, column) and (not visited[row][column]) and no_obstruction_in_row(p,t) then begin t.row := row; t.column := column; enqueue(q,t); visited[row][column]:=true; distance[row][column]:=distance[p.row][p.column]+1; end; end; end; { for i := 0 to 7 do begin for j := 0 to 7 do write(visited[i][j]); writeln; end; for i := 0 to 7 do begin for j := 0 to 7 do write(distance[i][j], ' '); writeln; end; } exit(distance[destination.row][destination.column]); end; var g:graph; start,destination:position; obstructions:array of position; begin fill_graph(g, start, destination, obstructions); { writeln(destination.row, ':', destination.column); } writeln(can_reach(g, start, destination, obstructions)); end.
{********************************************************} { } { Zeos Database Objects } { PostgreSql Query and Table components } { } { Copyright (c) 1999-2001 Sergey Seroukhov } { Copyright (c) 1999-2002 Zeos Development Group } { } {********************************************************} unit ZPgSqlQuery; interface {$R *.dcr} uses SysUtils, {$IFNDEF LINUX}Windows,{$ENDIF} DB, Classes, ZDirSql, ZDirPgSql, DBCommon, ZPgSqlCon, ZPgSqlTr, ZToken, ZLibPgSql, ZSqlExtra, ZQuery, ZSqlTypes, ZSqlItems, ZSqlParser, ZSqlBuffer, ZBlobStream; {$IFNDEF LINUX} {$INCLUDE ..\Zeos.inc} {$ELSE} {$INCLUDE ../Zeos.inc} {$ENDIF} type TZPgSqlOption = (poTextAsMemo, poOidAsBlob); TZPgSqlOptions = set of TZPgSqlOption; { Direct PgSql dataset with descendant of TZDataSet } TZCustomPgSqlDataset = class(TZDataSet) private FExtraOptions: TZPgSqlOptions; procedure SetDatabase(Value: TZPgSqlDatabase); procedure SetTransact(Value: TZPgSqlTransact); function GetDatabase: TZPgSqlDatabase; function GetTransact: TZPgSqlTransact; protected { Overriding ZDataset methods } procedure FormSqlQuery(OldData, NewData: PRecordData); override; procedure QueryRecord; override; procedure UpdateAfterInit(RecordData: PRecordData); override; procedure UpdateAfterPost(OldData, NewData: PRecordData); override; procedure UpdateFieldDef(FieldDesc: PFieldDesc; var FieldType: TFieldType; var FieldSize: Integer); override; function ValueToRowId(Value: string): TRowId; override; function RowIdToValue(Value: TRowId): string; override; {$IFDEF WITH_IPROVIDER} { IProvider support } function PSInTransaction: Boolean; override; function PSExecuteStatement(const ASql: string; AParams: TParams; ResultSet: Pointer): Integer; override; procedure PSSetCommandText(const CommandText: string); override; {$ENDIF} public constructor Create(AOwner: TComponent); override; procedure AddTableFields(Table: string; SqlFields: TSqlFields); override; procedure AddTableIndices(Table: string; SqlFields: TSqlFields; SqlIndices: TSqlIndices); override; function CheckTableExistence(Table: string): Boolean; override; published property ExtraOptions: TZPgSqlOptions read FExtraOptions write FExtraOptions; property Database: TZPgSqlDatabase read GetDatabase write SetDatabase; property Transaction: TZPgSqlTransact read GetTransact write SetTransact; end; { Direct PgSql query with descendant of TDataSet } TZPgSqlQuery = class(TZCustomPgSqlDataset) public property MacroCount; property ParamCount; published property MacroChar; property Macros; property MacroCheck; property Params; property ParamCheck; property DataSource; property Sql; property RequestLive; property Active; end; { Direct PgSql query with descendant of TDataSet } TZPgSqlTable = class(TZCustomPgSqlDataset) public constructor Create(AOwner: TComponent); override; published property TableName; property ReadOnly default False; property DefaultIndex default True; property Active; end; implementation uses ZExtra, ZDBaseConst, Math; {***************** TZCustomPgSqlDataset implemantation *******************} { Class constructor } constructor TZCustomPgSqlDataset.Create(AOwner: TComponent); begin inherited Create(AOwner); DatabaseType := dtPostgreSql; Query := TDirPgSqlQuery.Create(nil, nil); FExtraOptions := [poTextAsMemo, poOidAsBlob]; end; { Set connect to database component } procedure TZCustomPgSqlDataset.SetDatabase(Value: TZPgSqlDatabase); begin inherited SetDatabase(Value); end; { Set connect to transaction component } procedure TZCustomPgSqlDataset.SetTransact(Value: TZPgSqlTransact); begin inherited SetTransact(Value); end; { Get connect to database component } function TZCustomPgSqlDataset.GetDatabase: TZPgSqlDatabase; begin Result := TZPgSqlDatabase(DatabaseObj); end; { Get connect to transact-server component } function TZCustomPgSqlDataset.GetTransact: TZPgSqlTransact; begin Result := TZPgSqlTransact(TransactObj); end; { Read query from server to internal buffer } procedure TZCustomPgSqlDataset.QueryRecord; var I, Count: Integer; FieldNo, FieldNoOffs: Integer; RecordData: PRecordData; FieldDesc: PFieldDesc; BlobPtr: PRecordBlob; Temp: string; Cancel: Boolean; begin { Start fetching fields } Count := SqlBuffer.Count; while not Query.EOF and (Count = SqlBuffer.Count) do begin { Go to the record } if SqlBuffer.FillCount > 0 then Query.Next; { Invoke OnProgress event } if Assigned(OnProgress) then begin Cancel := False; OnProgress(Self, psRunning, ppFetching, Query.RecNo+1, MaxIntValue([Query.RecNo+1, Query.RecordCount]), Cancel); if Cancel then Query.Close; end; if Query.EOF then Break; { Getting record } RecordData := SqlBuffer.Add; if SqlParser.UsedRowId then begin RecordData^.RowId := ValueToRowId(Query.Field(0)); FieldNoOffs := 1; end else FieldNoOffs := 0; for I := 0 to SqlBuffer.SqlFields.Count - 1 do begin { Define field structure } FieldDesc := SqlBuffer.SqlFields[I]; if FieldDesc.FieldNo < 0 then Continue; FieldNo := FieldDesc.FieldNo + FieldNoOffs; if Query.FieldIsNull(FieldNo) and not (FieldDesc.FieldType in [ftBlob, ftMemo {$IFNDEF VER100}, ftArray{$ENDIF}]) then Continue; { Converting field values } case FieldDesc.FieldType of ftFloat, ftCurrency: SqlBuffer.SetFieldValue(FieldDesc, MoneyToFloat(Query.Field(FieldNo)), RecordData); {$IFNDEF VER100} ftArray: begin Temp := ConvertFromSqlEnc(Query.Field(FieldNo)); end; {$ENDIF} ftMemo, ftBlob: begin { Process blob and memo fields } BlobPtr := PRecordBlob(@RecordData.Bytes[FieldDesc.Offset+1]); BlobPtr.Handle.Ptr := 0; BlobPtr.Handle.PtrEx := 0; BlobPtr.Size := 0; BlobPtr.Data := nil; if FieldDesc.FieldType = ftMemo then BlobPtr.BlobType := btInternal else BlobPtr.BlobType := btExternal; if not Query.FieldIsNull(FieldNo) then begin RecordData.Bytes[FieldDesc.Offset] := 0; { Fill internal blobs } if FieldDesc.FieldType = ftMemo then begin BlobPtr.Size := Query.FieldSize(FieldNo); BlobPtr.Data := AllocMem(BlobPtr.Size); System.Move(PChar(ConvertFromSqlEnc(Query.Field(FieldNo)))^, BlobPtr.Data^, BlobPtr.Size); end { Fill external blobs } else BlobPtr.Handle.Ptr := StrToIntDef(Query.Field(FieldNo),0); end; end; ftString: begin Temp := ConvertFromSqlEnc(Query.Field(FieldNo)); SqlBuffer.SetFieldDataLen(FieldDesc, PChar(Temp), RecordData, Length(Temp)); end; ftSmallInt, ftInteger, ftBoolean, ftDate, ftTime, ftDateTime, ftAutoInc {$IFNDEF VER100}, ftLargeInt{$ENDIF}: SqlBuffer.SetField(FieldDesc, Query.Field(FieldNo), RecordData); else DatabaseError(SUnknownType + FieldDesc.Field); end; end; { Filter received record } SqlBuffer.FilterItem(SqlBuffer.Count-1); end; end; { Update record after initialization } procedure TZCustomPgSqlDataset.UpdateAfterInit(RecordData: PRecordData); var I: Integer; FieldDesc: PFieldDesc; RecordBlob: PRecordBlob; begin { Correct blobs description } for I := 0 to SqlBuffer.SqlFields.Count-1 do begin FieldDesc := SqlBuffer.SqlFields[I]; if FieldDesc.FieldType in [ftBlob, ftMemo, ftGraphic, ftFmtMemo] then begin RecordBlob := PRecordBlob(@RecordData.Bytes[FieldDesc.Offset+1]); if FieldDesc.FieldType = ftMemo then RecordBlob.BlobType := btInternal else RecordBlob.BlobType := btExternal; RecordBlob.Data := nil; RecordBlob.Size := 0; RecordBlob.Handle.Ptr := 0; RecordBlob.Handle.PtrEx := 0; end; end; end; { Update field parameters } procedure TZCustomPgSqlDataset.UpdateFieldDef(FieldDesc: PFieldDesc; var FieldType: TFieldType; var FieldSize: Integer); begin inherited UpdateFieldDef(FieldDesc, FieldType, FieldSize); { Fix oid fields according options } if (FieldType = ftBlob) and not (poOidAsBlob in ExtraOptions) then FieldType := ftInteger; { Fix text fields according options } if (FieldType = ftMemo) and not (poTextAsMemo in ExtraOptions) then begin FieldType := ftString; FieldSize := 255; end; { Fix autoinc fields } if (doEnableAutoInc in Options) and (FieldDesc <> nil) and (FieldType = ftInteger) and StrCmpBegin(FieldDesc.Default, 'nextval(') then FieldType := ftAutoInc; end; { Update record after post updates } procedure TZCustomPgSqlDataset.UpdateAfterPost(OldData, NewData: PRecordData); begin if OldData.RecordType = ztInserted then PInteger(@NewData.RowId)^ := TZPgSqlTransact(TransactObj).LastInsertOid; end; { Convert RowId value to string } function TZCustomPgSqlDataset.RowIdToValue(Value: TRowId): string; begin Result := IntToStr(PInteger(@Value)^); end; { Convert string value to RowId } function TZCustomPgSqlDataset.ValueToRowId(Value: string): TRowId; begin FillChar(Result, SizeOf(TRowId), 0); PInteger(@Result)^ := StrToIntDef(Value, 0); end; {************** Sql-queries processing ******************} { Define all fields in query } procedure TZCustomPgSqlDataset.AddTableFields(Table: string; SqlFields: TSqlFields); var Size: Integer; Decimals: Integer; FieldType: TFieldType; Query: TDirPgSqlQuery; Default: string; BlobType: TBlobType; ArraySubType: TFieldType; begin { Set start values } Query := TDirPgSqlQuery(Transaction.QueryHandle); Query.ShowColumns(Table, ''); { Fetch columns description } while not Query.EOF do begin { Evalute field parameters } Size := Max(0, StrToIntDef(Query.Field(3),0)); if (Query.Field(2) = 'numeric') and (Size > 0) then Decimals := StrToIntDef(Query.Field(3),0) and $ffff else if Query.Field(2) = 'money' then Decimals := 2 else Decimals := 4; FieldType := PgSqlToDelphiType(Query.Field(2), Size, ArraySubType, BlobType); if (FieldType = ftBlob) and StrCmpBegin(LowerCase(Table),'pg_') then FieldType := ftInteger; Default := Query.Field(5); { Put new field description } with SqlFields.Add(Table, Query.Field(1), '', Query.Field(2), FieldType, Size, Decimals, atNone, StrCmpBegin(Query.Field(4),'t'), False, Default, BlobType)^ do begin Index := StrToIntDef(Query.Field(0), -1); end; Query.Next; end; Query.Close; end; { Define all indices in query } procedure TZCustomPgSqlDataset.AddTableIndices(Table: string; SqlFields: TSqlFields; SqlIndices: TSqlIndices); { Find field by index } function FindField(Index: Integer): PFieldDesc; var I: Integer; begin for I := 0 to SqlFields.Count-1 do begin Result := SqlFields[I]; if StrCaseCmp(Result.Table, Table) and (Result.Index = Index) then Exit; end; Result := nil; end; var Buffer: string; KeyType: TKeyType; SortType: TSortType; Query: TDirPgSqlQuery; FieldDesc: PFieldDesc; begin { Set start values } Query := TDirPgSqlQuery(TransactObj.QueryHandle); Query.ShowIndexes(Table); { Fetch index descriptions } while not Query.EOF do begin { Define a key type } if Query.Field(3) = 't' then begin if StrCmpBegin(LowerCase(Query.Field(1)),LowerCase(Table)+'_pkey') then KeyType := ktPrimary else KeyType := ktUnique; end else KeyType := ktIndex; { Define sorting type } SortType := stAscending; { Define field names } Buffer := Query.Field(4); while Buffer <> '' do begin FieldDesc := FindField(StrToIntDef(StrTok(Buffer, ' '), -1)); { Put new index description } if FieldDesc <> nil then SqlIndices.AddIndex(Query.Field(1), Table, FieldDesc.Field, KeyType, SortType); end; Query.Next; end; Query.Close; end; { Check is table exist } function TZCustomPgSqlDataset.CheckTableExistence(Table: string): Boolean; var Query: TDirPgSqlQuery; begin Query := TDirPgSqlQuery(TransactObj.QueryHandle); Query.Sql := Format('select tablename from pg_tables where tablename=''%s''', [LowerCase(Table)]); Query.Open; Result := (Query.Field(0) <> ''); Query.Close; end; { Auto form update sql query } procedure TZCustomPgSqlDataset.FormSqlQuery(OldData, NewData: PRecordData); var I: Integer; FieldDesc: PFieldDesc; RecordBlob: PRecordBlob; BlobObj: TDirBlob; begin { Process large objects } if OldData.RecordType = ztDeleted then for I := 0 to SqlBuffer.SqlFields.Count-1 do begin FieldDesc := SqlBuffer.SqlFields[I]; if not (FieldDesc.FieldType in [ftBlob, ftMemo, ftGraphic, ftFmtMemo]) then Continue; RecordBlob := PRecordBlob(@NewData.Bytes[FieldDesc.Offset+1]); if RecordBlob.Handle.Ptr <> 0 then begin BlobObj := Query.CreateBlobObject; try BlobObj.Handle := RecordBlob.Handle; DeleteBlob(BlobObj); finally BlobObj.Free; end; end; end; { Call inherited method } inherited FormSqlQuery(OldData, NewData); end; { TZPgSqlQuery definition } {$IFDEF WITH_IPROVIDER} { IProvider support } { Is in transaction } function TZCustomPgSqlDataset.PSInTransaction: Boolean; begin Result := True; end; { Execute an sql statement } function TZCustomPgSqlDataset.PSExecuteStatement(const ASql: string; AParams: TParams; ResultSet: Pointer): Integer; begin if Assigned(ResultSet) then begin TDataSet(ResultSet^) := TZPgSqlQuery.Create(nil); with TZPgSqlQuery(ResultSet^) do begin Sql.Text := ASql; Params.Assign(AParams); Open; Result := RowsAffected; end; end else Result := TransactObj.ExecSql(ASql); end; { Set command query } procedure TZCustomPgSqlDataset.PSSetCommandText(const CommandText: string); begin Close; if Self is TZPgSqlQuery then TZPgSqlQuery(Self).Sql.Text := CommandText else if Self is TZPgSqlTable then TZPgSqlQuery(Self).TableName := CommandText; end; {$ENDIF} { TZPgSqlTable } constructor TZPgSqlTable.Create(AOwner: TComponent); begin inherited Create(AOwner); DefaultIndex := True; ReadOnly := False; end; end.
unit RDFUtilities; { Copyright (c) 2011+, HL7 and Health Intersections Pty Ltd (http://www.healthintersections.com.au) All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. } interface uses SysUtils, Classes, Generics.Collections, StringSupport, TextUtilities, AdvObjects, AdvGenerics, TurtleParser; const GOOD_IRI_CHAR = 'a-zA-Z0-9\u00A0-\uFFFE'; IRI_URL = '(([a-z])+:)*((%[0-9a-fA-F]{2})|[&''\\(\\)*+,;:@_~?!$\\/\\-\\#.\\='+GOOD_IRI_CHAR+'])+'; LANG_REGEX = '[a-z]{2}(\\-[a-zA-Z]{2})?'; { This RDF writer is orientated around producing legible TTL syntax. } type TRDFFormat = (rdfTurtle, rdfXMl, rdfNTriple); // First: a smart Turtle writer. The focus here is on producing human readable turtle TRDFGenerator = class; TRDFPredicate = class; TRDFTriple = {abstract} class (TADvObject) private uri : String; public end; TRDFString = class (TRDFTriple) private FValue : String; FType : String; public Constructor create(value : String); end; TRDFComplex = class (TRDFTriple) private FGen : TRDFGenerator; FPredicates : TAdvList<TRDFPredicate>; public Constructor Create(gen : TRDFGenerator); Destructor Destroy; override; function write(b : TStringBuilder; indent : integer) : boolean; function predicate(predicate, obj : String) : TRDFComplex; overload; function predicate(predicate, obj, xtype : String) : TRDFComplex; overload; function predicate(predicate : String; obj : TRDFTriple) : TRDFComplex; overload; function predicate(predicate : String) : TRDFComplex; overload; function complex : TRDFComplex; end; TRDFPredicate = class (TAdvObject) private FPredicate : String; FObj : TRDFTriple; FComment : String; public Destructor Destroy; override; function Link : TRDFPredicate; overload; end; TRDFSubject = class (TRDFComplex) private id : String; public Constructor Create(gen : TRDFGenerator); Destructor Destroy; override; function Link : TRDFSubject; overload; function predicate(predicate : String; obj : TRDFTriple; comment : String) : TRDFPredicate; overload; procedure comment(comment : String); procedure labl(labl: String); end; TRDFSection = class (TAdvObject) private FGen : TRDFGenerator; FName : String; FSubjects : TAdvList<TRDFSubject>; public Constructor Create(gen : TRDFGenerator); Destructor Destroy; override; function Link : TRDFSection; overload; property name : String read FName; function triple(subject : String; predicate : String; obj : String; comment : String): TRDFSubject; overload; function triple(subject : String; predicate : String; obj : String): TRDFSubject; overload; function triple(subject : String; predicate : String; obj : TRDFTriple): TRDFSubject; overload; function triple(subject : String; predicate : String; obj : TRDFTriple; comment : String): TRDFSubject; overload; procedure comment(subject : String; comment : String); procedure labl(subject : String; labl : String); function subject(subject : String): TRDFSubject; end; TRDFGenerator = class (TAdvObject) private FSections : TAdvList<TRDFSection>; FSubjectSet : TList<String>; FPredicateSet : TList<String>; FObjectSet : TList<String>; FPrefixes : TDictionary<String, String>; FFormat: TRDFFormat; FLastId : integer; procedure ln(b: TStringBuilder; s : String); function sorted(list : TEnumerable<String>) : TArray<String>; procedure checkPrefix(pname : String); overload; procedure checkPrefix(obj : TRDFTriple); overload; function hasSection(sn : String) : boolean; procedure writeTurtlePrefixes(b : TStringBuilder; header : boolean); procedure writeTurtleSection(b : TStringBuilder; section : TRDFSection); procedure writeNTripleSection(b : TStringBuilder; section : TRDFSection); procedure writeNTripleComplex(b: TStringBuilder; complex: TRDFComplex); procedure writeNTriple(b: TStringBuilder; url1, url2, url3: String); function fullUrl(s: String): String; public Constructor Create; override; Destructor Destroy; override; function Link : TRDFGenerator; overload; property format : TRDFFormat read FFormat write FFormat; procedure prefix(code, url : String); function section(sn: String) : TRDFSection; procedure generate(b : TStringBuilder; header : boolean); end; function ttlLiteral(s : String) : String; implementation function ttlLiteral(s : String) : String; begin result := '"'+jsonEscape(s, true)+'"'; end; function pctEncode(s : String; isString : boolean) : String; var b : TStringBuilder; c : char; begin if s = '' then exit(''); b := TStringBuilder.Create; try for c in s do begin if (c >= 'A') and (c <= 'Z') then b.append(c) else if (c >= 'a') and (c <= 'z') then b.append(c) else if (c >= '0') and (c <= '9') then b.append(c) else if (c = '.') then b.append(c) else if (ord(c) < 255) then b.append('%'+inttohex(ord(c), 2)) else b.append('%'+inttohex(ord(c), 4)); end; result := b.ToString; finally b.Free; end; end; function literal(s : String) : TRDFString; begin result := TRDFString.create('"'+jsonEscape(s, true)+'"'); end; { TRDFString } constructor TRDFString.create(value: String); begin inherited Create; FValue := value; end; { TRDFComplex } function TRDFComplex.complex: TRDFComplex; begin result := TRDFComplex.Create(FGen); end; constructor TRDFComplex.Create(gen : TRDFGenerator); begin inherited Create; FPredicates := TAdvList<TRDFPredicate>.create; FGen := gen; end; destructor TRDFComplex.Destroy; begin FPredicates.Free; inherited; end; function TRDFComplex.predicate(predicate, obj: String): TRDFComplex; begin result := self.predicate(predicate, TRDFString.create(obj)); end; function TRDFComplex.predicate(predicate: String; obj: TRDFTriple): TRDFComplex; var p : TRDFPredicate; begin if not Fgen.FPredicateSet.contains(predicate) then Fgen.FPredicateSet.add(predicate); if (obj is TRDFString) and not Fgen.FObjectSet.contains(TRDFString(obj).FValue) then Fgen.FObjectSet.add(TRDFString(obj).FValue); p := TRDFPredicate.Create; try p.FPredicate := predicate; p.FObj := obj; FPredicates.Add(p.Link); finally p.Free; end; result := self; end; function TRDFComplex.write(b: TStringBuilder; indent: integer): boolean; var left : String; i : integer; po : TRDFPredicate; begin if (Fpredicates.Count = 0) then exit(false); if (Fpredicates.Count = 1) and (Fpredicates[0].Fobj is TRDFString) and (Fpredicates[0].Fcomment = '') then begin b.Append(' '+Fpredicates[0].Fpredicate+' '+TRDFString(Fpredicates[0].Fobj).Fvalue); if TRDFString(Fpredicates[0].FObj).FType <> '' then b.Append('^^'+TRDFString(Fpredicates[0].FObj).FType); exit(false); end; result := true; left := StringpadLeft('', ' ', indent); i := 0; for po in Fpredicates do begin b.Append(#13#10); if (po.FObj is TRDFString) then begin b.Append(left+' '+po.FPredicate+ ' '+TRDFString(po.FObj).Fvalue); if TRDFString(po.FObj).FType <> '' then b.Append('^^'+TRDFString(po.FObj).FType); end else begin b.Append(left+' '+po.FPredicate+' ['); if TRDFComplex(po.FObj).write(b, indent+2) then b.Append(#13#10+left+' ]') else b.Append(' ]'); end; inc(i); if (i < Fpredicates.count) then b.Append(';'); if (po.Fcomment <> '') then b.Append(' # '+jsonEscape(po.Fcomment, false)); end; end; function TRDFComplex.predicate(predicate: String): TRDFComplex; begin result := complex; self.predicate(predicate, result); end; function TRDFComplex.predicate(predicate, obj, xtype: String): TRDFComplex; var s : TRDFString; begin s := TRDFString.create(obj); result := self.predicate(predicate, s); s.FType := xtype; end; { TRDFPredicate } destructor TRDFPredicate.Destroy; begin FObj.Free; inherited; end; function TRDFPredicate.Link: TRDFPredicate; begin result := TRDFPredicate(inherited Link); end; { TRDFSubject } constructor TRDFSubject.Create(gen: TRDFGenerator); begin inherited Create(gen); end; destructor TRDFSubject.Destroy; begin inherited; end; function TRDFSubject.Link: TRDFSubject; begin result := TRDFSubject(Inherited Link); end; function TRDFSubject.predicate(predicate: String; obj: TRDFTriple; comment: String): TRDFPredicate; var p : TRDFPredicate; begin if not FGen.FSubjectSet.contains(id) then FGen.FSubjectSet.add(id); if not Fgen.FPredicateSet.contains(predicate) then Fgen.FPredicateSet.add(predicate); if (obj is TRDFString) and not Fgen.FObjectSet.contains(TRDFString(obj).FValue) then Fgen.FObjectSet.add(TRDFString(obj).FValue); p := TRDFPredicate.Create; try p.FPredicate := predicate; p.FObj := obj; p.FComment := comment; FPredicates.Add(p.Link); result := p; finally p.Free; end; end; procedure TRDFSubject.labl(labl: String); begin if (labl <> '') then begin predicate('rdfs:label', literal(labl)); predicate('dc:title', literal(labl)); end; end; procedure TRDFSubject.comment(comment: String); begin if (comment <> '') then begin predicate('rdfs:comment', literal(comment)); predicate('dcterms:description', literal(comment)); end; end; { TRDFSection } constructor TRDFSection.Create(gen: TRDFGenerator); begin inherited create; FGen := gen; FSubjects := TAdvList<TRDFSubject>.create; end; destructor TRDFSection.Destroy; begin FSubjects.Free; inherited; end; function TRDFSection.Link: TRDFSection; begin result := TRDFSection(inherited Link); end; function TRDFSection.subject(subject: String): TRDFSubject; var ss : TRDFSubject; begin for ss in Fsubjects do if (ss.id = subject) then exit(ss); result := TRDFSubject.Create(FGen); FSubjects.Add(result); result.id := subject; end; function TRDFSection.triple(subject, predicate, obj, comment: String): TRDFSubject; begin result := triple(subject, predicate, TRDFString.create(obj), comment); end; function TRDFSection.triple(subject, predicate, obj: String): TRDFSubject; begin result := triple(subject, predicate, TRDFString.create(obj), ''); end; function TRDFSection.triple(subject, predicate: String; obj: TRDFTriple): TRDFSubject; begin result := triple(subject, predicate, obj, ''); end; function TRDFSection.triple(subject, predicate: String; obj: TRDFTriple; comment: String): TRDFSubject; begin result := self.subject(subject); result.predicate(predicate, obj, comment); end; procedure TRDFSection.comment(subject, comment: String); begin if (comment <> '') then begin triple(subject, 'rdfs:comment', literal(comment)); triple(subject, 'dcterms:description', literal(comment)); end; end; procedure TRDFSection.labl(subject, labl: String); begin if (labl <> '') then begin triple(subject, 'rdfs:label', literal(labl)); triple(subject, 'dc:title', literal(labl)); end; end; { TRDFGenerator } constructor TRDFGenerator.Create(); begin inherited Create; FSections := TAdvList<TRDFSection>.create; FSubjectSet := TList<String>.create; FPredicateSet := TList<String>.create; FObjectSet := TList<String>.create; FPrefixes := TDictionary<String, String>.create; end; destructor TRDFGenerator.Destroy; begin FSections.Free; FSubjectSet.Free; FPredicateSet.Free; FObjectSet.Free; FPrefixes.Free; inherited; end; function TRDFGenerator.Link: TRDFGenerator; begin result := TRDFGenerator(inherited link); end; procedure TRDFGenerator.ln(b: TStringBuilder; s: String); begin b.Append(s); b.Append(#13#10); end; function TRDFGenerator.hasSection(sn: String): boolean; var s : TRDFSection; begin result := false; for s in FSections do if (s.FName = sn) then exit(true); end; function TRDFGenerator.section(sn: String): TRDFSection; begin if (hasSection(sn)) then raise Exception.create('Duplicate section name '+sn); result := TRDFSection.Create(self); FSections.add(result); result.FName := sn; end; function TRDFGenerator.sorted(list: TEnumerable<String>): TArray<String>; var sort : TStringList; s : String; begin sort := TStringList.Create; try for s in list do sort.Add(s); sort.Sort; result := sort.ToStringArray; finally sort.Free; end; end; procedure TRDFGenerator.prefix(code, url: String); begin Fprefixes.AddOrSetValue(code, url); end; procedure TRDFGenerator.checkPrefix(obj: TRDFTriple); var co : TRDFComplex; po : TRDFPredicate; begin if (obj is TRDFString) then checkPrefix(TRDFString(obj).Fvalue) else begin co := TRDFComplex(obj); for po in co.FPredicates do begin checkPrefix(po.FPredicate); checkPrefix(po.FObj); end; end; end; procedure TRDFGenerator.checkPrefix(pname: String); var prefix : string; begin if (pname.startsWith('(')) then exit; if (pname.startsWith('"')) then exit; if (pname.startsWith('<')) then exit; if (pname.contains(':')) then begin prefix := pname.substring(0, pname.indexOf(':')); if (not Fprefixes.containsKey(prefix) and (prefix <> 'http') and (prefix <> 'urn')) then raise Exception.create('undefined prefix '+prefix); end; end; function TRDFGenerator.fullUrl(s : String) : String; var prefix, tail : string; begin if s = 'a' then result := fullUrl('rdfs:type') else if s.StartsWith('"') then result := s else if not s.Contains(':') then result := '"'+s+'"' else if s.StartsWith('<') then result := s.Substring(1, s.Length-2) else begin StringSplit(s, ':', prefix, tail); if FPrefixes.ContainsKey(prefix) then result := FPrefixes[prefix]+tail else result := '"'+s+'"'; end; end; procedure TRDFGenerator.writeNTriple(b: TStringBuilder; url1, url2, url3 : String); begin b.Append(url1); b.Append(' '); b.Append(url2); b.Append(' '); b.Append(url3); b.Append(#13#10); end; procedure TRDFGenerator.writeNTripleComplex(b: TStringBuilder; complex : TRDFComplex); var pred : TRDFPredicate; begin for pred in complex.FPredicates do if (pred.FObj is TRDFComplex) then begin inc(FLastId); if not complex.uri.Contains('#') then pred.FObj.uri := complex.uri + '#' + inttostr(FLastId) else pred.FObj.uri := complex.uri + '.' + inttostr(FLastId); writeNTriple(b, complex.uri, fullUrl(pred.FPredicate), pred.FObj.uri); end else writeNTriple(b, complex.uri, fullUrl(pred.FPredicate), fullUrl(TRDFString(pred.FObj).FValue)); for pred in complex.FPredicates do if (pred.FObj is TRDFComplex) then writeNTripleComplex(b, pred.FObj as TRDFComplex); end; procedure TRDFGenerator.writeNTripleSection(b: TStringBuilder; section: TRDFSection); var subject : TRDFSubject; begin for subject in section.FSubjects do begin subject.uri := fullUrl(subject.id); writeNTripleComplex(b, subject); end; end; procedure TRDFGenerator.writeTurtlePrefixes(b: TStringBuilder; header : boolean); var p : String; begin if (header) then begin ln(b, '# FHIR Turtle'); ln(b, '# see http://hl7.org/fhir/rdf.html'); ln(b, ''); end; for p in sorted(Fprefixes.Keys) do ln(b, '@prefix '+p+': <'+Fprefixes[p]+'> .'); ln(b, ''); end; procedure TRDFGenerator.writeTurtleSection(b: TStringBuilder; section: TRDFSection); var sbj : TRDFSubject; i : integer; p : TRDFPredicate; comment : String; begin ln(b, '# - '+section.name+' '+StringpadLeft('', '-', 75-section.name.length)); ln(b, ''); for sbj in section.Fsubjects do begin b.append(sbj.id); b.append(' '); i := 0; for p in sbj.Fpredicates do begin b.append(p.Fpredicate); b.append(' '); if (p.FObj is TRDFString) then b.append(TRDFString(p.FObj).Fvalue) else begin b.append('['); if (TRDFComplex(p.FObj).write(b, 4)) then b.append(#13#10+' ]') else b.append(']'); end; comment := ''; if p.Fcomment <> '' then comment := ' # '+p.Fcomment; inc(i); if (i < sbj.Fpredicates.count) then b.append(';'+comment+#13#10+' ') else b.append('.'+comment+#13#10); end; end; end; procedure TRDFGenerator.generate(b: TStringBuilder; header: boolean); var s : TRDFSection; begin case FFormat of rdfTurtle: begin writeTurtlePrefixes(b, header); for s in Fsections do writeTurtleSection(b, s); ln(b, '# -------------------------------------------------------------------------------------'); end; rdfXMl: begin raise Exception.Create('Not supported yet'); end; rdfNTriple: begin FLastId := 0; for s in Fsections do writeNTripleSection(b, s); end; end; end; end.
unit uAllergyTests; interface uses DUnitX.TestFramework; type [TestFixture] AllergyTests = class(TObject) public [Test] // [Ignore('Comment the "[Ignore]" statement to run the test')] procedure No_allergies_means_not_allergic; [Test] [Ignore] procedure Allergic_to_eggs; [Test] [Ignore] procedure Allergic_to_eggs_in_addition_to_other_stuff; [Test] [Ignore] procedure No_allergies_at_all; [Test] [Ignore] procedure Allergic_to_just_eggs; [Test] [Ignore] procedure Allergic_to_just_peanuts; [Test] [Ignore] procedure Allergic_to_eggs_and_peanuts; [Test] [Ignore] procedure Allergic_to_lots_of_stuff; [Test] [Ignore] procedure Allergic_to_everything; [Test] [Ignore] procedure Ignore_non_allergen_score_parts; end; implementation uses System.Generics.Collections, uAllergies; procedure AllergyTests.No_allergies_means_not_allergic; var allergies: IAllergies; begin allergies := TAllergies.Create(0); assert.IsFalse(allergies.AllergicTo('peanuts')); assert.IsFalse(allergies.AllergicTo('cats')); assert.IsFalse(allergies.AllergicTo('strawberries')); end; procedure AllergyTests.Allergic_to_eggs; var allergies: IAllergies; begin allergies := TAllergies.Create(1); assert.IsTrue(allergies.AllergicTo('eggs')); end; procedure AllergyTests.Allergic_to_eggs_in_addition_to_other_stuff; var allergies: IAllergies; begin allergies := TAllergies.Create(5); assert.IsTrue(allergies.AllergicTo('eggs')); assert.IsTrue(allergies.AllergicTo('shellfish')); assert.IsFalse(allergies.AllergicTo('strawberries')); end; procedure AllergyTests.No_allergies_at_all; var allergies: IAllergies; begin allergies := TAllergies.Create(0); assert.AreEqual(0, allergies.IList.Count); end; procedure AllergyTests.Allergic_to_just_eggs; var allergies: IAllergies; begin allergies := TAllergies.Create(1); assert.AreEqual(1, allergies.IList.Count); assert.IsTrue(allergies.IList.Contains('eggs')); end; procedure AllergyTests.Allergic_to_just_peanuts; var allergies: IAllergies; begin allergies := TAllergies.Create(2); assert.AreEqual(1, allergies.IList.Count); assert.IsTrue(allergies.IList.Contains('peanuts')); end; procedure AllergyTests.Allergic_to_eggs_and_peanuts; var allergies: IAllergies; begin allergies := TAllergies.Create(3); assert.AreEqual(2, allergies.IList.Count); assert.IsTrue(allergies.IList.Contains('peanuts')); assert.IsTrue(allergies.IList.Contains('eggs')); end; procedure AllergyTests.Allergic_to_lots_of_stuff; var allergies: IAllergies; Expected: TArray<string>; ExpectedCount: integer; ExpectedAllergen: string; begin ExpectedCount := 5; SetLength(Expected, ExpectedCount); Expected[0] := 'strawberries'; Expected[1] := 'tomatoes'; Expected[2] := 'chocolate'; Expected[3] := 'pollen'; Expected[4] := 'cats'; allergies := TAllergies.Create(248); assert.AreEqual(ExpectedCount, allergies.IList.Count); for ExpectedAllergen in Expected do assert.IsTrue(allergies.IList.Contains(ExpectedAllergen)); end; procedure AllergyTests.Allergic_to_everything; var allergies: IAllergies; Expected: TArray<string>; ExpectedCount: integer; ExpectedAllergen: string; begin ExpectedCount := 8; SetLength(Expected, ExpectedCount); Expected[0] := 'eggs'; Expected[1] := 'peanuts'; Expected[2] := 'shellfish'; Expected[3] := 'strawberries'; Expected[4] := 'tomatoes'; Expected[5] := 'chocolate'; Expected[6] := 'pollen'; Expected[7] := 'cats'; allergies := TAllergies.Create(255); assert.AreEqual(ExpectedCount, allergies.IList.Count); for ExpectedAllergen in Expected do assert.IsTrue(allergies.IList.Contains(ExpectedAllergen)); end; procedure AllergyTests.Ignore_non_allergen_score_parts; var allergies: IAllergies; Expected: TArray<string>; ExpectedCount: integer; ExpectedAllergen: string; begin ExpectedCount := 7; SetLength(Expected, ExpectedCount); Expected[0] := 'eggs'; Expected[1] := 'shellfish'; Expected[2] := 'strawberries'; Expected[3] := 'tomatoes'; Expected[4] := 'chocolate'; Expected[5] := 'pollen'; Expected[6] := 'cats'; allergies := TAllergies.Create(509); assert.AreEqual(ExpectedCount, allergies.IList.Count); for ExpectedAllergen in Expected do assert.IsTrue(allergies.IList.Contains(ExpectedAllergen)); end; initialization TDUnitX.RegisterTestFixture(AllergyTests); end.
unit ce_controls; {$I ce_defines.inc} interface uses Classes, SysUtils, Forms, Controls, ComCtrls, ExtCtrls, buttons; type TCEPageControlButton = (pbClose, pbMoveLeft, pbMoveRight, pbAdd); TCEPageControlButtons = set of TCEPageControlButton; const CEPageControlDefaultButtons = [pbClose, pbMoveLeft, pbMoveRight, pbAdd]; type // Used instead of a TTabSheet since only the caption is interesting TCEPage = class(TCustomControl) private function getIndex: integer; protected procedure realSetText(const Value: TCaption); override; public property index: integer read getIndex; end; (** * Minimalist page-control dedicated to Coedit * * - get rid of the framed aspect of the default LCL one * - no published props, since CE has to be compilable w/o extra IDE comps * - add/close/move left and right speed buttons *) TCEPageControl = class(TWinControl) private fHeader: TWinControl; fTabs: TTabControl; fCloseBtn: TSpeedButton; fMoveLeftBtn: TSpeedButton; fMoveRightBtn: TSpeedButton; fAddBtn: TSpeedButton; fContent: TPanel; fPages: TFPList; fPageIndex: integer; fButtons: TCEPageControlButtons; fOnChanged: TNotifyEvent; fOnChanging: TTabChangingEvent; procedure btnCloseClick(sender: TObject); procedure btnMoveLeftClick(sender: TObject); procedure btnMoveRightClick(sender: TObject); procedure btnAddClick(sender: TObject); procedure tabsChanging(Sender: TObject; var AllowChange: Boolean); procedure tabsChanged(sender: TObject); procedure hidePage(index: integer); procedure showPage(index: integer); procedure setPageIndex(index: integer); procedure setButtons(value: TCEPageControlButtons); procedure setCurrentPage(value: TCEPage); function getCurrentPage: TCEPage; function getPageCount: integer; function getPage(index: integer): TCEPage; procedure changedNotify; procedure updateButtonsState; public constructor Create(aowner: TComponent); override; destructor Destroy; override; function addPage: TCEPage; procedure deletePage(index: integer); function getPageIndex(page: TCEPage): integer; procedure movePageRight; procedure movePageLeft; property currentPage: TCEPage read getCurrentPage write setCurrentPage; property pageIndex: integer read fPageIndex write setPageIndex; property pageCount: integer read getPageCount; property pages[index: integer]: TCEPage read getPage; default; property buttons: TCEPageControlButtons read fButtons write setButtons; property closeButton: TSpeedButton read fCloseBtn; property moveLeftButton: TSpeedButton read fMoveLeftBtn; property moveRightButton: TSpeedButton read fMoveRightBtn; property addButton: TSpeedButton read fAddBtn; property onChanged: TNotifyEvent read fOnChanged write fOnChanged; property onChanging: TTabChangingEvent read fOnChanging write fOnChanging; end; implementation function TCEPage.getIndex: integer; var ctrl: TCEPageControl; i: integer; begin ctrl := TCEPageControl(owner); for i := 0 to ctrl.pageCount-1 do if ctrl.pages[i] = self then exit(i); exit(-1); end; procedure TCEPage.RealSetText(const Value: TCaption); var i: integer; ctrl: TCEPageControl; begin inherited; ctrl := TCEPageControl(owner); i := ctrl.getPageIndex(self); if i <> -1 then ctrl.fTabs.Tabs.Strings[i] := caption; end; constructor TCEPageControl.Create(aowner: TComponent); begin inherited; fHeader := TWinControl.Create(self); fHeader.Parent:= self; fHeader.Align := alTop; fHeader.Height:= 32; fTabs := TTabControl.Create(self); fTabs.Parent:= fHeader; fTabs.Align := alClient; fTabs.Options:=[]; fTabs.OnChange:=@tabsChanged; fTabs.OnChanging:=@tabsChanging; fMoveLeftBtn:= TSpeedButton.Create(self); fMoveLeftBtn.Parent := fHeader; fMoveLeftBtn.Align:= alRight; fMoveLeftBtn.Width:= 28; fMoveLeftBtn.BorderSpacing.Around:= 2; fMoveLeftBtn.ShowCaption:=false; fMoveLeftBtn.OnClick:=@btnMoveLeftClick; fMoveLeftBtn.Hint:='move current page to the left'; fMoveRightBtn:= TSpeedButton.Create(self); fMoveRightBtn.Parent := fHeader; fMoveRightBtn.Align:= alRight; fMoveRightBtn.Width:= 28; fMoveRightBtn.BorderSpacing.Around:= 2; fMoveRightBtn.ShowCaption:=false; fMoveRightBtn.OnClick:=@btnMoveRightClick; fMoveRightBtn.Hint:='move current page to the right'; fAddBtn:= TSpeedButton.Create(self); fAddBtn.Parent := fHeader; fAddBtn.Align:= alRight; fAddBtn.Width:= 28; fAddBtn.BorderSpacing.Around:= 2; fAddBtn.ShowCaption:=false; fAddBtn.OnClick:=@btnAddClick; fAddBtn.Hint:='add a new page'; fCloseBtn := TSpeedButton.Create(self); fCloseBtn.Parent := fHeader; fCloseBtn.Align:= alRight; fCloseBtn.Width:= 28; fCloseBtn.BorderSpacing.Around:= 2; fCloseBtn.ShowCaption:=false; fCloseBtn.OnClick:=@btnCloseClick; fCloseBtn.Hint:='close current page'; fContent := TPanel.Create(self); fContent.Parent := self; fContent.Align := alClient; fContent.BevelInner:= bvNone; fContent.BevelOuter:= bvNone; fContent.BorderStyle:=bsNone; fContent.BorderSpacing.Around:=0; fPages := TFPList.Create; fPageIndex := -1; fButtons:= CEPageControlDefaultButtons; updateButtonsState; end; destructor TCEPageControl.Destroy; begin while fPages.Count > 0 do deletePage(fPages.Count-1); fPages.Free; inherited; end; procedure TCEPageControl.changedNotify; begin updateButtonsState; if assigned(fOnChanged) then fOnChanged(self); end; procedure TCEPageControl.tabsChanged(sender: TObject); begin setPageIndex(fTabs.TabIndex); end; procedure TCEPageControl.tabsChanging(Sender: TObject; var AllowChange: Boolean); begin if assigned(fOnChanging) then fOnChanging(self, AllowChange); end; procedure TCEPageControl.hidePage(index: integer); var pge: TCEPage; ctl: TControl; begin if (index < 0) or (index > fPages.Count-1) then exit; pge := TCEPage(fPages.Items[index]); pge.Visible:=false; for ctl in pge.GetEnumeratorControls do ctl.Visible:=false; end; procedure TCEPageControl.showPage(index: integer); var pge: TCEPage; ctl: TControl; begin if (index < 0) or (index > fPages.Count-1) then exit; pge := TCEPage(fPages.Items[index]); pge.Visible:=true; pge.Repaint; for ctl in pge.GetEnumeratorControls do ctl.Visible:=true; end; procedure TCEPageControl.setPageIndex(index: integer); begin if (index > fPages.Count-1) then index := fPages.Count-1; if (index < 0) then exit; hidePage(fPageIndex); fPageIndex := index; showPage(fPageIndex); if fTabs.TabIndex <> fPageIndex then fTabs.TabIndex:= fPageIndex; changedNotify; end; function TCEPageControl.addPage: TCEPage; var pge: TCEPage; begin pge := TCEPage.Create(self); pge.Parent := fContent; pge.Align:= alClient; fPages.Add(pge); fTabs.Tabs.Add(format('', [fPages.Count])); setPageIndex(fTabs.Tabs.Count-1); result := pge; end; procedure TCEPageControl.deletePage(index: integer); begin if (index > fPages.Count-1) or (index < 0) then exit; TCEPage(fPages.Items[index]).Free; fPages.Delete(index); fTabs.Tabs.Delete(index); if fPageIndex >= fPages.Count then fPageIndex -= 1; updateButtonsState; if fPages.Count = 0 then exit; setPageIndex(fPageIndex); end; function TCEPageControl.getPageIndex(page: TCEPage): integer; begin exit(fPages.IndexOf(page)); end; function TCEPageControl.getCurrentPage: TCEPage; begin if (fPageIndex < 0) or (fPageIndex > fPages.Count-1) then exit(nil) else exit(TCEPage(fPages.Items[fPageIndex])); end; procedure TCEPageControl.setCurrentPage(value: TCEPage); begin setPageIndex(getPageIndex(value)); end; function TCEPageControl.getPageCount: integer; begin exit(fPages.Count); end; function TCEPageControl.getPage(index: integer): TCEPage; begin exit(TCEPage(fPages.Items[index])); end; procedure TCEPageControl.movePageRight; begin if fPageIndex = fPages.Count-1 then exit; fPages.Exchange(fPageIndex, fPageIndex + 1); fTabs.Tabs.Exchange(fPageIndex, fPageIndex + 1); setPageIndex(fPageIndex+1); end; procedure TCEPageControl.movePageLeft; begin if fPageIndex <= 0 then exit; fPages.Exchange(fPageIndex, fPageIndex - 1); fTabs.Tabs.Exchange(fPageIndex, fPageIndex - 1); setPageIndex(fPageIndex-1); end; procedure TCEPageControl.btnCloseClick(sender: TObject); begin deletePage(fPageIndex); end; procedure TCEPageControl.btnMoveLeftClick(sender: TObject); begin movePageLeft; end; procedure TCEPageControl.btnMoveRightClick(sender: TObject); begin movePageRight; end; procedure TCEPageControl.btnAddClick(sender: TObject); begin addPage; end; procedure TCEPageControl.setButtons(value: TCEPageControlButtons); begin if fButtons = value then exit; fButtons := value; updateButtonsState; fHeader.ReAlign; end; procedure TCEPageControl.updateButtonsState; begin fHeader.DisableAlign; fCloseBtn.Visible:= pbClose in fButtons; fMoveLeftBtn.Visible:= pbMoveLeft in fButtons; fCloseBtn.Visible:= pbMoveRight in fButtons; fAddBtn.Visible:= pbAdd in fButtons; fHeader.EnableAlign; fCloseBtn.Enabled := fPageIndex <> -1; fMoveLeftBtn.Enabled := fPageIndex > 0; fMoveRightBtn.Enabled := fPageIndex < fPages.Count-1; end; end.
unit WSTextArt; interface uses Windows, MediaCommon, MediaDibImage, Graphics; const TEXT_BUF_MAX_LEN = 1024; EFFECT_NAME_BUF_LEN = 64; FONT_BUF_MAX_LEN = 128; // TEXT_STYLE PCSFontStyleRegular = 0; // 常规 PCSFontStyleBold = $0001; // 粗体 PCSFontStyleItalic = $0002; // 斜体 PCSFontStyleUnderline = $0004; // 下划线 PCSFontStyleStrikeout = $0008; // 删除线 // 艺术字参数结构定义 type SHADOWPARAM = record crColor: COLORREF; nXOffset: Integer; nYOffset: Integer; nOpacity: Integer; nBlurSize: Integer; end; TShadowParam = SHADOWPARAM; PTEXTITEM = ^TTEXTITEM; TTEXTITEM = record strText : array[0..TEXT_BUF_MAX_LEN-1] of WideChar; // 文本内容 strFontName : array[0..TEXT_FONT_NAME_LEN-1] of WideChar; // 字体名称 crFont : COLORREF; // 字体颜色 nFontSize : Longint; // 字号 uStyle : UINT; // TEXT_STYLE 由各style与运算而成 bShadow : BOOL; // 是否使用阴影 paramShadow : SHADOWPARAM; // 文字阴影(bShadow为真时有效) 艺术字不使用该参数 nHalation : Longint; // 光晕值 0为无光晕效果 crHalation : COLORREF; // 光晕颜色值 nAngle : Longint; // 旋转角度 顺时针(0-360) xScale : Longint; // 用于文字缩放 暂未使用 yScale : Longint; // 用于文字缩放 暂未使用 dwReserved : DWORD; // 不能使用 dwReserved2 : DWORD; // 不能使用 end; // 艺术字数据结构定义 PARTTEXTITEM = ^TARTTEXTITEM; TARTTEXTITEM = record txtBase : TTextItem; // 基本文字数据 artTxtParam : TArtTextParam; // 艺术字参数 end; ITextItem = interface(IUnknown) ['{EDA25D65-A4EE-4d00-B2D0-B37DB619F145}'] function SetContent(const textContent: WideString): HRESULT; stdcall; function GetContent(var pContent: WideString): HRESULT; stdcall; function SetFontName(strFontName: WideString): HRESULT; stdcall; function GetFontName(var strFontName: WideString): HRESULT; stdcall; function SetFontColor(crFont: COLORREF): HRESULT; stdcall; function GetFontColor(): COLORREF; stdcall; function SetFontSize(nFontSize: Integer): HRESULT; stdcall; function GetFontSize(): Integer; stdcall; function SetStyle(uStyle: UINT): HRESULT; stdcall; function GetStyle(): UINT; stdcall; function SetUseShadow(bShadow: Integer): HRESULT; stdcall; function GetUseShadow(): Integer; stdcall; function SetShadowParam(paramShadow: SHADOWPARAM): HRESULT; stdcall; function GetShadowParam(): SHADOWPARAM; stdcall; function SetHalation(nHalation: Integer; halationColor: COLORREF): HRESULT; stdcall; function GetHalation(var pHalation: Integer; var pHalationColor: COLORREF): HRESULT; stdcall; function SetAngle(nAngle: Integer): HRESULT; stdcall; function GetAngle(): Integer; stdcall; function SetScale(xScale: Integer; yScale: Integer): HRESULT; stdcall; function GetScale(var pXScale: Integer; var pYScale: Integer): HRESULT; stdcall; end; IPCText = interface(IUnknown) ['{E8E0B4CB-9E9A-46f6-AA7D-FA547A3EA1F4}'] function LoadImage32B(picName: WideString): Pointer; stdcall; function CreateTextSetting(): Pointer; stdcall; function GetSupportFontCount(): Integer; stdcall; function GetSupportFontName(nIndex: Integer; var pFontName: WideString): HRESULT; stdcall; function CreateNormalTextByTrans(const pItem: ITextItem; const lpTextTransform: PTEXTTRANSFORM; pImageTexture: IDibImage): Pointer; stdcall; function CreateNormalTextBySize(const pItem: ITextItem; width: Integer; height: Integer; pImageTexture: IDibImage): Pointer; stdcall; function GetArtTextCount(): Integer; stdcall; function GetArtTextInfo(nIndex: Integer): PARTTEXTINFO; stdcall; function GetIndexFromID(var pArtID: WideString): Integer; stdcall; function GenerateArtTextByTrans(const pArtItem: PARTTEXTITEM; const lpTextTransform: PTEXTTRANSFORM): Pointer; stdcall; function GenerateArtTextBySize(const pArtItem: PARTTEXTITEM; width: Integer; height: Integer): Pointer; stdcall; end; TWSTextArtAPI = record function GenerateNormalTextEx(const pItem: TTextItem; width: Integer; height: Integer; hImageTexture: HDIBIMAGE = nil): HDIBIMAGE; end; function VCLFontStyleToTextStyle(AFontStyle: TFontStyles): DWORD; function TextStyleToVCLFontStyle(Value: DWORD): TFontStyles; var WSTextArtAPI: TWSTextArtAPI; implementation function VCLFontStyleToTextStyle(AFontStyle: TFontStyles): DWORD; begin Result:=PCSFontStyleRegular; if fsBold in AFontStyle then Result:=Result or PCSFontStyleBold; if fsItalic in AFontStyle then Result:=Result or PCSFontStyleItalic; if fsUnderline in AFontStyle then Result:=Result or PCSFontStyleUnderline; if fsStrikeOut in AFontStyle then Result:=Result or PCSFontStyleStrikeout; end; function TextStyleToVCLFontStyle(Value: DWORD): TFontStyles; begin Result:=[]; if Value and PCSFontStyleBold<>0 then Include(Result, fsBold); if Value and PCSFontStyleItalic<>0 then Include(Result, fsItalic); if Value and PCSFontStyleUnderline<>0 then Include(Result, fsUnderline); if Value and PCSFontStyleStrikeout<>0 then Include(Result, fsStrikeOut); end; { TWSTextArtAPI } function TWSTextArtAPI.GenerateNormalTextEx(const pItem: TTextItem; width, height: Integer; hImageTexture: HDIBIMAGE): HDIBIMAGE; var pPCText: IPCText; pTextItem: ITextItem; begin Result := nil; WSCoCreateInstance(CLSID_CPCSText, nil, 0, IID_IPCText, pPCText); if not Assigned(pPCText) then Exit; pTextItem := ITextItem(pPCText.CreateTextSetting); if Assigned(pTextItem) then begin pTextItem.SetContent(pItem.strText); pTextItem.SetFontName(pItem.strFontName); pTextItem.SetFontColor(pItem.crFont); pTextItem.SetFontSize(pItem.nFontSize); pTextItem.SetStyle(pItem.uStyle); pTextItem.SetUseShadow(Integer(pItem.bShadow)); pTextItem.SetShadowParam(pItem.paramShadow); pTextItem.SetHalation(pItem.nHalation, pItem.crHalation); pTextItem.SetAngle(pItem.nAngle); pTextItem.SetScale(pItem.xScale, pItem.yScale); Result := IDibImage(pPCText.CreateNormalTextBySize(pTextItem, width, height, hImageTexture)); pTextItem._Release; end; pPCText._Release; end; end.
{$include kode.inc} unit kode_osc_eptr; { pre-computing correction polynomials for the samples in the transition, while the linear regions of the signal are offset by a constant value } //---------------------------------------------------------------------- //---------------------------------------------------------------------- interface //---------------------------------------------------------------------- function KOsc_Saw_EPTR(t,dt:Single) : Single; inline; //---------------------------------------------------------------------- implementation //---------------------------------------------------------------------- function KOsc_Saw_EPTR(t,dt:Single) : Single; inline; begin if t > (1 - dt) then result := t - (t/dt) + (1/dt) - 1 else result := t; result -= 0.5; result *= 2; end; //---------------------------------------------------------------------- end. //---------------------------------------------------------------------- { http://www.kvraudio.com/forum/viewtopic.php?p=5971739#p5971739 FPhase = sync ? -1 : FPhase + t2 + FMBuffer[i]*FMLevel.Value; if (FPhase > 1.0f - T) //transition { sample = FPhase - (FPhase / T) + (1.0f / T) - 1.0f; FPhase -= 2.0f; } else { sample = FPhase; } } //---------------------------------------------------------------------- { http://www.kvraudio.com/forum/viewtopic.php?p=5619182#p5619182 float SawOut; phaseAccumulator = phaseAccumulator + 2.f * phaseIncrement; if (phaseAccumulator > 1.f - phaseIncrement) { SawOut = phaseAccumulator - (phaseAccumulator/phaseIncrement) + (1.f / phaseIncrement) - 1.f; phaseAccumulator = phaseAccumulator - 2.f; } else { SawOut = phaseAccumulator; } } //---------------------------------------------------------------------- { EPTR Saw (efficient polynomial transition region) http://www.kvraudio.com/forum/viewtopic.php?p=5619182#p5619182 float SawOut; phaseAccumulator = phaseAccumulator + 2.f * phaseIncrement; if (phaseAccumulator > 1.f - phaseIncrement) { SawOut = phaseAccumulator - (phaseAccumulator/phaseIncrement) + (1.f / phaseIncrement) - 1.f; phaseAccumulator = phaseAccumulator - 2.f; } else { SawOut = phaseAccumulator; } Haven't checked it against DPW but the CPU is in the same ballpark. .. I have just checked, and the frequency response is also virtually the same. .. Yeah, I though as much, thanks for testing! On my machine it has *slightly* better CPU, this is definetly a winner in the 'cheap & chearful class', since it behaves better when modulating. } //---------------------------------------------------------------------- { http://home.mit.bme.hu/~bank/publist/smc13.pdf improved polynomial transition regions algorithm for alias-suppressed signal synthesis } //----------------------------------------------------------------------
unit UfraExport; interface uses Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, Dialogs, ImgList, ActnList, cxGraphics, cxGrid, cxGridTableView, cxGridDBTableView, Generics.Collections; type TfraExport = class(TFrame) acl: TActionList; actExportarExcel: TAction; actExportarHTML: TAction; actExportarXML: TAction; actCustomizacao: TAction; ImageList: TcxImageList; procedure actExportarExcelExecute(Sender: TObject); procedure actExportarHTMLExecute(Sender: TObject); procedure actExportarXMLExecute(Sender: TObject); procedure actCustomizacaoExecute(Sender: TObject); private FShowCustomizeButton: Boolean; FTableView: TcxGridDBTableView; FGrid: TcxGrid; FKeyDownEventList: TDictionary<TcxGridDBTableView,TKeyEvent>; procedure ExportData(Sender: TObject; const Filter, DefaultExt: string); function GetComponentView(Sender: TObject): TcxGridDBTableView; procedure CustomNavigationButtonClick(Sender: TObject; AButtonIndex: Integer; var ADone: Boolean); procedure AddCustomNavigationButton(const ImageIndex: Integer; const Hint: string); procedure TableViewKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); public constructor Create(AOwner: TComponent); override; destructor Destroy; override; property Grid: TcxGrid read FGrid; property TableView: TcxGridDBTableView read FTableView; published procedure ConfigGrid(Parent: TComponent); property ShowCustomizeButton: Boolean read FShowCustomizeButton write FShowCustomizeButton; end; implementation uses cxCustomData, Math, Buttons, cxNavigator, cxGridExportLink, UDialogFunctions, UMsgFunctions, cxGridCustomTableView, cxCurrencyEdit, cxGridCustomView; {$R *.dfm} procedure TfraExport.actCustomizacaoExecute(Sender: TObject); var objGrid : TcxGridDBTableView; begin objGrid := GetComponentView(Sender); objGrid.Controller.Customization := True; end; procedure TfraExport.actExportarExcelExecute(Sender: TObject); begin Self.ExportData(Sender, 'Arquivos XLSX (*.xlsx)|*.xlsx', 'xlsx'); end; procedure TfraExport.actExportarHTMLExecute(Sender: TObject); begin Self.ExportData(Sender, 'Arquivos HTML (*.html)|*.html', 'html'); end; procedure TfraExport.actExportarXMLExecute(Sender: TObject); begin Self.ExportData(Sender, 'Arquivos XML (*.xml)|*.xml', 'xml'); end; procedure TfraExport.ConfigGrid(Parent: TComponent); var i: Integer; begin for i := 0 to Parent.ComponentCount - 1 do if (Parent.Components[i] is TcxGrid) then FGrid := (Parent.Components[i] as TcxGrid) else if (Parent.Components[i] is TcxGridTableView) and (TcxGridDBTableView(Parent.Components[i]).ColumnCount >= 1) then begin FTableView := TcxGridDBTableView(Parent.Components[i]); TableView.Navigator.Buttons.Images := ImageList; TableView.OptionsBehavior.NavigatorHints := True; TableView.Navigator.Visible := True; TableView.Navigator.Buttons.First.Visible := False; TableView.Navigator.Buttons.PriorPage.Visible := False; TableView.Navigator.Buttons.Prior.Visible := False; TableView.Navigator.Buttons.Next.Visible := False; TableView.Navigator.Buttons.NextPage.Visible := False; TableView.Navigator.Buttons.Last.Visible := False; TableView.Navigator.Buttons.Insert.Visible := False; TableView.Navigator.Buttons.Append.Visible := False; TableView.Navigator.Buttons.Delete.Visible := False; TableView.Navigator.Buttons.Edit.Visible := False; TableView.Navigator.Buttons.Post.Visible := False; TableView.Navigator.Buttons.Cancel.Visible := False; TableView.Navigator.Buttons.Refresh.Visible := False; TableView.Navigator.Buttons.SaveBookmark.Visible := False; TableView.Navigator.Buttons.GotoBookmark.Visible := False; TableView.Navigator.Buttons.Filter.Visible := False; TableView.Navigator.Buttons.OnButtonClick := Self.CustomNavigationButtonClick; AddCustomNavigationButton(0, 'Exportar para Excel'); AddCustomNavigationButton(1, 'Exportar para HTML'); AddCustomNavigationButton(2, 'Exportar para XML'); if Self.ShowCustomizeButton then AddCustomNavigationButton(3, 'Customizar colunas da grade'); if Assigned(TableView.OnKeyDown) then FKeyDownEventList.Add(TableView, TableView.OnKeyDown); FTableView.OnKeyDown := Self.TableViewKeyDown; end; end; procedure TfraExport.AddCustomNavigationButton(const ImageIndex: Integer; const Hint: string); var objButton: TcxNavigatorCustomButton; begin objButton := TableView.Navigator.Buttons.CustomButtons.Add; objButton.Hint := Hint; objButton.ImageIndex := ImageIndex; end; constructor TfraExport.Create(AOwner: TComponent); begin inherited; FShowCustomizeButton := False; FKeyDownEventList := TDictionary<TcxGridDBTableView, TKeyEvent>.Create(); end; procedure TfraExport.CustomNavigationButtonClick(Sender: TObject; AButtonIndex: Integer; var ADone: Boolean); const BUTTON_EXCEL = 16; BUTTON_HTML = 17; BUTTON_XML = 18; BUTTON_CUSTOMIZE = 19; begin FGrid := TcxGrid(TcxGridViewNavigatorButtons(Sender).GridView.control); case AButtonIndex of BUTTON_EXCEL: actExportarExcel.Execute; BUTTON_HTML: actExportarHTML.Execute; BUTTON_XML: actExportarXML.Execute; BUTTON_CUSTOMIZE: actCustomizacao.Execute; end; end; destructor TfraExport.Destroy; begin FKeyDownEventList.Free; inherited; end; procedure TfraExport.ExportData(Sender: TObject; const Filter, DefaultExt: string); var sFileName: string; begin sFileName := ''; if TDialogFunctions.SaveDialog('Salvar arquivo', Filter, DefaultExt, sFileName) then begin try if Assigned(Grid) then if SameText(DefaultExt, 'xlsx') then ExportGridToXLSX(sFileName, Grid, True, True, True) else if SameText(DefaultExt, 'xml') then ExportGridToXML(sFileName, Grid) else if SameText(DefaultExt, 'html') then ExportGridToHTML(sFileName, Grid) finally //TODO end; end; end; function TfraExport.GetComponentView(Sender: TObject): TcxGridDBTableView; var sAux: string; begin sAux := TAction(Sender).ActionComponent.Name; sAux := Copy(sAux, 1, Pos('_', sAux) - 1); Result := Self.Owner.FindComponent(sAux) as TcxGridDBTableView; end; procedure TfraExport.TableViewKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); var objTableView: TcxGridDBTableView; begin if (Sender is TcxGridSite) then begin objTableView := TcxGridDBTableView(TcxGridSite(Sender).GridView); if (Key > VK_HELP) and Assigned(objTableView.Controller.FocusedColumn) and (objTableView.Controller.FocusedColumn.Properties is TcxCurrencyEditProperties) then if Pos('R$', objTableView.Controller.IncSearchingText) = 0 then objTableView.Controller.IncSearchingText := 'R$ ' + objTableView.Controller.IncSearchingText; if FKeyDownEventList.ContainsKey(objTableView) then FKeyDownEventList[objTableView](Sender, Key, Shift); end; end; end.
unit UStr; interface {-$define _log_} {-$define _debug_} type TGetCountMethod = (gcmNormal,gcmSuccessive,gcmSuccessiveRight); type TStr = class(TObject) public class function CharIsNum(c:char): Boolean; static; class function GetCountChr(aStr, aSubStr: String; aGetCountMethod: TGetCountMethod = gcmNormal): Integer; static; class function PosWithoutShield(aSearch:string;aSource:string; aShield:string='\'): Integer; static; {: RPos() возвращает первый символ последней найденной подстроки Find в строке Search. Если Find не найдена, функция возвращает 0. Подобна реверсированной Pos(). } class function RPos(const aSubStr, aStr: string; aNum: integer = 1): Integer; static; end; var StrUtils:TStr; implementation {$ifdef _log_}uses ULog; {$endif} // -------------------------------------------------------- { ************************************* TStr ************************************* } class function TStr.CharIsNum(c:char): Boolean; begin result:=(ord(c)>=48) and (ord(c)<=57); end; class function TStr.GetCountChr(aStr, aSubStr: String; aGetCountMethod: TGetCountMethod = gcmNormal): Integer; var cPos: Integer; begin result:=0; case aGetCountMethod of gcmNormal: // просто подсчет уникальных непересекающихся вхождений begin while (Pos(aSubStr,aStr)>0) do begin result:=result+1; aStr:=copy(aStr,pos(aSubStr,aStr)+length(aSubStr),length(aStr)); end; end; gcmSuccessive: // подсчет непересекающихся вхождений подряд с левого края begin cPos:=Pos(aSubStr,aStr); while cPos = 1 do begin result:=result+1; aStr:=copy(aStr,Length(aSubStr)+1,Length(aStr)); cPos:=Pos(aSubStr,aStr); end; end; gcmSuccessiveRight: // подсчет непересекающихся вхождений подряд с правого края begin if Length(aStr) >0 then begin cPos:=RPos(aSubStr,aStr); while (cPos>0) and (cPos = Length(aStr)-Length(aSubStr)+1) do begin result:=result+1; aStr:=copy(aStr,1,cPos-1); cPos:=RPos(aSubStr,aStr); end; end;// if Length(aStr) >0 then end; end;//case; end; class function TStr.PosWithoutShield(aSearch:string;aSource:string; aShield:string='\'): Integer; var cBool: Boolean; cAdd: Integer; cStr, cTmp: string; cPos: Integer; cCount: Integer; cLen: Integer; cLenMax: Integer; function _IsNotShield():boolean; begin result:=false; end; begin result:=0; cStr:=aSource; //cBool:=false; cAdd:=0; cLen:=Length(aSearch); cLenMax:=Length(aSource); // определяет позицию строки поиска, при условии, что она не экранирована aShield // Ex: PosWithoutShield('*','string\*sring*','\') = 14 // Ex: PosWithoutShield('*','string\\*sring*','\') = 9 cBool:=true; while cBool do begin cPos:=Pos(aSearch,cStr); cBool:=(cPos <> 0); if (cBool) then begin // обрезаем строку и смотри не экранирован ли символ cTmp:=Copy(cStr,1,cPos-1); cCount:=GetCountChr(cTmp,aShield,gcmSuccessiveRight); // если нет экрана или экранов четное ко-во if (cCount = 0) or ((cCount and 1) = 0) then begin cBool:=false; result:=cPos+cAdd; end else begin cStr:=Copy(cStr,cPos+cLen,cLenMax); cAdd:=cAdd+cPos; cBool:=true; end; end end; end; class function TStr.RPos(const aSubStr, aStr: string; aNum: integer = 1): Integer; var cLenStr: Integer; cStr: string; cLenSubStr: Integer; begin result:=0; cLenStr:=Length(aStr); cLenSubStr:=Length(aSubStr); if cLenSubStr>cLenStr then begin result:=0; exit; end; cLenStr:=cLenStr-cLenSubStr+1; while cLenStr>0 do begin cStr:=copy(aStr,cLenStr,cLenSubStr); if cStr = aSubStr then begin aNum:=aNum-1; if aNum = 0 then begin result:=cLenStr; exit; end; end; cLenStr:=cLenStr-1; end; end; initialization end.
unit view.Principal; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,classe.CopiarPastas, classe.RenomearPastas, classe.RemoverPastas; type TviewPrincipal = class(TForm) btnCopiar: TButton; lblCopiaArq: TLabel; edtVersao: TEdit; btnRemover: TButton; procedure btnCopiarClick(Sender: TObject); procedure btnRemoverClick(Sender: TObject); procedure FormCreate(Sender: TObject); private { Private declarations } public { Public declarations } end; var viewPrincipal: TviewPrincipal; implementation {$R *.dfm} procedure TviewPrincipal.btnCopiarClick(Sender: TObject); var numeroVersao : Integer; copiaPasta : TCopiarPastas; renomearPasta : TRenomearPastas; begin copiaPasta := TCopiarPastas.Create; renomearPasta := TRenomearPastas.Create; try if not TryStrToInt(edtVersao.Text, numeroVersao) then begin MessageDlg('Digitar apenas números.', mtWarning,[mbOK],0); Exit; end; { Encerrar o Delphi } WinExec('taskkill /f /im bds.exe', SW_HIDE); renomearPasta.renomearPastas; copiaPasta.copiarPastas(edtVersao.Text); { Inicializar o Delphi } WinExec('bds.exe', SW_SHOW); finally renomearPasta.Free; copiaPasta.Free; end; end; procedure TviewPrincipal.btnRemoverClick(Sender: TObject); var removerPasta : TRemoverPastas; begin removerPasta := TRemoverPastas.Create; try removerPasta.removerRenomearPastas; finally removerPasta.Free; end; end; procedure TviewPrincipal.FormCreate(Sender: TObject); begin viewPrincipal.Height := 145; end; end.
program PhoneBook; uses crt,sysutils; const NameRequest='Kerem a nevet: '; AddressRequest='Kerem a cimet: '; TelephoneNumberRequest='Kerem a telefonszamot: '; MobilePhoneNumberRequest='Kerem a mobiltelefonszamot: '; ExitString='Nyomj egy ENTER-t a kilepeshez!'; FirstNames:array [1..6] of string = ('Nagy','Kis','Toth','Lakatos', 'Horvath','Dobos'); LastNames:array [1..6] of string = ('Janos','Andrea','Levente','Cecilia','Robert','Erika'); AddressSample:array [1..5] of string =('Bem utca','Liliom ter','Arpad ut','Hajnal utca','Mikszath korut'); TelephoneNumberSample:string ='0642'; MobilePhoneNumberSample:array [1..3] of string = ('0630','0670','0620'); type PDatas=^RDatas; RDatas=record Name:string; Address:string; TelephoneNumber:string; MobilePhoneNumber:string; NextData:PDatas; end; DataRecord=record Name:string; Addr:string; Tel:string; MTel:string; end; InfStringArray=array of string; InfDataRecord=array of DataRecord; var Datas:RDatas; DatasFirst, DatasLast, DatasNew, DatasTemp:PDatas; ExitNumber:byte; HowManyArray:InfStringArray; HowManyRows:longint; DataRecords:InfDataRecord; procedure FillDatas; var HowMuch:integer; FixNumber:longint; begin for HowMuch:=1 to 22 do begin new(DatasNew); with DatasNew^ do begin Name:=FirstNames[random(length(FirstNames))+1]+' '+LastNames[random(length(LastNames))+1]; Address:=AddressSample[random(length(AddressSample))+1]+' '+inttostr(random(50)); FixNumber:=1; while FixNumber<100000 do FixNumber:=random(999999); TelephoneNumber:=TelephoneNumberSample+'-'+inttostr(FixNumber); FixNumber:=1; while FixNumber<1000000 do FixNumber:=random(9999999); MobilePhoneNumber:=MobilePhoneNumberSample[random(length(MobilePhoneNumberSample))+1]+'-'+inttostr(FixNumber); NextData:=nil; end; if DatasFirst=nil then DatasFirst:=DatasNew else DatasLast^.NextData:=DatasNew; DatasLast:=DatasNew; end; end; procedure WriteRandomDatas; begin DatasTemp:=DatasFirst; while DatasTemp<>nil do begin with DatasTemp^ do begin Writeln(Name:16,' ',Address:19,' ',TelephoneNumber:15,' ',MobilePhoneNumber:15); end; DatasTemp:=DatasTemp^.NextData; end; end; procedure ReleaseRandomDatas; begin DatasTemp:=DatasFirst; while DatasTemp<>nil do begin DatasFirst:=DatasTemp^.NextData; dispose(DatasTemp); DatasTemp:=DatasFirst; end; end; procedure AskData; begin with Datas do begin write(NameRequest); readln(Name); write(AddressRequest); readln(Address); write(TelephoneNumberRequest); readln(TelephoneNumber); write(MobilePhoneNumberRequest); readln(MobilePhoneNumber); end; end; procedure WriteData; begin writeln; writeln; with Datas do begin writeln(Datas.Name); writeln(Datas.Address); writeln(Datas.TelephoneNumber); writeln(Datas.MobilePhoneNumber); end; writeln; end; procedure CreateFile; var HowMany,Temp:integer; FixNumber:longint; ReadFileName,LineRead:string; FileName:textfile; Name,Address, TelephoneNumber,MobilePhoneNumber:string; begin write('A file neve?: '); readln(ReadFileName); write('Mennyi rekordot hozzak letre?: '); readln(HowMany); assignfile(FileName,ReadFileName); rewrite(FileName); for Temp:=1 to HowMany do begin Name:=FirstNames[random(length(FirstNames))+1]+' '+LastNames[random(length(LastNames))+1]; Address:=AddressSample[random(length(AddressSample))+1]+' '+inttostr(random(50)); FixNumber:=1; while FixNumber<100000 do FixNumber:=random(999999); TelephoneNumber:=TelephoneNumberSample+'-'+inttostr(FixNumber); FixNumber:=1; while FixNumber<1000000 do FixNumber:=random(9999999); MobilePhoneNumber:=MobilePhoneNumberSample[random(length(MobilePhoneNumberSample))+1]+'-'+inttostr(FixNumber); writeln(FileName,Name,' ',Address,' ',TelephoneNumber,' ',MobilePhoneNumber); end; close(FileName); end; procedure ReadFile; var ReadFileName:string; FileName:textfile; Datas:string; Temp:longint; begin HowManyRows:=0; gotoxy(1,10); write('Mi a fajl neve?: '); readln(ReadFileName); assign(FileName,ReadFileName); reset(FileName); while not eof(FileName) do begin readln(FileName,Datas); inc(HowManyRows); end; setlength(HowManyArray,HowManyRows); close(FileName); reset(FileName); Temp:=0; while not eof(FileName) do begin readln(FileName,HowManyArray[Temp]); inc(Temp); end; close(FileName); end; procedure WriteArray; var WichLine:longint; begin gotoxy(1,1); write(' '); gotoxy(1,1); write('Melyik sort irjam ki (',HowManyRows,')?: '); readln(WichLine); gotoxy(1,3); write(' '); gotoxy(1,3); if (WichLine<=HowManyRows) and (WichLine<>0) then begin write(HowManyArray[WichLine-1]); repeat gotoxy(1,3); write(' '); gotoxy(1,3); write(HowManyArray[WichLine-1]); gotoxy(1,1); write(' '); gotoxy(1,1); write('Melyik sort irjam ki (',HowManyRows,')?: '); readln(WichLine); until (WichLine>HowManyRows) or (WichLine=0); end; end; function GetString(WorkString:string;var Position:integer):string; begin GetString:=''; while (WorkString[Position]<>#32) and (Position<>length(WorkString)+1) do begin GetString:=GetString+WorkString[Position]; inc(Position); end; inc(Position); end; procedure WriteDataRecords; var Temp2,Temp3,Temp4:integer; Street1:string; begin setlength(DataRecords,HowManyRows); for Temp4:=0 to HowManyRows-1 do begin Temp3:=1; Temp2:=1; with DataRecords[Temp4] do begin repeat Street1:=GetString(HowManyArray[Temp4],Temp2); if Temp3=1 then Name:=Street1+' '; if Temp3=2 then Name:=Name+Street1; if Temp3=3 then Addr:=Street1+' '; if Temp3=4 then Addr:=Addr+Street1+' '; if Temp3=5 then Addr:=Addr+Street1; If Temp3=6 then Tel:=Street1; If Temp3=7 then MTel:=Street1; inc(Temp3); until Temp2>length(HowManyArray[Temp4]); end; end; clrscr; write('Melyik rekordot mutassam meg ',HowManyRows,'?: '); readln(Temp4); repeat clrscr; gotoxy(1,5); writeln(DataRecords[Temp4-1].Name); writeln(DataRecords[Temp4-1].Addr); writeln(DataRecords[Temp4-1].Tel); writeln(DataRecords[Temp4-1].MTel); writeln; writeln(HowManyArray[Temp4-1]); gotoxy(1,1); write('Melyik rekordot mutassam meg ',HowManyRows,'?: '); readln(Temp4); until Temp4=0; end; begin clrscr; //CreateFile; //WriteArray; ReadFile; WriteDataRecords; end.
unit UCalculadoraImpostos; interface uses UICalculadora, UIObserverCalculos; type TCalculadoraImpostos = class(TInterfacedObject, ICalculadora) private FCalculadora: ICalculadora; function calculaImposto1(value: String): String; function calculaImposto2(value: String): String; function calculaImposto3(value: String): String; public constructor Create(calculadora: ICalculadora); procedure AdicionaObserver(observer: IObserverCalculos); procedure Comando(value: string); overload; procedure Comando(value: TComandosCalculadora); overload; function getSubtotal: string; procedure setSubtotal(value: string); procedure AtualizarResultado; end; implementation uses System.SysUtils; { TCalculadoraImpostos } procedure TCalculadoraImpostos.AdicionaObserver(observer: IObserverCalculos); begin FCalculadora.AdicionaObserver(observer); end; procedure TCalculadoraImpostos.Comando(value: string); begin FCalculadora.Comando(value); end; procedure TCalculadoraImpostos.AtualizarResultado; begin FCalculadora.AtualizarResultado(); end; function TCalculadoraImpostos.calculaImposto1(value: string): String; begin result := currToStr(strToCurr(value) * (20 / 100) - 500) end; function TCalculadoraImpostos.calculaImposto2(value: String): String; begin result := currToStr(strToCurr(calculaImposto1(value)) - 15); end; function TCalculadoraImpostos.calculaImposto3(value: String): String; begin result := currToStr(strToCurr(calculaImposto1(value)) + strToCurr(calculaImposto2(value))); end; procedure TCalculadoraImpostos.Comando(value: TComandosCalculadora); begin if value = imposto1 then begin setSubtotal(calculaImposto1(getSubtotal())); AtualizarResultado; end; if value = imposto2 then begin setSubtotal(calculaImposto2(getSubtotal)); AtualizarResultado; end; if value = imposto3 then begin setSubtotal(calculaImposto3(getSubtotal)); AtualizarResultado; end; FCalculadora.Comando(value); end; constructor TCalculadoraImpostos.Create(calculadora: ICalculadora); begin FCalculadora := calculadora; end; function TCalculadoraImpostos.getSubtotal: string; begin result := FCalculadora.getSubtotal end; procedure TCalculadoraImpostos.setSubtotal(value: string); begin FCalculadora.setSubtotal(value); end; end.
// ---------------------------------------------------------------------------- // Unit : PxSQLite3.pas - a part of PxLib // Author : Matthias Hryniszak // Date : 2005-08-09 // Version : 1.0 // Description : Import unit for sqlite3.dll (tested with SQLite 3.2.2) // Changes log : 2005-08-09 - initial version // ToDo : Some imports are still missing. // ---------------------------------------------------------------------------- // // 2001 September 15 // // The author disclaims copyright to this source code. In place of // a legal notice, here is a blessing: // // May you do good and not evil. // May you find forgiveness for yourself and forgive others. // May you share freely, never taking more than you give. // // // This header file defines the interface that the SQLite library // presents to client programs. // unit PxSQLite3; {$I PxDefines.inc} interface const // // The version of the SQLite library. // SQLITE_VERSION = '3.2.2'; // // The format of the version string is "X.Y.Z<trailing string>", where // X is the major version number, Y is the minor version number and Z // is the release number. The trailing string is often "alpha" or "beta". // For example "3.1.1beta". // // The SQLITE_VERSION_NUMBER is an integer with the value // (X*100000 + Y*1000 + Z). For example, for version "3.1.1beta", // SQLITE_VERSION_NUMBER is set to 3001001. To detect if they are using // version 3.1.1 or greater at compile time, programs may use the test // (SQLITE_VERSION_NUMBER>=3001001). // SQLITE_VERSION_NUMBER = 3002002; // // The version string is also compiled into the library so that a program // can check to make sure that the lib*.a file and the *.h file are from // the same version. The sqlite3_libversion() function returns a pointer // to the sqlite3_version variable - useful in DLLs which cannot access // global variables. // function sqlite3_libversion: PChar; external 'sqlite3.dll'; // // Return the value of the SQLITE_VERSION_NUMBER macro when the // library was compiled. // function sqlite3_libversion_number: Integer; external 'sqlite3.dll'; type // // Each open sqlite database is represented by an instance of the // following opaque structure. // psqlite3 = ^sqlite3; sqlite3 = record end; // // Some compilers do not support the "long long" datatype. So we have // to do a typedef that for 64-bit integers that depends on what compiler // is being used. // sqlite_int64 = Int64; sqlite_uint64 = Int64; PPPChar = ^PPChar; // // A function to close the database. // // Call this function with a pointer to a structure that was previously // returned from sqlite3_open() and the corresponding database will by closed. // // All SQL statements prepared using sqlite3_prepare() or // sqlite3_prepare16() must be deallocated using sqlite3_finalize() before // this routine is called. Otherwise, SQLITE_BUSY is returned and the // database connection remains open. // function sqlite3_close(db: psqlite3): Integer; cdecl; external 'sqlite3.dll'; type // // The type for a callback function. // sqlite3_callback = function(Param: Pointer; RowCount: Integer; Data, Fields: PPChar): Integer; cdecl; // // A function to executes one or more statements of SQL. // // If one or more of the SQL statements are queries, then // the callback function specified by the 3rd parameter is // invoked once for each row of the query result. This callback // should normally return 0. If the callback returns a non-zero // value then the query is aborted, all subsequent SQL statements // are skipped and the sqlite3_exec() function returns the SQLITE_ABORT. // // The 4th parameter is an arbitrary pointer that is passed // to the callback function as its first parameter. // // The 2nd parameter to the callback function is the number of // columns in the query result. The 3rd parameter to the callback // is an array of strings holding the values for each column. // The 4th parameter to the callback is an array of strings holding // the names of each column. // // The callback function may be NULL, even for queries. A NULL // callback is not an error. It just means that no callback // will be invoked. // // If an error occurs while parsing or evaluating the SQL (but // not while executing the callback) then an appropriate error // message is written into memory obtained from malloc() and // *errmsg is made to point to that message. The calling function // is responsible for freeing the memory that holds the error // message. Use sqlite3_free() for this. If errmsg==NULL, // then no error message is ever written. // // The return value is is SQLITE_OK if there are no errors and // some other return code if there is an error. The particular // return value depends on the type of error. // // If the query could not be executed because a database file is // locked or busy, then this function returns SQLITE_BUSY. (This // behavior can be modified somewhat using the sqlite3_busy_handler() // and sqlite3_busy_timeout() functions below.) // function sqlite3_exec( db : psqlite3; // An open database sql: PChar; // SQL to be executed cb : sqlite3_callback; // Callback function p : Pointer; // 1st argument to callback function err: PPChar // Error msg written here ): Integer; cdecl; external 'sqlite3.dll'; const // // Return values for sqlite3_exec() and sqlite3_step() // SQLITE_OK = 0; // Successful result SQLITE_ERROR = 1; // SQL error or missing database SQLITE_INTERNAL = 2; // An internal logic error in SQLite SQLITE_PERM = 3; // Access permission denied SQLITE_ABORT = 4; // Callback routine requested an abort SQLITE_BUSY = 5; // The database file is locked SQLITE_LOCKED = 6; // A table in the database is locked SQLITE_NOMEM = 7; // A malloc() failed SQLITE_READONLY = 8; // Attempt to write a readonly database SQLITE_INTERRUPT = 9; // Operation terminated by sqlite3_interrupt( SQLITE_IOERR = 10; // Some kind of disk I/O error occurred SQLITE_CORRUPT = 11; // The database disk image is malformed SQLITE_NOTFOUND = 12; // (Internal Only) Table or record not found SQLITE_FULL = 13; // Insertion failed because database is full SQLITE_CANTOPEN = 14; // Unable to open the database file SQLITE_PROTOCOL = 15; // Database lock protocol error SQLITE_EMPTY = 16; // Database is empty SQLITE_SCHEMA = 17; // The database schema changed SQLITE_TOOBIG = 18; // Too much data for one row of a table SQLITE_CONSTRAINT = 19; // Abort due to contraint violation SQLITE_MISMATCH = 20; // Data type mismatch SQLITE_MISUSE = 21; // Library used incorrectly SQLITE_NOLFS = 22; // Uses OS features not supported on host SQLITE_AUTH = 23; // Authorization denied SQLITE_FORMAT = 24; // Auxiliary database format error SQLITE_RANGE = 25; // 2nd parameter to sqlite3_bind out of range SQLITE_NOTADB = 26; // File opened that is not a database file SQLITE_ROW = 100; // sqlite3_step() has another row ready SQLITE_DONE = 101; // sqlite3_step() has finished executing // // Each entry in an SQLite table has a unique integer key. (The key is // the value of the INTEGER PRIMARY KEY column if there is such a column, // otherwise the key is generated at random. The unique key is always // available as the ROWID, OID, or _ROWID_ column.) The following routine // returns the integer key of the most recent insert in the database. // // This function is similar to the mysql_insert_id() function from MySQL. // function sqlite3_last_insert_rowid(db: psqlite3): sqlite_int64; cdecl; external 'sqlite3.dll'; // // This function returns the number of database rows that were changed // (or inserted or deleted) by the most recent called sqlite3_exec(). // // All changes are counted, even if they were later undone by a // ROLLBACK or ABORT. Except, changes associated with creating and // dropping tables are not counted. // // If a callback invokes sqlite3_exec() recursively, then the changes // in the inner, recursive call are counted together with the changes // in the outer call. // // SQLite implements the command "DELETE FROM table" without a WHERE clause // by dropping and recreating the table. (This is much faster than going // through and deleting individual elements form the table.) Because of // this optimization, the change count for "DELETE FROM table" will be // zero regardless of the number of elements that were originally in the // table. To get an accurate count of the number of rows deleted, use // "DELETE FROM table WHERE 1" instead. // function sqlite3_changes(db: psqlite3): Integer; cdecl; external 'sqlite3.dll'; // // This function returns the number of database rows that have been // modified by INSERT, UPDATE or DELETE statements since the database handle // was opened. This includes UPDATE, INSERT and DELETE statements executed // as part of trigger programs. All changes are counted as soon as the // statement that makes them is completed (when the statement handle is // passed to sqlite3_reset() or sqlite_finalise()). // // SQLite implements the command "DELETE FROM table" without a WHERE clause // by dropping and recreating the table. (This is much faster than going // through and deleting individual elements form the table.) Because of // this optimization, the change count for "DELETE FROM table" will be // zero regardless of the number of elements that were originally in the // table. To get an accurate count of the number of rows deleted, use // "DELETE FROM table WHERE 1" instead. // function sqlite3_total_changes(db: psqlite3): Integer; cdecl; external 'sqlite3.dll'; // This function causes any pending database operation to abort and // return at its earliest opportunity. This routine is typically // called in response to a user action such as pressing "Cancel" // or Ctrl-C where the user wants a long query operation to halt // immediately. // procedure sqlite3_interrupt(db: psqlite3); cdecl; external 'sqlite3.dll'; // These functions return true if the given input string comprises // one or more complete SQL statements. For the sqlite3_complete() call, // the parameter must be a nul-terminated UTF-8 string. For // sqlite3_complete16(), a nul-terminated machine byte order UTF-16 string // is required. // // The algorithm is simple. If the last token other than spaces // and comments is a semicolon, then return true. otherwise return // false. // function sqlite3_complete(sql: PChar): Integer; cdecl; external 'sqlite3.dll'; function sqlite3_complete16(sql: PChar): Integer; cdecl; external 'sqlite3.dll'; // // This routine identifies a callback function that is invoked // whenever an attempt is made to open a database table that is // currently locked by another process or thread. If the busy callback // is NULL, then sqlite3_exec() returns SQLITE_BUSY immediately if // it finds a locked table. If the busy callback is not NULL, then // sqlite3_exec() invokes the callback with three arguments. The // second argument is the name of the locked table and the third // argument is the number of times the table has been busy. If the // busy callback returns 0, then sqlite3_exec() immediately returns // SQLITE_BUSY. If the callback returns non-zero, then sqlite3_exec() // tries to open the table again and the cycle repeats. // // The default busy callback is NULL. // // Sqlite is re-entrant, so the busy handler may start a new query. // (It is not clear why anyone would every want to do this, but it // is allowed, in theory.) But the busy handler may not close the // database. Closing the database from a busy handler will delete // data structures out from under the executing query and will // probably result in a coredump. // // TODO: int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*); // // This routine sets a busy handler that sleeps for a while when a // table is locked. The handler will sleep multiple times until // at least "ms" milleseconds of sleeping have been done. After // "ms" milleseconds of sleeping, the handler returns 0 which // causes sqlite3_exec() to return SQLITE_BUSY. // // Calling this routine with an argument less than or equal to zero // turns off all busy handlers. // function sqlite3_busy_timeout(db: psqlite3; ms: Integer): Integer; cdecl; external 'sqlite3.dll'; // // This next routine is really just a wrapper around sqlite3_exec(). // Instead of invoking a user-supplied callback for each row of the // result, this routine remembers each row of the result in memory // obtained from malloc(), then returns all of the result after the // query has finished. // // As an example, suppose the query result where this table: // // Name | Age // ----------------------- // Alice | 43 // Bob | 28 // Cindy | 21 // // If the 3rd argument were &azResult then after the function returns // azResult will contain the following data: // // azResult[0] = "Name"; // azResult[1] = "Age"; // azResult[2] = "Alice"; // azResult[3] = "43"; // azResult[4] = "Bob"; // azResult[5] = "28"; // azResult[6] = "Cindy"; // azResult[7] = "21"; // // Notice that there is an extra row of data containing the column // headers. But the *nrow return value is still 3. *ncolumn is // set to 2. In general, the number of values inserted into azResult // will be ((*nrow) + 1)*(*ncolumn). // // After the calling function has finished using the result, it should // pass the result data pointer to sqlite3_free_table() in order to // release the memory that was malloc-ed. Because of the way the // malloc() happens, the calling function must not try to call // free() directly. Only sqlite3_free_table() is able to release // the memory properly and safely. // // The return value of this routine is the same as from sqlite3_exec(). // function sqlite3_get_table( db : psqlite3; // An open database sql : PChar; // SQL to be executed resultp: PPPChar; // Result written to a char *[] that this points to nrow : PInteger; // Number of result rows written here ncolumn: PInteger; // Number of result columns written here errmsg : PPChar // Error msg written here ): Integer; cdecl; external 'sqlite3.dll'; // // Call this routine to free the memory that sqlite3_get_table() allocated. // procedure sqlite3_free_table(result: PPChar); cdecl; external 'sqlite3.dll'; // // The following routines are variants of the "sprintf()" from the // standard C library. The resulting string is written into memory // obtained from malloc() so that there is never a possiblity of buffer // overflow. These routines also implement some additional formatting // options that are useful for constructing SQL statements. // // The strings returned by these routines should be freed by calling // sqlite3_free(). // // All of the usual printf formatting options apply. In addition, there // is a "%q" option. %q works like %s in that it substitutes a null-terminated // string from the argument list. But %q also doubles every '\'' character. // %q is designed for use inside a string literal. By doubling each '\'' // character it escapes that character and allows it to be inserted into // the string. // // For example, so some string variable contains text as follows: // // char *zText = "It's a happy day!"; // // We can use this text in an SQL statement as follows: // // sqlite3_exec_printf(db, "INSERT INTO table VALUES('%q')", // callback1, 0, 0, zText); // // Because the %q format string is used, the '\'' character in zText // is escaped and the SQL generated is as follows: // // INSERT INTO table1 VALUES('It''s a happy day!') // // This is correct. Had we used %s instead of %q, the generated SQL // would have looked like this: // // INSERT INTO table1 VALUES('It's a happy day!'); // // This second example is an SQL syntax error. As a general rule you // should always use %q instead of %s when inserting text into a string // literal. // // TODO: char *sqlite3_mprintf(const char*,...); // TODO: char *sqlite3_vmprintf(const char*, va_list); procedure sqlite3_free(z: PChar); cdecl; external 'sqlite3.dll'; // TODO: char *sqlite3_snprintf(int,char*,const char*, ...); {$IFNDEF SQLITE_OMIT_AUTHORIZATION} // // This routine registers a callback with the SQLite library. The // callback is invoked (at compile-time, not at run-time) for each // attempt to access a column of a table in the database. The callback // returns SQLITE_OK if access is allowed, SQLITE_DENY if the entire // SQL statement should be aborted with an error and SQLITE_IGNORE // if the column should be treated as a NULL value. // //function sqlite3_set_authorizer( // db: psqlite3; // int (*xAuth)(void*,int,const char*,const char*,const char*,const char*), // void *pUserData //): Integer; cdecl; external 'sqlite3.dll'; {$ENDIF} const // // The second parameter to the access authorization function above will // be one of the values below. These values signify what kind of operation // is to be authorized. The 3rd and 4th parameters to the authorization // function will be parameters or NULL depending on which of the following // codes is used as the second parameter. The 5th parameter is the name // of the database ("main", "temp", etc.) if applicable. The 6th parameter // is the name of the inner-most trigger or view that is responsible for // the access attempt or NULL if this access attempt is directly from // input SQL code. // // Arg-3 Arg-4 // SQLITE_COPY = 0; // Table Name File Name SQLITE_CREATE_INDEX = 1; // Index Name Table Name SQLITE_CREATE_TABLE = 2; // Table Name NULL SQLITE_CREATE_TEMP_INDEX = 3; // Index Name Table Name SQLITE_CREATE_TEMP_TABLE = 4; // Table Name NULL SQLITE_CREATE_TEMP_TRIGGER = 5; // Trigger Name Table Name SQLITE_CREATE_TEMP_VIEW = 6; // View Name NULL SQLITE_CREATE_TRIGGER = 7; // Trigger Name Table Name SQLITE_CREATE_VIEW = 8; // View Name NULL SQLITE_DELETE = 9; // Table Name NULL SQLITE_DROP_INDEX = 10; // Index Name Table Name SQLITE_DROP_TABLE = 11; // Table Name NULL SQLITE_DROP_TEMP_INDEX = 12; // Index Name Table Name SQLITE_DROP_TEMP_TABLE = 13; // Table Name NULL SQLITE_DROP_TEMP_TRIGGER = 14; // Trigger Name Table Name SQLITE_DROP_TEMP_VIEW = 15; // View Name NULL SQLITE_DROP_TRIGGER = 16; // Trigger Name Table Name SQLITE_DROP_VIEW = 17; // View Name NULL SQLITE_INSERT = 18; // Table Name NULL SQLITE_PRAGMA = 19; // Pragma Name 1st arg or NULL SQLITE_READ = 20; // Table Name Column Name SQLITE_SELECT = 21; // NULL NULL SQLITE_TRANSACTION = 22; // NULL NULL SQLITE_UPDATE = 23; // Table Name Column Name SQLITE_ATTACH = 24; // Filename NULL SQLITE_DETACH = 25; // Database Name NULL SQLITE_ALTER_TABLE = 26; // Database Name Table Name SQLITE_REINDEX = 27; // Index Name NULL // // The return value of the authorization function should be one of the // following constants: // SQLITE_DENY = 1; // Abort the SQL statement with an error SQLITE_IGNORE = 2; // Don't allow access, but don't generate an error // // Register a function that is called at every invocation of sqlite3_exec() // or sqlite3_prepare(). This function can be used (for example) to generate // a log file of all SQL executed against a database. // // TODO: void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*); // // This routine configures a callback function - the progress callback - that // is invoked periodically during long running calls to sqlite3_exec(), // sqlite3_step() and sqlite3_get_table(). An example use for this API is to // keep a GUI updated during a large query. // // The progress callback is invoked once for every N virtual machine opcodes, // where N is the second argument to this function. The progress callback // itself is identified by the third argument to this function. The fourth // argument to this function is a void pointer passed to the progress callback // function each time it is invoked. // // If a call to sqlite3_exec(), sqlite3_step() or sqlite3_get_table() results // in less than N opcodes being executed, then the progress callback is not // invoked. // // To remove the progress callback altogether, pass NULL as the third // argument to this function. // // If the progress callback returns a result other than 0, then the current // query is immediately terminated and any database changes rolled back. If the // query was part of a larger transaction, then the transaction is not rolled // back and remains active. The sqlite3_exec() call returns SQLITE_ABORT. // //***** THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ****** // // TODO: void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*); // // Register a callback function to be invoked whenever a new transaction // is committed. The pArg argument is passed through to the callback. // callback. If the callback function returns non-zero, then the commit // is converted into a rollback. // // If another function was previously registered, its pArg value is returned. // Otherwise NULL is returned. // // Registering a NULL function disables the callback. // //***** THIS IS AN EXPERIMENTAL API AND IS SUBJECT TO CHANGE ****** // // TODO: void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*); // // Open the sqlite database file "filename". The "filename" is UTF-8 // encoded for sqlite3_open() and UTF-16 encoded in the native byte order // for sqlite3_open16(). An sqlite3* handle is returned in *ppDb, even // if an error occurs. If the database is opened (or created) successfully, // then SQLITE_OK is returned. Otherwise an error code is returned. The // sqlite3_errmsg() or sqlite3_errmsg16() routines can be used to obtain // an English language description of the error. // // If the database file does not exist, then a new database is created. // The encoding for the database is UTF-8 if sqlite3_open() is called and // UTF-16 if sqlite3_open16 is used. // // Whether or not an error occurs when it is opened, resources associated // with the sqlite3* handle should be released by passing it to // sqlite3_close() when it is no longer required. // function sqlite3_open( filename: PChar; // Database filename (UTF-8) var db : psqlite3 // OUT: SQLite db handle ): Integer; cdecl; external 'sqlite3.dll'; function sqlite3_open16( filename: Pointer; // Database filename (UTF-16) var db : psqlite3 // OUT: SQLite db handle ): Integer; cdecl; external 'sqlite3.dll'; // // Return the error code for the most recent sqlite3_* API call associated // with sqlite3 handle 'db'. SQLITE_OK is returned if the most recent // API call was successful. // // Calls to many sqlite3_* functions set the error code and string returned // by sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16() // (overwriting the previous values). Note that calls to sqlite3_errcode(), // sqlite3_errmsg() and sqlite3_errmsg16() themselves do not affect the // results of future invocations. // // Assuming no other intervening sqlite3_* API calls are made, the error // code returned by this function is associated with the same error as // the strings returned by sqlite3_errmsg() and sqlite3_errmsg16(). // function sqlite3_errcode(db: psqlite3): Integer; cdecl; external 'sqlite3.dll'; // // Return a pointer to a UTF-8 encoded string describing in english the // error condition for the most recent sqlite3_* API call. The returned // string is always terminated by an 0x00 byte. // // The string "not an error" is returned when the most recent API call was // successful. // function sqlite3_errmsg(db: psqlite3): PChar; cdecl; external 'sqlite3.dll'; // // Return a pointer to a UTF-16 native byte order encoded string describing // in english the error condition for the most recent sqlite3_* API call. // The returned string is always terminated by a pair of 0x00 bytes. // // The string "not an error" is returned when the most recent API call was // successful. // function sqlite3_errmsg16(db: psqlite3): Pointer; cdecl; external 'sqlite3.dll'; // // An instance of the following opaque structure is used to represent // a compiled SQL statment. // type psqlite3_stmt = ^sqlite3_stmt; sqlite3_stmt = record end; // // To execute an SQL query, it must first be compiled into a byte-code // program using one of the following routines. The only difference between // them is that the second argument, specifying the SQL statement to // compile, is assumed to be encoded in UTF-8 for the sqlite3_prepare() // function and UTF-16 for sqlite3_prepare16(). // // The first parameter "db" is an SQLite database handle. The second // parameter "zSql" is the statement to be compiled, encoded as either // UTF-8 or UTF-16 (see above). If the next parameter, "nBytes", is less // than zero, then zSql is read up to the first nul terminator. If // "nBytes" is not less than zero, then it is the length of the string zSql // in bytes (not characters). // // *pzTail is made to point to the first byte past the end of the first // SQL statement in zSql. This routine only compiles the first statement // in zSql, so *pzTail is left pointing to what remains uncompiled. // // *ppStmt is left pointing to a compiled SQL statement that can be // executed using sqlite3_step(). Or if there is an error, *ppStmt may be // set to NULL. If the input text contained no SQL (if the input is and // empty string or a comment) then *ppStmt is set to NULL. // // On success, SQLITE_OK is returned. Otherwise an error code is returned. // function sqlite3_prepare( db : psqlite3; // Database handle zSql : PChar; // SQL statement, UTF-8 encoded nBytes: Integer; // Length of zSql in bytes. ppStmt: psqlite3_stmt; // OUT: Statement handle pzTail: PPChar // OUT: Pointer to unused portion of zSql ): Integer; cdecl; external 'sqlite3.dll'; function sqlite3_prepare16( db : psqlite3; // Database handle zSql : PChar; // SQL statement, UTF-16 encoded nBytes: Integer; // Length of zSql in bytes. ppStmt: psqlite3_stmt; // OUT: Statement handle pzTail: PPChar // OUT: Pointer to unused portion of zSql ): Integer; cdecl; external 'sqlite3.dll'; // // Pointers to the following two opaque structures are used to communicate // with the implementations of user-defined functions. // type psqlite3_context = ^sqlite3_context; sqlite3_context = record end; psqlite3_value = ^sqlite3_value; sqlite3_value = record end; // // In the SQL strings input to sqlite3_prepare() and sqlite3_prepare16(), // one or more literals can be replace by parameters "?" or ":AAA" or // "$VVV" where AAA is an identifer and VVV is a variable name according // to the syntax rules of the TCL programming language. // The value of these parameters (also called "host parameter names") can // be set using the routines listed below. // // In every case, the first parameter is a pointer to the sqlite3_stmt // structure returned from sqlite3_prepare(). The second parameter is the // index of the parameter. The first parameter as an index of 1. For // named parameters (":AAA" or "$VVV") you can use // sqlite3_bind_parameter_index() to get the correct index value given // the parameters name. If the same named parameter occurs more than // once, it is assigned the same index each time. // // The fifth parameter to sqlite3_bind_blob(), sqlite3_bind_text(), and // sqlite3_bind_text16() is a destructor used to dispose of the BLOB or // text after SQLite has finished with it. If the fifth argument is the // special value SQLITE_STATIC, then the library assumes that the information // is in static, unmanaged space and does not need to be freed. If the // fifth argument has the value SQLITE_TRANSIENT, then SQLite makes its // own private copy of the data. // // The sqlite3_bind_* routine must be called before sqlite3_step() after // an sqlite3_prepare() or sqlite3_reset(). Unbound parameterss are // interpreted as NULL. // // TODO: int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*)); function sqlite3_bind_double(stm: psqlite3_stmt; i: Integer; d: Double): Integer; cdecl; external 'sqlite3.dll'; function sqlite3_bind_int(stm: psqlite3_stmt; i1, i2: Integer): Integer; cdecl; external 'sqlite3.dll'; function sqlite3_bind_int64(stm: psqlite3_stmt; i: Integer; i64: sqlite_int64): Integer; cdecl; external 'sqlite3.dll'; function sqlite3_bind_null(stm: psqlite3_stmt; i: Integer): Integer; cdecl; external 'sqlite3.dll'; // TODO: int sqlite3_bind_text(sqlite3_stmt*, int, const char*, int n, void(*)(void*)); // TODO: int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*)); function sqlite3_bind_value(stm: psqlite3_stmt; i: Integer; v: psqlite3_value): Integer; cdecl; external 'sqlite3.dll'; // // Return the number of parameters in a compiled SQL statement. This // routine was added to support DBD::SQLite. // function sqlite3_bind_parameter_count(stm: psqlite3_stmt): Integer; cdecl; external 'sqlite3.dll'; // // Return the name of the i-th parameter. Ordinary parameters "?" are // nameless and a NULL is returned. For parameters of the form :AAA or // $VVV the complete text of the parameter name is returned, including // the initial ":" or "$". NULL is returned if the index is out of range. // function sqlite3_bind_parameter_name(stm: psqlite3_stmt; I: Integer): PChar; cdecl; external 'sqlite3.dll'; // // Return the index of a parameter with the given name. The name // must match exactly. If no parameter with the given name is found, // return 0. // function sqlite3_bind_parameter_index(stm: psqlite3_stmt; zName: PChar): Integer; cdecl; external 'sqlite3.dll'; // // Set all the parameters in the compiled SQL statement to NULL. // !!! function sqlite3_clear_bindings(stm: psqlite3_stmt): Integer; cdecl; external 'sqlite3.dll'; // // Return the number of columns in the result set returned by the compiled // SQL statement. This routine returns 0 if pStmt is an SQL statement // that does not return data (for example an UPDATE). // function sqlite3_column_count(stm: psqlite3_stmt): Integer; cdecl; external 'sqlite3.dll'; // // The first parameter is a compiled SQL statement. This function returns // the column heading for the Nth column of that statement, where N is the // second function parameter. The string returned is UTF-8 for // sqlite3_column_name() and UTF-16 for sqlite3_column_name16(). // function sqlite3_column_name(stm: psqlite3_stmt; i: Integer): PChar; cdecl; external 'sqlite3.dll'; function sqlite3_column_name16(stm: psqlite3_stmt; i: Integer): Pointer; cdecl; external 'sqlite3.dll'; // // The first parameter is a compiled SQL statement. If this statement // is a SELECT statement, the Nth column of the returned result set // of the SELECT is a table column then the declared type of the table // column is returned. If the Nth column of the result set is not at table // column, then a NULL pointer is returned. The returned string is always // UTF-8 encoded. For example, in the database schema: // // CREATE TABLE t1(c1 VARIANT); // // And the following statement compiled: // // SELECT c1 + 1, 0 FROM t1; // // Then this routine would return the string "VARIANT" for the second // result column (i==1), and a NULL pointer for the first result column // (i==0). // function sqlite3_column_decltype(stm: psqlite3_stmt; i: Integer): PChar; cdecl; external 'sqlite3.dll'; // // The first parameter is a compiled SQL statement. If this statement // is a SELECT statement, the Nth column of the returned result set // of the SELECT is a table column then the declared type of the table // column is returned. If the Nth column of the result set is not at table // column, then a NULL pointer is returned. The returned string is always // UTF-16 encoded. For example, in the database schema: // // CREATE TABLE t1(c1 INTEGER); // // And the following statement compiled: // // SELECT c1 + 1, 0 FROM t1; // // Then this routine would return the string "INTEGER" for the second // result column (i==1), and a NULL pointer for the first result column // (i==0). // function sqlite3_column_decltype16(stm: psqlite3_stmt; i: Integer): Pointer; cdecl; external 'sqlite3.dll'; // // After an SQL query has been compiled with a call to either // sqlite3_prepare() or sqlite3_prepare16(), then this function must be // called one or more times to execute the statement. // // The return value will be either SQLITE_BUSY, SQLITE_DONE, // SQLITE_ROW, SQLITE_ERROR, or SQLITE_MISUSE. // // SQLITE_BUSY means that the database engine attempted to open // a locked database and there is no busy callback registered. // Call sqlite3_step() again to retry the open. // // SQLITE_DONE means that the statement has finished executing // successfully. sqlite3_step() should not be called again on this virtual // machine. // // If the SQL statement being executed returns any data, then // SQLITE_ROW is returned each time a new row of data is ready // for processing by the caller. The values may be accessed using // the sqlite3_column_*() functions described below. sqlite3_step() // is called again to retrieve the next row of data. // // SQLITE_ERROR means that a run-time error (such as a constraint // violation) has occurred. sqlite3_step() should not be called again on // the VM. More information may be found by calling sqlite3_errmsg(). // // SQLITE_MISUSE means that the this routine was called inappropriately. // Perhaps it was called on a virtual machine that had already been // finalized or on one that had previously returned SQLITE_ERROR or // SQLITE_DONE. Or it could be the case the the same database connection // is being used simulataneously by two or more threads. // function sqlite3_step(stm: psqlite3_stmt): Integer; cdecl; external 'sqlite3.dll'; // // Return the number of values in the current row of the result set. // // After a call to sqlite3_step() that returns SQLITE_ROW, this routine // will return the same value as the sqlite3_column_count() function. // After sqlite3_step() has returned an SQLITE_DONE, SQLITE_BUSY or // error code, or before sqlite3_step() has been called on a // compiled SQL statement, this routine returns zero. // function sqlite3_data_count(stm: psqlite3_stmt): Integer; cdecl; external 'sqlite3.dll'; const // // Values are stored in the database in one of the following fundamental // types. // SQLITE_INTEGER = 1; SQLITE_FLOAT = 2; // SQLite version 2 defines SQLITE_TEXT differently. To allow both // version 2 and version 3 to be included, undefine them both if a // conflict is seen. Define SQLITE3_TEXT to be the version 3 value. SQLITE_TEXT = 3; // See below */ SQLITE_BLOB = 4; SQLITE_NULL = 5; // // The next group of routines returns information about the information // in a single column of the current result row of a query. In every // case the first parameter is a pointer to the SQL statement that is being // executed (the sqlite_stmt* that was returned from sqlite3_prepare()) and // the second argument is the index of the column for which information // should be returned. iCol is zero-indexed. The left-most column as an // index of 0. // // If the SQL statement is not currently point to a valid row, or if the // the colulmn index is out of range, the result is undefined. // // These routines attempt to convert the value where appropriate. For // example, if the internal representation is FLOAT and a text result // is requested, sprintf() is used internally to do the conversion // automatically. The following table details the conversions that // are applied: // // Internal Type Requested Type Conversion // ------------- -------------- -------------------------- // NULL INTEGER Result is 0 // NULL FLOAT Result is 0.0 // NULL TEXT Result is an empty string // NULL BLOB Result is a zero-length BLOB // INTEGER FLOAT Convert from integer to float // INTEGER TEXT ASCII rendering of the integer // INTEGER BLOB Same as for INTEGER->TEXT // FLOAT INTEGER Convert from float to integer // FLOAT TEXT ASCII rendering of the float // FLOAT BLOB Same as FLOAT->TEXT // TEXT INTEGER Use atoi() // TEXT FLOAT Use atof() // TEXT BLOB No change // BLOB INTEGER Convert to TEXT then use atoi() // BLOB FLOAT Convert to TEXT then use atof() // BLOB TEXT Add a \000 terminator if needed // // The following access routines are provided: // // _type() Return the datatype of the result. This is one of // SQLITE_INTEGER, SQLITE_FLOAT, SQLITE_TEXT, SQLITE_BLOB, // or SQLITE_NULL. // _blob() Return the value of a BLOB. // _bytes() Return the number of bytes in a BLOB value or the number // of bytes in a TEXT value represented as UTF-8. The \000 // terminator is included in the byte count for TEXT values. // _bytes16() Return the number of bytes in a BLOB value or the number // of bytes in a TEXT value represented as UTF-16. The \u0000 // terminator is included in the byte count for TEXT values. // _double() Return a FLOAT value. // _int() Return an INTEGER value in the host computer's native // integer representation. This might be either a 32- or 64-bit // integer depending on the host. // _int64() Return an INTEGER value as a 64-bit signed integer. // _text() Return the value as UTF-8 text. // _text16() Return the value as UTF-16 text. // function sqlite3_column_blob(stm: psqlite3_stmt; iCol: Integer): Pointer; cdecl; external 'sqlite3.dll'; function sqlite3_column_bytes(stm: psqlite3_stmt; iCol: Integer): Integer; cdecl; external 'sqlite3.dll'; function sqlite3_column_bytes16(stm: psqlite3_stmt; iCol: Integer): Integer; cdecl; external 'sqlite3.dll'; function sqlite3_column_double(stm: psqlite3_stmt; iCol: Integer): Double; cdecl; external 'sqlite3.dll'; function sqlite3_column_int(stm: psqlite3_stmt; iCol: Integer): Integer; cdecl; external 'sqlite3.dll'; function sqlite3_column_int64(stm: psqlite3_stmt; iCol: Integer): sqlite_int64; cdecl; external 'sqlite3.dll'; function sqlite3_column_text(stm: psqlite3_stmt; iCol: Integer): PChar; cdecl; external 'sqlite3.dll'; function sqlite3_column_text16(stm: psqlite3_stmt; iCol: Integer): Pointer; cdecl; external 'sqlite3.dll'; function sqlite3_column_type(stm: psqlite3_stmt; iCol: Integer): Integer; cdecl; external 'sqlite3.dll'; // // The sqlite3_finalize() function is called to delete a compiled // SQL statement obtained by a previous call to sqlite3_prepare() // or sqlite3_prepare16(). If the statement was executed successfully, or // not executed at all, then SQLITE_OK is returned. If execution of the // statement failed then an error code is returned. // // This routine can be called at any point during the execution of the // virtual machine. If the virtual machine has not completed execution // when this routine is called, that is like encountering an error or // an interrupt. (See sqlite3_interrupt().) Incomplete updates may be // rolled back and transactions cancelled, depending on the circumstances, // and the result code returned will be SQLITE_ABORT. // function sqlite3_finalize(stm: psqlite3_stmt): Integer; cdecl; external 'sqlite3.dll'; // // The sqlite3_reset() function is called to reset a compiled SQL // statement obtained by a previous call to sqlite3_prepare() or // sqlite3_prepare16() back to it's initial state, ready to be re-executed. // Any SQL statement variables that had values bound to them using // the sqlite3_bind_*() API retain their values. // function sqlite3_reset(stm: psqlite3_stmt): Integer; cdecl; external 'sqlite3.dll'; // // The following two functions are used to add user functions or aggregates // implemented in C to the SQL langauge interpreted by SQLite. The // difference only between the two is that the second parameter, the // name of the (scalar) function or aggregate, is encoded in UTF-8 for // sqlite3_create_function() and UTF-16 for sqlite3_create_function16(). // // The first argument is the database handle that the new function or // aggregate is to be added to. If a single program uses more than one // database handle internally, then user functions or aggregates must // be added individually to each database handle with which they will be // used. // // The third parameter is the number of arguments that the function or // aggregate takes. If this parameter is negative, then the function or // aggregate may take any number of arguments. // // The fourth parameter is one of SQLITE_UTF* values defined below, // indicating the encoding that the function is most likely to handle // values in. This does not change the behaviour of the programming // interface. However, if two versions of the same function are registered // with different encoding values, SQLite invokes the version likely to // minimize conversions between text encodings. // // The seventh, eighth and ninth parameters, xFunc, xStep and xFinal, are // pointers to user implemented C functions that implement the user // function or aggregate. A scalar function requires an implementation of // the xFunc callback only, NULL pointers should be passed as the xStep // and xFinal parameters. An aggregate function requires an implementation // of xStep and xFinal, but NULL should be passed for xFunc. To delete an // existing user function or aggregate, pass NULL for all three function // callback. Specifying an inconstent set of callback values, such as an // xFunc and an xFinal, or an xStep but no xFinal, SQLITE_ERROR is // returned. // // TODO: int sqlite3_create_function( // sqlite3 *, // const char *zFunctionName, // int nArg, // int eTextRep, // void*, // void (*xFunc)(sqlite3_context*,int,sqlite3_value**), // void (*xStep)(sqlite3_context*,int,sqlite3_value**), // void (*xFinal)(sqlite3_context*) //); // TODO: int sqlite3_create_function16( // sqlite3*, // const void *zFunctionName, // int nArg, // int eTextRep, // void*, // void (*xFunc)(sqlite3_context*,int,sqlite3_value**), // void (*xStep)(sqlite3_context*,int,sqlite3_value**), // void (*xFinal)(sqlite3_context*) //); // // The next routine returns the number of calls to xStep for a particular // aggregate function instance. The current call to xStep counts so this // routine always returns at least 1. // function sqlite3_aggregate_count(ctx: psqlite3_context): Integer; cdecl; external 'sqlite3.dll'; // // The next group of routines returns information about parameters to // a user-defined function. Function implementations use these routines // to access their parameters. These routines are the same as the // sqlite3_column_* routines except that these routines take a single // sqlite3_value* pointer instead of an sqlite3_stmt* and an integer // column number. // function sqlite3_value_blob(v: psqlite3_value): Pointer; cdecl; external 'sqlite3.dll'; function sqlite3_value_bytes(v: psqlite3_value): Integer; cdecl; external 'sqlite3.dll'; function sqlite3_value_bytes16(v: psqlite3_value): Integer; cdecl; external 'sqlite3.dll'; function sqlite3_value_double(v: psqlite3_value): Double; cdecl; external 'sqlite3.dll'; function sqlite3_value_int(v: psqlite3_value): Integer; cdecl; external 'sqlite3.dll'; function sqlite3_value_int64(v: psqlite3_value): sqlite_int64; cdecl; external 'sqlite3.dll'; function sqlite3_value_text(v: psqlite3_value): PChar; cdecl; external 'sqlite3.dll'; function sqlite3_value_text16(v: psqlite3_value): Pointer; cdecl; external 'sqlite3.dll'; function sqlite3_value_text16le(v: psqlite3_value): Pointer; cdecl; external 'sqlite3.dll'; function sqlite3_value_text16be(v: psqlite3_value): Pointer; cdecl; external 'sqlite3.dll'; function sqlite3_value_type(v: psqlite3_value): Integer; cdecl; external 'sqlite3.dll'; // // Aggregate functions use the following routine to allocate // a structure for storing their state. The first time this routine // is called for a particular aggregate, a new structure of size nBytes // is allocated, zeroed, and returned. On subsequent calls (for the // same aggregate instance) the same buffer is returned. The implementation // of the aggregate can use the returned buffer to accumulate data. // // The buffer allocated is freed automatically by SQLite. // function sqlite3_aggregate_context(ctx: psqlite3_context; nBytes: Integer): Pointer; cdecl; external 'sqlite3.dll'; // // The pUserData parameter to the sqlite3_create_function() and // sqlite3_create_aggregate() routines used to register user functions // is available to the implementation of the function using this // call. // function sqlite3_user_data(ctx: psqlite3_context): Pointer; cdecl; external 'sqlite3.dll'; // // The following two functions may be used by scalar user functions to // associate meta-data with argument values. If the same value is passed to // multiple invocations of the user-function during query execution, under // some circumstances the associated meta-data may be preserved. This may // be used, for example, to add a regular-expression matching scalar // function. The compiled version of the regular expression is stored as // meta-data associated with the SQL value passed as the regular expression // pattern. // // Calling sqlite3_get_auxdata() returns a pointer to the meta data // associated with the Nth argument value to the current user function // call, where N is the second parameter. If no meta-data has been set for // that value, then a NULL pointer is returned. // // The sqlite3_set_auxdata() is used to associate meta data with a user // function argument. The third parameter is a pointer to the meta data // to be associated with the Nth user function argument value. The fourth // parameter specifies a 'delete function' that will be called on the meta // data pointer to release it when it is no longer required. If the delete // function pointer is NULL, it is not invoked. // // In practice, meta-data is preserved between function calls for // expressions that are constant at compile time. This includes literal // values and SQL variables. // function sqlite3_get_auxdata(ctx: psqlite3_context; i: Integer): Pointer; cdecl; external 'sqlite3.dll'; // TODO: void sqlite3_set_auxdata(sqlite3_context*, int, void*, void (*)(void*)); const // // These are special value for the destructor that is passed in as the // final argument to routines like sqlite3_result_blob(). If the destructor // argument is SQLITE_STATIC, it means that the content pointer is constant // and will never change. It does not need to be destroyed. The // SQLITE_TRANSIENT value means that the content will likely change in // the near future and that SQLite should make its own private copy of // the content before returning. // SQLITE_STATIC = 0; SQLITE_TRANSIENT = -1; // // User-defined functions invoke the following routines in order to // set their return value. // // TODO: procedure sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*)); cdecl; external 'sqlite3.dll'; procedure sqlite3_result_double(ctx: psqlite3_context; v: double); cdecl; external 'sqlite3.dll'; procedure sqlite3_result_error(ctx: psqlite3_context; p: PChar; i: Integer); cdecl; external 'sqlite3.dll'; procedure sqlite3_result_error16(ctx: psqlite3_context; p: Pointer; i: Integer); cdecl; external 'sqlite3.dll'; procedure sqlite3_result_int(ctx: psqlite3_context; i: Integer); cdecl; external 'sqlite3.dll'; procedure sqlite3_result_int64(ctx: psqlite3_context; v: sqlite_int64); cdecl; external 'sqlite3.dll'; procedure sqlite3_result_null(ctx: psqlite3_context); cdecl; external 'sqlite3.dll'; // TODO: procedure sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*)); cdecl; external 'sqlite3.dll'; // TODO: procedure sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*)); cdecl; external 'sqlite3.dll'; // TODO: procedure sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*)); cdecl; external 'sqlite3.dll'; // TODO: procedure sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*)); cdecl; external 'sqlite3.dll'; procedure sqlite3_result_value(ctx: psqlite3_context; v: sqlite3_value); cdecl; external 'sqlite3.dll'; const // // These are the allowed values for the eTextRep argument to // sqlite3_create_collation and sqlite3_create_function. // SQLITE_UTF8 = 1; SQLITE_UTF16LE = 2; SQLITE_UTF16BE = 3; SQLITE_UTF16 = 4; // Use native byte order SQLITE_ANY = 5; // sqlite3_create_function only // // These two functions are used to add new collation sequences to the // sqlite3 handle specified as the first argument. // // The name of the new collation sequence is specified as a UTF-8 string // for sqlite3_create_collation() and a UTF-16 string for // sqlite3_create_collation16(). In both cases the name is passed as the // second function argument. // // The third argument must be one of the constants SQLITE_UTF8, // SQLITE_UTF16LE or SQLITE_UTF16BE, indicating that the user-supplied // routine expects to be passed pointers to strings encoded using UTF-8, // UTF-16 little-endian or UTF-16 big-endian respectively. // // A pointer to the user supplied routine must be passed as the fifth // argument. If it is NULL, this is the same as deleting the collation // sequence (so that SQLite cannot call it anymore). Each time the user // supplied function is invoked, it is passed a copy of the void* passed as // the fourth argument to sqlite3_create_collation() or // sqlite3_create_collation16() as its first parameter. // // The remaining arguments to the user-supplied routine are two strings, // each represented by a [length, data] pair and encoded in the encoding // that was passed as the third argument when the collation sequence was // registered. The user routine should return negative, zero or positive if // the first string is less than, equal to, or greater than the second // string. i.e. (STRING1 - STRING2). // // TODO: int sqlite3_create_collation( // sqlite3*, // const char *zName, // int eTextRep, // void*, // int(*xCompare)(void*,int,const void*,int,const void*) //); // TODO: int sqlite3_create_collation16( // sqlite3*, // const char *zName, // int eTextRep, // void*, // int(*xCompare)(void*,int,const void*,int,const void*) //); // // To avoid having to register all collation sequences before a database // can be used, a single callback function may be registered with the // database handle to be called whenever an undefined collation sequence is // required. // // If the function is registered using the sqlite3_collation_needed() API, // then it is passed the names of undefined collation sequences as strings // encoded in UTF-8. If sqlite3_collation_needed16() is used, the names // are passed as UTF-16 in machine native byte order. A call to either // function replaces any existing callback. // // When the user-function is invoked, the first argument passed is a copy // of the second argument to sqlite3_collation_needed() or // sqlite3_collation_needed16(). The second argument is the database // handle. The third argument is one of SQLITE_UTF8, SQLITE_UTF16BE or // SQLITE_UTF16LE, indicating the most desirable form of the collation // sequence function required. The fourth parameter is the name of the // required collation sequence. // // The collation sequence is returned to SQLite by a collation-needed // callback using the sqlite3_create_collation() or // sqlite3_create_collation16() APIs, described above. // // TODO: int sqlite3_collation_needed( // sqlite3*, // void*, // void(*)(void*,sqlite3*,int eTextRep,const char*) //); // TODO: int sqlite3_collation_needed16( // sqlite3*, // void*, // void(*)(void*,sqlite3*,int eTextRep,const void*) //); // // Specify the key for an encrypted database. This routine should be // called right after sqlite3_open(). // // The code to implement this API is not available in the public release // of SQLite. // function sqlite3_key( db : psqlite3; // Database to be rekeyed pKey: Pointer; nKey: Integer // The key ): Integer; cdecl; external 'sqlite3.dll'; // // Change the key on an open database. If the current database is not // encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the // database is decrypted. // // The code to implement this API is not available in the public release // of SQLite. // function sqlite3_rekey( db : sqlite3; // Database to be rekeyed pKey: Pointer; nKey: Integer // The new key ): Integer; cdecl; external 'sqlite3.dll'; // // Sleep for a little while. The second parameter is the number of // miliseconds to sleep for. // // If the operating system does not support sleep requests with // milisecond time resolution, then the time will be rounded up to // the nearest second. The number of miliseconds of sleep actually // requested from the operating system is returned. // function sqlite3_sleep(i: Integer): Integer; cdecl; external 'sqlite3.dll'; // // Return TRUE (non-zero) if the statement supplied as an argument needs // to be recompiled. A statement needs to be recompiled whenever the // execution environment changes in a way that would alter the program // that sqlite3_prepare() generates. For example, if new functions or // collating sequences are registered or if an authorizer function is // added or changed. // // function sqlite3_expired(stm: psqlite3_stmt): Integer; cdecl; external 'sqlite3.dll'; // // Move all bindings from the first prepared statement over to the second. // This routine is useful, for example, if the first prepared statement // fails with an SQLITE_SCHEMA error. The same SQL can be prepared into // the second prepared statement then all of the bindings transfered over // to the second statement before the first statement is finalized. // function sqlite3_transfer_bindings(stm1, stm2: psqlite3_stmt): Integer; cdecl; external 'sqlite3.dll'; // // This function is called to recover from a malloc() failure that occured // within the SQLite library. Normally, after a single malloc() fails the // library refuses to function (all major calls return SQLITE_NOMEM). // This function restores the library state so that it can be used again. // // All existing statements (sqlite3_stmt pointers) must be finalized or // reset before this call is made. Otherwise, SQLITE_BUSY is returned. // If any in-memory databases are in use, either as a main or TEMP // database, SQLITE_ERROR is returned. In either of these cases, the // library is not reset and remains unusable. // // This function is *not* threadsafe. Calling this from within a threaded // application when threads other than the caller have used SQLite is // dangerous and will almost certainly result in malfunctions. // // This functionality can be omitted from a build by defining the // SQLITE_OMIT_GLOBALRECOVER at compile time. // function sqlite3_global_recover: Integer; cdecl; external 'sqlite3.dll'; // // Test to see whether or not the database connection is in autocommit // mode. Return TRUE if it is and FALSE if not. Autocommit mode is on // by default. Autocommit is disabled by a BEGIN statement and reenabled // by the next COMMIT or ROLLBACK. // function sqlite3_get_autocommit(db: psqlite3): Integer; cdecl; external 'sqlite3.dll'; // // Return the sqlite3* database handle to which the prepared statement given // in the argument belongs. This is the same database handle that was // the first argument to the sqlite3_prepare() that was used to create // the statement in the first place. // function sqlite3_db_handle(stm: psqlite3_stmt): psqlite3; cdecl; external 'sqlite3.dll'; implementation end.
unit OptionsObjectFrame; interface uses System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, BCControls.ComboBox, Vcl.ExtCtrls, BCControls.CheckBox, BCCommon.OptionsContainer, BCFrames.OptionsFrame, JvExStdCtrls, JvCheckBox; type TOptionsObjectFrameFrame = class(TOptionsFrame) Panel: TPanel; ButtonPanelAlignLabel: TLabel; ButtonPanelAlignComboBox: TBCComboBox; ShowCreationAndModificationTimestampCheckBox: TBCCheckBox; ShowDataSearchPanelCheckBox: TBCCheckBox; FilterOnTypingCheckBox: TBCCheckBox; private { Private declarations } public { Public declarations } destructor Destroy; override; procedure GetData; override; procedure PutData; override; end; function OptionsObjectFrameFrame(AOwner: TComponent): TOptionsObjectFrameFrame; implementation {$R *.dfm} var FOptionsObjectFrameFrame: TOptionsObjectFrameFrame; function OptionsObjectFrameFrame(AOwner: TComponent): TOptionsObjectFrameFrame; begin if not Assigned(FOptionsObjectFrameFrame) then FOptionsObjectFrameFrame := TOptionsObjectFrameFrame.Create(AOwner); Result := FOptionsObjectFrameFrame; end; destructor TOptionsObjectFrameFrame.Destroy; begin inherited; FOptionsObjectFrameFrame := nil; end; procedure TOptionsObjectFrameFrame.PutData; begin OptionsContainer.ObjectFrameAlign := ButtonPanelAlignComboBox.Text; OptionsContainer.ShowObjectCreationAndModificationTimestamp := ShowCreationAndModificationTimestampCheckBox.Checked; OptionsContainer.ShowDataSearchPanel := ShowDataSearchPanelCheckBox.Checked; OptionsContainer.FilterOnTyping := FilterOnTypingCheckBox.Checked; end; procedure TOptionsObjectFrameFrame.GetData; begin ButtonPanelAlignComboBox.Text := OptionsContainer.ObjectFrameAlign; ShowCreationAndModificationTimestampCheckBox.Checked := OptionsContainer.ShowObjectCreationAndModificationTimestamp; ShowDataSearchPanelCheckBox.Checked := OptionsContainer.ShowDataSearchPanel; FilterOnTypingCheckBox.Checked := OptionsContainer.FilterOnTyping; end; end.
unit UCNumero; interface uses math,sysutils ; Type Numero = Class private Valor: Cardinal; public {Constructor} constructor crearX(x: Cardinal); constructor crear(); {Procedimientos} procedure setValor(x: Cardinal); procedure InserDigito (p,d:byte); procedure ElimDigito (p:byte); procedure Uunir2Num(x:Cardinal); procedure removeDigito(x:byte); procedure ordDesc(); procedure invertir(); {funciones} Function getValor(): Cardinal; function NumDigitos :byte; //cantidad de digitos function unidad(val:Cardinal):string; function dec(val: Cardinal): string; function decena(val: Cardinal): string; function centena(val: Cardinal): string; function literal(): string; function existeNum(x:Cardinal):Boolean; function digMay():byte; function verifPrimo():boolean; function sacarPrimo():Integer; function sacarNoPrimo():Integer; {examen 1-2021} procedure intercalarPrimoYnoPrimo(); End; implementation { Numero } function Numero.centena(val: Cardinal): string; var cen:string; dece: Cardinal; obj:Numero; begin cen:='';//100 1 01 5 85 obj:= Numero.crearX(val mod 100); case(val div 100 )of 1:cen:='CIEN'; 2:cen:='DOSCIENTOS'; 3:cen:='TRESCIENTOS'; 4:cen:='CUATROCIENTOS'; 5:cen:='QUINIENTOS'; 6:cen:='SEISCIENTOS'; 7:cen:='SETECIENTOS'; 8:cen:='OCHOCIENTOS'; 9:cen:='NOVECIENTOS'; end; if (val mod 100 <> 0) then begin if (val div 100 = 1) then cen := 'CIENTO ' + obj.literal else cen := cen +' '+ obj.literal end; Result:= cen; end; constructor Numero.crear(); begin valor := 0; end; //------------------------------------------------------------------ constructor Numero.crearX(x: Cardinal); begin valor := x; end; //------------------------------------------------------------------ {Elimina una posicion del numero ej valor = 456 p=2 --> valor 46} procedure Numero.ElimDigito(p: byte); var k,N1,N2 : cardinal; begin if (p>0) and (p<= NumDigitos) then begin k:= trunc(power(10,p-1)); n1:= valor div k; n2:= valor mod k; n1:= n1 div 10; valor:= n1 * k + n2; end else raise Exception.Create('Posicion fuera de rango'); end; //------------------------------------------------------------------ function Numero.getValor: Cardinal; begin result := valor; end; //------------------------------------------------------------------ procedure Numero.InserDigito(p, d: byte); var n1,n2,k:cardinal; begin if (p>0) and (p <= NumDigitos) then begin k:=trunc(power(10,p-1)); n1:= (valor div k)*10 + d; n2:= valor mod k; valor:=n1 *k + n2; end else raise Exception.Create('Posicion fuera de rango'); end; procedure Numero.intercalarPrimoYnoPrimo; var sw : Boolean; x : Integer; n : Cardinal; begin invertir(); sw := true; n := 0; while (valor > 0) do begin if sw then begin x := sacarPrimo(); end else begin x := sacarNoPrimo(); end; if x >= 0 then begin n := n * 10 + x; end; sw := not(sw); end; valor := n; end; procedure Numero.invertir; var n:Cardinal; begin n := 0; while Valor > 0 do begin n := n *10 +(valor mod 10); Valor := valor div 10; end; valor := n; end; //------------------------------------------------------------------ //cantidad de digitos function Numero.NumDigitos: byte; var res: byte; begin if valor = 0 then begin res := 0; end else begin res := trunc(log10(valor))+1; end; result:= res; end; //------------------------------------------------------------------ //ordear el numero descendentemente procedure Numero.ordDesc; var n:cardinal; d:byte; begin n := 0; while valor > 0 do begin d := digMay; n := n * 10 + d; removeDigito(d); //procedure end; valor := n; end; //------------------------------------------------------------------ {eliminar un digito x ej valor = 785;x = 8 ---> valor=75 } procedure Numero.removeDigito(x: byte); var d:byte; n,pot:Cardinal; sw:boolean; begin n := 0; sw := true; pot := 1; while (valor > 0) and (sw) do begin d := valor mod 10; if d = x then begin sw := false; end else begin n := d * pot + n; pot := pot * 10; end; valor := valor div 10; end; Uunir2Num(n); end; //------------------------------------------------------------------ {si un numero se encuentra en otro} function Numero.existeNum(x: Cardinal): Boolean; var cd: byte; val, d, n: Cardinal; cantD: Numero; //objeto sw:boolean; begin val := valor; cantD := Numero.crearX(x); cd := cantD.NumDigitos; n:=0; sw := false; while val > 0 do begin d := val MOD trunc(power(10, cd));//39; if d = x then begin val := 0; sw := true; end else begin n := n * 10 + d; val := val div 10; end; end; result := sw; end; //------------------------------------------------------------------ function Numero.sacarNoPrimo: Integer; var n, p : Cardinal; res:Integer; obj:Numero; begin p := 1; n := 0; res:=-1; obj := Numero.crearX(valor mod 10); while (valor > 0)and (obj.verifPrimo) do begin n := (valor mod 10) * p + n; p := p * 10; valor:= valor div 10; obj.setValor(valor mod 10); end; if valor > 0 then begin // encontraste al no primo res:= valor mod 10; valor := valor div 10; end; Uunir2Num(n); result := res; end; function Numero.sacarPrimo: Integer; var n, p : Cardinal; res:Integer; obj:Numero; begin p := 1; n := 0; res:=-1; obj := Numero.crearX(valor mod 10); while (valor > 0)and not(obj.verifPrimo) do begin n := (valor mod 10) * p + n; p := p * 10; valor:= valor div 10; obj.setValor(valor mod 10); end; if valor > 0 then begin // encontraste al primo res:= valor mod 10; valor := valor div 10; end; Uunir2Num(n); result := res; end; procedure Numero.setValor(x: Cardinal); begin valor := x; end; //------------------------------------------------------------------ function Numero.unidad(val: Cardinal): string; var uni:string; begin uni:=''; case (val )of 0: uni:='CERO'; 1: uni:='UNO'; 2: uni:='DOS'; 3: uni:='TRES'; 4: uni:='CUATRO'; 5: uni:='CINCO'; 6: uni:='SEIS'; 7: uni:='SIETE'; 8: uni:='OCHO'; 9: uni:='NUEVE'; end; result:= uni; end; //------------------------------------------------------------------ {unir 2 numeros} procedure Numero.Uunir2Num(x: Cardinal); var objeto:Numero; begin //123 46 //123 *100 + 46 ===> 12346 objeto := Numero.crearX(x); valor := valor * trunc(power(10,objeto.NumDigitos)) + objeto.Valor; end; function Numero.verifPrimo: boolean; var i: Cardinal; sw : Boolean; begin if valor = 1 then begin Result := false; end else begin i := Valor div 2; sw := true; while ( i > 1)and sw do begin if (valor mod i) = 0 then sw := false; i:= i - 1; end; result := sw; end; end; //------------------------------------------------------------------ function Numero.dec(val: Cardinal): string; var helps:string; begin helps:=''; case(val ) of 10:helps:='DIEZ '; 11:helps:='ONCE '; 12:helps:='DOCE '; 13:helps:='TRECE '; 14:helps:='CATORCE '; 15:helps:='QUINCE '; 16:helps:='DIECISEIS '; 17:helps:='DIECISIETE '; 18:helps:='DIECIOCHO '; 19:helps:='DIECINUEVE '; end; result:=helps; end; //------------------------------------------------------------------- function Numero.decena(val: Cardinal): string; var dece:string; d, m : byte; begin dece:='';//20 m := val mod 10; // 0 d := val div 10; //3 case( d )of 2:dece:='VEINTE'; 3:dece:='TREINTA'; 4:dece:='CUARENTA'; 5:dece:='CINCUENTA'; 6:dece:='SESENTA'; 7:dece:='SETENTA'; 8:dece:='OCHENTA'; 9:dece:='NOVENTA'; end; if (m <> 0) then begin if (d = 2) then //21...29 dece := 'VEINTI'+ unidad(m) else //31...99 dece := dece + ' Y '+ unidad(m); end; result := dece; end; //------------------------------------------------------------------- function Numero.digMay: byte; var n:Cardinal; d, may:byte; begin n := valor; may := 0; while n > 0 do begin d := n mod 10; n := n div 10; if d > may then may := d; end; result := may; end; //-------------------------------------------------------------- function Numero.literal(): string; var cad:string; begin cad:=''; //20 case(Valor)of 0..9: cad := unidad(valor); 10..19: cad := dec(valor); 20..99: cad := decena(valor); 100..999: cad := centena(valor) else cad:= 'fuera de rango'; end; result:= cad; end; //------------------------------------------------------------------ end.
unit HtmlToText; interface type HCkHtmlToText = Pointer; HCkString = Pointer; function CkHtmlToText_Create: HCkHtmlToText; stdcall; procedure CkHtmlToText_Dispose(handle: HCkHtmlToText); stdcall; procedure CkHtmlToText_getDebugLogFilePath(objHandle: HCkHtmlToText; outPropVal: HCkString); stdcall; procedure CkHtmlToText_putDebugLogFilePath(objHandle: HCkHtmlToText; newPropVal: PWideChar); stdcall; function CkHtmlToText__debugLogFilePath(objHandle: HCkHtmlToText): PWideChar; stdcall; function CkHtmlToText_getDecodeHtmlEntities(objHandle: HCkHtmlToText): wordbool; stdcall; procedure CkHtmlToText_putDecodeHtmlEntities(objHandle: HCkHtmlToText; newPropVal: wordbool); stdcall; procedure CkHtmlToText_getLastErrorHtml(objHandle: HCkHtmlToText; outPropVal: HCkString); stdcall; function CkHtmlToText__lastErrorHtml(objHandle: HCkHtmlToText): PWideChar; stdcall; procedure CkHtmlToText_getLastErrorText(objHandle: HCkHtmlToText; outPropVal: HCkString); stdcall; function CkHtmlToText__lastErrorText(objHandle: HCkHtmlToText): PWideChar; stdcall; procedure CkHtmlToText_getLastErrorXml(objHandle: HCkHtmlToText; outPropVal: HCkString); stdcall; function CkHtmlToText__lastErrorXml(objHandle: HCkHtmlToText): PWideChar; stdcall; function CkHtmlToText_getLastMethodSuccess(objHandle: HCkHtmlToText): wordbool; stdcall; procedure CkHtmlToText_putLastMethodSuccess(objHandle: HCkHtmlToText; newPropVal: wordbool); stdcall; function CkHtmlToText_getRightMargin(objHandle: HCkHtmlToText): Integer; stdcall; procedure CkHtmlToText_putRightMargin(objHandle: HCkHtmlToText; newPropVal: Integer); stdcall; function CkHtmlToText_getSuppressLinks(objHandle: HCkHtmlToText): wordbool; stdcall; procedure CkHtmlToText_putSuppressLinks(objHandle: HCkHtmlToText; newPropVal: wordbool); stdcall; function CkHtmlToText_getVerboseLogging(objHandle: HCkHtmlToText): wordbool; stdcall; procedure CkHtmlToText_putVerboseLogging(objHandle: HCkHtmlToText; newPropVal: wordbool); stdcall; procedure CkHtmlToText_getVersion(objHandle: HCkHtmlToText; outPropVal: HCkString); stdcall; function CkHtmlToText__version(objHandle: HCkHtmlToText): PWideChar; stdcall; function CkHtmlToText_IsUnlocked(objHandle: HCkHtmlToText): wordbool; stdcall; function CkHtmlToText_ReadFileToString(objHandle: HCkHtmlToText; filename: PWideChar; srcCharset: PWideChar; outStr: HCkString): wordbool; stdcall; function CkHtmlToText__readFileToString(objHandle: HCkHtmlToText; filename: PWideChar; srcCharset: PWideChar): PWideChar; stdcall; function CkHtmlToText_SaveLastError(objHandle: HCkHtmlToText; path: PWideChar): wordbool; stdcall; function CkHtmlToText_ToText(objHandle: HCkHtmlToText; html: PWideChar; outStr: HCkString): wordbool; stdcall; function CkHtmlToText__toText(objHandle: HCkHtmlToText; html: PWideChar): PWideChar; stdcall; function CkHtmlToText_UnlockComponent(objHandle: HCkHtmlToText; code: PWideChar): wordbool; stdcall; function CkHtmlToText_WriteStringToFile(objHandle: HCkHtmlToText; stringToWrite: PWideChar; filename: PWideChar; charset: PWideChar): wordbool; stdcall; implementation {$Include chilkatDllPath.inc} function CkHtmlToText_Create; external DLLName; procedure CkHtmlToText_Dispose; external DLLName; procedure CkHtmlToText_getDebugLogFilePath; external DLLName; procedure CkHtmlToText_putDebugLogFilePath; external DLLName; function CkHtmlToText__debugLogFilePath; external DLLName; function CkHtmlToText_getDecodeHtmlEntities; external DLLName; procedure CkHtmlToText_putDecodeHtmlEntities; external DLLName; procedure CkHtmlToText_getLastErrorHtml; external DLLName; function CkHtmlToText__lastErrorHtml; external DLLName; procedure CkHtmlToText_getLastErrorText; external DLLName; function CkHtmlToText__lastErrorText; external DLLName; procedure CkHtmlToText_getLastErrorXml; external DLLName; function CkHtmlToText__lastErrorXml; external DLLName; function CkHtmlToText_getLastMethodSuccess; external DLLName; procedure CkHtmlToText_putLastMethodSuccess; external DLLName; function CkHtmlToText_getRightMargin; external DLLName; procedure CkHtmlToText_putRightMargin; external DLLName; function CkHtmlToText_getSuppressLinks; external DLLName; procedure CkHtmlToText_putSuppressLinks; external DLLName; function CkHtmlToText_getVerboseLogging; external DLLName; procedure CkHtmlToText_putVerboseLogging; external DLLName; procedure CkHtmlToText_getVersion; external DLLName; function CkHtmlToText__version; external DLLName; function CkHtmlToText_IsUnlocked; external DLLName; function CkHtmlToText_ReadFileToString; external DLLName; function CkHtmlToText__readFileToString; external DLLName; function CkHtmlToText_SaveLastError; external DLLName; function CkHtmlToText_ToText; external DLLName; function CkHtmlToText__toText; external DLLName; function CkHtmlToText_UnlockComponent; external DLLName; function CkHtmlToText_WriteStringToFile; external DLLName; end.
unit NewsDM; interface uses Classes, DataBase, DB, DBClient; type TDM = class(TDB) News: TClientDataSet; dsNews: TDataSource; Categories: TClientDataSet; dsCategories: TDataSource; public { работа с путем для файлов } function GetFilesPath(DataSet: TDataSet): String; override; function GetLocalPath(DataSet: TDataSet): String; override; end; var DM: TDM; implementation {$R *.dfm} uses SysUtils; const NEWS_PATH : String = 'images\news\'; { TDM } function TDM.GetFilesPath(DataSet: TDataSet): String; var FileList: TStringList; Images: TStringList; i: Integer; begin Result := ''; if DataSet = News then begin // поулчение списка фоток if Length(Trim(DataSet['images'])) > 0 then begin Images := TStringList.Create; try Images.Text := DataSet['images']; FileList := TStringList.Create; try for i := 0 to Images.Count - 1 do FileList.Add(GetLocalPath(DataSet) + Images[i]); Result := FileList.Text; finally FileList.Free; end; finally Images.Free; end; end else // убиваем папку DelDir(GetLocalPath(DataSet)); end; end; function TDM.GetLocalPath(DataSet: TDataSet): String; begin Result := DataPath + NEWS_PATH + DataSet['name'] + '\'; end; end.
unit ResearchGroup; interface uses BaseObjects, BaseReport, CommonReport, LasFile, Classes, Material, Encoder; type TInfoGroup = class(TIDObject) private FTestQuery: string; FTag: string; FTestQueryResult: OleVariant; FPlace: string; FIsSingle: Boolean; protected function PrepareTestQuery: string; virtual; procedure InternalRetrieveObjectInfo(AObject: TIDObject; ADestinationPath: string = ''; AObjectList: TIDObjects = nil); virtual; procedure InternalRetrieveObjectsInfo(AObjects: TIDObjects; ADestinationPath: string = ''; AObjectList: TIDObjects = nil); virtual; procedure InitializeInfoGroup; virtual; function GetUserFolderName: string; virtual; public property TestQuery: string read FTestQuery write FTestQuery; property TestQueryResult: OleVariant read FTestQueryResult; property UserFolderName: string read GetUserFolderName; function ObjectInfoExists(AObject: TIDObject): Boolean; property Tag: string read FTag write FTag; property Place: string read FPlace write FPlace; property IsSingle: Boolean read FIsSingle write FIsSingle; procedure RetrieveObjectInfo(AObject: TIDObject; ADestinationPath: string = ''; AObjectList: TIDObjects = nil); procedure RetrieveObjectsInfo(AObjects: TIDObjects; ADestinationPath: string = ''; AObjectList: TIDObjects = nil); constructor Create(ACollection: TIDObjects); override; end; TInfoGroupClassType = class of TInfoGroup; TReportInfoGroup = class(TInfoGroup) private FReport: TBaseReport; FReportClass: TBaseReportClass; protected procedure InternalRetrieveObjectInfo(AObject: TIDObject; ADestinationPath: string = ''; AObjectList: TIDObjects = nil); override; procedure InternalRetrieveObjectsInfo(AObjects: TIDObjects; ADestinationPath: string = ''; AObjectList: TIDObjects = nil); override; function GetUserFolderName: string; override; public property ReportClass: TBaseReportClass read FReportClass write FReportClass; property Report: TBaseReport read FReport; end; TFileInfoGroup = class(TInfoGroup) private FSourceBaseDir: string; FOldFileName: string; FNewFilename: string; FDefaultExt: string; protected procedure DoAfterCopy(); virtual; procedure InternalRetrieveObjectInfo(AObject: TIDObject; ADestinationPath: string = ''; AObjectList: TIDObjects = nil); override; public property DefaultExt: string read FDefaultExt write FDefaultExt; property FileName: string read FNewFilename write FNewFileName; property OldFileName: string read FOldFileName write FOldFileName; property SourceBaseDir: string read FSourceBaseDir write FSourceBaseDir; end; TLasFileInfoGroup = class(TFileInfoGroup) private FLasFileContent: TLasFileContent; FCurvesToCrop: TStringList; FCropCurves: boolean; FCropBlocks: Boolean; FEncoding: TEncoding; FMakeReplacements: boolean; FReplacementList: TReplacementList; FBlocksToLeave: TStringList; function GetCurvesToCrop: TStringList; function GetBlocksToLeave: TStringList; protected procedure InitializeInfoGroup; override; procedure DoAfterCopy(); override; procedure InternalRetrieveObjectInfo(AObject: TIDObject; ADestinationPath: string = ''; AObjectList: TIDObjects = nil); override; function GetUserFolderName: string; override; public property Encoding: TEncoding read FEncoding write FEncoding; property LasFileContent: TLasFileContent read FLasFileContent; property CropCurves: Boolean read FCropCurves write FCropCurves; property CurvesToLeave: TStringList read GetCurvesToCrop; property CropBlocks: boolean read FCropBlocks write FCropBlocks; property BlocksToLeave: TStringList read GetBlocksToLeave; property MakeReplacements: boolean read FMakeReplacements write FMakeReplacements; property Replacements: TReplacementList read FReplacementList write FReplacementList; destructor Destroy; override; end; TAllLasFileCopyAnsi = class(TLasFileInfoGroup) protected procedure InitializeInfoGroup; override; end; TAllLasFileCopyAscii = class(TLasFileInfoGroup) protected procedure InitializeInfoGroup; override; end; TDMFileInfoGroup = class(TFileInfoGroup) private FDocTypeName: string; protected FDocumentTypes: TDocumentTypes; procedure DoAfterCopy; override; procedure InternalRetrieveObjectInfo(AObject: TIDObject; ADestinationPath: string = ''; AObjectList: TIDObjects = nil); override; function GetDocumentTypes: TDocumentTypes; virtual; procedure InitializeInfoGroup; override; function PrepareTestQuery: string; override; public property DocTypeName: string read FDocTypeName write FDocTypeName; property DocumentTypes: TDocumentTypes read GetDocumentTypes; destructor Destroy; override; end; TLasReplacements = class(TReplacementList) public constructor Create; override; end; TGKNGKLasFileInfoGroup = class(TLasFileInfoGroup) protected procedure InitializeInfoGroup; override; end; TStLasFileInfoGroup = class(TLasFileInfoGroup) protected procedure InitializeInfoGroup; override; end; TAKLasFileInfoGroup = class(TLasFileInfoGroup) protected procedure InitializeInfoGroup; override; end; TPetrophisicsReportInfoGroup = class(TReportInfoGroup) protected procedure InitializeInfoGroup; override; end; TGranulometryReportInfoGroup = class(TReportInfoGroup) protected procedure InitializeInfoGroup; override; end; TCentrifugingReportInfoGroup = class(TReportInfoGroup) protected procedure InitializeInfoGroup; override; end; TCoreDescriptionFileInfoGroup = class(TDMFileInfoGroup) protected procedure InitializeInfoGroup; override; end; TSchlamDescriptionFileInfoGroup = class(TDMFileInfoGroup) protected procedure InitializeInfoGroup; override; end; TSchlifDescriptionFileInfoGroup = class(TDMFileInfoGroup) protected procedure InitializeInfoGroup; override; end; TInclinometrFileInfoGroup = class(TDMFileInfoGroup) protected procedure InitializeInfoGroup; override; end; TDMPetrofisicsFileInfoGroup = class(TDMFileInfoGroup) protected procedure InitializeInfoGroup; override; function GetUserFolderName: string; override; end; TStandardSubdivisionReportInfoGroup = class(TReportInfoGroup) protected procedure InitializeInfoGroup; override; end; TInfoGroups = class(TIDObjects) private function GetItems(const Index: Integer): TInfoGroup; public function AreSingle: Boolean; function HaveSingle: Boolean; function AddInfoGroupClass(AInfoGroupClassType: TInfoGroupClassType): TInfoGroup; property Items[const Index: Integer]: TInfoGroup read GetItems; constructor Create; override; end; implementation uses Facade, SysUtils, Variants, Windows, PetrophisicsReports, SubdivisionReports, FileUtils; { TInfoGroups } function TInfoGroups.AddInfoGroupClass( AInfoGroupClassType: TInfoGroupClassType): TInfoGroup; begin Result := AInfoGroupClassType.Create(Self); inherited Add(Result, False, False); end; function TInfoGroups.AreSingle: Boolean; var i: Integer; begin Result := True; for i := 0 to Count - 1 do Result := Result and Items[i].IsSingle; end; constructor TInfoGroups.Create; begin inherited; FObjectClass := TInfoGroup; FDataPoster := nil; end; function TInfoGroups.GetItems(const Index: Integer): TInfoGroup; begin Result := inherited Items[index] as TInfoGroup; end; function TInfoGroups.HaveSingle: Boolean; var i: Integer; begin Result := false; for i := 0 to Count - 1 do Result := Result or Items[i].IsSingle; end; { TInfoGroup } constructor TInfoGroup.Create(ACollection: TIDObjects); begin inherited; FDataPoster := nil; ClassIDString := 'Ãðóïïà èññëåäîâàíèé'; InitializeInfoGroup; end; function TInfoGroup.GetUserFolderName: string; begin Result := Name; end; procedure TInfoGroup.InitializeInfoGroup; begin end; procedure TInfoGroup.InternalRetrieveObjectInfo(AObject: TIDObject; ADestinationPath: string = ''; AObjectList: TIDObjects = nil); begin end; procedure TInfoGroup.InternalRetrieveObjectsInfo(AObjects: TIDObjects; ADestinationPath: string; AObjectList: TIDObjects); begin end; function TInfoGroup.ObjectInfoExists(AObject: TIDObject): Boolean; var sQuery: string; begin sQuery := PrepareTestQuery; sQuery := Format(sQuery, [IntToStr(AObject.ID)]); Result := TMainFacade.GetInstance.ExecuteQuery(sQuery, FTestQueryResult) > 0; end; function TInfoGroup.PrepareTestQuery: string; begin Result := TestQuery; end; procedure TInfoGroup.RetrieveObjectInfo(AObject: TIDObject; ADestinationPath: string = ''; AObjectList: TIDObjects = nil); begin if ObjectInfoExists(AObject) then InternalRetrieveObjectInfo(AObject, ADestinationPath, AObjectList); end; procedure TInfoGroup.RetrieveObjectsInfo(AObjects: TIDObjects; ADestinationPath: string; AObjectList: TIDObjects); begin InternalRetrieveObjectsInfo(AObjects, ADestinationPath, AObjectList); end; { TFileInfoGroup } procedure TFileInfoGroup.DoAfterCopy; begin end; procedure TFileInfoGroup.InternalRetrieveObjectInfo(AObject: TIDObject; ADestinationPath: string = ''; AObjectList: TIDObjects = nil); var i: integer; sLastFileName, sRealExt: string; begin inherited; // êîïèðóåò ôàéëû èç BaseDir â ADestinationPath if (not varIsEmpty(FTestQueryResult)) and (not varIsNull(FTestQueryResult)) then begin sLastFileName := ''; for i := 0 to VarArrayHighBound(FTestQueryResult, 2) do begin FOldFileName := SourceBaseDir + varAsType(FTestQueryResult[0, i], varOleStr); sLastFileName := FNewFilename; if VarArrayHighBound(FTestQueryResult, 1) = 0 then FNewFileName := ADestinationPath + '\' + ExtractFileName(FOldFileName) else if VarArrayHighBound(FTestQueryResult, 1) > 0 then FNewFileName := ADestinationPath + '\' + ExtractFileName(varAsType(FTestQueryResult[1, i], varOleStr)); if (i > 0) and (sLastFileName = FNewFilename) then FNewFilename := StringReplace(FNewFilename, '.', '(' + IntToStr(i + 1) + ').', []); if VarArrayHighBound(FTestQueryResult, 1) > 1 then // òðåòèé ñòîëáåö - èñòî÷íèê ðàñøèðåíèÿ begin sRealExt := ExtractFileExt(varAsType(FTestQueryResult[2, i], varOleStr)); FNewFilename := ChangeFileExt(FNewFilename, sRealExt); end; FNewFilename := CorrectFileName(FNewFilename); if FileExists(FOldFileName) then begin //try CopyFile(PChar(FOldFileName), PChar(FNewFileName), False); DoAfterCopy(); //except // !! //end; end; end; end; end; { TGKNGKLasFileInfoGroup } procedure TGKNGKLasFileInfoGroup.InitializeInfoGroup; begin inherited; TestQuery := 'select distinct lf.vch_filename, lf.vch_old_filename from tbl_las_file lf, tbl_las_curve lc, tbl_curve_dict cc where cc.curve_id = lc.curve_id and lf.las_file_uin = lc.las_file_uin and cc.curve_category_id in (7,8,15,16) and lf.well_uin = %s'; Name := 'ÃÊ, ÍÃÊ, ÃÃÊÏ'; Encoding := encAnsi; CropCurves := True; CurvesToLeave.Add('DEPT'); CurvesToLeave.Add('DEPTH'); CurvesToLeave.Add('GGKp'); CurvesToLeave.Add('GK'); CurvesToLeave.Add('GK d_k'); CurvesToLeave.Add('GKp_k'); CurvesToLeave.Add('GR'); CurvesToLeave.Add('GR2'); CurvesToLeave.Add('NEUT'); CurvesToLeave.Add('NGK'); CurvesToLeave.Add('NGL'); CurvesToLeave.Add('NGR'); CurvesToLeave.Add('NKTB'); CurvesToLeave.Add('NKTM'); CurvesToLeave.Add('NKtb'); CurvesToLeave.Add('NPHI'); CurvesToLeave.Add('RHOB'); CurvesToLeave.Add('TNNB'); CurvesToLeave.Add('TNNS'); CurvesToLeave.Add('ÃÃÊÏ'); CurvesToLeave.Add('ÃÃÊÏ1'); CurvesToLeave.Add('ÃÃÊï'); CurvesToLeave.Add('ÃÃÊï_ê'); CurvesToLeave.Add('ÃÊ'); CurvesToLeave.Add('ÃÊ ñâ1'); CurvesToLeave.Add('ÃÊ ñâ2'); CurvesToLeave.Add('ÃÊ-áðàê'); CurvesToLeave.Add('ÃÊ1'); CurvesToLeave.Add('ÃÊ2'); CurvesToLeave.Add('ÃÊÍ'); CurvesToLeave.Add('ÃÊè'); CurvesToLeave.Add('ÃÊê'); CurvesToLeave.Add('ÃÊñâ'); CurvesToLeave.Add('ÍÃÊ'); CurvesToLeave.Add('ÍÃÊ ñâ1'); CurvesToLeave.Add('ÍÃÊ ñâ2'); CurvesToLeave.Add('ÍÊ'); CurvesToLeave.Add('ÍÊÒ'); CurvesToLeave.Add('ÍÊÒÁ'); CurvesToLeave.Add('ÍÊÒÁê'); CurvesToLeave.Add('ÍÊÒÌ'); CurvesToLeave.Add('ÍÊÒÌê'); CurvesToLeave.Add('ÍÊÒá'); CurvesToLeave.Add('ÍÊÒì'); CurvesToLeave.Add('ÍÍÊÒ'); CurvesToLeave.Add('ÍÍÊÒÁ'); CurvesToLeave.Add('ÍÍÊÒá'); CurvesToLeave.Add('ÍÍÊÒì'); CurvesToLeave.Add('ÍÍÊòÁÇ'); CurvesToLeave.Add('ÍÍÊòÌÇ'); CurvesToLeave.Add('ÍÍÍÁ'); CurvesToLeave.Add('ÍÍÍÌ'); CurvesToLeave.Add('ÍÍÒÁ'); CurvesToLeave.Add('ÍÍÒÌ'); FReplacementList := TLasReplacements.Create; ////1-------- ýòî äëÿ òàêîãî ñëó÷àÿ: WeLL. WELL:5----------------// Replacements.AddReplacement('~Well', 'WELL', ' WELL:2', '2_Saluk: '); Replacements.AddReplacement('~Well', 'FLD', 'FIELD:Ñàëþêèíñêàÿ (-îå)', ' : '); //Replacements.AddReplacement('~Well', 'WELL', ' 91', '91_Yareyag'); //Replacements.AddReplacement('~Well', 'FLD', 'ßðåéÿãèíñêàÿ', ' '); Replacements.AddReplacement('~Curve','À','À','A'); Replacements.AddReplacement('~Curve','Á','Á','B'); Replacements.AddReplacement('~Curve','Â','Â','V'); Replacements.AddReplacement('~Curve','Ã','Ã','G'); Replacements.AddReplacement('~Curve','Ä','Ä','D'); Replacements.AddReplacement('~Curve','Å','Å','E'); Replacements.AddReplacement('~Curve','Æ','Æ','J'); Replacements.AddReplacement('~Curve','Ç','Ç','Z'); Replacements.AddReplacement('~Curve','È','È','I'); Replacements.AddReplacement('~Curve','Ê','Ê','K'); Replacements.AddReplacement('~Curve','Ë','Ë','L'); Replacements.AddReplacement('~Curve','Ì','Ì','M'); Replacements.AddReplacement('~Curve','Í','Í','N'); Replacements.AddReplacement('~Curve','Î','Î','O'); Replacements.AddReplacement('~Curve','Ï','Ï','P'); Replacements.AddReplacement('~Curve','Ð','Ð','R'); Replacements.AddReplacement('~Curve','Ñ','Ñ','S'); Replacements.AddReplacement('~Curve','Ò','Ò','T'); Replacements.AddReplacement('~Curve','Ó','Ó','U'); Replacements.AddReplacement('~Curve','Ô','Ô','F'); Replacements.AddReplacement('~Curve','Õ','Õ','H'); Replacements.AddReplacement('~Curve','Ö','Ö','C'); Replacements.AddReplacement('~Curve','×','×','Ch'); Replacements.AddReplacement('~Curve','Ø','Ø','Sh'); Replacements.AddReplacement('~Curve','Ù','Ù','Sch'); Replacements.AddReplacement('~Curve','Ý','Ý','A'); Replacements.AddReplacement('~Curve','Þ','Þ','U'); Replacements.AddReplacement('~Curve','ß','ß','Ya'); end; { TLasFileInfoGroup } destructor TLasFileInfoGroup.Destroy; begin FreeAndNil(FReplacementList); FreeAndNil(FBlocksToLeave); FreeAndNil(FCurvesToCrop); inherited; end; procedure TLasFileInfoGroup.DoAfterCopy; var sFileName: string; begin inherited; sFileName := FileName + '_'; TEncoder.GetInstance.DecodeFile(FileName, sFileName); FLasFileContent := TLasFileContent.Create(sFileName); // FLasFileContent.ReadFile; if CropCurves then FLasFileContent.CropAllExceptListedCurves(CurvesToLeave); if CropBlocks then FLasFileContent.CropAllExceptListedBlocks(BlocksToLeave); if MakeReplacements then {FLasFileContent.MakeReplacements(Replacements); } case Encoding of encAscii: begin FLasFileContent.SaveFile(); TEncoder.GetInstance.EncodeFile(sFileName, FileName); end; encAnsi: FLasFileContent.SaveFile(FileName); end; DeleteFile(PChar(sFileName)); end; function TLasFileInfoGroup.GetBlocksToLeave: TStringList; begin if not Assigned(FBlocksToLeave) then FBlocksToLeave := TStringList.Create; Result := FBlocksToLeave; end; function TLasFileInfoGroup.GetCurvesToCrop: TStringList; begin if not Assigned(FCurvesToCrop) then FCurvesToCrop := TStringList.Create; Result := FCurvesToCrop; end; function TLasFileInfoGroup.GetUserFolderName: string; begin Result := Tag + '\' + Name; end; procedure TLasFileInfoGroup.InitializeInfoGroup; begin inherited; Tag := 'LAS-ôàéëû'; SourceBaseDir := '\\SRVDB.TPRC\LasBank\LasBank'; Place := 'ÐÁÖÃÈ'; DefaultExt := '.las'; CropCurves := true; MakeReplacements := true; CropBlocks := true; Encoding := encAnsi; BlocksToLeave.Add('~Version'); BlocksToLeave.Add('~Well'); BlocksToLeave.Add('~Curve'); BlocksToLeave.Add('~A'); end; procedure TLasFileInfoGroup.InternalRetrieveObjectInfo(AObject: TIDObject; ADestinationPath: string = ''; AObjectList: TIDObjects = nil); begin inherited; end; { TPetrophisicsReportInfoGroup } procedure TPetrophisicsReportInfoGroup.InitializeInfoGroup; begin inherited; TestQuery := 'select * from tbl_dnr_research d, tbl_rock_sample rs, tbl_slotting s where d.rock_sample_uin = rs.rock_sample_uin and s.slotting_uin = rs.slotting_uin and d.research_id >= 100 and d.research_id < 200 and s.Well_UIN = %s'; Name := 'Îáùèå ïåòðîôèçè÷åñêèå ñâîéñòâà'; Tag := 'Ïåòðîôèçèêà'; Place := 'ÐÁÖÃÈ'; ReportClass := TPetrophisicsReport; end; { TReportInfoGroup } function TReportInfoGroup.GetUserFolderName: string; begin Result := Tag; end; procedure TReportInfoGroup.InternalRetrieveObjectInfo(AObject: TIDObject; ADestinationPath: string = ''; AObjectList: TIDObjects = nil); begin inherited; FReport := ReportClass.Create(nil); FReport.ReportPath := ADestinationPath; FReport.MakeVisible := false; FReport.ReportingObjects.Clear; FReport.ReportingObjects.Add(AObject, False, False); // âñå îáúåêòû if Assigned(AObjectList) then begin FReport.AllObjects.Clear; FReport.AllObjects.AddObjects(AObjectList, False, False); end; FReport.Execute; FReport.Free; end; procedure TReportInfoGroup.InternalRetrieveObjectsInfo( AObjects: TIDObjects; ADestinationPath: string; AObjectList: TIDObjects); begin FReport := ReportClass.Create(nil); FReport.ReportPath := ADestinationPath; FReport.MakeVisible := false; FReport.ReportingObjects.Clear; FReport.ReportingObjects.AddObjects(AObjects, False, False); // âñå îáúåêòû if Assigned(AObjectList) then begin FReport.AllObjects.Clear; FReport.AllObjects.AddObjects(AObjectList, False, False); end; FReport.Execute; FReport.Free; end; { TDMFileInfoGroup } destructor TDMFileInfoGroup.Destroy; begin FreeAndNil(FDocumentTypes); inherited; end; procedure TDMFileInfoGroup.DoAfterCopy; begin inherited; end; function TDMFileInfoGroup.GetDocumentTypes: TDocumentTypes; begin if not Assigned(FDocumentTypes) then begin FDocumentTypes := TDocumentTypes.Create; FDocumentTypes.Poster := nil; FDocumentTypes.OwnsObjects := false; end; Result := FDocumentTypes; end; procedure TDMFileInfoGroup.InitializeInfoGroup; begin inherited; Tag := 'Äîêóìåíòû è ìàòåðèàëû'; SourceBaseDir := ''; Place := 'ÐÁÖÃÈ'; TestQuery := 'select m.vch_location, rf_trim(rf_strreplace(' + '''' + ':DOC_TYPE_NAME ' + '''' + '||w.vch_well_num||' + '''' + ' - ' + '''' + '||a.vch_area_name,' + '''' + '(-îå)' + '''' + ',' + '''' + '''' + '))||' + '''' + DefaultExt + '''' + 'from tbl_material m, tbl_material_binding mb, tbl_well w, tbl_area_dict a ' + 'where m.material_type_id in (:MATERIAL_TYPES_ID) and m.material_id = mb.material_id and mb.object_bind_type_id = 1 ' + 'and w.area_id = a.area_id and mb.object_bind_id = w.well_uin ' + 'and mb.object_bind_id = %s'; end; procedure TDMFileInfoGroup.InternalRetrieveObjectInfo(AObject: TIDObject; ADestinationPath: string = ''; AObjectList: TIDObjects = nil); begin inherited; end; function TDMFileInfoGroup.PrepareTestQuery: string; begin Result := inherited PrepareTestQuery; Result := StringReplace(Result, ':DOC_TYPE_NAME', DocTypeName, [rfReplaceAll]); Result := StringReplace(Result, ':MATERIAL_TYPES_ID', DocumentTypes.IDList(','), [rfReplaceAll]); end; { TCoreDescriptionFileInfoGroup } procedure TCoreDescriptionFileInfoGroup.InitializeInfoGroup; begin DefaultExt := '.doc'; inherited; Name := 'Îïèñàíèå êåðíà'; Tag := 'Îïèñàíèå êåðíà'; Place := 'Äîêóìåíòû è ìàòåðèàëû'; DocTypeName := 'Îïèñàíèå êåðíà'; DocumentTypes.Add(TMainFacade.GetInstance.DocumentTypes.ItemsByID[19], False, False); DocumentTypes.Add(TMainFacade.GetInstance.DocumentTypes.ItemsByID[39], False, False); DocumentTypes.Add(TMainFacade.GetInstance.DocumentTypes.ItemsByID[57], False, False); DocumentTypes.Add(TMainFacade.GetInstance.DocumentTypes.ItemsByID[58], False, False); end; { TInclinometrFileInfoGroup } procedure TInclinometrFileInfoGroup.InitializeInfoGroup; begin inherited; Name := 'Äàííûå èíêëèíîìåòðèè'; Tag := 'Äàííûå èíêëèíîìåòðèè'; Place := 'Äîêóìåíòû è ìàòåðèàëû'; DefaultExt := '.jpg'; TestQuery := 'select m.vch_location, rf_trim(rf_strreplace(' + 'mt.vch_material_type_name||' + '''' + ' ' + '''' + '||w.vch_well_num||' + '''' + ' - ' + '''' + '||a.vch_area_name,' + '''' + '(-îå)' + '''' + ',' + '''' + '''' + '))||' + '''' + DefaultExt + '''' + ',' + 'm.vch_location ' + 'from tbl_material m, tbl_material_binding mb, tbl_well w, tbl_area_dict a, tbl_material_type mt ' + 'where m.material_type_id in (:MATERIAL_TYPES_ID) and m.material_id = mb.material_id and mb.object_bind_type_id = 1 ' + 'and w.area_id = a.area_id and mb.object_bind_id = w.well_uin ' + 'and m.Material_type_id = mt.Material_Type_Id ' + 'and mb.object_bind_id = %s'; DocTypeName := 'Äàííûå èíêëèíîìåòðèè'; DocumentTypes.Add(TMainFacade.GetInstance.DocumentTypes.ItemsByID[60], False, False); DocumentTypes.Add(TMainFacade.GetInstance.DocumentTypes.ItemsByID[61], False, False); DocumentTypes.Add(TMainFacade.GetInstance.DocumentTypes.ItemsByID[62], False, False); end; { TGranulometryReportInfoGroup } procedure TGranulometryReportInfoGroup.InitializeInfoGroup; begin inherited; TestQuery := 'select * from tbl_dnr_research d, tbl_rock_sample rs, tbl_slotting s where d.rock_sample_uin = rs.rock_sample_uin and s.slotting_uin = rs.slotting_uin and d.research_id >= 300 and d.research_id < 400 and s.Well_UIN = %s'; Name := 'Ãðàíóëîìåòðè÷åñêèé ñîñòàâ ïîðîä'; Tag := 'Ïåòðîôèçèêà'; Place := 'ÐÁÖÃÈ'; ReportClass := TGranulometryReport; end; { TCentrifugingReportInfoGroup } procedure TCentrifugingReportInfoGroup.InitializeInfoGroup; begin inherited; TestQuery := 'select * from tbl_dnr_research d, tbl_rock_sample rs, tbl_slotting s where d.rock_sample_uin = rs.rock_sample_uin and s.slotting_uin = rs.slotting_uin and d.research_id >= 200 and d.research_id < 300 and s.Well_UIN = %s'; Name := 'Öåíòðèôóãèðîâàíèå'; Tag := 'Ïåòðîôèçèêà'; Place := 'ÐÁÖÃÈ'; ReportClass := TCentrifugingReport; end; { TDMPetrofisicsFileInfoGroup } function TDMPetrofisicsFileInfoGroup.GetUserFolderName: string; begin Result := Tag; end; procedure TDMPetrofisicsFileInfoGroup.InitializeInfoGroup; begin inherited; Name := 'Ïåòðîôèçè÷åñêèå èññëåäîâàíèÿ ïðîøëûõ ëåò'; Tag := 'Ïåòðîôèçèêà'; Place := 'Äîêóìåíòû è ìàòåðèàëû'; DefaultExt := '.xls'; TestQuery := 'select m.vch_location, rf_trim(rf_strreplace(' + 'mt.vch_material_type_name||' + '''' + ' ' + '''' + '||w.vch_well_num||' + '''' + ' - ' + '''' + '||a.vch_area_name,' + '''' + '(-îå)' + '''' + ',' + '''' + '''' + '))||' + '''' + DefaultExt + '''' + ',' + 'm.vch_location ' + 'from tbl_material m, tbl_material_binding mb, tbl_well w, tbl_area_dict a, tbl_material_type mt ' + 'where m.material_type_id in (:MATERIAL_TYPES_ID) and m.material_id = mb.material_id and mb.object_bind_type_id = 1 ' + 'and w.area_id = a.area_id and mb.object_bind_id = w.well_uin ' + 'and m.Material_type_id = mt.Material_Type_Id ' + 'and mb.object_bind_id = %s'; DocTypeName := 'Ïåòðîôèçè÷åñêèå èññëåäîâàíèÿ ïðîøëûõ ëåò'; DocumentTypes.Add(TMainFacade.GetInstance.DocumentTypes.ItemsByID[32], False, False); DocumentTypes.Add(TMainFacade.GetInstance.DocumentTypes.ItemsByID[63], False, False); DocumentTypes.Add(TMainFacade.GetInstance.DocumentTypes.ItemsByID[64], False, False); DocumentTypes.Add(TMainFacade.GetInstance.DocumentTypes.ItemsByID[65], False, False); end; { TStLasFileInfoGroup } procedure TStLasFileInfoGroup.InitializeInfoGroup; begin inherited; TestQuery := 'select distinct lf.vch_filename, lf.vch_old_filename from tbl_las_file lf, tbl_las_curve lc, tbl_curve_dict cc where cc.curve_id = lc.curve_id and lf.las_file_uin = lc.las_file_uin and cc.curve_category_id in (5,9,10,17,18,19) and lf.well_uin = %s'; Name := 'Ñòàíäàðòíûé êàðîòàæ'; CropCurves := True; Encoding := encAnsi; CurvesToLeave.Add('DEPT'); CurvesToLeave.Add('DEPTH'); CurvesToLeave.Add('1ÏÐ'); CurvesToLeave.Add('2ÏÐ'); CurvesToLeave.Add('A04M01N'); CurvesToLeave.Add('A05M8N'); CurvesToLeave.Add('A1M01N'); CurvesToLeave.Add('A1M05N'); CurvesToLeave.Add('A2M05N'); CurvesToLeave.Add('A4M05N'); CurvesToLeave.Add('A8M01N'); CurvesToLeave.Add('A8M10N'); CurvesToLeave.Add('A8M1N'); CurvesToLeave.Add('BS'); CurvesToLeave.Add('CAL'); CurvesToLeave.Add('CAL1'); CurvesToLeave.Add('CAL2'); CurvesToLeave.Add('CALI'); CurvesToLeave.Add('DS'); CurvesToLeave.Add('DS1'); CurvesToLeave.Add('DS2'); CurvesToLeave.Add('DS_m'); CurvesToLeave.Add('DSn'); CurvesToLeave.Add('Dn'); CurvesToLeave.Add('Dn_m'); CurvesToLeave.Add('EL07'); CurvesToLeave.Add('EN20'); CurvesToLeave.Add('GZ'); CurvesToLeave.Add('GZ1'); CurvesToLeave.Add('GZ2'); CurvesToLeave.Add('GZ3'); CurvesToLeave.Add('GZ4'); CurvesToLeave.Add('GZ5'); CurvesToLeave.Add('GZ6'); CurvesToLeave.Add('GZK'); CurvesToLeave.Add('KC4'); CurvesToLeave.Add('LES1'); CurvesToLeave.Add('N05M2A'); CurvesToLeave.Add('N11.0M0.5A'); CurvesToLeave.Add('N11.0Ì0,5À'); CurvesToLeave.Add('N11M05A'); CurvesToLeave.Add('N6M05A'); CurvesToLeave.Add('PR1'); CurvesToLeave.Add('PR2'); CurvesToLeave.Add('PS'); CurvesToLeave.Add('PZ'); CurvesToLeave.Add('PZ1'); CurvesToLeave.Add('PZ3'); CurvesToLeave.Add('PZ5'); CurvesToLeave.Add('PZ6'); CurvesToLeave.Add('R1ñêâ'); CurvesToLeave.Add('R2ñêâ'); CurvesToLeave.Add('R3ñêâ'); CurvesToLeave.Add('R4ñêâ'); CurvesToLeave.Add('Rñêâ1'); CurvesToLeave.Add('Rñêâ2'); CurvesToLeave.Add('Rñêâ3'); CurvesToLeave.Add('Rñêâ4'); CurvesToLeave.Add('SP'); CurvesToLeave.Add('SPèñõ'); CurvesToLeave.Add('pz'); CurvesToLeave.Add('ÃÇ'); CurvesToLeave.Add('ÄÑ'); CurvesToLeave.Add('ÄÑ ñâ1'); CurvesToLeave.Add('ÄÑ ñâ2'); CurvesToLeave.Add('ÄÑ ñâ3'); CurvesToLeave.Add('ÄÑ1'); CurvesToLeave.Add('ÄÑ2'); CurvesToLeave.Add('ÄÑ3'); CurvesToLeave.Add('ÄÑ_1'); CurvesToLeave.Add('ÄÑ_2'); CurvesToLeave.Add('ÄÑÍ'); CurvesToLeave.Add('ÄÑí'); CurvesToLeave.Add('ÄÑí ñâ1'); CurvesToLeave.Add('ÄÑí ñâ2'); CurvesToLeave.Add('ÄÑí1'); CurvesToLeave.Add('ÄÑí2'); CurvesToLeave.Add('ÄÑíîì'); CurvesToLeave.Add('Äñ1'); CurvesToLeave.Add('Äñ2'); CurvesToLeave.Add('ÊÀÂ'); CurvesToLeave.Add('ÊÂ'); CurvesToLeave.Add('ÊÂ1'); CurvesToLeave.Add('ÊÂ2'); CurvesToLeave.Add('ÊÂ3'); CurvesToLeave.Add('ÊÑ1'); CurvesToLeave.Add('ÊÑ2'); CurvesToLeave.Add('ÊÑ2Âð1'); CurvesToLeave.Add('ÊÑ2Âð2'); CurvesToLeave.Add('ÊÑ2Âð3'); CurvesToLeave.Add('ÊÑ3'); CurvesToLeave.Add('ÊÑ3Âð1'); CurvesToLeave.Add('ÊÑ3Âð2'); CurvesToLeave.Add('ÊÑ3Âð3'); CurvesToLeave.Add('ÊÑ3Âð4'); CurvesToLeave.Add('ÊÑ4'); CurvesToLeave.Add('ÊÑ4_1'); CurvesToLeave.Add('ÊÑ5'); CurvesToLeave.Add('ÊÑ5 ñâ1'); CurvesToLeave.Add('ÊÑ5 ñâ2'); CurvesToLeave.Add('ÊÑ5 ñâ3'); CurvesToLeave.Add('ÊÑ6'); CurvesToLeave.Add('ÊÑ7'); CurvesToLeave.Add('ÊÑ8'); CurvesToLeave.Add('ÊÑ8ê'); CurvesToLeave.Add('ÊÑ?'); CurvesToLeave.Add('ÏÇ'); CurvesToLeave.Add('ÏÇ ñâ1'); CurvesToLeave.Add('ÏÇ ñâ2'); CurvesToLeave.Add('ÏÇ ñâ3'); CurvesToLeave.Add('ÏÇ1'); CurvesToLeave.Add('ÏÇ2'); CurvesToLeave.Add('ÏÐ1'); CurvesToLeave.Add('ÏÐ2'); CurvesToLeave.Add('ÏÑ'); CurvesToLeave.Add('ÏÑ ñâ1'); CurvesToLeave.Add('ÏÑ ñâ2'); CurvesToLeave.Add('ÏÑ ñâ3'); CurvesToLeave.Add('ÏÑ1'); CurvesToLeave.Add('ÏÑñï'); Replacements := TLasReplacements.Create; ////2-------- ýòî äëÿ òàêîãî ñëó÷àÿ: WeLL. WELL:5----------------// { Replacements.AddReplacement('~Well', 'WELL', ' WELL:2', '2_Saluk: '); Replacements.AddReplacement('~Well', 'FLD', 'FIELD:Ñàëþêèíñêàÿ (-îå)', ' : '); } Replacements.AddReplacement('~Well', 'WELL', ' 91', '91_Yareyag'); Replacements.AddReplacement('~Well', 'FLD', 'ßðåéÿãèíñêàÿ', ' '); Replacements.AddReplacement('~Curve','À','À','A'); Replacements.AddReplacement('~Curve','Á','Á','B'); Replacements.AddReplacement('~Curve','Â','Â','V'); Replacements.AddReplacement('~Curve','Ã','Ã','G'); Replacements.AddReplacement('~Curve','Ä','Ä','D'); Replacements.AddReplacement('~Curve','Å','Å','E'); Replacements.AddReplacement('~Curve','Æ','Æ','J'); Replacements.AddReplacement('~Curve','Ç','Ç','Z'); Replacements.AddReplacement('~Curve','È','È','I'); Replacements.AddReplacement('~Curve','Ê','Ê','K'); Replacements.AddReplacement('~Curve','Ë','Ë','L'); Replacements.AddReplacement('~Curve','Ì','Ì','M'); Replacements.AddReplacement('~Curve','Í','Í','N'); Replacements.AddReplacement('~Curve','Î','Î','O'); Replacements.AddReplacement('~Curve','Ï','Ï','P'); Replacements.AddReplacement('~Curve','Ð','Ð','R'); Replacements.AddReplacement('~Curve','Ñ','Ñ','S'); Replacements.AddReplacement('~Curve','Ò','Ò','T'); Replacements.AddReplacement('~Curve','Ó','Ó','U'); Replacements.AddReplacement('~Curve','Ô','Ô','F'); Replacements.AddReplacement('~Curve','Õ','Õ','H'); Replacements.AddReplacement('~Curve','Ö','Ö','C'); Replacements.AddReplacement('~Curve','×','×','Ch'); Replacements.AddReplacement('~Curve','Ø','Ø','Sh'); Replacements.AddReplacement('~Curve','Ù','Ù','Sch'); Replacements.AddReplacement('~Curve','Ý','Ý','A'); Replacements.AddReplacement('~Curve','Þ','Þ','U'); Replacements.AddReplacement('~Curve','ß','ß','Ya'); end; { TAKLasFileInfoGroup } procedure TAKLasFileInfoGroup.InitializeInfoGroup; begin inherited; TestQuery := 'select distinct lf.vch_filename, lf.vch_old_filename from tbl_las_file lf, tbl_las_curve lc, tbl_curve_dict cc where cc.curve_id = lc.curve_id and lf.las_file_uin = lc.las_file_uin and cc.curve_category_id in (2) and lf.well_uin = %s'; Name := 'Àêóñòè÷åñêèé êàðîòàæ'; CropCurves := True; CurvesToLeave.Add('DEPT'); CurvesToLeave.Add('DEPTH'); CurvesToLeave.Add('ÀÊÄÒ'); CurvesToLeave.Add('ÀÊÒ1'); CurvesToLeave.Add('ÀÊÒ2'); CurvesToLeave.Add('ÀËÔ'); CurvesToLeave.Add('À1'); CurvesToLeave.Add('À2'); CurvesToLeave.Add('ÀÊÄÒ'); CurvesToLeave.Add('ÀÊÄÒ'); CurvesToLeave.Add('ÀÊÒ1'); CurvesToLeave.Add('ÀÊT2'); CurvesToLeave.Add('A2'); CurvesToLeave.Add('A1'); CurvesToLeave.Add('A1Lí'); CurvesToLeave.Add('A2Lí'); CurvesToLeave.Add('ÀËÔLí'); CurvesToLeave.Add('Ò1Lí'); CurvesToLeave.Add('Ò2Lí'); CurvesToLeave.Add('ÄÒLí'); CurvesToLeave.Add('A1s'); CurvesToLeave.Add('A1s'); CurvesToLeave.Add('A2s'); CurvesToLeave.Add('ÀËÔsí'); CurvesToLeave.Add('A1sí'); CurvesToLeave.Add('A2sí'); CurvesToLeave.Add('ÄÒsí'); CurvesToLeave.Add('Ò1sí'); CurvesToLeave.Add('Ò2sí'); CurvesToLeave.Add('A1pâ'); CurvesToLeave.Add('A2pâ'); CurvesToLeave.Add('ÀËÔðâ'); CurvesToLeave.Add('ÄÒðâ'); CurvesToLeave.Add('Ò1ðâ'); CurvesToLeave.Add('Ò2ðâ'); CurvesToLeave.Add('Ddol'); CurvesToLeave.Add('DT'); CurvesToLeave.Add('ÀÊÄÒ'); CurvesToLeave.Add('ÄÒ'); CurvesToLeave.Add('Ò1ðâ'); CurvesToLeave.Add('BAT1'); CurvesToLeave.Add('BAT2'); CurvesToLeave.Add('DTCO'); CurvesToLeave.Add('ÀÊÄÒ'); CurvesToLeave.Add('DTL'); CurvesToLeave.Add('DTLM'); CurvesToLeave.Add('DTP'); CurvesToLeave.Add('DTS'); CurvesToLeave.Add('ÀËÔ2'); CurvesToLeave.Add('ÀËÔ1'); CurvesToLeave.Add('ÀÊT1'); CurvesToLeave.Add('DTP1'); CurvesToLeave.Add('T1'); CurvesToLeave.Add('T2'); CurvesToLeave.Add('ÀÊ'); CurvesToLeave.Add('ÀÊÄÒ'); CurvesToLeave.Add('AZT'); CurvesToLeave.Add('DÒ'); CurvesToLeave.Add('ÀÊ'); CurvesToLeave.Add('DT'); CurvesToLeave.Add('ALFA'); Replacements := TLasReplacements.Create; end; { TLasReplacements } constructor TLasReplacements.Create; begin inherited; AddReplacement('~Curve','','KC4','GZ4'); AddReplacement('~Curve','','NGK','NGR'); AddReplacement('~Curve','','ÍÃÊ','NGR'); AddReplacement('~Curve','','PS','SP'); AddReplacement('~Curve','','ÃÃÊÏ','GGRp'); AddReplacement('~Curve','','ÃÃÊï','GGRp'); AddReplacement('~Curve','','ÃÊè','GRi'); AddReplacement('~Curve','','ÃÊ','GR'); AddReplacement('~Curve','','ÄÑí1','Dn '); AddReplacement('~Curve','','ÄÑí2','Dn '); AddReplacement('~Curve','','ÄÑí','Dn '); AddReplacement('~Curve','','ÄÑ','DS'); AddReplacement('~Curve','','ÊÑ4','GZ4'); AddReplacement('~Curve','','ÍÍÊÒ','NNKT'); AddReplacement('~Curve','','ÍÍÒÁ','NNTb'); AddReplacement('~Curve','','ÍÍÒÌ','NNTm'); AddReplacement('~Curve','','ÏÇ','PZ'); AddReplacement('~Curve','','ÏÑ','SP'); AddReplacement('~Curve','','ã/ñì3','g/cm3'); AddReplacement('~Curve','','ìêð/÷àñ','ur/h '); AddReplacement('~Curve','','èìï/ìèí','imp/min'); AddReplacement('~Curve','','ìì','mm'); AddReplacement('~Curve','','Îìì','Omm'); AddReplacement('~Curve','','ó.å.','u.e.'); AddReplacement('~Curve','','óñ.å','u.e. '); AddReplacement('~Curve','','Îìì','Omm'); AddReplacement('~Curve','','ìÂ','mv'); end; { TAllLasFileCopy } procedure TAllLasFileCopyAnsi.InitializeInfoGroup; begin inherited; CropCurves := false; MakeReplacements := false; CropBlocks := false; Encoding := encAnsi; TestQuery := 'select distinct lf.vch_filename, lf.vch_old_filename from tbl_las_file lf, tbl_las_curve lc where lf.las_file_uin = lc.las_file_uin and lf.well_uin = %s'; Name := 'LAS(ANSI)'; end; { TAllLasFileCopyAscii } procedure TAllLasFileCopyAscii.InitializeInfoGroup; begin inherited; CropCurves := false; MakeReplacements := false; CropBlocks := false; Encoding := encAscii; TestQuery := 'select distinct lf.vch_filename, lf.vch_old_filename from tbl_las_file lf, tbl_las_curve lc where lf.las_file_uin = lc.las_file_uin and lf.well_uin = %s'; Name := 'LAS(ASCII)'; end; { TStandardSubdivisionReport } procedure TStandardSubdivisionReportInfoGroup.InitializeInfoGroup; begin inherited; Name := 'Ñòðàòèãðàôè÷åñêèå ðàçáèâêè'; Tag := 'Ñòðàòèãðàôèÿ'; Place := 'ÐÁÖÃÈ'; TestQuery := 'select * from tbl_subdivision_component sc, tbl_Subdivision s where s.subdivision_id = sc.subdivision_id and s.well_uin in (%s)'; IsSingle := True; ReportClass := TStandardSubdivisionReport; end; { TSchlifDescriptionFileInfoGroup } procedure TSchlifDescriptionFileInfoGroup.InitializeInfoGroup; begin DefaultExt := '.doc'; inherited; Name := 'Îïèñàíèå øëèôîâ'; Tag := 'Îïèñàíèå øëèôîâ'; Place := 'Äîêóìåíòû è ìàòåðèàëû'; DocTypeName := 'Îïèñàíèå øëèôîâ'; DocumentTypes.Add(TMainFacade.GetInstance.DocumentTypes.ItemsByID[38], False, False); DocumentTypes.Add(TMainFacade.GetInstance.DocumentTypes.ItemsByID[20], False, False); DocumentTypes.Add(TMainFacade.GetInstance.DocumentTypes.ItemsByID[48], False, False); DocumentTypes.Add(TMainFacade.GetInstance.DocumentTypes.ItemsByID[51], False, False); end; { TSchlamDescriptionFileInfoGroup } procedure TSchlamDescriptionFileInfoGroup.InitializeInfoGroup; begin inherited; DefaultExt := '.doc'; inherited; Name := 'Îïèñàíèå øëàìà'; Tag := 'Îïèñàíèå øëàìà'; Place := 'Îïèñàíèå øëàìà'; DocTypeName := 'Îïèñàíèå êåðíà'; DocumentTypes.Add(TMainFacade.GetInstance.DocumentTypes.ItemsByID[34], False, False); end; end.
(*********************************************************************) (* Programmname : CODING.PAS V1.0 *) (* Programmautor : Michael Rippl *) (* Compiler : Quick Pascal V1.0 *) (* Inhalt : Kodierungsprogramm fr Venus V2.1 *) (* Bemerkung : Dieses Programm tr„gt auch die Seriennummer ein *) (* Letzte Žnderung : 22-JUL-1991 *) (*********************************************************************) PROGRAM Coding; (*$I- Kein I/O Checking *) CONST MemBlock = 65520; (* Gr”áe Speicherblock *) MinMemory = 200000; (* Coding Mindestspeicher *) TYPE VenArray = ARRAY [1..MemBlock] OF BYTE; (* Typ fr Speicherbl”cke *) VAR Source, (* Quelldatei *) Target : FILE; (* Zieldatei *) SerialNumber : LONGINT; (* Seriennummer von Venus *) VenPart1, (* 65520 Bytes von Venus *) VenPart2, (* 131040 Bytes von Venus *) VenPart3 : ^VenArray; (* Rest Bytes von Venus *) Result : WORD; (* Bytes Resultat Lesen *) (* Diese Funktion nimmt alle Initialisierungen vor *) FUNCTION Initialize : BOOLEAN; VAR Code : INTEGER; (* Code Zahlenumwandlung *) BEGIN Initialize := TRUE; (* Dient als Vorgabewert *) IF MaxAvail < MinMemory THEN (* Zu wenig Speicher *) BEGIN WriteLn('Error - Not Enough Memory'); Initialize := FALSE; END ELSE IF ParamCount <> 3 THEN (* Parameterfehler *) BEGIN WriteLn('Error - Illegal Number Of Parameters'); Initialize := FALSE; END ELSE IF ParamStr(2) = ParamStr(3) THEN (* Dateinamen sind gleich *) BEGIN WriteLn('Error - Source And Target Must Be Different'); Initialize := FALSE; END ELSE (* Anzahl Parameter Ok *) BEGIN Val(ParamStr(1), SerialNumber, Code); (* Seriennummer als Zahl *) Assign(Source, ParamStr(2)); (* Name der Quelldatei *) Assign(Target, ParamStr(3)); (* Name der Zieldatei *) IF Code <> 0 THEN (* Fehler Seriennummer *) BEGIN WriteLn('Error - Illegal Serial Number'); Initialize := FALSE; END ELSE (* Seriennummer ist Ok *) BEGIN Reset(Source, 1); (* Quelldatei ”ffnen *) IF IOResult <> 0 THEN (* Fehler beim Datei”ffnen *) BEGIN WriteLn('Error - Cannot Open Source File'); Initialize := FALSE; END ELSE (* Quelldatei ”ffnen Ok *) BEGIN ReWrite(Target, 1); (* Zieldatei ”ffnen *) IF IOResult <> 0 THEN (* Fehler beim Datei”ffnen *) BEGIN WriteLn('Error - Cannot Open Target File'); Close(Source); Initialize := FALSE; END; END; END; END; END; (* Initialize *) (* Diese Prozedur liest die Quelldatei Venus.Exe in den Speicher *) PROCEDURE ReadFile; BEGIN WriteLn('Reading File ...'); BlockRead(Source, VenPart1^, MemBlock, Result); BlockRead(Source, VenPart2^, MemBlock, Result); BlockRead(Source, VenPart3^, MemBlock, Result); END; (* ReadFile *) (* Diese Prozedur kodiert die Quelldatei Venus.Exe *) PROCEDURE CodeFile; VAR i : WORD; (* Dient als Z„hler *) BEGIN WriteLn('Coding File ...'); FOR i := 1 TO MemBlock DO (* Datei durchgehen *) BEGIN Dec(VenPart1^[i], 3); Dec(VenPart2^[i], 3); Dec(VenPart3^[i], 3); END; END; (* CodeFile *) (* Diese Prozedur tr„gt die Seriennummer in die Datei ein *) PROCEDURE EnterSerialNumber; VAR pNumber : ^LONGINT; (* Zeiger auf Seriennummer *) SerialIndex : WORD; (* Index fr Seriennummer *) BEGIN SerialIndex := Result - 3; (* Viermal Wert 28 suchen *) WHILE (VenPart3^[SerialIndex] <> 28) OR (* Datei wird durchsucht *) (VenPart3^[SerialIndex + 1] <> 28) OR (VenPart3^[SerialIndex + 2] <> 28) OR (VenPart3^[SerialIndex + 3] <> 28) DO Dec(SerialIndex); Inc(SerialIndex, 7); (* Zeigt auf Seriennummer *) pNumber := Addr(VenPart3^[SerialIndex]); pNumber^ := SerialNumber - 2; END; (* EnterSerialNumber *) (* Diese Prozedur schreibt die Quelldatei Venus.Exe *) PROCEDURE WriteFile; VAR Dummy : WORD; (* Dient als Platzhalter *) BEGIN WriteLn('Writing File ...'); BlockWrite(Target, VenPart1^, MemBlock, Dummy); BlockWrite(Target, VenPart2^, MemBlock, Dummy); BlockWrite(Target, VenPart3^, Result, Dummy); END; (* WriteFile *) BEGIN (* Hauptprogramm *) IF Initialize THEN (* Initialisierung ist Ok *) BEGIN GetMem(VenPart1, MemBlock); (* Speicher Venus Teil 1 *) GetMem(VenPart2, MemBlock); (* Speicher Venus Teil 2 *) GetMem(VenPart3, MemBlock); (* Speicher Venus Teil 3 *) ReadFile; (* Venus-Datei einlesen *) EnterSerialNumber; (* Seriennummer eintragen *) CodeFile; (* Datei wird kodiert *) WriteFile; (* Venus-Datei schreiben *) Close(Source); (* Quelldatei schlieáen *) Close(Target); (* Zieldatei schlieáen *) FreeMem(VenPart1, MemBlock); (* Speicher freigeben *) FreeMem(VenPart2, MemBlock); FreeMem(VenPart3, MemBlock); WriteLn('Working Done !'); END; END. (* Coding *)
unit Aurelius.Sql.MSSQL2014; interface uses Aurelius.Sql.Register, Aurelius.Sql.AnsiSqlGenerator, Aurelius.Sql.Metadata, Aurelius.Sql.Interfaces, Aurelius.Sql.Commands, Aurelius.Sql.MSSQL; type TMSSQL2014SQLGenerator = class(TMSSQLSQLGenerator) protected function GenerateInsert(Command: TInsertCommand): string; override; function GenerateUpdate(Command: TUpdateCommand): string; override; function GenerateDelete(Command: TDeleteCommand): string; override; function GenerateGetNextSequenceValue(Command: TGetNextSequenceValueCommand): string; override; function GenerateCreateSequence(Sequence: TSequenceMetadata): string; override; function GenerateDropSequence(Sequence: TSequenceMetadata): string; override; function GenerateDropField(Column: TColumnMetadata): string; override; function GetSupportedFeatures: TDBFeatures; override; end; implementation uses Variants, SysUtils, Aurelius.Sql.gmRegister; function TMSSQL2014SQLGenerator.GenerateInsert(Command: TInsertCommand): string; begin Result := inherited GenerateInsert(Command); Result := 'SET NOCOUNT ON; ' + sqlLineBreak +'DECLARE @BinVar varbinary(128);' + sqlLineBreak + Format('SET @BinVar = CAST(''%s'' AS varbinary(128) );', [TgmSQLGeneratorRegister.GuidToString(TgmSQLGeneratorRegister.UserId)]) + sqlLineBreak +'SET CONTEXT_INFO @BinVar;' + sqlLineBreak + Result; end; function TMSSQL2014SQLGenerator.GenerateUpdate(Command: TUpdateCommand): string; begin Result := inherited GenerateUpdate(Command); Result := 'SET NOCOUNT ON; ' + sqlLineBreak +'DECLARE @BinVar varbinary(128);' + sqlLineBreak + Format('SET @BinVar = CAST(''%s'' AS varbinary(128) );', [TgmSQLGeneratorRegister.GuidToString(TgmSQLGeneratorRegister.UserId)]) + sqlLineBreak +'SET CONTEXT_INFO @BinVar;' + sqlLineBreak + Result; end; function TMSSQL2014SQLGenerator.GenerateDelete(Command: TDeleteCommand): string; begin Result := inherited GenerateDelete(Command); Result := 'SET NOCOUNT ON; ' + sqlLineBreak +'DECLARE @BinVar varbinary(128);' + sqlLineBreak + Format('SET @BinVar = CAST(''%s'' AS varbinary(128) );', [TgmSQLGeneratorRegister.GuidToString(TgmSQLGeneratorRegister.UserId)]) + sqlLineBreak +'SET CONTEXT_INFO @BinVar;' + sqlLineBreak + Result; end; function TMSSQL2014SQLGenerator.GenerateCreateSequence(Sequence: TSequenceMetadata): string; begin Result := Format('CREATE SEQUENCE %s AS INTEGER START WITH %s INCREMENT BY %s MAXVALUE 9999999999;', [Sequence.Name, IntToStr(Sequence.InitialValue), IntToStr(Sequence.Increment)]); end; function TMSSQL2014SQLGenerator.GenerateDropField(Column: TColumnMetadata): string; begin result := InternalGenerateDropField(Column, True); end; function TMSSQL2014SQLGenerator.GenerateDropSequence(Sequence: TSequenceMetadata): string; begin Result := Format('DROP SEQUENCE %s;', [Sequence.Name]); end; function TMSSQL2014SQLGenerator.GenerateGetNextSequenceValue(Command: TGetNextSequenceValueCommand): string; begin Result := Format('SELECT CAST(NEXT VALUE FOR %s AS INTEGER);', [Command.SequenceName]); end; function TMSSQL2014SQLGenerator.GetSupportedFeatures: TDBFeatures; begin Result := AllDBFeatures {- [TDBFeature.Sequences]}; end; initialization TSQLGeneratorRegister.GetInstance.RegisterGenerator(TMSSQL2014SQLGenerator.Create); end.
unit Entities; interface uses Aurelius.Mapping.Attributes; type [Entity, Automapping] TCountry = class private FId: Integer; FName: string; public property Id: Integer read FId write FId; property Name: string read FName write FName; end; [Entity, Automapping] TCustomer = class private FId: Integer; FName: string; FCountry: TCountry; public property Id: Integer read FId write FId; property Name: string read FName write FName; property Country: TCountry read FCountry write FCountry; end; implementation initialization RegisterEntity(TCustomer); RegisterEntity(TCountry); end.
unit UDouble; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, UEmbedForm, StdCtrls, tc; type TFDouble = class(TEmbedForm) Edit1: TEdit; procedure Edit1KeyPress(Sender: TObject; var Key: Char); procedure FormCreate(Sender: TObject); private { Private declarations } public function GetNumber : massa; procedure SetNumber(value : massa); property Number : massa read GetNumber write SetNumber; end; var FDouble: TFDouble; implementation {$R *.DFM} procedure TFDouble.Edit1KeyPress(Sender: TObject; var Key: Char); begin if not( (Key in ['0'..'9']) or (key = #8) or (key = ',') ) then key := #27; end; procedure TFDouble.FormCreate(Sender: TObject); begin inherited; Number := 1; end; function TFDouble.GetNumber: massa; begin try result := StrToFloat(Edit1.Text); except Number := 0; result := 0; end; end; procedure TFDouble.SetNumber(value: massa); begin Edit1.Text := FloatToStr(value); end; end.
unit PCPanel; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, StdCtrls, Forms, Dialogs, ExtCtrls, emptypanel, ThreadedPanel, ThreadedEventPanel; type TPCPanel = class(TThreadedEventPanel) private { Private declarations } protected { Protected declarations } fImage: TImage; fPicture: TPicture; fCaption: TLabel; fCaptionString: string; procedure SetCaption(Value: string); procedure SetPicture(value: TPicture); public { Public declarations } constructor Create(AOwner: TComponent); override; destructor Destroy; override; published { Published declarations } property Picture:TPicture read fPicture write SetPicture; property Caption:String read fCaptionstring write SetCaption; end; implementation constructor TPCPanel.Create(AOwner: TComponent); begin Inherited Create(AOwner); fCaption:=TLabel.Create(Self); fCaption.Parent:=Self; fCaption.Align:=albottom; fCaption.Caption:='Caption'; fCaption.Show; fPicture:=TPicture.Create; fImage:=TImage.Create(self); fImage.Parent:=self; fImage.Align:=alclient; fImage.Stretch:=True; fImage.Show; end; destructor TPCPanel.Destroy; begin fImage.Free; fPicture.Free; fCaption.Free; Inherited Destroy; end; procedure TPCPanel.SetCaption(Value: string); begin fCaptionString:=value; fCaption.Caption:=value; end; procedure TPCPanel.SetPicture(Value: TPicture); begin fPicture.Assign(Value); fImage.Picture.Assign(fPicture); end; end.