text stringlengths 14 6.51M |
|---|
unit MenuUnit;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Data.DB, Data.Win.ADODB, Vcl.Grids,
Vcl.DBGrids, Vcl.ExtCtrls, Vcl.StdCtrls, Vcl.Imaging.jpeg, PNGImage, INIFiles, ShlObj;
type
TNewDisk = record
Title:Cardinal;
Title_Text:string;
Video:Cardinal;
Video_Text:string;
Disk:Cardinal;
Disk_Text:string;
end;
THistory = class(TStringList)
procedure AddLine(Line: string);
procedure AddList(List: TStrings);
procedure Load;
procedure Save;
public
FileName:string;
end;
TForm1 = class(TForm)
DB: TADOConnection;
Image1: TImage;
Button1: TButton;
Button2: TButton;
Button3: TButton;
Bevel1: TBevel;
Button4: TButton;
Button5: TButton;
Button6: TButton;
Bevel2: TBevel;
Button7: TButton;
Query: TADOQuery;
Button8: TButton;
procedure Button7Click(Sender: TObject);
procedure Button1Click(Sender: TObject);
procedure Button6Click(Sender: TObject);
procedure Button4Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button5Click(Sender: TObject);
procedure Button8Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
function AppData:string;
procedure Backup;
public
procedure AddDisk;
end;
TWindowPosition = record
Left:integer;
Top:Integer;
Width:Integer;
Height:Integer;
Maximize:Boolean;
ReadOnly:boolean;
end;
var
Form1: TForm1;
Canceled:boolean;
NewDisk:TNewDisk;
SQL_History:THistory;
Settings:TINIFile;
const
PF='\СтД\DVD_Library\';
implementation
{$R *.dfm}
uses SearchUnit, AdminUnit, AddTitle, AddVideo, AddDisk, PersUnit, ReportsUnit,
EditPersonsUnit, HistoryUnit;
procedure TForm1.AddDisk;
var
LastPrinted:integer;
TotalDisks:integer;
Delta:integer;
begin
if AddTitleForm.AddDisk_AddTitle then
if AddVideoForm.AddDisk_AddVideo then
if AddDiskForm.AddDisk_AddDisk then
begin
ShowMessage('Диск добавлен.');
LastPrinted:=Settings.ReadInteger('Print','Last-printed-No',-1);
Delta:=Settings.ReadInteger('Print','N-disks-to-print',-1);
with Query do
begin
SQL.Clear;
SQL.Add('SELECT COUNT([Номер в каталоге]) AS NDisk');
SQL.Add('FROM Список_дисков;');
Open;
TotalDisks:=FieldByName('NDisk').AsInteger;
end;
if LastPrinted+Delta<=TotalDisks then
begin
ShowMessage('Вы добавили уже '+IntToStr(TotalDisks-LastPrinted)+
' дисков с момента последней распечатки списков.'#13#10'Рекомендуем Вам распечатать списки.');
end;
end;
end;
function TForm1.AppData:string;
var
PItemID : PItemIDList;
ansiSbuf : array[0..MAX_PATH] of char;
begin
SHGetSpecialFolderLocation( Form1.Handle, CSIDL_APPDATA, PItemID );
SHGetPathFromIDList( PItemID, @ansiSbuf[0] );
AppData := ansiSbuf;
end;
procedure TForm1.Backup;
var
ST:TSystemTime;
OldFile, NewFile:string;
begin
DateTimeToSystemTime(Now,ST);
OldFile:=Settings.ReadString('DataBase','File','ERROR!!!');
NewFile:=Settings.ReadString('Backup','Foldler','ERROR!!!')+
'Backup_DVD_Lib_'+IntToStr(ST.wYear)+'-'+IntToStr(ST.wMonth)+'-'+IntToStr(ST.wDay)+'.mdb';
CopyFile(PWideChar(WideString(OldFile)), PWideChar(WideString(NewFile)), true);
Settings.WriteDate('Backup','Last',Date);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
SearchForm.SearchShow
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
Persons.ShowPersons;
end;
procedure TForm1.Button3Click(Sender: TObject);
begin
History.ShowHistory;
end;
procedure TForm1.Button4Click(Sender: TObject);
begin
AddDisk;
end;
procedure TForm1.Button5Click(Sender: TObject);
begin
Reports.ShowModal;
end;
procedure TForm1.Button6Click(Sender: TObject);
begin
AdminForm.Show;
end;
procedure TForm1.Button7Click(Sender: TObject);
begin
Application.Terminate;
end;
procedure TForm1.Button8Click(Sender: TObject);
begin
EditPersons.ShowEditPersona;
end;
procedure TForm1.FormCreate(Sender: TObject);
var
ST:TTimeStamp;
DaysL, DaysN:Cardinal;
begin
if DB.Connected then DB.Connected:=false;
SQL_History:=THistory.Create;
SQL_History.FileName:='SQL.log';
SQL_History.Load;
//ShowMessage(AppData+' '+PF+'settings.ini');
if not DirectoryExists(AppData+PF) then
ForceDirectories(AppData+PF);
Settings:=TIniFile.Create(AppData+PF+'settings.ini');
if Settings.ReadString('Backup','Foldler','@NONE@')='@NONE@' then
Settings.WriteString('Backup','Foldler','d:\Dropbox\Театр\DB\Backup\');
if Settings.ReadString('Backup','Last','@NONE@')='@NONE@' then
Backup;
ST := DateTimeToTimeStamp(Settings.ReadDate('Backup','Last',StrToDate('06.03.1989')));
DaysL:=ST.Date;
ST := DateTimeToTimeStamp(Date);
DaysN:=ST.Date;
if (DaysL+7)<=DaysN then Backup;
DB.ConnectionString:='Provider=Microsoft.Jet.OLEDB.4.0;User ID=Admin;Data Source='+
Settings.ReadString('DataBase','File','ERROR!!!')+
';Mode=Share Deny None;Jet OLEDB:System database="";Jet OLEDB:Registry Path="";'+
'Jet OLEDB:Database Password="";Jet OLEDB:Engine Type=5;Jet OLEDB:Database Locking Mode=1;'+
'Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Global Bulk Transactions=1;'+
'Jet OLEDB:New Database Password="";Jet OLEDB:Create System Database=True;'+
'Jet OLEDB:Encrypt Database=False;Jet OLEDB:Don''t Copy Locale on Compact=False;'+
'Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:SFP=False;';
DB.Connected:=true;
WS.ReadOnly:=true;
WS.Left:=Settings.ReadInteger('Forms','Search-Left',0);
WS.Top:=Settings.ReadInteger('Forms','Search-Top',0);
WS.Width:=Settings.ReadInteger('Forms','Search-Width',964);
WS.Height:=Settings.ReadInteger('Forms','Search-Height',465);
WS.Maximize:=Settings.ReadBool('Forms','Search-Maximize',false);
end;
{ THistory }
procedure THistory.AddLine(Line: string);
begin
Add('');
Add('/*'+DateTimeToStr(Now)+'*/');
Add(Line);
Save;
end;
procedure THistory.AddList(List: TStrings);
var
i:integer;
begin
Add('');
Add('/*'+DateTimeToStr(Now)+'*/');
for i := 0 to List.Count-1 do
Add(List[i]);
Save;
end;
procedure THistory.Load;
begin
{LoadFromFile(FileName); }
end;
procedure THistory.Save;
begin
{SaveToFile(FileName); }
end;
end.
|
{$ifdef license}
(*
Copyright 2020 ChapmanWorld LLC ( https://chapmanworld.com )
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. 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.
3. Neither the name of the copyright holder 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.
*)
{$endif}
/// <summary>
/// Provides routines for working with memory buffers and streams to
/// memory or file I/O.
/// </summary>
unit cwIO;
{$ifdef fpc}{$mode delphiunicode}{$endif}
interface
uses
cwUnicode
;
type
//-- Imported from unicode
/// <exclude/>
TUnicodeFormat = cwUnicode.TUnicodeFormat;
{$region ' Status codes '}
const
stStreamDoesNotSupportClear = '{3CEF06E2-7F55-4D64-B7ED-0656AC11D7D9} This stream does not support the clear method.';
stCannotEncodeUnknownUnicodeFormat = '{07BABDF7-4855-4DEB-B37B-7B87E2195509} Cannot encode unknown unicode format.';
stIndexOutOfBounds = '{05134522-C428-423A-A656-72C535F5C74C} Index out of bounds.';
{$endregion}
{$region ' IStream'}
type
/// <summary>
/// IStream is an abstract interface from which other stream interfaces
/// are derrived.
/// </summary>
IStream = interface
['{08852882-39D7-4CC1-8E1E-D5F323E47421}']
/// <summary>
/// For streams which support the method, clear will empty all content
/// from the stream and reset the position to zero.
/// For streams which do not support clear, an error is inserted into
/// the log. (lsFatal)
/// </summary>
procedure Clear;
/// <summary>
/// Returns true if the cursor is currently positioned at the end of the
/// stream.
/// </summary>
/// <returns>
/// True if the cursor is currently positioned at the end of the stream,
/// otherwise returns false.
/// </returns>
function getEndOfStream: boolean;
/// <summary>
/// Get the current cursor position within the stream.
/// </summary>
/// <returns>
/// index of the cursor within the stream from zero, in bytes.
/// </returns>
function getPosition: nativeuint;
/// <summary>
/// Set the cursor position within the stream.
/// </summary>
/// <param name="newPosition">
/// The index from zero at which to position the cursor, in bytes.
/// </param>
/// <remarks>
/// Some streams do not support setting the cursor position. In such
/// cases, the cursor position will remain unchanged. You should test
/// getPosition() to confirm that the move was successful.
/// </remarks>
procedure setPosition( const newPosition: nativeuint );
/// <summary>
/// Returns the number of bytes remaining on the stream.
/// </summary>
/// <remarks>
/// Some streams do not support reporting the cursor position, and so,
/// the remaining number of bytes may be unknown. In such cases, this
/// method will return zero.
/// </remarks>
function getRemainingBytes: nativeuint;
/// <summary>
/// Reads an arbritrary number of bytes from the stream. <br />
/// </summary>
/// <param name="p">
/// Pointer to a buffer with sufficient space to store the bytes read
/// from the stream.
/// </param>
/// <param name="Count">
/// The maximum number of bytes to read from the stream (size of the
/// buffer).
/// </param>
/// <returns>
/// The number of bytes actually read from the stream, which may differ
/// from the number requested in the count parameter. See remarks.
/// </returns>
/// <remarks>
/// <para>
/// When reading from streams, a number of conditions may prevent the
/// read operation from returning the number of bytes requested.
/// </para>
/// <para>
/// Examples Include:
/// </para>
/// <list type="bullet">
/// <item>
/// Request is for more bytes than remain in the datasource of
/// the stream. In this case, the remaining data bytes are
/// returned, and the return value of the Read() method will
/// reflect the number of bytes actually returned. <br /><br />
/// </item>
/// <item>
/// The stream does not support read operations. Some streams are
/// unidirectional. If this stream does not support reading
/// operations, the read() method will return zero.
/// </item>
/// </list>
/// </remarks>
function Read( const p: pointer; const Count: nativeuint ): nativeuint;
/// <summary>
/// Writes an arbritrary number of bytes to the stream.
/// </summary>
/// <param name="p">
/// A pointer to a buffer from which bytes will be written onto the
/// stream.
/// </param>
/// <param name="Count">
/// The number of bytes to write onto the stream.
/// </param>
/// <returns>
/// Returns the number of bytes actually written to the stream, which may
/// differ from the number specified in the Count parameter. See remarks.
/// </returns>
/// <remarks>
/// <para>
/// A number of conditions can prevent writing data to a stream, in
/// which case, the number of bytes written may differ from the
/// number specified in the count parameter.
/// </para>
/// <para>
/// Examples include:
/// </para>
/// <list type="bullet">
/// <item>
/// There is insufficient space left in the stream target for
/// additional data. In this case, the maximum amount of data
/// that can be written, will be written, and the return value of
/// the Write() method reflects the number of bytes actually
/// written. <br /><br />
/// </item>
/// <item>
/// The stream does not support writing. Some streams are
/// unidirectional and therefore may not support writing
/// operations. In this case, the Write() method will return
/// zero.
/// </item>
/// </list>
/// </remarks>
function Write( const p: pointer; const Count: nativeuint ): nativeuint;
/// <summary>
/// Copies the contents of another stream to this one.
/// </summary>
/// <param name="Source">
/// The stream to copy data from.
/// </param>
/// <returns>
/// <para>
/// Returns the number of bytes copied from the source stream to this
/// one. A number of conditions could prevent successful copying of
/// one stream to another.
/// </para>
/// <para>
/// Examples include
/// </para>
/// <list type="bullet">
/// <item>
/// The target stream is not writable. In this case, the
/// CopyFrom() method will return zero. <br /><br />
/// </item>
/// <item>
/// The source stream is not readable. In this case the
/// CopyFrom() method will return zero. <br /><br />
/// </item>
/// <item>
/// The target stream has insufficient storage space for the data
/// being copied from the source stream. In this case, the
/// maximum number of bytes that can be copied will be copied,
/// and the return value of the CopyFrom() method will reflect
/// the number of bytes actually copied.
/// </item>
/// </list>
/// </returns>
function CopyFrom( const Source: IStream ): nativeuint;
/// <summary>
/// Get the size of the stream in bytes.
/// </summary>
/// <returns>
/// Returns the number of bytes stored on the stream in bytes.
/// </returns>
function getSize: nativeuint;
/// <summary>
/// Returns the name of the stream.
/// Naming the stream is optional, and if the stream has not been
/// named, this method will return a null string.
/// </summary>
function getName: string;
/// <summary>
/// Optionally, this stream may be given a name.
/// This optional parameter is not used by the stream functionality,
/// but may be useful for labeling streams in mult-stream applications.
/// </summary>
procedure setName( const value: string );
/// <summary>
/// Writes a single byte to the stream.
/// </summary>
procedure WriteByte( const value: uint8 );
/// <summary>
/// Reads a single byte from the stream.
/// </summary>
function ReadByte: uint8;
/// <summary>
/// Writes an array of bytes to the stream.
/// </summary>
procedure WriteBytes( const value: array of uint8 );
//- Pascal only, properties -//
property Name: string read getName write setName;
property Size: nativeuint read getSize;
property Position: nativeuint read getPosition write setPosition;
end;
{$endregion}
{$region ' IUnicodeStream'}
/// <summary>
/// A stream which supports the IUnicodeStream is able to read data from
/// a stream in one unicode format, and translate it on-the-fly into
/// another unicode format.
/// </summary>
IUnicodeStream = interface( IStream )
['{BA3588F0-32A4-4039-A212-389C630BB2E4}']
/// <summary>
/// <para>
/// This method attempts to read the unicode BOM (byte-order-mark) of
/// the specified unicode format, and returns TRUE if the BOM is
/// found or else returns FALSE. <br />
/// Warning, the BOM for UTF16-LE will match when the BOM for UTF32-LE
/// is present, because the first two bytes of the UTF32-LE BOM match
/// those of the UTF-16LE BOM. Similarly the UTF32-BE BOM will match
/// for UTF16-BE. In order to determine the unicode format from the BOM
/// values, these values must be tested in order of length, starting
/// with the highest. i.e. Test of UTF32-LE and only if that fails to
/// match, test for UTF-16LE.
/// The Determine unicode format tests BOM's in order to determine the
/// unicode format from the BOM.
/// </para>
/// <para>
/// If the BOM is found, the stream position is advanced, but if the
/// BOM is not found, the stream position does not change.
/// </para>
/// </summary>
/// <param name="Format">
/// Specifies the unicode format for which a byte-order-mark is expected
/// on the stream.
/// </param>
/// <returns>
/// Returns TRUE if the BOM is discovered on the stream at the current
/// position, otherwise returns FALSE.
/// </returns>
function ReadBOM( const Format: TUnicodeFormat ): boolean;
/// <summary>
/// <para>
/// This method will write the Byte-Order-Mark of the specified
/// unicode text format onto the stream.
/// </para>
/// <para>
/// Formats of unknown and ansi will do nothing as there is no BOM
/// for these formats.
/// </para>
/// </summary>
/// <param name="Format">
/// Format The unicode format to write a BOM for.
/// </param>
procedure WriteBOM( const Format: TUnicodeFormat );
/// <summary>
/// This method looks for a unicode BOM (byte-order-mark), and if one is
/// found, the appropriate unicode format enumeration is returned. <br />
/// If no unicode BOM is found, this function returns utfUnknown and you
/// should default to the most appropriate format. In most cases UTF-8 is
/// a good default option due to it's compatability with ANSI. <br />
/// </summary>
/// <returns>
/// The TdeUnicodeFormat enum which indicates the BOM which was
/// discovered, or else utfUnknown is returned if no appropriate BOM is
/// found.
/// </returns>
function DetermineUnicodeFormat: TUnicodeFormat;
/// <summary>
/// This method writes a character to the stream in the specified
/// unicode format.
/// </summary>
/// <param name="aChar">
/// The character to write to the stream.
/// </param>
/// <param name="Format">
/// The unicode format used to encode the character onto the stream.
/// </param>
procedure WriteChar( const aChar: char; const Format: TUnicodeFormat );
/// <summary>
/// This method reads a single character from the stream using the
/// specified unicode format.
/// </summary>
/// <param name="Format">
/// The unicode format to use to decode the character being read from
/// the stream.
/// </param>
/// <returns>
/// Returns the next character from the unicode encoded stream.
/// </returns>
function ReadChar( const Format: TUnicodeFormat ): char;
/// <summary>
/// This method writes the string of characters to the stream in <br />
/// the specified unicode format.
/// </summary>
/// <param name="aString">
/// The string of characters to write to the stream.
/// </param>
/// <param name="Format">
/// The unicode format to use when writing the characters to the stream.
/// </param>
procedure WriteString( const aString: string; const Format: TUnicodeFormat );
/// <summary>
/// This method reads a string of characters from the stream in the
/// specified unicode format, translating them to a TString UTF-16LE. <br />
/// </summary>
/// <param name="Format">
/// The unicode format to use when reading the characters <br />from the
/// stream.
/// </param>
/// <param name="ZeroTerm">
/// Optional parameter. Terminate reading characters from the stream when
/// a zero character is found?
/// </param>
/// <param name="Max">
/// Optional parameter. The maximum number of unicode characters to read
/// from the stream.
/// </param>
/// <returns>
/// The string of characters read from the stream, converted to <br />
/// TdeString (UTF-16LE)
/// </returns>
/// <remarks>
/// <para>
/// This method, by default, will read characters from the stream
/// until the stream has been exhausted.
/// </para>
/// <para>
/// You can tell the stream to terminate early using the two optional
/// parameters. <br /><br />
/// </para>
/// <para>
/// Setting ZeroTerm to true causes the method to stop reading when a
/// code-point is discovered with the value of zero. This is useful
/// for reading zero terminated strings from the stream. The zero
/// will be removed from the stream, but not added to the string.
/// </para>
/// <para>
/// Alternatively, you can set the Max parameter to limit the number
/// of characters that will be read from the stream.
/// </para>
/// </remarks>
function ReadString( const Format: TUnicodeFormat; const ZeroTerm: boolean = False; const Max: int32 = -1 ): string;
//- Pascal Only, Properties -//
property Size: nativeuint read getSize;
property Position: nativeuint read getPosition write setPosition;
end;
{$endregion}
{$region ' IBuffer'}
/// <summary>
/// IBuffer provides methods for manipulating the data content of a buffer.
/// </summary>
/// <seealso cref="de.buffers|TBuffer">
/// TBuffer
/// </seealso>
IBuffer = interface
['{115CCCF5-4F51-425E-9A00-3CEB8E6E19E6}']
/// <summary>
/// Fills the entire buffer with the value passed in the 'value' parameter.
/// Useful for clearing the buffer for example.
/// </summary>
/// <param name="value">
/// The value to fill the buffer with.
/// </param>
procedure FillMem( const value: uint8 );
/// <summary>
/// Loads 'Bytes' bytes of data from the stream into the buffer.
/// </summary>
/// <param namme="Stream">
/// The stream to load data from.
/// </param>
/// <param name="Bytes">
/// The number of bytes to load from the stream.
/// </param>
/// <returns>
/// The number of bytes actually read from the stream.
/// </returns>
function LoadFromStream( const Stream: IStream; const Bytes: nativeuint ): nativeuint;
/// <summary>
/// Saves 'Bytes' bytes of data from the buffer into the stream.
/// </summary>
/// <param name="Stream">
/// The stream to save bytes into.
/// </param>
/// <param name="Bytes">
/// The number of bytes to write into the stream.
/// </param>
/// <returns>
/// The number of bytes actually written to the stream.
/// </returns>
function SaveToStream( const Stream: IStream; const Bytes: nativeuint ): nativeuint;
/// <summary>
/// Copy the data from another buffer to this one. <br />The size of the
/// buffer will be appropriately altered to match that of the buffer
/// being copied.
/// </summary>
/// <param name="Buffer">
/// The buffer to copy data from.
/// </param>
/// <remark>
/// This method is destructive to existing data in the buffer.
/// </remark>
procedure Assign( const Buffer: IBuffer );
/// <summary>
/// Insert data from another memory location into this buffer.
/// There must be sufficient space in the buffer to store the inserted
/// data at the specified offset.
/// </summary>
/// <param name="Buffer">
/// This is a pointer to the memory location that data should be copied
/// from.
/// </param>
/// <param name="Bytes">
/// Specifies the number of bytes to read from the memory location.
/// </param>
/// <remarks>
/// This method is destructive to existing data in the buffer.
/// </remarks>
procedure InsertData( const Buffer: Pointer; const Offset: nativeuint; const Bytes: nativeuint );
/// <summary>
/// Appends data from another memory location to the end of this buffer.
/// </summary>
/// <param name="Buffer">
/// A pointer to the memory location that data should be copied from.
/// </param>
/// <param name="Bytes">
/// Specifies the number of bytes to add to the buffer from the memory
/// location specified in the buffer parameter.
/// </param>
/// <returns>
/// Pointer to the newly appended data.
/// </returns>
function AppendData( const Buffer: Pointer; const Bytes: nativeuint ): pointer; overload;
/// <summary>
/// Appends data from another memory location to the end of this buffer.
/// The data to be appended must be zero-terminated.
/// If the size of the buffer to be appended is known, see the other
/// overload of AppendData().
/// </summary>
function AppendData( const Buffer: pointer ): pointer; overload;
/// <summary>
/// Extract data to another memory location from this buffer.
/// </summary>
/// <param name="Buffer">
/// This is a pointer to the memory location that data should be copied
/// to
/// </param>
/// <param name="Bytes">
/// This is the number of bytes that should be copied from this buffer.
/// </param>
procedure ExtractData( const Buffer: Pointer; const Offset: nativeuint; const Bytes: nativeuint );
/// <summary>
/// Returns a void pointer to the buffer data.
/// </summary>
function getDataPointer: pointer;
/// <summary>
/// Returns the size of the buffer in bytes.
/// </summary>
function getSize: nativeuint;
/// <summary>
/// Returns the value of the byte specified by index (offset within the buffer)
/// </summary>
/// <param name="idx">
/// An offset into the buffer.
/// </param>
function getByte( const idx: nativeuint ): uint8;
/// <summary>
/// Sets the value of the byte specified by index (offset within the buffer)
/// </summary>
/// <param name="idx">
/// An offset into the buffer.
/// </param>
/// <param>
/// The value to set.
/// </param>
procedure setByte( const idx: nativeuint; const value: uint8 );
/// <summary>
/// Sets the size of the buffer in bytes.
/// </summary>
/// <param name="aSize">
/// The new buffer size in bytes.
/// </param>
/// <remarks>
/// This function will retain any existing data, up-to the new size of
/// the buffer.
/// </remarks>
procedure setSize( const aSize: nativeuint );
/// <summary>
/// Get the size of the data in this buffer, in bytes.
/// </summary>
property Size: nativeuint read getSize write setSize;
property DataPtr: pointer read getDataPointer;
property Bytes[ const idx: nativeuint ]: uint8 read getByte write setByte;
end;
{$endregion}
{$region ' IUnicodeBuffer'}
/// <summary>
/// Provides methods for working with buffers containing unicode text.
/// </summary>
IUnicodeBuffer = interface( IBuffer )
['{E0472DB1-CDE7-4FD1-BB02-00291C0342F6}']
/// <summary>
/// Returns the entire buffer as a string, assuming that the data in
/// the buffer is encoded as UTF16-LE (the default string type).
/// </summary>
function getAsString: string;
/// <summary>
/// Sets the buffer length to be sufficient to store the string in
/// UTF16-LE format internally.
/// </summary>
procedure setAsString( const value: string );
/// <summary>
/// Attempts to read the byte-order-mark of the specified unicode format.
/// Returns true if the requested BOM is present at the beginning of
/// the buffer, else returns false.
/// </summary>
function ReadBOM( const Format: TUnicodeFormat ): boolean;
/// <summary>
/// Writes the specified unicode byte-order-mark to the beginning of the
/// buffer.
/// </summary>
procedure WriteBOM( const Format: TUnicodeFormat );
/// <summary>
/// Attempts to identify the unicode format of the data in the buffer
/// by inspecting the byte-order-mark or other attributes of the data.
/// </summary>
function DetermineUnicodeFormat: TUnicodeFormat;
/// Returns length of string written to buffer, in bytes.
/// The buffer size is set to match the length of the string after encoding.
/// If the optional ZeroTerm parameter is set true, a zero terminator is
/// added to the string and returned byte-count. This may only be useful
/// when writing ANSI or UTF8 format strings as other formats do not
/// typically use zero termination.
function WriteString( const aString: string; const Format: TUnicodeFormat; ZeroTerm: boolean = FALSE ): nativeuint;
/// Max when not -1, is lenght of TString in characters
function ReadString( const Format: TUnicodeFormat; const ZeroTerm: boolean = False; const Max: int32 = -1 ): string;
//- Pascal only properties -//
/// <summary>
/// When setting, will set the length of the buffer to the required number
/// of bytes to contain the string in UTF16-LE format internally.
/// When getting, the entire buffer will be returned as a string.
/// </summary>
property AsString: string read getAsString write setAsString;
end;
{$endregion}
{$region ' ITypedBuffer'}
/// <summary>
/// Creates a buffer for storing items of type T.
/// The buffer lays out the items <T> sequentially across the buffer
/// meaning they may be addressed as an array of items.
/// </summary>
ITypedBuffer<T> = interface( IBuffer )
['{4BD15A6F-73CE-43E7-BF16-E5BB76C0A841}']
/// <summary>
/// Fills the entire buffer with the value passed in the 'value'
/// parameter. Useful for clearing the buffer for example.
/// </summary>
/// <param name="value">
/// The value to fill the buffer with.
/// </param>
procedure Fill( const Value: T );
/// <summary>
/// Returns the number of iems for which there is space in the buffer.
/// </summary>
function getCount: nativeuint;
/// <summary>
/// Sets the buffer to a new size to accomodate the number of items
/// specified by the value parameter. Note: If the buffer is made
/// larger, the content will be maintained. If the buffer is
/// made smaller, only the content for which there is room after
/// resizing is maintained.
/// </summary>
procedure setCount( const value: nativeuint );
/// <summary>
/// Returns an item from the buffer by it's index.
/// </summary>
function getValue( const Index: nativeuint ): T;
/// <summary>
/// Sets the value of an item from the buffer by index.
/// </summary>
procedure setValue( const Index: nativeuint; const value: T );
/// <summary>
/// Get/Set items in the buffer by index (array style access)
/// </summary>
property Values[ const Index: nativeuint ]: T read getValue write setValue; default;
/// <summary>
/// Returns the number of iems for which there is space in the buffer.
/// </summary>
property Count: nativeuint read getCount write setCount;
end;
{$endregion}
{$region ' ICyclicBuffer'}
ICyclicBuffer = interface
['{42C239B3-36F7-4618-B4BD-929C53DFF75C}']
/// <summary>
/// Simply resets the buffer pointers.
/// </summary>
procedure Clear;
/// <summary>
/// Write 'Count' bytes into the buffer. If there is insufficient space in
/// the buffer, this method will return a <0 error code. Otherwise the
/// number of bytes added is returned.
/// </summary>
function Write( const DataPtr: Pointer; const Count: nativeuint ): nativeuint;
/// <summary>
/// Read 'Count' bytes from the buffer. If there is insufficient data to
/// return the number of bytes requested, the maximum available bytes
/// will be read. This method returns the number of bytes read from
/// the buffer.
/// </summary>
function Read( const DataPtr: Pointer; const Count: nativeuint ): nativeuint;
/// <summary>
/// Reads 'Size' bytes from the buffer, but doesn't remove that data from
/// the buffer as Read does.
/// </summary>
function Peek( const DataPtr: Pointer; const Count: nativeuint ): nativeuint;
/// <summary>
/// Loads 'Bytes' bytes of data from the stream into the buffer.
/// </summary>
function LoadFromStream( const Stream: IStream; const Bytes: nativeuint ): nativeuint;
/// <summary>
/// Saves 'Bytes' bytes of data from the buffer into the stream.
/// </summary>
function SaveToStream( const Stream: IStream; const Bytes: nativeuint ): nativeuint;
/// <summary>
/// Returns the number of bytes that are freely available in the buffer.
/// </summary>
function GetFreeBytes: nativeuint;
/// <summary>
/// Returns the number of bytes that are currently occupied in the buffer.
/// </summary>
function GetUsedBytes: nativeuint;
end;
{$endregion}
implementation
end.
|
unit UJSONConnectorTests;
interface
{$I dws.inc}
uses
{$IFDEF WINDOWS} Windows, {$ENDIF} Classes, SysUtils, Variants,
dwsXPlatformTests, dwsComp, dwsCompiler, dwsExprs, dwsErrors,
dwsXPlatform, dwsUtils, dwsJSONConnector;
type
TJSONConnectorTests = class (TTestCase)
private
FTests : TStringList;
FFailures : TStringList;
FCompiler : TDelphiWebScript;
FConnector : TdwsJSONLibModule;
public
procedure SetUp; override;
procedure TearDown; override;
procedure Execution;
procedure Compilation;
published
procedure CompilationNormal;
procedure CompilationWithMapAndSymbols;
procedure ExecutionNonOptimized;
procedure ExecutionOptimized;
procedure CompilationFailure;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------
// ------------------ TJSONConnectorTests ------------------
// ------------------
// SetUp
//
procedure TJSONConnectorTests.SetUp;
const
cMask = '*.pas';
begin
FTests:=TStringList.Create;
FFailures:=TStringList.Create;
CollectFiles(ExtractFilePath(ParamStr(0))+'JSONConnectorPass'+PathDelim, cMask, FTests);
CollectFiles(ExtractFilePath(ParamStr(0))+'JSONConnectorFail'+PathDelim, cMask, FFailures);
FCompiler:=TDelphiWebScript.Create(nil);
FConnector:=TdwsJSONLibModule.Create(nil);
FConnector.Script:=FCompiler;
end;
// TearDown
//
procedure TJSONConnectorTests.TearDown;
begin
FConnector.Free;
FCompiler.Free;
FFailures.Free;
FTests.Free;
end;
// Compilation
//
procedure TJSONConnectorTests.Compilation;
var
source : TStringList;
i : Integer;
prog : IdwsProgram;
begin
source:=TStringList.Create;
try
for i:=0 to FTests.Count-1 do begin
source.LoadFromFile(FTests[i]);
prog:=FCompiler.Compile(source.Text);
CheckEquals('', prog.Msgs.AsInfo, FTests[i]);
end;
finally
source.Free;
end;
end;
// CompilationNormal
//
procedure TJSONConnectorTests.CompilationNormal;
begin
FCompiler.Config.CompilerOptions:=[coOptimize];
Compilation;
end;
// CompilationWithMapAndSymbols
//
procedure TJSONConnectorTests.CompilationWithMapAndSymbols;
begin
FCompiler.Config.CompilerOptions:=[coSymbolDictionary, coContextMap, coAssertions];
Compilation;
end;
// ExecutionNonOptimized
//
procedure TJSONConnectorTests.ExecutionNonOptimized;
begin
FCompiler.Config.CompilerOptions:=[coAssertions];
Execution;
end;
// ExecutionOptimized
//
procedure TJSONConnectorTests.ExecutionOptimized;
begin
FCompiler.Config.CompilerOptions:=[coOptimize, coAssertions];
Execution;
end;
// CompilationFailure
//
procedure TJSONConnectorTests.CompilationFailure;
var
source : TStringList;
i : Integer;
prog : IdwsProgram;
expectedError : TStringList;
expectedErrorsFileName : String;
begin
FCompiler.Config.CompilerOptions:=[coOptimize, coAssertions];
source:=TStringList.Create;
expectedError:=TStringList.Create;
try
for i:=0 to FFailures.Count-1 do begin
source.LoadFromFile(FFailures[i]);
prog:=FCompiler.Compile(source.Text);
expectedErrorsFileName:=ChangeFileExt(FFailures[i], '.txt');
if FileExists(expectedErrorsFileName) then begin
expectedError.LoadFromFile(expectedErrorsFileName);
CheckEquals(expectedError.Text, prog.Msgs.AsInfo, FFailures[i]);
end else Check(prog.Msgs.AsInfo<>'', FFailures[i]+': undetected error');
end;
finally
expectedError.Free;
source.Free;
end;
end;
// Execution
//
procedure TJSONConnectorTests.Execution;
var
source, expectedResult : TStringList;
i : Integer;
prog : IdwsProgram;
exec : IdwsProgramExecution;
resultsFileName : String;
output : String;
begin
source:=TStringList.Create;
expectedResult:=TStringList.Create;
try
for i:=0 to FTests.Count-1 do begin
source.LoadFromFile(FTests[i]);
prog:=FCompiler.Compile(source.Text);
CheckEquals('', prog.Msgs.AsInfo, FTests[i]);
exec:=prog.Execute;
if exec.Msgs.Count=0 then
output:=exec.Result.ToString
else begin
output:= 'Errors >>>>'#13#10
+exec.Msgs.AsInfo
+'Result >>>>'#13#10
+exec.Result.ToString;
end;
resultsFileName:=ChangeFileExt(FTests[i], '.txt');
if FileExists(resultsFileName) then begin
expectedResult.LoadFromFile(resultsFileName);
CheckEquals(expectedResult.Text, output, FTests[i]);
end else CheckEquals('', output, FTests[i]);
end;
finally
expectedResult.Free;
source.Free;
end;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
initialization
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
RegisterTest('JSONConnectorTests', TJSONConnectorTests);
end.
|
unit toolbar_plant_generator;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Dialogs, StdCtrls,
Buttons, ShellCtrls, Menus,core_types, core_editor_states,
blocksToolbarUnit,core_plant_generator, core_utils, core_editor;
type
{ TtoolbarPlantGen }
TtoolbarPlantGen = class(TForm)
angleX1: TEdit;
angleY1: TEdit;
generateBtn: TButton;
Button2: TButton;
iterations: TEdit;
formulaFile: TEdit;
initAngleX: TEdit;
initAngleY: TEdit;
initAngleZ: TEdit;
axiom: TEdit;
Label12: TLabel;
Label13: TLabel;
Label14: TLabel;
Label3: TLabel;
Label6: TLabel;
Label7: TLabel;
Label9: TLabel;
blocks: TListBox;
menuDelete: TMenuItem;
treePopup: TPopupMenu;
rulesFrom: TMemo;
saveBtn: TSpeedButton;
tree: TShellTreeView;
sizeX: TEdit;
Label1: TLabel;
Label2: TLabel;
rulesTo: TMemo;
angleY: TEdit;
angleZ: TEdit;
sizeY: TEdit;
sizeZ: TEdit;
angleX: TEdit;
SpeedButton1: TSpeedButton;
SpeedButton2: TSpeedButton;
procedure generateBtnClick(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure FormActivate(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure menuDeleteClick(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
procedure SpeedButton2Click(Sender: TObject);
procedure saveBtnClick(Sender: TObject);
procedure treeMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure treeSelectionChanged(Sender: TObject);
private
{ private declarations }
procedure refreshTree;
procedure saveToFile(const filename:string);
public
{ public declarations }
end;
var
toolbarPlantGen: TtoolbarPlantGen;
implementation
{$R *.lfm}
{ TtoolbarPlantGen }
procedure TtoolbarPlantGen.SpeedButton1Click(Sender: TObject);
begin
if blocks.Items.IndexOf(toolbarBlocks.colorList.items[toolbarBlocks.colorList.ItemIndex])>-1 then exit;
blocks.AddItem(toolbarBlocks.colorList.items[toolbarBlocks.colorList.ItemIndex],nil);
end;
procedure TtoolbarPlantGen.FormCreate(Sender: TObject);
begin
tree.Root:=apppath+'LSystem';
end;
procedure TtoolbarPlantGen.menuDeleteClick(Sender: TObject);
begin
if MessageDlg('Sure?',mtConfirmation, mbOKCancel, 0)=mrOk then begin
if fileExists(TREE.GetSelectedNodePath) then deletefile(tree.GetSelectedNodePath);
refreshTree;
end;
end;
procedure TtoolbarPlantGen.FormActivate(Sender: TObject);
begin
refreshTree;
end;
procedure TtoolbarPlantGen.Button2Click(Sender: TObject);
begin
rulesFrom.Clear;
rulesTo.Clear;
blocks.Clear;
end;
procedure TtoolbarPlantGen.generateBtnClick(Sender: TObject);
begin
savetofile(tree.root+'\temp');
plantGenerator.fromFile(1,1,tree.root+'\temp',true);
editor.state:=esPaintWithBrush;
//ui.bringtofront;
end;
procedure TtoolbarPlantGen.SpeedButton2Click(Sender: TObject);
begin
if blocks.ItemIndex>-1 then
blocks.Items.Delete(blocks.ItemIndex);
end;
procedure TtoolbarPlantGen.saveBtnClick(Sender: TObject);
begin
if formulaFile.Text='' then begin
showmessage('Set filename first');
end;
if ExtractFileExt(formulafile.Text)<>'.txt' then formulaFile.Text:=formulaFile.Text+'.txt';
savetofile(tree.root+'\'+formulaFile.Text);
refreshTree;
end;
procedure TtoolbarPlantGen.treeMouseUp(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
begin
if button=TMouseButton.mbRight then treePopup.PopUp;
end;
procedure TtoolbarPlantGen.treeSelectionChanged(Sender: TObject);
var s,s1,s2:string;
list:tstringlist;
begin
if tree.Selected=nil then exit;
formulafile.Text:=tree.Selected.Text;
if ExtractFileExt(formulafile.Text)='.txt' then begin
rulesFrom.Clear;
rulesTo.Clear;
blocks.Clear;
//load values to controls
list:=tstringlist.create;
s:=tree.root+'\'+tree.Selected.GetTextPath;
list.LoadFromFile(s);
for s2 in list do begin
s:=s2;
s1:=eatstring(s);
if s1='rule' then begin
rulesFrom.Lines.add(eatstring(s));
rulesTo.Lines.add(eatstring(s));
continue;
end;
if s1='axiom' then axiom.text:=eatstring(s);
if s1='iterations' then iterations.text:=eatstring(s);
if s1='size' then begin
sizex.text:=eatstring(s);
sizey.text:=eatstring(s);
sizez.text:=eatstring(s);
end;
if s1='angle' then begin
anglex.text:=eatstring(s);
angley.text:=eatstring(s);
anglez.text:=eatstring(s);
end;
if s1='initialAngle' then begin
initAnglex.text:=eatstring(s);
initAngley.text:=eatstring(s);
initAnglez.text:=eatstring(s);
end;
if s1='colors' then begin
s1:=eatstring(s);
while length(s1)>2 do begin
blocks.Items.add(s1);
s1:=eatstring(s);
end;
end;
end;
list.free;
end else formulafile.text:='';
end;
procedure TtoolbarPlantGen.refreshTree;
var s:string;
begin
s:=tree.Root;
tree.BeginUpdate;
tree.Root:='c:\';
tree.root:=s;
tree.EndUpdate;
end;
procedure TtoolbarPlantGen.saveToFile(const filename: string);
var s,s1:string;
list:tstringlist;
i:integer;
begin
if rulesFrom.lines.count<>rulesTo.lines.count then begin
showmessage('rules line count doesn''t match');
exit;
end;
list:=tstringlist.create;
for i:=0 to rulesFrom.lines.count-1 do list.Add('rule;'+rulesFrom.lines[i]+';'+rulesTo.lines[i]+';');
list.add('axiom;'+axiom.text+';');
list.add('iterations;'+iterations.text+';');
list.add('size;'+sizeX.text+';'+sizeY.text+';'+sizeZ.text+';');
list.add('angle;'+angleX.text+';'+angleY.text+';'+angleZ.text+';');
list.add('initialAngle;'+initAngleX.text+';'+initAngleY.text+';'+initAngleZ.text+';');
s1:='colors;';
for i:=0 to blocks.Items.count-1 do s1:=s1+blocks.Items[i]+';';
list.add(s1);
list.SaveToFile(filename);
list.free;
tree.Refresh;
end;
end.
|
unit ShapesU;
interface
uses
Graphics, Types;
type
/// Базовия клас на примитивите, който съдържа общите характеристики на примитивите.
TShapes = class
protected
fRectangle : TRect;
fFillColor : TColor;
fBorderColor : TColor;
fBorderSize: Integer;
function GetWidth : Integer;
function GetHeight : Integer;
function GetLocation : TPoint;
procedure SetBorderSize(const Value : Integer); virtual;
procedure SetWidth(const Value: Integer);
procedure SetHeight(const Value: Integer);
procedure SetLocation(const Value: TPoint); virtual;
procedure SetFillColor(const Value : TColor); virtual;
procedure SetBorderColor(const Value : TColor); virtual;
public
constructor Create(Rectangle : TRect);
procedure Translate(dx,dy:integer); virtual;
/// Обхващащ правоъгълник на елемента. В случая двата съвпадат.
property Rectangle : TRect read fRectangle write fRectangle;
/// Широчина на елемента.
property Width : Integer read GetWidth write SetWidth;
/// Височина на елемента.
property Height : Integer read GetHeight write SetHeight;
/// Горен ляв ъгъл на елемента.
property Location : TPoint read GetLocation write SetLocation;
/// Цвят на елемента.
property FillColor : TColor read fFillColor write SetFillColor;
/// Цвят на контура.
property BorderColor : TColor read fBorderColor write SetBorderColor;
///Border Size
property BorderSize : Integer read fBorderSize write SetBorderSize;
procedure DrawSelf(grfx : TCanvas); virtual;
function Contains(P : TPoint) : Boolean; virtual;
public
// constructor Create(Rectangle : TRect);
end;
implementation
{ TShapes }
/// Конструктор
constructor TShapes.Create(Rectangle: TRect);
begin
Self.Rectangle := Rectangle;
end;
/// Проверка дали точка P принадлежи на елемента.
/// P - Точка.
/// Връща true, ако точката принадлежи на елемента и
/// false, ако не пренадлежи.
function TShapes.Contains(P: TPoint): Boolean;
begin
Result := (Location.X <= P.X) and (P.X < Location.X + Width) and
(Location.Y <= P.Y) and (P.Y < Location.Y + Height);
end;
/// Визуализира елемента.
/// grfx - Къде да бъде визуализиран елемента.
procedure TShapes.DrawSelf(grfx: TCanvas);
begin
//
end;
function TShapes.GetHeight: Integer;
begin
Result := Rectangle.Bottom - Rectangle.Top;
end;
function TShapes.GetLocation: TPoint;
begin
Result := Rectangle.TopLeft;
end;
function TShapes.GetWidth: Integer;
begin
Result := Rectangle.Right - Rectangle.Left;
end;
procedure TShapes.SetFillColor(const Value: TColor);
begin
fFillColor := Value;
end;
procedure TShapes.SetBorderColor(const Value: TColor);
begin
fBorderColor := Value;
end;
procedure TShapes.SetHeight(const Value: Integer);
begin
Rectangle := Rect(Rectangle.Left, Rectangle.Top, Rectangle.Right, Rectangle.Top + Value);
end;
procedure TShapes.SetWidth(const Value: Integer);
begin
Rectangle := Rect(Rectangle.Left, Rectangle.Top, Rectangle.Left + Value, Rectangle.Bottom);
end;
procedure TShapes.SetLocation(const Value: TPoint);
begin
Rectangle := Rect(Value.X, Value.Y, Value.X + Width, Value.Y + Height);
end;
procedure TShapes.Translate(dx,dy:integer);
begin
Location := Point(Location.X+dx,Location.Y+dy);
end;
procedure TShapes.SetBorderSize(const Value: Integer);
begin
fBorderSize := Value;
end;
end.
|
unit UFramePrintBill;
{$I Link.Inc}
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, UFrameBase, ComCtrls, ExtCtrls, Buttons, StdCtrls,
USelfHelpConst, cxGraphics, cxControls, cxLookAndFeels,
cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit, cxMaskEdit,
cxButtonEdit, cxDropDownEdit ;
type
TfFramePrintBill = class(TfFrameBase)
Pnl_OrderInfo: TPanel;
lbl_2: TLabel;
btnPrint: TSpeedButton;
edt_TruckNo: TcxComboBox;
Label1: TLabel;
EditID: TLabel;
Label2: TLabel;
EditCusName: TLabel;
Label4: TLabel;
EditValue: TLabel;
Label3: TLabel;
EditDone: TLabel;
SpeedButton1: TSpeedButton;
Timer1: TTimer;
procedure btnPrintClick(Sender: TObject);
procedure edt_TruckNoPropertiesChange(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
private
{ Private declarations }
FListA, FListB, FListC: TStrings;
private
public
{ Public declarations }
procedure OnCreateFrame; override;
procedure OnDestroyFrame; override;
procedure OnShowFrame; override;
class function FrameID: integer; override;
end;
var
fFramePrintBill: TfFramePrintBill;
implementation
{$R *.dfm}
uses
ULibFun, USysLoger, UDataModule, UMgrControl, USysBusiness, UMgrK720Reader,
USysDB, UBase64;
//------------------------------------------------------------------------------
//Desc: 记录日志
procedure WriteLog(const nEvent: string);
begin
gSysLoger.AddLog(TfFramePrintBill, '小票打印', nEvent);
end;
class function TfFramePrintBill.FrameID: Integer;
begin
Result := cFI_FramePrintBill;
end;
procedure TfFramePrintBill.OnCreateFrame;
var nStr: string;
begin
FListA := TStringList.Create;
FListB := TStringList.Create;
FListC := TStringList.Create;
end;
procedure TfFramePrintBill.OnDestroyFrame;
begin
FListA.Free;
FListB.Free;
FListC.Free;
end;
procedure TfFramePrintBill.OnShowFrame;
begin
edt_TruckNo.Text := '';
edt_TruckNo.SetFocus;
end;
procedure TfFramePrintBill.btnPrintClick(Sender: TObject);
var nMsg, nStr, nID: string;
nIdx: Integer;
begin
nID := EditID.Caption;
if nID = '' then
begin
ShowMsg('未查询单据,无法打印', sHint);
Exit;
end;
if PrintBillReport(nID, False) then
begin
nStr := 'Update %s Set L_PrintCount=L_PrintCount + 1 ' +
'Where L_ID=''%s''';
nStr := Format(nStr, [sTable_Bill, nID]);
FDM.ExecuteSQL(nStr);
end;
edt_TruckNo.Text := '';
gTimeCounter := 0;
end;
procedure TfFramePrintBill.edt_TruckNoPropertiesChange(Sender: TObject);
var nIdx : Integer;
nStr: string;
begin
edt_TruckNo.Properties.Items.Clear;
nStr := 'Select T_Truck From %s Where T_Truck like ''%%%s%%'' ';
nStr := Format(nStr, [sTable_Truck, edt_TruckNo.Text]);
nStr := nStr + Format(' And (T_Valid Is Null or T_Valid<>''%s'') ', [sFlag_No]);
with FDM.SQLQuery(nStr) do
begin
if RecordCount > 0 then
begin
try
edt_TruckNo.Properties.BeginUpdate;
First;
while not Eof do
begin
edt_TruckNo.Properties.Items.Add(Fields[0].AsString);
Next;
end;
finally
edt_TruckNo.Properties.EndUpdate;
end;
end;
end;
for nIdx := 0 to edt_TruckNo.Properties.Items.Count - 1 do
begin;
if Pos(edt_TruckNo.Text,edt_TruckNo.Properties.Items.Strings[nIdx]) > 0 then
begin
edt_TruckNo.SelectedItem := nIdx;
Break;
end;
end;
end;
procedure TfFramePrintBill.SpeedButton1Click(Sender: TObject);
var nStr, nTruck: string;
nCount: Integer;
begin
EditID.Caption := '';
EditCusName.Caption := '';
EditValue.Caption := '';
EditDone.Caption := '';
nTruck := Trim(edt_TruckNo.Text);
if (nTruck = '')then
begin
ShowMsg('请填写车牌号信息', sHint);
Exit;
end;
if edt_TruckNo.Properties.Items.IndexOf(nTruck) < 0 then
begin
ShowMsg('请选择车牌号或输入完整车牌号', sHint);
Exit;
end;
nCount := 1;
nStr := 'Select D_Value From %s Where D_Name= ''%s''';
nStr := Format(nStr, [sTable_SysDict, sFlag_AICMBillPCount]);
with FDM.SQLQuery(nStr) do
begin
if RecordCount > 0 then
nCount := Fields[0].AsInteger;
end;
nStr := 'Select top 1 L_ID, L_CusName,L_Value,L_OutFact,L_PrintCount From %s Where L_Truck like ''%%%s%%'' order by R_ID desc';
nStr := Format(nStr, [sTable_Bill, nTruck]);
with FDM.SQLQuery(nStr) do
begin
if RecordCount < 1 then
begin
nStr := '未找到单据,无法打印';
ShowMsg(nStr, sHint);
edt_TruckNo.SetFocus;
Exit;
end;
if FieldByName('L_PrintCount').AsInteger >= nCount then
begin
nStr := '超出设定打印次数,无法打印';
ShowMsg(nStr, sHint);
edt_TruckNo.SetFocus;
Exit;
end;
EditID.Caption := Fields[0].AsString;
EditCusName.Caption := Fields[1].AsString;
EditValue.Caption := Fields[2].AsString;
EditDone.Caption := Fields[3].AsString;
end;
end;
procedure TfFramePrintBill.Timer1Timer(Sender: TObject);
begin
if gNeedClear then
begin
gNeedClear := False;
edt_TruckNo.Text := '';
EditID.Caption := '';
EditCusName.Caption := '';
EditValue.Caption := '';
EditDone.Caption := '';
end;
end;
initialization
gControlManager.RegCtrl(TfFramePrintBill, TfFramePrintBill.FrameID);
end.
|
unit Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics, System.Sensors,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls,
Vcl.Themes;
type
TForm1 = class(TForm)
Label1: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormDeactivate(Sender: TObject);
private
FSensor: TCustomLightSensor;
procedure OnDataChanged(Sender: TObject);
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.FormCreate(Sender: TObject);
var
SensorManager: TSensorManager;
Sensors: TSensorArray;
Sensor: TCustomSensor;
begin
SensorManager := TSensorManager.Current;
SensorManager.Activate;
Sensors := SensorManager.GetSensorsByCategory(TSensorCategory.Light);
if Length(Sensors) > 0 then begin
FSensor := TCustomLightSensor(Sensors[0]);
FSensor.OnDataChanged := OnDataChanged;
end;
end;
procedure TForm1.FormDeactivate(Sender: TObject);
begin
TSensorManager.Current.Deactivate;
end;
procedure TForm1.OnDataChanged(Sender: TObject);
begin
if FSensor.Lux < 30 then begin
Label1.Caption := 'Noite';
TStyleManager.TrySetStyle('Windows10 Dark')
end
else begin
Label1.Caption := 'Dia';
TStyleManager.TrySetStyle('Windows10')
end;
end;
end.
|
unit ServerU;
interface
procedure RunServer;
implementation
uses
blcksock, synsock, rpi, SysUtils;
function HandleGPIOCmd(PRaspberryPI: TRaspberryPI; PCmd: string): string;
var
LPin: string;
LDir, LPinI: integer;
begin
// command accept 1 char: 'R' light bulb 1 or 'L' light bulb 2
LPin := PCmd[1];
// light bulb 1
if LPin = 'R' then
LPinI := RELAY_PIN_1
// light bulb 2
else if LPin = 'L' then
LPinI := RELAY_PIN_2
else
exit('');
Result := BoolToStr(PRaspberryPI.GetPIN(LPinI), '0', '1');
end;
procedure HandleClient(aSocket: TSocket; PRaspberry: TRaspberryPI);
var
lCmd, LSS: string;
sock: TTCPBlockSocket;
begin
sock := TTCPBlockSocket.Create;
try
Sock.socket := aSocket;
sock.GetSins;
lCmd := Trim(Sock.RecvTerminated(60000, #13));
if Sock.LastError <> 0 then
begin
Sock.SendString('error:' + sock.LastErrorDesc);
Exit;
end;
// do something on the rpi
LSS := HandleGPIOCmd(PRaspberry, lCmd);
Sock.SendString(LSS);
if Sock.LastError <> 0 then
begin
Sock.SendString('error:' + sock.LastErrorDesc);
Exit;
end;
finally
Sock.Free;
end;
end;
procedure RunServer;
var
ClientSock: TSocket;
lSocket: TTCPBlockSocket;
LRPi: TRaspberryPI;
begin
LRPi := TRaspberryPI.Create;
try
// initialize GPIO
lSocket := TTCPBlockSocket.Create;
try
lSocket.CreateSocket;
lSocket.setLinger(True, 10000);
lSocket.Bind('0.0.0.0', '8008');
lSocket.Listen;
while True do
begin
if lSocket.CanRead(1000) then
begin
ClientSock := lSocket.Accept;
if lSocket.LastError = 0 then
HandleClient(ClientSock, LRPi);
end;
end;
finally
lSocket.Free;
end;
finally
LRPi.Free;
end;
end;
end.
|
program timersoftint;
{$IFNDEF HASAMIGA}
{$FATAL This source is compatible with Amiga, AROS and MorphOS only !}
{$ENDIF}
{$IFDEF MORPHOS}
{$FATAL Unfortunately this source does not compile for MorphOS (yet)}
{$ENDIF}
{
Project : timersoftint
Title : Timer device software interrupt message port example.
Source : RKRM
}
{$MODE OBJFPC}{$H+}{$HINTS ON}
{$UNITPATH ../../../Base/CHelpers}
{$UNITPATH ../../../Base/Trinity}
{$IFDEF AMIGA} {$UNITPATH ../../../Sys/Amiga} {$ENDIF}
{$IFDEF AROS} {$UNITPATH ../../../Sys/AROS} {$ENDIF}
{$IFDEF MORPHOS} {$UNITPATH ../../../Sys/MorphOS} {$ENDIF}
Uses
Exec, Timer, AmigaDOS, AmigaLib,
CHelpers,
Trinity,
SysUtils;
const
MICRO_DELAY = 1000;
FLAG_OFF = 0;
FLAG_ON = 1;
STOPPED = 2;
type
PTSIData = ^TTSIData;
TTSIData = record
tsi_Counter : ULONG;
tsi_Flag : ULONG;
tsi_Port : PMsgPort;
end;
var
tsidata : PTSIData;
procedure tsoftcode; forward; //* Prototype for our software interrupt code */
procedure Main;
var
port : PMsgPort;
softint : PInterrupt;
tr : Ptimerequest;
endcount : ULONG;
begin
//* Allocate message port, data & interrupt structures. Don't use CreatePort() */
//* or CreateMsgPort() since they allocate a signal (don't need that) for a */
//* PA_SIGNAL type port. We need PA_SOFTINT. */
if SetAndTest(tsidata, ExecAllocMem(sizeof(TTSIData), MEMF_PUBLIC or MEMF_CLEAR)) then
begin
if SetAndTest(port, ExecAllocMem(sizeof(TMsgPort), MEMF_PUBLIC or MEMF_CLEAR)) then
begin
NewList(@(port^.mp_MsgList)); //* Initialize message list */
if SetAndTest(softint, ExecAllocMem(sizeof(TInterrupt), MEMF_PUBLIC or MEMF_CLEAR)) then
begin
//* Set up the (software)interrupt structure. Note that this task runs at */
//* priority 0. Software interrupts may only be priority -32, -16, 0, +16, */
//* +32. Also not that the correct node type for a software interrupt is */
//* NT_INTERRUPT. (NT_SOFTINT is an internal Exec flag). This is the same */
//* setup as that for a software interrupt which you Cause(). If our */
//* interrupt code was in assembler, you could initialize is_Data here to */
//* contain a pointer to shared data structures. An assembler software */
//* interrupt routine would receive the is_Data in A1. */
softint^.is_Code := @tsoftcode; //* The software interrupt routine */
softint^.is_Data := tsidata;
softint^.is_Node.ln_Pri := 0;
port^.mp_Node.ln_Type := NT_MSGPORT; //* Set up the PA_SOFTINT message port */
port^.mp_Flags := PA_SOFTINT; //* (no need to make this port public). */
port^.mp_SigTask := PTask(softint); //* pointer to interrupt structure */
//* Allocate timerequest */
if SetAndTest(tr, Ptimerequest(CreateExtIO(port, sizeof(Ttimerequest)))) then
begin
//* Open timer.device. NULL is success. */
if (not( OpenDevice('timer.device', UNIT_MICROHZ, PIORequest(tr), 0) <> 0)) then
begin
tsidata^.tsi_Flag := FLAG_ON; //* Init data structure to share globally. */
tsidata^.tsi_Port := port;
//* Send of the first timerequest to start. IMPORTANT: Do NOT */
//* BeginIO() to any device other than audio or timer from */
//* within a software or hardware interrupt. The BeginIO() code */
//* may allocate memory, wait or perform other functions which */
//* are illegal or dangerous during interrupts. */
WriteLn('starting softint. CTRL-C to break...');
tr^.tr_node.io_Command := TR_ADDREQUEST; //* Initial iorequest to start */
tr^.tr_time.tv_micro := MICRO_DELAY; //* software interrupt. */
BeginIO(PIORequest(tr));
Wait(SIGBREAKF_CTRL_C);
endcount := tsidata^.tsi_Counter;
WriteLn(Format('timer softint counted %d milliseconds.', [endcount]));
WriteLn('Stopping timer...');
tsidata^.tsi_Flag := FLAG_OFF;
while (tsidata^.tsi_Flag <> STOPPED) do DOSDelay(10);
CloseDevice(PIORequest(tr));
end
else WriteLn('couldn''t open timer.device');
DeleteExtIO(PIORequest(tr));
end
else WriteLn('couldn''t create timerequest');
ExecFreeMem(softint, sizeof(TInterrupt));
end;
ExecFreeMem(port, sizeof(TMsgPort));
end;
ExecFreeMem(tsidata, sizeof(TTSIData));
end;
end;
procedure tsoftcode;
var
tr : Ptimerequest;
begin
//* Remove the message from the port. */
tr := Ptimerequest(GetMsg(tsidata^.tsi_Port));
//* Keep on going if main() hasn't set flag to OFF. */
if (Assigned(tr) and (tsidata^.tsi_Flag = FLAG_ON)) then
begin
//* increment counter and re-send timerequest--IMPORTANT: This */
//* self-perpetuating technique of calling BeginIO() during a software */
//* interrupt may only be used with the audio and timer device. */
inc(tsidata^.tsi_Counter);
tr^.tr_node.io_Command := TR_ADDREQUEST;
tr^.tr_time.tv_micro := MICRO_DELAY;
BeginIO(PIORequest(tr));
end
//* Tell main() we're out of here. */
else tsidata^.tsi_Flag := STOPPED;
end;
begin
Main;
end.
|
unit mnControl;
interface
uses Controls, Types, mnSystem, cxListBox, cxDropDownEdit, cxMCListBox,
cxDBLookupComboBox, cxTextEdit, ComCtrls, Menus;
{--------------------------------
得到一个控件的左上角和右下角的点的坐标。使用屏幕坐标系。
Tested in TestApp.
--------------------------------}
function mnGetControlTopLeft(AControl: TControl): TPoint;
function mnGetControlBottomRight(AControl: TControl): TPoint;
{--------------------------------
判断一个点是否在控件范围内。点的坐标使用屏幕坐标系。
Tested in TestApp.
--------------------------------}
function mnPointInControl(const APoint: TPoint; AControl: TControl): Boolean;
{--------------------------------
得到一个控件的Text。
VCL的TControl类本身有Text属性,但是是protected的。
Tested in TestUnit and TestApp.
--------------------------------}
function mnGetControlText(AControl: TControl): TCaption;
{--------------------------------
验证一个Windows控件的Text是否满足指定约束。如果不满足,将输入焦点置于该控件,并抛出异常。
异常消息的规则如下:如果ErrorMsg有赋值,则为ErrorMsg;
否则,如果ControlMeaning有赋值,则使用ControlMeaning组合成异常消息;
如果这两个参数都没有赋值,则使用该控件的Name组合成缺省消息,作为异常消息。
Tested in TestUnit and TestApp.
--------------------------------}
procedure mnValidateControlText(AWinControl: TWinControl; const TextConstraint: mnTStrConstraint;
const ControlMeaning: string = ''; const ErrorMsg: string = '');
{--------------------------------
验证一个cxListBox、cxComboBox、cxMCListBox或cxLookupComboBox是否已被选择。
如果没有,将输入焦点置于该控件,并抛出异常。
异常消息的规则如下:如果ErrorMsg有赋值,则为ErrorMsg;
否则,如果ControlMeaning有赋值,则使用ControlMeaning组合成异常消息;
如果这两个参数都没有赋值,则使用该控件的Name组合成缺省消息,作为异常消息。
Tested in TestUnit.
--------------------------------}
procedure mnValidateControlSelected(ListBox: TcxListBox; const ControlMeaning: string = ''; const ErrorMsg: string = ''); overload;
procedure mnValidateControlSelected(ComboBox: TcxComboBox; const ControlMeaning: string = ''; const ErrorMsg: string = ''); overload;
procedure mnValidateControlSelected(MCListBox: TcxMCListBox; const ControlMeaning: string = ''; const ErrorMsg: string = ''); overload;
procedure mnValidateControlSelected(LookupComboBox: TcxLookupComboBox; const ControlMeaning: string = ''; const ErrorMsg: string = ''); overload;
{--------------------------------
在一个Edit或RichEdit的当前光标处插入文本。
连续插入TextBeforeCursor和TextAfterCursor,将光标移到TextBeforeCursor的后面,亦即TextAfterCursor的前面。
Tested in TestApp.
--------------------------------}
procedure mnInsertTextInEdit(Edit: TcxCustomTextEdit; const TextBeforeCursor, TextAfterCursor: string);
procedure mnInsertTextInRichEdit(RichEdit: TRichEdit; const TextBeforeCursor, TextAfterCursor: string);
{--------------------------------
在一个Edit的当前光标处弹出菜单。
Tested in TestApp.
--------------------------------}
procedure mnPopupMenuInEdit(Edit: TcxCustomTextEdit; Menu: TPopupMenu);
{--------------------------------
得到一个Edit的当前被选中文本,并将其之前的文本存入Prefix,将其之后的文本存入Suffix。
Tested in TestApp.
--------------------------------}
function mnGetSelText(Edit: TcxCustomTextEdit; var Prefix, Suffix: string): string;
implementation
uses mnResStrsU, Classes, mnDebug, Variants, mnString, StrUtils;
function mnGetControlTopLeft(AControl: TControl): TPoint;
begin
Result := AControl.ClientToScreen(AControl.ClientRect.TopLeft);
end;
function mnGetControlBottomRight(AControl: TControl): TPoint;
begin
Result := AControl.ClientToScreen(AControl.ClientRect.BottomRight);
end;
function mnPointInControl(const APoint: TPoint; AControl: TControl): Boolean;
begin
Result := PtInRect(Rect(mnGetControlTopLeft(AControl), mnGetControlBottomRight(AControl)), APoint);
end;
function mnGetControlText(AControl: TControl): TCaption;
var
Len: Integer;
begin
Len := AControl.GetTextLen;
if Len > 0 then
begin
SetString(Result, nil, Len+1);
AControl.GetTextBuf(Pointer(Result), Len+1);
SetLength(Result, Len);
end
else Result := '';
end;
procedure mnValidateControlText(AWinControl: TWinControl; const TextConstraint: mnTStrConstraint;
const ControlMeaning: string = ''; const ErrorMsg: string = '');
var
ErrorParam: string;
begin
if not mnCheckStrConstraint(mnGetControlText(AWinControl), TextConstraint) then
begin
AWinControl.SetFocus;
if ErrorMsg = '' then
begin
ErrorParam := mnChooseStr(ControlMeaning = '', AWinControl.Name, ControlMeaning);
case TextConstraint of
scNotEmpty: mnCreateError(SErrorMsgNotEmpty, [ErrorParam]);
scNotEmptyAbs: mnCreateError(SErrorMsgNotEmptyAbs, [ErrorParam]);
scIsInt: mnCreateError(SErrorMsgIsInt, [ErrorParam]);
scIsFloat: mnCreateError(SErrorMsgIsFloat, [ErrorParam]);
scIsDT: mnCreateError(SErrorMsgIsDT, [ErrorParam]);
scIsCurr: mnCreateError(SErrorMsgIsCurr, [ErrorParam]);
scNE0: mnCreateError(SErrorMsgNE0, [ErrorParam]);
scLT0: mnCreateError(SErrorMsgLT0, [ErrorParam]);
scLE0: mnCreateError(SErrorMsgLE0, [ErrorParam]);
scGT0: mnCreateError(SErrorMsgGT0, [ErrorParam]);
scGE0: mnCreateError(SErrorMsgGE0, [ErrorParam]);
else
mnNeverGoesHere;
end;
end
else mnCreateError(ErrorMsg);
end;
end;
procedure mnValidateControlSelected(ListBox: TcxListBox; const ControlMeaning: string = ''; const ErrorMsg: string = ''); overload;
begin
if ListBox.ItemIndex = -1 then
begin
ListBox.SetFocus;
if ErrorMsg = '' then
mnCreateError(SErrorMsgSelected, [mnChooseStr(ControlMeaning = '', ListBox.Name, ControlMeaning)])
else
mnCreateError(ErrorMsg);
end;
end;
procedure mnValidateControlSelected(ComboBox: TcxComboBox; const ControlMeaning: string = ''; const ErrorMsg: string = ''); overload;
begin
if ComboBox.ItemIndex = -1 then
begin
ComboBox.SetFocus;
if ErrorMsg = '' then
mnCreateError(SErrorMsgSelected, [mnChooseStr(ControlMeaning = '', ComboBox.Name, ControlMeaning)])
else
mnCreateError(ErrorMsg);
end;
end;
procedure mnValidateControlSelected(MCListBox: TcxMCListBox; const ControlMeaning: string = ''; const ErrorMsg: string = ''); overload;
begin
if MCListBox.ItemIndex = -1 then
begin
MCListBox.SetFocus;
if ErrorMsg = '' then
mnCreateError(SErrorMsgSelected, [mnChooseStr(ControlMeaning = '', MCListBox.Name, ControlMeaning)])
else
mnCreateError(ErrorMsg);
end;
end;
procedure mnValidateControlSelected(LookupComboBox: TcxLookupComboBox; const ControlMeaning: string = ''; const ErrorMsg: string = ''); overload;
begin
if LookupComboBox.EditValue = Null then
begin
LookupComboBox.SetFocus;
if ErrorMsg = '' then
mnCreateError(SErrorMsgSelected, [mnChooseStr(ControlMeaning = '', LookupComboBox.Name, ControlMeaning)])
else
mnCreateError(ErrorMsg);
end;
end;
procedure mnInsertTextInEdit(Edit: TcxCustomTextEdit; const TextBeforeCursor, TextAfterCursor: string);
var
OldSelStart: Integer;
begin
OldSelStart := mnSettleByte(Edit.Text, Edit.CursorPos);
Edit.Text := Copy(Edit.Text, 1, OldSelStart) +
TextBeforeCursor + TextAfterCursor +
Copy(Edit.Text, OldSelStart+1);
Edit.SelStart := OldSelStart + Length(TextBeforeCursor);
Edit.SelLength := 0;
end;
procedure mnInsertTextInRichEdit(RichEdit: TRichEdit; const TextBeforeCursor, TextAfterCursor: string);
var
OldSelStart: Integer;
begin
OldSelStart := RichEdit.SelStart;
RichEdit.SelText := TextBeforeCursor + TextAfterCursor;
RichEdit.SelStart := OldSelStart + Length(TextBeforeCursor);
RichEdit.SelLength := 0;
end;
procedure mnPopupMenuInEdit(Edit: TcxCustomTextEdit; Menu: TPopupMenu);
var
TextBeforeCursor: string;
begin
TextBeforeCursor := Copy(Edit.Text, 1, mnSettleByte(Edit.Text, Edit.CursorPos));
Menu.Popup(Edit.ClientToScreen(Edit.ClientRect.TopLeft).X + Edit.Canvas.TextWidth(TextBeforeCursor),
Edit.ClientToScreen(Edit.ClientRect.TopLeft).Y + Edit.Canvas.TextHeight(TextBeforeCursor));
end;
function mnGetSelText(Edit: TcxCustomTextEdit; var Prefix, Suffix: string): string;
begin
Result := Edit.SelText;
Prefix := LeftBStr(Edit.Text, Edit.SelStart);
Suffix := RightBStr(Edit.Text, Length(Edit.Text) - Edit.SelLength - Edit.SelStart);
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ }
{ Copyright(c) 2011-2013 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit FMX.Dialogs.Default;
interface
uses
System.Types, System.Classes, System.UITypes, System.UIConsts,
FMX.Forms, FMX.Platform, FMX.Types, FMX.Dialogs, FMX.Graphics;
function DefaultInputQuery(const ACaption: string; const APrompts: array of string; var AValues: array of string;
CloseQueryFunc: TInputCloseQueryFunc): Boolean;
implementation
uses System.Generics.Collections, System.SysUtils, System.Math,
FMX.StdCtrls, FMX.Edit, FMX.Consts;
type
TInputQueryForm = class(TForm)
public
FCloseQueryFunc: TFunc<Boolean>;
function CloseQuery: Boolean; override;
end;
function TInputQueryForm.CloseQuery: Boolean;
begin
Result := (ModalResult = mrCancel) or (not Assigned(FCloseQueryFunc)) or FCloseQueryFunc();
end;
function DefaultInputQuery(const ACaption: string; const APrompts: array of string; var AValues: array of string;
CloseQueryFunc: TInputCloseQueryFunc): Boolean;
var
I, J: Integer;
Form: TInputQueryForm;
Prompt: TLabel;
Edit: TEdit;
Button: TButton;
DialogUnits: TPoint;
PromptCount: Integer;
MaxPromptWidth, CurPrompt: Integer;
ButtonTop, ButtonWidth, ButtonHeight: Single;
function GetAveCharSize(Canvas: TCanvas): TPoint;
var
I: Integer;
Buffer: string;
begin
SetLength(Buffer, 52);
for I := 1 to 26 do
Buffer[I] := Chr((I - 1) + Ord('A'));
for I := 27 to 52 do
Buffer[I] := Chr((I - 27) + Ord('a'));
Result := Point(Round(Canvas.TextWidth(Buffer)), Round(Canvas.TextHeight(Buffer)));
Result.X := Round(Result.X / 52);
end;
function GetPromptCaption(const ACaption: string): string;
begin
if (Length(ACaption) > 1) and (ACaption[1] < #32) then
Result := Copy(ACaption, 2, MaxInt)
else
Result := ACaption;
end;
function GetMaxPromptWidth(Canvas: TCanvas): Integer;
var
I: Integer;
begin
Result := 0;
for I := 0 to PromptCount - 1 do
Result := Round(Max(Result, Canvas.TextWidth(GetPromptCaption(APrompts[I])) + DialogUnits.X));
end;
function GetPasswordChar(const ACaption: string): WideChar;
begin
if (Length(ACaption) > 1) and (ACaption[1] < #32) then
Result := '*'
else
Result := #0;
end;
begin
if Length(AValues) < Length(APrompts) then
raise EInvalidOperation.Create(SPromptArrayTooShort);
PromptCount := Length(APrompts);
if PromptCount < 1 then
raise EInvalidOperation.Create(SPromptArrayEmpty);
Result := False;
Form := TInputQueryForm.CreateNew(Application);
try
Form.FCloseQueryFunc :=
function: Boolean
var
I, J: Integer;
LValues: array of string;
Control: TFmxObject;
begin
Result := True;
if Assigned(CloseQueryFunc) then
begin
SetLength(LValues, PromptCount);
J := 0;
for I := 0 to Form.ChildrenCount - 1 do
begin
Control := Form.Children[I];
if Control is TEdit then
begin
LValues[J] := TEdit(Control).Text;
Inc(J);
end;
end;
Result := CloseQueryFunc(LValues);
end;
end;
// Form.Canvas.Font.As := Form.Font;
DialogUnits := GetAveCharSize(Form.Canvas);
MaxPromptWidth := GetMaxPromptWidth(Form.Canvas);
Form.BorderStyle := TFmxFormBorderStyle.bsSingle;
Form.BorderIcons := [TBorderIcon.biSystemMenu];
Form.Caption := ACaption;
Form.ClientWidth := (180 + MaxPromptWidth) * DialogUnits.X div 4;
// Form.PopupMode := pmAuto;
Form.Position := TFormPosition.poScreenCenter;
CurPrompt := 8 * DialogUnits.Y div 8;
Edit := nil;
for I := 0 to PromptCount - 1 do
begin
Prompt := TLabel.Create(Form);
Prompt.Parent := Form;
Prompt.Text := GetPromptCaption(APrompts[I]);
Prompt.TextAlign := TTextAlign.taLeading;
Prompt.VertTextAlign := TTextAlign.taLeading;
Prompt.Position.X := 8 * DialogUnits.X div 4;
Prompt.Position.Y := CurPrompt;
Prompt.VertTextAlign := TTextAlign.taLeading;
// Prompt.Constraints.MaxWidth := MaxPromptWidth;
Prompt.WordWrap := True;
Edit := TEdit.Create(Form);
Edit.Parent := Form;
Edit.Password := GetPasswordChar(APrompts[I]) <> #0;
Edit.ApplyStyleLookup;
Edit.Position.X := Prompt.Position.X + MaxPromptWidth;
Edit.Position.Y := Prompt.Position.Y - Edit.ContentRect.TopLeft.Y;
Edit.Width := Form.ClientWidth - Edit.Position.X - (8 * DialogUnits.X / 4);
Edit.MaxLength := 255;
Edit.VertTextAlign := TTextAlign.taLeading;
Edit.Height := Edit.Height - 1;
Edit.Text := AValues[I];
Edit.SelectAll;
Form.ActiveControl := Edit;
CurPrompt := Round(Prompt.Position.Y + Edit.Height + 5);
end;
ButtonTop := Edit.Position.Y + Edit.Height + 15;
ButtonWidth := 50 * DialogUnits.X div 4;
ButtonHeight := 14 * DialogUnits.Y div 8;
Button := TButton.Create(Form);
Button.Parent := Form;
Button.Text := SMsgDlgOK;
Button.ModalResult := mrOk;
Button.Default := True;
Button.SetBounds(Form.ClientWidth - (ButtonWidth + (8 * DialogUnits.X div 4)) * 2.0, ButtonTop, ButtonWidth, ButtonHeight);
Button := TButton.Create(Form);
Button.Parent := Form;
Button.Text := SMsgDlgCancel;
Button.ModalResult := mrCancel;
Button.Cancel := True;
Button.SetBounds(Form.ClientWidth - (ButtonWidth + (8 * DialogUnits.X div 4)), ButtonTop, ButtonWidth, ButtonHeight);
Form.ClientHeight := Trunc(Button.Position.Y + Button.Height + 13);
if Form.ShowModal = mrOk then
begin
J := 0;
for I := 0 to Form.ChildrenCount - 1 do
if Form.Children[I] is TEdit then
begin
Edit := TEdit(Form.Children[I]);
AValues[J] := Edit.Text;
Inc(J);
end;
Result := True;
end;
finally
if Assigned(Form) then
FreeAndNil(Form);
end;
end;
end.
|
(*$B+*)
PROGRAM SequentialSearch;
FUNCTION IsElement(VAR a: ARRAY OF INTEGER; x: INTEGER): BOOLEAN;
VAR i: INTEGER;
elementFound: BOOLEAN;
BEGIN
i := 0;
WHILE (i <= High(a)) AND (elementFound = FALSE) DO BEGIN
IF a[i] = x THEN BEGIN
elementFound := TRUE;
i := High(a);
END
ELSE BEGIN
i := i + 1;
END;
END;
IsElement := elementFound;
END;
VAR test: ARRAY[0..5] OF INTEGER;
BEGIN
test[0] := 15;
test[1] := 18;
test[2] := 3;
test[3] := 1180;
test[4] := 84;
test[5] := 2;
WriteLn(IsElement(test, 18));
WriteLn(IsElement(test, 17));
END. |
(*
ENUNCIADO
Faça um programa em Free Pascal que leia o número N, 1 <= N <= 20 e em seguida leia os nomes dos N times que participaram
do campeonato de um certo ano. Em seguida leia a pontuação respectiva que cada um dos times obteve naquele campeonato,
supondo (para simplificar) que nenhum time obteve a mesma pontuação.
Seu programa deve imprimir o nome do campeão, isto é, o que teve a maior pontuação.
No Free Pascal, nomes (ou frases) podem ser manipulados usando-se o tipo predefinido string.
Considere que os nomes dos times não ultrapassam 20 caracteres, por isso pode usar o tipo string20.
Neste tipo você pode ler os nomes a partir do teclado como se fossem números, mas para não gerar erros de compilação,
substitua todos os seus comandos read por readln, senão seu programa pode gerar erros de execução (runtime error)
por causa do modo como o compilador lida com o ENTER.
Exemplo do uso do tipo string:
-------------------------------------------------------------
var x, y: string[20];
begin
readln (x);
readln (y);
if x = y then
writeln ('os nomes sao iguais')
else
writeln ('o nome ',x,' eh diferente do nome ',y);
end.
-------------------------------------------------------------
Ou ainda:
-------------------------------------------------------------
var x, y: string[20];
begin
x:= 'algoritmos 1';
y:= 'computacao';
if x = y then
writeln ('os nomes sao iguais')
else
writeln ('o nome ',x,' eh diferente do nome ',y);
end.
--------------------------------------------------------------
então x < y, pois o Free Pascal usa ordenação lexicográfica para isso.
Exemplo de entrada:
5
XV de Piracicaba
Ferroviaria
Botafogo-RP
Sao Carlense
XV de Jau
75
47
68
82
56
Saida esperada:
O campeao eh o Sao Carlense
*)
program 3campeonato;
const
max = 20;
type
meuvetor = array [1 .. max] of string[20];
meuvetor2 = array [1 .. max] of integer;
var
nomes:meuvetor; pontos:meuvetor2;
indice,n:integer;
procedure ler(n:integer;var nomes: meuvetor;var pontos: meuvetor2);
var
cont: integer;
begin
if (n>=1) and (n<=20) then
begin
for cont:=1 to n do
readln(nomes[cont]);
for cont:=1 to n do
readln(pontos[cont]);
end;
end;
function maior(n:integer;pontos:meuvetor2):integer;
var
i, cont:integer;
begin
i:=1;
for cont:=2 to n-1 do
begin
if (pontos[cont] > pontos[i]) then
maior:= cont;
i:=i+1;
end;
end;
begin
readln(n);
ler(n,nomes,pontos);
indice := maior(n,pontos);
write('O campeao eh o ', nomes[indice]);
end.
|
unit ChatFacade;
interface
uses
Firebase.Interfaces, Firebase.Database, System.SysUtils, Generics.Collections,
System.Threading, System.JSON,
// Novas implementações
System.SyncObjs, IdSync;
type
TLog = class(TIdNotify)
protected
FArg: string;
FMsg: string;
procedure DoNotify; override;
public
class procedure LogMsg(const aArq, aMsg: string);
end;
TChatMessage = class(TObject)
private
FMsg: string;
FUsername: string;
FTimeStamp: TDateTime;
procedure SetMsg(const Value: string);
procedure SetUsername(const Value: string);
procedure SetTimeStamp(const Value: TDateTime);
public
property Username: string read FUsername write SetUsername;
property Msg: string read FMsg write SetMsg;
property TimeStamp: TDateTime read FTimeStamp write SetTimeStamp;
end;
TChatFile = class(TObject)
private
FUsername: string;
FFileName: string;
FPosition: string;
FFileStream: string;
FTimeStamp: TDateTime;
procedure SetUsername(const Value: string);
procedure SetFileName(const Value: string);
procedure SetPosition(const Value: string);
procedure SetFileStream(const Value: string);
procedure SetTimeStamp(const Value: TDateTime);
public
property Username: string read FUsername write SetUsername;
property FileName: string read FFileName write SetFileName;
property Position: string read FPosition write SetPosition;
property FileStream: string read FFileStream write SetFileStream;
property TimeStamp: TDateTime read FTimeStamp write SetTimeStamp;
end;
IFirebaseChatFacade = interface
['{84BAC826-AF2A-4422-A98F-53382119A693}']
procedure SetBaseURI(const AURI: string);
procedure SetToken(const AToken: string);
procedure SetUsername(const AUsername: string);
procedure SendScreen(PosX, PosY: integer; AFileStream: string);
procedure SendMessage(AMessage: string);
procedure SetOnNewMessage(AProc: TProc<TChatMessage>);
procedure SetOnNewScreen(AProc: TProc<TChatFile>);
procedure StartListenChat;
procedure StartListenScreen;
procedure StopListenChat;
procedure DeleteOlderChat;
end;
TFirebaseChatFacade = class(TInterfacedObject, IFirebaseChatFacade)
private
FMessages: TDictionary<string, TChatMessage>;
FScreens: TDictionary<string, TChatFile>;
FBaseURI: string;
FUsername: string;
FOnNewMessage: TProc<TChatMessage>;
FOnNewScreen: TProc<TChatFile>;
Run: Boolean;
FToken: string;
// Novas Implementações
FCritical: TCriticalSection;
procedure ParseResponseScr(AResp: IFirebaseResponse);
procedure ParseResponseMsg(AResp: IFirebaseResponse);
procedure RemoveOlderMessage;
procedure RemoveOlderFiles;
procedure SetBaseURI(const Value: string);
procedure SetUsername(const Value: string);
procedure OnNewMessage(AChatMsg: TChatMessage);
procedure OnNewScreen(AChatFile: TChatFile);
procedure SetToken(const Value: string);
public
constructor Create;
destructor Destroy; override;
property BaseURI: string read FBaseURI write SetBaseURI;
property Username: string read FUsername write SetUsername;
property Token: string read FToken write SetToken;
procedure SetOnNewMessage(AProc: TProc<TChatMessage>);
procedure SetOnNewScreen(AProc: TProc<TChatFile>);
procedure SendScreen(PosX, PosY: integer; AFileStream: string);
procedure SendMessage(AMessage: string);
procedure StartListenChat;
procedure StartListenScreen;
procedure StopListenChat;
procedure DeleteOlderChat;
end;
implementation
uses
System.Classes;
type
TChatParser = class(TObject)
class function GetMessage(AObj: TJSONObject): TChatMessage;
class function GetJSON(AChatMessage: TChatMessage): TJSONObject; overload;
class function GetJSON(AUsername: string; AMessage: string): TJSONObject; overload;
end;
TScreenParser = class(TObject)
class function GetScreen(APosicao: string; AObj: TJSONObject): TChatFile;
class function GetJSONScreen(AChatFile: TChatFile): TJSONObject; overload;
class function GetJSONScreen(AFileStream: string): TJSONObject; overload;
end;
{ TFirebaseChatFacade }
constructor TFirebaseChatFacade.Create;
begin
inherited Create;
FMessages := TDictionary<string, TChatMessage>.Create;
FScreens := TDictionary<string, TChatFile>.Create;
// Novas Implementações
FCritical := TCriticalSection.Create;
end;
destructor TFirebaseChatFacade.Destroy;
var
I: integer;
begin
Run := false;
for I := 0 to 2 do
TThread.Sleep(50);
if Assigned(FMessages) then
FMessages.Free;
if Assigned(FScreens) then
FScreens.Free;
// Novas Implementações
if Assigned(FCritical) then
FCritical.Free;
inherited;
end;
procedure TFirebaseChatFacade.OnNewMessage(AChatMsg: TChatMessage);
begin
TThread.Queue(nil,
procedure
begin
FOnNewMessage(AChatMsg);
end);
end;
procedure TFirebaseChatFacade.OnNewScreen(AChatFile: TChatFile);
begin
TThread.Queue(nil,
procedure
begin
FOnNewScreen(AChatFile);
end);
end;
procedure TFirebaseChatFacade.ParseResponseMsg(AResp: IFirebaseResponse);
var
Obj: TJSONObject;
I: integer;
Key: string;
ChatMsg: TChatMessage;
JSONResp: TJSONValue;
begin
// TLog.LogMsg('uChatFacade', AResp.ContentAsString);
JSONResp := TJSONObject.ParseJSONValue(AResp.ContentAsString);
if (not Assigned(JSONResp)) or (not(JSONResp is TJSONObject)) then
begin
if Assigned(JSONResp) then
JSONResp.Free;
exit;
end;
Obj := JSONResp as TJSONObject;
try
// TMonitor.Enter(FScreens);
FCritical.Enter;
try
for I := 0 to Obj.Count - 1 do
begin
Key := Obj.Pairs[I].JsonString.Value;
if not FMessages.ContainsKey(Key) then
begin
ChatMsg := TChatParser.GetMessage(Obj.Pairs[I].JsonValue as TJSONObject);
FMessages.Add(Key, ChatMsg);
OnNewMessage(ChatMsg);
RemoveOlderMessage;
end;
end;
finally
// TMonitor.exit(FScreens);
FCritical.Release;
end;
finally
Obj.Free;
end;
end;
procedure TFirebaseChatFacade.ParseResponseScr(AResp: IFirebaseResponse);
var
Obj, Obj2: TJSONObject;
I: integer;
Key, Posicao: string;
ChatFile: TChatFile;
JSONRespScr: TJSONValue;
X: integer;
begin
JSONRespScr := TJSONObject.ParseJSONValue(AResp.ContentAsString);
if (not Assigned(JSONRespScr)) or (not(JSONRespScr is TJSONObject)) then
begin
if Assigned(JSONRespScr) then
JSONRespScr.Free;
exit;
end;
Obj := JSONRespScr as TJSONObject;
try
TMonitor.Enter(FScreens);
// FCritical.Enter;
try
for I := 0 to Obj.Count - 1 do
begin
Posicao := Obj.Pairs[I].JsonString.Value;
Obj2 := Obj.Pairs[I].JsonValue as TJSONObject;
for X := 0 to Obj2.Count - 1 do
begin
Key := Obj2.Pairs[X].JsonString.Value;
if not FScreens.ContainsKey(Key) then // Verificar as Keys que precisa atualizar
begin
try
delete(Posicao, 1, 1);
ChatFile := TScreenParser.GetScreen(Posicao, Obj2.Pairs[X].JsonValue as TJSONObject);
FScreens.Add(Key, ChatFile);
OnNewScreen(ChatFile);
// RemoveOlderFiles;
except
end;
end;
end;
end;
finally
TMonitor.exit(FScreens);
// FCritical.Release;
end;
finally
Obj.Free;
end;
end;
procedure TFirebaseChatFacade.RemoveOlderMessage;
var
Pair: TPair<string, TChatMessage>;
Older: TDateTime;
ToDelete: string;
begin
TMonitor.Enter(FMessages);
try
if FMessages.Count < 20 then
exit;
Older := Now;
for Pair in FMessages do
if Pair.Value.TimeStamp < Older then
begin
Older := Pair.Value.TimeStamp;
ToDelete := Pair.Key;
end;
if not ToDelete.IsEmpty then
FMessages.Remove(ToDelete);
finally
TMonitor.exit(FMessages);
end;
end;
procedure TFirebaseChatFacade.RemoveOlderFiles;
var
Pair: TPair<string, TChatFile>;
Older: TDateTime;
ToDelete: string;
begin
TMonitor.Enter(FScreens);
try
if FScreens.Count < 162 then
exit;
Older := Now;
for Pair in FScreens do
if Pair.Value.TimeStamp < Older then
begin
Older := Pair.Value.TimeStamp;
ToDelete := Pair.Key;
end;
if not ToDelete.IsEmpty then
FScreens.Remove(ToDelete);
finally
TMonitor.exit(FScreens);
end;
end;
procedure TFirebaseChatFacade.SendScreen(PosX, PosY: integer; AFileStream: string);
begin
TTask.Run(
procedure
var
FFC: IFirebaseDatabase;
ToSend: TJSONObject;
QueryParams: TDictionary<string, string>;
begin
FFC := TFirebaseDatabase.Create;
FFC.SetBaseURI(FBaseURI);
FFC.SetToken(FToken);
ToSend := TScreenParser.GetJSONScreen(AFileStream);
QueryParams := TDictionary<string, string>.Create;
FFC.delete(['screen/a' + IntToStr(PosX) + IntToStr(PosY) + '.json'], QueryParams);
FFC.Post(['screen/a' + IntToStr(PosX) + IntToStr(PosY) + '.json'], ToSend);
end);
end;
procedure TFirebaseChatFacade.SendMessage(AMessage: string);
begin
TTask.Run(
procedure
var
FFC: IFirebaseDatabase;
ToSend: TJSONObject;
begin
FFC := TFirebaseDatabase.Create;
FFC.SetBaseURI(FBaseURI);
FFC.SetToken(FToken);
ToSend := TChatParser.GetJSON(FUsername, AMessage);
FFC.Post(['msg.json'], ToSend);
end);
end;
procedure TFirebaseChatFacade.SetBaseURI(const Value: string);
begin
FBaseURI := Value;
end;
procedure TFirebaseChatFacade.SetOnNewMessage(AProc: TProc<TChatMessage>);
begin
FOnNewMessage := AProc;
end;
procedure TFirebaseChatFacade.SetOnNewScreen(AProc: TProc<TChatFile>);
begin
FOnNewScreen := AProc;
end;
procedure TFirebaseChatFacade.SetToken(const Value: string);
begin
FToken := Value;
end;
procedure TFirebaseChatFacade.SetUsername(const Value: string);
begin
FUsername := Value;
end;
procedure TFirebaseChatFacade.StartListenChat;
begin
Run := true;
TTask.Run(
procedure
var
FFC: IFirebaseDatabase;
Response: IFirebaseResponse;
I: integer;
QueryParams: TDictionary<string, string>;
begin
FFC := TFirebaseDatabase.Create;
FFC.SetBaseURI(FBaseURI);
FFC.SetToken(FToken);
QueryParams := TDictionary<string, string>.Create;
try
QueryParams.Add('orderBy', '"$key"');
QueryParams.Add('limitToLast', '20');
while Run do
begin
Response := FFC.Get(['msg.json'], QueryParams);
ParseResponseMsg(Response);
TThread.Sleep(200);
end;
finally
QueryParams.Free;
end;
end);
end;
procedure TFirebaseChatFacade.StartListenScreen;
begin
Run := true;
TTask.Run(
procedure
var
FFC: IFirebaseDatabase;
Response: IFirebaseResponse;
I: integer;
QueryParams: TDictionary<string, string>;
begin
FFC := TFirebaseDatabase.Create;
FFC.SetBaseURI(FBaseURI);
FFC.SetToken(FToken);
QueryParams := TDictionary<string, string>.Create;
try
QueryParams.Add('orderBy', '"$key"');
QueryParams.Add('limitToLast', '60');
while Run do
begin
Response := FFC.Get(['screen.json'], QueryParams);
ParseResponseScr(Response);
TThread.Sleep(250);
end;
finally
QueryParams.Free;
end;
end);
end;
procedure TFirebaseChatFacade.DeleteOlderChat;
begin
Run := true;
TTask.Run(
procedure
var
FFC: IFirebaseDatabase;
Response: IFirebaseResponse;
I: integer;
QueryParams: TDictionary<string, string>;
begin
FFC := TFirebaseDatabase.Create;
FFC.SetBaseURI(FBaseURI);
FFC.SetToken(FToken);
QueryParams := TDictionary<string, string>.Create;
try
// QueryParams.Add('orderBy', '"$key"');
// QueryParams.Add('limitToLast', '1');
while Run do
begin
Response := FFC.delete(['.json'], QueryParams);
ParseResponseMsg(Response);
TThread.Sleep(30000);
end;
finally
QueryParams.Free;
end;
end);
end;
procedure TFirebaseChatFacade.StopListenChat;
begin
Run := false;
end;
{ TChatMessage }
procedure TChatMessage.SetMsg(const Value: string);
begin
FMsg := Value;
end;
procedure TChatMessage.SetTimeStamp(const Value: TDateTime);
begin
FTimeStamp := Value;
end;
procedure TChatMessage.SetUsername(const Value: string);
begin
FUsername := Value;
end;
{ TChatFile }
procedure TChatFile.SetFileName(const Value: string);
begin
FFileName := Value;
end;
procedure TChatFile.SetFileStream(const Value: string);
begin
FFileStream := Value;
end;
procedure TChatFile.SetPosition(const Value: string);
begin
FPosition := Value;
end;
procedure TChatFile.SetTimeStamp(const Value: TDateTime);
begin
FTimeStamp := Value;
end;
procedure TChatFile.SetUsername(const Value: string);
begin
FUsername := Value;
end;
{ TChatParser }
class function TChatParser.GetJSON(AChatMessage: TChatMessage): TJSONObject;
begin
Result := TJSONObject.Create;
Result.AddPair('name', AChatMessage.Username);
Result.AddPair('text', AChatMessage.Msg);
end;
class function TChatParser.GetJSON(AUsername, AMessage: string): TJSONObject;
var
ChatMsg: TChatMessage;
begin
ChatMsg := TChatMessage.Create;
try
ChatMsg.Username := AUsername;
ChatMsg.Msg := AMessage;
Result := TChatParser.GetJSON(ChatMsg);
finally
ChatMsg.Free;
end;
end;
class function TChatParser.GetMessage(AObj: TJSONObject): TChatMessage;
begin
Result := TChatMessage.Create;
Result.Username := AObj.Values['name'].Value;
Result.Msg := AObj.Values['text'].Value;
Result.TimeStamp := Now;
end;
{ TScreenParser }
class function TScreenParser.GetJSONScreen(AChatFile: TChatFile): TJSONObject;
begin
Result := TJSONObject.Create;
Result.AddPair('filestream', AChatFile.FileStream);
end;
class function TScreenParser.GetJSONScreen(AFileStream: string): TJSONObject;
var
ChatFile: TChatFile;
begin
ChatFile := TChatFile.Create;
try
ChatFile.FileStream := AFileStream;
Result := TScreenParser.GetJSONScreen(ChatFile);
finally
ChatFile.Free;
end;
end;
class function TScreenParser.GetScreen(APosicao: string; AObj: TJSONObject): TChatFile;
begin
Result := TChatFile.Create;
Result.Position := APosicao;
Result.FileStream := AObj.Values['filestream'].Value;
Result.TimeStamp := Now;
end;
{ TLog }
procedure TLog.DoNotify;
var
Log: TextFile;
arquivo: string;
dirlog: string;
begin
try
dirlog := IncludeTrailingPathDelimiter(ExtractFilePath(ParamStr(0))) + 'log';
arquivo := dirlog + '\_' + formatdatetime('ddmmyy', date) + '_' + FArg + '.txt';
if not DirectoryExists(dirlog) then
ForceDirectories(dirlog);
AssignFile(Log, arquivo);
if FileExists(arquivo) then
Append(Log)
else
ReWrite(Log);
try
WriteLn(Log, TimeToStr(Now) + ' - :' + FMsg);
finally
CloseFile(Log)
end;
except
raise Exception.Create('ERRO NA GERAÇÃO DO LOG');
end;
end;
class procedure TLog.LogMsg(const aArq, aMsg: string);
begin
with TLog.Create do
try
FArg := aArq;
FMsg := aMsg;
Notify;
except
Free;
raise;
end;
end;
end.
|
unit UFormParser;
(***** Code Written By Huang YanLai *****)
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
CommParser, Scanner,contnrs,stdctrls,ExtCtrls,Buttons,KSCtrls, ExtDialogs;
type
TUIObjectParam = (pNone,pLeft,pTop,pRight,pBottom,pColor,pBKColor,pCaption);
const
maxParams = ord(pCaption)-ord(pNone)+1;
type
TUIItemClass = class of TUIItem;
TUIObjectParams = Array[0..maxParams-1] of TUIObjectParam;
TClassMethodParams = record
className : string;
methodName : string;
params : TUIObjectParams;
itemClass : TUIItemClass;
end;
TUIObject = class
public
objname, className : string;
left,top,right,bottom : integer;
caption : string;
color, bkcolor : TColor;
isForm : boolean;
formIndex : integer;
constructor Create;
end;
TUIItem = class(TUIObject)
public
end;
//TUIItemClass = class of TUIItem;
TUIItemsObject = class(TUIObject)
private
FItems : TObjectList;
function GetItems(index: integer): TUIItem;
public
property Items[index : integer] : TUIItem read GetItems;
constructor Create;
Destructor Destroy;override;
function addItem : TUIItem;
procedure add(item : TUIItem);
function count : integer;
end;
TUIObjects = class(TObjectList)
private
function GetItems(index: integer): TUIObject;
public
function add:TUIObject;
function addItems: TUIItemsObject;
property Items[index:integer] : TUIObject read GetItems; default;
function findObj(const aname:string): TUIObject;
function getForm : TUIObject;
end;
TdmFormParser = class(TCommonParser)
SaveDialog: TOpenDialogEx;
procedure ScannerTokenRead(Sender: TObject; Token: TToken;
var AddToList, Stop: Boolean);
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
private
{ Private declarations }
UIObjects : TUIObjects;
UIFormClasses : TStringList;
CureentFormClass : integer;
protected
procedure analyseToken; override;
procedure beforeExecute; override;
procedure processMethod(obj : TUIObject; const Params: Array of TUIObjectParam);
procedure reportInfo; override;
procedure setObjBounds(ctrl : TControl; UIObj : TUIObject; delY:integer=0);
function getFormClassIndex(const className:string): integer;
function generateOneForm(formIndex : integer):TForm;
public
{ Public declarations }
// generate a delphi form from UIObjects
procedure generateForm(const pasFile:string; autoFileName:boolean=false; isShowForm:boolean=true);
end;
var
dmFormParser: TdmFormParser;
type
TUIConv = record
className : string;
Class1,Class2 : TControlClass;
end;
const
// symbol tags
stMember = 1; // ->
stDefine = 2; // ::
AllUIConvCount = 12;
AllUIConvs : array[0..AllUIConvCount-1] of TUIConv
= (
(className : 'CButton'; class1:TKSButton; class2:nil),
(className : 'CEdit'; class1:TKSLabel; class2:TKSEdit),
(className : 'CF2Edit'; class1:TKSLabel; class2:TKSSwitchEdit),
(className : 'CListEdit'; class1:TKSLabel; class2:TKSListEdit),
(className : 'CDateEdit'; class1:TKSLabel; class2:TKSDateEdit),
(className : 'CCheckBox'; class1:TKSCheckBox; class2:nil),
(className : 'CDBGrid'; class1:TKSDBGrid; class2:nil),
(className : 'CText'; class1:TKSMemo; class2:nil),
(className : 'CDBText'; class1:TKSDBMemo; class2:nil),
(className : 'CList'; class1:TKSPanel; class2:nil),
(className : 'CComboBox'; class1:TKSLabel; class2:TKSComboBox),
(className : 'CPanel'; class1:TKSPanel; class2:nil)
);
AllItemsClasseCount = 4;
AllItemsClasses : array[0..AllItemsClasseCount-1] of string
= ('CPanel','CDBGrid','CF2Edit','CList');
AllClassMethodCount = 17;
AllClassMethodParams : Array[0..AllClassMethodCount-1] of TClassMethodParams
=(
(className:'CButton';methodName:'Create';params:(pNone,pLeft,pTop,pRight,pBottom,pCaption,pNone,pNone);itemClass:nil),
(className:'CEdit';methodName:'Create';params:(pNone,pLeft,pTop,pRight,pBottom,pCaption,pNone,pNone);itemClass:nil),
(className:'CF2Edit';methodName:'Create';params:(pNone,pLeft,pTop,pRight,pBottom,pCaption,pNone,pNone);itemClass:nil),
(className:'CF2Edit';methodName:'AddItem';params:(pCaption,pNone,pNone,pNone,pNone,pNone,pNone,pNone);itemClass:TUIItem),
(className:'CListEdit';methodName:'Create';params:(pNone,pLeft,pTop,pRight,pBottom,pCaption,pNone,pNone);itemClass:nil),
(className:'CDateEdit';methodName:'Create';params:(pNone,pLeft,pTop,pRight,pBottom,pCaption,pNone,pNone);itemClass:nil),
(className:'CCheckBox';methodName:'Create';params:(pNone,pLeft,pTop,pRight,pBottom,pNone,pNone,pNone);itemClass:nil),
(className:'CListCheckBox';methodName:'Create';params:(pNone,pLeft,pTop,pRight,pBottom,pNone,pNone,pNone);itemClass:nil),
(className:'CDBGrid';methodName:'Create';params:(pNone,pLeft,pTop,pRight,pBottom,pNone,pNone,pNone);itemClass:nil),
(className:'CDBGrid';methodName:'AddField';params:(pCaption,pNone,pNone,pNone,pNone,pNone,pNone,pNone);itemClass:TUIItem),
(className:'CText';methodName:'Create';params:(pNone,pLeft,pTop,pRight,pBottom,pNone,pNone,pNone);itemClass:nil),
(className:'CDBText';methodName:'Create';params:(pNone,pLeft,pTop,pRight,pBottom,pNone,pNone,pNone);itemClass:nil),
(className:'CList';methodName:'Create';params:(pNone,pLeft,pTop,pRight,pBottom,pNone,pNone,pNone);itemClass:nil),
(className:'CList';methodName:'AddField';params:(pLeft,pTop,pCaption,pNone,pNone,pNone,pNone,pNone);itemClass:TUIItem),
(className:'CComboBox';methodName:'Create';params:(pNone,pLeft,pTop,pRight,pBottom,pCaption,pNone,pNone);itemClass:nil),
(className:'CPanel';methodName:'Create';params:(pNone,pLeft,pTop,pRight,pBottom,pNone,pNone,pNone);itemClass:nil),
(className:'CPanel';methodName:'ViewCaption';params:(pCaption,pLeft,pTop,pNone,pNone,pNone,pNone,pNone);itemClass:TUIItem)
);
TitleHeight = 24;
implementation
uses ProgDlg2,FrmFileGen,DBGrids,ExtUtils;
{$R *.DFM}
function isItemsClass(const className:string):boolean;
var
i : integer;
begin
result := true;
for i:=0 to AllItemsClasseCount-1 do
if AllItemsClasses[i]=className then exit;
result := false;
end;
// filter the Prefix of objName
function filterPrefix(const objName:string):string;
var
i,j,k : integer;
begin
k:=0;
j:=length(objName);
for i:=1 to j do
begin
if (objName[i]>='A') and (objName[i]<='Z') then
begin
k:=i;
break;
end;
end;
if (k>=1) and (k<j) then
result := copy(objName,k,j) else
result := objName;
end;
{ TUIObject }
constructor TUIObject.Create;
begin
formIndex := -1;
isForm:=false;
end;
{ TUIObjects }
function TUIObjects.add: TUIObject;
begin
result := TUIObject.create;
inherited add(result);
end;
function TUIObjects.addItems: TUIItemsObject;
begin
result := TUIItemsObject.create;
inherited add(result);
end;
function TUIObjects.findObj(const aname: string): TUIObject;
var
i : integer;
begin
for i:=count-1 downto 0 do
begin
result :=items[i];
if result.objname=aname then
exit;
end;
result := nil;
end;
function TUIObjects.getForm: TUIObject;
var
i : integer;
begin
for i:=count-1 downto 0 do
begin
result :=items[i];
if result.isForm then
exit;
end;
result := nil;
end;
function TUIObjects.GetItems(index: integer): TUIObject;
begin
result := TUIObject(inherited items[index]);
end;
{ TUIItemsObject }
procedure TUIItemsObject.add(item: TUIItem);
begin
FItems.add(item);
end;
function TUIItemsObject.addItem: TUIItem;
begin
result := TUIItem.create;
FItems.add(result);
end;
function TUIItemsObject.count: integer;
begin
result := FItems.count;
end;
constructor TUIItemsObject.Create;
begin
inherited;
FItems := TObjectList.create;
end;
destructor TUIItemsObject.Destroy;
begin
FItems.free;
inherited;
end;
function TUIItemsObject.GetItems(index: integer): TUIItem;
begin
result := TUIItem(FItems[index]);
end;
{ TdmFormParser }
procedure TdmFormParser.analyseToken;
var
i : integer;
t1,t2 : TToken;
objname,methodname,classname,parentClass : string;
UIObj : TUIObject;
Item : TUIItem;
begin
if isKeyword(token,'class') then
begin
t1 := nextToken;
className := getIdentifier(t1);
if className<>'' then
begin
nextToken; // skip :
nextToken; // skip public
t2 := nextToken; // parent class
parentClass := getIdentifier(t2);
if parentClass='CForm' then
UIFormClasses.add(className);
end;
end
else if (token.Token=ttSpecialChar) and (token.tag=stDefine) and (FTokenSeq>=2) then
begin
t1 := Scanner.Token[FTokenSeq-2];
className := getIdentifier(t1);
CureentFormClass := getFormClassIndex(className);
end
else if isKeyword(token,'new') then
begin
if FTokenSeq>=3 then
begin
// process: obj = new(className)
t1 := Scanner.Token[FTokenSeq-3]; // iden
t2 := Scanner.Token[FTokenSeq-2]; // =
objname:= getIdentifier(t1);
if (objname<>'') and (isSymbol(t2,'=')) then
begin
t2:=nextToken;
if isSymbol(t2,'(') then
t2:=nextToken;
classname:=getIdentifier(t2);
if classname<>'' then
begin
// find : obj = new(className)
//Freporter.addInfo(objname+'=new '+className);
if isItemsClass(classname) then
UIObj := UIObjects.addItems else
UIObj := UIObjects.add;
UIObj.className := classname;
UIObj.objname := objName;
UIObj.formIndex := CureentFormClass;
t2:=nextToken;
if isSymbol(t2,')') then
t2:=nextToken;
if isSymbol(t2,'(') then
begin
UIObj.formIndex := getFormClassIndex(UIObj.className);
UIObj.isForm:=UIObj.formIndex>=0;
if UIObj.isForm then processMethod(UIObj,[pLeft,pTop,pRight,pBottom,pCaption]);
end;
dlgProgress.checkCanceled;
end;
end;
end;
end
else if (token.Token=ttSpecialChar) and (token.tag=stMember) and (FTokenSeq>=2) then
begin
// process: obj->method
t1 := Scanner.Token[FTokenSeq-2];
objname := getIdentifier(t1);
t2 := nextToken;
methodname:=getIdentifier(t2);
t2 := nextToken;
if (objname<>'') and (methodname<>'') and isSymbol(t2,'(') then
begin
//Freporter.addInfo(objname+'->'+methodName);
dlgProgress.checkCanceled;
UIObj := UIObjects.findObj(objname);
if UIObj<>nil then
begin
className := UIObj.className;
for i:=0 to AllClassMethodCount-1 do
if (AllClassMethodParams[i].className=className)
and (AllClassMethodParams[i].methodName=methodName) then
begin
if (UIObj is TUIItemsObject) and (AllClassMethodParams[i].itemClass<>nil) then
begin
Item := AllClassMethodParams[i].itemClass.create;
TUIItemsObject(UIObj).add(item);
processMethod(item,AllClassMethodParams[i].params);
end
else
processMethod(UIObj,AllClassMethodParams[i].params);
end;
end;
end;
end;
end;
procedure TdmFormParser.ScannerTokenRead(Sender: TObject; Token: TToken;
var AddToList, Stop: Boolean);
var
i : integer;
t1 : TToken;
procedure check;
begin
dlgProgress.setInfo('Read Lines:'+IntToStr(Token.Row));
dlgProgress.checkCanceled;
end;
begin
inherited;
i:=Scanner.Count;
AddToList:=true;
stop:=false;
if i>0 then
begin
t1 := Scanner.Token[i-1];
if isSymbol(token,'>') and isSymbol(t1,'-') then
begin
t1.Text:='->';
t1.tag := stMember;
AddToList:=false;
check;
end
else if isSymbol(token,':') and isSymbol(t1,':') then
begin
t1.Text:='::';
t1.tag := stDefine;
AddToList:=false;
check;
end
end;
end;
procedure TdmFormParser.DataModuleCreate(Sender: TObject);
begin
inherited;
UIObjects := TUIObjects.create;
UIFormClasses := TStringList.create;
end;
procedure TdmFormParser.DataModuleDestroy(Sender: TObject);
begin
UIFormClasses.free;
UIObjects.free;
inherited;
end;
procedure TdmFormParser.beforeExecute;
begin
inherited;
UIObjects.Clear;
UIFormClasses.Clear;
CureentFormClass := -1;
end;
procedure TdmFormParser.processMethod(obj: TUIObject;
const Params: array of TUIObjectParam);
var
i : integer;
t : TToken;
begin
for i:=low(Params) to high(Params) do
begin
repeat
t:=nextToken;
if isSymbol(t,')') then exit;
until not isSymbol(t,',');
case Params[i] of
pNone: ;
pLeft: if t.token=ttInteger then obj.left:=StrToInt(t.text);
pTop: if t.token=ttInteger then obj.top:=StrToInt(t.text);
pRight: if t.token=ttInteger then obj.right:=StrToInt(t.text);
pBottom: if t.token=ttInteger then obj.bottom:=StrToInt(t.text);
pColor: ;
pBKColor: ;
pCaption: if t.token=ttString then obj.caption:=t.text;
end;
end;
end;
procedure TdmFormParser.reportInfo;
var
i,j : integer;
obj : TUIObject;
item : TUIItem;
formClass : string;
begin
inherited;
if FReporter=nil then exit;
FReporter.addInfo('');
FReporter.addInfo('======= Report =======');
FReporter.addInfo('');
FReporter.addInfo('Form Classes:'+IntToSTR(UIFormClasses.count));
for i:=0 to UIFormClasses.count-1 do
FReporter.addInfo(' '+UIFormClasses[i]);
FReporter.addInfo('');
for i:=0 to UIObjects.count-1 do
begin
obj := UIObjects[i];
if not obj.isForm and (obj.formIndex>=0) then
formClass:=UIFormClasses[obj.formIndex] else
formClass:='';
with obj do
FReporter.addInfo(
format('class=%s.%s; name=%s; left=%d; top=%d; right=%d; bottom=%d,caption=%s',
[formClass,className,objName,left,top,right,bottom,caption])
);
if obj is TUIItemsObject then
begin
for j:=0 to TUIItemsObject(obj).count-1 do
begin
item := TUIItemsObject(obj).Items[j];
with item do
FReporter.addInfo(
format('child-> class=%s; name=%s; left=%d; top=%d; right=%d; bottom=%d,caption=%s',
[className,objName,left,top,right,bottom,caption])
);
end;
end;
end;
FReporter.addInfo('');
FReporter.addInfo('======= Report 2 =======');
FReporter.addInfo('');
for i:=0 to UIFormClasses.count-1 do
begin
FReporter.addInfo(' * '+UIFormClasses[i]);
for j:=0 to UIObjects.count-1 do
begin
obj := UIObjects[j];
if obj.formIndex=i then
with obj do
begin
FReporter.addInfo(
format('class=%s; name=%s; left=%d; top=%d; right=%d; bottom=%d,caption=%s',
[className,objName,left,top,right,bottom,caption])
);
end;
end;
end;
end;
type
TControlAccess = class(TControl);
procedure TdmFormParser.generateForm(const pasFile:string; autoFileName:boolean=false;
isShowForm:boolean=true);
var
i : integer;
form : TForm;
fileName : string;
saveThis : boolean;
namePart,extPart : string;
begin
SaveDialog.FileName:=pasFile;
ParseFileName(pasFile,namePart,ExtPart);
//ExtPart:='.pas';
for i:=0 to UIFormClasses.count-1 do
begin
try
form:=generateOneForm(i);
if form<>nil then
begin
if isShowForm then form.ShowModal;
saveThis := false;
if autoFileName then
begin
saveThis:=true;
if i>0 then
FileName:=NamePart+'_'+IntToStr(i)+ExtPart else
FileName:=NamePart+ExtPart;
end else
begin
SaveDialog.Title:='Save form : '+form.caption;
if SaveDialog.Execute then
begin
saveThis:=true;
fileName := SaveDialog.fileName;
end;
end;
if saveThis then
ModuleFileGen(fileName,form,'T'+form.name,'TKSForm');
end;
finally
FreeAndNil(form);
end;
end;
end;
procedure TdmFormParser.setObjBounds(ctrl: TControl; UIObj: TUIObject; delY:integer=0);
begin
ctrl.SetBounds(UIobj.left,UIobj.top+delY,UIObj.right-UIObj.left,UIObj.bottom-UIObj.top);
end;
function TdmFormParser.getFormClassIndex(const className: string): integer;
begin
result := UIFormClasses.IndexOf(className);
end;
function TdmFormParser.generateOneForm(formIndex: integer): TForm;
var
i,j,k : integer;
form : TForm;
UIobj : TUIObject;
formClass : string;
ctrl,ctrl2,child : TControl;
labelWidth : integer;
column : TColumn;
labelCaption : string;
parentName : string;
begin
Form := nil;
// found form instance
if (formIndex<0) or (formIndex>=UIFormClasses.count) then
begin
result := nil;
exit;
end;
UIobj:= nil;
for i:=0 to UIObjects.Count-1 do
begin
if (UIObjects.items[i].isForm) and (UIObjects.items[i].formIndex=formIndex) then
begin
UIobj := UIObjects.items[i];
break;
end;
end;
if UIobj=nil then
begin
result := nil;
exit;
end;
try
// create this form
form := TForm.create(Application);
form.caption := UIobj.caption;
form.name := UIobj.className;
formClass := 'T'+UIobj.className;
form.font.Name := 'ËÎÌå';
form.font.Height:= -14;
form.Scaled:=false;
form.Position := poScreenCenter;
setObjBounds(form,UIobj);
// generate children
for i:=0 to UIObjects.count-1 do
begin
UIobj:=UIObjects[i];
if not UIobj.isForm and (UIobj.formIndex=formIndex) then
begin
ctrl := nil;
ctrl2 := nil;
for k:=0 to AllUIConvCount-1 do
if AllUIConvs[k].className=UIObj.className then
begin
ctrl := AllUIConvs[k].class1.Create(Form);
if AllUIConvs[k].class2<>nil then
ctrl2:=AllUIConvs[k].class2.Create(Form);
labelCaption := UIObj.caption;
if ctrl2<>nil then
begin
if UIobj.className='CF2Edit' then
begin
if TUIItemsObject(UIobj).count>0 then
begin
labelCaption := TUIItemsObject(UIobj).items[0].caption;
end;
end;
labelWidth := length(labelCaption)*8;
ctrl.name := 'lb'+UIObj.objname;
ctrl2.name := UIObj.objname;
ctrl.SetBounds(UIobj.left,UIobj.top-TitleHeight,labelWidth,UIObj.bottom-UIObj.top);
ctrl2.SetBounds(UIobj.left+labelWidth,UIobj.top-TitleHeight,UIObj.right-UIObj.left-labelWidth,UIObj.bottom-UIObj.top);
TControlAccess(ctrl2).Text:='';
end else
begin
ctrl.name := UIobj.objname;
ctrl.setBounds(UIobj.left,UIobj.top-TitleHeight,UIObj.right-UIObj.left,UIObj.bottom-UIObj.top);
end;
TControlAccess(ctrl).Caption:=labelCaption;
break;
end; // if, for k
if ctrl=nil then continue;
Form.InsertControl(ctrl);
if ctrl2<>nil then Form.InsertControl(ctrl2);
// handle specail children generate
if (UIObj.className='CPanel') or (UIObj.className='CList') then
begin
parentName := filterPrefix(UIObj.objname);
if (UIObj.className='CList') then
begin
TKSPanel(ctrl).BevelInner := bvRaised;
TKSPanel(ctrl).BevelOuter := bvLowered;
end else
begin
TKSPanel(ctrl).BevelInner := bvNone;
TKSPanel(ctrl).BevelOuter := bvNone;
end;
for j:=0 to TUIItemsObject(UIObj).count-1 do
begin
child := TKSLabel.create(Form);
child.name := 'lb'+parentName+'_'+IntToStr(j);
with TUIItemsObject(UIObj).Items[j] do
begin
child.Left := left;
child.top := top;
TKSLabel(child).caption := caption;
end;
labelWidth := length(TKSLabel(child).caption)*8+10;
TKSPanel(ctrl).InsertControl(child);
if (UIObj.className='CList') then
begin
child := TKSDBLabel.create(Form);
child.name := 'dlb'+parentName+'_'+IntToStr(j);
with TUIItemsObject(UIObj).Items[j] do
begin
child.Left := left+labelWidth;
child.top := top;
//TKSLabel(child).caption := '';
end;
TKSPanel(ctrl).InsertControl(child);
end;
end;
end
else if UIObj.className='CF2Edit' then
begin
for j:=0 to TUIItemsObject(UIObj).count-1 do
begin
TKSSwitchEdit(Ctrl2).items.add(TUIItemsObject(UIObj).items[j].caption);
end;
end
else if UIObj.className='CDBGrid' then
begin
for j:=0 to TUIItemsObject(UIObj).count-1 do
begin
column := TKSDBGrid(ctrl).Columns.Add;
column.Title.Caption:=TUIItemsObject(UIObj).Items[j].caption;
column.Width:=length(column.Title.Caption)*8;
end;
end;
end; // if is child
end; // for i
result := form;
except
result := nil;
Form.free;
end;
end;
end.
|
{**********************************************************************************}
{ }
{ Project vkDBF - dbf ntx clipper compatibility delphi component }
{ }
{ This Source Code Form is subject to the terms of the Mozilla Public }
{ License, v. 2.0. If a copy of the MPL was not distributed with this }
{ file, You can obtain one at http://mozilla.org/MPL/2.0/. }
{ }
{ The Initial Developer of the Original Code is Vlad Karpov (KarpovVV@protek.ru). }
{ }
{ Contributors: }
{ Sergey Klochkov (HSerg@sklabs.ru) }
{ }
{ You may retrieve the latest version of this file at the Project vkDBF home page, }
{ located at http://sourceforge.net/projects/vkdbf/ }
{ }
{**********************************************************************************}
unit VKDBFMemMgr;
interface
uses
contnrs, Dialogs, syncobjs,
{$IFDEF DELPHI6} Variants, {$ENDIF}
{$IFDEF VKDBFMEMCONTROL} Windows, DB,{$ENDIF}
sysutils;
type
{TVKDBFOneAlloc}
TVKDBFOneAlloc = class
private
FMemory: Pointer;
FCaller: TObject;
FCaption: AnsiString;
FSize: Cardinal;
FmemID: Int64;
public
constructor Create; overload;
constructor Create(Caller: TObject; Caption: AnsiString; Size: Cardinal; memID: Int64); overload;
constructor Create(Caller: TObject; Size: Cardinal; memID: Int64); overload;
destructor Destroy; override;
procedure GetMem(Size: Cardinal);
procedure ReallocMem(NewSize: Cardinal);
procedure FreeMem;
property Memory: Pointer read FMemory;
property Caller: TObject read FCaller write FCaller;
property Caption: AnsiString read FCaption write FCaption;
property Size: Cardinal read FSize;
end;
{TVKDBFMemMgr}
TVKDBFMemMgr = class(TObjectList)
private
memID: Int64;
FCS: TCriticalSection;
public
constructor Create;
destructor Destroy; override;
function FindIndex(p: Pointer; out Ind: Integer): boolean;
function FindCaption(Capt: AnsiString; out Ind: Integer): boolean;
procedure FreeForCaption(Capt: AnsiString);
function GetMem(Caller: TObject; size: Integer): Pointer; overload;
function ReallocMem(p: Pointer; size: Integer): Pointer; overload;
procedure FreeMem(p: Pointer); overload;
function GetMem(Capt: AnsiString; size: Integer): Pointer; overload;
function GetSize(p: Pointer): Integer;
end;
{$IFDEF VKDBFMEMCONTROL}
//function getUseDbf: boolean;
//procedure setUseDBF(newValue: boolean);
function getUseExDbf: boolean;
procedure setUseExDBF(newValue: boolean);
{$ENDIF}
var
oMem: TVKDBFMemMgr;
{$IFDEF VKDBFMEMCONTROL}
oCS: TCriticalSection;
useDBF: Boolean;
useExDBF: Boolean;
oDBF: TDataSet;
{$ENDIF}
implementation
uses
VKDBFUtil
{$IFDEF VKDBFMEMCONTROL}
, VKDBFDataSet, VKDBFNTX, VKDBFIndex, ActiveX
{$ENDIF};
{$IFDEF VKDBFMEMCONTROL}
function Int64toVariant(value: Int64): Variant;
begin
{$IFDEF DELPHI6}
Result := value;
{$ELSE}
TVarData(Result).VType := VT_DECIMAL;
Decimal(Result).lo64 := value;
{$ENDIF}
end;
function getUseDbf: boolean;
begin
oCS.Enter;
try
Result := ( useDBF and useExDBF );
finally
oCS.Leave;
end;
end;
procedure setUseDBF(newValue: boolean);
begin
oCS.Enter;
try
useDBF := newValue;
finally
oCS.Leave;
end;
end;
function getUseExDbf: boolean;
begin
oCS.Enter;
try
Result := useExDBF;
finally
oCS.Leave;
end;
end;
procedure setUseExDBF(newValue: boolean);
begin
oCS.Enter;
try
useExDBF := newValue;
finally
oCS.Leave;
end;
end;
{$ENDIF}
{ TVKDBFMemMgr }
constructor TVKDBFMemMgr.Create;
begin
inherited Create;
FCS := TCriticalSection.Create;
memID := 10;
end;
destructor TVKDBFMemMgr.Destroy;
begin
FreeAndNil(FCS);
inherited Destroy;
end;
function TVKDBFMemMgr.FindCaption(Capt: AnsiString; out Ind: Integer): boolean;
var
i: Integer;
begin
Result := false;
Ind := -1;
for i := 0 to Count - 1 do
if TVKDBFOneAlloc(Items[i]).Caption = Capt then begin
Result := true;
Ind := i;
Exit;
end;
end;
function TVKDBFMemMgr.FindIndex(p: Pointer; out Ind: Integer): boolean;
var
B: TVKDBFOneAlloc;
beg, Mid: Integer;
begin
Ind := Count;
if ( Ind > 0 ) then begin
beg := 0;
B := TVKDBFOneAlloc(Items[beg]);
if ( Integer(p) > Integer(B.FMemory) ) then begin
repeat
Mid := (Ind + beg) div 2;
B := TVKDBFOneAlloc(Items[Mid]);
if ( Integer(p) > Integer(B.FMemory) ) then
beg := Mid
else
Ind := Mid;
until ( ((Ind - beg) div 2) = 0 );
end else
Ind := beg;
if Ind < Count then begin
B := TVKDBFOneAlloc(Items[Ind]);
Result := (Integer(p) = Integer(B.FMemory));
end else
Result := false;
end else
Result := false;
end;
procedure TVKDBFMemMgr.FreeForCaption(Capt: AnsiString);
var
i: Integer;
begin
FCS.Enter;
try
while FindCaption(Capt, i) do Delete(i);
finally
FCS.Leave
end;
end;
procedure TVKDBFMemMgr.FreeMem(p: Pointer);
var
i: Integer;
begin
FCS.Enter;
try
if (p <> nil) and FindIndex(p, i) then Delete(i);
finally
FCS.Leave
end;
end;
function TVKDBFMemMgr.GetMem(Caller: TObject; size: Integer): Pointer;
var
Obj: TVKDBFOneAlloc;
i: Integer;
begin
FCS.Enter;
try
Obj := TVKDBFOneAlloc.Create(Caller, size, memID);
Inc(memID);
FindIndex(Obj.FMemory, i);
Insert(i, Obj);
Result := Obj.FMemory;
finally
FCS.Leave
end;
end;
function TVKDBFMemMgr.GetMem(Capt: AnsiString; size: Integer): Pointer;
var
Obj: TVKDBFOneAlloc;
i: Integer;
begin
FCS.Enter;
try
Obj := TVKDBFOneAlloc.Create(nil, Capt, size, memID);
Inc(memID);
FindIndex(Obj.FMemory, i);
Insert(i, Obj);
Result := Obj.FMemory;
finally
FCS.Leave
end;
end;
function TVKDBFMemMgr.GetSize(p: Pointer): Integer;
var
Obj: TVKDBFOneAlloc;
i: Integer;
begin
FCS.Enter;
try
if p <> nil then begin
if FindIndex(p, i) then begin
Obj := TVKDBFOneAlloc(Items[i]);
Result := Obj.FSize;
end else
Result := 0;
end else
Result := 0;
finally
FCS.Leave
end;
end;
function TVKDBFMemMgr.ReallocMem(p: Pointer; size: Integer): Pointer;
var
Obj: TVKDBFOneAlloc;
i: Integer;
Old: Pointer;
begin
FCS.Enter;
try
if p <> nil then begin
if FindIndex(p, i) then begin
Obj := TVKDBFOneAlloc(Items[i]);
Old := Obj.FMemory;
Obj.ReallocMem(size);
Result := Obj.FMemory;
if Integer(Old) <> Integer(Obj.FMemory) then begin
OwnsObjects := false;
try
Delete(i);
FindIndex(Obj.FMemory, i);
Insert(i, Obj);
finally
OwnsObjects := true;
end;
end;
end else
Result := nil;
end else
Result := self.GetMem(self, size);
finally
FCS.Leave
end;
end;
{ TVKDBFOneAlloc }
constructor TVKDBFOneAlloc.Create;
begin
FMemory := nil;
FCaller := nil;
FSize := 0;
FCaption := '';
FmemID := 0;
end;
constructor TVKDBFOneAlloc.Create(Caller: TObject; Caption: AnsiString; Size: Cardinal; memID: Int64);
begin
Create;
FmemID := memID;
self.GetMem(Size);
FCaller := Caller;
FCaption := Caption;
end;
constructor TVKDBFOneAlloc.Create(Caller: TObject; Size: Cardinal; memID: Int64);
begin
if Size > 0 then begin
Create;
FmemID := memID;
self.GetMem(Size);
FCaller := Caller;
if FCaller <> nil then
FCaption := FCaller.ClassName;
end else
raise Exception.Create('TVKDBFOneAlloc: Can not allocate 0 bytes memory!');
end;
destructor TVKDBFOneAlloc.Destroy;
begin
self.FreeMem;
inherited Destroy;
end;
procedure TVKDBFOneAlloc.FreeMem;
begin
if FMemory <> nil then begin
System.FreeMem(FMemory);
//SysFreeMem(FMemory);
FMemory := nil;
FSize := 0;
{$IFDEF VKDBFMEMCONTROL}
if getUseDBF then begin
setUseDbf(False);
try
if oDBF <> nil then
if oDBF.Active then
if oDBF.Locate('ID', Int64toVariant(FmemID), []) then
oDBF.Delete;
finally
setUseDbf(True);
end;
end;
{$ENDIF}
end;
end;
procedure TVKDBFOneAlloc.GetMem(Size: Cardinal);
begin
if FMemory = nil then begin
System.GetMem(FMemory, Size);
//FMemory := SysGetMem(Size);
FSize := Size;
{$IFDEF VKDBFMEMCONTROL}
if getUseDBF then begin
setUseDbf(False);
try
if oDBF <> nil then begin
if oDBF.Active then begin
oDBF.Append;
TLargeintField(oDBF.FieldByName('ID')).AsLargeInt := FmemID;
TLargeintField(oDBF.FieldByName('POINTER')).AsLargeInt := DWORD(FMemory);
oDBF.FieldByName('SIZE').AsInteger := Size;
oDBF.Post;
end;
end;
finally
setUseDbf(True);
end;
end;
{$ENDIF}
end else
ReallocMem(Size);
end;
procedure TVKDBFOneAlloc.ReallocMem(NewSize: Cardinal);
begin
{$IFDEF VKDBFMEMCONTROL}
if getUseDBF then begin
setUseDbf(False);
try
if oDBF <> nil then
if oDBF.Active then
if oDBF.Locate('ID', Int64toVariant(FmemID), []) then
oDBF.Delete;
finally
setUseDbf(True);
end;
end;
{$ENDIF}
System.ReallocMem(FMemory, Size);
//FMemory := SysReallocMem(FMemory, Size);
FSize := Size;
{$IFDEF VKDBFMEMCONTROL}
if getUseDBF then begin
setUseDbf(False);
try
if oDBF <> nil then begin
if oDBF.Active then begin
oDBF.Append;
TLargeintField(oDBF.FieldByName('ID')).AsLargeInt := FmemID;
TLargeintField(oDBF.FieldByName('POINTER')).AsLargeInt := DWORD(FMemory);
oDBF.FieldByName('SIZE').AsInteger := Size;
oDBF.Post;
end;
end;
finally
setUseDbf(True);
end;
end;
{$ENDIF}
end;
initialization
{$IFDEF VKDBFMEMCONTROL}
oDBF := nil;
{$ENDIF}
oMem := TVKDBFMemMgr.Create;
{$IFDEF VKDBFMEMCONTROL}
oCS := TCriticalSection.Create;
setUseDbf(False);
setUseExDbf(False);
oDBF := TVKDBFNTX.Create(nil);
TVKDBFNTX(oDBF).AccessMode.AccessMode := 66;
TVKDBFNTX(oDBF).DBFFileName := 'vkdbfmemmgr.dbf';
TVKDBFNTX(oDBF).SetDeleted := True;
with TVKDBFNTX(oDBF).DBFFieldDefs.add as TVKDBFFieldDef do begin
Name := 'ID';
field_type := 'E';
extend_type := dbftS8_N;
end;
with TVKDBFNTX(oDBF).DBFFieldDefs.add as TVKDBFFieldDef do begin
Name := 'POINTER';
field_type := 'E';
extend_type := dbftS8_N;
end;
with TVKDBFNTX(oDBF).DBFFieldDefs.add as TVKDBFFieldDef do begin
Name := 'SIZE';
field_type := 'N';
len := 10;
dec := 0;
end;
with TVKDBFNTX(oDBF).DBFIndexDefs.add as TVKDBFIndexBag do begin
IndexFileName := 'vkdbfmemmgr.ntx';
with Orders.add as TVKDBFOrder do begin
KeyExpresion := 'ID';
end;
end;
TVKDBFNTX(oDBF).CreateTable;
TVKDBFNTX(oDBF).Active := true;
setUseExDbf(True);
setUseDbf(True);
{$ENDIF}
finalization
{$IFDEF VKDBFMEMCONTROL}
setUseDbf(False);
setUseExDbf(False);
FreeAndNil(oDBF);
FreeAndNil(oCS);
{$ENDIF}
FreeAndNil(oMem);
end.
|
{-----------------------------------------------------------------------------
Unit Name: DUCanvas3D
Author: Sebastian Hütter
Date: 2006-08-01
Purpose: 3 Dimensional Canvas class. Uses simple projection.
History: 2006-08-01 initial release
-----------------------------------------------------------------------------}
unit DUCanvas3D;
interface
uses Windows, Consts, Classes,Graphics, math;
type
TPoint3d = record X,Y,Z:integer; end;
TSurface = record LF,RF,RR,LR:TPoint3d; end;
TCuboid = record
BLF,BRF,BRR,BLR,
TLF,TRF,TRR,TLR:TPoint3d;
end;
TColorRec = record
case boolean of
true: (Col:TColor);
false: (B,G,R:byte);
end;
TCanvas3D = class
private
FQ: Single;
FAngle: Single;
FHeight: integer;
FWidth: integer;
function GetBrush: TBrush;
function GetFont: TFont;
function GetPen: TPen;
protected
FCanvas:TCanvas;
function ProjectPoint(X,Y,Z:integer):TPoint; overload;
function ProjectPoint(P: TPoint3d): TPoint; overload;
function ColorFactor(S: array of TPoint3d): single;
public
constructor Create(ACanvas:TCanvas);
property Angle : Single read FAngle write FAngle;
property Q : Single read FQ write FQ;
property Width : integer read FWidth write FWidth;
property Height : integer read FHeight write FHeight;
procedure LineTo(P:TPoint3d); overload;
procedure MoveTo(P:TPoint3d); overload;
procedure LineTo(X, Y, Z: integer); overload;
procedure MoveTo(X, Y, Z: integer); overload;
procedure Polygon(Points: array of TPoint3d);
procedure FillRect(const Rect: TRect);
procedure FrameRect(const Rect: TRect);
procedure FillCuboid(const Cuboid: TCuboid; Open:boolean=false);
procedure FrameCuboid(const Cuboid: TCuboid; Open:boolean);
procedure FillSurface(const Surface:TSurface);
published
property Brush: TBrush read GetBrush;
property Font: TFont read GetFont;
property Pen: TPen read GetPen;
end;
function Point3d(X,Y,Z:integer):TPoint3d;
function CuboidBounds(X,Y,Z, CX,CY,CZ:integer):TCuboid;
function Surface(LF,RF,RR,LR:TPoint3d):TSurface;
implementation
function Sin(X:double):double;
begin
Result:= System.Sin(X* Pi / 180);
end;
function Cos(X:double):double;
begin
Result:= System.Cos(X* Pi / 180);
end;
function ProjectPointAQ(X, Y, Z, A,Q:double): TPoint;
begin
Result.x:= round(X+cos(A)*Z*Q);
Result.y:= round(Y+Sin(A)*Z*Q);
end;
function Volume(Cuboid:TCuboid):double;
begin
with Cuboid do
Result:= (BRF.x-BLF.X)*
(TLF.y-BLF.y)*
(BLR.z-BLF.z);
end;
function PolygonArea(Points: array of TPoint):double;
var i,j:integer;
area:double;
begin
area:= 0;
//--- Compute
for i:=0 to high(Points) do begin
j := (i + 1) mod length(Points);
area := area + Points[i].x * Points[j].y;
area := area - Points[i].y * Points[j].x;
end;
area:= area / 2;
Result:= abs(area);
end;
function Point3d(X,Y,Z:integer):TPoint3d;
begin
Result.X:= X;
Result.Y:= Y;
Result.Z:= Z;
end;
function CuboidBounds(X,Y,Z, CX,CY,CZ:integer):TCuboid;
begin
with Result do begin
BLF:=Point3d(X ,Y,Z);
BRF:=Point3d(X+CX,Y,Z);
BRR:=Point3d(X+Cx,Y,Z+CZ);
BLR:=Point3d(X ,Y,Z+CZ);
TLF:=Point3d(X ,Y+CY,Z);
TRF:=Point3d(X+CX,Y+CY,Z);
TRR:=Point3d(X+Cx,Y+CY,Z+CZ);
TLR:=Point3d(X ,Y+CY,Z+CZ);
end;
end;
function Surface(LF,RF,RR,LR:TPoint3d):TSurface;
begin
Result.LF:= LF;
Result.RF:= RF;
Result.RR:= RR;
Result.LR:= LR;
end;
{ TCanvas3D }
constructor TCanvas3D.Create(ACanvas: TCanvas);
begin
inherited Create;
FCanvas:= ACanvas;
FQ:= 0.5;
FAngle:= 45;
end;
//==============================================================================
// Functions Accessing Canvas
function TCanvas3D.ProjectPoint(X, Y, Z: integer): TPoint;
begin
Result:= ProjectPointAQ(x,y,z,FAngle,FQ);
Result.y:= Height-Result.y-2;
end;
function TCanvas3D.ProjectPoint(P:TPoint3d): TPoint;
begin
Result:= ProjectPoint(P.X,P.Y,P.z);
end;
procedure TCanvas3D.LineTo(X, Y, Z: integer);
var p:TPoint;
begin
p:= ProjectPoint(X,Y,Z);
FCanvas.LineTo(p.x,p.y);
end;
procedure TCanvas3D.MoveTo(X, Y, Z: integer);
var p:TPoint;
begin
p:= ProjectPoint(X,Y,Z);
FCanvas.MoveTo(p.x,p.y);
end;
procedure TCanvas3D.Polygon(Points: array of TPoint3d);
var p:array of TPoint;
i:integer;
begin
SetLength(p,length(Points));
for i:= 0 to high(Points) do
p[i]:= ProjectPoint(Points[i].X,Points[i].Y,Points[i].Z);
FCanvas.Polygon(p);
end;
//==============================================================================
procedure TCanvas3D.LineTo(P: TPoint3d);
begin
LineTo(P.X,P.Y,P.Z);
end;
procedure TCanvas3D.MoveTo(P: TPoint3d);
begin
MoveTo(P.X,P.Y,P.Z);
end;
function TCanvas3D.GetBrush: TBrush;
begin
Result:= FCanvas.Brush;
end;
function TCanvas3D.GetFont: TFont;
begin
Result:= FCanvas.Font;
end;
function TCanvas3D.GetPen: TPen;
begin
Result:= FCanvas.Pen;
end;
procedure TCanvas3D.FillRect(const Rect: TRect);
begin
FCanvas.FillRect(rect);
end;
procedure TCanvas3D.FrameRect(const Rect: TRect);
begin
FCanvas.FrameRect(rect);
end;
function TCanvas3D.ColorFactor(S: array of TPoint3d): single;
var f,A1,A2:double;
p1,p2:array of TPoint;
i:integer;
begin
SetLength(p1,length(S));
SetLength(p2,length(S));
for i:= 0 to High(s) do begin
p1[i]:= ProjectPoint (S[i].X,S[i].Y,S[i].Z);
p2[i]:= ProjectPointAQ(S[i].X,S[i].Y,S[i].Z,5,0.1);
P2[i].y:= Height-P2[i].y-2;
end;
A1:= PolygonArea(p1);
A2:= PolygonArea(p2);
if A1<A2 then
f:= A1/A2 else
if A2<A1 then
f:= A2/A1 else
if A1=0 then
f:= 0 else
f:=1;
if f > 1.0 then f := 1.0;
if f <= 0.2 then f := 0.2;
Result:= f;
end;
procedure TCanvas3D.FillSurface(const Surface: TSurface);
var c:TColorRec;
save:TColor;
s:TBrushStyle;
f:double;
begin
save:= Brush.Color;
s:= Brush.Style;
try
with Surface do begin
if Brush.Style<>bsClear then begin
f:= ColorFactor([LF,RF,RR,LR]);
c.Col:= Brush.Color;
c.B:= trunc(c.B * f);
c.G:= trunc(c.G * f);
c.R:= trunc(c.R * f);
Brush.Color:= c.col;
Brush.Style:= s;
end;
Polygon([LF,RF,RR,LR]);
end;
finally
Brush.Color:= save;
Brush.Style:= s;
end;
end;
procedure TCanvas3D.FillCuboid(const Cuboid: TCuboid; Open:boolean=false);
begin
if Volume(Cuboid)=0 then exit;
with Cuboid do begin
FillSurface(Surface(BLF,BRF,BRR,BLR));
FillSurface(Surface(BLF,BLR,TLR,TLF));
FillSurface(Surface(BLR,BRR,TRR,TLR));
if not Open then begin
FillSurface(Surface(BLF,BRF,TRF,TLF));
FillSurface(Surface(BRF,BRR,TRR,TRF));
FillSurface(Surface(TLF,TRF,TRR,TLR));
end;
end;
end;
procedure TCanvas3D.FrameCuboid(const Cuboid: TCuboid; Open:boolean);
var OldStyle:TBrushStyle;
begin
OldStyle:= Brush.Style;
Brush.Style:= bsClear;
FillCuboid(Cuboid, Open);
Brush.Style:= OldStyle;
end;
end.
|
namespace Beta;
interface
uses
System,
System.Collections.Generic,
System.Linq,
System.Net,
System.Windows,
System.Windows.Controls,
System.Windows.Navigation,
Microsoft.Phone.Controls,
Microsoft.Phone.Shell,
Beta.Resources,
Beta.ViewModels,
System.Windows.Data;
type
MainPage = public partial class(PhoneApplicationPage)
private
method MainLongListSelector_SelectionChanged(sender: System.Object; e: SelectionChangedEventArgs);
method btnLogin_Click(sender: Object; e: System.Windows.RoutedEventArgs);
method MainPage_Loaded(sender: Object; e: System.Windows.RoutedEventArgs);
method updateButton_Click(sender: Object; e: System.EventArgs);
property IsUpdatingBinding: Binding;
method ReloadData;
public
// Constructor
constructor ;
end;
implementation
constructor MainPage;
begin
InitializeComponent();
DataContext := App.ViewModel;
self.isUpdatingBinding := new Binding('IsUpdating', Source := DataContext);
App.ViewModel.LoginButtonContent := "Login";
self.LoginWindowBorder.Height := Application.Current.Host.Content.ActualHeight;
self.LoginWindowBorder.Width := Application.Current.Host.Content.ActualWidth;
end;
method MainPage.MainPage_Loaded(sender: Object; e: System.Windows.RoutedEventArgs);
begin
if not App.ViewModel.IsDataLoaded then
ReloadData;
end;
method MainPage.MainLongListSelector_SelectionChanged(sender: System.Object; e: SelectionChangedEventArgs);
begin
var currentList := sender as LongListSelector;
// If selected item is null (no selection) do nothing
if currentList.SelectedItem = nil then
exit;
// Navigate to the new page
NavigationService.Navigate(new Uri('/DetailsPage.xaml?selectedItem=' + (BuildViewModel(currentList.SelectedItem)).ID, UriKind.Relative));
// Reset selected item to null (no selection)
currentList.SelectedItem := nil
end;
method MainPage.btnLogin_Click(sender: Object; e: System.Windows.RoutedEventArgs);
begin
if self.UsernameTextBox.Text = '' then begin
MessageBox.Show('Please enter user name', 'Error', MessageBoxButton.OK);
exit
end;
App.ViewModel.LoginButtonContent := 'Connecting...';
DataAccess.GetInstance.BeginLogin(self.UsernameTextBox.Text,
self.PasswordTextBox.Password,
new AsyncCallback(DataAccess.GetInstance.EndLogin));
end;
method MainPage.ReloadData;
begin
var progressIndicator: ProgressIndicator := SystemTray.ProgressIndicator;
if progressIndicator = nil then begin
progressIndicator := new ProgressIndicator;
BindingOperations.SetBinding(progressIndicator, ProgressIndicator.IsVisibleProperty, self.IsUpdatingBinding);
progressIndicator.SetValue(ProgressIndicator.IsIndeterminateProperty, true);
progressIndicator.SetValue(ProgressIndicator.TextProperty, 'Updating data...');
SystemTray.SetProgressIndicator(self, progressIndicator)
end;
App.ViewModel.LoadData()
end;
method MainPage.updateButton_Click(sender: Object; e: System.EventArgs);
begin
ReloadData;
end;
end.
|
{******************************************************************************
PROYECTO FACTURACION ELECTRONICA
Copyright (C) 2010-2014 - Bambu Code SA de CV - Ing. Luis Carrasco
Clase usada para generar el Sello Digital de una Cadena Original proveniente
de una factura electrónica. Aqui se especifican todas las reglas especificadas
por el SAT para la generación del mismo.
Este archivo pertenece al proyecto de codigo abierto de Bambu Code:
http://bambucode.com/codigoabierto
La licencia de este codigo fuente se encuentra en:
http://github.com/bambucode/tfacturaelectronica/blob/master/LICENCIA
******************************************************************************}
unit SelloDigital;
interface
uses Windows, FacturaTipos, ClaseOpenSSL;
type
///<summary>Representa el Sello Digital con el cual debemos de
/// 'sellar' la factura electrónica.
///</summary>
TSelloDigital = class
private
fCadenaOriginal: TStringCadenaOriginal;
fDigestion: TTipoDigestionOpenSSL;
fOpenSSL: TOpenSSL;
fCertificado: TFECertificado;
fLlavePrivada: String;
function calcularSello(): WideString;
public
constructor Create(sCadenaOriginal: TStringCadenaOriginal; Certificado: TFECertificado; TipoDigestion: TTipoDigestionOpenSSL);
destructor Destroy; override;
property SelloCalculado : WideString read calcularSello;
end;
implementation
uses Sysutils, StrUtils;
constructor TSelloDigital.Create(sCadenaOriginal: TStringCadenaOriginal; Certificado: TFECertificado; TipoDigestion: TTipoDigestionOpenSSL);
begin
inherited Create;
// Creamos nuestra clase OpenSSL usada para hacer la digestión
fOpenSSL:=TOpenSSL.Create();
fCadenaOriginal:=sCadenaOriginal;
fDigestion:=TipoDigestion;
fCertificado:=Certificado;
end;
destructor TSelloDigital.Destroy;
begin
FreeAndNil(fOpenSSL);
inherited Destroy;
end;
// Calcula el Sello Digital para la Cadena Original preparada en el constructor
function TSelloDigital.calcularSello : WideString;
begin
// Realizamos la digestion de la cadena original usando el certificado
// indicado y el modo de digestion
Result:=fOpenSSL.HacerDigestion(fCertificado.LlavePrivada.Ruta,
fCertificado.LlavePrivada.Clave,
fCadenaOriginal,
fDigestion);
end;
end.
|
unit uMain;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Soap.InvokeRegistry, Vcl.StdCtrls,
Soap.Rio, Soap.SOAPHTTPClient, uCardService;
const
cURL = 'http://exim.demo.mdmworld.com/CardService.asmx?WSDL';
cService = 'CardService';
cPort = 'CardServiceSoap';
type
TfrmMain = class(TForm)
HTTPRIO1: THTTPRIO;
bCheckCard: TButton;
eLogin: TEdit;
Label1: TLabel;
Label2: TLabel;
ePassword: TEdit;
Label3: TLabel;
eCardNum: TEdit;
bCheckSale: TButton;
eBarCode: TEdit;
Label4: TLabel;
eResult: TEdit;
eCardNumRes: TEdit;
eResultChangePercent: TEdit;
eResultSummChangePercent: TEdit;
eResultRequestedPrice: TEdit;
eResultRequestedQuantity: TEdit;
lRequestedQuantity: TLabel;
lRequestedPrice: TLabel;
Label6: TLabel;
Label7: TLabel;
bCommit: TButton;
procedure bCheckCardClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure bCheckSaleClick(Sender: TObject);
procedure eCardNumChange(Sender: TObject);
procedure bCommitClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
uses Soap.XSBuiltIns;
{$R *.dfm}
procedure TfrmMain.bCheckCardClick(Sender: TObject);
var
res : string;
begin
Self.Cursor := crHourGlass;
Application.ProcessMessages;
res := (HTTPRIO1 as CardServiceSoap).checkCard(eCardNum.Text, eLogin.Text, ePassword.Text);
eCardNumRes.Text := res;
if res = 'Продажа доступна' then
bCheckSale.Enabled := true
else
bCheckSale.Enabled := false;
Self.Cursor := crDefault;
end;
procedure TfrmMain.bCheckSaleClick(Sender: TObject);
var
SendList : ArrayOfCardCheckItem;
ResList : ArrayOfCardCheckResultItem;
Item : CardCheckItem;
ResItem : CardCheckResultItem;
Price, Quantity, Amount : TXSDecimal;
begin
Item := CardCheckItem.Create;
ResItem := CardCheckResultItem.Create;
Price := TXSDecimal.Create;
Quantity := TXSDecimal.Create;
Amount := TXSDecimal.Create;
try
Item.MdmCode := eCardNum.Text;
Item.ProductFormCode := eBarCode.Text;
Item.SaleType := '1';
Price.XSToNative('1000');
Item.RequestedPrice := Price;
Quantity.XSToNative('1');
Item.RequestedQuantity := Quantity;
Amount.XSToNative('1');
Item.RequestedAmount := Amount;
SetLength(SendList, 1);
SendList[0] := Item;
ResList := (HTTPRIO1 as CardServiceSoap).checkCardSale(SendList, eLogin.Text, ePassword.Text);
ResItem := ResList[0];
eResult.Text:= ResItem.ResultDescription;
eResultChangePercent.Text:= FloatToStr(ResItem.ResultDiscountPercent);
eResultSummChangePercent.Text:= FloatToStr(ResItem.ResultDiscountAmount);
eResultRequestedQuantity.Text:= ResItem.RequestedQuantity.DecimalString;
eResultRequestedPrice.Text:= ResItem.RequestedPrice.DecimalString;
finally
FreeAndNil(Price);
FreeAndNil(Quantity);
FreeAndNil(Amount);
Item := nil;
ResItem := nil;
end;
end;
procedure TfrmMain.bCommitClick(Sender: TObject);
var
i : integer;
aSaleRequest : CardSaleRequest;
SendList : ArrayOfCardSaleRequestItem;
Item : CardSaleRequestItem;
SaleRes : CardSaleResult;
begin
aSaleRequest := CardSaleRequest.Create;
Item := CardSaleRequestItem.Create;
SaleRes := CardSaleResult.Create;
try
aSaleRequest.CheckId := '1';
aSaleRequest.CheckCode := '1';
aSaleRequest.CheckDate := TXSDateTime.Create;
aSaleRequest.CheckDate.AsDateTime := Now();
aSaleRequest.MdmCode := eCardNum.Text;
aSaleRequest.SaleType := '0';
// products
Item.ItemId := '1';
Item.MdmCode := eCardNum.Text;
Item.ProductFormCode := eBarCode.Text;
Item.SaleType := '0';
Item.PrimaryPrice := TXSDecimal.Create;
Item.PrimaryPrice.XSToNative('100');
Item.RequestedPrice := TXSDecimal.Create;
Item.RequestedPrice.XSToNative(FloatToStr(100*(100-10)/100));
Item.PrimaryAmount := TXSDecimal.Create;
Item.PrimaryAmount.XSToNative('200');
Item.RequestedAmount := TXSDecimal.Create;
Item.RequestedAmount.XSToNative(FloatToStr(200 - 90));
Item.RequestedQuantity := TXSDecimal.Create;
Item.RequestedQuantity.XSToNative('2');
SetLength(SendList, 1);
SendList[0] := Item;
aSaleRequest.Items := SendList;
SaleRes := (HTTPRIO1 as CardServiceSoap).commitCardSale(aSaleRequest, eLogin.Text, ePassword.Text);
finally
FreeAndNil(aSaleRequest);
FreeAndNil(SaleRes);
end;
end;
procedure TfrmMain.eCardNumChange(Sender: TObject);
begin
bCheckSale.Enabled := false;
end;
procedure TfrmMain.FormCreate(Sender: TObject);
begin
HTTPRIO1.WSDLLocation := cURL;
HTTPRIO1.Service := cService;
HTTPRIO1.Port := cPort;
bCheckSale.Enabled := false;
end;
end.
|
unit FormatSettings;
interface
implementation
uses
SysUtils;
procedure SetDefaultFormatSettings;
begin
ThousandSeparator := ',';
DecimalSeparator := '.';
DateSeparator := '/';
ShortDateFormat := 'd/m/y';
LongDateFormat := 'dddd d mmmm yyyy';
TimeSeparator := ':';
TimeAMString := 'am';
TimePMString := 'pm';
ShortTimeFormat := 'h:nn ampm';
LongTimeFormat := 'h:nn:ss ampm';
ShortMonthNames[ 1] := 'ene';
ShortMonthNames[ 2] := 'feb';
ShortMonthNames[ 3] := 'mar';
ShortMonthNames[ 4] := 'abr';
ShortMonthNames[ 5] := 'may';
ShortMonthNames[ 6] := 'jun';
ShortMonthNames[ 7] := 'jul';
ShortMonthNames[ 8] := 'ago';
ShortMonthNames[ 9] := 'sep';
ShortMonthNames[10] := 'oct';
ShortMonthNames[11] := 'nov';
ShortMonthNames[12] := 'dic';
LongMonthNames [ 1] := 'enero';
LongMonthNames [ 2] := 'febrero';
LongMonthNames [ 3] := 'marzo';
LongMonthNames [ 4] := 'abril';
LongMonthNames [ 5] := 'mayo';
LongMonthNames [ 6] := 'junio';
LongMonthNames [ 7] := 'julio';
LongMonthNames [ 8] := 'agosto';
LongMonthNames [ 9] := 'septiembre';
LongMonthNames [10] := 'octubre';
LongMonthNames [11] := 'noviembre';
LongMonthNames [12] := 'diciembre';
ShortDayNames[1] := 'dom';
ShortDayNames[2] := 'lun';
ShortDayNames[3] := 'mar';
ShortDayNames[4] := 'mie';
ShortDayNames[5] := 'jue';
ShortDayNames[6] := 'vie';
ShortDayNames[7] := 'sab';
LongDayNames [1] := 'domingo';
LongDayNames [2] := 'lunes';
LongDayNames [3] := 'martes';
LongDayNames [4] := 'miercoles';
LongDayNames [5] := 'jueves';
LongDayNames [6] := 'viernes';
LongDayNames [7] := 'sabado';
end;
begin
SetDefaultFormatSettings;
end.
|
unit FrameAntenna;
interface
uses
Forms, StdCtrls, Onoff, Controls, Classes, CommonObjs, AntennaWS, InvokeRegistry;
type
TFrame_Antenna = class(TFrame)
Led2: TLed;
Led1: TLed;
Led4: TLed;
Led5: TLed;
Led3: TLed;
Button1: TButton;
Bulb1: TBulb;
Label3: TLabel;
Label1: TLabel;
Label2: TLabel;
Label4: TLabel;
Label5: TLabel;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
fUpdating : boolean;
fAntenna : IAntennaWS;
fAuthHeader : TAuthHeader;
function GetAntenna : IAntennaWS;
function GetAntennaControl: IAntennaWS;
public
procedure Init( Value : IAntennaWS; AuthHeader : TAuthHeader);
procedure UpdateView;
property Updating : boolean read fUpdating;
published
property Antenna : IAntennaWS read GetAntenna;
property Control : IAntennaWS read GetAntennaControl;
end;
implementation
{$R *.DFM}
{ TFrame_Antenna }
procedure TFrame_Antenna.UpdateView;
begin
if fUpdating
then exit;
if assigned(Antenna)
then
begin
fUpdating := true;
try
try
Led1.State := Antenna.Antena_Listo;
Led2.State := Antenna.Cupula_Abierta;
Led3.State := Antenna.Averia_Excitacion;
Led4.State := Antenna.Limite_P;
Led5.State := Antenna.Limite_N;
Bulb1.State := Antenna.Acc_On;
except
end;
finally
fUpdating := false;
end;
end;
end;
procedure TFrame_Antenna.Button1Click(Sender: TObject);
begin
if assigned(Control)
then
if Bulb1.State
then Control.Apagar_Acc
else Control.Encender_Acc;
end;
procedure TFrame_Antenna.Button2Click(Sender: TObject);
begin
if assigned(Control)
then Control.Apagar_Acc;
end;
procedure TFrame_Antenna.Init(Value: IAntennaWS; AuthHeader: TAuthHeader);
begin
fUpdating := false;
fAuthHeader := AuthHeader;
fAntenna := Value;
UpdateView;
end;
function TFrame_Antenna.GetAntenna: IAntennaWS;
begin
result := fAntenna;
end;
function TFrame_Antenna.GetAntennaControl: IAntennaWS;
var
Headers : ISOAPHeaders;
begin
Headers := fAntenna as ISOAPHeaders;
Headers.Send(fAuthHeader);
result := fAntenna;
end;
end.
|
(*NIM/Nama : 16515034/Mikhael Artur Darmakesuma *)
(*Nama file : lingkaran.pas *)
(*Topik : Modular Programming *)
(*Tanggal : 6 April 2016 *)
(*Deskripsi : unit bernama utanggal yang mengandung deklarasi type tanggal berikut operasi-operasinya (dalam bentuk fungsi/prosedur). *)
unit utanggal;
interface
{ Type tanggal }
type
tanggal = record
dd: integer; {hari, 1 <= dd <= 31}
mm: integer; {bulan, 1 <= mm <= 12}
yy: integer; {tahun, 0 < yy <= 9999}
end;
{ Deklarasi Fungsi/Prosedur }
function IsKabisat (y : integer) : boolean;
{ Menghasilkan true jika y adalah tahun kabisat,
yaitu jika tahun abad (habis dibagi 100) maka harus habis dibagi 400
atau jika bukan tahun abad (tidak habis dibagi 100), maka harus habis dibagi 4 }
function IsTanggalValid (d, m, y : integer) : boolean;
{ Menghasilkan true jika d, m, y dapat membentuk tanggal yang valid
dengan d sebagai hari, m sebagai bulan, dan y sebagai tahun. }
{ Beberapa syarat tanggal valid selain syarat rentang nilai di atas:
Jika mm salah satu dari [1,3,5,7,8,10,12] maka 1 <= dd <= 31;
Jika mm salah satu dari [4,6,9,11] maka 1 <= dd <= 30
Jika mm = 2, jika yy tahun kabisat, maka 1 <= dd <= 29
jika yy bukan tahun kabisat, maka 1 <= dd <= 28 }
procedure TulisTanggal (T : tanggal);
{ Menuliskan tanggal P ke layar dalam bentuk "T.dd/T.mm/T.yy" }
{ Tidak diawali, diselangi, atau diakhiri dengan karakter apa pun, termasuk spasi
atau pun enter }
{ I.S.: T terdefinisi }
{ F.S.: T tercetak di layar dalam bentuk "T.dd/T.mm/T.yy" }
function IsLebihAkhir (T1, T2 : tanggal) : boolean;
{ Menghasilkan true jika T1 lebih akhir dari T2 }
{ Menggunakan analisis kasus }
{ Realisasi Fungsi/Prosedur }
implementation
function IsKabisat (y : integer) : boolean;
{ Menghasilkan true jika y adalah tahun kabisat,
yaitu jika tahun abad (habis dibagi 100) maka harus habis dibagi 400
atau jika bukan tahun abad (tidak habis dibagi 100), maka harus habis dibagi 4 }
begin
IsKabisat := (((y mod 100 = 0) and (y mod 400 = 0)) or ((y mod 100 <> 0) and
(y mod 4 = 0)));
end;
function IsTanggalValid (d, m, y : integer) : boolean;
{ Menghasilkan true jika d, m, y dapat membentuk tanggal yang valid
dengan d sebagai hari, m sebagai bulan, dan y sebagai tahun. }
{ Beberapa syarat tanggal valid selain syarat rentang nilai di atas:
Jika mm salah satu dari [1,3,5,7,8,10,12] maka 1 <= dd <= 31;
Jika mm salah satu dari [4,6,9,11] maka 1 <= dd <= 30
Jika mm = 2, jika yy tahun kabisat, maka 1 <= dd <= 29
jika yy bukan tahun kabisat, maka 1 <= dd <= 28 }
begin
if ((y > 0) and (y <= 9999) and (m >= 1) and (m <= 12)) then
begin
if (m in [1,3,5,7,8,10,12]) then
begin
if ((d >= 1) and (d <= 31)) then
begin
IsTanggalValid := TRUE;
end
else
begin
IsTanggalValid := FALSE;
end;
end
else
if (m in [4,6,9,11]) then
begin
if ((d >= 1) and (d <= 30)) then
begin
IsTanggalValid := TRUE;
end
else
begin
IsTanggalValid := FALSE;
end;
end
else {if (m = 2) then}
begin
if (IsKabisat (y)) then
begin
if ((d >= 1) and (d <= 29)) then
begin
IsTanggalValid := TRUE;
end
else
begin
IsTanggalValid := FALSE;
end;
end
else {not IsKabisat (y)}
begin
if ((d >= 1) and (d <= 28)) then
begin
IsTanggalValid := TRUE;
end
else
begin
IsTanggalValid := FALSE;
end;
end;
end;
end
else {y <= 0 or y > 9999 or m < 1 or m > 12}
begin
IsTanggalValid := FALSE;
end;
end;
procedure TulisTanggal (T : tanggal);
{ Menuliskan tanggal P ke layar dalam bentuk "T.dd/T.mm/T.yy" }
{ Tidak diawali, diselangi, atau diakhiri dengan karakter apa pun, termasuk spasi
atau pun enter }
{ I.S.: T terdefinisi }
{ F.S.: T tercetak di layar dalam bentuk "T.dd/T.mm/T.yy" }
begin
write(T.dd,'/',T.mm,'/',T.yy);
end;
function IsLebihAkhir (T1, T2 : tanggal) : boolean;
{ Menghasilkan true jika T1 lebih akhir dari T2 }
{ Menggunakan analisis kasus }
begin
if (T1.yy > T2.yy) then
begin
IsLebihAkhir := TRUE;
end
else
if (T1.yy < T2.yy) then
begin
IsLebihAkhir := FALSE;
end
else
if (T1.yy = T2.yy) then
begin
if (T1.mm > T2.mm) then
begin
IsLebihAkhir := TRUE;
end
else
if (T1.mm < T2. mm) then
begin
IsLebihAkhir := FALSE;
end
else
if (T1.mm = T2.mm) then
begin
if (T1.dd > T2.dd) then
begin
IsLebihAkhir := TRUE;
end
else
if (T1.dd < T2.dd) then
begin
IsLebihAkhir := FALSE;
end; {Asumsi J1 dan J2 berbeda}
end;
end;
end;
end.
|
unit Delphi.Mocks.Tests.ObjectProxy;
interface
uses
Rtti,
SysUtils,
DUnitX.TestFramework,
Delphi.Mocks;
type
TSimpleObject = class(TObject)
private
FCreateCalled: Cardinal;
public
constructor Create;
property CreateCalled: Cardinal read FCreateCalled;
end;
TMultipleConstructor = class
private
FCreateCalled: Cardinal;
public
constructor Create(Dummy: Integer);overload;
constructor Create;overload;
property CreateCalled: Cardinal read FCreateCalled;
end;
TCommand = class
private
FVirtualMethodCalled: Boolean;
public
constructor Create;
procedure Execute;virtual;abstract;
procedure Run(value: Integer);virtual;abstract;
procedure TestVarParam(var msg : string);virtual;abstract;
procedure TestOutParam(out msg : string);virtual;abstract;
function VirtualMethod: Integer; overload; virtual;
function VirtualMethod(const Arg: String): Integer; overload; virtual;
function NonVirtualMethod: Integer;
property VirtualMethodCalled: Boolean read FVirtualMethodCalled;
end;
{$M+}
[TestFixture]
TTestObjectProxy = class
published
[Test]
procedure ProxyObject_Calls_The_Create_Of_The_Object_Type;
[Test]
procedure ProxyObject_MultipleConstructor;
[Test]
procedure MockWithArgProcedureUsingOnce;
[Test]
procedure MockNoArgProcedureUsingOnce;
[Test]
procedure MockNoArgProcedureUsingOnceWhen;
[Test]
procedure MockNoArgProcedureUsingNeverWhen;
[Test]
procedure MockNoArgProcedureUsingAtLeastOnceWhen;
[Test]
procedure MockNoArgProcedureUsingAtLeastWhen;
[Test]
procedure MockNoArgProcedureUsingAtMostBetweenWhen;
[Test]
procedure MockNoArgProcedureUsingExactlyWhen;
[Test]
procedure TestOutParam;
[Test]
procedure TestVarParam;
[Test]
procedure MockNoBehaviorDefined;
[Test]
procedure WillRaiseMockNonVirtualMethod;
[Test]
procedure VirtualMethodNotCalledDuringMockSetup;
[Test]
procedure VirtualMethodCalledIfNoBehaviorDefined;
[Test]
procedure VirtualMethodNotCalledIfBehaviorMatches;
[Test]
procedure VirtualMethodCalledIfBehaviorNotMatches;
end;
{$M-}
implementation
uses
Delphi.Mocks.ObjectProxy;
const
G_CREATE_CALLED_UNIQUE_ID = 909090;
{ TTestObjectProxy }
procedure TTestObjectProxy.ProxyObject_Calls_The_Create_Of_The_Object_Type;
var
objectProxy: IProxy<TSimpleObject>;
begin
objectProxy := TObjectProxy<TSimpleObject>.Create(function: TSimpleObject
begin
result := TSimpleObject.Create;
end);
Assert.AreEqual(objectProxy.Proxy.CreateCalled, G_CREATE_CALLED_UNIQUE_ID);
end;
procedure TTestObjectProxy.ProxyObject_MultipleConstructor;
var
objectProxy: IProxy<TMultipleConstructor>;
begin
objectProxy := TObjectProxy<TMultipleConstructor>.Create(function: TMultipleConstructor
begin
result := TMultipleConstructor.Create;
end);
Assert.AreEqual(objectProxy.Proxy.CreateCalled, G_CREATE_CALLED_UNIQUE_ID);
end;
procedure TTestObjectProxy.TestOutParam;
const
RETURN_MSG = 'hello Delphi Mocks! - With out Param';
var
mock : TMock<TCommand>;
msg: string;
begin
mock := TMock<TCommand>.Create;
mock.Setup.WillExecute(
function (const args : TArray<TValue>; const ReturnType : TRttiType) : TValue
begin
Assert.AreEqual(2, Length(Args), 'Args Length');
//Argument Zero is Self Instance
args[1] := RETURN_MSG;
end
).When.TestOutParam(msg);
msg := EmptyStr;
mock.Instance.TestOutParam(msg);
Assert.AreEqual(RETURN_MSG, msg);
mock.Verify;
Assert.Pass;
end;
procedure TTestObjectProxy.TestVarParam;
const
RETURN_MSG = 'hello Delphi Mocks!';
var
mock : TMock<TCommand>;
msg: string;
begin
mock := TMock<TCommand>.Create;
mock.Setup.WillExecute(
function (const args : TArray<TValue>; const ReturnType : TRttiType) : TValue
begin
Assert.AreEqual(2, Length(Args), 'Args Length');
//Argument Zero is Self Instance
args[1] := RETURN_MSG;
end
).When.TestVarParam(msg);
msg := EmptyStr;
mock.Instance.TestVarParam(msg);
Assert.AreEqual(RETURN_MSG, msg);
mock.Verify;
Assert.Pass;
end;
procedure TTestObjectProxy.VirtualMethodCalledIfBehaviorNotMatches;
var
mock : TMock<TCommand>;
begin
mock := TMock<TCommand>.Create;
mock.Setup.WillReturn(2).When.VirtualMethod('test');
Assert.AreEqual(1, mock.Instance.VirtualMethod('test2'));
Assert.IsTrue(mock.Instance.VirtualMethodCalled);
end;
procedure TTestObjectProxy.VirtualMethodCalledIfNoBehaviorDefined;
var
mock : TMock<TCommand>;
begin
mock := TMock<TCommand>.Create;
Assert.AreEqual(1, mock.Instance.VirtualMethod('test'));
Assert.IsTrue(mock.Instance.VirtualMethodCalled);
end;
procedure TTestObjectProxy.VirtualMethodNotCalledDuringMockSetup;
var
mock : TMock<TCommand>;
begin
mock := TMock<TCommand>.Create;
mock.Setup.Expect.AtLeastOnce.When.VirtualMethod;
mock.Setup.WillReturn(1).When.VirtualMethod;
mock.Setup.WillReturnDefault('VirtualMethod', 1);
Assert.IsFalse(mock.Instance.VirtualMethodCalled);
end;
procedure TTestObjectProxy.VirtualMethodNotCalledIfBehaviorMatches;
var
mock : TMock<TCommand>;
begin
mock := TMock<TCommand>.Create;
mock.Setup.WillReturn(2).When.VirtualMethod('test');
Assert.AreEqual(2, mock.Instance.VirtualMethod('test'));
Assert.IsFalse(mock.Instance.VirtualMethodCalled);
end;
procedure TTestObjectProxy.MockNoArgProcedureUsingAtLeastOnceWhen;
var
mock : TMock<TCommand>;
begin
mock := TMock<TCommand>.Create;
mock.Setup.Expect.AtLeastOnce.When.Execute;
mock.Instance.Execute;
mock.Instance.Execute;
mock.Verify;
Assert.Pass;
end;
procedure TTestObjectProxy.MockNoArgProcedureUsingAtLeastWhen;
var
mock : TMock<TCommand>;
begin
mock := TMock<TCommand>.Create;
mock.Setup.Expect.AtLeast(3).When.Execute;
mock.Instance.Execute;
mock.Instance.Execute;
mock.Instance.Execute;
mock.Verify;
Assert.Pass;
end;
procedure TTestObjectProxy.MockNoArgProcedureUsingAtMostBetweenWhen;
var
mock : TMock<TCommand>;
begin
mock := TMock<TCommand>.Create;
mock.Setup.Expect.AtMost(2).When.Execute;
mock.Instance.Execute;
mock.Instance.Execute;
mock.Verify;
Assert.Pass;
end;
procedure TTestObjectProxy.MockNoArgProcedureUsingExactlyWhen;
var
mock : TMock<TCommand>;
begin
mock := TMock<TCommand>.Create;
mock.Setup.Expect.Exactly(2).When.Execute;
mock.Instance.Execute;
mock.Instance.Execute;
mock.Verify;
Assert.Pass;
end;
procedure TTestObjectProxy.MockNoArgProcedureUsingNeverWhen;
var
mock : TMock<TCommand>;
begin
mock := TMock<TCommand>.Create;
mock.Setup.Expect.Never.When.Execute;
mock.Instance.Execute;
Assert.WillRaiseAny(procedure
begin
mock.Verify;
end);
end;
procedure TTestObjectProxy.MockNoArgProcedureUsingOnce;
var
mock : TMock<TCommand>;
begin
mock := TMock<TCommand>.Create;
mock.Setup.Expect.Once('Execute');
mock.Instance.Execute;
Assert.Pass;
end;
procedure TTestObjectProxy.MockNoArgProcedureUsingOnceWhen;
var
mock : TMock<TCommand>;
begin
mock := TMock<TCommand>.Create;
mock.Setup.Expect.Once.When.Execute;
mock.Instance.Execute;
mock.Verify;
Assert.Pass;
end;
procedure TTestObjectProxy.MockNoBehaviorDefined;
var
mock : TMock<TCommand>;
begin
mock := TMock<TCommand>.Create;
mock.Setup.Expect.Once.When.VirtualMethod;
Assert.AreEqual(1, mock.Instance.VirtualMethod);
mock.Verify;
end;
procedure TTestObjectProxy.WillRaiseMockNonVirtualMethod;
var
mock : TMock<TCommand>;
begin
mock := TMock<TCommand>.Create;
Assert.WillRaise(procedure begin mock.Setup.Expect.Once.When.NonVirtualMethod; end);
Assert.WillRaise(procedure begin mock.Setup.WillReturn(2).When.NonVirtualMethod; end);
end;
procedure TTestObjectProxy.MockWithArgProcedureUsingOnce;
var
mock : TMock<TCommand>;
begin
mock := TMock<TCommand>.Create;
mock.Setup.Expect.Once.When.Run(3);
mock.Instance.Run(3);
mock.Verify;
Assert.Pass;
end;
{ TSimpleObject }
constructor TSimpleObject.Create;
begin
FCreateCalled := G_CREATE_CALLED_UNIQUE_ID;
end;
{ TMultipleConstructor }
constructor TMultipleConstructor.Create(Dummy: Integer);
begin
end;
constructor TMultipleConstructor.Create;
begin
FCreateCalled := G_CREATE_CALLED_UNIQUE_ID;
end;
{ TCommand }
constructor TCommand.Create;
begin
FVirtualMethodCalled := False;
end;
function TCommand.NonVirtualMethod: Integer;
begin
Result := 1;
end;
function TCommand.VirtualMethod(const Arg: String): Integer;
begin
FVirtualMethodCalled := True;
Result := 1;
end;
function TCommand.VirtualMethod: Integer;
begin
FVirtualMethodCalled := True;
Result := 1;
end;
initialization
TDUnitX.RegisterTestFixture(TTestObjectProxy);
end.
|
unit UForth;
interface
type
TTokenType = (ttNumber, ttString, ttAtom);
PStackElem = ^TStackElem;
TStackElem = record
sType : TTokenType;
val_str : String;
val_number : Extended;
end;
function TokenAtom(name : String) : TStackElem;
function TokenStr(value : String) : TStackElem;
function TokenNumber(value : Extended) : TStackElem;
procedure eval (expr : String);
implementation
uses Classes, SysUtils;
Type
TStack = class (TList)
procedure Push (pElem : TStackElem);
function Pop: TStackElem;
function Peek : TStackElem;
function IsEmpty : Boolean;
end;
TState = (sNormal, sString, sIfTrue, sIfFalse);
TStateStack = class (TList)
procedure Push (pElem : TState);
function Pop: TState;
function Peek : TState;
function IsEmpty : Boolean;
end;
var
StateStack : TStateStack;
type
TAtomImplementation = procedure;
TAtomType = (atBuiltin, atComp);
TAtomVal = record
name : String;
aType : TAtomType;
ptr : TAtomImplementation;
value : String;
end;
function AtomBuiltin(name : String; f : TAtomImplementation) : TAtomVal;
begin
Result.name := name;
Result.aType := atBuiltin;
Result.ptr := f;
end;
function AtomComp(name : String; value : String) : TAtomVal;
begin
Result.name := name;
Result.aType := atComp;
Result.value := value;
end;
var
MainStack : TStack;
var
AtomTable : array of TAtomVal;
procedure addAtom(atom : TAtomVal);
begin
SetLength(AtomTable, length(AtomTable)+1);
AtomTable[high(AtomTable)]:= atom;
end;
procedure findAndRunAtom(name : String);
var i : integer;
begin
i:=0;
while (i<length(AtomTable)) and (AtomTable[i].name<>name) do
inc(i);
if (i<length(AtomTable)) then
if AtomTable[i].aType = atBuiltin then
AtomTable[i].ptr
else
eval(AtomTable[i].value)
else
MainStack.Push(TokenAtom(name));
end;
function TokenAtom(name : String) : TStackElem;
begin
Result.sType := ttAtom;
Result.val_str := name;
end;
function TokenStr(value : String) : TStackElem;
begin
Result.sType := ttString;
Result.val_str := value;
end;
function TokenNumber(value : Extended) : TStackElem;
begin
Result.sType := ttNumber;
Result.val_number := value;
end;
function TokenToStr(pToken : TStackElem) : String;
begin
if pToken.sType = ttNumber then
Result := FloatToStr(pToken.val_number)
else Result := pToken.val_str;
end;
procedure ai_plus;
begin
MainStack.Push(TokenNumber(
MainStack.Pop.val_number + MainStack.Pop.val_number));
end;
procedure ai_minus;
begin
MainStack.Push(TokenNumber(MainStack.Pop.val_number - MainStack.Pop.val_number));
end;
procedure ai_mult;
begin
MainStack.Push(TokenNumber(
MainStack.Pop.val_number * MainStack.Pop.val_number));
end;
procedure ai_div;
begin
MainStack.Push(TokenNumber(
MainStack.Pop.val_number / MainStack.Pop.val_number));
end;
procedure ai_greater;
begin
if MainStack.Pop.val_number > MainStack.Pop.val_number
then
MainStack.Push(TokenAtom('T')) else
MainStack.Push(TokenAtom('F'));
end;
procedure ai_lesser;
begin
if MainStack.Pop.val_number < MainStack.Pop.val_number
then
MainStack.Push(TokenAtom('T')) else
MainStack.Push(TokenAtom('F'));
end;
procedure ai_equal;
begin
if MainStack.Pop.val_number = MainStack.Pop.val_number
then
MainStack.Push(TokenAtom('T')) else
MainStack.Push(TokenAtom('F'));
end;
procedure ai_notequal;
begin
if MainStack.Pop.val_number <> MainStack.Pop.val_number
then
MainStack.Push(TokenAtom('T')) else
MainStack.Push(TokenAtom('F'));
end;
procedure ai_concat;
begin
MainStack.Push(TokenStr(
MainStack.Pop.val_str + MainStack.Pop.val_str));
end;
procedure ai_eval;
begin
eval(MainStack.Pop.val_str);
end;
procedure ai_dup;
begin
MainStack.Push(MainStack.Peek);
end;
procedure ai_set;
begin
addAtom(AtomComp( MainStack.Pop.val_str,
MainStack.Pop.val_str));
end;
procedure ai_if;
begin
if MainStack.Pop.val_str = 'T' then
StateStack.Push(sIfTrue) else
StateStack.Push(sIfFalse);
end;
procedure ai_print;
begin
writeln(TokenToStr(MainStack.Pop));
end;
procedure ai_sqrt;
begin
MainStack.Push(TokenNumber(
sqrt(MainStack.Pop.val_number)));
end;
procedure ai_swap;
var a, b : TStackElem;
begin
a := MainStack.Pop;
b := MainStack.Pop;
MainStack.Push(a);
MainStack.Push(b);
end;
procedure ai_readnum;
var a : TStackElem;
begin
Readln(a.val_number);
a.sType := ttNumber;
MainStack.Push(a);
end;
procedure eval (expr : String);
var i : integer;
currword : String;
val_number : Extended;
val_str : String;
token : TStackElem;
instr : Boolean;
procedure ProcessCurrWord;
var i : Integer;
begin
// Смотрим, что это такое
//writeln('currword is '+currword);
//for i:= 0 to MainStack.Count-1 do
// write(TokenToStr(PStackElem(MainStack[i])^), ' ');
// writeln;
if TryStrToFloat(currword, val_number) then
token := TokenNumber(val_number) else
token := TokenAtom(currword);
if (StateStack.Peek in [sIfTrue, sIfFalse]) and (token.val_str = 'endif') then
StateStack.Pop else
if StateStack.Peek <> sIfFalse then
begin
if token.sType = ttAtom then
begin
//смотрим состояние
findAndRunAtom(token.val_str);
end
else
MainStack.Push(token);
end;
//for i:= 0 to MainStack.Count-1 do
// write(TokenToStr(PStackElem(MainStack[i])^), ' ');
// writeln;
end;
// условие if действия endif
// если мы встречаем if
begin
// тут мы работаем с главным стеком
i := 1;
currword := '';
instr := false;
while i<=length(expr) do
begin
if expr[i] = '"' then
begin
instr := not instr;
inc(i);
end;
if instr or not instr and not (expr[i] in [' ', #13, #10]) then
currword := currword+expr[i]
else
if currword<>'' then
begin
ProcessCurrWord;
currword := '';
end;
inc(i);
end;
if currword<>'' then
ProcessCurrWord;
end;
{ TStack }
function TStack.IsEmpty: Boolean;
begin
Result := Count=0;
end;
function TStack.Peek: TStackElem;
begin
Result := TStackElem(Last^);
end;
function TStack.Pop: TStackElem;
begin
Result := Peek;
FreeMem (Last);
Delete(Count-1);
end;
procedure TStack.Push(pElem: TStackElem);
var p : PStackElem;
begin
New(p);
//GetMem(p, sizeof(TStackElem));
p^ := pElem;
Add(p);
end;
{ TStateStack }
function TStateStack.IsEmpty: Boolean;
begin
Result := Count = 0;
end;
function TStateStack.Peek: TState;
begin
Result := TState(Items[Count-1])
end;
function TStateStack.Pop: TState;
begin
Result := TState(Items[Count-1]);
Delete(Count-1);
end;
procedure TStateStack.Push(pElem: TState);
begin
Add(Pointer(pElem));
end;
initialization
MainStack := TStack.Create;
StateStack := TStateStack.Create;
StateStack.Push(sNormal);
addAtom(AtomBuiltin('+', ai_plus));
addAtom(AtomBuiltin('-', ai_minus));
addAtom(AtomBuiltin('*', ai_mult));
addAtom(AtomBuiltin('/', ai_div));
addAtom(AtomBuiltin('>', ai_greater));
addAtom(AtomBuiltin('<', ai_lesser));
addAtom(AtomBuiltin('=', ai_equal));
addAtom(AtomBuiltin('<>', ai_notequal));
addAtom(AtomBuiltin('eval', ai_eval));
addAtom(AtomBuiltin('set', ai_set));
addAtom(AtomBuiltin('.', ai_print));
addAtom(AtomBuiltin('concat', ai_concat));
addAtom(AtomBuiltin('dup', ai_dup));
addAtom(AtomBuiltin('sqrt', ai_sqrt));
addAtom(AtomBuiltin('if', ai_if));
addAtom(AtomBuiltin('swap', ai_swap));
addAtom(AtomBuiltin('readnum', ai_readnum));
addAtom(AtomComp('sqr', 'dup *'));
addAtom(AtomComp('len', 'sqr sqr + sqrt'));
addAtom(AtomComp('writeall', 'dup 0 < if dup . 1 swap - writeall endif'));
//addAtom(AtomComp('write10', ''));
finalization
MainStack.Free;
StateStack.Free;
end.
|
PROGRAM tableau(output);
CONST
SIZE = 10;
MAX_INT = 100;
VAR
table : array[0..SIZE] of integer;
i : integer;
PROCEDURE randomize_table(var table : array of integer; size : integer);
VAR
i : integer;
BEGIN
for i := 0 to size do
table[i] := random(MAX_INT);
END;
PROCEDURE display_table(table : array of integer; size : integer);
VAR
i : integer;
BEGIN
write('(');
for i := 0 to size-1 do
write(table[i], ',');
writeln(table[size], ')');
END;
FUNCTION min_table(table : array of integer; size : integer) : integer;
VAR
i, r : integer;
BEGIN
r := table[0];
for i := 1 to size do
if r > table[i] then
r := table[i];
min_table := r;
END;
FUNCTION rmax_table(table : array of integer; size : integer) : integer;
VAR
i, j : integer;
BEGIN
j := 0;
for i := 1 to size do
if table[j] < table[i] then
j := i;
rmax_table := j;
END;
PROCEDURE swap(var i : integer; var j : integer);
VAR
t : integer;
BEGIN
t := i;
i := j;
j := t;
END;
PROCEDURE selectionsort_table(var table : array of integer; size : integer);
VAR
i : integer;
BEGIN
for i := size downto 1 do
swap(table[i], table[rmax_table(table, i)]);
END;
PROCEDURE quicksort_table(var table : array of integer; a : integer; b : integer);
VAR
p : integer;
i : integer;
BEGIN
if (a < b) then
begin
p := a;
for i := a+1 to b do
if table[i] < table[a] then
begin
p := p+1;
swap(table[i], table[p]);
end;
swap(table[a], table[p]);
quicksort_table(table, a, p-1);
quicksort_table(table, p+1, b);
end;
END;
BEGIN
for i := 0 to SIZE do
table[i] := 0;
randomize();
display_table(table, SIZE);
randomize_table(table, SIZE);
display_table(table, SIZE);
// selectionsort_table(table, SIZE);
quicksort_table(table, 0, SIZE);
display_table(table, SIZE);
END.
|
Unit ztvLoadLib;
(*--------------------------------------------------------------------------*)
(* *)
(* Unit : MyLibLod *)
(* *)
(* Purpose: Loads library dynamically and suppresses error box. *)
(* *)
(* Author : Philip R. "Pib" Burns. 98/08/10. *)
(* *)
(*--------------------------------------------------------------------------*)
Interface
Uses
Messages,
Windows;
{$I ZipTV.inc} //Declare the compiler defines
(* EXPORTS *)
Function MyLoadLibrary(LibName: String): THandle;
(*--------------------------------------------------------------------------*)
Implementation
(*--------------------------------------------------------------------------*)
(* MyLoadLibrary --- Loads library while suppressing error box. *)
(*--------------------------------------------------------------------------*)
Function MyLoadLibrary(LibName: String): THandle;
Var
PrevError: longint;
Begin (* MyLoadLibrary *)
(* Don't display an error box if the *)
(* library can't be loaded. *)
PrevError := SetErrorMode(SEM_NOOPENFILEERRORBOX);
(* Try loading the library. *)
Result := LoadLibrary(PChar(LibName));
(* Restore previous error box display *)
(* state. *)
SetErrorMode(PrevError);
End (* MyLoadLibrary *);
(*--------------------------------------------------------------------------*)
End.
|
unit Controllers.User;
interface
uses Horse, Services.User, DataSet.Serialize, System.JSON, System.SysUtils, Data.DB;
procedure Registry;
implementation
procedure DoListUsers(Req: THorseRequest; Res: THorseResponse; Next: TProc);
var
LUsers: TJSONArray;
LService: TServiceUser;
// LContent: TJSONObject;
begin
LService := TServiceUser.Create;
try
LUsers := LService.ListAll(Req.Query).ToJSONArray();
Res.Send<TJSONArray>(LUsers);
// LContent := TJSONObject.Create;
// LContent.AddPair('data', LUsers);
// LContent.AddPair('records', TJSONNumber.Create(LService.qryRecordCountcount.AsLargeInt));
// Res.Send<TJSONObject>(LContent);
finally
LService.Free;
end;
end;
procedure DoGetUser(Req: THorseRequest; Res: THorseResponse; Next: TProc);
var
LId: Int64;
LService: TServiceUser;
begin
LService := TServiceUser.Create;
try
LId := Req.Params['id'].ToInt64;
if LService.GetById(LId).IsEmpty then
raise EHorseException.Create(THTTPStatus.NotFound, 'Not found');
Res.Send<TJSONObject>(LService.qryPesquisa.ToJSONObject());
finally
LService.Free;
end;
end;
procedure Registry;
begin
THorse.Get('/users', DoListUsers);
THorse.Get('/users/:id', DoGetUser);
//THorse.Post('/users', DoPostUser);
//THorse.Put('/users/:id', DoPutUser);
//THorse.Delete('/users/:id', DoDeleteUser);
end;
end.
|
{## http://www.codezealot.org/archives/88 -- алгоритм GJK ##
## http://www.codezealot.org/archives/180 -- алгоритм EPA ##}
unit GJKCollisions;
interface
uses Math, PhysicsArifm, PhysicsRigidBody, SysUtils;
Type
TSimplex = class
protected
Elements: TVectors3;
public
Constructor Create;
Destructor Destroy;
Function GetLast: TVector3;
Procedure Add (const El: TVector3);
Procedure AddAt(const El: TVector3; const PositionIndex: Integer);
Procedure RemoveDuplicates;
Procedure RemoveElement (const ElementIndex: Integer);
Function ContainsOrigin (var SearchDirection: TVector3): boolean;
end;
TEdge = record
Distance: Double;
Normal: TVector3;
Index: Integer;
end;
{Проверить пересечение двух выпуклых тел, используя алгоритм Гилберта-Джонсона-Кёрти (GJK)}
Function GJKTestInterSection (const Body1, Body2: TRigidBody; var TerminatedSimplex: TSimplex;
var CurrentDirection: TVector3): boolean;
{Выполнить алгоритм расширяющегося политопа}
Procedure EPA (const Body1, Body2: TRigidBody; var TerminatedSimplex: TSimplex;
var ContactNormal: TVector3; var ContactPenetrationDepth: Double);
implementation
{Удалить из массива элемент по его индексу}
Procedure RemoveArrayEl (Var A: TVectors3; const Index: Integer); overload;
Var Len: Integer;
begin
Len := High (A);
If Index > Len then Exit;
A[Index] := A[Len];
SetLength (A, Len);
end;
{Удаляет дублирующиеся элементы в массиве векторов}
Procedure ClearDuplicates (Var A: TVectors3; StartIndex, EndIndex: Integer);
Var I, J: Integer;
begin
I := StartIndex;
If EndIndex > High (A) then EndIndex := High (A);
While (I <= EndIndex) do
begin
J := StartIndex;
While J <= EndIndex do
begin
While not V3Equal (A[I], A[J]) and (J < EndIndex) do
Inc (J);
If J <> I
then
begin
RemoveArrayEl (A, J);
Dec (EndIndex);
end
else Inc (J);
end;
If High (A) < EndIndex then EndIndex := High (A);
Inc (I);
end;
end;
{Удалить элементы массива, равные 0 по длине}
Procedure ClearZeroEqualElements (Var A: TVectors3);
Var J: Integer;
begin
J := 0;
While J <= High (A) do
begin
If not V3Equal (A[J], V3 (0))
then Inc (J)
else
begin
A[J] := V3Normalize (A[J]);
If V3Equal (A[J], V3 (0))
then RemoveArrayEl (A, J);
end;
end;
end;
{################################################################################################################
TSIMPLEX
################################################################################################################}
Constructor TSimplex.Create;
begin
inherited Create;
SetLength (Elements, 0);
end;
Destructor TSimplex.Destroy;
begin
SetLength (Elements, 0);
inherited Destroy;
end;
Function TSimplex.GetLast: TVector3;
begin
Result := Elements[High (Elements)];
end;
Procedure TSimplex.Add(const El: TVector3);
Var I: Integer;
begin
I := Length (Elements);
SetLength (Elements, I + 1);
Elements[I] := El;
end;
Procedure TSimplex.AddAt(const El: TVector3; const PositionIndex: Integer);
Var I, Len: Integer;
begin
Len := Length (Elements);
If PositionIndex >= Len then
begin
Add (El);
end else If (PositionIndex > 0) and (Len > 0) then
begin
SetLength (Elements, Len + 1);
{циклически сдвинуть элементы массива вправо}
For I := Len downto PositionIndex do Elements[I] := Elements[I - 1];
Elements[PositionIndex] := El;
end else If (PositionIndex = 0) then
begin
SetLength (Elements, Len + 1);
{циклически сдвинуть элементы массива вправо}
For I := Len downto 1 do Elements[I] := Elements[I - 1];
Elements[PositionIndex] := El;
end;
end;
Procedure TSimplex.RemoveElement(const ElementIndex: Integer);
Var Len: Integer;
begin
Len := High (Elements);
If ElementIndex > Len then Exit;
Elements[ElementIndex] := Elements[Len];
SetLength (Elements, Len);
end;
Procedure TSimplex.RemoveDuplicates;
Var I, J, EndIndex: Integer;
AreEqual: boolean;
begin
I := 0;
EndIndex := High (Elements);
If EndIndex <= 0 then Exit;
While (I <= EndIndex) do
begin
J := 1;
While J <= EndIndex do
begin
AreEqual := V3Equal (Elements[I], Elements[J]);
While not AreEqual and (J < EndIndex) do
begin
Inc (J);
AreEqual := V3Equal (Elements[I], Elements[J]);
end;
If (J <> I) and AreEqual then
begin
RemoveElement (J);
Dec (EndIndex);
end
else Inc (J);
end;
If High (Elements) < EndIndex then EndIndex := High (Elements);
Inc (I);
end;
end;
Function TSimplex.ContainsOrigin (var SearchDirection: TVector3): boolean;
Var A, B, C, AO, AB, AC, ABPerp, ACPerp: TVector3;
Len: Integer;
begin
{Получить добавленную последней точку симплекса}
A := GetLast;
{инвертированный радиус-вектор A}
AO := V3Invert (A);
Len := Length (Elements);
RemoveDuplicates;
If Len = 3 then
begin
{случай треугольника (2-симплекс)}
B := Elements[1];
C := Elements[0];
{стороны}
AB := V3Sub (B, A);
AC := V3Sub (C, A);
{перпендикуляры к ним}
ABPerp := V3TripleProduct (AC, AB, AB);
ACPerp := V3TripleProduct (AB, AC, AC);
{Начало координат в области Вороного R4?}
If V3ScalarProduct (ABPerp, AO) > 0 then
begin
{Удалить точку B}
RemoveElement (2);
{Установить направление поиска на нормаль к AB}
SearchDirection := ABPerp;
end else
If V3ScalarProduct (ACPerp, AO) > 0 then
begin
{Удалить точку C}
RemoveElement (1);
{Установить направление поиска на нормаль к AC}
SearchDirection := ACPerp;
end else
begin
Result := true;
Exit;
end;
end else If Len = 2 then
begin
{случай линии (1-симплекс)}
B := Elements[0];
AB := V3Sub (B, A);
ABPerp := V3TripleProduct (AB, AO, AB);
SearchDirection := ABPerp;
end;
Result := false;
end;
{Одним из следствий теоремы о разделяющих осях (Separating Axis Theorem, SAT) является то,
что для случая контактирующих многогранников этой осью всегда будет либо нормаль одного из фейсов,
либо векторное произведение направляющих пары рёбер, где одно ребро принадлежит одному многограннику,
а другое — другому. То есть, для случая контактирующих многогранников, если опустить все оптимизации,
алгоритм поиска SAT сводится к следующей паре действий:
a) построить массив потенциальных разделяющих осей, состоящий из всех нормалей фейсов
и всех возможных пар рёбер,
б) посчитать величину пересечения проекций обеих геометрий на каждую из осей. Ось,
на которую проекция окажется минимальной, назовём разделяющей
(опять же, это не совсем верно, так как геометрии пересекаются), а векторную
величину пересечения проекций назовём penetration depth или PD.
Заметим, что если первое тело сдвинуть на вектор PD, то пересечение нейтрализуется.}
Procedure GeneratePossibleSATs2RB (const Body1, Body2: TRigidBody; Var Results: TVectors3);
Var I, J: Integer;
Count: Integer;
Offset: Integer;
begin
{Пересчитать нормали к фейсам}
SetLength (Results, Length (Body1.Ribs) + Length (Body2.Ribs) + Sqr (Length (Body1.Ribs))
+ Sqr (Length (Body1.Ribs)));
{Нормали к фейсам 1 тела}
Count := High (Body1.Faces);
For I := 0 to Count do
With Body1 do
Results[i] := GetNormalToPlane (GlobalVertexes [Faces[I].Vertexes[0]].Pos,
GlobalVertexes [Faces[I].Vertexes[1]].Pos,
GlobalVertexes [Faces[I].Vertexes[2]].Pos);
{Нормали к фейсам 2 тела}
Offset := Count + 1;
Count := High (Body2.Faces);
For I := 0 to Count do
With Body2 do
Results[i + Offset] := GetNormalToPlane (GlobalVertexes [Faces[I].Vertexes[0]].Pos,
GlobalVertexes [Faces[I].Vertexes[1]].Pos,
GlobalVertexes [Faces[I].Vertexes[2]].Pos);
Offset := Offset + Count + 1;
{Посчитать векторные произведения рёбер 1 тела на рёбра 2 тела}
Count := 0;
For I := 0 to High (Body1.Ribs) do
begin
For J := 0 to High (Body2.Ribs) do
begin
Results[Count + Offset] := V3Mul (V3Sub (Body1.GlobalVertexes [Body1.Ribs[I, 1]].Pos,
Body1.GlobalVertexes [Body1.Ribs[I, 0]].Pos),
V3Sub (Body2.GlobalVertexes [Body2.Ribs[J, 1]].Pos,
Body2.GlobalVertexes [Body2.Ribs[J, 0]].Pos));
Inc (Count);
end;
end;
SetLength (Results, Offset + Count);
{Нормализовать получившиеся оси}
For J := 0 to High (Results) do
Results[J] := V3Normalize (Results[J]);
{Удалить дублирующиеся записи}
ClearDuplicates (Results, 0, High (Results));
{Удалить элементы, равные 0 по длине}
ClearZeroEqualElements (Results);
end;
{Support Mapping: вернуть точку тела в мировых координатах,
имеющую наибольшую проекцию на заданное направление}
Function Support (const Body1, Body2: TRigidBody; const Direction: TVector3): TVector3;
begin
Result := V3Sub (Body1.GetFarthestPointInDirection (Direction).Pos,
Body2.GetFarthestPointInDirection (V3Invert (Direction)).Pos);
end;
Function GJKTestInterSection (const Body1, Body2: TRigidBody; var TerminatedSimplex: TSimplex;
var CurrentDirection: TVector3): boolean;
begin
{Создать симплекс}
TerminatedSimplex := TSimplex.Create;
{Выбрать направление для взятия Support Point'ов}
With Body1 do
CurrentDirection := GetNormalToPlane (GlobalVertexes [Faces[0].Vertexes[0]].Pos,
GlobalVertexes [Faces[0].Vertexes[1]].Pos,
GlobalVertexes [Faces[0].Vertexes[2]].Pos);
{Добавить в симплекс первую точку на сумме Минковского}
TerminatedSimplex.Add(Support (Body1, Body2, CurrentDirection));
{Инвертировать направление для следующей точки}
CurrentDirection := V3Invert (CurrentDirection);
While true do
begin
{Добавить в симплекс очередную точку суммы Минковского}
TerminatedSimplex.Add(Support (Body1, Body2, CurrentDirection));
{и удалить дублирующиеся точки}
TerminatedSimplex.RemoveDuplicates;
If V3ScalarProduct (TerminatedSimplex.GetLast, CurrentDirection) <= 0 then
begin
Result := false;
CurrentDirection := V3 (0);
Break;
end else
{Если симплекс содержит начало координат, то мы нашли пересечение.}
If TerminatedSimplex.ContainsOrigin(CurrentDirection) then
begin
Result := true;
CurrentDirection := V3Normalize (CurrentDirection);
Exit;
end;
end;
end;
Function FindClosestEdgeInSimplex (const Simplex: TSimplex): TEdge;
Var I, J, Len: Integer;
EdgeVector, Normal: TVector3;
Dist: Double;
Edge: TEdge;
begin
Edge.Distance := +Infinity;
Len := High (Simplex.Elements);
For I := 0 to Len do
begin
{Выбрать индекс следующей точки}
If I = Len
then J := 0
else J := I + 1;
With Simplex do
begin
{Вектор из точки с индексом J в точку с индексом I}
EdgeVector := V3Sub (Elements[J], Elements[I]);
{Вектор от отрезка до начала координат}
Normal := V3Normalize (V3TripleProduct (EdgeVector, Elements[I], EdgeVector));
{Расстояние от отрезка до начала координат}
Dist := V3ScalarProduct (Elements[I], Normal);
end;
{Мы ищем наименьшее расстояние до начала координат. Отобрать нужный отрезок.}
If Dist < Edge.Distance then
begin
Edge.Distance := Dist;
Edge.Normal := Normal;
Edge.Index := J;
end;
end;
Result := Edge;
end;
Procedure EPA (const Body1, Body2: TRigidBody; var TerminatedSimplex: TSimplex;
var ContactNormal: TVector3; var ContactPenetrationDepth: Double);
Var Edge: TEdge;
SupportPoint: TVector3;
DistanceToOrigin: Double;
begin
While true do
begin
{Найти в симплексе отрезок, наиболее близкий к началу координат}
Edge := FindClosestEdgeInSimplex (TerminatedSimplex);
{Получить Support Point в направлении нормали выбранного отрезка}
SupportPoint := Support (Body1, Body2, Edge.Normal);
{Получить расстояние от начала координат до взятого Support Point'а}
DistanceToOrigin := -V3ScalarProduct (SupportPoint, Edge.Normal);
{Если точка лежит ближе к началу координат, тогда}
If DistanceToOrigin + Edge.Distance < 0.000001 then
begin
ContactNormal := Edge.Normal;
ContactPenetrationDepth := Abs (DistanceToOrigin);
Exit;
end else TerminatedSimplex.AddAt (SupportPoint, Edge.Index);
end;
end;
end.
|
unit AndroidTTS;
interface
uses
System.SysUtils, System.Classes,
{$IFDEF ANDROID}
AndroidAPI.JNIBridge, androidapi.JNI.TTS,
Androidapi.JNI.JavaTypes,
{$ENDIF}
FMX.Forms;
type
TAndroidTTS = class(TComponent)
private
{$IFDEF ANDROID}
ftts: JTextToSpeech;
type
TttsOnInitListener = class(TJavaLocal, JTextToSpeech_OnInitListener,
JTextToSpeech_OnUtteranceCompletedListener)
private
[weak] FParent : TAndroidTTS;
public
constructor Create(AParent : TAndroidTTS);
// JTextToSpeech_OnInitListener
procedure onInit(status: Integer); cdecl;
// JTextToSpeech_OnUtteranceCompletedListener
procedure onUtteranceCompleted(utteranceID: JString); cdecl;
end;
private
fttsListener : TttsOnInitListener;
FDone: TNotifyEvent;
procedure Init;
// Never fires
// property OnDone: TNotifyEvent read FDone write FDone;
{$ENDIF}
public
constructor Create(AOwner: TComponent); override;
procedure Speak(say: String);
end;
procedure Register;
implementation
{$IFDEF ANDROID}
uses
FMX.Helpers.Android
, FMX.Platform.Android
, Androidapi.JNI.Os
, Androidapi.JNI.GraphicsContentViewText
, Androidapi.Helpers
, Androidapi.JNI.App
;
{$ENDIF}
procedure Register;
begin
RegisterComponents('Android', [TAndroidTTS]);
end;
{ TAndroidTTS }
constructor TAndroidTTS.Create(AOwner: TComponent);
begin
inherited;
{$IFDEF ANDROID}
Init;
{$ENDIF}
end;
procedure TAndroidTTS.Speak(say: String);
{$IFDEF ANDROID}
var
params: JHashMap;
begin
params := nil;
// This needs to be a <String,String> hashmap for the OnDone to work.
{ params := TJHashMap.JavaClass.init();
params.put(TJTextToSpeech_Engine.JavaClass.KEY_PARAM_UTTERANCE_ID,
StringToJString('id')); }
ftts.speak(StringToJString(say), TJTextToSpeech.JavaClass.QUEUE_FLUSH, params);
end;
{$ELSE}
begin
end;
{$ENDIF}
{$IFDEF ANDROID}
procedure TAndroidTTS.Init;
begin
Ftts := TJTextToSpeech.JavaClass.init(SharedActivityContext, fttsListener);
end;
{ TAndroidTTS.TttsOnInitListener }
constructor TAndroidTTS.TttsOnInitListener.Create(AParent: TAndroidTTS);
begin
Inherited Create;
FParent := AParent;
end;
procedure TAndroidTTS.TttsOnInitListener.onInit(status: Integer);
var
Result : Integer;
begin
if (status = TJTextToSpeech.JavaClass.SUCCESS) then
begin
result := FParent.ftts.setLanguage(TJLocale.JavaClass.ENGLISH);
FParent.ftts.setOnUtteranceCompletedListener(self);
if (result = TJTextToSpeech.JavaClass.LANG_MISSING_DATA) or
(result = TJTextToSpeech.JavaClass.LANG_NOT_SUPPORTED) then
raise Exception.Create('This Language is not supported')
else
begin
// Processing after Init
end;
end
else
raise Exception.Create('Initilization Failed!');
end;
procedure TAndroidTTS.TttsOnInitListener.onUtteranceCompleted(
utteranceID: JString);
begin
// Currently not firing.
TThread.Synchronize(nil, procedure begin
if Assigned(FParent.FDone) then
begin
FParent.FDone(FParent);
end;
end);
end;
{$ENDIF}
end.
|
unit YOTM.DB.TaskRepeats;
interface
uses SQLite3, SQLLang, SQLiteTable3, System.Generics.Collections,
HGM.Controls.VirtualTable, YOTM.DB;
type
//Комментарии к задаче
TRepeatState = class;
TRepeatStates = class;
TRepeatState = class(TObject)
private
FOwner:TRepeatStates;
FID:Integer;
FTask: Integer;
FDate: TDate;
FDateDeadline: TDate;
FNotifyComplete: Boolean;
FState: Boolean;
procedure SetOwner(const Value: TRepeatStates);
procedure SetID(const Value: Integer);
procedure SetDate(const Value: TDate);
procedure SetTask(const Value: Integer);
procedure SetDateDeadline(const Value: TDate);
procedure SetNotifyComplete(const Value: Boolean);
procedure SetState(const Value: Boolean);
public
constructor Create(AOwner: TRepeatStates);
property Owner:TRepeatStates read FOwner write SetOwner;
property DateDeadline:TDate read FDateDeadline write SetDateDeadline;
property NotifyComplete:Boolean read FNotifyComplete write SetNotifyComplete;
property DateChange:TDate read FDate write SetDate;
property ID:Integer read FID write SetID;
property Task:Integer read FTask write SetTask;
property State:Boolean read FState write SetState;
end;
TRepeatStates = class(TTableData<TRepeatState>)
const
tnTable = 'RepeatStates';
fnID = 'rsID';
fnTask = 'rsTask';
fnDeadline = 'rsDeadline';
fnDateChange = 'rsDate';
fnNotifyComplete = 'rsNotifyComplete';
fnState = 'rsState';
private
FDataBase: TDB;
procedure SetDataBase(const Value: TDB);
public
constructor Create(ADataBase:TDB; ATableEx:TTableEx);
function GetItem(Task: Integer; Date:TDate): TRepeatState;
procedure Reload(TaskID:Integer);
/// <summary>
/// Обновить запись (добавить или изменить)
/// </summary>
procedure Update(Item: TRepeatState);
/// <summary>
/// Удалить запись
/// </summary>
procedure Delete(Index: Integer); override;
/// <summary>
/// Обновить все записи (добавить или изменить)
/// </summary>
procedure Save;
procedure CompleteTask(TaskID:Integer; Date:TDate; State:Boolean);
procedure NotifyComplete(TaskID:Integer; Date:TDate);
property DataBase:TDB read FDataBase write SetDataBase;
end;
implementation
uses System.SysUtils, DateUtils;
{ TRepeatState }
constructor TRepeatState.Create(AOwner: TRepeatStates);
begin
inherited Create;
FID:=-1;
FTask:=-1;
Owner:=AOwner;
end;
procedure TRepeatState.SetDate(const Value: TDate);
begin
FDate := Value;
end;
procedure TRepeatState.SetDateDeadline(const Value: TDate);
begin
FDateDeadline := Value;
end;
procedure TRepeatState.SetID(const Value: Integer);
begin
FID := Value;
end;
procedure TRepeatState.SetNotifyComplete(const Value: Boolean);
begin
FNotifyComplete := Value;
end;
procedure TRepeatState.SetOwner(const Value: TRepeatStates);
begin
FOwner := Value;
end;
procedure TRepeatState.SetState(const Value: Boolean);
begin
FState := Value;
end;
procedure TRepeatState.SetTask(const Value: Integer);
begin
FTask := Value;
end;
{ TRepeatStates }
procedure TRepeatStates.CompleteTask(TaskID: Integer; Date: TDate; State:Boolean);
var Item:TRepeatState;
begin
Item:=GetItem(TaskID, Date);
if Assigned(Item) then
begin
Item.State:=State;
Item.DateChange:=Now;
Update(Item);
end
else
begin
Item:=TRepeatState.Create(Self);
Item.DateChange:=Now;
Item.DateDeadline:=Date;
Item.State:=State;
Item.Task:=TaskID;
Update(Item);
end;
Item.Free;
end;
constructor TRepeatStates.Create(ADataBase: TDB; ATableEx:TTableEx);
begin
inherited Create(ATableEx);
FDataBase:=ADataBase;
if not FDataBase.DB.TableExists(tnTable) then
with SQL.CreateTable(tnTable) do
begin
AddField(fnID, ftInteger, True, True);
AddField(fnTask, ftInteger);
AddField(fnDeadline, ftDateTime);
AddField(fnDateChange, ftDateTime);
AddField(fnNotifyComplete, ftBoolean);
AddField(fnState, ftBoolean);
FDataBase.DB.ExecSQL(GetSQL);
EndCreate;
end;
end;
procedure TRepeatStates.Delete(Index: Integer);
begin
with SQL.Delete(tnTable) do
begin
WhereFieldEqual(fnID, Items[Index].ID);
DataBase.DB.ExecSQL(GetSQL);
EndCreate;
end;
inherited;
end;
function TRepeatStates.GetItem(Task: Integer; Date:TDate): TRepeatState;
var Table:TSQLiteTable;
begin
Result:=nil;
try
with SQL.Select(tnTable) do
begin
AddField(fnID);
AddField(fnTask);
AddField(fnDeadline);
AddField(fnDateChange);
AddField(fnNotifyComplete);
AddField(fnState);
WhereFieldEqual(fnTask, Task);
WhereFieldEqual(fnDeadline, DateOf(Date));
Table:=FDataBase.DB.GetTable(GetSQL);
EndCreate;
Table.MoveFirst;
if Table.RowCount > 0 then
begin
Result:=TRepeatState.Create(Self);
Result.ID:=Table.FieldAsInteger(0);
Result.Task:=Table.FieldAsInteger(1);
Result.DateDeadline:=Table.FieldAsDateTime(2);
Result.DateChange:=Table.FieldAsDateTime(3);
Result.NotifyComplete:=Table.FieldAsBoolean(4);
Result.State:=Table.FieldAsBoolean(5);
end;
Table.Free;
end;
except
end;
end;
procedure TRepeatStates.NotifyComplete(TaskID: Integer; Date: TDate);
var Item:TRepeatState;
begin
Item:=GetItem(TaskID, Date);
if Assigned(Item) then
begin
Item.NotifyComplete:=True;
Item.DateChange:=Now;
Update(Item);
end
else
begin
Item:=TRepeatState.Create(Self);
Item.NotifyComplete:=True;
Item.Task:=TaskID;
Update(Item);
end;
Item.Free;
end;
procedure TRepeatStates.Reload;
var Table:TSQLiteTable;
Item:TRepeatState;
begin
BeginUpdate;
Clear;
try
with SQL.Select(tnTable) do
begin
AddField(fnID);
AddField(fnTask);
AddField(fnDeadline);
AddField(fnDateChange);
AddField(fnNotifyComplete);
AddField(fnState);
WhereFieldEqual(fnTask, TaskID);
Table:=FDataBase.DB.GetTable(GetSQL);
EndCreate;
Table.MoveFirst;
while not Table.EOF do
begin
Item:=TRepeatState.Create(Self);
Item.ID:=Table.FieldAsInteger(0);
Item.Task:=Table.FieldAsInteger(1);
Item.DateDeadline:=Table.FieldAsDateTime(2);
Item.DateChange:=Table.FieldAsDateTime(3);
Item.NotifyComplete:=Table.FieldAsBoolean(4);
Item.State:=Table.FieldAsBoolean(5);
Add(Item);
Table.Next;
end;
Table.Free;
end;
finally
EndUpdate;
end;
end;
procedure TRepeatStates.Update(Item: TRepeatState);
begin
if Item.ID < 0 then
with SQL.InsertInto(tnTable) do
begin
AddValue(fnTask, Item.Task);
AddValue(fnDeadline, DateOf(Item.DateDeadline));
AddValue(fnDateChange, Item.DateChange);
AddValue(fnNotifyComplete, Item.NotifyComplete);
AddValue(fnState, Item.State);
DataBase.DB.ExecSQL(GetSQL);
Item.ID:=DataBase.DB.GetLastInsertRowID;
EndCreate;
end
else
with SQL.Update(tnTable) do
begin
AddValue(fnTask, Item.Task);
AddValue(fnDeadline, DateOf(Item.DateDeadline));
AddValue(fnDateChange, Item.DateChange);
AddValue(fnNotifyComplete, Item.NotifyComplete);
AddValue(fnState, Item.State);
WhereFieldEqual(fnID, Item.ID);
DataBase.DB.ExecSQL(GetSQL);
EndCreate;
end;
end;
procedure TRepeatStates.Save;
var i:Integer;
begin
for i:= 0 to Count-1 do Update(Items[i]);
end;
procedure TRepeatStates.SetDataBase(const Value: TDB);
begin
FDataBase:=Value;
end;
end.
|
{*******************************************************}
{ }
{ Find dialog form }
{ }
{ Last corrections 11.02.99 }
{ }
{*******************************************************}
Unit FindDlgc;
Interface
Uses Forms, StdCtrls, Buttons, Controls, ExtCtrls, Classes,
DB, DBTables, DBIndex, Grids, DBGrids, DBCtrls, LnTables, LnkMisc,
SrcIndex;
type
TLnFindDlg = class(TForm)
EditPanel: TPanel;
ToolsPanel: TPanel;
BtnPanel: TPanel;
OKBtn: TBitBtn;
CancelBtn: TBitBtn;
IndexPanel: TPanel;
FindDataSource: TDataSource;
IndexCheck: TCheckBox;
ChangeKeyBtn: TSpeedButton;
OkContextBtn: TBitBtn;
CloseCheck: TCheckBox;
IndexCombo: TSrcLinkCombo;
NavPanel: TPanel;
Nav1: TDBNavigator;
LikeSource: TDataSource;
procedure IndexComboChange(Sender: TObject);
procedure IndexCheckClick(Sender: TObject);
procedure ChangeKeyBtnClick(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure OKBtnClick(Sender: TObject);
procedure OkContextBtnClick(Sender: TObject);
procedure CloseCheckClick(Sender: TObject);
procedure CancelBtnClick(Sender: TObject);
procedure Nav1Click(Sender: TObject; Button: TNavigateBtn);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure IndexComboKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
FIsNotInitParams: Boolean;
LC:boolean;{!Igo}
FIsNavCancel: Boolean;
FStoreWidth: Integer;
FormHeight: Integer;
ATop,ALeft: Integer;
Lw,Ew: Integer;
TextWidth: Integer;{!Val}
FFindLink: TFindLink;
Lab: TLabel;
Ed: TWinControl;
Field: TField;
Edits: TList;
Labels: TStrings;
function GetIFNCheck: Boolean;
procedure SetIFNCheck(Value: Boolean);
procedure SetFindLink(aFindLink: TFindLink);
procedure UpdateFindLinkValues;
public
procedure InitParams;
procedure DestroyDlg;
procedure InitDlg;
procedure DoneDlg;
procedure GoFind;
property IFNCheck: Boolean read GetIFNCheck write SetIFNCheck;
property FindLink: TFindLink read FFindLink write SetFindLink;
end;
{ TLnFindDlg }
{
var
LnFindDlg: TLnFindDlg;}
implementation
uses Windows, Messages, Dialogs, BDE, XCracks, XDBMisc, FVisDisp;
{$R *.DFM}
function TLnFindDlg.GetIFNCheck: Boolean;
begin
Result:=IndexCheck.Checked;
end;
procedure TLnFindDlg.UpdateFindLinkValues;
begin
end;
procedure TLnFindDlg.SetIFNCheck(Value: Boolean);
begin
IndexCheck.Checked:=Value;
end;
procedure TLnFindDlg.SetFindLink(aFindLink: TFindLink);
begin
if aFindLink<>FFindLink then begin
FFindLink:=aFindLink;
if Assigned(FFindLink) then begin
{}
end;
end;
end;
procedure TLnFindDlg.InitParams;
begin
FIsNotInitParams:=False;
FindDataSource.DataSet:=FindLink.FindDataset;
Labels:=TStringList.Create;
Edits:=TList.Create;
FStoreWidth:=Width;
FIsNavCancel:=False;
TWinControlSelf(NavPanel).SetZOrder(True);
FindDataSource.AutoEdit:=False;
IFNCheck:=FindLink.IFNCheck;
FIsNotInitParams:=True;
end;
procedure TLnFindDlg.DestroyDlg;
begin
DoneDlg;
Edits.Free;
Labels.Free;
end;
procedure TLnFindDlg.InitDlg;
var i: Integer;
aDataset: TDataset;
begin
if Assigned(FindDataSource.DataSet) then begin
Width:=FStoreWidth;
aDataset:=FindDataSource.DataSet;
with aDataset do begin
FindLink.LikeList.Clear;
GetFieldList(FindLink.LikeList, FindLink.IFN);
{ Определили высоту формы }
FormHeight:=FindLink.LikeList.Count;
if FormHeight*28+ToolsPanel.Height+34>=Screen.Height then begin
Height:=Screen.Height-34
end else Height:=FormHeight*28+ToolsPanel.Height+34;
ATop:=8;
ALeft:=EditPanel.Left+4;
Lw:=0; Ew:=0;
for i:=0 to FindLink.LikeList.Count-1 do begin
Field:=TField(FindLink.LikeList.Items[i]);
if Field.Tag=8 then Field:=GetLookField(Field);
Labels.Add(Field.DisplayLabel);
{end;}
{for i:=0 to Labels.Count-1 do begin}
if Length(Labels[i])>Lw then Lw:=Length(Labels[i])+1;
if Field.DisplayWidth>Ew then Ew:=Field.DisplayWidth+2;
end;
if (FindLink.MaxLW>0) and (Lw>FindLink.MaxLW) then Lw:=FindLink.MaxLW;
if (FindLink.MaxEW>0) and (Ew>FindLink.MaxEW) then Ew:=FindLink.MaxLW;{?!}
TextWidth:=Canvas.TextWidth('0');
Lw:=Lw*TextWidth;
Ew:=Ew*TextWidth;
if Left+ALeft+Lw+Ew+16>=Screen.Width then begin
Width:=Screen.Width-ALeft-8;
Ew:=Screen.Width-ALeft-Lw-16;
end else begin
if Lw+Ew+8>Width then Width:=Lw+Ew+20;
end;
for i:=0 to FindLink.LikeList.Count-1 do begin
Field:=TField(FindLink.LikeList.Items[i]);
if Field.Tag=8 then Field:=GetLookField(Field);
Lab:=TLabel.Create(Self);
Labels.Objects[i]:=Lab;
Lab.Top:=ATop;
Lab.Left:=ALeft;
Lab.Caption:=Labels.Strings[i];
{LevTest:=false;}
if Assigned(Field.LookupDataSet) then begin
LC:=true;
Ed:=GetDispLookCombo(Self);
end else begin
LC:=false;
Ed:=GetDispDBEdit(Self);
end;
if LC then begin
if i<FindLink.FindValues.Count then
SetDispLookField(Ed, Field, FindDataSource, FindLink.FindValues[i],
(i<FindLink.FindValues.Count) and (FindLink.FindValues[i]<>''))
else SetDispLookField(Ed, Field, FindDataSource,'',
(i<FindLink.FindValues.Count));
end else begin
if i<FindLink.FindValues.Count then
SetDispDBEditField(Ed, TField(FindLink.LikeList.Items[i]),
FindDataSource, FindLink.FindValues[i], (i<FindLink.FindValues.Count))
else SetDispDBEditField(Ed, TField(FindLink.LikeList.Items[i]),
FindDataSource, '', (i<FindLink.FindValues.Count));
end;
(**)
Ed.Top:=ATop;
Ed.Left:=ALeft+Lw;
(*
if Ew<=(TField(FindLink.LikeList.Items[i]).DisplayWidth+2)*TextWidth then Ed.Width:=Ew
else Ed.Width:=(TField(FindLink.LikeList.Items[i]).DisplayWidth+2)*TextWidth;
*)
if Ew<=(Field.DisplayWidth+2)*TextWidth then Ed.Width:=Ew
else Ed.Width:=(Field.DisplayWidth+2)*TextWidth;
(**)
Lab.FocusControl:=Ed;
Edits.Add(Ed);
EditPanel.InsertControl(Lab);
EditPanel.InsertControl(Ed);
if i=0 then ActiveControl:=Ed;
Inc(ATop,28);
end;
FindLink.SetFindState;
end;
end;
end;
procedure TLnFindDlg.DoneDlg;
var
i: Integer;
begin
for i:=0 to Labels.Count-1 do Labels.Objects[i].Free;
for i:=0 to Edits.Count-1 do TWinControl(Edits.Items[i]).Free;
Labels.Clear;
Edits.Clear;
end;
procedure TLnFindDlg.GoFind;
var aValues: Variant{TStringList};
i: Integer;
IsPriz: Boolean;
begin
IsPriz:=True;
if not Assigned(FindDataSource.DataSet) then Exit;
if FindLink.IsFirstFind then begin
if FindLink.IsLikeFind then begin
LinkDatasetListLocate(FindLink.LikeQuery, FindLink.FindDataset, FindLink.LikeList);
LinkDatasetListLocate(FindLink.LikeQuery, FindLink.ModelDataset, FindLink.LikeList);
end else{ ATable.Next};
end else begin
FindLink.IsFirstFind:=True;
begin
FindLink.CancelFindRange;
UpdateFindLinkValues;
aValues:=FindLink.GetFindValues;
if FindLink.IsLikeFind then begin
LikeSource.DataSet:=FindLink.LikeQuery;
FindLink.ChangeFindLikeValues(aValues);
LinkDatasetListLocate(FindLink.LikeQuery, FindLink.FindDataset, FindLink.LikeList);
LinkDatasetListLocate(FindLink.LikeQuery, FindLink.ModelDataset, FindLink.LikeList);
end else begin
LikeSource.DataSet:=FindLink.FindDataset;
end;
if FindLink.IsLikeFind then begin
NavPanel.Visible:=True;
IndexCombo.Enabled:=False;
{ FindLink.SetFindState;}
for i:=0 to Edits.Count-1 do
TWinControl(Edits[i]).Enabled:=False;
end else
if FindLink.SetFindRange(aValues) and FindLink.IsSetRange then begin
if not FindLink.IsLikeFind then begin
FindLink.FindDataset.First;
NavPanel.Visible:=True;
IndexCombo.Enabled:=False;
for i:=0 to Edits.Count-1 do
TWinControl(Edits[i]).Enabled:=False;
end else TTable(FindLink.FindDataset).GoToNearest;
FindLink.GotoCurrentFind(IsPriz);
end;
end;
end;
VarClear(AValues);
end;
Procedure TLnFindDlg.IndexComboChange(Sender: TObject);
begin
if ((not IndexCombo.DroppedDown) or (IndexCombo.IsKeyReturn))
and Assigned(FindDataSource.DataSet) then begin
DoneDlg;
if FindLink.FindState=ltTable then begin
{FindLink.IFN:=TTable(FindLink.FindDataset).IndexFieldNames;}
FindLink.IFN:=FindLink.IfnLink.Items[IndexCombo.SrcLinks.CurrentIndex].Fields;
TTable(FindLink.FindDataset).IndexFieldNames;
if IndexCheck.Checked then begin
if FindLink.ModelState=ltTable then begin
TTable(TLnTable(FindLink.FindDataset).CloneMaster).IndexFieldNames:=FindLink.IFN;
{???}
end;
end;
end;
InitDlg;
IndexCombo.ActiveChanged;
end;
end;
procedure TLnFindDlg.IndexCheckClick(Sender: TObject);
begin
if FIsNotInitParams then begin
if Assigned(FindDataSource.DataSet) then begin
if FindLink.FindState=ltTable then begin
if IndexCheck.Checked then
if FindLink.ModelState=ltTable then
TTable(TLnTable(FindLink.FindDataset).CloneMaster).IndexFieldNames:=
TLnTable(FindLink.FindDataset).IndexFieldNames;
end;
end;
SelectFirst;
end;
FindLink.IFNCheck:=IndexCheck.Checked;
end;
procedure TLnFindDlg.ChangeKeyBtnClick(Sender: TObject);
begin
if FindLink.IFNItem.ChooseOrderFields(FindLink.FindDataset, 'поиск') then begin
DoneDlg;
if FindLink.FindState=ltTable then begin
TTable(FindLink.FindDataset).IndexFieldNames:=FindLink.IFN;
IndexCombo.SrcLinkItem:=FindLink.IFNItem;
IndexCombo.SrcLinks.CurrentIndex:=TIFNLink(IndexCombo.SrcLinks).IndexOfFields(FindLink.IFN);
if IndexCheck.Checked then begin
if FindLink.ModelState=ltTable then
TTable(TLnTable(FindLink.FindDataset).CloneMaster).IndexFieldNames:=FindLink.IFN;
end;
end;
(*
else
if (FindLink.FindState=ltQuery)and(FindLink.ModelState=ltQuery) then begin
if Assigned(FindLink.FindDataset) then begin
FindLink.FindDataset.Active:=False;
FindLink.FindDataset.Free;
end;
FindLink.FindDataset:=GetLinkCloneDataset(FindLink.ModelDataset, FindLink.ModelState, FindLink.FindState,
FindLink.ModelTableName, FindLink.ModelFieldNames, True{False}, True, FindLink.IFN, True);
TQuery(FindLink.FindDataset).RequestLive:=True;
FindDataSource.Dataset:=FindLink.FindDataset;
end;
*)
InitDlg;
end;
end;
procedure TLnFindDlg.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
if ModalResult=mrOk then begin
CanClose:=CloseCheck.Checked;
if (not CanClose) and Assigned(FindDataSource.DataSet) then GoFind;
end;
if (ModalResult=mrCancel)and FIsNavCancel then begin
FIsNavCancel:=False;
CanClose:=False;
end;
if CanClose and (ModalResult=mrOk) then GoFind;
end;
procedure TLnFindDlg.OKBtnClick(Sender: TObject);
begin
FindLink.IsLikeFind:=False;
SelectFirst;
end;
procedure TLnFindDlg.OkContextBtnClick(Sender: TObject);
begin
FindLink.IsLikeFind:=True;
SelectFirst;
end;
procedure TLnFindDlg.CloseCheckClick(Sender: TObject);
begin
FindLink.IsFirstFind:=False;
SelectFirst;
end;
procedure TLnFindDlg.CancelBtnClick(Sender: TObject);
var i: Integer;
begin
if FindLink.IsFirstFind then begin
FIsNavCancel:=True;
IndexCombo.Enabled:=True;
for i:=0 to Edits.Count-1 do TWinControl(Edits[i]).Enabled:=True;
NavPanel.Visible:=False;
FindLink.CancelFind;
end;
SelectFirst;
end;
Procedure TLnFindDlg.Nav1Click(Sender: TObject; Button: TNavigateBtn);
begin
GoFind;
end;
Procedure TLnFindDlg.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
if ((ActiveControl is TDBLookUpComboBox) and
(TDBLookUpComboBox(ActiveControl).ListVisible)) then Exit;
if (Key=VK_Return) and (Shift=[]) and
(EditPanel.ControlCount>0) and
(ActiveControl=EditPanel.Controls[EditPanel.ControlCount-1])
then begin
OkBtn.Click;
ModalResult:=mrOk;
Key:=0;
end else
if ssCtrl in Shift then begin
case Key of
Word('F'): OkContextBtn.Click;
Word('C'): CancelBtn.Click;
Word('B'): begin
IndexCheck.Checked:=not IndexCheck.Checked;
IndexCheckClick(Sender);
end;
Word('P'): begin
CloseCheck.Checked:=not CloseCheck.Checked;
CloseCheckClick(Sender);
end;
Word('K'): if IndexCombo.Focused and (not IndexCombo.DroppedDown) then SelectFirst
else begin
IndexCombo.SetFocus;
IndexCombo.DroppedDown:=True;
end;
end;
if Key in [Word('F'),Word('S'),Word('C'),Word('B'),Word('P'),Word('K')] then Key:=0;
end;
Inherited;
end;
procedure TLnFindDlg.IndexComboKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key=VK_RETURN then IndexComboChange(Sender);
end;
end.
|
{******************************************************************************}
{ }
{ Icon Fonts ImageList: An extended ImageList for Delphi }
{ to simplify use of Icons (resize, colors and more...) }
{ }
{ Copyright (c) 2019-2023 (Ethea S.r.l.) }
{ Contributors: }
{ Carlo Barazzetta }
{ Nicola Tambascia }
{ }
{ https://github.com/EtheaDev/IconFontsImageList }
{ }
{******************************************************************************}
{ }
{ 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 IconFontsCharMapUnit;
interface
{$INCLUDE ..\Source\IconFontsImageList.inc}
uses
Windows
, Messages
, SysUtils
, Graphics
, Forms
, StdCtrls
, ExtCtrls
, Controls
, Classes
, Dialogs
, ComCtrls
, ImgList
, ExtDlgs
, Spin
, IconFontsImageListBase
, IconFontsImageList
, ActnList
, IconFontsItems
, IconFontsImage
{$IFDEF DXE3+}, System.Actions{$ENDIF}
;
type
TIconFontsCharMapForm = class(TForm)
ImageListGroup: TGroupBox;
ImageView: TListView;
paTop: TPanel;
paClient: TPanel;
IconBuilderGroupBox: TGroupBox;
CharsEdit: TEdit;
CopyToclipboardButton: TButton;
ImageGroup: TGroupBox;
FontIconHexLabel: TLabel;
FontIconDecLabel: TLabel;
MainPanel: TPanel;
MainImage: TIconFontImage;
FontIconHex: TEdit;
FontIconDec: TEdit;
DefaultFontName: TComboBox;
DefaultFontNameLabel: TLabel;
cbShowSurrogate: TCheckBox;
ProgressBar: TProgressBar;
ActionList: TActionList;
CopyToCipboardAction: TAction;
ShowCaptionsCheckBox: TCheckBox;
IconName: TEdit;
IconNameLabel: TLabel;
BottomPanel: TPanel;
OKButton: TButton;
HelpButton: TButton;
CancelButton: TButton;
procedure FormCreate(Sender: TObject);
procedure AddButtonClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure HelpButtonClick(Sender: TObject);
procedure ImageViewSelectItem(Sender: TObject; Item: TListItem;
Selected: Boolean);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure BuildAllIcons(const ASurrogate: Boolean = False);
procedure EditChangeUpdateGUI(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure ImageViewMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure cbShowSurrogateClick(Sender: TObject);
procedure ImageViewDblClick(Sender: TObject);
procedure OKButtonClick(Sender: TObject);
procedure ActionListUpdate(Action: TBasicAction; var Handled: Boolean);
procedure CopyToCipboardActionExecute(Sender: TObject);
procedure CopyToCipboardActionUpdate(Sender: TObject);
procedure DefaultFontNameSelect(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
procedure CancelButtonClick(Sender: TObject);
procedure ShowCaptionsCheckBoxClick(Sender: TObject);
private
FStopped: Boolean;
FBuilding: Boolean;
FFirstTime: Boolean;
FMaxIcons: Integer;
FFirstIcon: Integer;
FTotIcons: Integer;
FIconsCount: Integer;
FIconIndexLabel: string;
FUpdating: Boolean;
FCharMapList: TIconFontsImageList;
FIconFontItems: TIconFontItems;
FImageListCaption: string;
procedure DrawIconProgress(const ASender: TObject; const ACount: Integer;
const AItem: TIconFontItem);
function AssignSource(AIconFontsImageList: TIconFontsImageListBase;
const AFontName: TFontName = ''): Boolean;
procedure AddNewItem;
procedure ClearAllImages;
procedure UpdateGUI;
procedure UpdateCharsToBuild;
function GetFontName: TFontName;
procedure SetFontName(const Value: TFontName);
//Events for notification from item to imagelist
procedure CheckFontName(const AFontName: TFontName);
procedure OnItemChanged(Sender: TIconFontItem);
procedure GetOwnerAttributes(out AFontName: TFontName;
out AFontColor, AMaskColor: TColor);
procedure BuildList(Selected: Integer);
public
function SelectedIconFont: TIconFontItem;
constructor Create(AOwner: TComponent); override;
constructor CreateForFont(AOwner: TComponent;
const AFontName: TFontName; const ASize: Integer = 32;
const AFontColor: TColor = clDefault; const AMaskColor: TColor = clNone); virtual;
constructor CreateForImageList(AOwner: TComponent;
AIconFontsImageList: TIconFontsImageListBase;
const AFontName: TFontName = ''); virtual;
procedure AssignImageList(const AIconFontsImageList: TIconFontsImageListBase;
const AFontName: TFontName = '');
property FontName: TFontName read GetFontName write SetFontName;
end;
function ShowIconFontsCharMap(const AFontName: TFontName;
const ASize: Integer = 32;
const AFontColor: TColor = clBlack;
const AMaskColor: TColor = clWhite): string;
implementation
{$R *.dfm}
uses
CommCtrl
, TypInfo
, ShellApi
{$IFDEF D2010+}
, Icons.Utils
{$ENDIF}
//WARNING: you must define this directive to use this unit outside the IDE
{$IFNDEF UseIconFontEditorsAtRunTime}
{$IF (CompilerVersion >= 24.0)}
, Vcl.Themes
, ToolsAPI
{$IFEND}
{$IF (CompilerVersion >= 32.0)}
, IDETheme.Utils
, BrandingAPI
{$IFEND}
{$ENDIF}
, IconFontsUtils
;
const
crColorPick = -100;
var
SavedBounds: TRect = (Left: 0; Top: 0; Right: 0; Bottom: 0);
function ShowIconFontsCharMap(const AFontName: TFontName;
const ASize: Integer = 32;
const AFontColor: TColor = clBlack;
const AMaskColor: TColor = clWhite): string;
var
IconFontsCharMapForm: TIconFontsCharMapForm;
begin
IconFontsCharMapForm := TIconFontsCharMapForm.CreateForFont(nil, AFontName,
ASize, AFontColor, AMaskColor);
try
if IconFontsCharMapForm.ShowModal = mrOk then
Result := IconFontsCharMapForm.CharsEdit.Text
else
Result := '';
finally
IconFontsCharMapForm.Free;
end;
end;
{ TIconFontsCharMapForm }
procedure TIconFontsCharMapForm.HelpButtonClick(Sender: TObject);
begin
ShellExecute(handle, 'open',
PChar('https://github.com/EtheaDev/IconFontsImageList/wiki/CharMap'), nil, nil,
SW_SHOWNORMAL)
end;
procedure TIconFontsCharMapForm.UpdateCharsToBuild;
begin
CharsEdit.Font.Size := 14;
if DefaultFontName.Text <> '' then
begin
CharsEdit.Font.Name := FCharMapList.FontName;
CharsEdit.Enabled := True;
end
else
begin
CharsEdit.Enabled := False;
CopyToClipboardButton.Enabled := False;
end;
end;
procedure TIconFontsCharMapForm.UpdateGUI;
var
LIsItemSelected: Boolean;
LItemFontName: TFontName;
LIconFontItem: TIconFontItem;
begin
FUpdating := True;
try
LIconFontItem := SelectedIconFont;
LIsItemSelected := LIconFontItem <> nil;
CopyToClipboardButton.Enabled := CharsEdit.Text <> '';
if LIsItemSelected then
begin
ImageGroup.Caption := Format(FIconIndexLabel,[LIconFontItem.Index]);
LItemFontName := LIconFontItem.FontName;
FontIconDec.Text := IntToStr(LIconFontItem.FontIconDec);
FontIconHex.Text := LIconFontItem.FontIconHex;
IconName.Text := LIconFontItem.IconName;
MainPanel.Invalidate;
end
else
begin
FontIconDec.Text := '0';
FontIconHex.Text := '';
end;
if LIsItemSelected then
MainImage.ImageIndex := LIconFontItem.Index
else
MainImage.ImageIndex := -1;
finally
FUpdating := False;
end;
end;
procedure TIconFontsCharMapForm.CancelButtonClick(Sender: TObject);
begin
if not FBuilding then
begin
ModalResult := mrCancel;
Close;
end;
end;
procedure TIconFontsCharMapForm.CheckFontName(const AFontName: TFontName);
begin
//Don't check anything
end;
procedure TIconFontsCharMapForm.ClearAllImages;
begin
Screen.Cursor := crHourglass;
try
FCharMapList.ClearIcons;
ImageView.Clear;
finally
Screen.Cursor := crDefault;
end;
end;
procedure TIconFontsCharMapForm.DrawIconProgress(const ASender: TObject;
const ACount: Integer;
const AItem: TIconFontItem);
var
LPosition: Integer;
LTotCount: Integer;
begin
LTotCount := (FMaxIcons-FFirstIcon);
if ACount <>0 then
FIconsCount := ACount
else
FIconsCount := FTotIcons+1;
LPosition := Round(FIconsCount*100 / LTotCount);
if ProgressBar.Position <> LPosition then
begin
ProgressBar.Position := LPosition;
Application.ProcessMessages;
if FStopped then
Abort;
end;
end;
constructor TIconFontsCharMapForm.Create(AOwner: TComponent);
begin
FCharMapList := TIconFontsImageList.Create(Self);
FCharMapList.OnDrawIcon := DrawIconProgress;
FFirstTime := True;
inherited;
MainImage.ImageList := FCharMapList;
end;
constructor TIconFontsCharMapForm.CreateForFont(AOwner: TComponent;
const AFontName: TFontName; const ASize: Integer = 32;
const AFontColor: TColor = clDefault; const AMaskColor: TColor = clNone);
begin
Create(AOwner);
FCharMapList.FontName := AFontName;
FCharMapList.Size := ASize;
if AFontColor <> clDefault then
FCharMapList.FontColor := AFontColor
else
FCharMapList.FontColor := clWindowText;
if AMaskColor <> clNone then
FCharMapList.MaskColor := AMaskColor
else
FCharMapList.MaskColor := clBtnFace;
end;
function TIconFontsCharMapForm.AssignSource(AIconFontsImageList: TIconFontsImageListBase;
const AFontName: TFontName = ''): Boolean;
var
LFontName: TFontName;
begin
Result := False;
if AFontName <> '' then
LFontName := AFontName
else
LFontName := AIconFontsImageList.FontName;
if LFontName = '' then
Exit;
if FCharMapList.FontName <> LFontName then
begin
FCharMapList.FontName := LFontName;
Result := True;
end;
if FCharMapList.Size <> AIconFontsImageList.Size then
begin
FCharMapList.Size := AIconFontsImageList.Size;
Result := True;
end;
if FCharMapList.FontColor <> AIconFontsImageList.FontColor then
begin
FCharMapList.FontColor := AIconFontsImageList.FontColor;
Result := True;
end;
if FCharMapList.MaskColor <> AIconFontsImageList.MaskColor then
begin
FCharMapList.MaskColor := AIconFontsImageList.MaskColor;
Result := True;
end;
ClearAllImages;
end;
constructor TIconFontsCharMapForm.CreateForImageList(
AOwner: TComponent;
AIconFontsImageList: TIconFontsImageListBase;
const AFontName: TFontName = '');
begin
Create(AOwner);
AssignSource(AIconFontsImageList, AFontName);
end;
procedure TIconFontsCharMapForm.ImageViewDblClick(Sender: TObject);
begin
if (SelectedIconFont <> nil) then
CharsEdit.Text := CharsEdit.Text + SelectedIconFont.Character;
end;
procedure TIconFontsCharMapForm.ImageViewMouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
LSelected: TListItem;
LIconFontItem: TIconFontItem;
begin
if (ssCtrl in Shift) then
begin
LSelected := ImageView.GetItemAt(X,Y);
if Assigned(LSelected) then
begin
LIconFontItem := FCharMapList.IconFontItems[LSelected.Index];
CharsEdit.Text := CharsEdit.Text + LIconFontItem.Character;
end;
end;
end;
procedure TIconFontsCharMapForm.ImageViewSelectItem(Sender: TObject;
Item: TListItem; Selected: Boolean);
begin
if Selected then
UpdateGUI;
end;
procedure TIconFontsCharMapForm.OKButtonClick(Sender: TObject);
begin
if not FBuilding then
begin
ModalResult := mrOK;
Close;
end;
end;
procedure TIconFontsCharMapForm.OnItemChanged(Sender: TIconFontItem);
begin
;
end;
procedure TIconFontsCharMapForm.DefaultFontNameSelect(Sender: TObject);
begin
if FCharMapList.FontName <> DefaultFontName.Text then
begin
FCharMapList.ClearIcons;
FCharMapList.FontName := DefaultFontName.Text;
BuildAllIcons;
end;
end;
procedure TIconFontsCharMapForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if ModalResult = mrOK then
OKButton.SetFocus;
end;
procedure TIconFontsCharMapForm.FormCreate(Sender: TObject);
{$IFNDEF UseIconFontEditorsAtRunTime}
{$IF (CompilerVersion >= 32.0)}
var
LStyle: TCustomStyleServices;
{$IFEND}
{$ENDIF}
begin
{$IFNDEF UseIconFontEditorsAtRunTime}
{$IF (CompilerVersion >= 32.0)}
{$IF (CompilerVersion <= 34.0)}
if UseThemeFont then
Self.Font.Assign(GetThemeFont);
{$IFEND}
{$IF CompilerVersion > 34.0}
if TIDEThemeMetrics.Font.Enabled then
Self.Font.Assign(TIDEThemeMetrics.Font.GetFont);
{$IFEND}
if ThemeProperties <> nil then
begin
LStyle := ThemeProperties.StyleServices;
StyleElements := StyleElements - [seClient];
Color := LStyle.GetSystemColor(clWindow);
BottomPanel.StyleElements := BottomPanel.StyleElements - [seClient];
BottomPanel.ParentBackground := False;
BottomPanel.Color := LStyle.GetSystemColor(clBtnFace);
IDEThemeManager.RegisterFormClass(TIconFontsCharMapForm);
ThemeProperties.ApplyTheme(Self);
end;
{$IFEND}
{$ENDIF}
{$IF (CompilerVersion >= 24.0)}
ImageView.AlignWithMargins := True;
ImageView.Margins.Top := 6;
{$IFEND}
{$IFDEF D2010+}
cbShowSurrogate.Visible := True;
{$ELSE}
cbShowSurrogate.Visible := False;
{$ENDIF}
FImageListCaption := ImageListGroup.Caption;
ImageListGroup.Caption := '';
ImageView.LargeImages := FCharMapList;
ImageView.SmallImages := FCharMapList;
Caption := Format(Caption, [IconFontsImageListVersion]);
FUpdating := True;
FIconFontItems := TIconFontItems.Create(FCharMapList, TIconFontItem,
OnItemChanged, CheckFontName, GetOwnerAttributes);
DefaultFontName.Items := Screen.Fonts;
FIconIndexLabel := ImageGroup.Caption;
end;
procedure TIconFontsCharMapForm.FormDestroy(Sender: TObject);
begin
FreeAndNil(FIconFontItems);
Screen.Cursors[crColorPick] := 0;
end;
procedure TIconFontsCharMapForm.FormKeyPress(Sender: TObject; var Key: Char);
begin
if (Key = #27) and FBuilding then
begin
FStopped := True;
Key := #0;
end;
end;
procedure TIconFontsCharMapForm.FormShow(Sender: TObject);
begin
CharsEdit.Text := '';
if FFirstTime or FStopped or (ImageView.Items.Count = 0) then
begin
FStopped := False;
FCharMapList.ClearIcons;
DefaultFontName.ItemIndex := -1;
DefaultFontName.Text := '';
FFirstTime := True;
end;
if ImageView.CanFocus then
ImageView.SetFocus;
end;
function TIconFontsCharMapForm.GetFontName: TFontName;
begin
Result := DefaultFontName.Text;
end;
procedure TIconFontsCharMapForm.GetOwnerAttributes(out AFontName: TFontName;
out AFontColor, AMaskColor: TColor);
begin
AFontName := FCharMapList.FontName;
AFontColor := FCharMapList.FontColor;
AMaskColor := FCharMapList.MaskColor;
end;
procedure TIconFontsCharMapForm.EditChangeUpdateGUI(Sender: TObject);
begin
UpdateGUI;
end;
function TIconFontsCharMapForm.SelectedIconFont: TIconFontItem;
begin
if (ImageView.Selected <> nil) and (ImageView.Selected.Index < FCharMapList.IconFontItems.Count) then
Result := FCharMapList.IconFontItems[ImageView.Selected.Index]
else
Result := nil;
end;
procedure TIconFontsCharMapForm.SetFontName(const Value: TFontName);
begin
if (Value <> '') and (DefaultFontName.Text <> Value) then
begin
DefaultFontName.ItemIndex := DefaultFontName.Items.IndexOf(Value);
BuildAllIcons;
end;
end;
procedure TIconFontsCharMapForm.ShowCaptionsCheckBoxClick(Sender: TObject);
begin
Screen.Cursor := crHourGlass;
Try
UpdateIconFontListViewCaptions(ImageView, ShowCaptionsCheckBox.Checked);
Finally
Screen.Cursor := crDefault;
End;
end;
procedure TIconFontsCharMapForm.ActionListUpdate(Action: TBasicAction;
var Handled: Boolean);
begin
if FFirstTime and Assigned(FCharMapList) then
begin
FFirstTime := False;
FontName := FCharMapList.FontName;
UpdateGUI;
end;
end;
procedure TIconFontsCharMapForm.AddButtonClick(Sender: TObject);
begin
AddNewItem;
end;
procedure TIconFontsCharMapForm.AddNewItem;
var
LInsertIndex: Integer;
begin
if (ImageView.Selected <> nil) then
LInsertIndex := ImageView.Selected.Index +1
else
LInsertIndex := ImageView.Items.Count;
ImageView.Selected := nil;
FCharMapList.IconFontItems.Insert(LInsertIndex);
//UpdateIconFontListView(ImageView);
ImageView.ItemIndex := LInsertIndex;
end;
procedure TIconFontsCharMapForm.AssignImageList(
const AIconFontsImageList: TIconFontsImageListBase;
const AFontName: TFontName = '');
begin
if AssignSource(AIconFontsImageList, AFontName) then
begin
FontName := '';
FFirstTime := True;
end;
end;
procedure TIconFontsCharMapForm.CopyToCipboardActionExecute(Sender: TObject);
begin
CharsEdit.SelectAll;
CharsEdit.CopyToClipboard;
end;
procedure TIconFontsCharMapForm.CopyToCipboardActionUpdate(Sender: TObject);
begin
CopyToCipboardAction.Enabled := CharsEdit.Text <> '';
end;
procedure TIconFontsCharMapForm.BuildAllIcons(const ASurrogate: Boolean = False);
var
LStart, LEnd: Integer;
{$IFDEF D2010+}
LIconCollection: TIconCollection;
{$ENDIF}
LFontName: string;
begin
Screen.Cursor := crHourGlass;
try
paClient.Enabled := False;
BottomPanel.Enabled := False;
ImageView.Enabled := False;
IconBuilderGroupBox.Enabled := False;
FStopped := False;
LFontName := DefaultFontName.Text;
if not ASurrogate then
begin
{$IFDEF D2010+}
cbShowSurrogate.Visible := True;
{$ENDIF}
end;
if FCharMapList.Count > 0 then
FFirstIcon := FCharMapList.Count-1
else
FFirstIcon := -1;
ImageView.Clear;
//Check for metadata font registered
{$IFDEF D2010+}
if TIconManager.Instance.FindCollection(LFontName, LIconCollection) then
begin
IconName.Visible := True;
IconNameLabel.Visible := True;
cbShowSurrogate.Visible := False;
ProgressBar.Position := 0;
FBuilding := True;
Try
//If metadata exists iterate to add icons into CharMap
ProgressBar.Visible := True;
ImageView.Items.BeginUpdate;
FMaxIcons := 0;
LIconCollection.ForEach(
function (const Entry: TIconEntry): Boolean
begin
Result := True;
Inc(FMaxIcons);
end);
FCharMapList.StopDrawing(True);
try
LIconCollection.ForEach(
function (const Entry: TIconEntry): Boolean
begin
Result := True;
FCharMapList.AddIcon(
Entry.codepoint,
Entry.name);
Inc(FTotIcons);
end);
finally
FCharMapList.StopDrawing(False);
FCharMapList.RecreateBitmaps;
end;
Finally
ImageView.Items.EndUpdate;
FBuilding := False;
ProgressBar.Visible := False;
ImageListGroup.Caption := Format(FImageListCaption, [FIconsCount]);
BuildList(FFirstIcon);
End;
end
else
{$ENDIF}
begin
IconName.Visible := False;
IconNameLabel.Visible := False;
if not ASurrogate then
begin
//Clear
FTotIcons := 0;
CharsEdit.Text := '';
ImageListGroup.Caption := '';
ClearAllImages;
//Normal Chars
LStart := $0001;
LEnd := $FFFF;
end
else
begin
//Surrogate Pairs Chars
LStart := $F0000;
LEnd := $FFFFF;
end;
FMaxIcons := LEnd - LStart;
ProgressBar.Position := 0;
FBuilding := True;
Try
ImageView.Items.BeginUpdate;
ProgressBar.Visible := True;
FTotIcons := FTotIcons + FCharMapList.AddIcons(
LStart, //From Chr
LEnd, //To Chr
LFontName,
FCharMapList.FontColor,
FCharMapList.MaskColor,
True);
Finally
ImageView.Items.EndUpdate;
FBuilding := False;
ProgressBar.Visible := False;
ImageListGroup.Caption := Format(FImageListCaption, [FIconsCount]);
BuildList(FFirstIcon);
End;
end;
finally
IconBuilderGroupBox.Enabled := True;
ImageView.Enabled := True;
BottomPanel.Enabled := True;
paClient.Enabled := True;
Screen.Cursor := crDefault;
end;
end;
procedure TIconFontsCharMapForm.BuildList(Selected: Integer);
begin
Screen.Cursor := crHourGlass;
try
UpdateIconFontListView(ImageView, '');
if Selected < -1 then
Selected := -1
else if (Selected = -1) and (ImageView.Items.Count > 0) then
Selected := 0
else if Selected >= ImageView.Items.Count then
Selected := ImageView.Items.Count - 1;
ImageView.ItemIndex := Selected;
if Self.Visible and (ImageView.ItemIndex >= 0) and ImageView.CanFocus then
ImageView.SetFocus;
UpdateCharsToBuild;
finally
Screen.Cursor := crDefault;
end;
end;
procedure TIconFontsCharMapForm.cbShowSurrogateClick(Sender: TObject);
begin
BuildAllIcons(cbShowSurrogate.Checked);
end;
end.
|
unit USrvSnapFarmaReportService;
interface
uses
Winapi.Windows,
System.SysUtils,
Vcl.SvcMgr,
USnapFarmaReportServiceThread;
type
TSnapFarmaReportServiceService = class(TService)
procedure ServiceAfterInstall(Sender: TService);
procedure ServiceStart(Sender: TService; var Started: Boolean);
procedure ServiceStop(Sender: TService; var Stopped: Boolean);
procedure ServiceShutdown(Sender: TService);
private
{ Private declarations }
SnapFarmaReportServiceThread : TSnapFarmaReportServiceThread;
FDebug: integer;
procedure ServiceStopShutdown;
function directorio_dll: string;
procedure SetDebug(const Value: integer);
public
{ Public declarations }
function GetServiceController: TServiceController; override;
property Debug: integer read FDebug write SetDebug;
end;
var
SnapFarmaReportServiceService: TSnapFarmaReportServiceService;
implementation
{$R *.DFM}
uses ULogger, URegistry;
procedure ServiceController(CtrlCode: DWord); stdcall;
begin
SnapFarmaReportServiceService.Controller(CtrlCode);
end;
function TSnapFarmaReportServiceService.directorio_dll: string;
var
FileName : array[0..MAX_PATH] of char;
path : string;
begin
try
FillChar(FileName, sizeof(FileName), #0);
GetModuleFileName(hInstance, FileName, sizeof(FileName));
path := FileName;
path := ExtractFilePath(path);
path := copy(path, pos(':', path) - 1, length(path));
Result := path;
except
on e : Exception do log_always(e.Message);
end;
end;
function TSnapFarmaReportServiceService.GetServiceController: TServiceController;
begin
Result := ServiceController;
end;
procedure TSnapFarmaReportServiceService.ServiceAfterInstall(Sender: TService);
begin
//Pone la descripcion en el panel de administracion de servicios
SetRegistryValue('\SYSTEM\CurrentControlSet\Services\' + Name, 'Description', 'Servicio de Reportes automaticos para Farmacia - www.snappler.com');
end;
procedure TSnapFarmaReportServiceService.ServiceShutdown(Sender: TService);
begin
ServiceStopShutdown;
end;
procedure TSnapFarmaReportServiceService.ServiceStart(Sender: TService;
var Started: Boolean);
var
BasePath: string;
begin
//Primero leo las claves del registro que necesito
Debug := GetRegistryDebug;
BasePath := directorio_dll;
//Escribo el basepath al registro para que lo pueda tomar la unit ULogger
SetRegistryValue('\SOFTWARE\Snappler\SnapFarmaReportService', 'BasePath', BasePath);
log_always('========================================Start del Servicio=======================================');
log('El BasePath es: ' + BasePath);
// Allocate resources here that you need when the service is running
{ Create an instance of the secondary thread where your service code is placed }
SnapFarmaReportServiceThread := TSnapFarmaReportServiceThread.Create;
{ Set misc. properties you need (if any) in your thread }
SnapFarmaReportServiceThread.Start;
end;
procedure TSnapFarmaReportServiceService.ServiceStop(Sender: TService;
var Stopped: Boolean);
begin
ServiceStopShutdown;
end;
procedure TSnapFarmaReportServiceService.ServiceStopShutdown;
begin
// Deallocate resources here
if Assigned(SnapFarmaReportServiceThread) then
begin
// The TService must WaitFor the thread to finish (and free it)
// otherwise the thread is simply killed when the TService ends.
SnapFarmaReportServiceThread.Terminate;
SnapFarmaReportServiceThread.WaitFor;
FreeAndNil(SnapFarmaReportServiceThread);
end;
end;
procedure TSnapFarmaReportServiceService.SetDebug(const Value: integer);
begin
FDebug := Value;
end;
end.
|
{
ClickFORMS
(C) Copyright 1998 - 2010, Bradford Technologies, Inc.
All Rights Reserved.
Purpose: A portal to the Pictometry imagery service.
}
unit UPictometry;
interface
uses
Classes,
PictometryService,
SysUtils,
UContainer,
UFormPictometry,
UAWSI_Utils,
AWSI_Server_Pictometry,
UWinUtils,
UGlobals;
type
/// summary: An enumeration of directions for which Pictometry provides imagery.
TDirection = (dOrthogonal, dNorth, dEast, dSouth, dWest);
/// summary: An enumeration of faces for which Pictometry provides imagery.
TFace = (fOverhead, fFront, fBack, fLeft, fRight);
/// summary: A portal to the Pictometry imagery service.
TPictometryPortal = class
private
FDocument: TContainer;
FImageEast: TMemoryStream;
FImageNorth: TMemoryStream;
FImageOrthogonal: TMemoryStream;
FImageSouth: TMemoryStream;
FImageWest: TMemoryStream;
FUserCredentials: UserCredentials;
function GetFaceImageStream(const Face: TFace): TStream;
function GetFaceImageStream2(const Face: TFace; var ImageCaption: String): TStream;
procedure HandleServiceError(const E: Exception);
function GetCFDB_SearchByAddress(const Street: String; const City: String; const State: String; const Zip: String): Boolean;
procedure GetCFAW_SearchByAddress(const Street: String; const City: String; const State: String; const Zip: String);
procedure ReadMapSettingsFromIni;
protected
procedure FillFormSubjectAerialPhoto;
procedure Reset;
procedure SetDocument(const Document: TContainer);
procedure ShowModal;
procedure GetPictometryFromService(AddrInfo: AddrInfoRec);
procedure TransferPictometryToReport(doc: TContainer);
public
FPictometryWidth,FPictometryHeight: Integer;
constructor Create;
destructor Destroy; override;
property Document: TContainer read FDocument write SetDocument;
class procedure Execute(const Document: TContainer);
end;
procedure LoadPictometry(doc: TContainer; AddrInfo: AddrInfoRec);
function LoadSubjectParceView(Lat, Lon: Double; var ParcelImageView: WideString): Boolean;
function LoadSubjectParceViewByAddr(Street, city, state, zip: String; var ParcelImageView: WideString): Boolean;
implementation
uses
Controls,
Forms,
InvokeRegistry,
RIO,
SoapHTTPClient,
Types,
UCell,
UCustomerServices,
UDebugTools,
UExceptions,
UForm,
ULicUser,
UMain,
UStatus,
UStrings,
UUtil1,
UWebConfig,
Jpeg,
UBase64,
iniFiles;
const
// number of images to download
nPictImages = 5;
errNotAllImagesAvailable = 'Only %d images available for the address!';
// *** BTWSI Service Error Codes **********************************************
/// summary: Error code for the message, 'UnknownError'
CServiceError_UnknownError = 1;
/// summary: Error code for the message, 'Invalid Credential'
CServiceError_AuthorizationFailed = 2;
/// summary: Error code for the message, 'Customer does not exist on DB'
CServiceError_InvalidCustomer = 3;
/// summary: Error code for the message, 'Customer does not have the service'
CServiceError_NoActiveSubscription = 4;
/// summary: Error code for the message, 'No available service units'
CServiceError_AllUnitsConsumed = 5;
/// summary: Error code for the message, 'Service Expired'
CServiceError_AllUnitsExpired = 6;
/// summary: Error code for the message, 'Unknown Error, please try later'
CServiceError_WaitSubsequentRequestDelay = 7;
/// summary: Error code for the message, 'Can not get images from Pictometry Service'
CServiceError_ImagesUnavailable = 8;
/// summary: Error code for the message, 'Cannot update service usage'
CServiceError_DatabaseError = 9;
// *** Service Configuration **************************************************
/// summary: Timeout in milliseconds for Pictometry service calls.
CTimeoutPictometryService = 90000; // 90 seconds
// *** Unit ******************************************************************
/// summary: Loads a dynamic byte array into a stream.
procedure ByteDynArrayToStream(const ByteDynArray: TByteDynArray; const Stream: TStream);
var
Size: Integer;
begin
if not (Assigned(ByteDynArray) and Assigned(Stream)) then
//raise EArgumentException.Create('Parameter is nil');
exit;
Size := Length(ByteDynArray);
Stream.WriteBuffer(PChar(ByteDynArray)^, Size);
end;
// *** TPictometryPortal *****************************************************
/// summary: Creates a new instance of TPictometryPortal.
constructor TPictometryPortal.Create;
begin
try
FImageEast := TMemoryStream.Create;
FImageNorth := TMemoryStream.Create;
FImageOrthogonal := TMemoryStream.Create;
FImageSouth := TMemoryStream.Create;
FImageWest := TMemoryStream.Create;
FUserCredentials := UserCredentials.Create;
ReadMapSettingsFromIni;
inherited Create;
except on E:Exception do
begin
HandleServiceError(E);
Abort;
end;
end;
end;
/// summary: Frees memory and releases resources.
destructor TPictometryPortal.Destroy;
begin
FreeAndNil(FImageEast);
FreeAndNil(FImageNorth);
FreeAndNil(FImageOrthogonal);
FreeAndNil(FImageSouth);
FreeAndNil(FImageWest);
FreeAndNil(FUserCredentials);
inherited;
end;
procedure TPictometryPortal.ReadMapSettingsFromIni;
var
INIFile: TINIFile;
Region: TRect;
begin
INIFile := TINIFile.Create(IncludeTrailingPathDelimiter(appPref_DirPref) + cClickFormsINI);
try
finally
INIFile.Free;
end;
end;
/// summary: Responds to the OnExecute event of the SearchByAddress action on the pictometry form.
procedure TPictometryPortal.GetPictometryFromService(AddrInfo: AddrInfoRec);
var
PreviousEnabled: Boolean;
nImages: Integer;
begin
PushMouseCursor(crHourglass);
try
if not GetCFDB_SearchByAddress(AddrInfo.StreetAddr, AddrInfo.City, AddrInfo.State, AddrInfo.Zip) then
if CurrentUser.OK2UseAWProduct(pidPictometry, False, False) then
GetCFAW_SearchByAddress(AddrInfo.StreetAddr, AddrInfo.City, AddrInfo.State, AddrInfo.Zip);
FImageOrthogonal.Position := 0;
FImageNorth.Position := 0;
FImageSouth.Position := 0;
FImageWest.Position := 0;
FImageEast.Position := 0;
// nImages := FPictometryForm.LoadFormImages(FImageOrthogonal, FImageNorth, FImageSouth, FImageWest, FImageEast);
// if nImages < nPictImages then
// ShowNotice(Format(errNotAllImagesAvailable,[nImages]));
finally
PopMouseCursor;
end;
end;
/// summary: Responds to the OnExecute event of the Transfer action on the pictometry form.
/// Transfers Pictometry images to the report.
procedure TPictometryPortal.TransferPictometryToReport(doc:TContainer);
begin
try
if not Assigned(doc) then
doc := Main.NewEmptyContainer;
FillFormSubjectAerialPhoto;
doc.docView.Invalidate;
finally
end;
end;
/// summary: Gets the Pictometry image stream for the specified face.
function TPictometryPortal.GetFaceImageStream(const Face: TFace): TStream;
var
Front: TDirection;
begin
Front := dNorth;
// find the requested face based on which direction is front
case Front of
dNorth:
case Face of
fFront: Result := FImageNorth;
fBack: Result := FImageSouth;
fLeft: Result := FImageEast;
fRight: Result := FImageWest;
else
Result := FImageOrthogonal;
end;
dEast:
case Face of
fFront: Result := FImageEast;
fBack: Result := FImageWest;
fLeft: Result := FImageSouth;
fRight: Result := FImageNorth;
else
Result := FImageOrthogonal;
end;
dSouth:
case Face of
fFront: Result := FImageSouth;
fBack: Result := FImageNorth;
fLeft: Result := FImageWest;
fRight: Result := FImageEast;
else
Result := FImageOrthogonal;
end;
dWest:
case Face of
fFront: Result := FImageWest;
fBack: Result := FImageEast;
fLeft: Result := FImageNorth;
fRight: Result := FImageSouth;
else
Result := FImageOrthogonal;
end;
else
Result := FImageOrthogonal;
end;
end;
/// summary: Gets the Pictometry image stream for the specified face.
function TPictometryPortal.GetFaceImageStream2(const Face: TFace; var ImageCaption:String): TStream;
var
Front: TDirection;
begin
// find which direction is the front
Front := dNorth;
// find the requested face based on which direction is front
case Front of
dNorth:
case Face of
fFront: begin Result := FImageNorth; ImageCaption := 'Aerial Front - North'; end;
fBack: begin Result := FImageSouth; ImageCaption := 'South'; end;
fLeft: begin Result := FImageEast; ImageCaption := 'East'; end;
fRight: begin Result := FImageWest; ImageCaption := 'West'; end;
else
begin result := FImageOrthogonal; ImageCaption := 'Overhead'; end;
end;
dEast:
case Face of
fFront: begin Result := FImageEast; ImageCaption := 'Aerial Front - East'; end;
fBack: begin Result := FImageWest; ImageCaption := 'West'; end;
fLeft: begin Result := FImageSouth; ImageCaption := 'South'; end;
fRight: begin Result := FImageNorth; ImageCaption := 'North'; end;
else
begin result := FImageOrthogonal; ImageCaption := 'Overhead'; end;
end;
dSouth:
case Face of
fFront: begin Result := FImageSouth; ImageCaption := 'Aerial Front- South'; end;
fBack: begin Result := FImageNorth; ImageCaption := 'North'; end;
fLeft: begin Result := FImageWest; ImageCaption := 'West'; end;
fRight: begin Result := FImageEast; ImageCaption := 'East'; end;
else
begin result := FImageOrthogonal; ImageCaption := 'Overhead'; end;
end;
dWest:
case Face of
fFront: begin Result := FImageWest; ImageCaption := 'Aerial Front - West'; end;
fBack: begin Result := FImageEast; ImageCaption := 'East'; end;
fLeft: begin Result := FImageNorth; ImageCaption := 'North'; end;
fRight: begin Result := FImageSouth; ImageCaption := 'South'; end;
else
begin result := FImageOrthogonal; ImageCaption := 'Overhead'; end;
end;
else
begin result := FImageOrthogonal; ImageCaption := 'Overhead'; end;
end;
end;
/// summary: Handles errors returned by the the Pictometry service.
procedure TPictometryPortal.HandleServiceError(const E: Exception);
var
ServiceError: EServStatusException;
Text: String;
begin
if ControlKeyDown or DebugMode then
TDebugTools.Debugger.ShowConsole;
if (E is ERemotableException) and SameText(E.Message, 'Error in the application.') then
begin
ServiceError := EServStatusException.Create(E as ERemotableException);
TDebugTools.WriteLine(ServiceError.ClassName + ': ' + ServiceError.excDescr);
case ServiceError.excCode of
CServiceError_UnknownError:
Text := 'The Pictometry Aerial Imagery service is temporarily unavailable.|' + E.Message;
CServiceError_AuthorizationFailed:
Text := 'A newer version of ClickFORMS is required to use this service.|' + E.Message;
CServiceError_InvalidCustomer:
Text := 'The Pictometry Aerial Imagery service is temporarily unavailable.|' + E.Message;
CServiceError_NoActiveSubscription:
Text := 'Please contact Bradford Technologies at ' + OurPhoneNumber + ' to purchase Pictometry Aerial Imagery.|' + E.Message;
CServiceError_AllUnitsConsumed:
Text := 'Please contact Bradford Technologies at ' + OurPhoneNumber + ' to purchase additional units of Pictometry Aerial Imagery.|' + E.Message;
CServiceError_AllUnitsExpired:
Text := 'Please contact Bradford Technologies at ' + OurPhoneNumber + ' to purchase additional units of Pictometry Aerial Imagery.|' + E.Message;
CServiceError_WaitSubsequentRequestDelay:
Text := 'The Pictometry Aerial Imagery service is busy. Please try again later.|' + E.Message;
CServiceError_ImagesUnavailable:
Text := 'The Pictometry Aerial Imagery service is temporarily unavailable.|' + E.Message;
CServiceError_DatabaseError:
Text := 'The Pictometry Aerial Imagery service is temporarily unavailable.|' + E.Message;
else
Text := 'The Pictometry Aerial Imagery service encountered an error while processing your request.|' + E.Message;
end;
end
else
begin
TDebugTools.WriteLine(E.ClassName + ': ' + E.Message);
if (E is ERemotableException) and (Pos('404', E.Message) > 0) then
Text := 'The address is outside the Pictometry coverage area.|' + E.Message
else
Text := 'The Pictometry Aerial Imagery service encountered an error while processing your request.|' + E.Message;
end;
// re-raise the exception as an informational error
try
raise EInformationalError.Create(Text);
except
on OE: Exception do
Application.HandleException(Self);
end;
end;
/// summary: Locates the subject property by address.
function TPictometryPortal.GetCFDB_SearchByAddress(const Street: String; const City: String; const State: String; const Zip: String): Boolean;
const
CImageQuality = 90;
var
Address: PictometryAddress;
ImageSize: TSize;
Maps: PictometryMaps;
Options: PictometrySearchModifiers;
PictometryService: PictometryServiceSoap;
PreviousCursor: TCursor;
RIO: THTTPRIO;
begin
result := false;
if length(CurrentUser.UserCustUID) = 0 then
exit; //do not call if user does not have custID
Address := nil;
Maps := nil;
Options := nil;
PictometryService := nil;
PreviousCursor := Screen.Cursor;
try
Screen.Cursor := crHourglass;
Address := PictometryAddress.Create;
Address.streetAddress := Street;
Address.city := City;
Address.state := State;
Address.zip := Zip;
ImageSize := TGraphicCell.CalculateImageSizeFromCellFrame(Rect(0, 0, 250, 250));
Options := PictometrySearchModifiers.Create;
Options.MapWidth := Trunc(ImageSize.cx * 1.3);
Options.MapHeight := Trunc(ImageSize.cy * 1.3);
Options.MapQuality := CImageQuality;
FUserCredentials.CustID := CurrentUser.UserCustUID;
FUserCredentials.Password := WS_Pictometry_Password;
PictometryService := GetPictometryServiceSoap(True, GetURLForPictometryService);
RIO := (PictometryService as IRIOAccess).RIO as THTTPRIO;
RIO.HTTPWebNode.ReceiveTimeout := CTimeoutPictometryService;
RIO.HTTPWebNode.SendTimeout := CTimeoutPictometryService;
RIO.SOAPHeaders.SetOwnsSentHeaders(False);
RIO.SOAPHeaders.Send(FUserCredentials);
try
Maps := PictometryService.SearchByAddress(Address, Options);
ByteDynArrayToStream(Maps.EastView, FImageEast);
ByteDynArrayToStream(Maps.NorthView, FImageNorth);
ByteDynArrayToStream(Maps.OrthogonalView, FImageOrthogonal);
ByteDynArrayToStream(Maps.SouthView, FImageSouth);
ByteDynArrayToStream(Maps.WestView, FImageWest);
Result := True;
except
Result := False;
end;
finally
Screen.Cursor := PreviousCursor;
try
PictometryService := nil;
except
Pointer(PictometryService) := nil;
end;
FreeAndNil(Address);
FreeAndNil(Maps);
FreeAndNil(Options);
end;
end;
//Insert a data array of bytes that represent an image and put it into a JPEG
procedure LoadJPEGFromByteArray(const dataArray: String; var JPGImg: TJPEGImage);
var
msByte: TMemoryStream;
iSize: Integer;
begin
msByte := TMemoryStream.Create;
try
iSize := Length(DataArray);
msByte.WriteBuffer(PChar(DataArray)^, iSize);
msByte.Position:=0;
if not assigned(JPGImg) then
JPGImg := TJPEGImage.Create;
JPGImg.LoadFromStream(msByte);
finally
msByte.Free;
end;
end;
/// summary: Locates the subject property by address.
procedure TPictometryPortal.GetCFAW_SearchByAddress(const Street: String; const City: String; const State: String; const Zip: String);
const
CImageQuality = 90;
var
Credentials : clsUserCredentials;
AddressRequest : clsPictometrySearchByAddressRequest;
SearchModifiers : clsPictometrySearchModifiers;
Response : clsSearchByAddressResponse;
Token, CompanyKey, OrderKey : WideString;
dataPics: clsPictometryData;
AerialImages: clsDownloadMapsResponse;
Acknowledgement : clsAcknowledgement;
NorthView: String;
EastView: String;
SouthView: String;
WestView: String;
TopView: String;
NorthJPG: TJPEGImage;
EastJPG: TJPEGImage;
SouthJPG: TJPEGImage;
WestJPG: TJPEGImage;
TopJPG: TJPEGImage;
begin
{Get Token,CompanyKey and OrderKey}
if AWSI_GetCFSecurityToken(AWCustomerEmail, AWCustomerPSW, CurrentUser.UserCustUID, Token, CompanyKey, OrderKey) then
try
{User Credentials}
Credentials := clsUserCredentials.Create;
Credentials.Username := AWCustomerEmail;
Credentials.Password := Token;
Credentials.CompanyKey := CompanyKey;
Credentials.OrderNumberKey := OrderKey;
Credentials.Purchase := 0;
{Address Request}
AddressRequest := clsPictometrySearchByAddressRequest.Create;
AddressRequest.StreetAddress := Street;
AddressRequest.City := City;
AddressRequest.State := State;
AddressRequest.Zip := Zip;
{Search Modifiers}
SearchModifiers := clsPictometrySearchModifiers.Create;
searchModifiers.MapHeight := 300;
searchModifiers.MapWidth := 400;
searchModifiers.MapQuality := 90;
try
with GetPictometryServerPortType(False, GetAWURLForPictometryService) do
begin
Response := PictometryService_SearchByAddress(Credentials, AddressRequest, SearchModifiers);
{if zero is sucess call}
if Response.Results.Code = 0 then
begin
{Load Data Object to be send Back}
dataPics := clsPictometryData.Create;
dataPics.NorthView := Response.ResponseData.NorthView;
dataPics.EastView := Response.ResponseData.EastView;
dataPics.SouthView := Response.ResponseData.SouthView;
dataPics.WestView := Response.ResponseData.WestView;
dataPics.OrthogonalView := Response.ResponseData.OrthogonalView;
{get Map photos}
AerialImages := PictometryService_DownloadMaps(Credentials,dataPics);
if AerialImages.Results.Code = 0 then
begin
{Success call now Send Back Acknowledgement}
try
Acknowledgement := clsAcknowledgement.Create;
Acknowledgement.Received := 1;
if Assigned(Response.ResponseData) then
Acknowledgement.ServiceAcknowledgement := AerialImages.ResponseData.ServiceAcknowledgement;
with GetPictometryServerPortType(false,GetAWURLForPictometryService) do
PictometryService_Acknowledgement(Credentials,Acknowledgement);
finally
Acknowledgement.Free;
end;
{Decode base64 data string }
NorthView := Base64Decode(AerialImages.ResponseData.NorthView);
WestView := Base64Decode(AerialImages.ResponseData.WestView);
EastView := Base64Decode(AerialImages.ResponseData.EastView);
SouthView := Base64Decode(AerialImages.ResponseData.SouthView);
TopView := Base64Decode(AerialImages.ResponseData.OrthogonalView);
{create JPGs}
NorthJPG := TJPEGImage.Create;
EastJPG := TJPEGImage.Create;
SouthJPG := TJPEGImage.Create;
WestJPG := TJPEGImage.Create;
TopJPG := TJPEGImage.Create;
{Transfer images to JPGs}
LoadJPEGFromByteArray(NorthView,NorthJPG);
LoadJPEGFromByteArray(EastView,EastJPG);
LoadJPEGFromByteArray(WestView,WestJPG);
LoadJPEGFromByteArray(SouthView,SouthJPG);
LoadJPEGFromByteArray(TopView,TopJPG);
{Save MemoryStream To CF process}
NorthJPG.SaveToStream(FImageNorth);
EastJPG.SaveToStream(FImageEast);
WestJPG.SaveToStream(FImageWest);
SouthJPG.SaveToStream(FImageSouth);
TopJPG.SaveToStream(FImageOrthogonal);
end;
{ShowAlert(atInfoAlert, Response.Results.Description);}
end
else
ShowAlert(atWarnAlert, Response.Results.Description);
end;
except
on e: Exception do
ShowAlert(atStopAlert, e.Message);
end;
finally
Credentials.Free;
AddressRequest.Free;
SearchModifiers.Free;
NorthJPG.Free;
EastJPG.Free;
SouthJPG.Free;
WestJPG.Free;
TopJPG.Free;
end;
end;
/// summary: Fills the Subject Aerial Photo form (625)
/// with the images returned by the Pictometry service.
/// 09/30/2014: Replace form #625 with 9039.
procedure TPictometryPortal.FillFormSubjectAerialPhoto;
var
Cell: TGraphicCell;
CreateForm: Boolean;
Form, sForm: TDocForm;
Stream: TStream;
ImageCaption: String;
begin
Form := FDocument.GetFormByOccurance(9039, 0, False);
if Assigned(Form) then
begin
CreateForm := (mrNo = WhichOption12('Replace', 'Add', msgPictometryConfirmReplace));
if CreateForm then
Form := FDocument.GetFormByOccurance(9039, -1, True);
end
else
Form := FDocument.GetFormByOccurance(9039, -1, True);
if Assigned(Form) then
begin
//Get Subject Front view from 301 if found
sForm := FDocument.GetFormByOccurance(301, 0, False);
if Assigned(sForm) then //we found 301 form
begin
Form.SetCellText(1, 13, 'Street Front');
Form.SetCellImageFromCell(1, 14, sForm.GetCell(1,15)); //Subject Front
end;
// Stream := GetFaceImageStream(fFront);
Stream := GetFaceImageStream2(fFront, ImageCaption);
Stream.Position := 0;
// Cell := Form.GetCell(1, 13) as TGraphicCell;
Form.SetCellText(1, 15, ImageCaption);
Cell := Form.GetCell(1, 16) as TGraphicCell;
Cell.LoadStreamData(Stream, Stream.Size, True);
Stream := GetFaceImageStream2(fBack, ImageCaption);
Stream.Position := 0;
// Cell := Form.GetCell(1, 14) as TGraphicCell;
Form.SetCellText(1, 17, ImageCaption);
Cell := Form.GetCell(1, 18) as TGraphicCell;
Cell.LoadStreamData(Stream, Stream.Size, True);
Stream := GetFaceImageStream2(fOverhead, ImageCaption);
Stream.Position := 0;
// Cell := Form.GetCell(1, 15) as TGraphicCell;
Form.SetCellText(1, 19, ImageCaption);
Cell := Form.GetCell(1, 20) as TGraphicCell;
Cell.LoadStreamData(Stream, Stream.Size, True);
Stream := GetFaceImageStream2(fLeft, ImageCaption);
Stream.Position := 0;
// Cell := Form.GetCell(1, 16) as TGraphicCell;
Form.SetCellText(1, 21, ImageCaption);
Cell := Form.GetCell(1, 22) as TGraphicCell;
Cell.LoadStreamData(Stream, Stream.Size, True);
Stream := GetFaceImageStream2(fRight, ImageCaption);
Stream.Position := 0;
Form.SetCellText(1, 23, ImageCaption);
Cell := Form.GetCell(1, 24) as TGraphicCell;
Cell.LoadStreamData(Stream, Stream.Size, True);
end;
end;
/// summary: Resets the Pictometry portal to its initial state containing no data.
procedure TPictometryPortal.Reset;
begin
FImageEast.Clear;
FImageNorth.Clear;
FImageOrthogonal.Clear;
FImageSouth.Clear;
FImageWest.Clear;
FDocument := nil;
// FPictometryForm.LoadFormData(nil);
// FPictometryForm.LoadFormImages(nil, nil, nil, nil, nil);
end;
/// summary: Sets the document for use with the Pictometry service.
procedure TPictometryPortal.SetDocument(const Document: TContainer);
begin
if (Document <> FDocument) then
begin
FDocument := Document;
// FPictometryForm.LoadFormData(FDocument);
end;
end;
/// summary: Shows the Pictometry service user interface in a modal window.
procedure TPictometryPortal.ShowModal;
begin
// if (FPictometryForm.ShowModal <> mrOK) then
// Abort;
end;
/// summary: Executes the Pictometry portal, filling the appraisal report
/// with aerial images of the subject property.
/// remarks: I am appalled that there is nothing in CurrentUser to say
/// that the user is running on an evaluation license of ClickFORMS.
/// I have spent FAR TOO MUCH TIME trying to figure this out.
/// CurrentUser.UsageLeft is useless (Use the global AppEvalUsageLeft instead).
/// CurrentUser.InTrialPeriod(picClickForms) is useless (Always results in TRUE).
/// CurrentUser.LicInfo.UserCustID is your only hope, under the assumption that
/// the result is an empty string.
class procedure TPictometryPortal.Execute(const Document: TContainer);
var
Portal: TPictometryPortal;
begin
if Assigned(Document) and Document.Locked then
begin
ShowNotice('Please unlock your report before using Pictometry.');
Abort;
end;
Portal := TPictometryPortal.Create;
try
Portal.Reset;
Portal.Document := Document;
Portal.ShowModal;
finally
FreeAndNil(Portal);
end;
end;
procedure LoadPictometry(doc: TContainer; AddrInfo: AddrInfoRec);
var
PictometryPortal: TPictometryPortal;
begin
PictometryPortal := TPictometryPortal.Create;
try
PictometryPortal.FDocument := doc;
PictometryPortal.GetPictometryFromService(AddrInfo);
PictometryPortal.TransferPictometryToReport(doc);
finally
PictometryPortal.Free;
end;
end;
function DoGetParcelImage(Lat, Lon: Double; var ParcelImageView: WideString ): Boolean;
var
Credentials : clsUserCredentials;
SearchModifiers : clsPictometrySearchWithParcelModifiers;
GeoSearch: clsPictometrySearchByGeocodeRequest;
GeoResponse: clsSearchByGeocodeResponse;
Parcel: clsParcelInfo;
Token, CompanyKey, OrderKey : WideString;
dataPics: clsPictometryData;
Acknowledgement : clsAcknowledgement;
AerialImages: clsDownloadMapsResponse;
begin
{Get Token,CompanyKey and OrderKey}
if AWSI_GetCFSecurityToken(AWCustomerEmail, AWCustomerPSW, CurrentUser.UserCustUID, Token, CompanyKey, OrderKey) then
try
{User Credentials}
Credentials := clsUserCredentials.Create;
Credentials.Username := AWCustomerEmail;
Credentials.Password := Token;
Credentials.CompanyKey := CompanyKey;
Credentials.OrderNumberKey := OrderKey;
Credentials.Purchase := 0;
{Load Subject GeoCode}
GeoSearch := clsPictometrySearchByGeocodeRequest.Create;
GeoSearch.Longitude := Lon;
GeoSearch.Latitude := Lat;
{Parcel View Settings}
Parcel := clsParcelInfo.Create;
Parcel.StrokeColor := 'ffff00';
Parcel.StrokeOpacity := 1.0;
// Parcel.StrokeWidth := '2';
Parcel.StrokeWidth := '4';
Parcel.FillColor := 'ffffff';
Parcel.FillOpacity := '0.0';
Parcel.FeatureBuffer := 100;
Parcel.Orientations := 'O';
{Modifiers Config}
searchModifiers := clsPictometrySearchWithParcelModifiers.Create;
searchModifiers.MapHeight := 1100;
searchModifiers.MapWidth := 720;
searchModifiers.MapQuality := 200;
searchModifiers.ParcelInfo := Parcel;
try
with GetPictometryServerPortType(false, awsiPictometry) do
begin
GeoResponse := PictometryService_SearchByGeocodeWithParcel(Credentials,GeoSearch,searchModifiers);
if GeoResponse.Results.Code = 0 then
begin
{Load Data Object to be send Back}
dataPics := clsPictometryData.Create;
dataPics.OrthogonalView := GeoResponse.ResponseData.OrthogonalView;
{Get parcel view}
AerialImages := PictometryService_DownloadMaps(Credentials, dataPics);
if AerialImages.Results.Code = 0 then
begin
//If Success Send Back Acknowledgement}
try
Acknowledgement := clsAcknowledgement.Create;
Acknowledgement.Received := 1;
if Assigned(GeoResponse.ResponseData) then
Acknowledgement.ServiceAcknowledgement := AerialImages.ResponseData.ServiceAcknowledgement;
with GetPictometryServerPortType(false, awsiPictometry) do
PictometryService_Acknowledgement(Credentials, Acknowledgement);
finally
Acknowledgement.Free;
end;
{Decode base64 data string }
ParcelImageView := Base64Decode(AerialImages.ResponseData.OrthogonalView);
result := True;
end
else
result := False; //AerialImages.Results.Code is not 0
end
else
result := False; //GeoResponse.Results.Code is not 0
//if Fail alert user and send back failure acknowledgement
if not result then
begin
ShowAlert(atWarnAlert, GeoResponse.Results.Description);
try
Acknowledgement := clsAcknowledgement.Create;
Acknowledgement.Received := 0;
if Assigned(GeoResponse.ResponseData) then
Acknowledgement.ServiceAcknowledgement := GeoResponse.ResponseData.ServiceAcknowledgement;
with GetPictometryServerPortType(false, awsiPictometry) do
PictometryService_Acknowledgement(Credentials, Acknowledgement);
finally
Acknowledgement.Free;
end;
end;
end; //with
except on E:Exception do
ShowAlert(atWarnAlert, 'Error in getting Subject Parcel Map: '+e.Message);
end;
finally
Credentials.Free;
GeoSearch.Free;
searchModifiers.Free;
end;
end;
function LoadSubjectParceView(Lat, Lon: Double; var ParcelImageView: WideString): Boolean;
var
Credentials : clsUserCredentials;
SearchModifiers : clsPictometrySearchWithParcelModifiers;
GeoSearch: clsPictometrySearchByGeocodeRequest;
GeoResponse: clsSearchByGeocodeResponse;
Parcel: clsParcelInfo;
Token, CompanyKey, OrderKey : WideString;
dataPics: clsPictometryData;
Acknowledgement : clsAcknowledgement;
AerialImages: clsDownloadMapsResponse;
begin
PushMouseCursor(crHourglass);
{Get Token,CompanyKey and OrderKey}
// if AWSI_GetCFSecurityToken(AWCustomerEmail, AWCustomerPSW, CurrentUser.LicInfo.UserCustID, Token, CompanyKey, OrderKey) then
if GetFREEAWSISecutityToken(Token) then
begin
try
{User Credentials}
Credentials := clsUserCredentials.Create;
// Credentials.Username := AWCustomerEmail;
// Credentials.CompanyKey := CompanyKey;
// Credentials.OrderNumberKey := OrderKey;
//### Use free token for this call, since user already bought pictometry should get this one for free
Credentials.Username := 'compcruncher@bradfordsoftware.com';
Credentials.Password := Token;
Credentials.CompanyKey :='ed77ee59-87b5-afdf-92aa-1a3b14ef4e8e';
Credentials.OrderNumberKey := 'xxxxxxxxxxxnotrequiredxxxxxxxxxx';
Credentials.Purchase := 0;
{Load Subject GeoCode}
GeoSearch := clsPictometrySearchByGeocodeRequest.Create;
GeoSearch.Longitude := Lon;
GeoSearch.Latitude := Lat;
{Parcel View Settings}
Parcel := clsParcelInfo.Create;
Parcel.StrokeColor := 'ffff00';
Parcel.StrokeOpacity := 1.0;
// Parcel.StrokeWidth := '2';
Parcel.StrokeWidth := '4';
Parcel.FillColor := 'ffffff';
Parcel.FillOpacity := '0.0';
Parcel.FeatureBuffer := 100;
Parcel.Orientations := 'O';
{Modifiers Config}
searchModifiers := clsPictometrySearchWithParcelModifiers.Create;
searchModifiers.MapHeight := 1100;
searchModifiers.MapWidth := 720;
searchModifiers.MapQuality := 200;
searchModifiers.ParcelInfo := Parcel;
try
with GetPictometryServerPortType(false, awsiPictometry) do
begin
GeoResponse := PictometryService_SearchByGeocodeWithParcel(Credentials,GeoSearch,searchModifiers);
if GeoResponse.Results.Code = 0 then
begin
{Load Data Object to be send Back}
dataPics := clsPictometryData.Create;
dataPics.OrthogonalView := GeoResponse.ResponseData.OrthogonalView;
{Get parcel view}
AerialImages := PictometryService_DownloadMaps(Credentials, dataPics);
if AerialImages.Results.Code = 0 then
begin
//If Success Send Back Acknowledgement}
try
Acknowledgement := clsAcknowledgement.Create;
Acknowledgement.Received := 1;
if Assigned(GeoResponse.ResponseData) then
Acknowledgement.ServiceAcknowledgement := AerialImages.ResponseData.ServiceAcknowledgement;
with GetPictometryServerPortType(false, awsiPictometry) do
PictometryService_Acknowledgement(Credentials, Acknowledgement);
finally
Acknowledgement.Free;
end;
{Decode base64 data string }
ParcelImageView := Base64Decode(AerialImages.ResponseData.OrthogonalView);
result := True;
end
else
result := False; //AerialImages.Results.Code is not 0
end
else
result := False; //GeoResponse.Results.Code is not 0
//if Fail alert user and send back failure acknowledgement
if not result then
begin
ShowAlert(atWarnAlert, GeoResponse.Results.Description);
try
Acknowledgement := clsAcknowledgement.Create;
Acknowledgement.Received := 0;
if Assigned(GeoResponse.ResponseData) then
Acknowledgement.ServiceAcknowledgement := GeoResponse.ResponseData.ServiceAcknowledgement;
with GetPictometryServerPortType(false, awsiPictometry) do
PictometryService_Acknowledgement(Credentials, Acknowledgement);
finally
Acknowledgement.Free;
end;
end;
end; //with
except on E:Exception do
ShowAlert(atWarnAlert, 'Error in getting Subject Parcel Map: '+e.Message);
end;
finally
Credentials.Free;
GeoSearch.Free;
searchModifiers.Free;
PopMouseCursor;
end;
end;
end;
function LoadSubjectParceViewByAddr(Street, city, state, zip: String; var ParcelImageView: WideString): Boolean;
var
Credentials : clsUserCredentials;
SearchModifiers : clsPictometrySearchWithParcelModifiers;
AddrSearch: clsPictometrySearchByAddressRequest;
AddrResponse: clsSearchByAddressResponse;
Parcel: clsParcelInfo;
Token, CompanyKey, OrderKey : WideString;
dataPics: clsPictometryData;
Acknowledgement : clsAcknowledgement;
AerialImages: clsDownloadMapsResponse;
begin
PushMouseCursor(crHourglass);
{Get Token,CompanyKey and OrderKey}
// if AWSI_GetCFSecurityToken(AWCustomerEmail, AWCustomerPSW, CurrentUser.LicInfo.UserCustID, Token, CompanyKey, OrderKey) then
if GetFREEAWSISecutityToken(Token) then
begin
try
{User Credentials}
Credentials := clsUserCredentials.Create;
//### Use free token for this call, since user already bought pictometry should get this one for free
Credentials.Username := 'compcruncher@bradfordsoftware.com';
Credentials.Password := Token;
Credentials.CompanyKey :='ed77ee59-87b5-afdf-92aa-1a3b14ef4e8e';
Credentials.OrderNumberKey := 'xxxxxxxxxxxnotrequiredxxxxxxxxxx';
Credentials.Purchase := 0;
{Load Subject GeoCode}
AddrSearch := clsPictometrySearchByAddressRequest.Create;
AddrSearch.StreetAddress := trim(Street);
AddrSearch.City := trim(City);
AddrSearch.State := trim(State);
AddrSearch.Zip := trim(zip);
{Parcel View Settings}
Parcel := clsParcelInfo.Create;
Parcel.StrokeColor := 'ffff00';
Parcel.StrokeOpacity := 1.0;
// Parcel.StrokeWidth := '2';
Parcel.StrokeWidth := '4';
Parcel.FillColor := 'ffffff';
Parcel.FillOpacity := '0.0';
Parcel.FeatureBuffer := 100;
Parcel.Orientations := 'O';
{Modifiers Config}
searchModifiers := clsPictometrySearchWithParcelModifiers.Create;
searchModifiers.MapHeight := 1100;
searchModifiers.MapWidth := 720;
searchModifiers.MapQuality := 200;
searchModifiers.ParcelInfo := Parcel;
try
with GetPictometryServerPortType(false, awsiPictometry) do
begin
AddrResponse := PictometryService_SearchByAddressWithParcel(Credentials,AddrSearch,searchModifiers);
if AddrResponse.Results.Code = 0 then
begin
{Load Data Object to be send Back}
dataPics := clsPictometryData.Create;
dataPics.OrthogonalView := AddrResponse.ResponseData.OrthogonalView;
{Get parcel view}
AerialImages := PictometryService_DownloadMaps(Credentials, dataPics);
if AerialImages.Results.Code = 0 then
begin
//If Success Send Back Acknowledgement}
try
Acknowledgement := clsAcknowledgement.Create;
Acknowledgement.Received := 1;
if Assigned(AddrResponse.ResponseData) then
Acknowledgement.ServiceAcknowledgement := AerialImages.ResponseData.ServiceAcknowledgement;
with GetPictometryServerPortType(false, awsiPictometry) do
PictometryService_Acknowledgement(Credentials, Acknowledgement);
finally
Acknowledgement.Free;
end;
{Decode base64 data string }
ParcelImageView := Base64Decode(AerialImages.ResponseData.OrthogonalView);
result := True;
end
else
result := False; //AerialImages.Results.Code is not 0
end
else
result := False; //GeoResponse.Results.Code is not 0
//if Fail alert user and send back failure acknowledgement
if not result then
begin
ShowAlert(atWarnAlert, AddrResponse.Results.Description);
try
Acknowledgement := clsAcknowledgement.Create;
Acknowledgement.Received := 0;
if Assigned(AddrResponse.ResponseData) then
Acknowledgement.ServiceAcknowledgement := AddrResponse.ResponseData.ServiceAcknowledgement;
with GetPictometryServerPortType(false, awsiPictometry) do
PictometryService_Acknowledgement(Credentials, Acknowledgement);
finally
Acknowledgement.Free;
end;
end;
end; //with
except on E:Exception do
ShowAlert(atWarnAlert, 'Error in getting Subject Parcel Map: '+e.Message);
end;
finally
Credentials.Free;
AddrSearch.Free;
searchModifiers.Free;
PopMouseCursor;
end;
end;
end;
end.
|
unit AqDrop.DB.Base;
interface
uses
AqDrop.Core.Collections,
AqDrop.DB.Connection,
AqDrop.DB.ORM.Manager,
AqDrop.DB.SQL.Intf,
AqDrop.Core.Collections.Intf,
System.SysUtils,
AqDrop.DB.ORM.Attributes;
type
TAqDBObject = class;
TAqDBObjectClass = class of TAqDBObject;
TAqDBGenericObjectManager = class abstract(TAqDBORMManagerClient)
private
procedure Save(const pDBObject: TAqDBObject);
function Delete(const pDBObject: TAqDBObject): Boolean;
strict protected
function DoNew: TAqDBObject; virtual; abstract;
function DoGet(const pID: UInt64): TAqDBObject; virtual; abstract;
procedure DoSave(const pDBObject: TAqDBObject); virtual; abstract;
function DoDelete(const pDBObject: TAqDBObject): Boolean; virtual; abstract;
end;
TAqDBObject = class
public
const ID_COLUMN = 'ID';
strict private
[weak]
FManager: TAqDBGenericObjectManager;
private
procedure SetManager(const pManager: TAqDBGenericObjectManager);
strict protected
function GetID: UInt64; virtual; abstract;
function GetForeignManager<T: TAqDBGenericObjectManager>: T;
procedure StartTransaction;
procedure CommitTransaction;
procedure RollbackTransaction;
procedure ValidateData; virtual;
property Manager: TAqDBGenericObjectManager read FManager;
public
procedure Save;
procedure Delete;
property ID: UInt64 read GetID;
end;
TAqDBObjectAutoID = class(TAqDBObject)
strict private
[AqAutoIncrementColumn(TAqDBObject.ID_COLUMN)]
FID: UInt64;
strict protected
function GetID: UInt64; override;
end;
TAqDBObjectRegularID = class(TAqDBObject)
strict private
[AqPrimaryKey(TAqDBObject.ID_COLUMN)]
FID: UInt64;
strict protected
function GetID: UInt64; override;
end;
TAqDBObjectManager<T: TAqDBObject, constructor> = class(TAqDBGenericObjectManager)
strict private
FCache: TAqDictionary<UInt64, T>;
strict protected
function DoGet(const pID: UInt64): TAqDBObject; override;
function DoNew: TAqDBObject; override;
procedure DoSave(const pDBObject: TAqDBObject); override;
function DoDelete(const pDBObject: TAqDBObject): Boolean; override;
procedure AddObject(const pObject: T); virtual;
public
constructor Create; override;
destructor Destroy; override;
function Get(const pID: Int64): T; overload;
function Get(const pID: Int64; out pObject: T): Boolean; overload;
function Get(out pResultList: IAqResultList<T>): Boolean; overload;
function Get(const pCustomizationMethod: TProc<IAqDBSQLSelect>;
out pResultList: IAqResultList<T>): Boolean; overload;
function Get: IAqResultList<T>; overload;
function Get(const pCustomizationMethod: TProc<IAqDBSQLSelect>): IAqResultList<T>; overload;
function New: T;
end;
implementation
uses
AqDrop.Core.Exceptions,
AqDrop.DB.SQL,
AqDrop.DB.Base.Exceptions;
{ TAqDBObject }
procedure TAqDBObject.CommitTransaction;
begin
FManager.ORMManager.Connection.CommitTransaction;
end;
procedure TAqDBObject.Delete;
begin
if not FManager.Delete(Self) then
begin
{$IFNDEF AUTOREFCOUNT}
Free;
{$ENDIF}
end;
end;
function TAqDBObject.GetForeignManager<T>: T;
begin
Result := FManager.ORMManager.GetClient<T>;
end;
procedure TAqDBObject.RollbackTransaction;
begin
FManager.ORMManager.Connection.RollbackTransaction;
end;
procedure TAqDBObject.Save;
begin
ValidateData;
FManager.Save(Self);
end;
procedure TAqDBObject.SetManager(const pManager: TAqDBGenericObjectManager);
begin
FManager := pManager;
end;
procedure TAqDBObject.StartTransaction;
begin
FManager.ORMManager.Connection.StartTransaction;
end;
procedure TAqDBObject.ValidateData;
begin
// virtual method to be overwritten in order to validate the object's data before it being saved.
end;
{ TAqDBObjectManager<T> }
procedure TAqDBObjectManager<T>.AddObject(const pObject: T);
begin
FCache.Lock;
try
if not FCache.ContainsKey(pObject.ID) or (pObject <> FCache.Items[pObject.ID]) then
begin
FCache.AddOrSetValue(pObject.ID, pObject);
pObject.SetManager(Self);
end;
finally
FCache.Release;
end;
end;
constructor TAqDBObjectManager<T>.Create;
begin
FCache := TAqDictionary<UInt64, T>.Create([TAqDictionaryContent.adcValue], True);
end;
destructor TAqDBObjectManager<T>.Destroy;
begin
FCache.Free;
inherited;
end;
function TAqDBObjectManager<T>.DoDelete(const pDBObject: TAqDBObject): Boolean;
var
lObjectInCache: T;
begin
FCache.Lock;
try
if FCache.TryGetValue(pDBObject.ID, lObjectInCache) and
(Pointer(pDBObject) = Pointer(lObjectInCache)) then
begin
ORMManager.Delete(pDBObject, False);
end;
FCache.Remove(pDBObject.ID);
Result := True; // if someday the object will not be freed by the cache, the result must be set to false
finally
FCache.Release;
end;
end;
function TAqDBObjectManager<T>.DoGet(const pID: UInt64): TAqDBObject;
begin
Result := Get(pID);
end;
function TAqDBObjectManager<T>.DoNew: TAqDBObject;
begin
Result := T.Create;
Result.SetManager(Self);
end;
procedure TAqDBObjectManager<T>.DoSave(const pDBObject: TAqDBObject);
begin
if not pDBObject.InheritsFrom(T) then
begin
raise EAqInternal.Create('Incomptible type when creatin a new Object Manager: ' + pDBObject.QualifiedClassName +
' x ' + T.QualifiedClassName);
end;
ORMManager.Post(pDBObject);
AddObject(T(pDBObject));
end;
function TAqDBObjectManager<T>.Get(out pResultList: IAqResultList<T>): Boolean;
begin
Result := Get(nil, pResultList);
end;
function TAqDBObjectManager<T>.Get: IAqResultList<T>;
begin
if not Get(Result) then
begin
Result := nil;
end;
end;
function TAqDBObjectManager<T>.Get(const pCustomizationMethod: TProc<IAqDBSQLSelect>): IAqResultList<T>;
begin
if not Get(pCustomizationMethod, Result) then
begin
Result := nil;
end;
end;
function TAqDBObjectManager<T>.Get(const pID: Int64; out pObject: T): Boolean;
var
lList: IAqResultList<T>;
begin
FCache.Lock;
try
Result := FCache.TryGetValue(pID, pObject);
finally
FCache.Release;
end;
if not Result then
begin
Result := Get(
procedure(pSelect: IAqDBSQLSelect)
begin
pSelect.CustomizeCondition.AddColumnEqual(TAqDBSQLColumn.Create(T.ID_COLUMN, pSelect.Source), pID);
end, lList);
if Result then
begin
pObject := lList.First;
end else begin
pObject := nil;
end;
end;
end;
function TAqDBObjectManager<T>.New: T;
var
lNew: TAqDBObject;
begin
Result := nil;
lNew := DoNew;
try
if lNew.InheritsFrom(T) then
begin
Result := T(lNew);
end else begin
raise EAqInternal.Create('Incomptible type when creatin a new Object Manager: ' + lNew.QualifiedClassName +
' x ' + T.QualifiedClassName);
end;
except
lNew.Free;
raise;
end;
Result := T(lNew);
end;
function TAqDBObjectManager<T>.Get(const pCustomizationMethod: TProc<IAqDBSQLSelect>;
out pResultList: IAqResultList<T>): Boolean;
var
lObject: T;
begin
Result := ORMManager.Get<T>(pCustomizationMethod, pResultList);
if Result then
begin
for lObject in pResultList do
begin
AddObject(lObject);
end;
pResultList.OnwsResults := False;
end;
end;
function TAqDBObjectManager<T>.Get(const pID: Int64): T;
begin
if not Get(pID, Result) then
begin
Result := nil;
end;
end;
{ TAqDBObjectAutoID }
function TAqDBObjectAutoID.GetID: UInt64;
begin
Result := FID;
end;
{ TAqDBObjectRegularID }
function TAqDBObjectRegularID.GetID: UInt64;
begin
Result := FID;
end;
{ TAqDBGenericObjectManager }
function TAqDBGenericObjectManager.Delete(const pDBObject: TAqDBObject): Boolean;
begin
Result := DoDelete(pDBObject);
end;
procedure TAqDBGenericObjectManager.Save(const pDBObject: TAqDBObject);
begin
DoSave(pDBObject);
end;
end.
|
unit types_mct;
interface
uses jpeg;
const time_const:extended=1000/60;
WM_USER = $0400;
WM_NEXTDLGCTL = $0028;
type
byte_ar = array of byte;
pbyte_ar = ^byte_ar;
int_ar = array of integer;
//tipi dla mnozhestv blokov
for_set = 0..255;
set_trans_blocks = set of for_set;
//tip dannih dla hraneniya light_level, diffuse_level
TID_data = record
id,data:integer;
end;
TID_data_ar = array of TID_data;
//tip dla hraneniya data_value dla bloka
TBlock_data_set = record
data_id:byte;
data_name:string[45];
end;
//tip dla sootvetstviya ID bloka, ego nazvaniya i harakteristik
TBlock_set = record
id:integer;
name:string[35];
solid,transparent,diffuse,tile:boolean;
light_level:byte;
diffuse_level:byte;
data:array of TBlock_data_set;
end;
TBlock_set_ar = array of TBlock_set;
pTBlock_set_ar = ^TBlock_set_ar;
//tip dla zameni blokov
TBlock_change = record
fromID,toID:integer;
fromData,toData:byte;
end;
TBlock_change_ar = array of TBlock_change;
//tip dla infi o plagine
pTPlugSettings=^TPlugSettings;
TPlugSettings = packed record
plugin_type:byte;
aditional_type:byte;
full_name:PChar;
name:PChar;
author:PChar;
dll_path:PChar;
maj_v, min_v, rel_v:byte; //version
change_par:array[1..21] of boolean;
has_preview:boolean;
end;
//tip dla polucheniya infi o plagine
TPlugRec = record
size_info:integer;
size_flux:integer;
size_gen_settings:integer;
size_chunk:integer;
size_change_block:integer;
data:pointer;
end;
//tip dla izmeneniya parametrov
TFlux_set = record
available:Boolean;
min_max:boolean;
default:int64;
min:int64;
max:int64;
end;
//tip dla nastroek igroka
TPlayer_settings = record
XP_level:integer;
XP:single;
HP:integer;
Food_level:integer;
Score:integer;
Rotation:array[0..1] of single;
Overrite_pos:Boolean;
Pos:array[0..2] of double;
Floating:Boolean;
end;
//tip dla nastroek generatora
TGen_settings = record
Border_gen:TPlugRec;
Buildings_gen:TPlugRec;
Landscape_gen:TPlugRec;
Path:PChar;
Name:PChar;
Map_type:byte;
Width, Length:integer;
border_in,border_out:integer;
Game_type:integer;
SID:int64;
Populate_chunks:Boolean;
Generate_structures:Boolean;
Game_time:integer;
Raining, Thundering:Boolean;
Rain_time, Thunder_time:integer;
Player:TPlayer_settings;
Files_size:int64;
Spawn_pos:array[0..2] of integer;
end;
//****************************************************************
//tip dla opisaniya Entity
TEntity_type = record
Id:string;
Pos:array[0..2] of double;
Motion:array[0..2] of double;
Rotation:array[0..1] of single;
Fall_distance:single;
Fire:smallint;
Air:smallint;
On_ground:Boolean;
Data:pointer;
end;
//tip dla opisaniya TileEntity
TTile_entity_type = record
Id:string;
x,y,z:integer;
data:pointer;
end;
ar_entity_type=array of TEntity_type;
par_entity_type=^ar_entity_type;
ar_tile_entity_type=array of TTile_entity_type;
par_tile_entity_type=^ar_tile_entity_type;
//tip dla inventara i sundukov, furnace, dispenser
pslot_item_data=^slot_item_data;
slot_item_data=record
id:smallint;
damage:smallint;
count,slot:byte;
end;
//Furnace
pfurnace_tile_entity_data=^furnace_tile_entity_data;
furnace_tile_entity_data=record
burn_time, cook_time:smallint; //BurnTime=vremya do propadaniya ogn'ya; CookTime=vremya do obzhiganiya resursa (vse vremya v tikah)
//pri bol'shom burntime indikator zapolnen a potom kak vrema zakanchivaetsa - indikator obichno umen'shitsa do nula (predpolozhitel'no)
items:array of slot_item_data; //slot 0=gotovashiesa; 1=toplivo; 2=resultat
end;
//Sign
psign_tile_entity_data=^sign_tile_entity_data;
sign_tile_entity_data=record
text:array[1..4]of string[15]; //esli stroki pustie, to v programme oni dolzhni bit' proinicializirovani tak: text[x]:='';
end;
//MonsterSpawner
pmon_spawn_tile_entity_data=^mon_spawn_tile_entity_data;
mon_spawn_tile_entity_data=record
entityid:string; //id moba, kotoriy spavnitsa (i ne tol'ko moba)
delay:smallint;
end;
//Chest
pchest_tile_entity_data=^chest_tile_entity_data;
chest_tile_entity_data=record
items:array of slot_item_data; //ot 0 do 26 (vsego 27=3*9)
end;
//Note Block
pnote_tile_entity_data=^note_tile_entity_data;
note_tile_entity_data=record
pitch:byte; //kol-vo nazhatiy pravoy knopkoy
end;
//Dispenser
pdispenser_tile_entity_data=^dispenser_tile_entity_data;
dispenser_tile_entity_data=record
items:array of slot_item_data; //kol-vo ot 0 do 8 (sloti 0-8)
end;
//Jukebox
pjukebox_tile_entity_data=^jukebox_tile_entity_data;
jukebox_tile_entity_data=record
rec:integer; //item ID veshi (mozhet bit' ne tol'ko plastinka). Esli vnutri nichego net, to pole otsutstvuet (nuzhno prisvaivat' -1)
//chtobi plastinka viprigivala po PKM, to nado v date k bloku JukeBox postavit' 1
//esli ne propisat' data, to vesh vseravno vipadet pri razbivanii
end;
//Brewing Stand (Cauldron)
pcauldron_tile_entity_data=^cauldron_tile_entity_data;
cauldron_tile_entity_data=record
brew_time:smallint;
items:array of slot_item_data; //kol-vo ot 0 do 3 (sloti 0-3) Slot3=resurs, kotoriy pererabativaetsa
end;
//********************************************************------------
//tip dla chanka
{TChunk = record
Biomes:byte_ar;
Blocks:byte_ar;
Data:byte_ar;
Has_additional_id:Boolean;
Add_id:byte_ar;
has_skylight,has_blocklight:boolean;
Skylight:byte_ar;
Light:byte_ar;
Entities:array of TEntity_type;
Tile_entities:array of TTile_entity_type;
end; }
//tip dla izmeneniya ID blokov
TChange_block = record
id:integer;
name:PChar;
solid,transparent:Boolean;
light_level:integer;
end;
//tip dla chanka
TGen_chunk = record
Biomes:byte_ar;
Blocks:byte_ar;
Data:byte_ar;
Light:byte_ar;
Skylight:byte_ar;
Heightmap:int_ar;
Has_additional_id:Boolean;
sections:array[0..15] of boolean;
Add_id:byte_ar;
has_skylight,has_blocklight:boolean;
raschet_skylight:boolean;
Entities:ar_entity_type;
Tile_entities:ar_tile_entity_type;
end;
line=array of TGen_Chunk;
region=array of line;
//tipi dla funkciy plagina
TGet_prot = function (protocol:integer):integer; register;
TGet_info = function:TPlugRec; register;
TInit = function (hndl:Cardinal; temp:int64):boolean; register;
TGet_diff = function (id:integer):TFlux_set; register;
TGet_compatible = function (plugin_info:TPlugRec):boolean; register;
TGet_last_err = function:PChar; register;
TInit_gen = function (gen_set:TGen_settings; var bord_in,bord_out:integer):boolean; register;
TGet_chunk = function (i,j:integer):TGen_Chunk; register;
TGet_chunk2 = function (xreg,yreg,i,j:integer):TGen_Chunk; stdcall;
TGet_chunk_add = function (i,j:integer; var chunk:TGen_Chunk):boolean; register;
TStop_gen = procedure (i:integer); register;
//TReplace_blocks = function (ids:array of TChange_block):boolean;
TSet_blocks = function (ids:array of TBlock_set):boolean; register;
TShow_wnd = function (gen_set:TGen_settings):integer; register;
TGen_region = function (i,j:integer; map:region):boolean; register;
//tip dla plagina
pTPlugin_type = ^TPlugin_type;
TPlugin_type = record
active:boolean;
handle:cardinal;
info:TPlugSettings;
plug_version:string;
plug_file:string;
plug_full_name:string[30];
plug_name:string[30];
plug_author:string[30];
crc_info:int64;
plugrec:TPlugRec;
preview:TJPEGImage;
auth:boolean;
get_protocol:TGet_prot;
get_info:TGet_info;
init:TInit;
get_different_settings:TGet_diff;
get_compatible:TGet_compatible;
get_last_error:TGet_last_err;
init_gen:TInit_gen;
gen_chunk:TGet_chunk;
gen_chunk2:TGet_chunk2;
get_chunk_add:TGet_chunk_add;
stop_gen:TStop_gen;
set_block_id:TSet_blocks;
show_settings_wnd:TShow_wnd;
gen_region:TGen_region;
end;
//massiv plaginov
TPlugin_ar = array of TPlugin_type;
form_coord=record
top,left:integer;
end;
//tip dla sohraneniya nastroek
save_options_type=record
save_enabled:boolean;
save_type:integer;
fast_load:boolean;
change_disabled:boolean;
main_f,options_f,blocks_f,about_f,border_f:form_coord;
sid:int64;
end;
//massiv hendlov dla potokov
pTHNDL_ar = ^THNDL_ar;
THNDL_ar = array of cardinal;
mcheader=record //tip dannih, opisivayushiy zagolovok fayla regionov Minecraft
mclocations:array[1..1024] of cardinal;
mctimestamp:array[1..1024] of longint;
end;
const plug_size = sizeof(TPlugSettings);
flux_size = sizeof(TFlux_set);
gen_settings_size = sizeof(TGen_settings);
chunk_size = sizeof(TGen_Chunk);
change_block_size = sizeof(TBlock_set);
PROTOCOL = 5;
implementation
end.
|
{******************************************************************************}
{ }
{ Demo }
{ }
{ Copyright (C) Antônio José Medeiros Schneider Júnior }
{ }
{ https://github.com/antoniojmsjr/IPGeoLocation }
{ }
{ }
{******************************************************************************}
{ }
{ 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 Main;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, REST.Types, REST.Client,
Data.Bind.Components, Data.Bind.ObjectScope, Vcl.StdCtrls, Vcl.Grids,
Vcl.ValEdit, Vcl.OleCtrls, SHDocVw;
type
TfrmMain = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
Bevel1: TBevel;
Panel3: TPanel;
Bevel2: TBevel;
rstClientGetIP: TRESTClient;
rstRequestGetIP: TRESTRequest;
rstResponseGetIP: TRESTResponse;
edtIP: TEdit;
cbxProvedor: TComboBox;
Label1: TLabel;
Label2: TLabel;
btnLocalizacao: TButton;
btnIPExterno: TButton;
mmoJSONGeolocalizacao: TMemo;
Panel4: TPanel;
Bevel3: TBevel;
vleJSON: TValueListEditor;
wbrMaps: TWebBrowser;
Bevel4: TBevel;
procedure btnIPExternoClick(Sender: TObject);
procedure btnLocalizacaoClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
{ Private declarations }
procedure ResultJSON(const Value: string);
public
{ Public declarations }
end;
var
frmMain: TfrmMain;
implementation
uses
System.JSON, REST.Json, IPGeoLocation, IPGeoLocation.Types;
{$R *.dfm}
procedure TfrmMain.btnIPExternoClick(Sender: TObject);
var
lJSONObject: TJSONObject;
lIP: string;
begin
try
rstClientGetIP.BaseURL := 'https://api.ipgeolocation.io/getip';
rstClientGetIP.Accept := 'application/json';
rstRequestGetIP.Method := TRESTRequestMethod.rmGET;
rstRequestGetIP.Execute;
case rstResponseGetIP.StatusCode of
200:
begin
if (rstResponseGetIP.JSONValue.Null) or
not (rstResponseGetIP.JSONValue is TJSONObject) then
Exit;
try
lJSONObject :=
TJSONObject.ParseJSONValue(rstResponseGetIP.JSONValue.ToString) as TJSONObject;
lJSONObject.TryGetValue('ip', lIP);
edtIP.Clear;
edtIP.Text := lip;
finally
if Assigned(lJSONObject) then
FreeAndNil(lJSONObject);
end;
end;
end;
except
on E: Exception do
begin
ShowMessage(E.Message);
end;
end;
end;
procedure TfrmMain.btnLocalizacaoClick(Sender: TObject);
begin
try
TIPGeoLocation
.New
.IP[edtIP.Text]
.Provider[TIPGeoLocationProviderType(cbxProvedor.ItemIndex)]
.Params
.Request
.Execute
.ToJSON(ResultJSON);
except
on E: EIPGeoLocationRequestException do
begin
var lMsg: string;
lMsg := EmptyStr;
lMsg := Concat(lMsg, Format('Provider: %s', [E.Provider]), sLineBreak);
lMsg := Concat(lMsg, Format('Kind: %s', [IPGeoLocationExceptionKindToString(E.Kind)]), sLineBreak);
lMsg := Concat(lMsg, Format('URL: %s', [E.URL]), sLineBreak);
lMsg := Concat(lMsg, Format('Method: %s', [E.Method]), sLineBreak);
lMsg := Concat(lMsg, Format('Status Code: %d', [E.StatusCode]), sLineBreak);
lMsg := Concat(lMsg, Format('Status Text: %s', [E.StatusText]), sLineBreak);
lMsg := Concat(lMsg, Format('Message: %s', [E.Message]), sLineBreak);
Application.MessageBox(PWideChar(lMsg), 'ATENÇÃO', MB_OK + MB_ICONERROR);
end;
on E: Exception do
begin
Application.MessageBox(PWideChar(E.Message), 'ATENÇÃO', MB_OK + MB_ICONERROR);
end;
end;
end;
procedure TfrmMain.FormShow(Sender: TObject);
begin
btnIPExterno.Click;
end;
procedure TfrmMain.ResultJSON(const Value: string);
const
cURLMaps = 'https://www.google.com/maps/search/?api=1&query=%s,%s';
var
lJSONObject: TJsonObject;
lValueJSON: string;
lLogitude: string;
lLatitude: string;
begin
lJSONObject := TJSONObject.ParseJSONValue(Value, False, False) as TJsonObject;
try
mmoJSONGeolocalizacao.Clear;
mmoJSONGeolocalizacao.Lines.Add(lJSONObject.Format());
for var I := 0 to Pred(vleJSON.RowCount) do
if lJSONObject.TryGetValue(vleJSON.Keys[I], lValueJSON) then
vleJSON.Cells[1, I] := lValueJSON;
lJSONObject.TryGetValue('latitude', lLatitude);
lJSONObject.TryGetValue('longitude', lLogitude);
finally
if Assigned(lJSONObject) then
FreeAndNil(lJSONObject);
end;
if (lLatitude <> EmptyStr) and
(lLogitude <> EmptyStr) then
begin
wbrMaps.Stop;
//https://developers.google.com/maps/documentation/urls/guide
wbrMaps.Navigate(Format(cURLMaps, [lLatitude, lLogitude]));
end;
end;
end.
|
unit SG_Mail;
interface
uses
NMsmtp,
stdctrls;
procedure sendMail(puerto:integer;servidor,idUsuario,remitente,destinatarios,
cuerpo,asunto:string;EncodeTypeUuCode:boolean=true);
function getRemitente:string;
function getMailByNroUsuario(NroUsuario:string):string;
function getMailsByNroUsuarioFromListBox(listBox:TListBox):string;
procedure sendGMail;
implementation
uses
sysutils,
dbtables,
unitconexion,
SG_ListBox,
IdSMTP, IdSSLOpenSSL, IdMessage;
procedure sendMail(puerto:integer;servidor,idUsuario,remitente,destinatarios,
cuerpo,asunto:string;EncodeTypeUuCode:boolean=true);
var
NMSMTP:TNMSMTP;
begin
NMSMTP:=TNMSMTP.Create(nil);
NMSMTP.Host:=servidor;
NMSMTP.Port:=puerto;
NMSMTP.UserID:=idUsuario;
NMSMTP.PostMessage.FromAddress:=remitente;
NMSMTP.PostMessage.ToAddress.Text:=destinatarios;
NMSMTP.PostMessage.Body.Text:=cuerpo;
NMSMTP.PostMessage.Subject:=asunto;
if EncodeTypeUuCode then
NMSMTP.EncodeType:=uuCode
else
NMSMTP.EncodeType:=uuMime;
try
NMSMTP.Connect;
NMSMTP.SendMail;
NMSMTP.Disconnect;
except
on Exception do
begin
NMSMTP.Disconnect;
NMSMTP.Free;
raise;
end;
end;
NMSMTP.Free;
end;
function getRemitente:string;
var
consulta:string;
query:TQuery;
begin
consulta:=
'select EMail '+
'from MaestroUsuarios '+
'where IdUsuario = suser_sname()';
query:=AbreQuery(consulta);
Result:=query['EMail'];
end;
function getMailByNroUsuario(NroUsuario:string):string;
var
consulta:string;
query:TQuery;
begin
consulta:=
'select EMail '+
'from MaestroUsuarios '+
'where NroUsuario = '+NroUsuario;
query:=AbreQuery(consulta);
Result:=query['EMail'];
end;
function getMailsByNroUsuarioFromListBox(listBox:TListBox):string;
var
i:integer;
begin
for i:=0 to listBox.Items.Count-1 do
begin
if i>0 then
Result:=Result+'; ';
Result:=Result+getMailByNroUsuario(getCodigoListBox(listBox,i));
end;
end;
procedure sendGMail;
var
IdSMTP1: TIdSMTP;
IdSSLIOHandlerSocketOpenSSL1:TIdSSLIOHandlerSocketOpenSSL;
IdMessage1:TIdMessage;
//IdSSLIOHandlerSocketOpenSSL1StatusInfo:TIdSSLIOHandlerSocketOpenSSL1StatusInfo;
begin
IdSSLIOHandlerSocketOpenSSL1:=TIdSSLIOHandlerSocketOpenSSL.Create;
IdSMTP1:=TIdSMTP.Create;
IdMessage1:=TIdMessage.create;
with IdSSLIOHandlerSocketOpenSSL1 do
begin
Destination := 'smtp.gmail.com:587';
Host := 'smtp.gmail.com';
//MaxLineAction := maException;
Port := 587;
SSLOptions.Method := sslvTLSv1;
SSLOptions.Mode := sslmUnassigned;
SSLOptions.VerifyMode := [];
SSLOptions.VerifyDepth := 0;
//OnStatusInfo := IdSSLIOHandlerSocketOpenSSL1StatusInfo;
end;
with IdSMTP1 do
begin
//OnStatus := IdSMTP1Status;
IOHandler := IdSSLIOHandlerSocketOpenSSL1;
Host := 'smtp.gmail.com';
Password := 'c3r3br1n';
Port := 587;
//SASLMechanisms := <>;
//seTLS := utUseExplicitTLS;
Username := 'sebas.goldberg';
end;
IdSMTP1.Connect;
IdSMTP1.Send(IdMessage1);
IdSMTP1.Disconnect;
end;
end.
|
unit TSTOBsv.Xml;
Interface
Uses Classes, SysUtils, RTLConsts, HsXmlDocEx;
Type
IXmlBsvImage = Interface(IXmlNodeEx)
['{4B61686E-29A0-2112-90B9-955AA4158E49}']
Function GetImageName() : AnsiString;
Procedure SetImageName(Const AImageName : AnsiString);
Function GetX() : Word;
Procedure SetX(Const AX : Word);
Function GetY() : Word;
Procedure SetY(Const AY : Word);
Function GetWidth() : Word;
Procedure SetWidth(Const AWidth : Word);
Function GetHeight() : Word;
Procedure SetHeight(Const AHeight : Word);
Procedure Assign(ASource : IInterface);
Property ImageName : AnsiString Read GetImageName Write SetImageName;
Property X : Word Read GetX Write SetX;
Property Y : Word Read GetY Write SetY;
Property Width : Word Read GetWidth Write SetWidth;
Property Height : Word Read GetHeight Write SetHeight;
End;
IXmlBsvImages = Interface(IXmlNodeCollectionEx)
['{4B61686E-29A0-2112-8931-C22CD848108C}']
Function GetItem(Const Index : Integer) : IXmlBsvImage;
Function Add() : IXmlBsvImage;
Function Insert(Const Index: Integer) : IXmlBsvImage;
Procedure Assign(ASource : IInterface);
Property Items[Const Index: Integer] : IXmlBsvImage Read GetItem; Default;
End;
IXmlBsvAnimation = Interface(IXmlNodeEx)
['{4B61686E-29A0-2112-909C-C4CBB6E73754}']
Function GetAnimationName() : AnsiString;
Procedure SetAnimationName(Const AAnimationName : AnsiString);
Function GetStartFrame() : Word;
Procedure SetStartFrame(Const AStartFrame : Word);
Function GetEndFrame() : Word;
Procedure SetEndFrame(Const AEndFrame : Word);
Procedure Assign(ASource : IInterface);
Property AnimationName : AnsiString Read GetAnimationName Write SetAnimationName;
Property StartFrame : Word Read GetStartFrame Write SetStartFrame;
Property EndFrame : Word Read GetEndFrame Write SetEndFrame;
End;
IXmlBsvAnimations = Interface(IXmlNodeCollectionEx)
['{4B61686E-29A0-2112-B4E8-7EE9E3AB521C}']
Function GetItem(Const Index : Integer) : IXmlBsvAnimation;
Function Add() : IXmlBsvAnimation;
Function Insert(Const Index: Integer) : IXmlBsvAnimation;
Procedure Assign(ASource : IInterface);
Property Items[Const Index: Integer] : IXmlBsvAnimation Read GetItem; Default;
End;
IXmlBsvSubData = Interface(IXmlNodeEx)
['{4B61686E-29A0-2112-B50B-D85085FC64EB}']
Function GetImageId() : Word;
Procedure SetImageId(Const AImageId : Word);
Function GetX() : Single;
Procedure SetX(Const AX : Single);
Function GetY() : Single;
Procedure SetY(Const AY : Single);
Function GetXScale() : Single;
Procedure SetXScale(Const AXScale : Single);
Function GetSkew_H() : Single;
Procedure SetSkew_H(Const ASkew_H : Single);
Function GetSkew_V() : Single;
Procedure SetSkew_V(Const ASkew_V : Single);
Function GetYScale() : Single;
Procedure SetYScale(Const AYScale : Single);
Function GetOpacity() : Byte;
Procedure SetOpacity(Const AOpacity : Byte);
Procedure Assign(ASource : IInterface);
Property ImageId : Word Read GetImageId Write SetImageId;
Property X : Single Read GetX Write SetX;
Property Y : Single Read GetY Write SetY;
Property XScale : Single Read GetXScale Write SetXScale;
Property Skew_H : Single Read GetSkew_H Write SetSkew_H;
Property Skew_V : Single Read GetSkew_V Write SetSkew_V;
Property YScale : Single Read GetYScale Write SetYScale;
Property Opacity : Byte Read GetOpacity Write SetOpacity;
End;
IXmlBsvSubDatas = Interface(IXmlNodeCollectionEx)
['{4B61686E-29A0-2112-8992-2474D8C7D5AD}']
Function GetItem(Const Index : Integer) : IXmlBsvSubData;
Function Add() : IXmlBsvSubData;
Function Insert(Const Index: Integer) : IXmlBsvSubData;
Procedure Assign(ASource : IInterface);
Property Items[Const Index: Integer] : IXmlBsvSubData Read GetItem; Default;
End;
IXmlBsvSub = Interface(IXmlNodeEx)
['{4B61686E-29A0-2112-BF12-5274FC98CBCC}']
Function GetSubCount() : Word;
Function GetSubLen() : Byte;
Procedure SetSubLen(Const ASubLen : Byte);
Function GetSubData() : IXmlBsvSubDatas;
Procedure Assign(ASource : IInterface);
Property SubCount : Word Read GetSubCount;
Property SubLen : Byte Read GetSubLen Write SetSubLen;
Property SubData : IXmlBsvSubDatas Read GetSubData;
End;
IXmlBsvSubs = Interface(IXmlNodeCollectionEx)
['{4B61686E-29A0-2112-997D-05BD79702236}']
Function GetItem(Const Index : Integer) : IXmlBsvSub;
Function Add() : IXmlBsvSub;
Function Insert(Const Index: Integer) : IXmlBsvSub;
Procedure Assign(ASource : IInterface);
Property Items[Const Index: Integer] : IXmlBsvSub Read GetItem; Default;
End;
IXmlBsvFile = Interface(IXmlNodeEx)
['{4B61686E-29A0-2112-BB1A-792C3984FE97}']
Function GetFileSig() : Word;
Procedure SetFileSig(Const AFileSig : Word);
Function GetRegionCount() : Word;
Function GetHasOpacity() : Byte;
Procedure SetHasOpacity(Const AHasOpacity : Byte);
Function GetRgbFileName() : AnsiString;
Procedure SetRgbFileName(Const ARgbFileName : AnsiString);
Function GetRegion() : IXmlBsvImages;
Function GetTransformationCount() : Word;
Function GetSub() : IXmlBsvSubs;
Function GetAnimationCount() : Word;
Function GetAnimation() : IXmlBsvAnimations;
Procedure Assign(ASource : IInterface);
Property FileSig : Word Read GetFileSig Write SetFileSig;
Property RegionCount : Word Read GetRegionCount;
Property HasOpacity : Byte Read GetHasOpacity Write SetHasOpacity;
Property RgbFileName : AnsiString Read GetRgbFileName Write SetRgbFileName;
Property Region : IXmlBsvImages Read GetRegion;
Property TransformationCount : Word Read GetTransformationCount;
Property Sub : IXmlBsvSubs Read GetSub;
Property AnimationCount : Word Read GetAnimationCount;
Property Animation : IXmlBsvAnimations Read GetAnimation;
End;
(******************************************************************************)
TXmlBsvFile = Class(TObject)
Public
Class Function CreateBsvFile() : IXmlBsvFile; OverLoad;
Class Function CreateBsvFile(Const AXmlText : AnsiString) : IXmlBsvFile; OverLoad;
End;
Implementation
Uses Variants, HsInterfaceEx, TSTOBsvIntf;
Type
TXmlBsvImage = Class(TXmlNodeEx, IBsvImage, IXmlBsvImage)
Private
FImageImpl : Pointer;
Function GetImplementor() : IBsvImage;
Protected
Property ImageImpl : IBsvImage Read GetImplementor;
Function GetImageName() : AnsiString;
Procedure SetImageName(Const AImageName : AnsiString);
Function GetX() : Word;
Procedure SetX(Const AX : Word);
Function GetY() : Word;
Procedure SetY(Const AY : Word);
Function GetWidth() : Word;
Procedure SetWidth(Const AWidth : Word);
Function GetHeight() : Word;
Procedure SetHeight(Const AHeight : Word);
Procedure Clear();
Procedure Assign(ASource : IInterface);
Property ImageName : AnsiString Read GetImageName Write SetImageName;
Property X : Word Read GetX Write SetX;
Property Y : Word Read GetY Write SetY;
Property Width : Word Read GetWidth Write SetWidth;
Property Height : Word Read GetHeight Write SetHeight;
Public
Procedure AfterConstruction(); OverRide;
End;
TXmlBsvImages = Class(TXMLNodeCollectionEx, IBsvImages, IXmlBsvImages)
Private
FImagesImpl : IBsvImages;
Function GetImplementor() : IBsvImages;
Protected
Property ImagesImpl : IBsvImages Read GetImplementor Implements IBsvImages;
Function GetItem(Const Index : Integer) : IXmlBsvImage;
Function Add() : IXmlBsvImage;
Function Insert(Const Index : Integer) : IXmlBsvImage;
Procedure Assign(ASource : IInterface);
Procedure AssignTo(ATarget : IBsvImages);
Public
Procedure AfterConstruction(); OverRide;
End;
TXmlBsvAnimation = Class(TXmlNodeEx, IBsvAnimation, IXmlBsvAnimation)
Private
FAnimationImpl : Pointer;
Function GetImplementor() : IBsvAnimation;
Protected
Property AnimationImpl : IBsvAnimation Read GetImplementor;
Function GetAnimationName() : AnsiString;
Procedure SetAnimationName(Const AAnimationName : AnsiString);
Function GetStartFrame() : Word;
Procedure SetStartFrame(Const AStartFrame : Word);
Function GetEndFrame() : Word;
Procedure SetEndFrame(Const AEndFrame : Word);
Procedure Clear();
Procedure Assign(ASource : IInterface);
Property AnimationName : AnsiString Read GetAnimationName Write SetAnimationName;
Property StartFrame : Word Read GetStartFrame Write SetStartFrame;
Property EndFrame : Word Read GetEndFrame Write SetEndFrame;
Public
Procedure AfterConstruction(); OverRide;
End;
TXmlBsvAnimations = Class(TXMLNodeCollectionEx, IBsvAnimations, IXmlBsvAnimations)
Private
FAnimationsImpl : IBsvAnimations;
Function GetImplementor() : IBsvAnimations;
Protected
Property AnimationsImpl : IBsvAnimations Read GetImplementor Implements IBsvAnimations;
Function GetItem(Const Index : Integer) : IXmlBsvAnimation;
Function Add() : IXmlBsvAnimation;
Function Insert(Const Index : Integer) : IXmlBsvAnimation;
Procedure Assign(ASource : IInterface);
Procedure AssignTo(ATarget : IBsvAnimations);
Public
Procedure AfterConstruction(); OverRide;
End;
TXmlBsvSubData = Class(TXmlNodeEx, IBsvSubData, IXmlBsvSubData)
Private
FSubDataImpl : Pointer;
Function GetImplementor() : IBsvSubData;
Protected
Property SubDataImpl : IBsvSubData Read GetImplementor;
Function GetImageId() : Word;
Procedure SetImageId(Const AImageId : Word);
Function GetX() : Single;
Procedure SetX(Const AX : Single);
Function GetY() : Single;
Procedure SetY(Const AY : Single);
Function GetXScale() : Single;
Procedure SetXScale(Const AXScale : Single);
Function GetSkew_H() : Single;
Procedure SetSkew_H(Const ASkew_H : Single);
Function GetSkew_V() : Single;
Procedure SetSkew_V(Const ASkew_V : Single);
Function GetYScale() : Single;
Procedure SetYScale(Const AYScale : Single);
Function GetOpacity() : Byte;
Procedure SetOpacity(Const AOpacity : Byte);
Procedure Clear();
Procedure Assign(ASource : IInterface);
Property ImageId : Word Read GetImageId Write SetImageId;
Property X : Single Read GetX Write SetX;
Property Y : Single Read GetY Write SetY;
Property XScale : Single Read GetXScale Write SetXScale;
Property Skew_H : Single Read GetSkew_H Write SetSkew_H;
Property Skew_V : Single Read GetSkew_V Write SetSkew_V;
Property YScale : Single Read GetYScale Write SetYScale;
Property Opacity : Byte Read GetOpacity Write SetOpacity;
Public
Procedure AfterConstruction(); OverRide;
End;
TXmlBsvSubDatas = Class(TXMLNodeCollectionEx, IBsvSubDatas, IXmlBsvSubDatas)
Private
FSubDatasImpl : IBsvSubDatas;
Function GetImplementor() : IBsvSubDatas;
Protected
Property SubDatasImpl : IBsvSubDatas Read GetImplementor Implements IBsvSubDatas;
Function GetItem(Const Index : Integer) : IXmlBsvSubData;
Function Add() : IXmlBsvSubData;
Function Insert(Const Index : Integer) : IXmlBsvSubData;
Procedure Assign(ASource : IInterface);
Procedure AssignTo(ATarget : IBsvSubDatas);
Public
Procedure AfterConstruction(); OverRide;
End;
TXmlBsvSub = Class(TXmlNodeEx, IBsvSub, IXmlBsvSub)
Private
FSubImpl : Pointer;
Function GetImplementor() : IBsvSub;
Protected
Property SubImpl : IBsvSub Read GetImplementor;
Function GetSubCount() : Word;
Function GetSubLen() : Byte;
Procedure SetSubLen(Const ASubLen : Byte);
Function GetSubData() : IXmlBsvSubDatas;
Function GetISubData() : IBsvSubDatas;
Function IBsvSub.GetSubData = GetISubData;
Procedure Clear();
Property SubCount : Word Read GetSubCount;
Property SubLen : Byte Read GetSubLen Write SetSubLen;
Property SubData : IXmlBsvSubDatas Read GetSubData;
Procedure Assign(ASource : IInterface);
Public
Procedure AfterConstruction(); OverRide;
End;
TXmlBsvSubs = Class(TXMLNodeCollectionEx, IBsvSubs, IXmlBsvSubs)
Private
FSubsImpl : IBsvSubs;
Function GetImplementor() : IBsvSubs;
Protected
Property SubsImpl : IBsvSubs Read GetImplementor Implements IBsvSubs;
Function GetItem(Const Index : Integer) : IXmlBsvSub;
Function Add() : IXmlBsvSub;
Function Insert(Const Index : Integer) : IXmlBsvSub;
Procedure Assign(ASource : IInterface);
Procedure AssignTo(ATarget : IBsvSubs);
Public
Procedure AfterConstruction(); OverRide;
End;
TXmlBsvFileImpl = Class(TXmlNodeEx, IBsvFile, IXmlBsvFile)
Private
FFileImpl : Pointer;
Function GetImplementor() : IBsvFile;
Protected
Property FileImpl : IBsvFile Read GetImplementor;
Function GetFileSig() : Word;
Procedure SetFileSig(Const AFileSig : Word);
Function GetRegionCount() : Word;
Function GetHasOpacity() : Byte;
Procedure SetHasOpacity(Const AHasOpacity : Byte);
Function GetRgbFileName() : AnsiString;
Procedure SetRgbFileName(Const ARgbFileName : AnsiString);
Function GetRegion() : IXmlBsvImages;
Function GetIRegion() : IBsvImages;
Function IBsvFile.GetRegion = GetIRegion;
Function GetTransformationCount() : Word;
Function GetSub() : IXmlBsvSubs;
Function GetISub() : IBsvSubs;
Function IBsvFile.GetSub = GetISub;
Function GetAnimationCount() : Word;
Function GetAnimation() : IXmlBsvAnimations;
Function GetIAnimation() : IBsvAnimations;
Function IBsvFile.GetAnimation = GetIAnimation;
Procedure Clear();
Procedure Assign(ASource : IInterface);
Property FileSig : Word Read GetFileSig Write SetFileSig;
Property RegionCount : Word Read GetRegionCount;
Property HasOpacity : Byte Read GetHasOpacity Write SetHasOpacity;
Property RgbFileName : AnsiString Read GetRgbFileName Write SetRgbFileName;
Property Region : IXmlBsvImages Read GetRegion;
Property TransformationCount : Word Read GetTransformationCount;
Property Sub : IXmlBsvSubs Read GetSub;
Property AnimationCount : Word Read GetAnimationCount;
Property Animation : IXmlBsvAnimations Read GetAnimation;
Public
Procedure AfterConstruction(); OverRide;
End;
Class Function TXmlBsvFile.CreateBsvFile() : IXmlBsvFile;
Begin
Result := NewXmlDocument().GetDocBinding('BsvFile', TXmlBsvFileImpl) As IXmlBsvFile;
End;
Class Function TXmlBsvFile.CreateBsvFile(Const AXmlText : AnsiString) : IXmlBsvFile;
Begin
Result := LoadXmlData(AXmlText).GetDocBinding('BsvFile', TXmlBsvFileImpl) As IXmlBsvFile;
End;
(******************************************************************************)
Procedure TXmlBsvImage.AfterConstruction();
Begin
InHerited AfterConstruction();
FImageImpl := Pointer(IBsvImage(Self));
End;
Function TXmlBsvImage.GetImplementor() : IBsvImage;
Begin
Result := IBsvImage(FImageImpl);
End;
Procedure TXmlBsvImage.Clear();
Begin
ChildNodes['ImageName'].NodeValue := Null;
ChildNodes['X'].NodeValue := Null;
ChildNodes['Y'].NodeValue := Null;
ChildNodes['Width'].NodeValue := Null;
ChildNodes['Height'].NodeValue := Null;
End;
Procedure TXmlBsvImage.Assign(ASource : IInterface);
Var lXmlSrc : IXmlBsvImage;
lSrc : IBsvImage;
Begin
If Supports(ASource, IXmlNodeEx) And
Supports(ASource, IXmlBsvImage, lXmlSrc) Then
Begin
ChildNodes['ImageName'].NodeValue := lXmlSrc.ImageName;
ChildNodes['X'].NodeValue := lXmlSrc.X;
ChildNodes['Y'].NodeValue := lXmlSrc.Y;
ChildNodes['Width'].NodeValue := lXmlSrc.Width;
ChildNodes['Height'].NodeValue := lXmlSrc.Height;
End
Else If Supports(ASource, IBsvImage, lSrc) Then
Begin
ChildNodes['ImageName'].NodeValue := lSrc.ImageName;
ChildNodes['X'].NodeValue := lSrc.X;
ChildNodes['Y'].NodeValue := lSrc.Y;
ChildNodes['Width'].NodeValue := lSrc.Width;
ChildNodes['Height'].NodeValue := lSrc.Height;
FImageImpl := Pointer(lSrc);
End
Else
Raise EConvertError.CreateResFmt(@SAssignError, [GetInterfaceName(ASource), ClassName]);
End;
Function TXmlBsvImage.GetImageName() : AnsiString;
Begin
Result := ChildNodes['ImageName'].AsString;
End;
Procedure TXmlBsvImage.SetImageName(Const AImageName : AnsiString);
Begin
ChildNodes['ImageName'].AsString := AImageName;
If Not IsImplementorOf(ImageImpl) Then
ImageImpl.ImageName := AImageName;
End;
Function TXmlBsvImage.GetX() : Word;
Begin
Result := ChildNodes['X'].AsInteger;
End;
Procedure TXmlBsvImage.SetX(Const AX : Word);
Begin
ChildNodes['X'].AsInteger := AX;
If Not IsImplementorOf(ImageImpl) Then
ImageImpl.X := AX;
End;
Function TXmlBsvImage.GetY() : Word;
Begin
Result := ChildNodes['Y'].AsInteger;
End;
Procedure TXmlBsvImage.SetY(Const AY : Word);
Begin
ChildNodes['Y'].AsInteger := AY;
If Not IsImplementorOf(ImageImpl) Then
ImageImpl.Y := AY;
End;
Function TXmlBsvImage.GetWidth() : Word;
Begin
Result := ChildNodes['Width'].AsInteger;
End;
Procedure TXmlBsvImage.SetWidth(Const AWidth : Word);
Begin
ChildNodes['Width'].AsInteger := AWidth;
If Not IsImplementorOf(ImageImpl) Then
ImageImpl.Width := AWidth;
End;
Function TXmlBsvImage.GetHeight() : Word;
Begin
Result := ChildNodes['Height'].AsInteger;
End;
Procedure TXmlBsvImage.SetHeight(Const AHeight : Word);
Begin
ChildNodes['Height'].AsInteger := AHeight;
If Not IsImplementorOf(ImageImpl) Then
ImageImpl.Height := AHeight;
End;
Procedure TXmlBsvImages.AfterConstruction();
Begin
RegisterChildNode('XmlBsvImage', TXmlBsvImage);
ItemTag := 'XmlBsvImage';
ItemInterface := IXmlBsvImage;
InHerited AfterConstruction();
End;
Function TXmlBsvImages.GetImplementor() : IBsvImages;
Begin
If Not Assigned(FImagesImpl) Then
FImagesImpl := TBsvFile.CreateBsvImages();
Result := FImagesImpl;
AssignTo(Result);
End;
Function TXmlBsvImages.GetItem(Const Index : Integer) : IXmlBsvImage;
Begin
Result := List[Index] As IXmlBsvImage;
End;
Function TXmlBsvImages.Add() : IXmlBsvImage;
Begin
Result := AddItem(-1) As IXmlBsvImage;
End;
Function TXmlBsvImages.Insert(Const Index : Integer) : IXmlBsvImage;
Begin
Result := AddItem(Index) As IXmlBsvImage;
End;
Procedure TXmlBsvImages.Assign(ASource : IInterface);
Var lXmlSrc : IXmlBsvImages;
lSrc : IBsvImages;
X : Integer;
Begin
If Supports(ASource, IXMLNodeCollectionEx) And
Supports(ASource, IXmlBsvImages, lXmlSrc) Then
Begin
Clear();
For X := 0 To lXmlSrc.Count - 1 Do
Add().Assign(lXmlSrc[X]);
End
Else If Supports(ASource, IBsvImages, lSrc) Then
Begin
Clear();
For X := 0 To lSrc.Count - 1 Do
Add().Assign(lSrc[X]);
FImagesImpl := lSrc;
End
Else
Raise EConvertError.CreateResFmt(@SAssignError, [GetInterfaceName(ASource), ClassName]);
End;
Procedure TXmlBsvImages.AssignTo(ATarget : IBsvImages);
Var X : Integer;
lItem : IBsvImage;
Begin
ATarget.Clear();
For X := 0 To Count - 1 Do
If Supports(List[X], IBsvImage, lItem) Then
ATarget.Add().Assign(lItem);
End;
Procedure TXmlBsvAnimation.AfterConstruction();
Begin
InHerited AfterConstruction();
FAnimationImpl := Pointer(IBsvAnimation(Self));
End;
Function TXmlBsvAnimation.GetImplementor() : IBsvAnimation;
Begin
Result := IBsvAnimation(FAnimationImpl);
End;
Procedure TXmlBsvAnimation.Clear();
Begin
ChildNodes['AnimationName'].NodeValue := Null;
ChildNodes['StartFrame'].NodeValue := Null;
ChildNodes['EndFrame'].NodeValue := Null;
End;
Procedure TXmlBsvAnimation.Assign(ASource : IInterface);
Var lXmlSrc : IXmlBsvAnimation;
lSrc : IBsvAnimation;
Begin
If Supports(ASource, IXmlNodeEx) And
Supports(ASource, IXmlBsvAnimation, lXmlSrc) Then
Begin
ChildNodes['AnimationName'].NodeValue := lXmlSrc.AnimationName;
ChildNodes['StartFrame'].NodeValue := lXmlSrc.StartFrame;
ChildNodes['EndFrame'].NodeValue := lXmlSrc.EndFrame;
End
Else If Supports(ASource, IBsvAnimation, lSrc) Then
Begin
ChildNodes['AnimationName'].NodeValue := lSrc.AnimationName;
ChildNodes['StartFrame'].NodeValue := lSrc.StartFrame;
ChildNodes['EndFrame'].NodeValue := lSrc.EndFrame;
FAnimationImpl := Pointer(lSrc);
End
Else
Raise EConvertError.CreateResFmt(@SAssignError, [GetInterfaceName(ASource), ClassName]);
End;
Function TXmlBsvAnimation.GetAnimationName() : AnsiString;
Begin
Result := ChildNodes['AnimationName'].AsString;
End;
Procedure TXmlBsvAnimation.SetAnimationName(Const AAnimationName : AnsiString);
Begin
ChildNodes['AnimationName'].AsString := AAnimationName;
If Not IsImplementorOf(AnimationImpl) Then
AnimationImpl.AnimationName := AAnimationName;
End;
Function TXmlBsvAnimation.GetStartFrame() : Word;
Begin
Result := ChildNodes['StartFrame'].AsInteger;
End;
Procedure TXmlBsvAnimation.SetStartFrame(Const AStartFrame : Word);
Begin
ChildNodes['StartFrame'].AsInteger := AStartFrame;
If Not IsImplementorOf(AnimationImpl) Then
AnimationImpl.StartFrame := AStartFrame;
End;
Function TXmlBsvAnimation.GetEndFrame() : Word;
Begin
Result := ChildNodes['EndFrame'].AsInteger;
End;
Procedure TXmlBsvAnimation.SetEndFrame(Const AEndFrame : Word);
Begin
ChildNodes['EndFrame'].AsInteger := AEndFrame;
If Not IsImplementorOf(AnimationImpl) Then
AnimationImpl.EndFrame := AEndFrame;
End;
Procedure TXmlBsvAnimations.AfterConstruction();
Begin
RegisterChildNode('XmlBsvAnimation', TXmlBsvAnimation);
ItemTag := 'XmlBsvAnimation';
ItemInterface := IXmlBsvAnimation;
InHerited AfterConstruction();
End;
Function TXmlBsvAnimations.GetImplementor() : IBsvAnimations;
Begin
If Not Assigned(FAnimationsImpl) Then
FAnimationsImpl := TBsvFile.CreateBsvAnimations();
Result := FAnimationsImpl;
AssignTo(Result);
End;
Function TXmlBsvAnimations.GetItem(Const Index : Integer) : IXmlBsvAnimation;
Begin
Result := List[Index] As IXmlBsvAnimation;
End;
Function TXmlBsvAnimations.Add() : IXmlBsvAnimation;
Begin
Result := AddItem(-1) As IXmlBsvAnimation;
End;
Function TXmlBsvAnimations.Insert(Const Index : Integer) : IXmlBsvAnimation;
Begin
Result := AddItem(Index) As IXmlBsvAnimation;
End;
Procedure TXmlBsvAnimations.Assign(ASource : IInterface);
Var lXmlSrc : IXmlBsvAnimations;
lSrc : IBsvAnimations;
X : Integer;
Begin
If Supports(ASource, IXmlNodeListEx) And
Supports(ASource, IXmlBsvAnimations, lXmlSrc) Then
Begin
Clear();
For X := 0 To lXmlSrc.Count - 1 Do
Add().Assign(lXmlSrc[X]);
End
Else If Supports(ASource, IBsvAnimations, lSrc) Then
Begin
Clear();
For X := 0 To lSrc.Count - 1 Do
Add().Assign(lSrc[X]);
FAnimationsImpl := lSrc;
End
Else
Raise EConvertError.CreateResFmt(@SAssignError, [GetInterfaceName(ASource), ClassName]);
End;
Procedure TXmlBsvAnimations.AssignTo(ATarget : IBsvAnimations);
Var X : Integer;
lItem : IBsvAnimation;
Begin
ATarget.Clear();
For X := 0 To Count - 1 Do
If Supports(List[X], IBsvAnimation, lItem) Then
ATarget.Add().Assign(lItem);
End;
Procedure TXmlBsvSubData.AfterConstruction();
Begin
InHerited AfterConstruction();
FSubDataImpl := Pointer(IBsvSubData(Self));
End;
Function TXmlBsvSubData.GetImplementor() : IBsvSubData;
Begin
Result := IBsvSubData(FSubDataImpl);
End;
Procedure TXmlBsvSubData.Clear();
Begin
ChildNodes['ImageId'].NodeValue := Null;
ChildNodes['X'].NodeValue := Null;
ChildNodes['Y'].NodeValue := Null;
ChildNodes['XScale'].NodeValue := Null;
ChildNodes['Skew_H'].NodeValue := Null;
ChildNodes['Skew_V'].NodeValue := Null;
ChildNodes['YScale'].NodeValue := Null;
End;
Procedure TXmlBsvSubData.Assign(ASource : IInterface);
Var lXmlSrc : IXmlBsvSubData;
lSrc : IBsvSubData;
Begin
If Supports(ASource, IXmlNodeEx) And
Supports(ASource, IXmlBsvSubData, lXmlSrc) Then
Begin
ChildNodes['ImageId'].NodeValue := lXmlSrc.ImageId;
ChildNodes['X'].NodeValue := lXmlSrc.X;
ChildNodes['Y'].NodeValue := lXmlSrc.Y;
ChildNodes['XScale'].NodeValue := lXmlSrc.XScale;
ChildNodes['Skew_H'].NodeValue := lXmlSrc.Skew_H;
ChildNodes['Skew_V'].NodeValue := lXmlSrc.Skew_V;
ChildNodes['YScale'].NodeValue := lXmlSrc.YScale;
ChildNodes['Opacity'].NodeValue := lXmlSrc.Opacity;
End
Else If Supports(ASource, IBsvSubData, lSrc) Then
Begin
ChildNodes['ImageId'].NodeValue := lSrc.ImageId;
ChildNodes['X'].NodeValue := lSrc.X;
ChildNodes['Y'].NodeValue := lSrc.Y;
ChildNodes['XScale'].NodeValue := lSrc.XScale;
ChildNodes['Skew_H'].NodeValue := lSrc.Skew_H;
ChildNodes['Skew_V'].NodeValue := lSrc.Skew_V;
ChildNodes['YScale'].NodeValue := lSrc.YScale;
ChildNodes['Opacity'].NodeValue := lSrc.Opacity;
FSubDataImpl := Pointer(lSrc);
End
Else
Raise EConvertError.CreateResFmt(@SAssignError, [GetInterfaceName(ASource), ClassName]);
End;
Function TXmlBsvSubData.GetImageId() : Word;
Begin
Result := ChildNodes['ImageId'].AsInteger;
End;
Procedure TXmlBsvSubData.SetImageId(Const AImageId : Word);
Begin
ChildNodes['ImageId'].AsInteger := AImageId;
If Not IsImplementorOf(SubDataImpl) Then
SubDataImpl.ImageId := AImageId;
End;
Function TXmlBsvSubData.GetX() : Single;
Begin
Result := ChildNodes['X'].AsFloat;
End;
Procedure TXmlBsvSubData.SetX(Const AX : Single);
Begin
ChildNodes['X'].AsFloat := AX;
If Not IsImplementorOf(SubDataImpl) Then
SubDataImpl.X := AX;
End;
Function TXmlBsvSubData.GetY() : Single;
Begin
Result := ChildNodes['Y'].AsFloat;
End;
Procedure TXmlBsvSubData.SetY(Const AY : Single);
Begin
ChildNodes['Y'].AsFloat := AY;
If Not IsImplementorOf(SubDataImpl) Then
SubDataImpl.Y := AY;
End;
Function TXmlBsvSubData.GetXScale() : Single;
Begin
Result := ChildNodes['XScale'].AsFloat;
End;
Procedure TXmlBsvSubData.SetXScale(Const AXScale : Single);
Begin
ChildNodes['XScale'].AsFloat := AXScale;
If Not IsImplementorOf(SubDataImpl) Then
SubDataImpl.XScale := AXScale;
End;
Function TXmlBsvSubData.GetSkew_H() : Single;
Begin
Result := ChildNodes['Skew_H'].AsFloat;
End;
Procedure TXmlBsvSubData.SetSkew_H(Const ASkew_H : Single);
Begin
ChildNodes['Skew_H'].AsFloat := ASkew_H;
If Not IsImplementorOf(SubDataImpl) Then
SubDataImpl.Skew_H := ASkew_H;
End;
Function TXmlBsvSubData.GetSkew_V() : Single;
Begin
Result := ChildNodes['Skew_V'].AsFloat;
End;
Procedure TXmlBsvSubData.SetSkew_V(Const ASkew_V : Single);
Begin
ChildNodes['Skew_V'].AsFloat := ASkew_V;
If Not IsImplementorOf(SubDataImpl) Then
SubDataImpl.Skew_V := ASkew_V;
End;
Function TXmlBsvSubData.GetYScale() : Single;
Begin
Result := ChildNodes['YScale'].AsFloat;
End;
Procedure TXmlBsvSubData.SetYScale(Const AYScale : Single);
Begin
ChildNodes['YScale'].AsFloat := AYScale;
If Not IsImplementorOf(SubDataImpl) Then
SubDataImpl.YScale := AYScale;
End;
Function TXmlBsvSubData.GetOpacity() : Byte;
Begin
Result := ChildNodes['Opacity'].AsInteger;
End;
Procedure TXmlBsvSubData.SetOpacity(Const AOpacity : Byte);
Begin
ChildNodes['Opacity'].AsInteger := AOpacity;
If Not IsImplementorOf(SubDataImpl) Then
SubDataImpl.Opacity := AOpacity;
End;
Procedure TXmlBsvSubDatas.AfterConstruction();
Begin
RegisterChildNode('XmlBsvSubData', TXmlBsvSubData);
ItemTag := 'XmlBsvSubData';
ItemInterface := IXmlBsvSubData;
InHerited AfterConstruction();
End;
Function TXmlBsvSubDatas.GetImplementor() : IBsvSubDatas;
Begin
If Not Assigned(FSubDatasImpl) Then
FSubDatasImpl := TBsvFile.CreateBsvSubDatas();
Result := FSubDatasImpl;
AssignTo(Result);
End;
Function TXmlBsvSubDatas.GetItem(Const Index : Integer) : IXmlBsvSubData;
Begin
Result := List[Index] As IXmlBsvSubData;
End;
Function TXmlBsvSubDatas.Add() : IXmlBsvSubData;
Begin
Result := AddItem(-1) As IXmlBsvSubData;
End;
Function TXmlBsvSubDatas.Insert(Const Index : Integer) : IXmlBsvSubData;
Begin
Result := AddItem(Index) As IXmlBsvSubData;
End;
Procedure TXmlBsvSubDatas.Assign(ASource : IInterface);
Var lXmlSrc : IXmlBsvSubDatas;
lSrc : IBsvSubDatas;
X : Integer;
Begin
If Supports(ASource, IXMLNodeCollectionEx) And
Supports(ASource, IXmlBsvSubDatas, lXmlSrc) Then
Begin
Clear();
For X := 0 To lXmlSrc.Count - 1 Do
Add().Assign(lXmlSrc[X]);
End
Else If Supports(ASource, IBsvSubDatas, lSrc) Then
Begin
Clear();
For X := 0 To lSrc.Count - 1 Do
Add().Assign(lSrc[X]);
FSubDatasImpl := lSrc;
End
Else
Raise EConvertError.CreateResFmt(@SAssignError, [GetInterfaceName(ASource), ClassName]);
End;
Procedure TXmlBsvSubDatas.AssignTo(ATarget : IBsvSubDatas);
Var X : Integer;
lItem : IBsvSubData;
Begin
ATarget.Clear();
For X := 0 To Count - 1 Do
If Supports(List[X], IBsvSubData, lItem) Then
ATarget.Add().Assign(lItem);
End;
Procedure TXmlBsvSub.AfterConstruction();
Begin
InHerited AfterConstruction();
RegisterChildNode('SubData', TXmlBsvSubDatas);
FSubImpl := Pointer(IBsvSub(Self));
End;
Function TXmlBsvSub.GetImplementor() : IBsvSub;
Begin
Result := IBsvSub(FSubImpl);
End;
Procedure TXmlBsvSub.Clear();
Begin
ChildNodes['SubCount'].NodeValue := Null;
ChildNodes['SubLen'].NodeValue := Null;
ChildNodes['SubData'].NodeValue := Null;
End;
Procedure TXmlBsvSub.Assign(ASource : IInterface);
Var lXmlSrc : IXmlBsvSub;
lSrc : IBsvSub;
Begin
If Supports(ASource, IXmlNodeEx) And
Supports(ASource, IXmlBsvSub, lXmlSrc) Then
Begin
ChildNodes['SubCount'].NodeValue := lXmlSrc.SubCount;
ChildNodes['SubLen'].NodeValue := lXmlSrc.SubLen;
SubData.Assign(lXmlSrc.SubData);
End
Else If Supports(ASource, IBsvSub, lSrc) Then
Begin
ChildNodes['SubCount'].NodeValue := lSrc.SubCount;
ChildNodes['SubLen'].NodeValue := lSrc.SubLen;
SubData.Assign(lSrc.SubData);
FSubImpl := Pointer(lSrc);
End
Else
Raise EConvertError.CreateResFmt(@SAssignError, [GetInterfaceName(ASource), ClassName]);
End;
Function TXmlBsvSub.GetSubCount() : Word;
Begin
Result := SubData.Count;
End;
Function TXmlBsvSub.GetSubLen() : Byte;
Begin
Result := ChildNodes['SubLen'].AsInteger;
End;
Procedure TXmlBsvSub.SetSubLen(Const ASubLen : Byte);
Begin
ChildNodes['SubLen'].AsInteger := ASubLen;
If Not IsImplementorOf(SubImpl) Then
SubImpl.SubLen := ASubLen;
End;
Function TXmlBsvSub.GetSubData() : IXmlBsvSubDatas;
Begin
Result := ChildNodes['SubData'] As IXmlBsvSubDatas;
End;
Function TXmlBsvSub.GetISubData() : IBsvSubDatas;
Begin
Result := GetSubData() As IBsvSubDatas;
End;
Procedure TXmlBsvSubs.AfterConstruction();
Begin
RegisterChildNode('XmlBsvSub', TXmlBsvSub);
ItemTag := 'XmlBsvSub';
ItemInterface := IXmlBsvSub;
InHerited AfterConstruction();
End;
Function TXmlBsvSubs.GetImplementor() : IBsvSubs;
Begin
If Not Assigned(FSubsImpl) Then
FSubsImpl := TBsvFile.CreateBsvSubs();
Result := FSubsImpl;
AssignTo(FSubsImpl);
End;
Function TXmlBsvSubs.GetItem(Const Index : Integer) : IXmlBsvSub;
Begin
Result := List[Index] As IXmlBsvSub;
End;
Function TXmlBsvSubs.Add() : IXmlBsvSub;
Begin
Result := AddItem(-1) As IXmlBsvSub;
End;
Function TXmlBsvSubs.Insert(Const Index : Integer) : IXmlBsvSub;
Begin
Result := AddItem(Index) As IXmlBsvSub;
End;
Procedure TXmlBsvSubs.Assign(ASource : IInterface);
Var lXmlSrc : IXmlBsvSubs;
lSrc : IBsvSubs;
X : Integer;
Begin
If Supports(ASource, IXMLNodeCollectionEx) And
Supports(ASource, IXmlBsvSubs, lXmlSrc) Then
Begin
Clear();
For X := 0 To lXmlSrc.Count - 1 Do
Add().Assign(lXmlSrc[X]);
End
Else If Supports(ASource, IBsvSubs, lSrc) Then
Begin
Clear();
For X := 0 To lSrc.Count - 1 Do
Add().Assign(lSrc[X]);
FSubsImpl := lSrc;
End
Else
Raise EConvertError.CreateResFmt(@SAssignError, [GetInterfaceName(ASource), ClassName]);
End;
Procedure TXmlBsvSubs.AssignTo(ATarget : IBsvSubs);
Begin
End;
Procedure TXmlBsvFileImpl.AfterConstruction();
Begin
InHerited AfterConstruction();
RegisterChildNode('Region', TXmlBsvImages);
RegisterChildNode('Sub', TXmlBsvSubs);
RegisterChildNode('Animation', TXmlBsvAnimations);
FFileImpl := Pointer(IBsvFile(Self));
End;
Function TXmlBsvFileImpl.GetImplementor() : IBsvFile;
Begin
Result := IBsvFile(FFileImpl);
End;
Procedure TXmlBsvFileImpl.Clear();
Begin
ChildNodes['FileSig'].NodeValue := Null;
ChildNodes['RegionCount'].NodeValue := Null;
ChildNodes['HasOpacity'].NodeValue := Null;
ChildNodes['RgbFileName'].NodeValue := Null;
ChildNodes['Region'].NodeValue := Null;
ChildNodes['TransformationCount'].NodeValue := Null;
ChildNodes['Sub'].NodeValue := Null;
ChildNodes['AnimationCount'].NodeValue := Null;
ChildNodes['Animation'].NodeValue := Null;
End;
Procedure TXmlBsvFileImpl.Assign(ASource : IInterface);
Var lXmlSrc : IXmlBsvFile;
lSrc : IBsvFile;
Begin
If Supports(ASource, IXmlNodeEx) And
Supports(ASource, IXmlBsvFile, lXmlSrc) Then
Begin
ChildNodes['FileSig'].NodeValue := lXmlSrc.FileSig;
ChildNodes['HasOpacity'].NodeValue := lXmlSrc.HasOpacity;
ChildNodes['RgbFileName'].NodeValue := lXmlSrc.RgbFileName;
Region.Assign(lXmlSrc.Region);
Sub.Assign(lXmlSrc.Sub);
Animation.Assign(lXmlSrc.Animation);
End
Else If Supports(ASource, IBsvFile, lSrc) Then
Begin
ChildNodes['FileSig'].NodeValue := lSrc.FileSig;
ChildNodes['HasOpacity'].NodeValue := lSrc.HasOpacity;
ChildNodes['RgbFileName'].NodeValue := lSrc.RgbFileName;
Region.Assign(lSrc.Region);
Sub.Assign(lSrc.Sub);
Animation.Assign(lSrc.Animation);
FFileImpl := Pointer(lSrc);
End
Else
Raise EConvertError.CreateResFmt(@SAssignError, [GetInterfaceName(ASource), ClassName]);
End;
Function TXmlBsvFileImpl.GetFileSig() : Word;
Begin
Result := ChildNodes['FileSig'].AsInteger;
End;
Procedure TXmlBsvFileImpl.SetFileSig(Const AFileSig : Word);
Begin
ChildNodes['FileSig'].AsInteger := AFileSig;
End;
Function TXmlBsvFileImpl.GetRegionCount() : Word;
Begin
Result := Region.Count;
End;
Function TXmlBsvFileImpl.GetHasOpacity() : Byte;
Begin
Result := ChildNodes['HasOpacity'].AsInteger;
End;
Procedure TXmlBsvFileImpl.SetHasOpacity(Const AHasOpacity : Byte);
Begin
ChildNodes['HasOpacity'].AsInteger := AHasOpacity;
End;
Function TXmlBsvFileImpl.GetRgbFileName() : AnsiString;
Begin
Result := ChildNodes['RgbFileName'].AsString;
End;
Procedure TXmlBsvFileImpl.SetRgbFileName(Const ARgbFileName : AnsiString);
Begin
ChildNodes['RgbFileName'].AsString := ARgbFileName;
End;
Function TXmlBsvFileImpl.GetRegion() : IXmlBsvImages;
Begin
Result := ChildNodes['Region'] As IXmlBsvImages;
End;
Function TXmlBsvFileImpl.GetIRegion() : IBsvImages;
Begin
Result := GetRegion() As IBsvImages;
End;
Function TXmlBsvFileImpl.GetTransformationCount() : Word;
Begin
Result := Sub.Count;
End;
Function TXmlBsvFileImpl.GetSub() : IXmlBsvSubs;
Begin
Result := ChildNodes['Sub'] As IXmlBsvSubs;
End;
Function TXmlBsvFileImpl.GetISub() : IBsvSubs;
Begin
Result := GetSub() As IBsvSubs;
End;
Function TXmlBsvFileImpl.GetAnimationCount() : Word;
Begin
Result := Animation.Count;
End;
Function TXmlBsvFileImpl.GetAnimation() : IXmlBsvAnimations;
Begin
Result := ChildNodes['Animation'] As IXmlBsvAnimations;
End;
Function TXmlBsvFileImpl.GetIAnimation() : IBsvAnimations;
Begin
Result := GetAnimation() As IBsvAnimations;
End;
End.
|
unit RESTRequest4D.Response.Contract;
interface
uses
{$IFDEF FPC}
SysUtils, Classes, fpjson;
{$ELSE}
System.SysUtils, System.JSON, System.Classes;
{$ENDIF}
type
IResponse = interface
['{A3BB1797-E99E-4C72-8C4A-925825A50C27}']
function Content: string;
function ContentLength: Cardinal;
function ContentType: string;
function ContentEncoding: string;
function ContentStream: TStream;
function StatusCode: Integer;
function StatusText: string;
function RawBytes: TBytes;
function Headers: TStrings;
function GetCookie(const ACookieName: string): string;
{$IFDEF FPC}
function JSONValue: TJSONData;
{$ELSE}
function JSONValue: TJSONValue;
{$ENDIF}
end;
implementation
end.
|
(* Output:
me 100.0
Max value is :
*)
program Test20;
(* Function *)
function high(num1, num2: real): real;
var
num1, num2, num: real;
begin
num1 := 9;
num2 := 2;
writeln('a ', a);
writeln('b ', b);
end;
(* Global *)
var
a, b, c : real;
begin
a := 100;
b := 200;
c := 20;
high(a, b);
writeln('Max value is : ');
end. |
{$A-,B+,D+,E-,F+,G-,I+,L+,N+,O+,P-,Q-,R-,S+,T-,V+,X+}
{$M 16384,0,10000}
Unit U_Graph;
Interface
Uses
Graph,F_Mouse,BStack;
Procedure SaveColor;
Procedure RestoreColor;
Procedure SaveTextSettings;
Procedure RestoreTextSettings;
Procedure SetTextSettings(Settings:TextSettingsType);
Procedure Filling (x,y:integer;fill:word);
Procedure Desk (xb,yb,xe,ye,bord:integer);
Procedure DeskC(xb,yb,xe,ye,bord,color:integer);
Procedure NormalMargins (xb,yb,xe,ye,bord:integer);
Procedure InversedMargins(xb,yb,xe,ye,bord:integer);
Procedure SetGrMouseCur(FName:String;X,Y:Byte);
Implementation
Type
PByte=^Byte;
TColorStack=Object(TStack)
Procedure Push(B:Byte);
Procedure Pop(Var B:Byte);
End;{TColorStack The Object}
Var
Colors:TColorStack;
SavedTextSettings:TextSettingsType;
{===========TCOLORSTACK===============}
Procedure TColorStack.Push;
Var
PB:PByte;
Begin
New(PB);
PB^:=B;
Put(Addr(PB^));
End;{TColorStack.Push}
{----------------------------}
Procedure TColorStack.Pop;
Var
P:Pointer;
PB:PByte;
Begin
Get(P);
PB := P;
B:=PB^;
Dispose(PB);
End;{TColorStack.Pop}
{----------------------------}
Procedure SaveColor;
Begin
Colors.Push(GetColor)
End;{SaveColor}
{-----------------}
Procedure RestoreColor;
Var
SavedColor:Byte;
Begin
If Colors.Empty Then
Exit;
Colors.Pop(SavedColor);
SetColor(SavedColor);
End;{RestoreColor}
{------------------}
Procedure SetTextSettings(Settings:TextSettingsType);
Begin
With Settings Do
Begin
SetTextStyle(Font,Direction,CharSize);
SetTextJustify(Horiz,Vert);
End;{With}
End;{SetTextSettings}
{--------------------------}
Procedure SaveTextSettings;
Begin
GetTextSettings(SavedTextSettings);
End;{SaveTextSettings}
{-------------------------}
Procedure RestoreTextSettings;
Begin
SetTextSettings(SavedTextSettings);
End;{RestoreTextSettings}
{------------------------}
Procedure Filling (x,y:integer;fill:word);
Begin{Filling}
setfillstyle (1,fill);
floodfill (x,y,fill)
End;{Filling}
{------------------------------------------}
Procedure UpLeftBorder (xb,yb,xe,ye,bord:integer;Color:Word);
Begin
SetColor (Color);
Line (xb-Bord,yb-Bord,xb-Bord,ye+Bord);
Line (xb,yb,xb,ye);
line (xb,ye,xb-Bord,ye+Bord);
Line (xb-Bord,yb-Bord,xe+Bord,yb-Bord);
Line (xb,yb,xe,yb);
Line (xe+Bord,yb-Bord,xe,yb);
Filling(xb-bord Div 2,yb+(ye-yb)Div 2,Color);
End;{UpLeftBorder}
{---------------------------------------------}
Procedure DownRightBorder(xb,yb,xe,ye,bord:integer;Color:Word);
Begin
SetColor (Color);
Line (xb-Bord,ye+Bord,xe+Bord,ye+Bord);
Line (xb-Bord,ye+Bord,xb,ye);
Line (xb,ye,xe,ye);
Line (xe+Bord,yb-Bord,xe+Bord,ye+Bord);
Line (xe,ye,xe,yb);
Line (xe+Bord,yb-Bord,xe,yb);
Filling (xb-Bord+(xe-xb)Div 2,ye+bord Div 2,Color);
End;{DownRightBorder}
{----------------------------------------------}
Procedure InversedMargins;
Begin
SaveColor;
UpLeftBorder (xb,yb,xe,ye,bord,DarkGray);
DownRightBorder(xb,yb,xe,ye,bord,White);
SetColor(7);
Line(xe+Bord,ye+Bord,xe,ye);
Line(xb-Bord,yb-Bord,xb,yb);
RestoreColor;
end;{InversedMargins}
{--------------------------------------}
Procedure NormalMargins;
Begin
SaveColor;
UpLeftBorder (xb,yb,xe,ye,bord,White);
DownRightBorder(xb,yb,xe,ye,bord,DarkGray);
SetColor(7);
Line(xe+Bord,ye+Bord,xe,ye);
Line(xb-Bord,yb-Bord,xb,yb);
RestoreColor;
End;{NormalMargins}
{------------------------------------------}
Procedure DeskC;
Begin
SaveColor;
SetFillStyle(1,Color);
Bar(xb,yb,xe,ye);
RestoreColor;
NormalMargins(xb,yb,xe,ye,bord);
End;{DeskC}
{------------------------------}
Procedure Desk;
Begin
DeskC(Xb,Yb,Xe,Ye,Bord,LightGray);
End;{Desk}
{-------------------------------}
Procedure SetGrMouseCur(FName:String;X,Y:Byte);
Var
F:File Of Byte;
Ar:Array[1..64] Of Byte;
I:Byte;
Begin
Assign( |
unit unAplOrdenaGrid;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, Grids, AdvObj, BaseGrid, AdvGrid, AdvCGrid, StrUtils, Vcl.ComCtrls,
Vcl.ToolWin, AeroLabel, Vcl.ExtCtrls, AdvPanel, AdvAppStyler, AdvGlowButton,
AdvToolBar;
type
TfmAplOrdenaGrid = class(TForm)
ColumnGridOrdenacao: TAdvColumnGrid;
FormStyler: TAdvFormStyler;
DockPaneOpcoes: TAdvDockPanel;
ToolBarOpcoes: TAdvToolBar;
ButtonSelecionarTodos: TAdvGlowButton;
ButtonAplicar: TAdvGlowButton;
ButtonCancelar: TAdvGlowButton;
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure ColumnGridOrdenacaoComboChange(Sender: TObject; ACol, ARow,
AItemIndex: Integer; ASelection: string);
procedure FormCreate(Sender: TObject);
procedure ButtonSelecionarTodosClick(Sender: TObject);
procedure ButtonAplicarClick(Sender: TObject);
procedure ButtonCancelarClick(Sender: TObject);
private
{ Private declarations }
pId: TGUID;
pCampos, pCamposRetorno: string;
pSelecionarTodos, pSelecionado: boolean;
procedure setaCampos(prmCampos: string);
function obtemCampos: string;
procedure setaCamposRetorno(prmCamposRetorno: string);
procedure aplicarFiltro;
function obtemCamposRetorno: string;
public
{ Public declarations }
function buscaId: cardinal;
procedure carregaImagensBotoes;
property Campos: string read obtemCampos write setaCampos;
property CamposRetorno: string read obtemCamposRetorno write setaCamposRetorno;
end;
var
fmAplOrdenaGrid: TfmAplOrdenaGrid;
implementation
{$R *.dfm}
uses unPrincipal, undmEstilo;
procedure TfmAplOrdenaGrid.aplicarFiltro;
var
i: integer;
vRetorno: string;
vFlag: char;
begin
vRetorno := EmptyStr;
vFlag := 'N';
with ColumnGridOrdenacao do
for i:= 1 to RowCount-1 do
begin
if IsChecked(0,i) = true then
begin
vRetorno := vRetorno + '|"' + ColumnByName['Campo'].Rows[i] + '":"S":"' + ColumnByName['Ordem'].Rows[i] + '"|;';
vFlag := 'S';
end
else
vRetorno := vRetorno + '|"' + ColumnByName['Campo'].Rows[i] + '":"N":"' + ColumnByName['Ordem'].Rows[i] + '"|;'
end;
if vFlag = 'N' then
begin
MessageBox(fmPrincipal.Handle,
PWideChar('Nenhum Campo foi selecionado, a ordenação não poderá ser aplicada.'#13#10+
'A ordenação anterior será mantida para a listagem dos dados.'),
cTituloMensagemInformacao,
MB_OK or MB_ICONINFORMATION);
CamposRetorno := Campos;
end
else
begin
pSelecionado := true;
CamposRetorno := Copy(vRetorno,1,Length(vRetorno)-1);
end;
end;
function TfmAplOrdenaGrid.buscaId: cardinal;
begin
Result := pId.D1;
end;
procedure TfmAplOrdenaGrid.ButtonAplicarClick(Sender: TObject);
begin
aplicarFiltro;
Close;
end;
procedure TfmAplOrdenaGrid.ButtonCancelarClick(Sender: TObject);
begin
setaCampos(Campos);
CamposRetorno := Campos;
Close;
end;
procedure TfmAplOrdenaGrid.ButtonSelecionarTodosClick(Sender: TObject);
begin
if pSelecionarTodos = true then
ColumnGridOrdenacao.CheckAll(0)
else
ColumnGridOrdenacao.UnCheckAll(0);
pSelecionarTodos := not pSelecionarTodos;
end;
procedure TfmAplOrdenaGrid.carregaImagensBotoes;
begin
ButtonSelecionarTodos.Picture.LoadFromFile(fmPrincipal.LocalIcones + 'view-details-e-16.png');
ButtonSelecionarTodos.HotPicture.LoadFromFile(fmPrincipal.LocalIcones + 'view-details-h-16.png');
ButtonSelecionarTodos.DisabledPicture.LoadFromFile(fmPrincipal.LocalIcones + 'view-details-d-16.png');
ButtonAplicar.Picture.LoadFromFile(fmPrincipal.LocalIcones + 'ok-e-16.png');
ButtonAplicar.HotPicture.LoadFromFile(fmPrincipal.LocalIcones + 'ok-h-16.png');
ButtonAplicar.DisabledPicture.LoadFromFile(fmPrincipal.LocalIcones + 'ok-d-16.png');
ButtonCancelar.Picture.LoadFromFile(fmPrincipal.LocalIcones + 'cancel-e-16.png');
ButtonCancelar.HotPicture.LoadFromFile(fmPrincipal.LocalIcones + 'cancel-h-16.png');
ButtonCancelar.DisabledPicture.LoadFromFile(fmPrincipal.LocalIcones + 'cancel-d-16.png');
end;
procedure TfmAplOrdenaGrid.ColumnGridOrdenacaoComboChange(Sender: TObject; ACol,
ARow, AItemIndex: Integer; ASelection: string);
begin
ColumnGridOrdenacao.ColumnByName['Ordem'].Rows[ARow] := ASelection;
end;
procedure TfmAplOrdenaGrid.FormClose(Sender: TObject; var Action: TCloseAction);
begin
// Se somente saiu, sem aplicar alterações, retorna com o padrão anterior.
if not pSelecionado then
CamposRetorno := Campos;
Action := caFree;
end;
procedure TfmAplOrdenaGrid.FormCreate(Sender: TObject);
var
i: integer;
begin
try
CreateGUID(pId);
Color := Self.Color;
FormStyler.AutoThemeAdapt := false;
// Configura a Grid.
with ColumnGridOrdenacao do
begin
DrawingStyle := gdsThemed;
AutoThemeAdapt := false;
for i := 0 to ColCount -1 do
Columns[i].ShowBands := true;
Bands.Active := true;
end;
carregaImagensBotoes;
pSelecionarTodos := true;
CamposRetorno := Campos;
except
on E: Exception do
begin
fmPrincipal.manipulaExcecoes(Sender,E);
Close;
end;
end;
end;
function TfmAplOrdenaGrid.obtemCampos: string;
begin
Result := pCampos;
end;
function TfmAplOrdenaGrid.obtemCamposRetorno: string;
begin
Result := pCamposRetorno;
end;
procedure TfmAplOrdenaGrid.setaCampos(prmCampos: string);
var
i: integer;
vAux, vAux2: TStringList;
begin
pCampos := prmCampos;
// Passa para a Grid.
vAux := TStringList.Create;
vAux2 := TStringList.Create;
try
with ColumnGridOrdenacao do
begin
BeginUpdate;
ClearRows(1,RowCount-1);
vAux.Delimiter := ';';
vAux.QuoteChar := '|';
vAux2.Delimiter := ':';
vAux2.QuoteChar := '"';
vAux.DelimitedText := pCampos;
RowCount := vAux.Count+1;
// Preenche a Grid.
for i := 0 to vAux.Count-1 do
begin
vAux2.Clear;
vAux2.DelimitedText := vAux[i];
if vAux2[1] = 'S' then
AddCheckBox(0,i+1,true,false)
else
AddCheckBox(0,i+1,false,false);
ColumnByName['Campo'].Rows[i+1] := vAux2[0];
ColumnByName['Ordem'].Rows[i+1] := vAux2[2];
end;
EndUpdate;
end;
finally
FreeAndNil(vAux);
FreeAndNil(vAux2);
end;
end;
procedure TfmAplOrdenaGrid.setaCamposRetorno(prmCamposRetorno: string);
begin
pCamposRetorno := prmCamposRetorno;
end;
end.
|
unit DatabaseAuthentificationFormViewModelPropertiesINIFile;
interface
uses
DatabaseAuthentificationFormViewModel,
SystemAuthentificationFormViewModelPropertiesINIFile,
SystemAuthentificationFormViewModel,
SysUtils,
Classes;
const
DATABASE_NAMES_SECTION = 'DatabaseNamesSection';
CURRENT_DATABASE_NAME_PROPERTY_NAME = 'CurrentDatabaseName';
USED_DATABASE_NAMES_PROPERTY_NAME = 'UsedDatabaseNames';
type
TDatabaseAuthentificationFormViewModelPropertiesINIFile =
class (TSystemAuthentificationFormViewModelPropertiesINIFile)
protected
function GetValidSystemAuthentificationFormViewModelClass:
TSystemAuthentificationFormViewModelClass; override;
protected
procedure SaveSystemAuthentificationFormViewModelProperties(
ViewModel: TSystemAuthentificationFormViewModel
); override;
procedure RestoreSystemAuthentificationFormViewModelProperties(
ViewModel: TSystemAuthentificationFormViewModel
); override;
end;
implementation
{ TDatabaseAuthentificationFormViewModelPropertiesINIFile }
function TDatabaseAuthentificationFormViewModelPropertiesINIFile.
GetValidSystemAuthentificationFormViewModelClass:
TSystemAuthentificationFormViewModelClass;
begin
Result := TDatabaseAuthentificationFormViewModel;
end;
procedure TDatabaseAuthentificationFormViewModelPropertiesINIFile.
RestoreSystemAuthentificationFormViewModelProperties(
ViewModel: TSystemAuthentificationFormViewModel
);
var UsedDatabaseNames: TStrings;
begin
inherited;
FPropertiesINIFile.GoToSection(DATABASE_NAMES_SECTION);
with ViewModel as TDatabaseAuthentificationFormViewModel do begin
CurrentDatabaseName :=
FPropertiesINIFile.ReadValueForProperty(
CURRENT_DATABASE_NAME_PROPERTY_NAME, varString, ''
);
UsedDatabaseNames := TStringList.Create;
try
UsedDatabaseNames.CommaText :=
FPropertiesINIFile.ReadValueForProperty(
USED_DATABASE_NAMES_PROPERTY_NAME, varString, ''
);
DatabaseNames := UsedDatabaseNames;
except
on e: Exception do begin
FreeAndNil(UsedDatabaseNames);
raise;
end;
end;
end;
end;
procedure TDatabaseAuthentificationFormViewModelPropertiesINIFile.
SaveSystemAuthentificationFormViewModelProperties(
ViewModel: TSystemAuthentificationFormViewModel
);
begin
inherited;
FPropertiesINIFile.GoToSection(DATABASE_NAMES_SECTION);
with ViewModel as TDatabaseAuthentificationFormViewModel do begin
FPropertiesINIFile.WriteValueForProperty(
CURRENT_DATABASE_NAME_PROPERTY_NAME, CurrentDatabaseName
);
if DatabaseNames.Count = 0 then begin
FPropertiesINIFile.WriteValueForProperty(
USED_DATABASE_NAMES_PROPERTY_NAME, CurrentDatabaseName
);
end
else begin
FPropertiesINIFile.WriteValueForProperty(
USED_DATABASE_NAMES_PROPERTY_NAME, DatabaseNames.CommaText
);
end;
end;
end;
end.
|
unit AqDrop.DB.SQL;
interface
uses
System.Rtti,
AqDrop.Core.Collections.Intf,
AqDrop.Core.Collections,
AqDrop.Core.InterfacedObject,
AqDrop.DB.SQL.Intf;
type
TAqDBSQLAliasable = class;
TAqDBSQLColumn = class;
TAqDBSQLSubselect = class;
TAqDBSQLSource = class;
TAqDBSQLTable = class;
TAqDBSQLSelect = class;
TAqDBSQLAbstraction = class(TAqInterfacedObject)
strict protected
class function MustCountReferences: Boolean; override;
end;
TAqDBSQLAliasable = class(TAqDBSQLAbstraction, IAqDBSQLAliasable)
strict private
FAlias: string;
function GetAlias: string;
function GetIsAliasDefined: Boolean;
public
constructor Create(const pAlias: string = '');
end;
TAqDBSQLValue = class(TAqDBSQLAliasable, IAqDBSQLValue)
strict private
FAggregator: TAqDBSQLAggregatorType;
function GetAggregator: TAqDBSQLAggregatorType;
strict protected
function GetValueType: TAqDBSQLValueType; virtual; abstract;
function GetAsColumn: IAqDBSQLColumn; virtual;
function GetAsOperation: IAqDBSQLOperation; virtual;
function GetAsSubselect: IAqDBSQLSubselect; virtual;
function GetAsConstant: IAqDBSQLConstant; virtual;
function GetAsParameter: IAqDBSQLParameter; virtual;
public
constructor Create(const pAlias: string = ''; const pAggregator: TAqDBSQLAggregatorType = atNone);
end;
TAqDBSQLColumn = class(TAqDBSQLValue, IAqDBSQLColumn)
strict private
FExpression: string;
FSource: IAqDBSQLSource;
function GetExpression: string;
function GetSource: IAqDBSQLSource;
function GetIsSourceDefined: Boolean;
strict protected
function GetValueType: TAqDBSQLValueType; override;
function GetAsColumn: IAqDBSQLColumn; override;
public
constructor Create(const pExpression: string; pSource: IAqDBSQLSource = nil;
const pAlias: string = ''; const pAggregator: TAqDBSQLAggregatorType = atNone);
end;
TAqDBSQLOperation = class(TAqDBSQLValue, IAqDBSQLOperation)
strict private
FLeftOperand: IAqDBSQLValue;
FOperator: TAqDBSQLOperator;
FRightOperand: IAqDBSQLValue;
function GetOperator: TAqDBSQLOperator;
function GetRightOperand: IAqDBSQLValue;
function GetLeftOperand: IAqDBSQLValue;
strict protected
function GetValueType: TAqDBSQLValueType; override;
function GetAsOperation: IAqDBSQLOperation; override;
public
constructor Create(pLeftOperand: IAqDBSQLValue; const pOperator: TAqDBSQLOperator;
pRightOperand: IAqDBSQLValue; const pAlias: string = '';
const pAggregator: TAqDBSQLAggregatorType = atNone);
end;
TAqDBSQLSubselect = class(TAqDBSQLValue, IAqDBSQLSubselect)
strict private
FSelect: IAqDBSQLSelect;
function GetSelect: IAqDBSQLSelect;
strict protected
function GetValueType: TAqDBSQLValueType; override;
function GetAsSubselect: IAqDBSQLSubselect; override;
public
constructor Create(pSelect: IAqDBSQLSelect; const pAlias: string = '';
const pAggregator: TAqDBSQLAggregatorType = atNone);
end;
TAqDBSQLConstant = class abstract(TAqDBSQLValue, IAqDBSQLConstant)
strict protected
function GetValueType: TAqDBSQLValueType; override;
function GetAsConstant: IAqDBSQLConstant; override;
function GetConstantType: TAqDBSQLConstantValueType; virtual; abstract;
function GetAsTextConstant: IAqDBSQLTextConstant; virtual;
function GetAsIntConstant: IAqDBSQLIntConstant; virtual;
function GetAsUIntConstant: IAqDBSQLUIntConstant; virtual;
function GetAsDoubleConstant: IAqDBSQLDoubleConstant; virtual;
function GetAsCurrencyConstant: IAqDBSQLCurrencyConstant; virtual;
function GetAsDateTimeConstant: IAqDBSQLDateTimeConstant; virtual;
function GetAsDateConstant: IAqDBSQLDateConstant; virtual;
function GetAsTimeConstant: IAqDBSQLTimeConstant; virtual;
function GetAsBooleanConstant: IAqDBSQLBooleanConstant; virtual;
end;
TAqDBSQLGenericConstant<T> = class(TAqDBSQLConstant)
strict private
FValue: T;
public
constructor Create(const pValue: T; const pAlias: string = '';
const pAggregator: TAqDBSQLAggregatorType = atNone);
function GetValue: T;
end;
TAqDBSQLTextConstant = class(TAqDBSQLGenericConstant<string>, IAqDBSQLTextConstant)
strict protected
function GetConstantType: TAqDBSQLConstantValueType; override;
function GetAsTextConstant: IAqDBSQLTextConstant; override;
end;
TAqDBSQLIntConstant = class(TAqDBSQLGenericConstant<Int64>, IAqDBSQLIntConstant)
strict protected
function GetConstantType: TAqDBSQLConstantValueType; override;
function GetAsIntConstant: IAqDBSQLIntConstant; override;
end;
TAqDBSQLUIntConstant = class(TAqDBSQLGenericConstant<UInt64>, IAqDBSQLUIntConstant)
strict protected
function GetConstantType: TAqDBSQLConstantValueType; override;
function GetAsUIntConstant: IAqDBSQLUIntConstant; override;
end;
TAqDBSQLDoubleConstant = class(TAqDBSQLGenericConstant<Double>, IAqDBSQLDoubleConstant)
strict protected
function GetConstantType: TAqDBSQLConstantValueType; override;
function GetAsDoubleConstant: IAqDBSQLDoubleConstant; override;
end;
TAqDBSQLCurrencyConstant = class(TAqDBSQLGenericConstant<Currency>, IAqDBSQLCurrencyConstant)
strict protected
function GetConstantType: TAqDBSQLConstantValueType; override;
function GetAsCurrencyConstant: IAqDBSQLCurrencyConstant; override;
end;
TAqDBSQLDateTimeConstant = class(TAqDBSQLGenericConstant<TDateTime>, IAqDBSQLDateTimeConstant)
strict protected
function GetConstantType: TAqDBSQLConstantValueType; override;
function GetAsDateTimeConstant: IAqDBSQLDateTimeConstant; override;
end;
TAqDBSQLDateConstant = class(TAqDBSQLGenericConstant<TDate>, IAqDBSQLDateConstant)
strict protected
function GetConstantType: TAqDBSQLConstantValueType; override;
function GetAsDateConstant: IAqDBSQLDateConstant; override;
end;
TAqDBSQLTimeConstant = class(TAqDBSQLGenericConstant<TTime>, IAqDBSQLTimeConstant)
strict protected
function GetConstantType: TAqDBSQLConstantValueType; override;
function GetAsTimeConstant: IAqDBSQLTimeConstant; override;
end;
TAqDBSQLBooleanConstant = class(TAqDBSQLGenericConstant<Boolean>, IAqDBSQLBooleanConstant)
strict protected
function GetConstantType: TAqDBSQLConstantValueType; override;
function GetAsBooleanConstant: IAqDBSQLBooleanConstant; override;
end;
TAqDBSQLParameter = class(TAqDBSQLValue, IAqDBSQLParameter)
strict private
FName: string;
function GetName: string;
strict protected
function GetValueType: TAqDBSQLValueType; override;
function GetAsParameter: IAqDBSQLParameter; override;
public
constructor Create(const pName: string; const pAlias: string = '';
const pAggregator: TAqDBSQLAggregatorType = atNone);
end;
TAqDBSQLSource = class(TAqDBSQLAliasable, IAqDBSQLSource)
strict protected
function GetSourceType: TAqDBSQLSourceType; virtual; abstract;
function GetAsTable: IAqDBSQLTable; virtual;
function GetAsSelect: IAqDBSQLSelect; virtual;
end;
TAqDBSQLTable = class(TAqDBSQLSource, IAqDBSQLTable, IAqDBSQLSource)
strict private
FName: string;
function GetName: string;
strict protected
function GetSourceType: TAqDBSQLSourceType; override;
function GetAsTable: IAqDBSQLTable; override;
public
constructor Create(const pName: string; const pAlias: string = '');
end;
TAqDBSQLCondition = class(TAqDBSQLAbstraction, IAqDBSQLCondition)
strict protected
function GetConditionType: TAqDBSQLConditionType; virtual; abstract;
function GetAsComparison: IAqDBSQLComparisonCondition; virtual;
function GetAsValueIsNull: IAqDBSQLValueIsNullCondition; virtual;
function GetAsComposed: IAqDBSQLComposedCondition; virtual;
function GetAsBetween: IAqDBSQLBetweenCondition; virtual;
end;
TAqDBSQLComparisonCondition = class(TAqDBSQLCondition, IAqDBSQLComparisonCondition)
strict private
FLeftValue: IAqDBSQLValue;
FComparison: TAqDBSQLComparison;
FRightValue: IAqDBSQLValue;
function GetLeftValue: IAqDBSQLValue;
function GetComparison: TAqDBSQLComparison;
function GetRightValue: IAqDBSQLValue;
procedure SetLeftValue(pValue: IAqDBSQLValue);
procedure SetRightValue(pValue: IAqDBSQLValue);
procedure SetComparison(const pComparison: TAqDBSQLComparison);
strict protected
function GetConditionType: TAqDBSQLConditionType; override;
function GetAsComparison: IAqDBSQLComparisonCondition; override;
public
constructor Create(pLeftValue: IAqDBSQLValue; const pComparison: TAqDBSQLComparison;
pRightValue: IAqDBSQLValue);
end;
TAqDBSQLValueIsNullCondition = class(TAqDBSQLCondition, IAqDBSQLValueIsNullCondition)
strict private
FValue: IAqDBSQLValue;
function GetValue: IAqDBSQLValue;
strict protected
function GetConditionType: TAqDBSQLConditionType; override;
function GetAsValueIsNull: IAqDBSQLValueIsNullCondition; override;
public
constructor Create(pValue: IAqDBSQLValue);
end;
TAqDBSQLComposedCondition = class(TAqDBSQLCondition, IAqDBSQLComposedCondition)
strict private
FConditions: TAqList<IAqDBSQLCondition>;
FOperators: TAqList<TAqDBSQLBooleanOperator>;
function GetConditions: AqDrop.Core.Collections.Intf.IAqReadList<AqDrop.DB.SQL.Intf.IAqDBSQLCondition>;
function GetLinkOperators: AqDrop.Core.Collections.Intf.IAqReadList<AqDrop.DB.SQL.Intf.TAqDBSQLBooleanOperator>;
strict protected
function GetConditionType: TAqDBSQLConditionType; override;
function GetAsComposed: IAqDBSQLComposedCondition; override;
public
constructor Create(pInitialCondition: IAqDBSQLCondition = nil);
destructor Destroy; override;
function GetIsInitialized: Boolean;
function AddCondition(const pLinkOperator: TAqDBSQLBooleanOperator; pCondition: IAqDBSQLCondition): Int32;
function AddAnd(pCondition: IAqDBSQLCondition): IAqDBSQLComposedCondition;
function AddOr(pCondition: IAqDBSQLCondition): IAqDBSQLComposedCondition;
function AddXor(pCondition: IAqDBSQLCondition): IAqDBSQLComposedCondition;
function AddColumnEqual(pColumn: IAqDBSQLColumn; pValue: IAqDBSQLValue;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnEqual(const pColumnName: string; pValue: IAqDBSQLValue;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnEqual(pColumn: IAqDBSQLColumn; pValue: string;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnEqual(const pColumnName: string; pValue: string;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnEqual(pColumn: IAqDBSQLColumn; pValue: Int64;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnEqual(const pColumnName: string; pValue: Int64;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnEqual(pColumn: IAqDBSQLColumn; pValue: UInt64;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnEqual(const pColumnName: string; pValue: UInt64;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnEqual(pColumn: IAqDBSQLColumn; pValue: Double;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnEqual(const pColumnName: string; pValue: Double;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnEqual(pColumn: IAqDBSQLColumn; pValue: Currency;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnEqual(const pColumnName: string; pValue: Currency;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnEqual(pColumn: IAqDBSQLColumn; pValue: TDateTime;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnEqual(const pColumnName: string; pValue: TDateTime;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnEqual(pColumn: IAqDBSQLColumn; pValue: TDate;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnEqual(const pColumnName: string; pValue: TDate;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnEqual(pColumn: IAqDBSQLColumn; pValue: TTime;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnEqual(const pColumnName: string; pValue: TTime;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnEqual(pColumn: IAqDBSQLColumn; pValue: Boolean;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnEqual(const pColumnName: string; pValue: Boolean;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnGreaterThan(pColumn: IAqDBSQLColumn; pValue: IAqDBSQLValue;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnGreaterThan(const pColumnName: string; pValue: IAqDBSQLValue;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnGreaterThan(pColumn: IAqDBSQLColumn; pValue: string;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnGreaterThan(const pColumnName: string; pValue: string;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnGreaterThan(pColumn: IAqDBSQLColumn; pValue: Int64;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnGreaterThan(const pColumnName: string; pValue: Int64;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnGreaterThan(pColumn: IAqDBSQLColumn; pValue: Double;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnGreaterThan(const pColumnName: string; pValue: Double;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnGreaterThan(pColumn: IAqDBSQLColumn; pValue: Currency;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnGreaterThan(const pColumnName: string; pValue: Currency;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnGreaterThan(pColumn: IAqDBSQLColumn; pValue: TDateTime;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnGreaterThan(const pColumnName: string; pValue: TDateTime;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnGreaterThan(pColumn: IAqDBSQLColumn; pValue: TDate;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnGreaterThan(const pColumnName: string; pValue: TDate;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnGreaterThan(pColumn: IAqDBSQLColumn; pValue: TTime;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnGreaterThan(const pColumnName: string; pValue: TTime;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnGreaterEqualThan(pColumn: IAqDBSQLColumn; pValue: IAqDBSQLValue;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnGreaterEqualThan(const pColumnName: string; pValue: IAqDBSQLValue;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnGreaterEqualThan(pColumn: IAqDBSQLColumn; pValue: string;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnGreaterEqualThan(const pColumnName: string; pValue: string;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnGreaterEqualThan(pColumn: IAqDBSQLColumn; pValue: Int64;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnGreaterEqualThan(const pColumnName: string; pValue: Int64;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnGreaterEqualThan(pColumn: IAqDBSQLColumn; pValue: Double;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnGreaterEqualThan(const pColumnName: string; pValue: Double;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnGreaterEqualThan(pColumn: IAqDBSQLColumn; pValue: Currency;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnGreaterEqualThan(const pColumnName: string; pValue: Currency;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnGreaterEqualThan(pColumn: IAqDBSQLColumn; pValue: TDateTime;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnGreaterEqualThan(const pColumnName: string; pValue: TDateTime;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnGreaterEqualThan(pColumn: IAqDBSQLColumn; pValue: TDate;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnGreaterEqualThan(const pColumnName: string; pValue: TDate;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnGreaterEqualThan(pColumn: IAqDBSQLColumn; pValue: TTime;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnGreaterEqualThan(const pColumnName: string; pValue: TTime;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnLessThan(pColumn: IAqDBSQLColumn; pValue: IAqDBSQLValue;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnLessThan(const pColumnName: string; pValue: IAqDBSQLValue;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnLessThan(pColumn: IAqDBSQLColumn; pValue: string;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnLessThan(const pColumnName: string; pValue: string;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnLessThan(pColumn: IAqDBSQLColumn; pValue: Int64;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnLessThan(const pColumnName: string; pValue: Int64;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnLessThan(pColumn: IAqDBSQLColumn; pValue: Double;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnLessThan(const pColumnName: string; pValue: Double;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnLessThan(pColumn: IAqDBSQLColumn; pValue: Currency;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnLessThan(const pColumnName: string; pValue: Currency;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnLessThan(pColumn: IAqDBSQLColumn; pValue: TDateTime;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnLessThan(const pColumnName: string; pValue: TDateTime;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnLessThan(pColumn: IAqDBSQLColumn; pValue: TDate;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnLessThan(const pColumnName: string; pValue: TDate;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnLessThan(pColumn: IAqDBSQLColumn; pValue: TTime;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnLessThan(const pColumnName: string; pValue: TTime;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnLessEqualThan(pColumn: IAqDBSQLColumn; pValue: IAqDBSQLValue;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnLessEqualThan(const pColumnName: string; pValue: IAqDBSQLValue;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnLessEqualThan(pColumn: IAqDBSQLColumn; pValue: string;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnLessEqualThan(const pColumnName: string; pValue: string;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnLessEqualThan(pColumn: IAqDBSQLColumn; pValue: Int64;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnLessEqualThan(const pColumnName: string; pValue: Int64;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnLessEqualThan(pColumn: IAqDBSQLColumn; pValue: Double;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnLessEqualThan(const pColumnName: string; pValue: Double;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnLessEqualThan(pColumn: IAqDBSQLColumn; pValue: Currency;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnLessEqualThan(const pColumnName: string; pValue: Currency;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnLessEqualThan(pColumn: IAqDBSQLColumn; pValue: TDateTime;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnLessEqualThan(const pColumnName: string; pValue: TDateTime;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnLessEqualThan(pColumn: IAqDBSQLColumn; pValue: TDate;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnLessEqualThan(const pColumnName: string; pValue: TDate;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnLessEqualThan(pColumn: IAqDBSQLColumn; pValue: TTime;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnLessEqualThan(const pColumnName: string; pValue: TTime;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnIsNull(pColumn: IAqDBSQLColumn;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnIsNull(const pColumnName: string;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnBetween(pColumn: IAqDBSQLColumn; const pRangeBegin, pRangeEnd: IAqDBSQLValue;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnBetween(const pColumnName: string; const pRangeBegin, pRangeEnd: IAqDBSQLValue;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnBetween(pColumn: IAqDBSQLColumn; const pRangeBegin, pRangeEnd: string;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnBetween(const pColumnName: string; const pRangeBegin, pRangeEnd: string;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnBetween(pColumn: IAqDBSQLColumn; const pRangeBegin, pRangeEnd: Int64;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnBetween(const pColumnName: string; const pRangeBegin, pRangeEnd: Int64;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnBetween(pColumn: IAqDBSQLColumn; const pRangeBegin, pRangeEnd: Double;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnBetween(const pColumnName: string; const pRangeBegin, pRangeEnd: Double;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnBetween(pColumn: IAqDBSQLColumn; const pRangeBegin, pRangeEnd: Currency;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnBetween(const pColumnName: string; const pRangeBegin, pRangeEnd: Currency;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnBetween(pColumn: IAqDBSQLColumn; const pRangeBegin, pRangeEnd: TDateTime;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnBetween(const pColumnName: string; const pRangeBegin, pRangeEnd: TDateTime;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnBetween(pColumn: IAqDBSQLColumn; const pRangeBegin, pRangeEnd: TDate;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnBetween(const pColumnName: string; const pRangeBegin, pRangeEnd: TDate;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnBetween(pColumn: IAqDBSQLColumn; const pRangeBegin, pRangeEnd: TTime;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
function AddColumnBetween(const pColumnName: string; const pRangeBegin, pRangeEnd: TTime;
const pLinkOperator: TAqDBSQLBooleanOperator = TAqDBSQLBooleanOperator.boAnd):
IAqDBSQLComposedCondition; overload;
end;
TAqDBSQLBetweenCondition = class(TAqDBSQLCondition, IAqDBSQLBetweenCondition)
strict private
FValue: IAqDBSQLValue;
FRangeBegin: IAqDBSQLValue;
FRangeEnd: IAqDBSQLValue;
function GetValue: IAqDBSQLValue;
function GetRangeBegin: IAqDBSQLValue;
function GetRangeEnd: IAqDBSQLValue;
strict protected
function GetAsBetween: IAqDBSQLBetweenCondition; override;
function GetConditionType: TAqDBSQLConditionType; override;
public
constructor Create(pValue, pRangeBegin, pRangeEnd: IAqDBSQLValue);
end;
TAqDBSQLJoin = class(TAqDBSQLAliasable, IAqDBSQLJoin)
strict private
FType: TAqDBSQLJoinType;
FMainSource: IAqDBSQLSource;
FJoinSource: IAqDBSQLSource;
FCondition: IAqDBSQLCondition;
function GetSource: IAqDBSQLSource;
function GetCondition: IAqDBSQLCondition;
function GetJoinType: TAqDBSQLJoinType;
public
constructor Create(const pType: TAqDBSQLJoinType; pMainSource: IAqDBSQLSource; pJoinSource: IAqDBSQLSource;
pCondition: IAqDBSQLCondition); overload;
function &On(const pColumnName: string): IAqDBSQLJoin;
function EqualsTo(const pColumnName: string): IAqDBSQLJoin;
end;
TAqDBSQLOrderByItem = class(TAqDBSQLAbstraction, IAqDBSQLOrderByItem)
strict private
FValue: IAqDBSQLValue;
FDesc: Boolean;
function GetValue: IAqDBSQLValue;
function GetDesc: Boolean;
public
constructor Create(pValue: IAqDBSQLValue; const pDesc: Boolean);
property Value: IAqDBSQLValue read GetValue;
property Desc: Boolean read GetDesc;
end;
TAqDBSQLSelect = class(TAqDBSQLSource, IAqDBSQLSource, IAqDBSQLSelect, IAqDBSQLCommand)
strict private
FColumns: TAqList<IAqDBSQLValue>;
FSource: IAqDBSQLSource;
FJoins: TAqList<IAqDBSQLJoin>;
FLimit: UInt32;
FCondition: IAqDBSQLCondition;
FOrderBy: TAqList<IAqDBSQLOrderByItem>;
constructor InternalCreate(const pAlias: string);
function GetColumns: IAqReadList<IAqDBSQLValue>;
function GetSource: IAqDBSQLSource;
function GetHasJoins: Boolean;
function GetJoins: IAqReadList<IAqDBSQLJoin>;
function GetIsConditionDefined: Boolean;
function GetCondition: IAqDBSQLCondition;
procedure SetCondition(pValue: IAqDBSQLCondition);
function CustomizeCondition(pNewCondition: IAqDBSQLCondition = nil): IAqDBSQLComposedCondition;
function GetIsLimitDefined: Boolean;
function GetLimit: UInt32;
procedure SetLimit(const pValue: UInt32);
function GetIsOrderByDefined: Boolean;
function GetOrderBy: IAqReadList<IAqDBSQLOrderbyItem>;
function GetAsDelete: IAqDBSQLDelete;
function GetAsInsert: IAqDBSQLInsert;
function GetAsUpdate: IAqDBSQLUpdate;
strict protected
function GetCommandType: TAqDBSQLCommandType;
function GetSourceType: TAqDBSQLSourceType; override;
function GetAsSelect: IAqDBSQLSelect; override;
public
constructor Create(const pSource: TAqDBSQLSource; const pAlias: string = ''); overload;
constructor Create(const pSourceTable: string; const pAlias: string = ''); overload;
destructor Destroy; override;
function GetColumnByExpression(const pExpression: string): IAqDBSQLColumn;
function AddColumn(pValue: IAqDBSQLValue): Int32; overload;
function AddColumn(const pExpression: string; const pAlias: string = ''; pSource: IAqDBSQLSource = nil;
const pAggregator: TAqDBSQLAggregatorType = atNone): IAqDBSQLColumn; overload;
function AddJoin(const pType: TAqDBSQLJoinType; pSource: IAqDBSQLSource;
pCondition: IAqDBSQLCondition): IAqDBSQLJoin;
function InnerJoin(const pTableName: string): IAqDBSQLJoin;
function AddOrderBy(pValue: IAqDBSQLValue; const pDesc: Boolean): Int32;
procedure UnsetLimit;
end;
TAqDBSQLCommand = class(TAqDBSQLAbstraction, IAqDBSQLCommand)
strict protected
function GetCommandType: TAqDBSQLCommandType; virtual; abstract;
function GetAsDelete: IAqDBSQLDelete; virtual;
function GetAsInsert: IAqDBSQLInsert; virtual;
function GetAsSelect: IAqDBSQLSelect; virtual;
function GetAsUpdate: IAqDBSQLUpdate; virtual;
end;
TAqDBSQLAssignment = class(TAqDBSQLAbstraction, IAqDBSQLAssignment)
strict private
FColumn: IAqDBSQLColumn;
FValue: IAqDBSQLValue;
function GetColumn: IAqDBSQLColumn;
function GetValue: IAqDBSQLValue;
public
constructor Create(pColumn: IAqDBSQLColumn; pValue: IAqDBSQLValue);
end;
TAqDBSQLInsert = class(TAqDBSQLCommand, IAqDBSQLInsert)
strict private
FTable: IAqDBSQLTable;
FAssignments: TAqList<IAqDBSQLAssignment>;
function GetAssignments: IAqReadList<IAqDBSQLAssignment>;
function GetTable: IAqDBSQLTable;
strict protected
function GetCommandType: TAqDBSQLCommandType; override;
function GetAsInsert: IAqDBSQLInsert; override;
public
constructor Create(pTable: IAqDBSQLTable); overload;
constructor Create(const pTableName: string); overload;
destructor Destroy; override;
function AddAssignment(pAssignment: IAqDBSQLAssignment): Int32; overload;
function AddAssignment(pColumn: IAqDBSQLColumn; pValue: IAqDBSQLValue): IAqDBSQLAssignment; overload;
end;
TAqDBSQLUpdate = class(TAqDBSQLCommand, IAqDBSQLUpdate)
strict private
FTable: IAqDBSQLTable;
FAssignments: TAqList<IAqDBSQLAssignment>;
FCondition: IAqDBSQLCondition;
function GetAssignments: IAqReadList<IAqDBSQLAssignment>;
function GetTable: IAqDBSQLTable;
function GetIsConditionDefined: Boolean;
function GetCondition: IAqDBSQLCondition;
procedure SetCondition(pValue: IAqDBSQLCondition);
function CustomizeCondition(pNewCondition: IAqDBSQLCondition = nil): IAqDBSQLComposedCondition;
strict protected
function GetCommandType: TAqDBSQLCommandType; override;
function GetAsUpdate: IAqDBSQLUpdate; override;
public
constructor Create(pTable: IAqDBSQLTable); overload;
constructor Create(const pTableName: string); overload;
destructor Destroy; override;
function AddAssignment(pAssignment: IAqDBSQLAssignment): Int32; overload;
function AddAssignment(pColumn: IAqDBSQLColumn; pValue: IAqDBSQLValue): IAqDBSQLAssignment; overload;
end;
TAqDBSQLDelete = class(TAqDBSQLCommand, IAqDBSQLDelete)
strict private
FTable: IAqDBSQLTable;
FCondition: IAqDBSQLCondition;
function GetTable: IAqDBSQLTable;
function GetIsConditionDefined: Boolean;
function GetCondition: IAqDBSQLCondition;
procedure SetCondition(pValue: IAqDBSQLCondition);
function CustomizeCondition(pNewCondition: IAqDBSQLCondition = nil): IAqDBSQLComposedCondition;
strict protected
function GetCommandType: TAqDBSQLCommandType; override;
function GetAsDelete: IAqDBSQLDelete; override;
public
constructor Create(pTable: IAqDBSQLTable); overload;
constructor Create(const pTableName: string); overload;
end;
implementation
uses
AqDrop.Core.Exceptions;
{ TAqDBSQLColumn }
function TAqDBSQLColumn.GetAsColumn: IAqDBSQLColumn;
begin
Result := Self;
end;
constructor TAqDBSQLColumn.Create(const pExpression: string; pSource: IAqDBSQLSource;
const pAlias: string; const pAggregator: TAqDBSQLAggregatorType);
begin
inherited Create(pAlias, pAggregator);
FExpression := pExpression;
FSource := pSource;
end;
function TAqDBSQLColumn.GetExpression: string;
begin
Result := FExpression;
end;
function TAqDBSQLColumn.GetSource: IAqDBSQLSource;
begin
Result := FSource;
end;
function TAqDBSQLColumn.GetIsSourceDefined: Boolean;
begin
Result := Assigned(FSource);
end;
function TAqDBSQLColumn.GetValueType: TAqDBSQLValueType;
begin
Result := TAqDBSQLValueType.vtColumn;
end;
{ TAqDBSQLAliasable }
constructor TAqDBSQLAliasable.Create(const pAlias: string);
begin
FAlias := pAlias;
end;
{ TAqDBSQLSubselectColumn }
function TAqDBSQLSubselect.GetAsSubselect: IAqDBSQLSubselect;
begin
Result := Self;
end;
constructor TAqDBSQLSubselect.Create(pSelect: IAqDBSQLSelect; const pAlias: string;
const pAggregator: TAqDBSQLAggregatorType);
begin
inherited Create(pAlias, pAggregator);
FSelect := pSelect;
end;
function TAqDBSQLSubselect.GetSelect: IAqDBSQLSelect;
begin
Result := FSelect;
end;
function TAqDBSQLSubselect.GetValueType: TAqDBSQLValueType;
begin
Result := TAqDBSQLValueType.vtSubselect;
end;
{ TAqDBSQLTable }
function TAqDBSQLTable.GetAsTable: IAqDBSQLTable;
begin
Result := Self;
end;
constructor TAqDBSQLTable.Create(const pName, pAlias: string);
begin
inherited Create(pAlias);
FName := pName;
end;
function TAqDBSQLTable.GetName: string;
begin
Result := FName;
end;
function TAqDBSQLTable.GetSourceType: TAqDBSQLSourceType;
begin
Result := TAqDBSQLSourceType.stTable;
end;
{ TAqDBSQLSelect }
constructor TAqDBSQLSelect.Create(const pSourceTable, pAlias: string);
begin
InternalCreate(pAlias);
FSource := TAqDBSQLTable.Create(pSourceTable);
end;
function TAqDBSQLSelect.CustomizeCondition(pNewCondition: IAqDBSQLCondition = nil): IAqDBSQLComposedCondition;
begin
if GetIsConditionDefined then
begin
Result := TAqDBSQLComposedCondition.Create(FCondition);
if Assigned(pNewCondition) then
begin
Result.AddAnd(pNewCondition);
end;
end else begin
Result := TAqDBSQLComposedCondition.Create(pNewCondition);
end;
FCondition := Result;
end;
function TAqDBSQLSelect.AddColumn(const pExpression: string; const pAlias: string; pSource: IAqDBSQLSource;
const pAggregator: TAqDBSQLAggregatorType): IAqDBSQLColumn;
begin
if Assigned(pSource) then
begin
Result := TAqDBSQLColumn.Create(pExpression, pSource, pAlias, pAggregator);
end else begin
Result := TAqDBSQLColumn.Create(pExpression, Self.FSource, pAlias, pAggregator);
end;
FColumns.Add(Result);
end;
function TAqDBSQLSelect.AddColumn(pValue: IAqDBSQLValue): Int32;
begin
Result := FColumns.Add(pValue);
end;
function TAqDBSQLSelect.AddJoin(const pType: TAqDBSQLJoinType; pSource: IAqDBSQLSource;
pCondition: IAqDBSQLCondition): IAqDBSQLJoin;
begin
Result := TAqDBSQLJoin.Create(pType, Self.FSource, pSource, pCondition);
if not Assigned(FJoins) then
begin
FJoins := TAqList<IAqDBSQLJoin>.Create;
end;
FJoins.Add(Result);
end;
function TAqDBSQLSelect.AddOrderBy(pValue: IAqDBSQLValue; const pDesc: Boolean): Int32;
begin
if not Assigned(FOrderBy) then
begin
FOrderBy := TAqList<IAqDBSQLOrderByItem>.Create;
end;
Result := FOrderBy.Add(TAqDBSQLOrderByItem.Create(pValue, pDesc));
end;
function TAqDBSQLSelect.GetAsDelete: IAqDBSQLDelete;
begin
raise EAqInternal.Create('Objects of ' + Self.QualifiedClassName + ' cannot be consumed as IAqDBDelete.');
end;
function TAqDBSQLSelect.GetAsInsert: IAqDBSQLInsert;
begin
raise EAqInternal.Create('Objects of ' + Self.QualifiedClassName + ' cannot be consumed as IAqDBInsert.');
end;
function TAqDBSQLSelect.GetAsSelect: IAqDBSQLSelect;
begin
Result := Self;
end;
function TAqDBSQLSelect.GetAsUpdate: IAqDBSQLUpdate;
begin
raise EAqInternal.Create('Objects of ' + Self.QualifiedClassName + ' cannot be consumed as IAqDBSQLUpdate.');
end;
function TAqDBSQLSelect.InnerJoin(const pTableName: string): IAqDBSQLJoin;
begin
Result := AddJoin(TAqDBSQLJoinType.jtInnerJoin, TAqDBSQLTable.Create(pTableName), nil);
end;
constructor TAqDBSQLSelect.InternalCreate(const pAlias: string);
begin
inherited Create(pAlias);
FColumns := TAqList<IAqDBSQLValue>.Create;
FLimit := High(FLimit);
end;
procedure TAqDBSQLSelect.SetCondition(pValue: IAqDBSQLCondition);
begin
FCondition := pValue;
end;
procedure TAqDBSQLSelect.SetLimit(const pValue: UInt32);
begin
FLimit := pValue;
end;
procedure TAqDBSQLSelect.UnsetLimit;
begin
FLimit := High(FLimit);
end;
constructor TAqDBSQLSelect.Create(const pSource: TAqDBSQLSource; const pAlias: string);
begin
InternalCreate(pAlias);
FSource := pSource;
end;
destructor TAqDBSQLSelect.Destroy;
begin
FOrderBy.Free;
FJoins.Free;
FColumns.Free;
inherited;
end;
function TAqDBSQLSelect.GetColumnByExpression(const pExpression: string): IAqDBSQLColumn;
var
lI: Int32;
begin
lI := 0;
Result := nil;
while not Assigned(Result) and (lI < FColumns.Count) do
begin
if (FColumns[lI].ValueType = TAqDBSQLValueType.vtColumn) and
(FColumns[lI].GetAsColumn.Expression = pExpression) then
begin
Result := FColumns[lI].GetAsColumn;
end else begin
Inc(lI);
end;
end;
end;
function TAqDBSQLSelect.GetColumns: IAqReadList<IAqDBSQLValue>;
begin
Result := FColumns.GetIReadList;
end;
function TAqDBSQLSelect.GetSource: IAqDBSQLSource;
begin
Result := FSource;
end;
function TAqDBSQLSelect.GetCommandType: TAqDBSQLCommandType;
begin
Result := TAqDBSQLCommandType.ctSelect;
end;
function TAqDBSQLSelect.GetCondition: IAqDBSQLCondition;
begin
Result := FCondition;
end;
function TAqDBSQLSelect.GetHasJoins: Boolean;
begin
Result := Assigned(FJoins) and (FJoins.Count > 0);
end;
function TAqDBSQLSelect.GetIsConditionDefined: Boolean;
begin
Result := Assigned(FCondition);
end;
function TAqDBSQLSelect.GetIsLimitDefined: Boolean;
begin
Result := FLimit <> High(FLimit);
end;
function TAqDBSQLSelect.GetIsOrderByDefined: Boolean;
begin
Result := Assigned(FOrderBy) and (FOrderBy.Count > 0);
end;
function TAqDBSQLSelect.GetJoins: IAqReadList<IAqDBSQLJoin>;
begin
Result := FJoins.GetIReadList;
end;
function TAqDBSQLSelect.GetLimit: UInt32;
begin
Result := FLimit;
end;
function TAqDBSQLSelect.GetOrderBy: IAqReadList<IAqDBSQLOrderByItem>;
begin
Result := FOrderBy.GetIReadList;
end;
function TAqDBSQLSelect.GetSourceType: TAqDBSQLSourceType;
begin
Result := TAqDBSQLSourceType.stSelect;
end;
{ TAqDBSQLSource }
function TAqDBSQLSource.GetAsSelect: IAqDBSQLSelect;
begin
raise EAqInternal.Create('Objects of type ' + Self.QualifiedClassName + ' cannot be consumed as IAqDBSQLSelect.');
end;
function TAqDBSQLSource.GetAsTable: IAqDBSQLTable;
begin
raise EAqInternal.Create('Objects of type ' + Self.QualifiedClassName + ' cannot be consumed as IAqDBTable.');
end;
{ TAqDBOperationColumn }
function TAqDBSQLOperation.GetAsOperation: IAqDBSQLOperation;
begin
Result := Self;
end;
constructor TAqDBSQLOperation.Create(pLeftOperand: IAqDBSQLValue; const pOperator: TAqDBSQLOperator;
pRightOperand: IAqDBSQLValue; const pAlias: string; const pAggregator: TAqDBSQLAggregatorType);
begin
inherited Create(pAlias, pAggregator);
FLeftOperand := pLeftOperand;
FOperator := pOperator;
FRightOperand := pRightOperand;
end;
function TAqDBSQLOperation.GetOperator: TAqDBSQLOperator;
begin
Result := FOperator;
end;
function TAqDBSQLOperation.GetRightOperand: IAqDBSQLValue;
begin
Result := FRightOperand;
end;
function TAqDBSQLOperation.GetLeftOperand: IAqDBSQLValue;
begin
Result := FLeftOperand;
end;
function TAqDBSQLOperation.GetValueType: TAqDBSQLValueType;
begin
Result := TAqDBSQLValueType.vtOperation;
end;
{ TAqDBSQLValue }
function TAqDBSQLValue.GetAsColumn: IAqDBSQLColumn;
begin
raise EAqInternal.Create('Objects of type ' + Self.QualifiedClassName + ' cannot be consumed as IAqDBColumn.');
end;
function TAqDBSQLValue.GetAsConstant: IAqDBSQLConstant;
begin
raise EAqInternal.Create('Objects of type ' + Self.QualifiedClassName + ' cannot be consumed as IAqDBSQLConstant.');
end;
function TAqDBSQLValue.GetAsOperation: IAqDBSQLOperation;
begin
raise EAqInternal.Create('Objects of type ' + Self.QualifiedClassName +
' cannot be consumed as IAqDBOperationValue.');
end;
function TAqDBSQLValue.GetAsParameter: IAqDBSQLParameter;
begin
raise EAqInternal.Create('Objects of type ' + Self.QualifiedClassName + ' cannot be consumed as IAqDBSQLParameter.');
end;
function TAqDBSQLValue.GetAsSubselect: IAqDBSQLSubselect;
begin
raise EAqInternal.Create('Objects of type ' + Self.QualifiedClassName + ' cannot be consumed as IAqDBSQLSubselect.');
end;
constructor TAqDBSQLValue.Create(const pAlias: string; const pAggregator: TAqDBSQLAggregatorType);
begin
inherited Create(pAlias);
FAggregator := pAggregator;
end;
function TAqDBSQLAliasable.GetAlias: string;
begin
Result := FAlias;
end;
function TAqDBSQLAliasable.GetIsAliasDefined: Boolean;
begin
Result := FAlias <> '';
end;
function TAqDBSQLValue.GetAggregator: TAqDBSQLAggregatorType;
begin
Result := FAggregator;
end;
{ TAqDBSQLComparisonCondition }
constructor TAqDBSQLComparisonCondition.Create(pLeftValue: IAqDBSQLValue; const pComparison: TAqDBSQLComparison;
pRightValue: IAqDBSQLValue);
begin
FLeftValue := pLeftValue;
FComparison := pComparison;
FRightValue := pRightValue;
end;
function TAqDBSQLComparisonCondition.GetAsComparison: IAqDBSQLComparisonCondition;
begin
Result := Self;
end;
function TAqDBSQLComparisonCondition.GetComparison: TAqDBSQLComparison;
begin
Result := FComparison;
end;
function TAqDBSQLComparisonCondition.GetConditionType: TAqDBSQLConditionType;
begin
Result := TAqDBSQLConditionType.ctComparison;
end;
function TAqDBSQLComparisonCondition.GetLeftValue: IAqDBSQLValue;
begin
Result := FLeftValue;
end;
function TAqDBSQLComparisonCondition.GetRightValue: IAqDBSQLValue;
begin
Result := FRightValue;
end;
procedure TAqDBSQLComparisonCondition.SetComparison(const pComparison: TAqDBSQLComparison);
begin
FComparison := pComparison;
end;
procedure TAqDBSQLComparisonCondition.SetLeftValue(pValue: IAqDBSQLValue);
begin
FLeftValue := pValue;
end;
procedure TAqDBSQLComparisonCondition.SetRightValue(pValue: IAqDBSQLValue);
begin
FRightValue := pValue;
end;
{ TAqDBSQLValueIsNullCondition }
constructor TAqDBSQLValueIsNullCondition.Create(pValue: IAqDBSQLValue);
begin
FValue := pValue;
end;
function TAqDBSQLValueIsNullCondition.GetAsValueIsNull: IAqDBSQLValueIsNullCondition;
begin
Result := Self;
end;
function TAqDBSQLValueIsNullCondition.GetConditionType: TAqDBSQLConditionType;
begin
Result := TAqDBSQLConditionType.ctValueIsNull;
end;
function TAqDBSQLValueIsNullCondition.GetValue: IAqDBSQLValue;
begin
Result := FValue;
end;
{ TAqDBSQLAbstraction }
class function TAqDBSQLAbstraction.MustCountReferences: Boolean;
begin
Result := True;
end;
{ TAqDBSQLJoin }
function TAqDBSQLJoin.&On(const pColumnName: string): IAqDBSQLJoin;
begin
FCondition := TAqDBSQLComparisonCondition.Create(TAqDBSQLColumn.Create(pColumnName, FJoinSource),
TAqDBSQLComparison.cpEqual, nil);
Result := Self;
end;
constructor TAqDBSQLJoin.Create(const pType: TAqDBSQLJoinType; pMainSource: IAqDBSQLSource; pJoinSource: IAqDBSQLSource;
pCondition: IAqDBSQLCondition);
begin
inherited Create;
FMainSource := pMainSource;
FJoinSource := pJoinSource;
FCondition := pCondition;
end;
function TAqDBSQLJoin.EqualsTo(const pColumnName: string): IAqDBSQLJoin;
begin
if (FCondition.ConditionType = TAqDBSQLConditionType.ctComparison) then
begin
FCondition.GetAsComparison.RightValue := TAqDBSQLColumn.Create(pColumnName, FMainSource);
end;
Result := Self;
end;
function TAqDBSQLJoin.GetCondition: IAqDBSQLCondition;
begin
Result := FCondition;
end;
function TAqDBSQLJoin.GetJoinType: TAqDBSQLJoinType;
begin
Result := FType;
end;
function TAqDBSQLJoin.GetSource: IAqDBSQLSource;
begin
Result := FJoinSource;
end;
{ TAqDBSQLComposedCondition }
function TAqDBSQLComposedCondition.AddAnd(pCondition: IAqDBSQLCondition): IAqDBSQLComposedCondition;
begin
AddCondition(TAqDBSQLBooleanOperator.boAnd, pCondition);
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnBetween(pColumn: IAqDBSQLColumn; const pRangeBegin, pRangeEnd: TDateTime;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator, TAqDBSQLBetweenCondition.Create(pColumn,
TAqDBSQLDateTimeConstant.Create(pRangeBegin), TAqDBSQLDateTimeConstant.Create(pRangeEnd)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnBetween(const pColumnName: string; const pRangeBegin, pRangeEnd: TDateTime;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnBetween(TAqDBSQLColumn.Create(pColumnName), pRangeBegin, pRangeEnd, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnBetween(pColumn: IAqDBSQLColumn; const pRangeBegin, pRangeEnd: Currency;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator, TAqDBSQLBetweenCondition.Create(pColumn,
TAqDBSQLCurrencyConstant.Create(pRangeBegin), TAqDBSQLCurrencyConstant.Create(pRangeEnd)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnBetween(const pColumnName: string; const pRangeBegin, pRangeEnd: Currency;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnBetween(TAqDBSQLColumn.Create(pColumnName), pRangeBegin, pRangeEnd, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnBetween(pColumn: IAqDBSQLColumn; const pRangeBegin, pRangeEnd: TTime;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator, TAqDBSQLBetweenCondition.Create(pColumn,
TAqDBSQLTimeConstant.Create(pRangeBegin), TAqDBSQLTimeConstant.Create(pRangeEnd)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnBetween(const pColumnName: string; const pRangeBegin, pRangeEnd: TTime;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnBetween(TAqDBSQLColumn.Create(pColumnName), pRangeBegin, pRangeEnd, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnBetween(pColumn: IAqDBSQLColumn; const pRangeBegin, pRangeEnd: TDate;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator, TAqDBSQLBetweenCondition.Create(pColumn,
TAqDBSQLDateConstant.Create(pRangeBegin), TAqDBSQLDateConstant.Create(pRangeEnd)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnBetween(const pColumnName: string; const pRangeBegin, pRangeEnd: TDate;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnBetween(TAqDBSQLColumn.Create(pColumnName), pRangeBegin, pRangeEnd, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnBetween(pColumn: IAqDBSQLColumn; const pRangeBegin, pRangeEnd: string;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator, TAqDBSQLBetweenCondition.Create(pColumn,
TAqDBSQLTextConstant.Create(pRangeBegin), TAqDBSQLTextConstant.Create(pRangeEnd)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnBetween(const pColumnName, pRangeBegin, pRangeEnd: string;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnBetween(TAqDBSQLColumn.Create(pColumnName), pRangeBegin, pRangeEnd, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnBetween(pColumn: IAqDBSQLColumn; const pRangeBegin,
pRangeEnd: IAqDBSQLValue; const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator, TAqDBSQLBetweenCondition.Create(pColumn, pRangeBegin, pRangeEnd));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnBetween(const pColumnName: string; const pRangeBegin,
pRangeEnd: IAqDBSQLValue; const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnBetween(TAqDBSQLColumn.Create(pColumnName), pRangeBegin, pRangeEnd, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnBetween(pColumn: IAqDBSQLColumn; const pRangeBegin, pRangeEnd: Double;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator, TAqDBSQLBetweenCondition.Create(pColumn,
TAqDBSQLDoubleConstant.Create(pRangeBegin), TAqDBSQLDoubleConstant.Create(pRangeEnd)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnBetween(const pColumnName: string; const pRangeBegin, pRangeEnd: Double;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnBetween(TAqDBSQLColumn.Create(pColumnName), pRangeBegin, pRangeEnd, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnBetween(pColumn: IAqDBSQLColumn; const pRangeBegin, pRangeEnd: Int64;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator, TAqDBSQLBetweenCondition.Create(pColumn,
TAqDBSQLIntConstant.Create(pRangeBegin), TAqDBSQLIntConstant.Create(pRangeEnd)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnBetween(const pColumnName: string; const pRangeBegin, pRangeEnd: Int64;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnBetween(TAqDBSQLColumn.Create(pColumnName), pRangeBegin, pRangeEnd, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnEqual(const pColumnName: string; pValue: TDateTime;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnEqual(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnEqual(pColumn: IAqDBSQLColumn; pValue: TDate;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpEqual,
TAqDBSQLDateConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnEqual(const pColumnName: string; pValue: Currency;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnEqual(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnEqual(pColumn: IAqDBSQLColumn; pValue: TDateTime;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpEqual,
TAqDBSQLDateTimeConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnEqual(const pColumnName: string; pValue: TDate;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnEqual(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnEqual(pColumn: IAqDBSQLColumn; pValue: Boolean;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpEqual,
TAqDBSQLBooleanConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnEqual(const pColumnName: string; pValue: Boolean;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnEqual(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnEqual(pColumn: IAqDBSQLColumn; pValue: UInt64;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpEqual,
TAqDBSQLUIntConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnEqual(const pColumnName: string; pValue: UInt64;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnEqual(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnEqual(pColumn: IAqDBSQLColumn; pValue: TTime;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpEqual,
TAqDBSQLTimeConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnEqual(const pColumnName: string; pValue: TTime;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnEqual(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnEqual(pColumn: IAqDBSQLColumn; pValue: string;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpEqual,
TAqDBSQLTextConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnEqual(const pColumnName: string; pValue: string;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnEqual(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnEqual(pColumn: IAqDBSQLColumn; pValue: IAqDBSQLValue;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpEqual, pValue));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnEqual(const pColumnName: string; pValue: IAqDBSQLValue;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnEqual(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnEqual(pColumn: IAqDBSQLColumn; pValue: Int64;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpEqual,
TAqDBSQLIntConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnEqual(const pColumnName: string; pValue: Double;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnEqual(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnEqual(pColumn: IAqDBSQLColumn; pValue: Currency;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpEqual,
TAqDBSQLCurrencyConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnEqual(const pColumnName: string; pValue: Int64;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnEqual(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnEqual(pColumn: IAqDBSQLColumn; pValue: Double;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpEqual,
TAqDBSQLDoubleConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnGreaterEqualThan(pColumn: IAqDBSQLColumn; pValue: TDateTime;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpGreaterEqual,
TAqDBSQLDateTimeConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnGreaterEqualThan(const pColumnName: string; pValue: TDateTime;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnGreaterEqualThan(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnGreaterEqualThan(pColumn: IAqDBSQLColumn; pValue: Currency;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpGreaterEqual,
TAqDBSQLCurrencyConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnGreaterEqualThan(const pColumnName: string; pValue: Currency;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnGreaterEqualThan(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnGreaterEqualThan(pColumn: IAqDBSQLColumn; pValue: TTime;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpGreaterEqual,
TAqDBSQLTimeConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnGreaterEqualThan(const pColumnName: string; pValue: TTime;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnGreaterEqualThan(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnGreaterEqualThan(pColumn: IAqDBSQLColumn; pValue: TDate;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpGreaterEqual,
TAqDBSQLDateConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnGreaterEqualThan(const pColumnName: string; pValue: TDate;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnGreaterEqualThan(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnGreaterEqualThan(pColumn: IAqDBSQLColumn; pValue: string;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpGreaterEqual,
TAqDBSQLTextConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnGreaterEqualThan(const pColumnName: string; pValue: string;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnGreaterEqualThan(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnGreaterEqualThan(pColumn: IAqDBSQLColumn; pValue: IAqDBSQLValue;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpGreaterEqual, pValue));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnGreaterEqualThan(const pColumnName: string; pValue: IAqDBSQLValue;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnGreaterEqualThan(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnGreaterEqualThan(pColumn: IAqDBSQLColumn; pValue: Double;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpGreaterEqual,
TAqDBSQLDoubleConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnGreaterEqualThan(const pColumnName: string; pValue: Double;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnGreaterEqualThan(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnGreaterEqualThan(pColumn: IAqDBSQLColumn; pValue: Int64;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpGreaterEqual,
TAqDBSQLIntConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnGreaterEqualThan(const pColumnName: string; pValue: Int64;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnGreaterEqualThan(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnGreaterThan(pColumn: IAqDBSQLColumn; pValue: Double;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpGreaterThan,
TAqDBSQLDoubleConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnGreaterThan(const pColumnName: string; pValue: Int64;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnGreaterThan(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnGreaterThan(pColumn: IAqDBSQLColumn; pValue: Currency;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpGreaterThan,
TAqDBSQLCurrencyConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnGreaterThan(const pColumnName: string; pValue: Double;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnGreaterThan(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnGreaterThan(pColumn: IAqDBSQLColumn; pValue: Int64;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpGreaterThan,
TAqDBSQLIntConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnGreaterThan(pColumn: IAqDBSQLColumn; pValue: IAqDBSQLValue;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpGreaterThan, pValue));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnGreaterThan(const pColumnName: string; pValue: IAqDBSQLValue;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnGreaterThan(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnGreaterThan(const pColumnName: string; pValue: string;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnGreaterThan(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnGreaterThan(pColumn: IAqDBSQLColumn; pValue: string;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpGreaterThan,
TAqDBSQLTextConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnGreaterThan(const pColumnName: string; pValue: TDate;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnGreaterThan(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnGreaterThan(pColumn: IAqDBSQLColumn; pValue: TTime;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpGreaterThan,
TAqDBSQLTimeConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnGreaterThan(const pColumnName: string; pValue: TTime;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnGreaterThan(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnGreaterThan(pColumn: IAqDBSQLColumn; pValue: TDate;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpGreaterThan,
TAqDBSQLDateConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnGreaterThan(const pColumnName: string; pValue: Currency;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnGreaterThan(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnGreaterThan(pColumn: IAqDBSQLColumn; pValue: TDateTime;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpGreaterThan,
TAqDBSQLDateTimeConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnGreaterThan(const pColumnName: string; pValue: TDateTime;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnGreaterThan(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnIsNull(const pColumnName: string;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnIsNull(TAqDBSQLColumn.Create(pColumnName), pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnIsNull(pColumn: IAqDBSQLColumn;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator, TAqDBSQLValueIsNullCondition.Create(pColumn));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnLessEqualThan(const pColumnName: string; pValue: Int64;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnLessEqualThan(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnLessEqualThan(pColumn: IAqDBSQLColumn; pValue: Int64;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpLessEqual,
TAqDBSQLIntConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnLessEqualThan(const pColumnName: string; pValue: Double;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnLessEqualThan(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnLessEqualThan(pColumn: IAqDBSQLColumn; pValue: Double;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpLessEqual,
TAqDBSQLDoubleConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnLessEqualThan(const pColumnName: string; pValue: IAqDBSQLValue;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnLessEqualThan(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnLessEqualThan(pColumn: IAqDBSQLColumn; pValue: IAqDBSQLValue;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpLessEqual, pValue));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnLessEqualThan(const pColumnName: string; pValue: string;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnLessEqualThan(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnLessEqualThan(pColumn: IAqDBSQLColumn; pValue: string;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpLessEqual,
TAqDBSQLTextConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnLessEqualThan(const pColumnName: string; pValue: TDate;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnLessEqualThan(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnLessEqualThan(pColumn: IAqDBSQLColumn; pValue: TDate;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpLessEqual,
TAqDBSQLDateConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnLessEqualThan(const pColumnName: string; pValue: TTime;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnLessEqualThan(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnLessEqualThan(pColumn: IAqDBSQLColumn; pValue: TTime;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpLessEqual,
TAqDBSQLTimeConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnLessEqualThan(const pColumnName: string; pValue: Currency;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnLessEqualThan(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnLessEqualThan(pColumn: IAqDBSQLColumn; pValue: Currency;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpLessEqual,
TAqDBSQLCurrencyConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnLessEqualThan(const pColumnName: string; pValue: TDateTime;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnLessEqualThan(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnLessEqualThan(pColumn: IAqDBSQLColumn; pValue: TDateTime;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpLessEqual,
TAqDBSQLDateTimeConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnLessThan(pColumn: IAqDBSQLColumn; pValue: TDateTime;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpLessThan,
TAqDBSQLDateTimeConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnLessThan(const pColumnName: string; pValue: TDateTime;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnLessThan(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnLessThan(pColumn: IAqDBSQLColumn; pValue: Currency;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpLessThan,
TAqDBSQLCurrencyConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnLessThan(const pColumnName: string; pValue: Currency;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnLessThan(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnLessThan(pColumn: IAqDBSQLColumn; pValue: TTime;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpLessThan,
TAqDBSQLTimeConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnLessThan(const pColumnName: string; pValue: TTime;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnLessThan(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnLessThan(pColumn: IAqDBSQLColumn; pValue: TDate;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpLessThan,
TAqDBSQLDateConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnLessThan(const pColumnName: string; pValue: TDate;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnLessThan(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnLessThan(pColumn: IAqDBSQLColumn; pValue: string;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpLessThan,
TAqDBSQLTextConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnLessThan(const pColumnName: string; pValue: string;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnLessThan(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnLessThan(pColumn: IAqDBSQLColumn; pValue: IAqDBSQLValue;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpLessThan, pValue));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnLessThan(const pColumnName: string; pValue: IAqDBSQLValue;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnLessThan(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnLessThan(pColumn: IAqDBSQLColumn; pValue: Double;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpLessThan,
TAqDBSQLDoubleConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnLessThan(const pColumnName: string; pValue: Double;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnLessThan(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddColumnLessThan(pColumn: IAqDBSQLColumn; pValue: Int64;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
AddCondition(pLinkOperator,
TAqDBSQLComparisonCondition.Create(pColumn, TAqDBSQLComparison.cpLessThan,
TAqDBSQLIntConstant.Create(pValue)));
Result := Self;
end;
function TAqDBSQLComposedCondition.AddColumnLessThan(const pColumnName: string; pValue: Int64;
const pLinkOperator: TAqDBSQLBooleanOperator): IAqDBSQLComposedCondition;
begin
Result := AddColumnLessThan(TAqDBSQLColumn.Create(pColumnName), pValue, pLinkOperator);
end;
function TAqDBSQLComposedCondition.AddCondition(const pLinkOperator: TAqDBSQLBooleanOperator;
pCondition: IAqDBSQLCondition): Int32;
begin
if GetIsInitialized then
begin
FOperators.Add(pLinkOperator);
end;
Result := FConditions.Add(pCondition);
end;
function TAqDBSQLComposedCondition.AddOr(pCondition: IAqDBSQLCondition): IAqDBSQLComposedCondition;
begin
AddCondition(TAqDBSQLBooleanOperator.boOr, pCondition);
Result := Self;
end;
function TAqDBSQLComposedCondition.AddXor(pCondition: IAqDBSQLCondition): IAqDBSQLComposedCondition;
begin
AddCondition(TAqDBSQLBooleanOperator.boXor, pCondition);
Result := Self;
end;
constructor TAqDBSQLComposedCondition.Create(pInitialCondition: IAqDBSQLCondition);
begin
FConditions := TAqList<IAqDBSQLCondition>.Create;
FOperators := TAqList<TAqDBSQLBooleanOperator>.Create;
if Assigned(pInitialCondition) then
begin
FConditions.Add(pInitialCondition);
end;
end;
destructor TAqDBSQLComposedCondition.Destroy;
begin
FOperators.Free;
FConditions.Free;
inherited;
end;
function TAqDBSQLComposedCondition.GetAsComposed: IAqDBSQLComposedCondition;
begin
Result := Self;
end;
function TAqDBSQLComposedCondition.GetConditions: IAqReadList<AqDrop.DB.SQL.Intf.IAqDBSQLCondition>;
begin
Result := FConditions.GetIReadList;
end;
function TAqDBSQLComposedCondition.GetConditionType: TAqDBSQLConditionType;
begin
Result := TAqDBSQLConditionType.ctComposed;
end;
function TAqDBSQLComposedCondition.GetIsInitialized: Boolean;
begin
Result := FConditions.Count > 0;
end;
function TAqDBSQLComposedCondition.GetLinkOperators: IAqReadList<AqDrop.DB.SQL.Intf.TAqDBSQLBooleanOperator>;
begin
Result := FOperators.GetIReadList;
end;
{ TAqDBSQLCondition }
function TAqDBSQLCondition.GetAsBetween: IAqDBSQLBetweenCondition;
begin
raise EAqInternal.Create('Objects of type ' + Self.QualifiedClassName +
' cannot be consumed as IAqDBSQLComparisonCondition.');
end;
function TAqDBSQLCondition.GetAsComparison: IAqDBSQLComparisonCondition;
begin
raise EAqInternal.Create('Objects of type ' + Self.QualifiedClassName +
' cannot be consumed as IAqDBSQLComparisonCondition.');
end;
function TAqDBSQLCondition.GetAsComposed: IAqDBSQLComposedCondition;
begin
raise EAqInternal.Create('Objects of type ' + Self.QualifiedClassName +
' cannot be consumed as IAqDBSQLComposedCondition.');
end;
function TAqDBSQLCondition.GetAsValueIsNull: IAqDBSQLValueIsNullCondition;
begin
raise EAqInternal.Create('Objects of type ' + Self.QualifiedClassName +
' cannot be consumed as IAqDBSQLValueIsNullCondition.');
end;
{ TAqDBSQLCommand }
function TAqDBSQLCommand.GetAsDelete: IAqDBSQLDelete;
begin
raise EAqInternal.Create('Objects of type ' + Self.QualifiedClassName + ' cannot be consumed as IAqDBSQLDelete.');
end;
function TAqDBSQLCommand.GetAsInsert: IAqDBSQLInsert;
begin
raise EAqInternal.Create('Objects of type ' + Self.QualifiedClassName + ' cannot be consumed as IAqDBSQLInsert.');
end;
function TAqDBSQLCommand.GetAsSelect: IAqDBSQLSelect;
begin
raise EAqInternal.Create('Objects of type ' + Self.QualifiedClassName + ' cannot be consumed as IAqDBSQLSelect.');
end;
function TAqDBSQLCommand.GetAsUpdate: IAqDBSQLUpdate;
begin
raise EAqInternal.Create('Objects of type ' + Self.QualifiedClassName + ' cannot be consumed as IAqDBSQLUpdate.');
end;
{ TAqDBSQLInsert }
constructor TAqDBSQLInsert.Create(pTable: IAqDBSQLTable);
begin
FTable := pTable;
FAssignments := TAqList<IAqDBSQLAssignment>.Create;
end;
function TAqDBSQLInsert.AddAssignment(pAssignment: IAqDBSQLAssignment): Int32;
begin
Result := FAssignments.Add(pAssignment);
end;
function TAqDBSQLInsert.AddAssignment(pColumn: IAqDBSQLColumn; pValue: IAqDBSQLValue): IAqDBSQLAssignment;
begin
Result := TAqDBSQLAssignment.Create(pColumn, pValue);
FAssignments.Add(Result);
end;
constructor TAqDBSQLInsert.Create(const pTableName: string);
begin
Create(TAqDBSQLTable.Create(pTableName));
end;
destructor TAqDBSQLInsert.Destroy;
begin
FAssignments.Free;
inherited;
end;
function TAqDBSQLInsert.GetAsInsert: IAqDBSQLInsert;
begin
Result := Self;
end;
function TAqDBSQLInsert.GetAssignments: IAqReadList<IAqDBSQLAssignment>;
begin
Result := FAssignments.GetIReadList;
end;
function TAqDBSQLInsert.GetCommandType: TAqDBSQLCommandType;
begin
Result := TAqDBSQLCommandType.ctInsert;
end;
function TAqDBSQLInsert.GetTable: IAqDBSQLTable;
begin
Result := FTable;
end;
{ TAqDBSQLAssignment }
constructor TAqDBSQLAssignment.Create(pColumn: IAqDBSQLColumn; pValue: IAqDBSQLValue);
begin
FColumn := pColumn;
FValue := pValue;
end;
function TAqDBSQLAssignment.GetColumn: IAqDBSQLColumn;
begin
Result := FColumn;
end;
function TAqDBSQLAssignment.GetValue: IAqDBSQLValue;
begin
Result := FValue;
end;
{ TAqDBSQLParameter }
constructor TAqDBSQLParameter.Create(const pName: string; const pAlias: string = '';
const pAggregator: TAqDBSQLAggregatorType = atNone);
begin
inherited Create(pAlias, pAggregator);
FName := pName;
end;
function TAqDBSQLParameter.GetAsParameter: IAqDBSQLParameter;
begin
Result := Self;
end;
function TAqDBSQLParameter.GetName: string;
begin
Result := FName;
end;
function TAqDBSQLParameter.GetValueType: TAqDBSQLValueType;
begin
Result := TAqDBSQLValueType.vtParameter;
end;
{ TAqDBSQLBetweenCondition }
constructor TAqDBSQLBetweenCondition.Create(pValue, pRangeBegin, pRangeEnd: IAqDBSQLValue);
begin
FValue := pValue;
FRangeBegin := pRangeBegin;
FRangeEnd := pRangeEnd;
end;
function TAqDBSQLBetweenCondition.GetAsBetween: IAqDBSQLBetweenCondition;
begin
Result := Self;
end;
function TAqDBSQLBetweenCondition.GetConditionType: TAqDBSQLConditionType;
begin
Result := TAqDBSQLConditionType.ctBetween;
end;
function TAqDBSQLBetweenCondition.GetRangeEnd: IAqDBSQLValue;
begin
Result := FRangeEnd;
end;
function TAqDBSQLBetweenCondition.GetRangeBegin: IAqDBSQLValue;
begin
Result := FRangeBegin;
end;
function TAqDBSQLBetweenCondition.GetValue: IAqDBSQLValue;
begin
Result := FValue;
end;
{ TAqDBSQLConstant }
function TAqDBSQLConstant.GetAsBooleanConstant: IAqDBSQLBooleanConstant;
begin
raise EAqInternal.Create('Objects of type ' + Self.QualifiedClassName +
' cannot be consumed as IAqDBSQLBooleanConstant.');
end;
function TAqDBSQLConstant.GetAsConstant: IAqDBSQLConstant;
begin
Result := Self;
end;
function TAqDBSQLConstant.GetAsCurrencyConstant: IAqDBSQLCurrencyConstant;
begin
raise EAqInternal.Create('Objects of type ' + Self.QualifiedClassName +
' cannot be consumed as IAqDBSQLCurrencyConstant.');
end;
function TAqDBSQLConstant.GetAsDateConstant: IAqDBSQLDateConstant;
begin
raise EAqInternal.Create('Objects of type ' + Self.QualifiedClassName +
' cannot be consumed as IAqDBSQLDateConstant.');
end;
function TAqDBSQLConstant.GetAsDateTimeConstant: IAqDBSQLDateTimeConstant;
begin
raise EAqInternal.Create('Objects of type ' + Self.QualifiedClassName +
' cannot be consumed as IAqDBSQLDateTimeConstant.');
end;
function TAqDBSQLConstant.GetAsDoubleConstant: IAqDBSQLDoubleConstant;
begin
raise EAqInternal.Create('Objects of type ' + Self.QualifiedClassName +
' cannot be consumed as IAqDBSQLDoubleConstant.');
end;
function TAqDBSQLConstant.GetAsIntConstant: IAqDBSQLIntConstant;
begin
raise EAqInternal.Create('Objects of type ' + Self.QualifiedClassName
+ ' cannot be consumed as IAqDBSQLIntConstant.');
end;
function TAqDBSQLConstant.GetAsTextConstant: IAqDBSQLTextConstant;
begin
raise EAqInternal.Create('Objects of type ' + Self.QualifiedClassName +
' cannot be consumed as IAqDBSQLTextConstant.');
end;
function TAqDBSQLConstant.GetAsTimeConstant: IAqDBSQLTimeConstant;
begin
raise EAqInternal.Create('Objects of type ' + Self.QualifiedClassName +
' cannot be consumed as IAqDBSQLTimeConstant.');
end;
function TAqDBSQLConstant.GetAsUIntConstant: IAqDBSQLUIntConstant;
begin
raise EAqInternal.Create('Objects of type ' + Self.QualifiedClassName
+ ' cannot be consumed as IAqDBSQLUIntConstant.');
end;
function TAqDBSQLConstant.GetValueType: TAqDBSQLValueType;
begin
Result := TAqDBSQLValueType.vtConstant;
end;
{ TAqDBSQLTextConstant }
function TAqDBSQLTextConstant.GetAsTextConstant: IAqDBSQLTextConstant;
begin
Result := Self;
end;
function TAqDBSQLTextConstant.GetConstantType: TAqDBSQLConstantValueType;
begin
Result := TAqDBSQLConstantValueType.cvText;
end;
{ TAqDBSQLDateTimeConstant }
function TAqDBSQLDateTimeConstant.GetAsDateTimeConstant: IAqDBSQLDateTimeConstant;
begin
Result := Self;
end;
function TAqDBSQLDateTimeConstant.GetConstantType: TAqDBSQLConstantValueType;
begin
Result := TAqDBSQLConstantValueType.cvDateTime;
end;
{ TAqDBSQLBooleanConstant }
function TAqDBSQLBooleanConstant.GetAsBooleanConstant: IAqDBSQLBooleanConstant;
begin
Result := Self;
end;
function TAqDBSQLBooleanConstant.GetConstantType: TAqDBSQLConstantValueType;
begin
Result := TAqDBSQLConstantValueType.cvBoolean;
end;
{ TAqDBSQLDateConstant }
function TAqDBSQLDateConstant.GetAsDateConstant: IAqDBSQLDateConstant;
begin
Result := Self;
end;
function TAqDBSQLDateConstant.GetConstantType: TAqDBSQLConstantValueType;
begin
Result := TAqDBSQLConstantValueType.cvDate;
end;
{ TAqDBSQLTimeConstant }
function TAqDBSQLTimeConstant.GetAsTimeConstant: IAqDBSQLTimeConstant;
begin
Result := Self;
end;
function TAqDBSQLTimeConstant.GetConstantType: TAqDBSQLConstantValueType;
begin
Result := TAqDBSQLConstantValueType.cvTime;
end;
{ TAqDBSQLUpdate }
function TAqDBSQLUpdate.AddAssignment(pColumn: IAqDBSQLColumn; pValue: IAqDBSQLValue): IAqDBSQLAssignment;
begin
Result := TAqDBSQLAssignment.Create(pColumn, pValue);
FAssignments.Add(Result);
end;
function TAqDBSQLUpdate.AddAssignment(pAssignment: IAqDBSQLAssignment): Int32;
begin
Result := FAssignments.Add(pAssignment);
end;
constructor TAqDBSQLUpdate.Create(const pTableName: string);
begin
Create(TAqDBSQLTable.Create(pTableName));
end;
function TAqDBSQLUpdate.CustomizeCondition(pNewCondition: IAqDBSQLCondition): IAqDBSQLComposedCondition;
begin
if GetIsConditionDefined then
begin
Result := TAqDBSQLComposedCondition.Create(FCondition);
if Assigned(pNewCondition) then
begin
Result.AddAnd(pNewCondition);
end;
end else begin
Result := TAqDBSQLComposedCondition.Create(pNewCondition);
end;
FCondition := Result;
end;
destructor TAqDBSQLUpdate.Destroy;
begin
FAssignments.Free;
inherited;
end;
constructor TAqDBSQLUpdate.Create(pTable: IAqDBSQLTable);
begin
FTable := pTable;
FAssignments := TAqList<IAqDBSQLAssignment>.Create;
end;
function TAqDBSQLUpdate.GetAssignments: IAqReadList<IAqDBSQLAssignment>;
begin
Result := FAssignments.GetIReadList;
end;
function TAqDBSQLUpdate.GetAsUpdate: IAqDBSQLUpdate;
begin
Result := Self;
end;
function TAqDBSQLUpdate.GetCommandType: TAqDBSQLCommandType;
begin
Result := TAqDBSQLCommandType.ctUpdate;
end;
function TAqDBSQLUpdate.GetCondition: IAqDBSQLCondition;
begin
Result := FCondition;
end;
function TAqDBSQLUpdate.GetIsConditionDefined: Boolean;
begin
Result := Assigned(FCondition);
end;
function TAqDBSQLUpdate.GetTable: IAqDBSQLTable;
begin
Result := FTable;
end;
procedure TAqDBSQLUpdate.SetCondition(pValue: IAqDBSQLCondition);
begin
FCondition := pValue;
end;
{ TAqDBSQLDelete }
constructor TAqDBSQLDelete.Create(pTable: IAqDBSQLTable);
begin
FTable := pTable;
end;
constructor TAqDBSQLDelete.Create(const pTableName: string);
begin
Create(TAqDBSQLTable.Create(pTableName));
end;
function TAqDBSQLDelete.CustomizeCondition(pNewCondition: IAqDBSQLCondition): IAqDBSQLComposedCondition;
begin
if GetIsConditionDefined then
begin
Result := TAqDBSQLComposedCondition.Create(FCondition);
if Assigned(pNewCondition) then
begin
Result.AddAnd(pNewCondition);
end;
end else begin
Result := TAqDBSQLComposedCondition.Create(pNewCondition);
end;
FCondition := Result;
end;
function TAqDBSQLDelete.GetAsDelete: IAqDBSQLDelete;
begin
Result := Self;
end;
function TAqDBSQLDelete.GetCommandType: TAqDBSQLCommandType;
begin
Result := TAqDBSQLCommandType.ctDelete;
end;
function TAqDBSQLDelete.GetCondition: IAqDBSQLCondition;
begin
Result := FCondition;
end;
function TAqDBSQLDelete.GetIsConditionDefined: Boolean;
begin
Result := Assigned(FCondition);
end;
function TAqDBSQLDelete.GetTable: IAqDBSQLTable;
begin
Result := FTable;
end;
procedure TAqDBSQLDelete.SetCondition(pValue: IAqDBSQLCondition);
begin
FCondition := pValue;
end;
{ TAqDBSQLGenericConstant<T> }
constructor TAqDBSQLGenericConstant<T>.Create(const pValue: T; const pAlias: string;
const pAggregator: TAqDBSQLAggregatorType);
begin
inherited Create(pAlias, pAggregator);
FValue := pValue;
end;
function TAqDBSQLGenericConstant<T>.GetValue: T;
begin
Result := FValue;
end;
{ TAqDBSQLIntConstant }
function TAqDBSQLIntConstant.GetAsIntConstant: IAqDBSQLIntConstant;
begin
Result := Self;
end;
function TAqDBSQLIntConstant.GetConstantType: TAqDBSQLConstantValueType;
begin
Result := TAqDBSQLConstantValueType.cvInt;
end;
{ TAqDBSQLDoubleConstant }
function TAqDBSQLDoubleConstant.GetAsDoubleConstant: IAqDBSQLDoubleConstant;
begin
Result := Self;
end;
function TAqDBSQLDoubleConstant.GetConstantType: TAqDBSQLConstantValueType;
begin
Result := TAqDBSQLConstantValueType.cvDouble;
end;
{ TAqDBSQLCurrencyConstant }
function TAqDBSQLCurrencyConstant.GetAsCurrencyConstant: IAqDBSQLCurrencyConstant;
begin
Result := Self;
end;
function TAqDBSQLCurrencyConstant.GetConstantType: TAqDBSQLConstantValueType;
begin
Result := TAqDBSQLConstantValueType.cvCurrency;
end;
{ TAqDBSQLUIntConstant }
function TAqDBSQLUIntConstant.GetAsUIntConstant: IAqDBSQLUIntConstant;
begin
Result := Self;
end;
function TAqDBSQLUIntConstant.GetConstantType: TAqDBSQLConstantValueType;
begin
Result := TAqDBSQLConstantValueType.cvUInt;
end;
{ TAqDBSQLOderByItem }
constructor TAqDBSQLOrderByItem.Create(pValue: IAqDBSQLValue; const pDesc: Boolean);
begin
FValue := pValue;
FDesc := pDesc;
end;
function TAqDBSQLOrderByItem.GetDesc: Boolean;
begin
Result := FDesc;
end;
function TAqDBSQLOrderByItem.GetValue: IAqDBSQLValue;
begin
Result := FValue;
end;
end.
|
// ************************************************************************ //
// The types declared in this file were generated from data read from the
// WSDL File described below:
// WSDL : http://carme/secure/ws/awsi/PictometryServer.php?wsdl
// >Import : http://carme/secure/ws/awsi/PictometryServer.php?wsdl:0
// Encoding : ISO-8859-1
// Version : 1.0
// (10/8/2012 3:46:00 PM - - $Rev: 10138 $)
// ************************************************************************ //
unit AWSI_Server_Pictometry;
interface
uses InvokeRegistry, SOAPHTTPClient, Types, XSBuiltIns;
const
IS_OPTN = $0001;
type
// ************************************************************************ //
// The following types, referred to in the WSDL document are not being represented
// in this file. They are either aliases[@] of other types represented or were referred
// to but never[!] declared in the document. The types from the latter category
// typically map to predefined/known XML or Borland types; however, they could also
// indicate incorrect WSDL documents that failed to declare or import a schema type.
// ************************************************************************ //
// !:int - "http://www.w3.org/2001/XMLSchema"[Gbl]
// !:string - "http://www.w3.org/2001/XMLSchema"[Gbl]
// !:float - "http://www.w3.org/2001/XMLSchema"[Gbl]
clsResults = class; { "http://carme/secure/ws/WSDL"[GblCplx] }
clsPictometryData = class; { "http://carme/secure/ws/WSDL"[GblCplx] }
clsSearchByGeocodeResponse = class; { "http://carme/secure/ws/WSDL"[GblCplx] }
clsSearchByAddressResponse = class; { "http://carme/secure/ws/WSDL"[GblCplx] }
clsAcknowledgementResponse = class; { "http://carme/secure/ws/WSDL"[GblCplx] }
clsAcknowledgementResponseData = class; { "http://carme/secure/ws/WSDL"[GblCplx] }
clsDownloadMapsResponse = class; { "http://carme/secure/ws/WSDL"[GblCplx] }
clsPictometrySearchByAddressRequest = class; { "http://carme/secure/ws/WSDL"[GblCplx] }
clsPictometrySearchByGeocodeRequest = class; { "http://carme/secure/ws/WSDL"[GblCplx] }
clsUserCredentials = class; { "http://carme/secure/ws/WSDL"[GblCplx] }
clsPictometrySearchModifiers = class; { "http://carme/secure/ws/WSDL"[GblCplx] }
clsParcelInfo = class; { "http://carme/secure/ws/WSDL"[GblCplx] }
clsPictometrySearchWithParcelModifiers = class; { "http://carme/secure/ws/WSDL"[GblCplx] }
clsAcknowledgement = class; { "http://carme/secure/ws/WSDL"[GblCplx] }
// ************************************************************************ //
// XML : clsResults, global, <complexType>
// Namespace : http://carme/secure/ws/WSDL
// ************************************************************************ //
clsResults = class(TRemotable)
private
FCode: Integer;
FType_: WideString;
FDescription: WideString;
published
property Code: Integer read FCode write FCode;
property Type_: WideString read FType_ write FType_;
property Description: WideString read FDescription write FDescription;
end;
// ************************************************************************ //
// XML : clsPictometryData, global, <complexType>
// Namespace : http://carme/secure/ws/WSDL
// ************************************************************************ //
clsPictometryData = class(TRemotable)
private
FNorthView: WideString;
FEastView: WideString;
FSouthView: WideString;
FWestView: WideString;
FOrthogonalView: WideString;
FServiceAcknowledgement: WideString;
published
property NorthView: WideString read FNorthView write FNorthView;
property EastView: WideString read FEastView write FEastView;
property SouthView: WideString read FSouthView write FSouthView;
property WestView: WideString read FWestView write FWestView;
property OrthogonalView: WideString read FOrthogonalView write FOrthogonalView;
property ServiceAcknowledgement: WideString read FServiceAcknowledgement write FServiceAcknowledgement;
end;
// ************************************************************************ //
// XML : clsSearchByGeocodeResponse, global, <complexType>
// Namespace : http://carme/secure/ws/WSDL
// ************************************************************************ //
clsSearchByGeocodeResponse = class(TRemotable)
private
FResults: clsResults;
FResponseData: clsPictometryData;
public
destructor Destroy; override;
published
property Results: clsResults read FResults write FResults;
property ResponseData: clsPictometryData read FResponseData write FResponseData;
end;
// ************************************************************************ //
// XML : clsSearchByAddressResponse, global, <complexType>
// Namespace : http://carme/secure/ws/WSDL
// ************************************************************************ //
clsSearchByAddressResponse = class(TRemotable)
private
FResults: clsResults;
FResponseData: clsPictometryData;
public
destructor Destroy; override;
published
property Results: clsResults read FResults write FResults;
property ResponseData: clsPictometryData read FResponseData write FResponseData;
end;
// ************************************************************************ //
// XML : clsAcknowledgementResponse, global, <complexType>
// Namespace : http://carme/secure/ws/WSDL
// ************************************************************************ //
clsAcknowledgementResponse = class(TRemotable)
private
FResults: clsResults;
FResponseData: clsAcknowledgementResponseData;
public
destructor Destroy; override;
published
property Results: clsResults read FResults write FResults;
property ResponseData: clsAcknowledgementResponseData read FResponseData write FResponseData;
end;
// ************************************************************************ //
// XML : clsAcknowledgementResponseData, global, <complexType>
// Namespace : http://carme/secure/ws/WSDL
// ************************************************************************ //
clsAcknowledgementResponseData = class(TRemotable)
private
FReceived: Integer;
published
property Received: Integer read FReceived write FReceived;
end;
// ************************************************************************ //
// XML : clsDownloadMapsResponse, global, <complexType>
// Namespace : http://carme/secure/ws/WSDL
// ************************************************************************ //
clsDownloadMapsResponse = class(TRemotable)
private
FResults: clsResults;
FResponseData: clsPictometryData;
public
destructor Destroy; override;
published
property Results: clsResults read FResults write FResults;
property ResponseData: clsPictometryData read FResponseData write FResponseData;
end;
// ************************************************************************ //
// XML : clsPictometrySearchByAddressRequest, global, <complexType>
// Namespace : http://carme/secure/ws/WSDL
// ************************************************************************ //
clsPictometrySearchByAddressRequest = class(TRemotable)
private
FStreetAddress: WideString;
FCity: WideString;
FState: WideString;
FZip: WideString;
published
property StreetAddress: WideString read FStreetAddress write FStreetAddress;
property City: WideString read FCity write FCity;
property State: WideString read FState write FState;
property Zip: WideString read FZip write FZip;
end;
// ************************************************************************ //
// XML : clsPictometrySearchByGeocodeRequest, global, <complexType>
// Namespace : http://carme/secure/ws/WSDL
// ************************************************************************ //
clsPictometrySearchByGeocodeRequest = class(TRemotable)
private
FLongitude: Single;
FLatitude: Single;
published
property Longitude: Single read FLongitude write FLongitude;
property Latitude: Single read FLatitude write FLatitude;
end;
// ************************************************************************ //
// XML : clsUserCredentials, global, <complexType>
// Namespace : http://carme/secure/ws/WSDL
// ************************************************************************ //
clsUserCredentials = class(TRemotable)
private
FUsername: WideString;
FPassword: WideString;
FCompanyKey: WideString;
FOrderNumberKey: WideString;
FPurchase: Integer;
FCustomerOrderNumber: WideString;
FCustomerOrderNumber_Specified: boolean;
procedure SetCustomerOrderNumber(Index: Integer; const AWideString: WideString);
function CustomerOrderNumber_Specified(Index: Integer): boolean;
published
property Username: WideString read FUsername write FUsername;
property Password: WideString read FPassword write FPassword;
property CompanyKey: WideString read FCompanyKey write FCompanyKey;
property OrderNumberKey: WideString read FOrderNumberKey write FOrderNumberKey;
property Purchase: Integer read FPurchase write FPurchase;
property CustomerOrderNumber: WideString Index (IS_OPTN) read FCustomerOrderNumber write SetCustomerOrderNumber stored CustomerOrderNumber_Specified;
end;
// ************************************************************************ //
// XML : clsPictometrySearchModifiers, global, <complexType>
// Namespace : http://carme/secure/ws/WSDL
// ************************************************************************ //
clsPictometrySearchModifiers = class(TRemotable)
private
FMapHeight: Integer;
FMapHeight_Specified: boolean;
FMapWidth: Integer;
FMapWidth_Specified: boolean;
FMapQuality: Integer;
FMapQuality_Specified: boolean;
FGetImages: Integer;
FGetImages_Specified: boolean;
procedure SetMapHeight(Index: Integer; const AInteger: Integer);
function MapHeight_Specified(Index: Integer): boolean;
procedure SetMapWidth(Index: Integer; const AInteger: Integer);
function MapWidth_Specified(Index: Integer): boolean;
procedure SetMapQuality(Index: Integer; const AInteger: Integer);
function MapQuality_Specified(Index: Integer): boolean;
procedure SetGetImages(Index: Integer; const AInteger: Integer);
function GetImages_Specified(Index: Integer): boolean;
published
property MapHeight: Integer Index (IS_OPTN) read FMapHeight write SetMapHeight stored MapHeight_Specified;
property MapWidth: Integer Index (IS_OPTN) read FMapWidth write SetMapWidth stored MapWidth_Specified;
property MapQuality: Integer Index (IS_OPTN) read FMapQuality write SetMapQuality stored MapQuality_Specified;
property GetImages: Integer Index (IS_OPTN) read FGetImages write SetGetImages stored GetImages_Specified;
end;
// ************************************************************************ //
// XML : clsParcelInfo, global, <complexType>
// Namespace : http://carme/secure/ws/WSDL
// ************************************************************************ //
clsParcelInfo = class(TRemotable)
private
FStrokeColor: WideString;
FStrokeColor_Specified: boolean;
FStrokeOpacity: Single;
FStrokeOpacity_Specified: boolean;
FStrokeWidth: WideString;
FStrokeWidth_Specified: boolean;
FFillColor: WideString;
FFillColor_Specified: boolean;
FFillOpacity: WideString;
FFillOpacity_Specified: boolean;
FFeatureBuffer: Integer;
FFeatureBuffer_Specified: boolean;
FOrientations: WideString;
FOrientations_Specified: boolean;
FDraw: Integer;
FDraw_Specified: boolean;
procedure SetStrokeColor(Index: Integer; const AWideString: WideString);
function StrokeColor_Specified(Index: Integer): boolean;
procedure SetStrokeOpacity(Index: Integer; const ASingle: Single);
function StrokeOpacity_Specified(Index: Integer): boolean;
procedure SetStrokeWidth(Index: Integer; const AWideString: WideString);
function StrokeWidth_Specified(Index: Integer): boolean;
procedure SetFillColor(Index: Integer; const AWideString: WideString);
function FillColor_Specified(Index: Integer): boolean;
procedure SetFillOpacity(Index: Integer; const AWideString: WideString);
function FillOpacity_Specified(Index: Integer): boolean;
procedure SetFeatureBuffer(Index: Integer; const AInteger: Integer);
function FeatureBuffer_Specified(Index: Integer): boolean;
procedure SetOrientations(Index: Integer; const AWideString: WideString);
function Orientations_Specified(Index: Integer): boolean;
procedure SetDraw(Index: Integer; const AInteger: Integer);
function Draw_Specified(Index: Integer): boolean;
published
property StrokeColor: WideString Index (IS_OPTN) read FStrokeColor write SetStrokeColor stored StrokeColor_Specified;
property StrokeOpacity: Single Index (IS_OPTN) read FStrokeOpacity write SetStrokeOpacity stored StrokeOpacity_Specified;
property StrokeWidth: WideString Index (IS_OPTN) read FStrokeWidth write SetStrokeWidth stored StrokeWidth_Specified;
property FillColor: WideString Index (IS_OPTN) read FFillColor write SetFillColor stored FillColor_Specified;
property FillOpacity: WideString Index (IS_OPTN) read FFillOpacity write SetFillOpacity stored FillOpacity_Specified;
property FeatureBuffer: Integer Index (IS_OPTN) read FFeatureBuffer write SetFeatureBuffer stored FeatureBuffer_Specified;
property Orientations: WideString Index (IS_OPTN) read FOrientations write SetOrientations stored Orientations_Specified;
property Draw: Integer Index (IS_OPTN) read FDraw write SetDraw stored Draw_Specified;
end;
// ************************************************************************ //
// XML : clsPictometrySearchWithParcelModifiers, global, <complexType>
// Namespace : http://carme/secure/ws/WSDL
// ************************************************************************ //
clsPictometrySearchWithParcelModifiers = class(TRemotable)
private
FMapHeight: Integer;
FMapHeight_Specified: boolean;
FMapWidth: Integer;
FMapWidth_Specified: boolean;
FMapQuality: Integer;
FMapQuality_Specified: boolean;
FGetImages: Integer;
FGetImages_Specified: boolean;
FParcelInfo: clsParcelInfo;
FParcelInfo_Specified: boolean;
procedure SetMapHeight(Index: Integer; const AInteger: Integer);
function MapHeight_Specified(Index: Integer): boolean;
procedure SetMapWidth(Index: Integer; const AInteger: Integer);
function MapWidth_Specified(Index: Integer): boolean;
procedure SetMapQuality(Index: Integer; const AInteger: Integer);
function MapQuality_Specified(Index: Integer): boolean;
procedure SetGetImages(Index: Integer; const AInteger: Integer);
function GetImages_Specified(Index: Integer): boolean;
procedure SetParcelInfo(Index: Integer; const AclsParcelInfo: clsParcelInfo);
function ParcelInfo_Specified(Index: Integer): boolean;
public
destructor Destroy; override;
published
property MapHeight: Integer Index (IS_OPTN) read FMapHeight write SetMapHeight stored MapHeight_Specified;
property MapWidth: Integer Index (IS_OPTN) read FMapWidth write SetMapWidth stored MapWidth_Specified;
property MapQuality: Integer Index (IS_OPTN) read FMapQuality write SetMapQuality stored MapQuality_Specified;
property GetImages: Integer Index (IS_OPTN) read FGetImages write SetGetImages stored GetImages_Specified;
property ParcelInfo: clsParcelInfo Index (IS_OPTN) read FParcelInfo write SetParcelInfo stored ParcelInfo_Specified;
end;
// ************************************************************************ //
// XML : clsAcknowledgement, global, <complexType>
// Namespace : http://carme/secure/ws/WSDL
// ************************************************************************ //
clsAcknowledgement = class(TRemotable)
private
FReceived: Integer;
FServiceAcknowledgement: WideString;
published
property Received: Integer read FReceived write FReceived;
property ServiceAcknowledgement: WideString read FServiceAcknowledgement write FServiceAcknowledgement;
end;
// ************************************************************************ //
// Namespace : PictometryServerClass
// soapAction: PictometryServerClass#%operationName%
// transport : http://schemas.xmlsoap.org/soap/http
// style : rpc
// binding : PictometryServerBinding
// service : PictometryServer
// port : PictometryServerPort
// URL : http://carme/secure/ws/awsi/PictometryServer.php
// ************************************************************************ //
PictometryServerPortType = interface(IInvokable)
['{D67175BA-F212-7CE0-7AAE-B09F866C1120}']
function PictometryService_SearchByAddress(const UserCredentials: clsUserCredentials; const PictometryAddressSearch: clsPictometrySearchByAddressRequest; const PictometrySearchModifiers: clsPictometrySearchModifiers): clsSearchByAddressResponse; stdcall;
function PictometryService_SearchByGeocode(const UserCredentials: clsUserCredentials; const PictometryGeoCodeSearch: clsPictometrySearchByGeocodeRequest; const PictometrySearchModifiers: clsPictometrySearchModifiers): clsSearchByGeocodeResponse; stdcall;
function PictometryService_SearchByAddressWithParcel(const UserCredentials: clsUserCredentials; const PictometryAddressSearch: clsPictometrySearchByAddressRequest; const PictometrySearchModifiers: clsPictometrySearchWithParcelModifiers): clsSearchByAddressResponse; stdcall;
function PictometryService_SearchByGeocodeWithParcel(const UserCredentials: clsUserCredentials; const PictometryGeoCodeSearch: clsPictometrySearchByGeocodeRequest; const PictometrySearchModifiers: clsPictometrySearchWithParcelModifiers): clsSearchByGeocodeResponse; stdcall;
function PictometryService_DownloadMaps(const UserCredentials: clsUserCredentials; const PictometryDownloadMaps: clsPictometryData): clsDownloadMapsResponse; stdcall;
function PictometryService_Acknowledgement(const UserCredentials: clsUserCredentials; const PictometryAcknowledgement: clsAcknowledgement): clsAcknowledgementResponse; stdcall;
end;
function GetPictometryServerPortType(UseWSDL: Boolean=System.False; Addr: string=''; HTTPRIO: THTTPRIO = nil): PictometryServerPortType;
implementation
uses SysUtils;
function GetPictometryServerPortType(UseWSDL: Boolean; Addr: string; HTTPRIO: THTTPRIO): PictometryServerPortType;
const
defWSDL = 'http://carme/secure/ws/awsi/PictometryServer.php?wsdl';
defURL = 'http://carme/secure/ws/awsi/PictometryServer.php';
defSvc = 'PictometryServer';
defPrt = 'PictometryServerPort';
var
RIO: THTTPRIO;
begin
Result := nil;
if (Addr = '') then
begin
if UseWSDL then
Addr := defWSDL
else
Addr := defURL;
end;
if HTTPRIO = nil then
RIO := THTTPRIO.Create(nil)
else
RIO := HTTPRIO;
try
Result := (RIO as PictometryServerPortType);
if UseWSDL then
begin
RIO.WSDLLocation := Addr;
RIO.Service := defSvc;
RIO.Port := defPrt;
end else
RIO.URL := Addr;
finally
if (Result = nil) and (HTTPRIO = nil) then
RIO.Free;
end;
end;
destructor clsSearchByGeocodeResponse.Destroy;
begin
FreeAndNil(FResults);
FreeAndNil(FResponseData);
inherited Destroy;
end;
destructor clsSearchByAddressResponse.Destroy;
begin
FreeAndNil(FResults);
FreeAndNil(FResponseData);
inherited Destroy;
end;
destructor clsAcknowledgementResponse.Destroy;
begin
FreeAndNil(FResults);
FreeAndNil(FResponseData);
inherited Destroy;
end;
destructor clsDownloadMapsResponse.Destroy;
begin
FreeAndNil(FResults);
FreeAndNil(FResponseData);
inherited Destroy;
end;
procedure clsUserCredentials.SetCustomerOrderNumber(Index: Integer; const AWideString: WideString);
begin
FCustomerOrderNumber := AWideString;
FCustomerOrderNumber_Specified := True;
end;
function clsUserCredentials.CustomerOrderNumber_Specified(Index: Integer): boolean;
begin
Result := FCustomerOrderNumber_Specified;
end;
procedure clsPictometrySearchModifiers.SetMapHeight(Index: Integer; const AInteger: Integer);
begin
FMapHeight := AInteger;
FMapHeight_Specified := True;
end;
function clsPictometrySearchModifiers.MapHeight_Specified(Index: Integer): boolean;
begin
Result := FMapHeight_Specified;
end;
procedure clsPictometrySearchModifiers.SetMapWidth(Index: Integer; const AInteger: Integer);
begin
FMapWidth := AInteger;
FMapWidth_Specified := True;
end;
function clsPictometrySearchModifiers.MapWidth_Specified(Index: Integer): boolean;
begin
Result := FMapWidth_Specified;
end;
procedure clsPictometrySearchModifiers.SetMapQuality(Index: Integer; const AInteger: Integer);
begin
FMapQuality := AInteger;
FMapQuality_Specified := True;
end;
function clsPictometrySearchModifiers.MapQuality_Specified(Index: Integer): boolean;
begin
Result := FMapQuality_Specified;
end;
procedure clsPictometrySearchModifiers.SetGetImages(Index: Integer; const AInteger: Integer);
begin
FGetImages := AInteger;
FGetImages_Specified := True;
end;
function clsPictometrySearchModifiers.GetImages_Specified(Index: Integer): boolean;
begin
Result := FGetImages_Specified;
end;
procedure clsParcelInfo.SetStrokeColor(Index: Integer; const AWideString: WideString);
begin
FStrokeColor := AWideString;
FStrokeColor_Specified := True;
end;
function clsParcelInfo.StrokeColor_Specified(Index: Integer): boolean;
begin
Result := FStrokeColor_Specified;
end;
procedure clsParcelInfo.SetStrokeOpacity(Index: Integer; const ASingle: Single);
begin
FStrokeOpacity := ASingle;
FStrokeOpacity_Specified := True;
end;
function clsParcelInfo.StrokeOpacity_Specified(Index: Integer): boolean;
begin
Result := FStrokeOpacity_Specified;
end;
procedure clsParcelInfo.SetStrokeWidth(Index: Integer; const AWideString: WideString);
begin
FStrokeWidth := AWideString;
FStrokeWidth_Specified := True;
end;
function clsParcelInfo.StrokeWidth_Specified(Index: Integer): boolean;
begin
Result := FStrokeWidth_Specified;
end;
procedure clsParcelInfo.SetFillColor(Index: Integer; const AWideString: WideString);
begin
FFillColor := AWideString;
FFillColor_Specified := True;
end;
function clsParcelInfo.FillColor_Specified(Index: Integer): boolean;
begin
Result := FFillColor_Specified;
end;
procedure clsParcelInfo.SetFillOpacity(Index: Integer; const AWideString: WideString);
begin
FFillOpacity := AWideString;
FFillOpacity_Specified := True;
end;
function clsParcelInfo.FillOpacity_Specified(Index: Integer): boolean;
begin
Result := FFillOpacity_Specified;
end;
procedure clsParcelInfo.SetFeatureBuffer(Index: Integer; const AInteger: Integer);
begin
FFeatureBuffer := AInteger;
FFeatureBuffer_Specified := True;
end;
function clsParcelInfo.FeatureBuffer_Specified(Index: Integer): boolean;
begin
Result := FFeatureBuffer_Specified;
end;
procedure clsParcelInfo.SetOrientations(Index: Integer; const AWideString: WideString);
begin
FOrientations := AWideString;
FOrientations_Specified := True;
end;
function clsParcelInfo.Orientations_Specified(Index: Integer): boolean;
begin
Result := FOrientations_Specified;
end;
procedure clsParcelInfo.SetDraw(Index: Integer; const AInteger: Integer);
begin
FDraw := AInteger;
FDraw_Specified := True;
end;
function clsParcelInfo.Draw_Specified(Index: Integer): boolean;
begin
Result := FDraw_Specified;
end;
destructor clsPictometrySearchWithParcelModifiers.Destroy;
begin
FreeAndNil(FParcelInfo);
inherited Destroy;
end;
procedure clsPictometrySearchWithParcelModifiers.SetMapHeight(Index: Integer; const AInteger: Integer);
begin
FMapHeight := AInteger;
FMapHeight_Specified := True;
end;
function clsPictometrySearchWithParcelModifiers.MapHeight_Specified(Index: Integer): boolean;
begin
Result := FMapHeight_Specified;
end;
procedure clsPictometrySearchWithParcelModifiers.SetMapWidth(Index: Integer; const AInteger: Integer);
begin
FMapWidth := AInteger;
FMapWidth_Specified := True;
end;
function clsPictometrySearchWithParcelModifiers.MapWidth_Specified(Index: Integer): boolean;
begin
Result := FMapWidth_Specified;
end;
procedure clsPictometrySearchWithParcelModifiers.SetMapQuality(Index: Integer; const AInteger: Integer);
begin
FMapQuality := AInteger;
FMapQuality_Specified := True;
end;
function clsPictometrySearchWithParcelModifiers.MapQuality_Specified(Index: Integer): boolean;
begin
Result := FMapQuality_Specified;
end;
procedure clsPictometrySearchWithParcelModifiers.SetGetImages(Index: Integer; const AInteger: Integer);
begin
FGetImages := AInteger;
FGetImages_Specified := True;
end;
function clsPictometrySearchWithParcelModifiers.GetImages_Specified(Index: Integer): boolean;
begin
Result := FGetImages_Specified;
end;
procedure clsPictometrySearchWithParcelModifiers.SetParcelInfo(Index: Integer; const AclsParcelInfo: clsParcelInfo);
begin
FParcelInfo := AclsParcelInfo;
FParcelInfo_Specified := True;
end;
function clsPictometrySearchWithParcelModifiers.ParcelInfo_Specified(Index: Integer): boolean;
begin
Result := FParcelInfo_Specified;
end;
initialization
InvRegistry.RegisterInterface(TypeInfo(PictometryServerPortType), 'PictometryServerClass', 'ISO-8859-1');
InvRegistry.RegisterDefaultSOAPAction(TypeInfo(PictometryServerPortType), 'PictometryServerClass#%operationName%');
InvRegistry.RegisterExternalMethName(TypeInfo(PictometryServerPortType), 'PictometryService_SearchByAddress', 'PictometryService.SearchByAddress');
InvRegistry.RegisterExternalMethName(TypeInfo(PictometryServerPortType), 'PictometryService_SearchByGeocode', 'PictometryService.SearchByGeocode');
InvRegistry.RegisterExternalMethName(TypeInfo(PictometryServerPortType), 'PictometryService_SearchByAddressWithParcel', 'PictometryService.SearchByAddressWithParcel');
InvRegistry.RegisterExternalMethName(TypeInfo(PictometryServerPortType), 'PictometryService_SearchByGeocodeWithParcel', 'PictometryService.SearchByGeocodeWithParcel');
InvRegistry.RegisterExternalMethName(TypeInfo(PictometryServerPortType), 'PictometryService_DownloadMaps', 'PictometryService.DownloadMaps');
InvRegistry.RegisterExternalMethName(TypeInfo(PictometryServerPortType), 'PictometryService_Acknowledgement', 'PictometryService.Acknowledgement');
RemClassRegistry.RegisterXSClass(clsResults, 'http://carme/secure/ws/WSDL', 'clsResults');
RemClassRegistry.RegisterExternalPropName(TypeInfo(clsResults), 'Type_', 'Type');
RemClassRegistry.RegisterXSClass(clsPictometryData, 'http://carme/secure/ws/WSDL', 'clsPictometryData');
RemClassRegistry.RegisterXSClass(clsSearchByGeocodeResponse, 'http://carme/secure/ws/WSDL', 'clsSearchByGeocodeResponse');
RemClassRegistry.RegisterXSClass(clsSearchByAddressResponse, 'http://carme/secure/ws/WSDL', 'clsSearchByAddressResponse');
RemClassRegistry.RegisterXSClass(clsAcknowledgementResponse, 'http://carme/secure/ws/WSDL', 'clsAcknowledgementResponse');
RemClassRegistry.RegisterXSClass(clsAcknowledgementResponseData, 'http://carme/secure/ws/WSDL', 'clsAcknowledgementResponseData');
RemClassRegistry.RegisterXSClass(clsDownloadMapsResponse, 'http://carme/secure/ws/WSDL', 'clsDownloadMapsResponse');
RemClassRegistry.RegisterXSClass(clsPictometrySearchByAddressRequest, 'http://carme/secure/ws/WSDL', 'clsPictometrySearchByAddressRequest');
RemClassRegistry.RegisterXSClass(clsPictometrySearchByGeocodeRequest, 'http://carme/secure/ws/WSDL', 'clsPictometrySearchByGeocodeRequest');
RemClassRegistry.RegisterXSClass(clsUserCredentials, 'http://carme/secure/ws/WSDL', 'clsUserCredentials');
RemClassRegistry.RegisterXSClass(clsPictometrySearchModifiers, 'http://carme/secure/ws/WSDL', 'clsPictometrySearchModifiers');
RemClassRegistry.RegisterXSClass(clsParcelInfo, 'http://carme/secure/ws/WSDL', 'clsParcelInfo');
RemClassRegistry.RegisterXSClass(clsPictometrySearchWithParcelModifiers, 'http://carme/secure/ws/WSDL', 'clsPictometrySearchWithParcelModifiers');
RemClassRegistry.RegisterXSClass(clsAcknowledgement, 'http://carme/secure/ws/WSDL', 'clsAcknowledgement');
end.
|
unit qtxStyles;
//#############################################################################
//
// Unit: qtxStyles.pas
// Author: Jon Lennart Aasenden [cipher diaz of quartex]
// Copyright: Jon Lennart Aasenden, all rights reserved
//
// Description:
// ============
// This unit introduces CSS oriented helper classes and methods
//
// _______ _______ _______ _________ _______
// ( ___ )|\ /|( ___ )( ____ )\__ __/( ____ \|\ /|
// | ( ) || ) ( || ( ) || ( )| ) ( | ( \/( \ / )
// | | | || | | || (___) || (____)| | | | (__ \ (_) /
// | | | || | | || ___ || __) | | | __) ) _ (
// | | /\| || | | || ( ) || (\ ( | | | ( / ( ) \
// | (_\ \ || (___) || ) ( || ) \ \__ | | | (____/\( / \ )
// (____\/_)(_______)|/ \||/ \__/ )_( (_______/|/ \|
//
//
//#############################################################################
interface
uses
System.Types, SmartCL.system, w3c.dom;
type
TQTXStyleSheet = Class(TObject)
private
FHandle: THandle;
protected
function getSheet:THandle;
function getRules:THandle;
function getCount:Integer;
function getItem(index:Integer):String;
public
Property Sheet:THandle read getSheet;
Property Handle:THandle read FHandle;
function Add(aName:String;const aRules:String):String;overload;
Procedure Add(const aRuleText:String);overload;
Property Count:Integer read getCount;
Property Items[index:Integer]:String
read getItem;
class procedure addClassToElement(const aElement:THandle;const aName:String);
class procedure removeClassFromElement(const aElement:THandle;const aName:String);
class function findClassInElement(const aElement:THandle;const aName:String):Boolean;
Constructor Create;virtual;
Destructor Destroy;Override;
End;
implementation
//############################################################################
// TQTXStyleSheet
//############################################################################
Constructor TQTXStyleSheet.Create;
var
mDocument: THandle;
begin
inherited Create;
mDocument:=BrowserAPI.document;
FHandle:=mDocument.createElement('style');
FHandle.type := 'text/css';
mDocument.getElementsByTagName('head')[0].appendChild(FHandle);
end;
Destructor TQTXStyleSheet.Destroy;
Begin
if (FHandle) then
FHandle.parentNode.removeChild(FHandle);
FHandle:=null;
Inherited;
end;
function TQTXStyleSheet.getCount:Integer;
Begin
if (FHandle) then
result:=getRules.length else
result:=0;
end;
function TQTXStyleSheet.getItem(index:Integer):String;
Begin
if (FHandle) then
result:=getRules[index].cssText
end;
(* Takes height for differences between webkit, moz and IE *)
function TQTXStyleSheet.getRules:THandle;
var
xRef: THandle;
Begin
if (FHandle) then
begin
xRef:=getSheet;
asm
@result = (@xRef).cssRules || (@xRef).rules;
end;
end;
end;
(* Takes height for differences between webkit, moz and IE *)
function TQTXStyleSheet.getSheet:THandle;
var
xRef: THandle;
Begin
if (FHandle) then
begin
xRef:=FHandle;
asm
@result = (@xRef).styleSheet || (@xRef).sheet;
end;
end;
end;
class procedure TQTXStyleSheet.addClassToElement(const aElement:THandle;
const aName:String);
Begin
w3_AddClass( aElement,aName);
end;
class procedure TQTXStyleSheet.removeClassFromElement(const aElement:THandle;
const aName:String);
Begin
w3_RemoveClass(aElement,aName);
end;
class function TQTXStyleSheet.findClassInElement(const aElement:THandle;
const aName:String):Boolean;
Begin
result:=w3_hasClass(aElement,aName);
end;
Procedure TQTXStyleSheet.Add(const aRuleText:String);
var
mDocument: THandle;
mSheet: THandle;
Begin
mDocument:=BrowserAPI.document;
if (FHandle) then
Begin
mSheet:=getSheet;
if not (mSheet.insertRule) then
mSheet.addRule(aRuleText) else
mSheet.insertRule(aRuleText,0);
end;
end;
function TQTXStyleSheet.Add(aName:String;const aRules:String):String;
var
mDocument: THandle;
mSheet: THandle;
Begin
aName:=trim(aName);
if length(aName)=0 then
aName:=w3_GetUniqueObjId;
mDocument:=BrowserAPI.document;
if (FHandle) then
Begin
mSheet:=getSheet;
if not (mSheet.insertRule) then
mSheet.addRule('.' + aName,aRules) else
mSheet.insertRule('.' + aName + '{' + aRules + '}',0);
end;
result:=aName;
end;
end.
|
(* Problema: TROVAPAROLA, selezioni territoriali 2013 *)
(* Autore: William Di Luigi <williamdiluigi@gmail.com> *)
(* La soluzione implementa una visita in profondita' (DFS) per *)
(* cercare di comporre la parola P partendo dal suo idx-esimo *)
(* carattere, sapendo che ci troviamo in posizione (i, j) nella *)
(* griglia di lettere. Usiamo l'accortezza di evitare di passare due *)
(* volte per la stessa cella, dato che la lunghezza di qualsiasi *)
(* percorso che va da (1, 1) a (i, j) e' sempre uguale, e quindi ci *)
(* ritroveremmo ogni volta nella stessa cella (i, j) ma con lo stesso *)
(* indice idx da cui "ripartire", e gia' sappiamo che non riusciremo *)
(* a comporre la parola (se cosi' non fosse l'avremmo trovata prima). *)
var
R, C : longint;
M : array[1..100, 1..100] of char;
P : ansistring;
visto : array[1..100, 1..100] of boolean;
(* La funzione restituisce direttamente la stringa richiesta in *)
(* output dall'esercizio. La "stringa soluzione" viene costruita *)
(* concatenando un carattere ('B' o 'D' = Basso o Destra) a sinistra *)
(* della "stringa soluzione" per il sottoproblema che viene generato *)
(* rispettivamente aprendo "in basso" o "a destra". Stiamo attenti *)
(* a restituire 'ASSENTE' quando le due chiamate ricorsive hanno *)
(* entrambe esito 'ASSENTE'. *)
function dfs(i : longint; j : longint; idx : longint) : ansistring;
var
temp : ansistring;
begin
(* Se sono fuori dalla griglia, o ho gia' visto questa cella,
o il carattere non combacia *)
if (i > R) or (j > C) or visto[i][j] or (M[i][j] <> P[idx]) then
begin
dfs := 'ASSENTE';
exit;
end;
(* Se ho fatto combaciare tutti i caratteri *)
if idx = length(P) then
begin
(* Allora restituisco la stringa vuota,
in modo che verra' "compilata" dal chiamante *)
dfs := '';
exit;
end;
(* Segna che ho visto questa posizione
cosi' non ci ripasso due volte *)
visto[i][j] := True;
(* Prova ad "aprire in basso" *)
temp := dfs(i+1, j, idx+1);
if temp <> 'ASSENTE' then
begin
(* Se va bene, restituisci la soluzione *)
dfs := 'B' + temp;
exit;
end;
(* Prova ad "aprire a destra" *)
temp := dfs(i, j+1, idx+1);
if temp <> 'ASSENTE' then
begin
(* Se va bene, restituisci la soluzione *)
dfs := 'D' + temp;
exit;
end;
(* Se arrivo qui, questo ramo ricorsivo non ha soluzione *)
dfs := 'ASSENTE';
end;
var
i, j : longint;
begin
(* Redireziona l'input/output da tastiera sui relativi files txt *)
assign(input, 'input.txt');
assign(output, 'output.txt');
reset(input);
rewrite(output);
(* Leggi R, C *)
readln(R, C);
(* Leggi la parola P *)
readln(P);
(* Leggi i singoli caratteri, e intanto
inizializza a False l'array "visto" *)
for i:=1 to R do
for j:=1 to C do
begin
repeat
read(M[i][j]);
until ('A' <= M[i][j]) and (M[i][j] <= 'Z');
visto[i][j] := False;
end;
(* Cerca partendo da (1, 1) e dall'indice 1 nella stringa P *)
writeln(dfs(1, 1, 1));
end.
|
unit Unit1;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, IPPeerClient, IPPeerServer,
System.Tether.Manager, System.Tether.AppProfile, Vcl.StdCtrls, ACBrMail,
ACBrNFeDANFEClass, ACBrBase, ACBrDFe,
ACBrNFe,pcnConversao, ACBrNFeDANFeRLClass, ACBrDANFCeFortesFr;
type
TForm1 = class(TForm)
TetheringManager1: TTetheringManager;
Memo1: TMemo;
TetheringAppProfile1: TTetheringAppProfile;
ACBrNFe1: TACBrNFe;
Edit1: TEdit;
Edit2: TEdit;
Button1: TButton;
Button2: TButton;
ACBrNFeDANFeRL1: TACBrNFeDANFeRL;
ACBrNFeDANFCeFortes1: TACBrNFeDANFCeFortes;
procedure TetheringManager1RequestManagerPassword(const Sender: TObject;
const ARemoteIdentifier: string; var Password: string);
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure TetheringAppProfile1Resources0ResourceReceived(
const Sender: TObject; const AResource: TRemoteResource);
procedure TetheringAppProfile1ResourceReceived(const Sender: TObject;
const AResource: TRemoteResource);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
uses
uNotaFiscal, REST.JSON, pcnConversaoNFe,
System.Tether.NetworkAdapter, System.Bluetooth, System.Bluetooth.Components,
System.Tether.BluetoothAdapter;
procedure TForm1.Button1Click(Sender: TObject);
begin
Edit1.Text := ACBrNFe1.SSL.SelecionarCertificado;
end;
procedure TForm1.Button2Click(Sender: TObject);
var
nfce : TNFCe;
i,j : integer;
begin
nfce := TJson.JsonToObject<TNFCe>(memo1.Lines.Text);
ACBrNFe1.Configuracoes.Geral.ModeloDF := moNFCe;
with ACBrNFe1.NotasFiscais.Add.NFe do
begin
Ide.cNF := StrToInt(nfce.Numero);
Ide.natOp := nfce.natOp;
Ide.indPag := ipVista;
Ide.modelo := 65;
Ide.serie := StrToInt(nfce.Serie);
Ide.nNF := StrToInt(nfce.Numero);
Ide.dEmi := now;
Ide.dSaiEnt := now;
Ide.hSaiEnt := now;
Ide.tpNF := tnSaida;
Ide.tpEmis := TpcnTipoEmissao(0); ;
Ide.tpAmb := taHomologacao;
Ide.cUF := UFtoCUF(nfce.Empresa.UF);
Ide.cMunFG := nfce.Empresa.CodigoMunicipio;
Ide.finNFe := fnNormal;
Ide.tpImp := tiNFCe;
Ide.indFinal := cfConsumidorFinal;
Ide.indPres := pcPresencial;
Emit.CNPJCPF := nfce.Empresa.CNPJ;
Emit.IE := '82448209';
Emit.xNome := nfce.Empresa.RazaoSocial;
Emit.xFant := nfce.Empresa.NomeFantasia;
Emit.EnderEmit.fone := nfce.Empresa.Telefone;
Emit.EnderEmit.CEP := StrToInt(nfce.Empresa.CEP);
Emit.EnderEmit.xLgr := nfce.Empresa.Endereco;
Emit.EnderEmit.nro := nfce.Empresa.Numero;
Emit.EnderEmit.xCpl := nfce.Empresa.Complemento;
Emit.EnderEmit.xBairro := nfce.Empresa.Bairro;
Emit.EnderEmit.cMun := nfce.Empresa.CodigoMunicipio;
Emit.EnderEmit.xMun := nfce.Empresa.Municipio;
Emit.EnderEmit.UF := nfce.Empresa.UF;
Emit.enderEmit.cPais := 1058;
Emit.enderEmit.xPais := 'BRASIL';
Emit.IEST := '';
Emit.CRT := crtRegimeNormal;// (1-crtSimplesNacional, 2-crtSimplesExcessoReceita, 3-crtRegimeNormal)
for I := Low(nfce.Produtos) to High(nfce.Produtos) do
begin
with Det.Add do
begin
Prod.nItem := i+1; // Número sequencial, para cada item deve ser incrementado
Prod.cProd := nfce.Produtos[i].cProd;
Prod.cEAN := nfce.Produtos[i].cEANTrib;
Prod.xProd := nfce.Produtos[i].xProd;
Prod.NCM := nfce.Produtos[i].NCM;
Prod.EXTIPI := '';
Prod.CFOP := IntToStr(nfce.Produtos[i].CFOP);
Prod.uCom := nfce.Produtos[i].uCom;
Prod.qCom := nfce.Produtos[i].qCom;
Prod.vUnCom := nfce.Produtos[i].vUnCom;
Prod.vProd := nfce.Produtos[i].vProd;
Prod.cEANTrib := nfce.Produtos[i].cEANTrib;
Prod.uTrib := nfce.Produtos[i].ucom;
Prod.qTrib := nfce.Produtos[i].qCom;
Prod.vUnTrib := nfce.Produtos[i].vUnCom;
Prod.vOutro := nfce.Produtos[i].vOutro;
Prod.vDesc := nfce.Produtos[i].vDesc;
with Imposto do
begin
// lei da transparencia nos impostos
vTotTrib := 0;
with ICMS do
begin
CST := cst00;
ICMS.orig := oeNacional;
ICMS.modBC := dbiValorOperacao;
ICMS.vBC := nfce.Produtos[i].vBC;
ICMS.pICMS := nfce.Produtos[i].Aliquota;
ICMS.vICMS := nfce.Produtos[i].ValorICMS;
ICMS.modBCST := dbisMargemValorAgregado;
ICMS.pMVAST := 0;
ICMS.pRedBCST:= 0;
ICMS.vBCST := 0;
ICMS.pICMSST := 0;
ICMS.vICMSST := 0;
ICMS.pRedBC := 0;
end;
end;
end ;
end;
Total.ICMSTot.vBC := nfce.ValorBase;
Total.ICMSTot.vICMS := nfce.ValorICMS;
Total.ICMSTot.vBCST := 0;
Total.ICMSTot.vST := 0;
Total.ICMSTot.vProd := nfce.ValorProd;
Total.ICMSTot.vFrete := 0;
Total.ICMSTot.vSeg := 0;
Total.ICMSTot.vDesc := nfce.ValorDesc;
Total.ICMSTot.vII := 0;
Total.ICMSTot.vIPI := 0;
Total.ICMSTot.vPIS := 0;
Total.ICMSTot.vCOFINS := 0;
Total.ICMSTot.vOutro := 0;
Total.ICMSTot.vNF := nfce.ValorNota;
Transp.modFrete := mfSemFrete; // NFC-e não pode ter FRETE
for J := Low(NFCe.Pagamentos) to High(NFCe.Pagamentos) do
begin
with pag.Add do //PAGAMENTOS apenas para NFC-e
begin
tPag := TpcnFormaPagamento( nfce.Pagamentos[j].codigo );
vPag := nfce.Pagamentos[j].valor;
end;
end;
InfAdic.infCpl := '';
InfAdic.infAdFisco := '';
end;
ACBrNFe1.Configuracoes.Certificados.NumeroSerie := Edit1.Text;
ACBrNFe1.Configuracoes.Arquivos.PathSchemas :=
'C:\HomePC\Palestras\EConf2015\ACBrNFCeTether\NFCe\Servidor\Win32\Debug\Schemas';
ACBrNFe1.NotasFiscais[0].Assinar;
ACBrNFe1.Enviar(1,True)
end;
procedure TForm1.TetheringAppProfile1ResourceReceived(const Sender: TObject;
const AResource: TRemoteResource);
begin
Memo1.Lines.LoadFromStream(AResource.Value.AsStream);
if Memo1.Lines.Text <> '' then
begin
Button2Click(Button2);
end;
end;
procedure TForm1.TetheringAppProfile1Resources0ResourceReceived(
const Sender: TObject; const AResource: TRemoteResource);
begin
Memo1.Lines.LoadFromStream(AResource.Value.AsStream);
end;
procedure TForm1.TetheringManager1RequestManagerPassword(const Sender: TObject;
const ARemoteIdentifier: string; var Password: string);
begin
Password := '1234';
end;
end.
|
unit utilTbxMenuConvert;
{Utility to convert standard TMenu to TB2K/TBX}
interface
{$I TB2Ver.inc}
uses
Windows, SysUtils, Classes, Controls, Forms, Menus, StdCtrls,
TB2Item,TBX;
procedure CopyConvertTB2K(const ParentItem: TTBCustomItem; Menu: TMenu);
procedure CopyConvertTBX(const ParentItem: TTBCustomItem; Menu: TMenu);
implementation
procedure CopyConvertTB2K(const ParentItem: TTBCustomItem; Menu: TMenu);
{originally taken from TB2DsgnConverter.pas from TB2K lib ver 2.1.6}
const
SPropNotTransferred = 'Warning: %s property not transferred on ''%s''.';
//var ConverterForm: TTBConverterForm;
procedure Log(const S: String);
begin
{ConverterForm.MessageList.Items.Add(S);
ConverterForm.MessageList.TopIndex := ConverterForm.MessageList.Items.Count-1;
ConverterForm.Update;}
end;
procedure Recurse(MenuItem: TMenuItem; TBItem: TTBCustomItem);
var
I: Integer;
Src: TMenuItem;
IsSep, IsSubmenu: Boolean;
Dst: TTBCustomItem;
N: String;
var Owner : TComponent;
begin
Owner := ParentItem.Owner;
for I := 0 to MenuItem.Count-1 do begin
Src := MenuItem[I];
IsSep := (Src.Caption = '-');
IsSubmenu := False;
if not IsSep then begin
if Src.Count > 0 then
IsSubmenu := True;
if not IsSubmenu then
Dst := TTBItem.Create(Owner)
else
Dst := TTBSubmenuItem.Create(Owner);
Dst.Action := Src.Action;
{$IFDEF JR_D6}
Dst.AutoCheck := Src.AutoCheck;
{$ENDIF}
Dst.Caption := Src.Caption;
Dst.Checked := Src.Checked;
if Src.Default then
Dst.Options := Dst.Options + [tboDefault];
Dst.Enabled := Src.Enabled;
Dst.GroupIndex := Src.GroupIndex;
Dst.HelpContext := Src.HelpContext;
Dst.ImageIndex := Src.ImageIndex;
Dst.RadioItem := Src.RadioItem;
Dst.ShortCut := Src.ShortCut;
{$IFDEF JR_D5}
Dst.SubMenuImages := Src.SubMenuImages;
{$ENDIF}
Dst.OnClick := Src.OnClick;
end
else begin
Dst := TTBSeparatorItem.Create(Owner);
end;
Dst.Hint := Src.Hint;
Dst.Tag := Src.Tag;
Dst.Visible := Src.Visible;
if not IsSep then
{ Temporarily clear the menu item's OnClick property, so that renaming
the menu item doesn't cause the function name to change }
Src.OnClick := nil;
try
{N := Src.Name;
Src.Name := N + '_OLD';
Dst.Name := N;}
Dst.Name := Src.Name;
finally
if not IsSep then
Src.OnClick := Dst.OnClick;
end;
TBItem.Add(Dst);
{$IFDEF JR_D5}
if @Src.OnAdvancedDrawItem <> nil then
Log(Format(SPropNotTransferred, ['OnAdvancedDrawItem', Dst.Name]));
{$ENDIF}
if @Src.OnDrawItem <> nil then
Log(Format(SPropNotTransferred, ['OnDrawItem', Dst.Name]));
if @Src.OnMeasureItem <> nil then
Log(Format(SPropNotTransferred, ['OnMeasureItem', Dst.Name]));
if IsSubmenu then
Recurse(Src, Dst);
end;
end;
var
// OptionsForm: TTBConvertOptionsForm;
I: Integer;
C: TComponent;
//Menu: TMenu;
begin
// Menu := nil;
//OptionsForm := TTBConvertOptionsForm.Create(Application);
{try
for I := 0 to Owner.ComponentCount-1 do begin
C := Owner.Components[I];
if (C is TMenu) and not(C is TTBPopupMenu) then
OptionsForm.MenuCombo.Items.AddObject(C.Name, C);
end;
if OptionsForm.MenuCombo.Items.Count = 0 then
raise Exception.Create('Could not find any menus on the form to convert');
OptionsForm.MenuCombo.ItemIndex := 0;
if (OptionsForm.ShowModal <> mrOK) or (OptionsForm.MenuCombo.ItemIndex < 0) then
Exit;
Menu := TMenu(OptionsForm.MenuCombo.Items.Objects[OptionsForm.MenuCombo.ItemIndex]);
finally
OptionsForm.Free;
end;}
ParentItem.SubMenuImages := Menu.Images;
{ConverterForm := TTBConverterForm.Create(Application);
ConverterForm.Show;
ConverterForm.Update;
Log(Format('Converting ''%s'', please wait...', [Menu.Name]));}
ParentItem.ViewBeginUpdate;
try
Recurse(Menu.Items, ParentItem);
finally
ParentItem.ViewEndUpdate;
end;
{Log('Done!');
ConverterForm.CloseButton.Enabled := True;
ConverterForm.CopyButton.Enabled := True;}
end;
procedure CopyConvertTBX(const ParentItem: TTBCustomItem; Menu: TMenu);
{originally taken from TB2DsgnConverter.pas from TB2K lib ver 2.1.6}
const
SPropNotTransferred = 'Warning: %s property not transferred on ''%s''.';
//var ConverterForm: TTBConverterForm;
procedure Log(const S: String);
begin
{ConverterForm.MessageList.Items.Add(S);
ConverterForm.MessageList.TopIndex := ConverterForm.MessageList.Items.Count-1;
ConverterForm.Update;}
end;
procedure Recurse(MenuItem: TMenuItem; TBXItem: TTBCustomItem);
var
I: Integer;
Src: TMenuItem;
IsSep, IsSubmenu: Boolean;
Dst: TTBCustomItem;
N: String;
var Owner : TComponent;
begin
Owner := ParentItem.Owner;
for I := 0 to MenuItem.Count-1 do begin
Src := MenuItem[I];
IsSep := (Src.Caption = '-');
IsSubmenu := False;
if not IsSep then begin
if Src.Count > 0 then
IsSubmenu := True;
if not IsSubmenu then
Dst := TTBXItem.Create(Owner)
else
Dst := TTBXSubmenuItem.Create(Owner);
Dst.Action := Src.Action;
{$IFDEF JR_D6}
Dst.AutoCheck := Src.AutoCheck;
{$ENDIF}
Dst.Caption := Src.Caption;
Dst.Checked := Src.Checked;
if Src.Default then
Dst.Options := Dst.Options + [tboDefault];
Dst.Enabled := Src.Enabled;
Dst.GroupIndex := Src.GroupIndex;
Dst.HelpContext := Src.HelpContext;
Dst.ImageIndex := Src.ImageIndex;
Dst.RadioItem := Src.RadioItem;
Dst.ShortCut := Src.ShortCut;
{$IFDEF JR_D5}
Dst.SubMenuImages := Src.SubMenuImages;
{$ENDIF}
Dst.OnClick := Src.OnClick;
end
else begin
Dst := TTBXSeparatorItem.Create(Owner);
end;
Dst.Hint := Src.Hint;
Dst.Tag := Src.Tag;
Dst.Visible := Src.Visible;
if not IsSep then
{ Temporarily clear the menu item's OnClick property, so that renaming
the menu item doesn't cause the function name to change }
Src.OnClick := nil;
try
{N := Src.Name;
Src.Name := N + '_OLD';
Dst.Name := N;}
Dst.Name := Src.Name;
finally
if not IsSep then
Src.OnClick := Dst.OnClick;
end;
TBXItem.Add(Dst);
{$IFDEF JR_D5}
if @Src.OnAdvancedDrawItem <> nil then
Log(Format(SPropNotTransferred, ['OnAdvancedDrawItem', Dst.Name]));
{$ENDIF}
if @Src.OnDrawItem <> nil then
Log(Format(SPropNotTransferred, ['OnDrawItem', Dst.Name]));
if @Src.OnMeasureItem <> nil then
Log(Format(SPropNotTransferred, ['OnMeasureItem', Dst.Name]));
if IsSubmenu then
Recurse(Src, Dst);
end;
end;
var
// OptionsForm: TTBConvertOptionsForm;
I: Integer;
C: TComponent;
//Menu: TMenu;
begin
// Menu := nil;
//OptionsForm := TTBConvertOptionsForm.Create(Application);
{try
for I := 0 to Owner.ComponentCount-1 do begin
C := Owner.Components[I];
if (C is TMenu) and not(C is TTBPopupMenu) then
OptionsForm.MenuCombo.Items.AddObject(C.Name, C);
end;
if OptionsForm.MenuCombo.Items.Count = 0 then
raise Exception.Create('Could not find any menus on the form to convert');
OptionsForm.MenuCombo.ItemIndex := 0;
if (OptionsForm.ShowModal <> mrOK) or (OptionsForm.MenuCombo.ItemIndex < 0) then
Exit;
Menu := TMenu(OptionsForm.MenuCombo.Items.Objects[OptionsForm.MenuCombo.ItemIndex]);
finally
OptionsForm.Free;
end;}
ParentItem.SubMenuImages := Menu.Images;
{ConverterForm := TTBConverterForm.Create(Application);
ConverterForm.Show;
ConverterForm.Update;
Log(Format('Converting ''%s'', please wait...', [Menu.Name]));}
ParentItem.ViewBeginUpdate;
try
Recurse(Menu.Items, ParentItem);
finally
ParentItem.ViewEndUpdate;
end;
{Log('Done!');
ConverterForm.CloseButton.Enabled := True;
ConverterForm.CopyButton.Enabled := True;}
end;
end.
|
unit UEditSaveLocation;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls,ShellApi, FileCtrl;
type
TSavePointDialog = class(TForm)
ebCaption: TEdit;
ebLocation: TEdit;
Label1: TLabel;
Label2: TLabel;
btnSelectLocation: TButton;
btnOK: TButton;
btnCancel: TButton;
procedure FormCreate(Sender: TObject);
Procedure WMDropFiles(Var Msg: TWMDropFiles);Message WM_DropFiles;
procedure btnSelectLocationClick(Sender: TObject);
procedure ebChange(Sender: TObject);
private
function GetSPCaption: String;
function GetSPLocation: String;
{ Private 宣言 }
public
property SPCaption:String read GetSPCaption;
property SPLocation:String read GetSPLocation;
function ShowDialog(ASPCaption, ASPLocation:string):Boolean;
{ Public 宣言 }
end;
implementation
{$R *.DFM}
procedure TSavePointDialog.FormCreate(Sender: TObject);
begin
DragAcceptFiles(Handle,True);
end;
function TSavePointDialog.GetSPCaption: String;
begin
Result:=ebCaption.Text;
end;
function TSavePointDialog.GetSPLocation: String;
begin
Result:=ebLocation.Text;
end;
function TSavePointDialog.ShowDialog(ASPCaption, ASPLocation: string): Boolean;
begin
ebCaption.Text:=ASPCaption;
ebLocation.Text:=ASPLocation;
btnOK.Enabled:=False;
if Self.ShowModal=mrOK then
Result:=True
else
Result:=False;
end;
procedure TSavePointDialog.WMDropFiles(var Msg: TWMDropFiles);
var
FileName: Array[0..255] of Char;
begin
DragQueryFile(Msg.Drop, 0, FileName, SizeOf(FileName));
ebLocation.Text:=FileName;
ebChange(nil);
end;
procedure TSavePointDialog.btnSelectLocationClick(Sender: TObject);
var
SP:String;
begin
if SelectDirectory('固定保存フォルダの選択','',SP) then begin
ebLocation.Text:=SP;
ebChange(nil);
end;
end;
procedure TSavePointDialog.ebChange(Sender: TObject);
begin
if (ebCaption.Text<>'') and (ebLocation.Text<>'') and DirectoryExists(ebLocation.Text) then
btnOK.Enabled:=True
else
btnOK.Enabled:=False;
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/ }
{ }
{ Software distributed under the License is distributed on an }
{ "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express }
{ or implied. See the License for the specific language }
{ governing rights and limitations under the License. }
{ }
{ Copyright Eric Grange / Creative IT }
{ }
{**********************************************************************}
unit dwsSuggestions;
{$I ../dws.inc}
interface
uses
Classes, SysUtils,
dwsExprs, dwsSymbols, dwsErrors, dwsUtils, dwsTokenizer,
dwsUnitSymbols, dwsPascalTokenizer, dwsCompiler;
type
// code suggestions helper (ala ctrl+space in Delphi)
// needs prog to have been compiler with coSymbolDictionary & coContextMap
TdwsSuggestionCategory = (scUnknown,
scUnit, scType,
scClass, scRecord, scInterface, scDelegate,
scFunction, scProcedure, scMethod,
scConstructor, scDestructor,
scProperty,
scEnum, scElement,
scParameter,
scVariable, scConst,
scReservedWord,
scSpecialFunction);
IdwsSuggestions = interface
['{09CA8BF2-AF3F-4B5A-B188-4B2FF574AC34}']
function GetCode(i : Integer) : UnicodeString;
function GetCategory(i : Integer) : TdwsSuggestionCategory;
function GetCaption(i : Integer) : UnicodeString;
function GetSymbols(i : Integer) : TSymbol;
property Code[i : Integer] : UnicodeString read GetCode;
property Category[i : Integer] : TdwsSuggestionCategory read GetCategory;
property Caption[i : Integer] : UnicodeString read GetCaption;
property Symbols[i : Integer] : TSymbol read GetSymbols;
function Count : Integer;
function PartialToken : UnicodeString;
function PreviousSymbol : TSymbol;
end;
// Pseudo-symbols for suggestion purposes
TReservedWordSymbol = class(TSymbol);
TSpecialFunctionSymbol = class(TSymbol);
TSimpleSymbolList = class;
TProcAddToList = procedure (aList : TSimpleSymbolList) of object;
TSimpleSymbolList = class(TSimpleList<TSymbol>)
protected
function ScopeStruct(symbol : TSymbol) : TCompositeTypeSymbol;
// min visibility of struct members when seen from scope
function ScopeVisiblity(scope, struct : TCompositeTypeSymbol) : TdwsVisibility;
public
procedure AddSymbolTable(table : TSymbolTable);
procedure AddDirectSymbolTable(table : TSymbolTable);
procedure AddEnumeration(enum : TEnumerationSymbol; const addToList : TProcAddToList = nil);
procedure AddMembers(struc : TCompositeTypeSymbol; from : TSymbol;
const addToList : TProcAddToList = nil);
procedure AddMetaMembers(struc : TCompositeTypeSymbol; from : TSymbol;
const addToList : TProcAddToList = nil);
procedure AddNameSpace(unitSym : TUnitSymbol);
end;
TdwsSuggestionsOption = (soNoReservedWords);
TdwsSuggestionsOptions = set of TdwsSuggestionsOption;
TNameSymbolHash = TSimpleNameObjectHash<TSymbol>;
TdwsSuggestions = class (TInterfacedObject, IdwsSuggestions)
private
FProg : IdwsProgram;
FSourcePos : TScriptPos;
FSourceFile : TSourceFile;
FList : TSimpleSymbolList;
FCleanupList : TTightList;
FListLookup : TObjectsLookup;
FNamesLookup : TNameSymbolHash;
FPartialToken : UnicodeString;
FPreviousSymbol : TSymbol;
FPreviousSymbolIsMeta : Boolean;
FPreviousTokenString : UnicodeString;
FPreviousToken : TTokenType;
FAfterDot : Boolean;
FLocalContext : TdwsSourceContext;
FLocalTable : TSymbolTable;
FContextSymbol : TSymbol;
FSymbolClassFilter : TSymbolClass;
FStaticArrayHelpers : TSymbolTable;
FDynArrayHelpers : TSymbolTable;
FEnumElementHelpers : TSymbolTable;
protected
function GetCode(i : Integer) : UnicodeString;
function GetCategory(i : Integer) : TdwsSuggestionCategory;
function GetCaption(i : Integer) : UnicodeString;
function GetSymbols(i : Integer) : TSymbol;
function Count : Integer;
function PartialToken : UnicodeString;
function PreviousSymbol : TSymbol;
procedure AnalyzeLocalTokens;
procedure AddToList(aList : TSimpleSymbolList);
function IsContextSymbol(sym : TSymbol) : Boolean;
function CreateHelper(const name : UnicodeString; resultType : TTypeSymbol;
const args : array of const) : TFuncSymbol;
procedure AddEnumerationElementHelpers(list : TSimpleSymbolList);
procedure AddStaticArrayHelpers(list : TSimpleSymbolList);
procedure AddDynamicArrayHelpers(dyn : TDynamicArraySymbol; list : TSimpleSymbolList);
procedure AddTypeHelpers(typ : TTypeSymbol; meta : Boolean; list : TSimpleSymbolList);
procedure AddUnitSymbol(unitSym : TUnitSymbol; list : TSimpleSymbolList);
procedure AddReservedWords;
procedure AddSpecialFuncs;
procedure AddImmediateSuggestions;
procedure AddContextSuggestions;
procedure AddUnitSuggestions;
procedure AddGlobalSuggestions;
public
constructor Create(const prog : IdwsProgram; const sourcePos : TScriptPos;
const options : TdwsSuggestionsOptions = [];
customSuggestions : TSimpleSymbolList = nil);
destructor Destroy; override;
end;
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
implementation
// ------------------------------------------------------------------
// ------------------------------------------------------------------
// ------------------------------------------------------------------
type
THelperFilter = class (TSimpleSymbolList)
private
List : TSimpleSymbolList;
Meta : Boolean;
function OnHelper(helper : THelperSymbol) : Boolean;
end;
// OnHelper
//
function THelperFilter.OnHelper(helper : THelperSymbol) : Boolean;
begin
if not Meta then
List.AddMembers(helper, nil);
List.AddMetaMembers(helper, nil);
Result:=False;
end;
// ------------------
// ------------------ TdwsSuggestions ------------------
// ------------------
// Create
//
constructor TdwsSuggestions.Create(const prog : IdwsProgram; const sourcePos : TScriptPos;
const options : TdwsSuggestionsOptions = [];
customSuggestions : TSimpleSymbolList = nil);
begin
FProg:=prog;
FSourcePos:=sourcePos;
FSourceFile:=sourcePos.SourceFile;
FList:=TSimpleSymbolList.Create;
FListLookup:=TObjectsLookup.Create;
FNamesLookup:=TNameSymbolHash.Create;
AnalyzeLocalTokens;
AddImmediateSuggestions;
if customSuggestions<>nil then
AddToList(customSuggestions);
AddContextSuggestions;
AddUnitSuggestions;
AddGlobalSuggestions;
if not FAfterDot then begin
if not (soNoReservedWords in options) then
AddReservedWords;
AddSpecialFuncs;
end;
FNamesLookup.Clear;
FListLookup.Clear;
end;
// Destroy
//
destructor TdwsSuggestions.Destroy;
begin
FNamesLookup.Free;
FListLookup.Free;
FList.Free;
FCleanupList.Clean;
FStaticArrayHelpers.Free;
FDynArrayHelpers.Free;
FEnumElementHelpers.Free;
inherited;
end;
// AnalyzeLocalTokens
//
procedure TdwsSuggestions.AnalyzeLocalTokens;
var
codeLine : UnicodeString;
p, p2 : Integer;
sl : TStringList;
lineNumber : Integer;
function NeedCodeLine : Boolean;
begin
if lineNumber>0 then begin
Dec(lineNumber);
codeLine:=sl[lineNumber];
p:=Length(codeLine);
Result:=True;
end else Result:=False;
end;
function SkipBrackets : Boolean;
var
n : Integer;
inString : Char;
begin
while p<=0 do
if not NeedCodeLine then
Exit(False);
n:=0;
inString:=#0;
Result:=(codeLine[p]=']') or (codeLine[p]=')');
while p>=1 do begin
if inString=#0 then begin
case codeLine[p] of
')', ']' : Inc(n);
'(', '[' : Dec(n);
'''' : inString:='''';
'"' : inString:='"';
end;
if n=0 then Exit;
end else begin
if codeLine[p]=inString then
inString:=#0;
end;
Dec(p);
while p<=0 do
if not NeedCodeLine then
Exit(False);
end;
Result:=Result and (p>=1);
end;
procedure MoveToTokenStart;
begin
if p>Length(codeLine)+1 then
p:=Length(codeLine)+1;
while p>1 do begin
case codeLine[p-1] of
{$ifdef FPC}
'0'..'9', 'A'..'Z', 'a'..'z', '_', #127..#$FF : begin
{$else}
'0'..'9', 'A'..'Z', 'a'..'z', '_', #127..#$FFFF : begin
{$endif}
Dec(p);
end;
else
Break;
end;
end;
end;
var
context : TdwsSourceContext;
arrayItem : Boolean;
begin
FLocalContext:=FProg.SourceContextMap.FindContext(FSourcePos);
// find context symbol
context:=FLocalContext;
while (context<>nil) and (context.ParentSym=nil) do
context:=context.Parent;
if context<>nil then
FContextSymbol:=context.ParentSym;
// find context table
context:=FLocalContext;
while (context<>nil) and (context.LocalTable=nil) do
context:=context.Parent;
if context<>nil then
FLocalTable:=context.LocalTable
else FLocalTable:=FProg.Table;
sl:=TStringList.Create;
try
if FSourceFile<>nil then
sl.Text:=FSourceFile.Code;
if Cardinal(FSourcePos.Line-1)>=Cardinal(sl.Count) then begin
lineNumber:=0;
codeLine:='';
end else begin
lineNumber:=FSourcePos.Line-1;
codeLine:=sl[lineNumber]
end;
p:=FSourcePos.Col;
MoveToTokenStart;
FPartialToken:=Copy(codeLine, p, FSourcePos.Col-p);
if (p>1) and (codeLine[p-1]='.') then begin
FAfterDot:=True;
Dec(p, 2);
arrayItem:=SkipBrackets;
MoveToTokenStart;
FPreviousSymbol:=FProg.SymbolDictionary.FindSymbolAtPosition(p, lineNumber+1, FSourceFile.Name);
if FPreviousSymbol<>nil then begin
if FPreviousSymbol is TAliasSymbol then
FPreviousSymbol:=TAliasSymbol(FPreviousSymbol).UnAliasedType;
if arrayItem then begin
FPreviousSymbolIsMeta:=False;
if FPreviousSymbol.Typ is TArraySymbol then
FPreviousSymbol:=TArraySymbol(FPreviousSymbol.Typ).Typ
else if FPreviousSymbol is TPropertySymbol then
FPreviousSymbol:=TArraySymbol(FPreviousSymbol).Typ;
end else begin
FPreviousSymbolIsMeta:=FPreviousSymbol.IsType;
end;
end;
end else FAfterDot:=False;
finally
sl.Free;
end;
Dec(p);
while (p>1) do begin
case codeLine[p] of
' ', #13, #10, #9 : Dec(p);
else
Break;
end;
end;
p2:=p;
MoveToTokenStart;
FPreviousTokenString:=LowerCase(Copy(codeLine, p, p2-p+1));
FPreviousToken:=TTokenBuffer.StringToTokenType(FPreviousTokenString);
end;
// AddToList
//
procedure TdwsSuggestions.AddToList(aList : TSimpleSymbolList);
var
i : Integer;
tmp : TStringList;
sym : TSymbol;
begin
tmp:=TFastCompareTextList.Create;
try
tmp.CaseSensitive:=False;
tmp.Capacity:=aList.Count;
for i:=0 to aList.Count-1 do begin
sym:=aList[i];
if FPartialToken<>'' then begin
if not StrIBeginsWith(sym.Name, FPartialToken) then continue;
end;
if FSymbolClassFilter<>nil then begin
if not ((sym is FSymbolClassFilter) or (sym.Typ is FSymbolClassFilter)) then continue;
end else if sym is TOpenArraySymbol then
continue;
if StrContains(sym.Name, WideChar(' ')) then continue;
if FListLookup.IndexOf(sym)<0 then begin
FListLookup.Add(sym);
if FNamesLookup.Objects[sym.Name]=nil then begin
tmp.AddObject(sym.Name, sym);
FNamesLookup.AddObject(sym.Name, sym);
end;
end;
end;
tmp.Sort;
for i:=0 to tmp.Count-1 do
FList.Add(TSymbol(tmp.Objects[i]));
finally
tmp.Free;
end;
end;
// IsContextSymbol
//
function TdwsSuggestions.IsContextSymbol(sym : TSymbol) : Boolean;
var
context : TdwsSourceContext;
begin
context:=FLocalContext;
while context<>nil do begin
if context.ParentSym=sym then
Exit(True);
context:=context.Parent;
end;
Result:=False;
end;
// CreateHelper
//
function TdwsSuggestions.CreateHelper(const name : UnicodeString; resultType : TTypeSymbol;
const args : array of const) : TFuncSymbol;
var
i : Integer;
p : TParamSymbol;
vParamName: String;
begin
if resultType=nil then
Result:=TFuncSymbol.Create(name, fkProcedure, 0)
else begin
Result:=TFuncSymbol.Create(name, fkFunction, 0);
Result.Typ:=resultType;
end;
for i:=0 to (Length(args) div 2)-1 do
begin
case args[i*2].VType of
vtUnicodeString: vParamName := UnicodeString(args[i*2].VUnicodeString);
vtAnsiString: vParamName := AnsiString(args[i*2].VAnsiString);
else Assert(False, IntToStr(args[i*2].VType));
end;
Assert(args[i*2+1].VType=vtObject);
p:=TParamSymbol.Create(vParamName, TObject(args[i*2+1].VObject) as TTypeSymbol);
Result.Params.AddSymbol(p);
end;
end;
// AddEnumerationElementHelpers
//
procedure TdwsSuggestions.AddEnumerationElementHelpers(list : TSimpleSymbolList);
var
p : TdwsMainProgram;
begin
if FEnumElementHelpers=nil then begin
FEnumElementHelpers:=TSymbolTable.Create;
p:=FProg.ProgramObject;
FEnumElementHelpers.AddSymbol(CreateHelper('Name', p.TypString, []));
FEnumElementHelpers.AddSymbol(CreateHelper('Value', p.TypInteger, []));
end;
list.AddSymbolTable(FEnumElementHelpers);
end;
// AddStaticArrayHelpers
//
procedure TdwsSuggestions.AddStaticArrayHelpers(list : TSimpleSymbolList);
var
p : TdwsMainProgram;
begin
if FStaticArrayHelpers=nil then begin
FStaticArrayHelpers:=TSymbolTable.Create;
p:=FProg.ProgramObject;
FStaticArrayHelpers.AddSymbol(CreateHelper('Low', p.TypInteger, []));
FStaticArrayHelpers.AddSymbol(CreateHelper('High', p.TypInteger, []));
FStaticArrayHelpers.AddSymbol(CreateHelper('Length', p.TypInteger, []));
end;
list.AddSymbolTable(FStaticArrayHelpers);
end;
// AddDynamicArrayHelpers
//
procedure TdwsSuggestions.AddDynamicArrayHelpers(dyn : TDynamicArraySymbol; list : TSimpleSymbolList);
var
p : TdwsMainProgram;
begin
if FDynArrayHelpers=nil then begin
p:=FProg.ProgramObject;
FDynArrayHelpers:=TSystemSymbolTable.Create;
FDynArrayHelpers.AddSymbol(CreateHelper('Count', p.TypInteger, []));
FDynArrayHelpers.AddSymbol(CreateHelper('Add', nil, ['item', dyn.Typ]));
FDynArrayHelpers.AddSymbol(CreateHelper('Push', nil, ['item', dyn.Typ]));
FDynArrayHelpers.AddSymbol(CreateHelper('Pop', dyn.Typ, []));
FDynArrayHelpers.AddSymbol(CreateHelper('Peek', dyn.Typ, []));
FDynArrayHelpers.AddSymbol(CreateHelper('Delete', nil, ['index', dyn.Typ, 'count', p.TypInteger]));
FDynArrayHelpers.AddSymbol(CreateHelper('IndexOf', p.TypInteger, ['item', dyn.Typ, 'fromIndex', p.TypInteger]));
FDynArrayHelpers.AddSymbol(CreateHelper('Insert', nil, ['index', p.TypInteger, 'item', dyn.Typ]));
FDynArrayHelpers.AddSymbol(CreateHelper('SetLength', nil, ['newLength', p.TypInteger]));
FDynArrayHelpers.AddSymbol(CreateHelper('Clear', nil, []));
FDynArrayHelpers.AddSymbol(CreateHelper('Remove', nil, []));
FDynArrayHelpers.AddSymbol(CreateHelper('Reverse', nil, []));
FDynArrayHelpers.AddSymbol(CreateHelper('Swap', nil, ['index1', p.TypInteger, 'index2', p.TypInteger]));
FDynArrayHelpers.AddSymbol(CreateHelper('Copy', nil, ['startIndex', p.TypInteger, 'count', p.TypInteger]));
FDynArrayHelpers.AddSymbol(CreateHelper('Sort', nil, ['comparer', dyn.SortFunctionType(p.TypInteger)]));
FDynArrayHelpers.AddSymbol(CreateHelper('Map', nil, ['func', dyn.MapFunctionType(p.TypInteger)]));
end;
list.AddSymbolTable(FDynArrayHelpers);
end;
// AddTypeHelpers
//
procedure TdwsSuggestions.AddTypeHelpers(typ : TTypeSymbol; meta : Boolean; list : TSimpleSymbolList);
var
filter : THelperFilter;
begin
if FLocalTable=nil then Exit;
filter:=THelperFilter.Create;
try
filter.List:=list;
filter.Meta:=meta;
FLocalTable.EnumerateHelpers(typ, filter.OnHelper);
finally
filter.Free;
end;
end;
// AddUnitSymbol
//
procedure TdwsSuggestions.AddUnitSymbol(unitSym : TUnitSymbol; list : TSimpleSymbolList);
begin
if unitSym.Main<>nil then
list.AddSymbolTable(unitSym.Table);
if unitSym.NameSpace<>nil then
list.AddNameSpace(unitSym);
end;
// AddReservedWords
//
procedure TdwsSuggestions.AddReservedWords;
function IsAlpha(const s : UnicodeString) : Boolean;
var
i : Integer;
begin
for i:=1 to Length(s) do begin
case s[i] of
'a'..'z', 'A'..'Z' : ;
else
exit(False);
end;
end;
Result:=True;
end;
var
t : TTokenType;
rws : TReservedWordSymbol;
list : TSimpleSymbolList;
begin
list:=TSimpleSymbolList.Create;
try
for t in cPascalReservedNames do begin
if IsAlpha(cTokenStrings[t]) then begin
rws:=TReservedWordSymbol.Create(LowerCase(cTokenStrings[t]), nil);
list.Add(rws);
FCleanupList.Add(rws);
end;
end;
AddToList(list);
finally
list.Free;
end;
end;
// AddSpecialFuncs
//
procedure TdwsSuggestions.AddSpecialFuncs;
var
skk : TSpecialKeywordKind;
sfs : TSpecialFunctionSymbol;
list : TSimpleSymbolList;
begin
list:=TSimpleSymbolList.Create;
try
for skk:=Succ(skNone) to High(TSpecialKeywordKind) do begin
sfs:=TSpecialFunctionSymbol.Create(cSpecialKeywords[skk], nil);
list.Add(sfs);
FCleanupList.Add(sfs);
end;
AddToList(list);
finally
list.Free;
end;
end;
// AddImmediateSuggestions
//
procedure TdwsSuggestions.AddImmediateSuggestions;
var
list : TSimpleSymbolList;
begin
list:=TSimpleSymbolList.Create;
try
if FPreviousSymbol<>nil then begin
if FPreviousSymbolIsMeta then begin
AddTypeHelpers(FPreviousSymbol as TTypeSymbol, True, list);
end else if (FPreviousSymbol.Typ<>nil) and FPreviousSymbol.Typ.IsType then begin
AddTypeHelpers(FPreviousSymbol.Typ, False, list);
end else if FPreviousSymbol is TTypeSymbol then
AddTypeHelpers(TTypeSymbol(FPreviousSymbol), False, list);
if FPreviousSymbol is TStructuredTypeMetaSymbol then begin
// nothing
end else if FPreviousSymbol is TStructuredTypeSymbol then begin
if not FPreviousSymbolIsMeta then
list.AddMembers(TStructuredTypeSymbol(FPreviousSymbol), FContextSymbol)
else begin
if FPreviousToken in [ttPROCEDURE, ttFUNCTION, ttMETHOD, ttCONSTRUCTOR, ttDESTRUCTOR] then begin
FSymbolClassFilter:=TFuncSymbol;
list.AddMembers(TStructuredTypeSymbol(FPreviousSymbol), FContextSymbol);
end else list.AddMetaMembers(TStructuredTypeSymbol(FPreviousSymbol), FContextSymbol);
end;
end else if (FPreviousSymbol is TMethodSymbol)
and (TMethodSymbol(FPreviousSymbol).Kind=fkConstructor) then begin
list.AddMembers(TMethodSymbol(FPreviousSymbol).StructSymbol, FContextSymbol);
end else if FPreviousSymbol.Typ is TStructuredTypeSymbol then begin
if (FContextSymbol is TMethodSymbol)
and (TMethodSymbol(FContextSymbol).StructSymbol=FPreviousSymbol.Typ) then
list.AddMembers(TStructuredTypeSymbol(FPreviousSymbol.Typ), FContextSymbol, AddToList)
else list.AddMembers(TStructuredTypeSymbol(FPreviousSymbol.Typ), FContextSymbol);
end else if FPreviousSymbol.Typ is TStructuredTypeMetaSymbol then begin
list.AddMetaMembers(TStructuredTypeMetaSymbol(FPreviousSymbol.Typ).StructSymbol, FContextSymbol);
end else if FPreviousSymbol is TUnitSymbol then begin
AddUnitSymbol(TUnitSymbol(FPreviousSymbol), list);
end else if FPreviousSymbol.Typ is TArraySymbol then begin
AddStaticArrayHelpers(list);
if FPreviousSymbol.Typ is TDynamicArraySymbol then begin
AddDynamicArrayHelpers(TDynamicArraySymbol(FPreviousSymbol.Typ), list);
end;
end else if FPreviousSymbol.Typ is TBaseStringSymbol then begin
AddStaticArrayHelpers(list);
end else if FPreviousSymbol is TEnumerationSymbol then begin
list.AddSymbolTable(TEnumerationSymbol(FPreviousSymbol).Elements);
end else if (FPreviousSymbol is TElementSymbol)
or (FPreviousSymbol.Typ is TEnumerationSymbol) then begin
AddEnumerationElementHelpers(list);
end else if list.Count=0 then
FPreviousSymbol:=nil;
end;
if FPreviousToken=ttNEW then
FSymbolClassFilter:=TClassSymbol;
AddToList(list);
finally
list.Free;
end;
end;
// AddContextSuggestions
//
procedure TdwsSuggestions.AddContextSuggestions;
var
list : TSimpleSymbolList;
context : TdwsSourceContext;
funcSym : TFuncSymbol;
methSym : TMethodSymbol;
begin
if FPreviousSymbol<>nil then Exit;
context:=FLocalContext;
list:=TSimpleSymbolList.Create;
try
while context<>nil do begin
list.AddSymbolTable(context.LocalTable);
funcSym:=context.ParentSym.AsFuncSymbol;
if funcSym<>nil then begin
list.AddDirectSymbolTable(funcSym.Params);
list.AddDirectSymbolTable(funcSym.InternalParams);
// if a method, add the object's members to the list
if funcSym is TMethodSymbol then begin
methSym:=TMethodSymbol(funcSym);
if methSym.IsClassMethod then
list.AddMetaMembers(methSym.StructSymbol, methSym.StructSymbol, AddToList)
else list.AddMembers(methSym.StructSymbol, methSym.StructSymbol, AddToList);
end;
end;
context:=context.Parent;
end;
AddToList(list);
finally
list.Free;
end;
end;
// AddUnitSuggestions
//
procedure TdwsSuggestions.AddUnitSuggestions;
var
table : TSymbolTable;
main : TUnitMainSymbol;
list : TSimpleSymbolList;
begin
if FPreviousSymbol<>nil then Exit;
if FSourcePos.IsMainModule then
table:=FProg.Table
else begin
main:=FProg.UnitMains.Find(FSourceFile.Name);
if main=nil then Exit;
table:=main.Table;
end;
list:=TSimpleSymbolList.Create;
try
list.AddSymbolTable(table);
AddToList(list);
finally
list.Free;
end;
end;
// AddGlobalSuggestions
//
procedure TdwsSuggestions.AddGlobalSuggestions;
var
list : TSimpleSymbolList;
unitMains : TUnitMainSymbols;
table : TSymbolTable;
i : Integer;
begin
if FPreviousSymbol<>nil then Exit;
unitMains:=FProg.UnitMains;
list:=TSimpleSymbolList.Create;
try
for i:=0 to unitMains.Count-1 do begin
table:=unitMains[i].Table;
list.AddSymbolTable(table);
if table is TLinkedSymbolTable then
list.AddSymbolTable(TLinkedSymbolTable(table).ParentSymbolTable);
end;
AddToList(list);
finally
list.Free;
end;
end;
// GetCode
//
function TdwsSuggestions.GetCode(i : Integer) : UnicodeString;
begin
Result:=FList[i].Name;
end;
// GetCategory
//
function TdwsSuggestions.GetCategory(i : Integer) : TdwsSuggestionCategory;
var
symbol : TSymbol;
symbolClass : TClass;
begin
Result:=scUnknown;
symbol:=GetSymbols(i);
symbolClass:=symbol.ClassType;
if symbolClass.InheritsFrom(TTypeSymbol) then begin
Result:=scType;
if symbolClass.InheritsFrom(TStructuredTypeSymbol) then begin
if symbolClass.InheritsFrom(TClassSymbol) then
Result:=scClass
else if symbolClass.InheritsFrom(TRecordSymbol) then
Result:=scRecord
else if symbolClass.InheritsFrom(TInterfaceSymbol) then
Result:=scInterface
end else if symbolClass.InheritsFrom(TMethodSymbol) then begin
case TMethodSymbol(symbol).Kind of
fkConstructor : Result:=scConstructor;
fkDestructor : Result:=scDestructor;
fkMethod : Result:=scMethod;
fkProcedure : Result:=scProcedure;
fkFunction : Result:=scFunction;
end;
end else if symbolClass.InheritsFrom(TFuncSymbol) then begin
if TFuncSymbol(symbol).IsType then
Result:=scDelegate
else if symbol.Typ=nil then
Result:=scProcedure
else Result:=scFunction;
end else if symbolClass.InheritsFrom(TEnumerationSymbol) then
Result:=scEnum
else if symbolClass.InheritsFrom(TUnitSymbol) then
Result:=scUnit;
end else if symbolClass.InheritsFrom(TValueSymbol) then begin
if symbolClass.InheritsFrom(TParamSymbol) then
Result:=scParameter
else if symbolClass.InheritsFrom(TPropertySymbol) then
Result:=scProperty
else if symbolClass.InheritsFrom(TConstSymbol) then begin
if symbolClass.InheritsFrom(TElementSymbol) then
Result:=scElement
else Result:=scConst
end else Result:=scVariable;
end else if symbolClass.InheritsFrom(TReservedWordSymbol) then
Result:=scReservedWord
else if symbolClass.InheritsFrom(TSpecialFunctionSymbol) then
Result:=scSpecialFunction;
end;
// GetCaption
//
function TdwsSuggestions.GetCaption(i : Integer) : UnicodeString;
function SafeSymbolName(symbol : TSymbol) : UnicodeString;
begin
if symbol<>nil then begin
Result:=symbol.Name;
if (Result='') and (symbol.Typ<>nil) then
Result:=symbol.Caption;
end else Result:='???';
end;
var
symbol : TSymbol;
funcSym : TFuncSymbol;
valueSym : TValueSymbol;
enumSym : TEnumerationSymbol;
propSymbol : TPropertySymbol;
alias : TAliasSymbol;
begin
symbol:=FList[i];
funcSym:=symbol.AsFuncSymbol;
if funcSym<>nil then begin
Result:=funcSym.Name+' '+funcSym.ParamsDescription;
if funcSym.Result<>nil then
Result:=Result+' : '+SafeSymbolName(funcSym.Result.Typ);
end else if symbol is TEnumerationSymbol then begin
enumSym:=TEnumerationSymbol(symbol);
if enumSym.Elements.Count>0 then
Result:=enumSym.Name+' : '+SafeSymbolName(enumSym.Elements[0])+'..'+SafeSymbolName(enumSym.Elements[enumSym.Elements.Count-1])
else Result:=enumSym.Name;
end else if symbol is TPropertySymbol then begin
propSymbol:=TPropertySymbol(symbol);
if propSymbol.ArrayIndices.Count>0 then
Result:=propSymbol.Name+' '+propSymbol.GetArrayIndicesDescription+' : '+SafeSymbolName(propSymbol.Typ)
else Result:=propSymbol.Name+' : '+SafeSymbolName(propSymbol.Typ);
end else if symbol is TValueSymbol then begin
valueSym:=TValueSymbol(symbol);
Result:=valueSym.Name+' : '+SafeSymbolName(valueSym.Typ);
end else if symbol is TAliasSymbol then begin
alias:=TAliasSymbol(symbol);
Result:=alias.Name+' = '+SafeSymbolName(alias.Typ);
end else if symbol is TSpecialFunctionSymbol then begin
if symbol.Name='DebugBreak' then
Result:=symbol.Name
else Result:=symbol.Name+' ( special )';
end else Result:=symbol.Name;
end;
// GetSymbols
//
function TdwsSuggestions.GetSymbols(i : Integer) : TSymbol;
begin
Result:=FList[i];
end;
// Count
//
function TdwsSuggestions.Count : Integer;
begin
Result:=FList.Count;
end;
// PartialToken
//
function TdwsSuggestions.PartialToken : UnicodeString;
begin
Result:=FPartialToken;
end;
function TdwsSuggestions.PreviousSymbol: TSymbol;
begin
Result := FPreviousSymbol;
end;
// ------------------
// ------------------ TSimpleSymbolList ------------------
// ------------------
// ScopeStruct
//
function TSimpleSymbolList.ScopeStruct(symbol : TSymbol) : TCompositeTypeSymbol;
begin
if symbol is TCompositeTypeSymbol then
Result:=TCompositeTypeSymbol(symbol)
else if symbol is TMethodSymbol then
Result:=TMethodSymbol(symbol).StructSymbol
else if symbol is TStructuredTypeMetaSymbol then
Result:=(TStructuredTypeMetaSymbol(symbol).Typ as TCompositeTypeSymbol)
else Result:=nil;
end;
// ScopeVisiblity
//
function TSimpleSymbolList.ScopeVisiblity(scope, struct : TCompositeTypeSymbol) : TdwsVisibility;
begin
if scope=struct then
Result:=cvPrivate
else if (scope<>nil) and scope.IsOfType(struct) then
Result:=cvProtected
else Result:=cvPublic;
end;
// AddSymbolTable
//
procedure TSimpleSymbolList.AddSymbolTable(table : TSymbolTable);
var
sym : TSymbol;
begin
if table=nil then Exit;
if table is TLinkedSymbolTable then
table:=TLinkedSymbolTable(table).ParentSymbolTable;
for sym in table do begin
if sym is TUnitSymbol then
AddNameSpace(TUnitSymbol(sym))
else begin
Add(sym);
if sym.ClassType=TEnumerationSymbol then
AddEnumeration(TEnumerationSymbol(sym));
end;
end;
end;
// AddDirectSymbolTable
//
procedure TSimpleSymbolList.AddDirectSymbolTable(table : TSymbolTable);
var
sym : TSymbol;
begin
for sym in table do
Add(sym);
end;
// AddEnumeration
//
procedure TSimpleSymbolList.AddEnumeration(enum : TEnumerationSymbol; const addToList : TProcAddToList = nil);
begin
if enum.Style=enumClassic then
AddDirectSymbolTable(enum.Elements);
end;
// AddMembers
//
procedure TSimpleSymbolList.AddMembers(struc : TCompositeTypeSymbol; from : TSymbol;
const addToList : TProcAddToList = nil);
var
sym : TSymbol;
symClass : TClass;
scope : TCompositeTypeSymbol;
visibility : TdwsVisibility;
first : Boolean;
begin
scope:=ScopeStruct(from);
visibility:=ScopeVisiblity(scope, struc);
first:=True;
repeat
for sym in struc.Members do begin
symClass:=sym.ClassType;
if (symClass=TClassOperatorSymbol)
or (symClass=TClassConstSymbol)
or (symClass=TClassVarSymbol)
then continue;
if not sym.IsVisibleFor(visibility) then continue;
Add(sym);
end;
if first then begin
first:=False;
if Assigned(addToList) then begin
addToList(Self);
Clear;
end;
end;
if visibility=cvPrivate then
visibility:=cvProtected;
struc:=struc.Parent;
until struc=nil;
end;
// AddMetaMembers
//
procedure TSimpleSymbolList.AddMetaMembers(struc : TCompositeTypeSymbol; from : TSymbol;
const addToList : TProcAddToList = nil);
function IsMetaAccessor(sym : TSymbol) : Boolean;
var
symClass : TClass;
begin
if sym=nil then Exit(False);
symClass:=sym.ClassType;
Result:= (symClass=TClassConstSymbol)
or (symClass=TClassVarSymbol)
or (symClass.InheritsFrom(TMethodSymbol) and TMethodSymbol(sym).IsClassMethod);
end;
var
sym : TSymbol;
methSym : TMethodSymbol;
propSym : TPropertySymbol;
scope : TCompositeTypeSymbol;
visibility : TdwsVisibility;
first, allowConstructors : Boolean;
begin
scope:=ScopeStruct(from);
visibility:=ScopeVisiblity(scope, struc);
first:=True;
allowConstructors:=(struc is TClassSymbol) and not TClassSymbol(struc).IsStatic;
repeat
for sym in struc.Members do begin
if not sym.IsVisibleFor(visibility) then continue;
if sym is TMethodSymbol then begin
methSym:=TMethodSymbol(sym);
if methSym.IsClassMethod
or ( allowConstructors
and (methSym.Kind=fkConstructor)) then
Add(Sym);
end else if sym is TClassConstSymbol then begin
Add(sym);
end else if sym is TClassVarSymbol then begin
Add(sym);
end else if sym is TPropertySymbol then begin
propSym:=TPropertySymbol(sym);
if IsMetaAccessor(propSym.ReadSym) or IsMetaAccessor(propSym.WriteSym) then
Add(sym);
end;
end;
if first then begin
first:=False;
if Assigned(addToList) then begin
addToList(Self);
Clear;
end;
end;
if visibility=cvPrivate then
visibility:=cvProtected;
struc:=struc.Parent;
until struc=nil;
end;
// AddNameSpace
//
procedure TSimpleSymbolList.AddNameSpace(unitSym : TUnitSymbol);
var
i : Integer;
begin
if unitSym.Main<>nil then
Add(unitSym)
else begin
for i:=0 to unitSym.NameSpace.Count-1 do
AddNameSpace(unitSym.NameSpace.Objects[i] as TUnitSymbol);
end;
end;
end.
|
{ A modified version of TDBNavigator. Added 4 new buttons:
2 buttons to jump either forward or backwards a specified number of records.
1 button to set a bookmark to the current record.
1 button to goto bookmark prevously set.
Properties:
JUMP: integer set this property to the number of
records you would like to jump.
I couldn't figure out how to add this functionality through
inheritence because of all the types that are defined for the
dbnavigator and the resource files and so on.
I was able to add this functionallity through copying all the code
associated with the dbnavigator into another unit and make changes to that
unit, creating my own recource file(nav.res) and registering the component as
TExtDBNavigator.
}
Unit Nav;
Interface
Uses SysUtils, WinTypes, WinProcs, Messages, Classes, Controls, Forms,
Graphics, Menus, StdCtrls, ExtCtrls, DB, DBTables, Mask, Buttons, XMisc;
Const InitRepeatPause = 400; { pause before repeat timer (ms) }
RepeatPause = 100; { pause before hint window displays (ms)}
SpaceSize = 5; { size of space between special buttons }
type
TNavButton = class;
TNavDataLink = class;
TNavGlyph = (ngEnabled, ngDisabled);
{Added nbMark, nbGoto: How can I override these variables}
TNavigateBtn = (nbFirst, nbRW, nbPrior, nbNext, nbFF, nbLast, nbInsert,
nbDelete, nbEdit, nbPost, nbCancel, nbRefresh, nbMark, nbGoto);
TButtonSet = set of TNavigateBtn;
TNavButtonStyle = set of (nsAllowTimer, nsFocusRect);
ENavClick = procedure (Sender: TObject; Button: TNavigateBtn) of object;
{ TExtDBNavigator }
TExtDBNavigator = class (TCustomPanel)
private
{FIsStoredDataSource: Boolean;}
{FStoredDataSource: TDataSource;}
FStoredControlSource: TDataSource;
FDataLink: TNavDataLink;
FVisibleButtons: TButtonSet;
FHints: TStrings;
ButtonWidth: Integer;
MinBtnSize: TPoint;
FOnNavClick: ENavClick;
FBeforeAction: ENavClick;
FocusedButton: TNavigateBtn;
FConfirmDelete: Boolean;
{added Bookmark: this could be acomplished with inheritence}
FBM: TBookmark;
FJump: longint;
function GetDataSource: TDataSource;
procedure SetDataSource(Value: TDataSource);
procedure InitButtons;
procedure InitHints;
procedure ClickBtn(Sender: TObject);
procedure BtnMouseDown (Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure SetVisible(Value: TButtonSet);
procedure AdjustSize (var W: Integer; var H: Integer);
procedure SetHints(Value: TStrings);
procedure WMSize(var Message: TWMSize); message WM_SIZE;
procedure WMSetFocus(var Message: TWMSetFocus); message WM_SETFOCUS;
procedure WMKillFocus(var Message: TWMKillFocus); message WM_KILLFOCUS;
procedure WMGetDlgCode(var Message: TWMGetDlgCode); message WM_GETDLGCODE;
procedure WMChangeControlSource(var Msg: TMessage); message WM_ChangeControlSource;
procedure CMEnabledChanged(var Message: TMessage); message CM_ENABLEDCHANGED;
protected
Buttons: array[TNavigateBtn] of TNavButton;
procedure DataChanged;
procedure EditingChanged;
procedure ActiveChanged;
procedure ReadState(Reader: TReader); override;
{ procedure Loaded; override;}
procedure KeyDown(var Key: Word; Shift: TShiftState); override;
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
procedure SetBounds(ALeft, ATop, AWidth, AHeight: Integer); override;
procedure BtnClick(Index: TNavigateBtn);
published
property DataSource: TDataSource read GetDataSource write SetDataSource;
property VisibleButtons: TButtonSet read FVisibleButtons write SetVisible
default [nbFirst, nbRW, nbPrior, nbNext, nbFF, nbLast, nbInsert, nbDelete,
nbEdit, nbPost, nbCancel, nbRefresh];
property Jump: longint read FJump write FJump default 20;
property Align;
property DragCursor;
property DragMode;
property Enabled;
property Ctl3D;
property Hints: TStrings read FHints write SetHints;
property ParentCtl3D;
property ParentShowHint;
property PopupMenu;
property ConfirmDelete: Boolean read FConfirmDelete write FConfirmDelete default True;
property ShowHint;
property TabOrder;
property TabStop;
property Visible;
property BeforeAction: ENavClick read FBeforeAction write FBeforeAction;
property OnClick: ENavClick read FOnNavClick write FOnNavClick;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDrag;
property OnEnter;
property OnExit;
property OnResize;
end;
{ TExtDBNavigator }
{ TNavButton }
TNavButton = class(TSpeedButton)
private
FIndex: TNavigateBtn;
FNavStyle: TNavButtonStyle;
FRepeatTimer: TTimer;
procedure TimerExpired(Sender: TObject);
protected
procedure Paint; override;
procedure MouseDown(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
procedure MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer); override;
public
destructor Destroy; override;
property NavStyle: TNavButtonStyle read FNavStyle write FNavStyle;
property Index : TNavigateBtn read FIndex write FIndex;
end;
{ TNavButton }
{ TNavDataLink }
TNavDataLink = class(TDataLink)
private
FNavigator: TExtDBNavigator;
protected
procedure EditingChanged; override;
procedure DataSetChanged; override;
procedure ActiveChanged; override;
public
constructor Create(ANav: TExtDBNavigator);
destructor Destroy; override;
end;
{procedure register;}
Implementation
Uses DBIErrs, DBITypes, Clipbrd, DBConsts, Dialogs;
{$R Nav}
{ TExtDBNavigator }
{
procedure Register;
begin
RegisterComponents('Samples', [TExtDBNavigator]);
end;
}
(*
const
BtnStateName: array[TNavGlyph] of PChar = ('EN', 'DI');
{Added Mark and Goto to this list}
BtnTypeName: array[TNavigateBtn] of PChar = ('FIRST', 'RW', 'PRIOR', 'NEXT','FF',
'LAST', 'INSERT', 'DELETE', 'EDIT', 'POST', 'CANCEL', 'REFRESH', 'MARK', 'GOTO');
{Added 10 thru 13 to this list????}
BtnHintId: array[TNavigateBtn] of Word = (SFirstRecord, SPriorRecord,
SNextRecord, SLastRecord, SInsertRecord, SDeleteRecord, SEditRecord,
SPostEdit, SCancelEdit, SRefreshRecord,10, 11, 12, 13);
*)
var
{Added Mark and Goto to this list}
BtnTypeName: array[TNavigateBtn] of PChar = ('FIRST', 'RW', 'PRIOR', 'NEXT','FF',
'LAST', 'INSERT', 'DELETE', 'EDIT', 'POST', 'CANCEL', 'REFRESH', 'MARK', 'GOTO');
BtnHintId: array[TNavigateBtn] of string = (
'Первая запись',
'Назад на страницу',
'Предыдущая запись',
'Следующая запись',
'Вперед на страницу',
'Последняя запись',
'Новая запись',
'Удалить запись',
'Редактировать запись',
'Сохранить измененное',
'Отказаться от измененного',
'Обновить записи',
'Установить отметку',
'Перейти на отметку');
Constructor TExtDBNavigator.Create(AOwner: TComponent);
begin
Inherited Create(AOwner);
ControlStyle := ControlStyle - [csAcceptsControls, csSetCaption] + [csFramed, csOpaque];
FDataLink := TNavDataLink.Create(Self);
FVisibleButtons := [nbFirst, {nbRW,} nbPrior, nbNext, {nbFF,} nbLast, nbInsert,
nbDelete, nbEdit, nbPost, nbCancel, nbRefresh, nbMark, nbGoto];
FHints := TStringList.Create;
{ added hints }
FJump := 20;
FHints.add('Первая запись');
FHints.add('Назад на страницу');
FHints.add('Предыдущая запись');
FHints.add('Следующая запись');
FHints.add('Вперед на страницу');
FHints.add('Последняя запись');
FHints.add('Новая запись');
FHints.add('Удалить запись');
FHints.add('Редактировать запись');
FHints.add('Сохранить измененное');
FHints.add('Отказаться от измененного');
FHints.add('Обновить записи');
FHints.add('Установить отметку');
FHints.add('Перейти на отметку');
ShowHint:=True;
InitButtons;
BevelOuter:=bvNone;
BevelInner:=bvNone;
Width:=241;
Height:=25;
ButtonWidth:=0;
FocusedButton:=nbFirst;
FConfirmDelete:=True;
end;
Destructor TExtDBNavigator.Destroy;
begin
FHints.Free;
FDataLink.Free;
FDataLink:=nil;
Inherited Destroy;
end;
Procedure TExtDBNavigator.InitButtons;
var i: TNavigateBtn;
Btn: TNavButton;
X: Integer;
ResName: array[0..40] of Char;
begin
MinBtnSize:=Point(20, 18);
X:=0;
for i:=Low(Buttons) to High(Buttons) do begin
Btn:=TNavButton.Create(Self);
Btn.Index:=i;
Btn.Visible:=i in FVisibleButtons;
Btn.Enabled:=True;
Btn.SetBounds(X, 0, MinBtnSize.X, MinBtnSize.Y);
{Changed dbn to dbd, to match nav.res file}
Btn.Glyph.Handle:=LoadBitmap(HInstance, StrFmt(ResName, 'dbd_%s',[BtnTypeName[i]]));
Btn.NumGlyphs:=2;
Btn.OnClick:=ClickBtn;
Btn.OnMouseDown:=BtnMouseDown;
Btn.Parent:=Self;
Buttons[I]:=Btn;
X:=X+MinBtnSize.X;
end;
InitHints;
Buttons[nbPrior].NavStyle:=Buttons[nbPrior].NavStyle + [nsAllowTimer];
Buttons[nbNext].NavStyle:=Buttons[nbNext].NavStyle + [nsAllowTimer];
end;
Procedure TExtDBNavigator.InitHints;
var i: Integer;
j: TNavigateBtn;
begin
for j:=Low(Buttons) to High(Buttons) do Buttons[j].Hint:=BtnHintId[j];
j:=Low(Buttons);
for i:=0 to (FHints.Count-1) do begin
if FHints.Strings[i]<>'' then Buttons[j].Hint:=FHints.Strings[i];
if j=High(Buttons) then Exit;
Inc(j);
end;
end;
Procedure TExtDBNavigator.SetHints(Value: TStrings);
begin
FHints.Assign(Value);
InitHints;
end;
Procedure TExtDBNavigator.Notification(AComponent: TComponent;
Operation: TOperation);
begin
Inherited Notification(AComponent, Operation);
if (Operation=opRemove) and (FDataLink<>nil) and
(AComponent=DataSource) then DataSource:=nil;
end;
Procedure TExtDBNavigator.SetVisible(Value: TButtonSet);
var i: TNavigateBtn;
w,h: Integer;
begin
W:=Width;
H:=Height;
FVisibleButtons:=Value;
for i:=Low(Buttons) to High(Buttons) do Buttons[i].Visible:=i in FVisibleButtons;
AdjustSize(W,H);
if (W<>Width) or (H<>Height) then Inherited SetBounds(Left, Top, W, H);
Invalidate;
end;
Procedure TExtDBNavigator.AdjustSize (var W: Integer; var H: Integer);
var Count: Integer;
MinW: Integer;
I: TNavigateBtn;
{LastBtn: TNavigateBtn;}
Space, Temp, Remain: Integer;
X: Integer;
begin
{ if (csLoading in ComponentState) then Exit;}
if Buttons[nbFirst]=nil then Exit;
Count := 0;
{LastBtn := High(Buttons);}
for i:=Low(Buttons) to High(Buttons) do begin
if Buttons[I].Visible then begin
Inc(Count);
{LastBtn:=i;}
end;
end;
if Count=0 then Inc(Count);
MinW:=Count*(MinBtnSize.X - 1) + 1;
if W < MinW then W := MinW;
if H < MinBtnSize.Y then H := MinBtnSize.Y;
ButtonWidth := ((W - 1) div Count) + 1;
Temp := Count * (ButtonWidth - 1) + 1;
if Align = alNone then W := Temp;
X:=0;
Remain:=W-Temp;
Temp:=Count div 2;
for i:=Low(Buttons) to High(Buttons) do begin
if Buttons[I].Visible then begin
Space := 0;
if Remain <> 0 then begin
Dec (Temp, Remain);
if Temp < 0 then begin
Inc (Temp, Count);
Space := 1;
end;
end;
Buttons[I].SetBounds (X, 0, ButtonWidth + Space, Height);
Inc(X, ButtonWidth - 1 + Space);
{LastBtn:=i;}
end else Buttons[i].SetBounds (Width + 1, 0, ButtonWidth, Height);
end;
end;
Procedure TExtDBNavigator.SetBounds(ALeft, ATop, AWidth, AHeight: Integer);
var W, H: Integer;
begin
W := AWidth;
H := AHeight;
AdjustSize (W, H);
Inherited SetBounds (ALeft, ATop, W, H);
end;
Procedure TExtDBNavigator.WMSize(var Message: TWMSize);
var W, H: Integer;
begin
Inherited;
{ check for minimum size }
W := Width;
H := Height;
AdjustSize (W, H);
if (W <> Width) or (H <> Height) then Inherited SetBounds(Left, Top, W, H);
Message.Result := 0;
end;
Procedure TExtDBNavigator.ClickBtn(Sender: TObject);
begin
BtnClick (TNavButton (Sender).Index);
end;
Procedure TExtDBNavigator.BtnMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var OldFocus: TNavigateBtn;
begin
OldFocus := FocusedButton;
FocusedButton := TNavButton (Sender).Index;
if TabStop and (GetFocus <> Handle) and CanFocus then begin
SetFocus;
if (GetFocus <> Handle) then Exit;
end else
if TabStop and (GetFocus = Handle) and (OldFocus <> FocusedButton) then begin
Buttons[OldFocus].Invalidate;
Buttons[FocusedButton].Invalidate;
end;
end;
Procedure TExtDBNavigator.BtnClick(Index: TNavigateBtn);
begin
if (DataSource <> nil) and (DataSource.State <> dsInactive) then begin
if not (csDesigning in ComponentState) and Assigned(FBeforeAction) then
FBeforeAction(Self, Index);
with DataSource.DataSet do begin
case Index of
nbPrior: Prior;
nbRW: MoveBy(-FJump);
nbFF: MoveBy(Fjump);
nbNext: Next;
nbFirst: First;
nbLast: Last;
nbInsert: Insert;
nbEdit: Edit;
nbCancel: Cancel;
nbPost: Post;
nbRefresh: Refresh;
nbDelete:
begin
if not FConfirmDelete or
(MessageDlg (SDeleteRecordQuestion, mtConfirmation, mbOKCancel, 0) <> idCancel) then
Delete;
end;
nbMark:
begin
FBM:=GetBookMark;
Buttons[nbGoto].Enabled:=True;
end;
nbGoto:
begin
GotoBookMark(FBM);
FreeBookMark(FBM);
end;
end;
end;
end;
if not (csDesigning in ComponentState) and Assigned(FOnNavClick) then
FOnNavClick(Self, Index);
end;
Procedure TExtDBNavigator.WMSetFocus(var Message: TWMSetFocus);
begin
Buttons[FocusedButton].Invalidate;
end;
Procedure TExtDBNavigator.WMKillFocus(var Message: TWMKillFocus);
begin
Buttons[FocusedButton].Invalidate;
end;
Procedure TExtDBNavigator.KeyDown(var Key: Word; Shift: TShiftState);
var
NewFocus: TNavigateBtn;
OldFocus: TNavigateBtn;
begin
OldFocus := FocusedButton;
case Key of
VK_RIGHT:
begin
NewFocus := FocusedButton;
repeat
if NewFocus < High(Buttons) then NewFocus := Succ(NewFocus);
until (NewFocus=High(Buttons)) or (Buttons[NewFocus].Visible);
if NewFocus<>FocusedButton then begin
FocusedButton:=NewFocus;
Buttons[OldFocus].Invalidate;
Buttons[FocusedButton].Invalidate;
end;
end;
VK_LEFT:
begin
NewFocus := FocusedButton;
repeat
if NewFocus>Low(Buttons) then NewFocus:=Pred(NewFocus);
until (NewFocus=Low(Buttons)) or (Buttons[NewFocus].Visible);
if NewFocus<>FocusedButton then begin
FocusedButton := NewFocus;
Buttons[OldFocus].Invalidate;
Buttons[FocusedButton].Invalidate;
end;
end;
VK_SPACE: if Buttons[FocusedButton].Enabled then Buttons[FocusedButton].Click;
end;
end;
Procedure TExtDBNavigator.WMGetDlgCode(var Message: TWMGetDlgCode);
begin
Message.Result:=DLGC_WANTARROWS;
end;
Procedure TExtDBNavigator.DataChanged;
var UpEnable, DnEnable: Boolean;
begin
UpEnable:=Enabled and FDataLink.Active and not FDataLink.DataSet.BOF;
DnEnable:=Enabled and FDataLink.Active and not FDataLink.DataSet.EOF;
Buttons[nbFirst].Enabled:=UpEnable;
Buttons[nbPrior].Enabled:=UpEnable;
Buttons[nbNext].Enabled:=DnEnable;
Buttons[nbLast].Enabled:=DnEnable;
Buttons[nbDelete].Enabled:=Enabled and FDataLink.Active and
FDataLink.DataSet.CanModify and
not (FDataLink.DataSet.BOF and FDataLink.DataSet.EOF);
{Control New Buttons}
Buttons[nbFF].Enabled:=Buttons[nbNext].Enabled;
Buttons[nbRW].Enabled:=Buttons[nbPrior].Enabled;
if Assigned(DataSource) then begin
Buttons[nbMark].Enabled:=(DataSource.State=dsBrowse);
Buttons[nbGoto].Enabled:=(DataSource.State=dsBrowse);
end;
if not assigned(FBM) then Buttons[nbGoto].Enabled:=False;
end;
Procedure TExtDBNavigator.EditingChanged;
var CanModify: Boolean;
begin
CanModify:=Enabled and FDataLink.Active and FDataLink.DataSet.CanModify;
Buttons[nbInsert].Enabled:=CanModify;
Buttons[nbEdit].Enabled:=CanModify and not FDataLink.Editing;
Buttons[nbPost].Enabled:=CanModify and FDataLink.Editing;
Buttons[nbCancel].Enabled:=CanModify and FDataLink.Editing;
Buttons[nbRefresh].Enabled:=not (FDataLink.DataSet is TQuery);
{Control New Buttons}
if Assigned(DataSource) then begin
Buttons[nbMark].Enabled:=(DataSource.State=dsBrowse);
Buttons[nbGoto].Enabled:=(DataSource.State=dsBrowse);
end;
if not Assigned(FBM) then Buttons[nbGoto].Enabled:=False;
end;
Procedure TExtDBNavigator.ActiveChanged;
var I: TNavigateBtn;
begin
if not (Enabled and FDataLink.Active) then
for i:=Low(Buttons) to High(Buttons) do Buttons[i].Enabled:=False
else begin
DataChanged;
EditingChanged;
end;
end;
Procedure TExtDBNavigator.WMChangeControlSource(var Msg: TMessage);
var wSource, lSource: TDataSource;
begin
lSource:= TDataSource(Msg.lParam);
wSource:= TDataSource(Msg.wParam);
if Assigned(lSource) then begin
if wSource=DataSource then begin
FStoredControlSource:= DataSource;
DataSource:= lSource;
end;
end else begin
if wSource=FStoredControlSource then begin
DataSource:= FStoredControlSource;
FStoredControlSource:=nil;
end;
end;
end;
Procedure TExtDBNavigator.CMEnabledChanged(var Message: TMessage);
begin
Inherited;
if not (csLoading in ComponentState) then ActiveChanged;
end;
Procedure TExtDBNavigator.SetDataSource(Value: TDataSource);
begin
FDataLink.DataSource:=Value;
if not (csLoading in ComponentState) then ActiveChanged;
end;
Function TExtDBNavigator.GetDataSource: TDataSource;
begin
Result:=FDataLink.DataSource;
end;
Procedure TExtDBNavigator.ReadState(Reader: TReader);
var W, H: Integer;
begin
Inherited ReadState(Reader);
W:=Width;
H:=Height;
AdjustSize (W, H);
if (W<>Width) or (H<>Height) then Inherited SetBounds (Left, Top, W, H);
InitHints;
ActiveChanged;
end;
{
procedure TExtDBNavigator.Loaded;
var
W, H: Integer;
begin
inherited Loaded;
W := Width;
H := Height;
AdjustSize (W, H);
if (W <> Width) or (H <> Height) then
inherited SetBounds (Left, Top, W, H);
InitHints;
ActiveChanged;
end;
}
{TNavButton}
Destructor TNavButton.Destroy;
begin
if FRepeatTimer<>nil then FRepeatTimer.Free;
Inherited Destroy;
end;
Procedure TNavButton.MouseDown(Button: TMouseButton; Shift: TShiftState;
X, Y: Integer);
begin
Inherited MouseDown (Button, Shift, X, Y);
if nsAllowTimer in FNavStyle then begin
if FRepeatTimer=nil then FRepeatTimer := TTimer.Create(Self);
FRepeatTimer.OnTimer:=TimerExpired;
FRepeatTimer.Interval:=InitRepeatPause;
FRepeatTimer.Enabled:=True;
end;
end;
Procedure TNavButton.MouseUp(Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
Inherited MouseUp (Button, Shift, X, Y);
if FRepeatTimer<>nil then FRepeatTimer.Enabled := False;
end;
Procedure TNavButton.TimerExpired(Sender: TObject);
begin
FRepeatTimer.Interval := RepeatPause;
if (FState = bsDown) and MouseCapture then begin
try
Click;
except
FRepeatTimer.Enabled := False;
raise;
end;
end;
end;
Procedure TNavButton.Paint;
var R: TRect;
begin
Inherited Paint;
if (GetFocus=Parent.Handle) and (FIndex=TExtDBNavigator(Parent).FocusedButton) then begin
R:=Bounds(0, 0, Width, Height);
InflateRect(R, -3, -3);
if FState = bsDown then OffsetRect(R, 1, 1);
DrawFocusRect(Canvas.Handle, R);
end;
end;
{ TNavDataLink }
Constructor TNavDataLink.Create(ANav: TExtDBNavigator);
begin
Inherited Create;
FNavigator := ANav;
end;
Destructor TNavDataLink.Destroy;
begin
FNavigator:=nil;
Inherited Destroy;
end;
Procedure TNavDataLink.EditingChanged;
begin
if FNavigator<>nil then FNavigator.EditingChanged;
end;
Procedure TNavDataLink.DataSetChanged;
begin
if FNavigator<>nil then FNavigator.DataChanged;
end;
Procedure TNavDataLink.ActiveChanged;
begin
if FNavigator<>nil then FNavigator.ActiveChanged;
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/
Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
the specific language governing rights and limitations under the License.
Contributors to the SynEdit and mwEdit projects are listed in the
Contributors.txt file.
Alternatively, the contents of this file may be used under the terms of the
GNU General Public License Version 2 or later (the "GPL"), in which case
the provisions of the GPL are applicable instead of those above.
If you wish to allow use of your version of this file only under the terms
of the GPL and not to allow others to use your version of this file
under the MPL, indicate your decision by deleting the provisions above and
replace them with the notice and other provisions required by the GPL.
If you do not delete the provisions above, a recipient may use your version
of this file under either the MPL or the GPL.
Known Issues:
------------------------------------------------------------------------------- }
unit SynEditUndo;
{$I SynEdit.inc}
interface
uses
SynEdit,
SynEditTypes,
SynEditKeyCmds;
{ Factory Method}
function CreateSynEditUndo(Editor: TCustomSynEdit): ISynEditUndo;
implementation
uses
System.Classes,
System.SysUtils,
System.Math,
System.Generics.Collections,
Vcl.Controls,
SynEditTextBuffer;
type
TSynUndoItem = class abstract(TObject)
ChangeNumber: Integer;
FCaret: TBufferCoord;
GroupBreak: Boolean;
public
procedure Undo(Editor: TCustomSynEdit); virtual; abstract;
procedure Redo(Editor: TCustomSynEdit); virtual; abstract;
end;
TSynLinePutUndoItem = class(TSynUndoItem)
private
FIndex: Integer;
FStartPos: Integer;
FOldValue: string;
FNewValue: string;
FChangeFlags: TSynLineChangeFlags;
FCommandProcessed: TSynEditorCommand;
public
function GroupWith(Item:TSynLinePutUndoItem): Boolean;
procedure Undo(Editor: TCustomSynEdit); override;
procedure Redo(Editor: TCustomSynEdit); override;
constructor Create(Editor: TCustomSynEdit; Index: Integer; OldLine: string;
Command: TSynEditorCommand);
end;
TSynLinesInsertedUndoItem = class(TSynUndoItem)
private
FIndex: Integer;
FLines: TArray<string>;
FChangeFlags: TArray<TSynLineChangeFlags>;
public
procedure Undo(Editor: TCustomSynEdit); override;
procedure Redo(Editor: TCustomSynEdit); override;
constructor Create(Editor: TCustomSynEdit; Index, Count: Integer);
end;
TSynLinesDeletedUndoItem = class(TSynUndoItem)
private
FIndex: Integer;
FLines: TArray<string>;
FChangeFlags: TArray<TSynLineChangeFlags>;
public
procedure Undo(Editor: TCustomSynEdit); override;
procedure Redo(Editor: TCustomSynEdit); override;
constructor Create(Editor: TCustomSynEdit; Index: Integer; DeletedLines:
TArray<string>; DeletedChangeFlags: TArray<TSynLineChangeFlags>);
end;
TSynCaretAndSelectionUndoItem = class(TSynUndoItem)
private
FBlockBegin: TBufferCoord;
FBlockEnd: TBufferCoord;
public
procedure Undo(Editor: TCustomSynEdit); override;
procedure Redo(Editor: TCustomSynEdit); override;
constructor Create(Editor: TCustomSynEdit);
end;
TSynEditUndo = class;
TSynUndoPlugin = class(TSynEditPlugin)
private
FSynEditUndo: TSynEditUndo;
FDeletedLines: TArray<string>;
FDeletedChangeFlags: TArray<TSynLineChangeFlags>;
protected
procedure LinesInserted(FirstLine, Count: Integer); override;
procedure LinesBeforeDeleted(FirstLine, Count: Integer); override;
procedure LinesDeleted(FirstLine, Count: Integer); override;
procedure LinePut(aIndex: Integer; const OldLine: string); override;
public
constructor Create(SynEditUndo: TSynEditUndo; Editor: TCustomSynEdit);
end;
TSynEditUndoList = class(TObjectStack<TSynUndoItem>)
protected
FOwner: TSynEditUndo;
FFullUndoImposible: Boolean;
procedure EnsureMaxEntries;
public
constructor Create(Owner: TSynEditUndo);
procedure Push(const Value: TSynUndoItem);
end;
TSynEditUndo = class(TInterfacedObject, ISynEditUndo)
private
FPlugin: TSynUndoPlugin;
FGroupUndo: Boolean;
FBlockCount: Integer;
FLockCount: Integer;
FBlockChangeNumber: Integer;
FNextChangeNumber: Integer;
FInitialChangeNumber: Integer;
FMaxUndoActions: Integer;
FBlockStartModified: Boolean;
FUndoList: TSynEditUndoList;
FRedoList: TSynEditUndoList;
FOnModifiedChanged: TNotifyEvent;
FInsideUndoRedo: Boolean;
FCommandProcessed: TSynEditorCommand;
FBlockSelRestoreItem: TSynUndoItem;
function GetModified: Boolean;
function GetCanUndo: Boolean;
function GetCanRedo: Boolean;
function GetFullUndoImposible: Boolean;
function GetOnModifiedChanged: TNotifyEvent;
procedure SetModified(const Value: Boolean);
procedure SetCommandProcessed(const Command: TSynEditorCommand);
procedure SetMaxUndoActions(const Value: Integer);
procedure SetOnModifiedChanged(const Value: TNotifyEvent);
procedure SetGroupUndo(const Value: Boolean);
function GetMaxUndoActions: Integer;
procedure BeginBlock(Editor: TControl);
procedure EndBlock(Editor: TControl);
procedure Lock;
procedure Unlock;
function IsLocked: Boolean;
procedure Clear;
procedure Undo(Editor: TControl);
procedure Redo(Editor: TControl);
procedure BufferSaved(Lines: TStrings);
procedure ClearTrackChanges(Lines: TStrings);
function NextChangeNumber: Integer;
procedure AddGroupBreak;
procedure AddUndoItem(Item: TSynUndoItem);
public
constructor Create(Editor: TCustomSynEdit);
destructor Destroy; override;
end;
{ TSynEditUndoList }
constructor TSynEditUndoList.Create(Owner: TSynEditUndo);
begin
inherited Create(True);
FOwner := Owner;
end;
procedure TSynEditUndoList.EnsureMaxEntries;
var
KeepCount: Integer;
ItemArray: TArray<TSynUndoItem>;
I: Integer;
begin
if FOwner.FMaxUndoActions <= 0 then Exit;
if Count > FOwner.FMaxUndoActions then
begin
FFullUndoImposible := True;
KeepCount := (FOwner.FMaxUndoActions div 4) * 3;
ItemArray := ToArray;
for I := 1 to KeepCount do
Extract;
Clear; // Destroys remaining items
for I := Length(ItemArray) - KeepCount to Length(ItemArray) - 1 do
Push(ItemArray[I]);
end;
end;
procedure TSynEditUndoList.Push(const Value: TSynUndoItem);
begin
inherited Push(Value);
EnsureMaxEntries;
end;
{ TSynEditUndo }
procedure TSynEditUndo.AddUndoItem(Item: TSynUndoItem);
var
OldModified: Boolean;
begin
Assert(not FInsideUndoRedo);
OldModified := GetModified;
if FBlockChangeNumber <> 0 then
Item.ChangeNumber := FBlockChangeNumber
else
Item.ChangeNumber := NextChangeNumber;
FUndoList.Push(Item);
FRedoList.Clear;
// Do not sent unnecessary notifications
if (FBlockCount = 0) and (OldModified xor GetModified) and
Assigned(FOnModifiedChanged)
then
FOnModifiedChanged(Self);
end;
procedure TSynEditUndo.AddGroupBreak;
begin
if (FUndoList.Count > 0) and (FBlockCount = 0) then
FUndoList.Peek.GroupBreak := True;
end;
procedure TSynEditUndo.BeginBlock(Editor: TControl);
begin
Inc(FBlockCount);
if FBlockCount = 1 then // it was 0
begin
FBlockStartModified := GetModified;
FBlockChangeNumber := NextChangeNumber;
// So that position is restored after Redo
FBlockSelRestoreItem := TSynCaretAndSelectionUndoItem.Create(Editor as TCustomSynEdit);
FBlockSelRestoreItem.ChangeNumber := FBlockChangeNumber;
FUndoList.Push(FBlockSelRestoreItem);
end;
end;
procedure TSynEditUndo.BufferSaved(Lines: TStrings);
procedure PutItemSaved(Item: TSynLinePutUndoItem);
begin
if Item.FChangeFlags = [sfAsSaved] then
Item.FChangeFlags := [sfModified];
end;
procedure InsertedItemSaved(Item: TSynLinesInsertedUndoItem);
var
I: Integer;
begin
for I := 0 to Length(Item.FChangeFlags) - 1 do
Item.FChangeFlags[I] := [sfModified];
end;
procedure DeletedItemSaved(Item: TSynLinesDeletedUndoItem);
var
I: Integer;
begin
for I := 0 to Length(Item.FChangeFlags) - 1 do
Item.FChangeFlags[I] := [sfModified];
end;
var
SynLines: TSynEditStringList;
Index: Integer;
Flags: TSynLineChangeFlags;
Item: TSynUndoItem;
begin
SynLines := Lines as TSynEditStringList;
// First change the flags of TSynEditStringList
for Index := 0 to SynLines.Count - 1 do
begin
Flags := SynLines.ChangeFlags[Index];
if Flags = [sfSaved] then
// original line saved and then restored
SynLines.ChangeFlags[Index] := []
else if sfModified in Flags then
SynLines.ChangeFlags[Index] := Flags - [sfModified] + [sfSaved, sfAsSaved];
end;
// Then modify the Undo/Redo lists
for Item in FUndoList do
if Item is TSynLinePutUndoItem then
PutItemSaved(TSynLinePutUndoItem(Item))
else if Item is TSynLinesInsertedUndoItem then
InsertedItemSaved(TSynLinesInsertedUndoItem(Item))
else if Item is TSynLinesDeletedUndoItem then
DeletedItemSaved(TSynLinesDeletedUndoItem(Item));
for Item in FRedoList do
if Item is TSynLinePutUndoItem then
PutItemSaved(TSynLinePutUndoItem(Item))
else if Item is TSynLinesInsertedUndoItem then
InsertedItemSaved(TSynLinesInsertedUndoItem(Item))
else if Item is TSynLinesDeletedUndoItem then
DeletedItemSaved(TSynLinesDeletedUndoItem(Item));
end;
procedure TSynEditUndo.Clear;
begin
FUndoList.Clear;
FRedoList.Clear;
end;
procedure TSynEditUndo.ClearTrackChanges(Lines: TStrings);
procedure InsertedItemClear(Item: TSynLinesInsertedUndoItem);
var
I: Integer;
begin
for I := 0 to Length(Item.FChangeFlags) - 1 do
Item.FChangeFlags[I] := [sfModified];
end;
procedure DeletedItemClear(Item: TSynLinesDeletedUndoItem);
var
I: Integer;
begin
for I := 0 to Length(Item.FChangeFlags) - 1 do
Item.FChangeFlags[I] := [sfModified];
end;
var
SynLines: TSynEditStringList;
Index: Integer;
Item: TSynUndoItem;
begin
SynLines := Lines as TSynEditStringList;
// First change the flags of TSynEditStringList
for Index := 0 to SynLines.Count - 1 do
SynLines.ChangeFlags[Index] := [];
// Then modify the Undo/Redo lists
for Item in FUndoList do
if Item is TSynLinesInsertedUndoItem then
InsertedItemClear(TSynLinesInsertedUndoItem(Item))
else if Item is TSynLinesDeletedUndoItem then
DeletedItemClear(TSynLinesDeletedUndoItem(Item));
for Item in FRedoList do
if Item is TSynLinesInsertedUndoItem then
InsertedItemClear(TSynLinesInsertedUndoItem(Item))
else if Item is TSynLinesDeletedUndoItem then
DeletedItemClear(TSynLinesDeletedUndoItem(Item));
end;
constructor TSynEditUndo.Create(Editor: TCustomSynEdit);
begin
inherited Create;
FGroupUndo := True;
FMaxUndoActions := 0;
FNextChangeNumber := 1;
FUndoList := TSynEditUndoList.Create(Self);
FRedoList := TSynEditUndoList.Create(Self);
FPlugin := TSynUndoPlugin.Create(Self, Editor);
end;
destructor TSynEditUndo.Destroy;
begin
FUndoList.Free;
FRedoList.Free;
inherited;
end;
procedure TSynEditUndo.EndBlock(Editor: TControl);
var
Item: TSynCaretAndSelectionUndoItem;
begin
Assert(FBlockCount > 0);
if FBlockCount > 0 then
begin
Dec(FBlockCount);
if FBlockCount = 0 then
begin
if FUndoList.Peek = FBlockSelRestoreItem then
// No undo items added from BlockBegin to BlockEnd
FUndoList.Pop
else
begin
// So that position is restored after Redo
Item := TSynCaretAndSelectionUndoItem.Create(Editor as TCustomSynEdit);
Item.ChangeNumber := FBlockChangeNumber;
FUndoList.Push(Item);
end;
FBlockChangeNumber := 0;
AddGroupBreak;
if FBlockStartModified xor GetModified and Assigned(FOnModifiedChanged) then
FOnModifiedChanged(Self);
end;
end;
end;
function TSynEditUndo.GetCanUndo: Boolean;
begin
Result := FUndoList.Count > 0;
end;
function TSynEditUndo.GetFullUndoImposible: Boolean;
begin
Result := FUndoList.FFullUndoImposible;
end;
function TSynEditUndo.GetMaxUndoActions: Integer;
begin
Result := FMaxUndoActions;
end;
function TSynEditUndo.GetModified: Boolean;
begin
if FUndoList.Count = 0 then
Result := FInitialChangeNumber <> 0
else
Result := FUndoList.Peek.ChangeNumber <> FInitialChangeNumber;
end;
function TSynEditUndo.GetOnModifiedChanged: TNotifyEvent;
begin
Result := FOnModifiedChanged;
end;
function TSynEditUndo.IsLocked: Boolean;
begin
Result := FLockCount > 0;
end;
function TSynEditUndo.GetCanRedo: Boolean;
begin
Result := FRedoList.Count > 0;
end;
procedure TSynEditUndo.Lock;
begin
Inc(FLockCount);
end;
function TSynEditUndo.NextChangeNumber: Integer;
begin
Result := FNextChangeNumber;
Inc(FNextChangeNumber);
end;
procedure TSynEditUndo.Redo(Editor: TControl);
var
Item, LastItem: TSynUndoItem;
OldChangeNumber: Integer;
OldModified: Boolean;
FKeepGoing: Boolean;
LastItemHasGroupBreak: Boolean;
begin
Assert((FBlockCount = 0) and (FBlockChangeNumber = 0));
if FRedoList.Count > 0 then
begin
Item := FRedoList.Peek;
OldModified := GetModified;
OldChangeNumber := Item.ChangeNumber;
repeat
Item := FRedoList.Extract;
LastItemHasGroupBreak := Item.GroupBreak;
LastItem := Item;
FInsideUndoRedo := True;
try
Item.Redo(Editor as TCustomSynEdit);
finally
FInsideUndoRedo := False;
end;
// Move it to the UndoList
FUndoList.Push(Item);
if FRedoList.Count = 0 then
Break
else
Item := FRedoList.Peek;
if Item.ChangeNumber = OldChangeNumber then
FKeepGoing := True
else
FKeepGoing :=
FGroupUndo and
{ Last Item had a group break - Stop redoing }
not LastItemHasGroupBreak and
{ Group together same undo actions }
(LastItem is TSynLinePutUndoItem) and
(Item is TSynLinePutUndoItem) and
TSynLinePutUndoItem(LastItem).GroupWith(TSynLinePutUndoItem(Item));
until not(FKeepGoing);
if not (Item is TSynCaretAndSelectionUndoItem) then
(Editor as TCustomSynEdit).CaretXY := Item.FCaret; // removes selection
if (OldModified xor GetModified) and Assigned(FOnModifiedChanged) then
FOnModifiedChanged(Self);
end;
end;
procedure TSynEditUndo.SetCommandProcessed(const Command: TSynEditorCommand);
begin
FCommandProcessed := Command;
end;
procedure TSynEditUndo.SetGroupUndo(const Value: Boolean);
begin
FGroupUndo := Value;
end;
procedure TSynEditUndo.SetMaxUndoActions(const Value: Integer);
begin
if Value <> FMaxUndoActions then
begin
FMaxUndoActions := Value;
FUndoList.EnsureMaxEntries;
FRedoList.EnsureMaxEntries;
end;
end;
procedure TSynEditUndo.SetModified(const Value: Boolean);
begin
if not Value then
begin
if FUndoList.Count = 0 then
FInitialChangeNumber := 0
else
FInitialChangeNumber := FUndoList.Peek.ChangeNumber;
end
else if FUndoList.Count = 0 then
begin
if FInitialChangeNumber = 0 then
FInitialChangeNumber := -1;
end
else if FUndoList.Peek.ChangeNumber = FInitialChangeNumber then
FInitialChangeNumber := -1
end;
procedure TSynEditUndo.SetOnModifiedChanged(const Value: TNotifyEvent);
begin
FOnModifiedChanged := Value;
end;
procedure TSynEditUndo.Undo(Editor: TControl);
var
Item, LastItem: TSynUndoItem;
OldChangeNumber: Integer;
OldModified: Boolean;
FKeepGoing: Boolean;
begin
Assert((FBlockCount = 0) and (FBlockChangeNumber = 0));
if FUndoList.Count > 0 then
begin
Item := FUndoList.Peek;
OldModified := GetModified;
OldChangeNumber := Item.ChangeNumber;
repeat
Item := FUndoList.Extract;
LastItem := Item;
FInsideUndoRedo := True;
try
Item.Undo(Editor as TCustomSynEdit);
finally
FInsideUndoRedo := False;
end;
// Move it to the RedoList
FRedoList.Push(Item);
if FUndoList.Count = 0 then
Break
else
Item := FUndoList.Peek;
if Item.ChangeNumber = OldChangeNumber then
FKeepGoing := True
else
FKeepGoing :=
FGroupUndo and
{ Last Item had a group break - Stop redoing }
not Item.GroupBreak and
{ Group together same undo actions }
(LastItem is TSynLinePutUndoItem) and
(Item is TSynLinePutUndoItem) and
TSynLinePutUndoItem(Item).GroupWith(TSynLinePutUndoItem(LastItem));
until not(FKeepGoing);
if not (LastItem is TSynCaretAndSelectionUndoItem) then
(Editor as TCustomSynEdit).SetCaretAndSelection(LastItem.FCaret, LastItem.FCaret,
LastItem.FCaret);
if (OldModified xor GetModified) and Assigned(FOnModifiedChanged) then
FOnModifiedChanged(Self);
end;
end;
procedure TSynEditUndo.Unlock;
begin
if FLockCount > 0 then
Dec(FLockCount);
end;
{ Factory Method}
function CreateSynEditUndo(Editor: TCustomSynEdit): ISynEditUndo;
begin
Result := TSynEditUndo.Create(Editor);
end;
{ TSynCaretAndSelectionUndoItem }
constructor TSynCaretAndSelectionUndoItem.Create(Editor: TCustomSynEdit);
begin
inherited Create;
FCaret := Editor.CaretXY;
FBlockBegin := Editor.BlockBegin;
FBlockEnd := Editor.BlockEnd;
end;
procedure TSynCaretAndSelectionUndoItem.Redo(Editor: TCustomSynEdit);
begin
// Same as Undo
Editor.SetCaretAndSelection(FCaret, FBlockBegin, FBlockEnd);
end;
procedure TSynCaretAndSelectionUndoItem.Undo(Editor: TCustomSynEdit);
begin
Editor.SetCaretAndSelection(FCaret, FBlockBegin, FBlockEnd);
end;
{ TSynLinesDeletedUndoItem }
constructor TSynLinesDeletedUndoItem.Create(Editor: TCustomSynEdit; Index:
Integer; DeletedLines: TArray<string>; DeletedChangeFlags:
TArray<TSynLineChangeFlags>);
begin
inherited Create;
FIndex := Index;
FLines := DeletedLines;
FChangeFlags := DeletedChangeFlags;
end;
procedure TSynLinesDeletedUndoItem.Redo(Editor: TCustomSynEdit);
var
I: Integer;
begin
// Save change flags
SetLength(FChangeFlags, Length(FLines));
for I := 0 to Length(FLines) - 1 do
FChangeFlags[I] := TSynEditStringList(Editor.Lines).ChangeFlags[FIndex + I];
TSynEditStringList(Editor.Lines).DeleteLines(FIndex, Length(FLines));
FCaret := BufferCoord(1, FIndex + 1);
end;
procedure TSynLinesDeletedUndoItem.Undo(Editor: TCustomSynEdit);
var
I: Integer;
begin
TSynEditStringList(Editor.Lines).InsertStrings(FIndex, FLines);
// Restore change flags
for I := 0 to Length(FLines) - 1 do
TSynEditStringList(Editor.Lines).ChangeFlags[FIndex + I] := FChangeFlags[I];
FCaret := BufferCoord(1,
Min(Editor.Lines.Count, FIndex + Length(FLines) + 1));
end;
{ TSynLinesInsertedUndoItem }
constructor TSynLinesInsertedUndoItem.Create(Editor: TCustomSynEdit; Index,
Count: Integer);
var
I: Integer;
begin
inherited Create;
FIndex := Index;
SetLength(FLines, Count);
for I := 0 to Count - 1 do
begin
FLines[I] := Editor.Lines[Index + I];
// Mark the lines modified
TSynEditStringList(Editor.Lines).ChangeFlags[Index + I] := [sfModified];
end;
end;
procedure TSynLinesInsertedUndoItem.Redo(Editor: TCustomSynEdit);
var
I: Integer;
begin
TSynEditStringList(Editor.Lines).InsertStrings(FIndex, FLines);
// Restore change flags
for I := 0 to Length(FLines) - 1 do
TSynEditStringList(Editor.Lines).ChangeFlags[FIndex + I] := FChangeFlags[I];
FCaret := BufferCoord(1,
Min(Editor.Lines.Count, FIndex + Length(FLines) + 1));
end;
procedure TSynLinesInsertedUndoItem.Undo(Editor: TCustomSynEdit);
var
I: Integer;
begin
// Save change flags
SetLength(FChangeFlags, Length(FLines));
for I := 0 to Length(FLines) - 1 do
FChangeFlags[I] := TSynEditStringList(Editor.Lines).ChangeFlags[FIndex + I];
TSynEditStringList(Editor.Lines).DeleteLines(FIndex, Length(FLines));
FCaret := BufferCoord(1, FIndex + 1);
end;
{ TSynLinePutUndoItem }
function TSynLinePutUndoItem.GroupWith(Item: TSynLinePutUndoItem): Boolean;
begin
if (FNewValue.Length = Item.FNewValue.Length) and
(FOldValue.Length = Item.FOldValue.Length) and
(FOldValue.Length <= 1) and (FNewValue.Length <= 1) and
(Abs(FStartPos - Item.FStartPos) <= 1)
then
Result := True
else
Result := False;
end;
constructor TSynLinePutUndoItem.Create(Editor: TCustomSynEdit; Index: Integer;
OldLine: string; Command: TSynEditorCommand);
var
Len1, Len2: Integer;
Line: string;
begin
FCommandProcessed := Command;
FIndex := Index;
Line := Editor.Lines[Index];
Len1 := OldLine.Length;
Len2 := Line.Length;
// Compare from start
FStartPos := 1;
while (Len1 > 0) and (Len2 > 0) and (OldLine[FStartPos] = Line[FStartPos]) do
begin
Dec(Len1);
Dec(Len2);
Inc(FStartPos);
end;
// Compare from end
while (Len1 > 0) and (Len2 > 0) and
(OldLine[Len1 + FStartPos - 1] = Line[len2 + FStartPos - 1]) do
begin
Dec(len1);
Dec(len2);
end;
FOldValue := Copy(OldLine, FStartPos, Len1);
FNewValue := Copy(Line, FStartPos, Len2);
FChangeFlags := TSynEditStringList(Editor.Lines).ChangeFlags[Index] -
[sfSaved];
TSynEditStringList(Editor.Lines).ChangeFlags[Index] :=
TSynEditStringList(Editor.Lines).ChangeFlags[Index] +
[sfModified] - [sfAsSaved];
end;
procedure TSynLinePutUndoItem.Redo(Editor: TCustomSynEdit);
var
Line: string;
Char: Integer;
TempCF: TSynLineChangeFlags;
begin
Line := Editor.Lines[FIndex];
// Delete New
Delete(Line, FStartPos, FOldValue.Length);
Insert(FNewValue, Line, FStartPos);
Editor.Lines[FIndex] := Line;
// Swap change flags
TempCF := FChangeFlags;
FChangeFlags := TSynEditStringList(Editor.Lines).ChangeFlags[FIndex] -
[sfSaved];
TSynEditStringList(Editor.Lines).ChangeFlags[FIndex] :=
TSynEditStringList(Editor.Lines).ChangeFlags[FIndex]
- [sfModified, sfAsSaved] + TempCF;
// Guess Caret position
case FCommandProcessed of
ecChar:
if (FOldValue.Length = 1) and (FNewValue.Length = 1) then
Char := FStartPos // Typing in Insert Mode
else
Char := FStartPos + FNewValue.Length;
ecDeleteChar,
ecDeleteWord,
ecDeleteEOL: Char := FStartPos;
else
Char := FStartPos + FNewValue.Length;
end;
FCaret := BufferCoord(Char, FIndex + 1);
end;
procedure TSynLinePutUndoItem.Undo(Editor: TCustomSynEdit);
var
Line: string;
Char: Integer;
TempCF: TSynLineChangeFlags;
begin
Line := Editor.Lines[FIndex];
// Delete New
Delete(Line, FStartPos, FNewValue.Length);
Insert(FOldValue, Line, FStartPos);
Editor.Lines[FIndex] := Line;
// Swap change flags
TempCF := FChangeFlags;
FChangeFlags := TSynEditStringList(Editor.Lines).ChangeFlags[FIndex] -
[sfSaved];
TSynEditStringList(Editor.Lines).ChangeFlags[FIndex] :=
TSynEditStringList(Editor.Lines).ChangeFlags[FIndex]
- [sfModified, sfAsSaved] + TempCF;
// Guess Caret position
case FCommandProcessed of
ecChar:
if (FOldValue.Length = 1) and (FNewValue.Length = 1) then
Char := FStartPos // Typing in Insert Mode
else
Char := FStartPos + FOldValue.Length;
ecDeleteChar,
ecDeleteWord,
ecDeleteEOL: Char := FStartPos;
else
Char := FStartPos + FOldValue.Length;
end;
FCaret := BufferCoord(Char, FIndex + 1);
end;
{ TSynUndoPlugin }
constructor TSynUndoPlugin.Create(SynEditUndo: TSynEditUndo;
Editor: TCustomSynEdit);
begin
FSynEditUndo := SynEditUndo;
inherited Create(Editor,
[phLinePut, phLinesInserted, phLinesBeforeDeleted, phLinesDeleted]);
end;
procedure TSynUndoPlugin.LinePut(aIndex: Integer; const OldLine: string);
var
Line: string;
Item: TSynLinePutUndoItem;
begin
if Editor.IsChained or FSynEditUndo.IsLocked or FSynEditUndo.FInsideUndoRedo
then
Exit;
Line := Editor.Lines[aIndex];
if Line <> OldLine then
begin
Item := TSynLinePutUndoItem.Create(Editor, aIndex, OldLine,
FSynEditUndo.FCommandProcessed);
FSynEditUndo.AddUndoItem(Item);
end;
end;
procedure TSynUndoPlugin.LinesBeforeDeleted(FirstLine, Count: Integer);
var
I: Integer;
begin
if Editor.IsChained or FSynEditUndo.IsLocked or FSynEditUndo.FInsideUndoRedo
then
Exit;
// Save deleted lines and change flags
SetLength(FDeletedLines, Count);
SetLength(FDeletedChangeFlags, Count);
for I := 0 to Count -1 do
begin
FDeletedLines[I] := Editor.Lines[FirstLine + I];
FDeletedChangeFlags[I] :=
TSynEditStringList(Editor.Lines).ChangeFlags[FirstLine + I];
end;
end;
procedure TSynUndoPlugin.LinesDeleted(FirstLine, Count: Integer);
var
Item: TSynLinesDeletedUndoItem;
begin
if Editor.IsChained or FSynEditUndo.IsLocked or FSynEditUndo.FInsideUndoRedo
then
Exit;
if Count > 0 then
begin
Item := TSynLinesDeletedUndoItem.Create(Editor, FirstLine,
FDeletedLines, FDeletedChangeFlags);
FSynEditUndo.AddUndoItem(Item);
end;
end;
procedure TSynUndoPlugin.LinesInserted(FirstLine, Count: Integer);
var
Item: TSynLinesInsertedUndoItem;
begin
if Editor.IsChained or FSynEditUndo.IsLocked or FSynEditUndo.FInsideUndoRedo
then
Exit;
// Consider a file with one empty line as empty
// Otherwise when you type in a new file and undo it, CanUndo will still
// return True because the initial insertion will be on the Undo list
if (FSynEditUndo.FUndoList.Count = 0) and
(Editor.Lines.Count = 1) and (Editor.Lines[0] = '')
then
Exit;
if Count > 0 then
begin
Item := TSynLinesInsertedUndoItem.Create(Editor, FirstLine, Count);
FSynEditUndo.AddUndoItem(Item);
end;
end;
end.
|
unit uMain;
{$IFDEF FPC}
{$mode objfpc}{$H+}
{$ENDIF}
interface
uses
{$IFDEF FPC}
LResources,
{$ENDIF}
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, Buttons,
ACS_Audio, ACS_File, ACS_Classes, ACS_Allformats, ExtCtrls, StdCtrls,
ComCtrls, uPlaylist, ACS_Indicator, uvis
//You must include Output drivers to not get an "No drier selected" exception
{$IFDEF WINDOWS}
{$IFDEF DIRECTX_ENABLED}
,ACS_DXAudio //DirectSound Driver
{$ENDIF}
{$ELSE}
,acs_alsaaudio //Alsa Driver
// ,ACS_AOLive //AO Live Driver
{$ENDIF}
,acs_stdaudio //Wavemapper Driver
;
type
TTimeFormat = (tfElapsed,tfRemain);
{ TfMain }
TfMain = class(TForm)
AudioOut1: TACSAudioOut;
btVizu: TBitBtn;
btPlaylist: TBitBtn;
btPause: TBitBtn;
btRew: TBitBtn;
btFfw: TBitBtn;
btPlay: TBitBtn;
btStop: TBitBtn;
btOpen: TBitBtn;
FileIn1: TACSFileIn;
lLeft: TLabel;
lFilename: TLabel;
lTime: TLabel;
OpenDialog1: TOpenDialog;
Panel1: TPanel;
Progress: TProgressBar;
PlayTimer: TTimer;
lTime1: TLabel;
lTime2: TLabel;
SoundIndicator: TACSSoundIndicator;
procedure AudioOut1Done(Sender: TComponent);
procedure AudioOut1ThreadException(Sender: TComponent; E: Exception);
procedure FormClose(Sender: TObject; var CloseAction: TCloseAction);
procedure FormCreate(Sender: TObject);
procedure Pauseclick(Sender: TObject);
procedure PlayClick(Sender: TObject);
procedure StopClick(Sender: TObject);
procedure OpenClick(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
procedure btFfwClick(Sender: TObject);
procedure btPlaylistClick(Sender: TObject);
procedure btRewClick(Sender: TObject);
procedure btVizuClick(Sender: TObject);
procedure lTime1Click(Sender: TObject);
procedure resetDisplay;
private
{ private declarations }
FPaused : Boolean;
FStopped : Boolean;
TimeFormat : TTimeFormat;
public
{ public declarations }
end;
var
fMain: TfMain;
implementation
{ TfMain }
procedure TfMain.PlayClick(Sender: TObject);
begin
if FPaused then
begin
AudioOut1.Resume;
FPaused := False;
end
else
begin
if FileIn1.FileName = '' then
begin
if fPlaylist.lbPlaylist.Items.Count = 0 then exit;
if fPlaylist.lbPlaylist.ItemIndex = -1 then
fPlayList.lbPlaylist.ItemIndex := 0;
FileIn1.FileName := fPlayList.lbPlaylist.Items[fPlayList.lbPlaylist.ItemIndex];
lFilename.Caption := Format('File:%s',[ExtractFileName(FileIn1.FileName)]);
end;
AudioOut1.Run;
end;
FStopped := False;
btPlay.Enabled := False;
btStop.Enabled := True;
btOpen.Enabled := False;
btRew.Enabled := False;
btFfw.Enabled := False;
btPause.Enabled := True;
PlayTimer.Enabled := True;
end;
procedure TfMain.AudioOut1Done(Sender: TComponent);
begin
btPlay.Enabled := True;
btStop.Enabled := False;
btOpen.Enabled := True;
btRew.Enabled := True;
btFfw.Enabled := True;
PlayTimer.Enabled := false;
ResetDisplay;
if FStopped then
exit;
if fPlaylist.lbPlaylist.Items.Count = 0 then exit;
if fPlaylist.lbPlaylist.ItemIndex = -1 then
fPlayList.lbPlaylist.ItemIndex := 0;
FileIn1.FileName := fPlayList.lbPlaylist.Items[fPlayList.lbPlaylist.ItemIndex];
if fPlayList.lbPlaylist.Items.Count-1 > fPlayList.lbPlaylist.ItemIndex then
begin
fPlayList.lbPlaylist.ItemIndex := fPlayList.lbPlaylist.ItemIndex+1;
FileIn1.FileName := fPlayList.lbPlaylist.Items[fPlayList.lbPlaylist.ItemIndex];
lFilename.Caption := Format('File:%s',[ExtractFileName(FileIn1.FileName)]);
PlayClick(nil);
end;
end;
procedure TfMain.AudioOut1ThreadException(Sender: TComponent; E: Exception);
begin
ShowMessage(E.Message);
end;
procedure TfMain.FormClose(Sender: TObject; var CloseAction: TCloseAction);
begin
FStopped := True;
if (AudioOut1.Status <> tosIdle) then
AudioOut1.Stop;
while (AudioOut1.Status <> tosIdle) and (AudioOut1.Status <> tosUndefined) do
Application.Processmessages;
end;
procedure TfMain.FormCreate(Sender: TObject);
begin
// AudioOut1.Driver := 'Alsa';
end;
procedure TfMain.Pauseclick(Sender: TObject);
begin
if FPaused then
exit;
AudioOut1.Pause;
FPaused := True;
btPause.Enabled := False;
btPlay.Enabled := True;
PlayTimer.Enabled := False;
end;
procedure TfMain.StopClick(Sender: TObject);
begin
FStopped := True;
AudioOut1.Stop;
end;
procedure TfMain.OpenClick(Sender: TObject);
begin
if OpenDialog1.Execute then
begin
FileIn1.FileName:=OpenDialog1.FileName;
btPlay.Enabled := True;
ResetDisplay;
end;
end;
procedure TfMain.Timer1Timer(Sender: TObject);
var
tmp : real;
begin
if FileIn1.Size<=0 then exit;
case TimeFormat of
tfElapsed:
begin
tmp := ((FileIn1.Position * FileIn1.TotalTime) / FileIn1.Size);
lTime.Caption := Format('%.2d:%.2d:%.2d',[round((tmp-30) / 60) mod 120,round(tmp) mod 60,round(tmp*100) mod 100]);
tmp := FileIn1.TotalTime-((FileIn1.Position * FileIn1.TotalTime) / FileIn1.Size);
lLeft.Caption := Format('%.2d:%.2d:%.2d',[round((tmp-30) / 60) mod 120,round(tmp) mod 60,round(tmp*100) mod 100]);
lTime1.Caption := 'Time elapsed';
lTime2.Caption := 'left';
end;
tfRemain:
begin
tmp := ((FileIn1.Position * FileIn1.TotalTime) / FileIn1.Size);
lLeft.Caption := Format('%.2d:%.2d:%.2d',[round((tmp-30) / 60) mod 120,round(tmp) mod 60,round(tmp*100) mod 100]);
tmp := FileIn1.TotalTime-((FileIn1.Position * FileIn1.TotalTime) / FileIn1.Size);
lTime.Caption := Format('%.2d:%.2d:%.2d',[round((tmp-30) / 60) mod 120,round(tmp) mod 60,round(tmp*100) mod 100]);
lTime1.Caption := 'Time remain';
lTime2.Caption := 'elapsed';
end;
end;
Progress.Position := round((FileIn1.Position * 100) / FileIn1.Size);
end;
procedure TfMain.btFfwClick(Sender: TObject);
begin
if fPlayList.lbPlaylist.Items.Count-1 > fPlayList.lbPlaylist.ItemIndex then
fPlayList.lbPlaylist.ItemIndex := fPlayList.lbPlaylist.ItemIndex+1;
FileIn1.FileName := fPlayList.lbPlaylist.Items[fPlayList.lbPlaylist.ItemIndex];
ResetDisplay;
end;
procedure TfMain.btPlaylistClick(Sender: TObject);
begin
fPlaylist.Visible := True;
end;
procedure TfMain.btRewClick(Sender: TObject);
begin
if fPlayList.lbPlaylist.ItemIndex >= 1 then
fPlayList.lbPlaylist.ItemIndex := fPlayList.lbPlaylist.ItemIndex-1;
FileIn1.FileName := fPlayList.lbPlaylist.Items[fPlayList.lbPlaylist.ItemIndex];
ResetDisplay;
end;
procedure TfMain.btVizuClick(Sender: TObject);
begin
fVizu.Show;
end;
procedure TfMain.lTime1Click(Sender: TObject);
begin
case TimeFormat of
tfElapsed:TimeFormat := tfRemain;
tfRemain:TimeFormat := tfElapsed;
end;
ResetDisplay;
end;
procedure TfMain.resetDisplay;
var
tmp : real;
begin
lFilename.Caption := Format('File:%s',[ExtractFileName(FileIn1.FileName)]);
case TimeFormat of
tfElapsed:
begin
tmp := 0;
// if FileIn1.Size > 0 then
// tmp := ((FileIn1.Position * FileIn1.TotalTime) / FileIn1.Size);
lTime.Caption := Format('%.2d:%.2d:%.2d',[round((tmp-30) / 60) mod 120,round(tmp) mod 60,round(tmp*100) mod 100]);
// tmp := FileIn1.TotalTime-((FileIn1.Position * FileIn1.TotalTime) / FileIn1.Size);
lLeft.Caption := Format('%.2d:%.2d:%.2d',[round((tmp-30) / 60) mod 120,round(tmp) mod 60,round(tmp*100) mod 100]);
lTime1.Caption := 'Time elapsed';
lTime2.Caption := 'left';
end;
tfRemain:
begin
// if FileIn1.Size > 0 then
// tmp := ((FileIn1.Position * FileIn1.TotalTime) / FileIn1.Size);
lLeft.Caption := Format('%.2d:%.2d:%.2d',[round((tmp-30) / 60) mod 120,round(tmp) mod 60,round(tmp*100) mod 100]);
// tmp := FileIn1.TotalTime-((FileIn1.Position * FileIn1.TotalTime) / FileIn1.Size);
lTime.Caption := Format('%.2d:%.2d:%.2d',[round((tmp-30) / 60) mod 120,round(tmp) mod 60,round(tmp*100) mod 100]);
lTime1.Caption := 'Time remain';
lTime2.Caption := 'elapsed';
end;
end;
// Progress.Position := round((FileIn1.Position * 100) / FileIn1.Size);
end;
initialization
{$IFDEF FPC}
{$I umain.lrs}
{$ELSE}
{$R *.dfm}
{$ENDIF}
end.
|
unit Testparser;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, System.SysUtils, System.Generics.Collections, HTML.Parser, System.Contnrs,
System.RegularExpressionsCore, System.StrUtils, System.Classes;
type
// Test methods for class TDomTree
TestTDomTree = class(TTestCase)
strict private
FDomTree: TDomTree;
public
procedure SetUp; override;
procedure TearDown; override;
end;
// Test methods for class TDomTreeNode
TestTDomTreeNode = class(TTestCase)
strict private
FDomTreeNode: TDomTreeNode;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestParse;
procedure TestGetTagName;
procedure TestGetAttrValue;
procedure TestGetTextValue;
procedure TestGetComment;
procedure TestFindNode;
procedure TestFindTagOfIndex;
procedure TestGetPath;
procedure TestFindPath;
end;
// Test methods for class TChildList
TestTChildList = class(TTestCase)
strict private
FChildList: TDomTreeNodeList;
public
procedure SetUp; override;
procedure TearDown; override;
end;
// Test methods for class TPrmRecList
TestTPrmRecList = class(TTestCase)
strict private
FPrmRecList: TPrmRecList;
public
procedure SetUp; override;
procedure TearDown; override;
end;
implementation
procedure TestTDomTree.SetUp;
begin
FDomTree := TDomTree.Create;
end;
procedure TestTDomTree.TearDown;
begin
FDomTree.Free;
FDomTree := nil;
end;
procedure TestTDomTreeNode.SetUp;
var
DomTree: TDomTree;
begin
DomTree := TDomTree.Create;
FDomTreeNode := DomTree.RootNode;
CheckEquals('Root', FDomTreeNode.Tag);
CheckEquals('', FDomTreeNode.TypeTag);
CheckEquals('', FDomTreeNode.AttributesTxt);
CheckEquals('', FDomTreeNode.Text);
CheckEquals(0, FDomTreeNode.Child.Count);
end;
procedure TestTDomTreeNode.TearDown;
begin
FDomTreeNode.Free;
FDomTreeNode := nil;
end;
procedure TestTDomTreeNode.TestParse;
var
ReturnValue: Boolean;
HtmlTxt: TStringList;
tmp: string;
tmpNode: TDomTreeNode;
begin
HtmlTxt := TStringList.Create;
HtmlTxt.LoadFromFile('test.html');
ReturnValue := FDomTreeNode.Parse(HtmlTxt.Text);
CheckEquals(true, ReturnValue);
//check <?
CheckEquals('<?xml version="1.0" encoding="UTF-8"?>', FDomTreeNode.Child[0].Tag);
CheckEquals('%s', FDomTreeNode.Child[0].Typetag);
CheckEquals('', FDomTreeNode.Child[0].AttributesTxt);
CheckEquals('', FDomTreeNode.Child[0].Text);
//check multiline comment
tmp :=
'<!-- <link href="https://ozlotteries.r.worldssl.net/stylesheet/main.css" rel="stylesheet" type="text/css" > 1'#$D#$A'123-->';
CheckEquals(tmp, FDomTreeNode.Child[2].Tag);
//check Exceptions contain any symbols
tmp := 'Title "<!-- <'#39'this"/> --> '#39'document';
tmpNode := FDomTreeNode.Child[3].child[0].child[0].child[0];
CheckEquals(tmp, tmpNode.Text);
tmpNode := FDomTreeNode.Child[3].child[1].child[1];
CheckEquals('textarea', AnsiLowerCase(tmpNode.Tag));
CheckEquals('This disabled field? don'#39't write here<123/>', tmpNode.child[0].Text);
//check attributes
tmpNode := FDomTreeNode.Child[3].child[1];
CheckEquals('body', AnsiLowerCase(tmpNode.Tag));
CheckEquals(true, tmpNode.Attributes.ContainsKey('class'));
CheckEquals(true, tmpNode.Attributes.TryGetValue('class', tmp));
CheckEquals('"default"', tmp);
CheckEquals(true, tmpNode.Attributes.ContainsKey('bgcolor'));
CheckEquals(true, tmpNode.Attributes.TryGetValue('bgcolor', tmp));
CheckEquals(#39'blue'#39, tmp);
tmpNode := FDomTreeNode.Child[3].child[1].child[1];
CheckEquals('textarea', AnsiLowerCase(tmpNode.Tag));
CheckEquals(true, tmpNode.Attributes.ContainsKey('disabled'));
CheckEquals(false, tmpNode.Attributes.TryGetValue('class', tmp));
end;
procedure TestTDomTreeNode.TestGetTagName;
var
ReturnValue: string;
tmpNode: TDomTreeNode;
HtmlTxt: TStringList;
begin
HtmlTxt := TStringList.Create;
HtmlTxt.LoadFromFile('test.html');
FDomTreeNode.Parse(HtmlTxt.Text);
tmpNode := FDomTreeNode.Child[3].child[1].child[1];
ReturnValue := tmpNode.GetTagName;
CheckEquals('<textarea disabled cols="30" rows="5">', ReturnValue);
end;
procedure TestTDomTreeNode.TestGetAttrValue;
var
ReturnValue: string;
tmpNode: TDomTreeNode;
HtmlTxt: TStringList;
begin
HtmlTxt := TStringList.Create;
HtmlTxt.LoadFromFile('test.html');
FDomTreeNode.Parse(HtmlTxt.Text);
tmpNode := FDomTreeNode.Child[3].child[1].child[3];
ReturnValue := tmpNode.GetAttrValue('id');
CheckEquals('"maincontainer"', ReturnValue);
end;
procedure TestTDomTreeNode.TestGetTextValue;
var
ReturnValue: string;
tmpNode: TDomTreeNode;
HtmlTxt: TStringList;
begin
HtmlTxt := TStringList.Create;
HtmlTxt.LoadFromFile('test.html');
FDomTreeNode.Parse(HtmlTxt.Text);
tmpNode := FDomTreeNode.Child[3].child[1].child[3].child[1].child[0].child[0].child[0].child[1].child[0].child[0].child
[0].child[0].child[0].child[1].child[1].child[0].child[3].child[1];
ReturnValue := tmpNode.GetTextValue(0);
CheckEquals('Draw 960', ReturnValue);
ReturnValue := tmpNode.GetTextValue(1);
CheckEquals('Draw 960', ReturnValue);
ReturnValue := tmpNode.GetTextValue(2);
CheckEquals('Thursday 9th October 2014', ReturnValue);
end;
procedure TestTDomTreeNode.TestGetComment;
var
ReturnValue: string;
tmpNode: TDomTreeNode;
HtmlTxt: TStringList;
begin
HtmlTxt := TStringList.Create;
HtmlTxt.LoadFromFile('test.html');
FDomTreeNode.Parse(HtmlTxt.Text);
tmpNode := FDomTreeNode.Child[3].child[1];
ReturnValue := tmpNode.GetComment(0);
CheckEquals('<!-- logo(s) -->', ReturnValue);
ReturnValue := tmpNode.GetComment(1);
CheckEquals('<!-- logo(s) -->', ReturnValue);
end;
procedure TestTDomTreeNode.TestFindNode;
var
ReturnValue: Boolean;
dListNode: TDomTreeNodeList;
HtmlTxt: TStringList;
begin
HtmlTxt := TStringList.Create;
HtmlTxt.LoadFromFile('test.html');
FDomTreeNode.Parse(HtmlTxt.Text);
dListNode := TDomTreeNodeList.Create;
ReturnValue := FDomTreeNode.FindNode('', 0, 'id="maincontainer"', True, dListNode);
CheckEquals(true, ReturnValue);
CheckEquals('<div id="maincontainer">', dListNode[0].GetTagName);
dListNode.Clear;
ReturnValue := FDomTreeNode.FindNode('', 0, 'id="maincontainer"', false, dListNode);
CheckEquals(false, ReturnValue);
dListNode.Clear;
ReturnValue := FDomTreeNode.FindNode('div', 0, 'id="TopBox"', True, dListNode);
CheckEquals(true, ReturnValue);
CheckEquals('<div id="TopBox">', dListNode[0].GetTagName);
dListNode.Clear;
ReturnValue := FDomTreeNode.FindNode('h1', 0, '', True, dListNode);
CheckEquals(true, ReturnValue);
CheckEquals('<h1 class="pageTitle logintitle">', dListNode[0].GetTagName);
dListNode.Clear;
end;
procedure TestTDomTreeNode.TestFindTagOfIndex;
var
ReturnValue: Boolean;
dListNode: TDomTreeNodeList;
tmpNode: TDomTreeNode;
HtmlTxt: TStringList;
begin
HtmlTxt := TStringList.Create;
HtmlTxt.LoadFromFile('test.html');
FDomTreeNode.Parse(HtmlTxt.Text);
dListNode := TDomTreeNodeList.Create;
ReturnValue := FDomTreeNode.FindTagOfIndex('div', 2, false, dListNode);
CheckEquals(false, ReturnValue);
tmpNode := FDomTreeNode.Child[3].child[1].child[3].child[1].child[0].child[0].child[0].child[1].child[0].child[0].child
[0].child[0].child[0].child[1].child[1].child[0].child[3];
ReturnValue := tmpNode.FindTagOfIndex('div', 2, false, dListNode);
CheckEquals(true, ReturnValue);
CheckEquals('<div class="numbers">', dListNode[0].GetTagName);
end;
procedure TestTDomTreeNode.TestGetPath;
var
ReturnValue: string;
tmpNode: TDomTreeNode;
HtmlTxt: TStringList;
begin
HtmlTxt := TStringList.Create;
HtmlTxt.LoadFromFile('test.html');
FDomTreeNode.Parse(HtmlTxt.Text);
tmpNode := FDomTreeNode.Child[3].child[1].child[3].child[1].child[0].child[0].child[0].child[1].child[0].child[0].child
[0].child[0].child[0].child[1].child[1].child[0].child[3];
ReturnValue := tmpNode.GetPath(true);
CheckEquals('//*[@id="TopBox"]/div/div/div/div[1]', ReturnValue);
ReturnValue := tmpNode.GetPath(false);
CheckEquals('./html/body/div/table/tbody/tr/td/table/tbody/tr/td/div/div/div/div/div/div[1]', ReturnValue);
end;
procedure TestTDomTreeNode.TestFindPath;
var
ReturnValue: Boolean;
dListValue: TStringList;
dListNode: TDomTreeNodeList;
HtmlTxt: TStringList;
begin
HtmlTxt := TStringList.Create;
HtmlTxt.LoadFromFile('test.html');
FDomTreeNode.Parse(HtmlTxt.Text);
dListNode := TDomTreeNodeList.Create;
dListValue := TStringList.Create;
ReturnValue := FDomTreeNode.FindPath('//*[@id="TopBox"]/div/div/div/div[1]', dListNode, dListValue);
CheckEquals(true, ReturnValue);
CheckEquals(1, dListNode.Count);
CheckEquals('<div class="result_block result_13">', dListNode[0].GetTagName);
dListNode.Clear;
ReturnValue := FDomTreeNode.FindPath('//*[@id="TopBox"]/div/div/div/div/div[@class="draw default"]/text()[2]',
dListNode, dListValue);
CheckEquals(true, ReturnValue);
CheckEquals(2, dListNode.Count);
CheckEquals(2, dListValue.Count);
CheckEquals('Thursday 9th October 2014', dListValue[0]);
dListNode.Clear;
dListValue.Clear;
ReturnValue := FDomTreeNode.FindPath('//*[@id="TopBox"]/div/div/div/div/div[@class="numbers"]/table/tbody/tr[2]/td[1]/img[2]/@alt',
dListNode, dListValue);
CheckEquals(true, ReturnValue);
CheckEquals(2, dListNode.Count);
CheckEquals(2, dListValue.Count);
CheckEquals('"35"', dListValue[0]);
CheckEquals('"9"', dListValue[1]);
end;
procedure TestTChildList.SetUp;
begin
FChildList := TDomTreeNodeList.Create;
end;
procedure TestTChildList.TearDown;
begin
FChildList.Free;
FChildList := nil;
end;
procedure TestTPrmRecList.SetUp;
begin
FPrmRecList := TPrmRecList.Create;
end;
procedure TestTPrmRecList.TearDown;
begin
FPrmRecList.Free;
FPrmRecList := nil;
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTDomTree.Suite);
RegisterTest(TestTDomTreeNode.Suite);
RegisterTest(TestTChildList.Suite);
RegisterTest(TestTPrmRecList.Suite);
end.
|
{$MODESWITCH RESULT+}
{$GOTO ON}
(*************************************************************************
Copyright (c) 2005-2007, Sergey Bochkanov (ALGLIB project).
>>> SOURCE LICENSE >>>
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 (www.fsf.org); 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.
A copy of the GNU General Public License is available at
http://www.fsf.org/licensing/licenses
>>> END OF LICENSE >>>
*************************************************************************)
unit matdet;
interface
uses Math, Sysutils, Ap, reflections, creflections, hqrnd, matgen, ablasf, ablas, trfac;
function RMatrixLUDet(const A : TReal2DArray;
const Pivots : TInteger1DArray;
N : AlglibInteger):Double;
function RMatrixDet(A : TReal2DArray; N : AlglibInteger):Double;
function CMatrixLUDet(const A : TComplex2DArray;
const Pivots : TInteger1DArray;
N : AlglibInteger):Complex;
function CMatrixDet(A : TComplex2DArray; N : AlglibInteger):Complex;
function SPDMatrixCholeskyDet(const A : TReal2DArray;
N : AlglibInteger):Double;
function SPDMatrixDet(A : TReal2DArray;
N : AlglibInteger;
IsUpper : Boolean):Double;
implementation
(*************************************************************************
Determinant calculation of the matrix given by its LU decomposition.
Input parameters:
A - LU decomposition of the matrix (output of
RMatrixLU subroutine).
Pivots - table of permutations which were made during
the LU decomposition.
Output of RMatrixLU subroutine.
N - size of matrix A.
Result: matrix determinant.
-- ALGLIB --
Copyright 2005 by Bochkanov Sergey
*************************************************************************)
function RMatrixLUDet(const A : TReal2DArray;
const Pivots : TInteger1DArray;
N : AlglibInteger):Double;
var
I : AlglibInteger;
S : AlglibInteger;
begin
Result := 1;
S := 1;
I:=0;
while I<=N-1 do
begin
Result := Result*A[I,I];
if Pivots[I]<>I then
begin
S := -S;
end;
Inc(I);
end;
Result := Result*S;
end;
(*************************************************************************
Calculation of the determinant of a general matrix
Input parameters:
A - matrix, array[0..N-1, 0..N-1]
N - size of matrix A.
Result: determinant of matrix A.
-- ALGLIB --
Copyright 2005 by Bochkanov Sergey
*************************************************************************)
function RMatrixDet(A : TReal2DArray; N : AlglibInteger):Double;
var
Pivots : TInteger1DArray;
begin
A := DynamicArrayCopy(A);
RMatrixLU(A, N, N, Pivots);
Result := RMatrixLUDet(A, Pivots, N);
end;
(*************************************************************************
Determinant calculation of the matrix given by its LU decomposition.
Input parameters:
A - LU decomposition of the matrix (output of
RMatrixLU subroutine).
Pivots - table of permutations which were made during
the LU decomposition.
Output of RMatrixLU subroutine.
N - size of matrix A.
Result: matrix determinant.
-- ALGLIB --
Copyright 2005 by Bochkanov Sergey
*************************************************************************)
function CMatrixLUDet(const A : TComplex2DArray;
const Pivots : TInteger1DArray;
N : AlglibInteger):Complex;
var
I : AlglibInteger;
S : AlglibInteger;
begin
Result := C_Complex(1);
S := 1;
I:=0;
while I<=N-1 do
begin
Result := C_Mul(Result,A[I,I]);
if Pivots[I]<>I then
begin
S := -S;
end;
Inc(I);
end;
Result := C_MulR(Result,S);
end;
(*************************************************************************
Calculation of the determinant of a general matrix
Input parameters:
A - matrix, array[0..N-1, 0..N-1]
N - size of matrix A.
Result: determinant of matrix A.
-- ALGLIB --
Copyright 2005 by Bochkanov Sergey
*************************************************************************)
function CMatrixDet(A : TComplex2DArray; N : AlglibInteger):Complex;
var
Pivots : TInteger1DArray;
begin
A := DynamicArrayCopy(A);
CMatrixLU(A, N, N, Pivots);
Result := CMatrixLUDet(A, Pivots, N);
end;
(*************************************************************************
Determinant calculation of the matrix given by the Cholesky decomposition.
Input parameters:
A - Cholesky decomposition,
output of SMatrixCholesky subroutine.
N - size of matrix A.
As the determinant is equal to the product of squares of diagonal elements,
itís not necessary to specify which triangle - lower or upper - the matrix
is stored in.
Result:
matrix determinant.
-- ALGLIB --
Copyright 2005-2008 by Bochkanov Sergey
*************************************************************************)
function SPDMatrixCholeskyDet(const A : TReal2DArray;
N : AlglibInteger):Double;
var
I : AlglibInteger;
begin
Result := 1;
I:=0;
while I<=N-1 do
begin
Result := Result*AP_Sqr(A[I,I]);
Inc(I);
end;
end;
(*************************************************************************
Determinant calculation of the symmetric positive definite matrix.
Input parameters:
A - matrix. Array with elements [0..N-1, 0..N-1].
N - size of matrix A.
IsUpper - if IsUpper = True, then the symmetric matrix A is given by
its upper triangle, and the lower triangle isnít used by
subroutine. Similarly, if IsUpper = False, then A is given
by its lower triangle.
Result:
determinant of matrix A.
If matrix A is not positive definite, then subroutine returns -1.
-- ALGLIB --
Copyright 2005-2008 by Bochkanov Sergey
*************************************************************************)
function SPDMatrixDet(A : TReal2DArray;
N : AlglibInteger;
IsUpper : Boolean):Double;
begin
A := DynamicArrayCopy(A);
if not SPDMatrixCholesky(A, N, IsUpper) then
begin
Result := -1;
end
else
begin
Result := SPDMatrixCholeskyDet(A, N);
end;
end;
end. |
(*
Copyright (c) 2011-2014, Stefan Glienke
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 this library 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.
*)
unit DSharp.Core.XmlSerialization.XmlSerializer;
interface
uses
DSharp.Core.XmlSerialization,
TypInfo;
type
TXmlSerializer = class(TInterfacedObject, IXmlSerializer)
public
function Deserialize(reader: IXmlReader): TObject; virtual;
procedure Serialize(instance: TObject; writer: IXmlWriter); virtual;
end;
TXmlSerializer<T: class, constructor> = class(TXmlSerializer)
private
function GetTypeName: string;
public
function Deserialize(reader: IXmlReader): TObject; override;
procedure Serialize(instance: TObject; writer: IXmlWriter); override;
end;
implementation
uses
DSharp.Core.Reflection,
Rtti;
{ TXmlSerializer }
function TXmlSerializer.Deserialize(reader: IXmlReader): TObject;
var
value: TValue;
begin
reader.ReadStartElement;
reader.ReadValue(value);
if value.IsObject then
Result := value.AsObject
else
Result := nil;
reader.ReadEndElement;
end;
procedure TXmlSerializer.Serialize(instance: TObject; writer: IXmlWriter);
begin
writer.WriteStartElement(instance.ClassName);
writer.WriteValue(TValue.From<TObject>(instance));
writer.WriteEndElement(instance.ClassName);
end;
{ TXmlSerializer<T> }
function TXmlSerializer<T>.Deserialize(reader: IXmlReader): TObject;
var
value: TValue;
begin
reader.ReadStartElement;
Result := T.Create;
value := TValue.From<T>(Result);
reader.ReadValue(value);
reader.ReadEndElement;
end;
function TXmlSerializer<T>.GetTypeName: string;
var
rttiType: TRttiType;
rootAttribute: XmlRootAttribute;
begin
rttiType := GetRttiType(TypeInfo(T));
if rttiType.TryGetCustomAttribute<XmlRootAttribute>(rootAttribute) then
Exit(rootAttribute.ElementName);
if rttiType.IsPublicType then
Result := rttiType.QualifiedName
else
Result := rttiType.Name;
if rttiType.IsGenericTypeDefinition then
begin
Result := Copy(Result, 1, Pos('<', Result) - 1) + 'Of';
// keep it simple for now -> will move to reflection in the future
for rttiType in rttiType.GetGenericArguments do
Result := Result + rttiType.Name;
end;
end;
procedure TXmlSerializer<T>.Serialize(instance: TObject; writer: IXmlWriter);
var
typeName: string;
begin
typeName := GetTypeName;
writer.WriteStartElement(typeName);
writer.WriteValue(TValue.From<T>(instance));
writer.WriteEndElement(typeName);
end;
end.
|
(*
Copyright (c) 2012, Stefan Glienke
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 this library 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.
*)
unit DSharp.Windows.CustomPresenter.DataSetAdapter;
interface
uses
DB,
DSharp.Collections,
DSharp.Core.DataTemplates,
DSharp.Windows.ColumnDefinitions,
Rtti;
type
TDataSetBookmark = class
FBookmark: TBookmark;
public
constructor Create(ABookmark: TBookmark);
end;
TDataSetList = class(TList<TDataSetBookmark>, IList)
private
FDataSet: TDataSet;
FNotify: Boolean;
procedure DoAfterPost(DataSet: TDataSet);
protected
procedure Notify(const Value: TDataSetBookmark;
const Action: TCollectionChangedAction); override;
public
constructor Create(ADataSet: TDataSet);
destructor Destroy; override;
end;
TDataSetColumnDefinitions = class(TColumnDefinitions)
public
constructor Create(ADataSet: TDataSet); reintroduce;
end;
TDataSetTemplate = class(TDataTemplate)
private
FDataSet: TDataSet;
public
constructor Create(ADataSet: TDataSet);
function GetItem(const Item: TObject;
const Index: Integer): TObject; override;
function GetItemCount(const Item: TObject): Integer; override;
function GetText(const Item: TObject;
const ColumnIndex: Integer): string; override;
procedure SetText(const Item: TObject;
const ColumnIndex: Integer; const Value: string); override;
function CompareItems(const Item1, Item2: TObject;
const ColumnIndex: Integer): Integer; override;
function GetTemplateDataClass: TClass; override;
end;
implementation
uses
SysUtils;
{ TDataSetBookmark }
constructor TDataSetBookmark.Create(ABookmark: TBookmark);
begin
FBookmark := ABookmark;
end;
{ TDataSetList }
constructor TDataSetList.Create(ADataSet: TDataSet);
begin
inherited Create;
FDataSet := ADataSet;
FDataSet.AfterPost := DoAfterPost;
FNotify := False;
SetCapacity(FDataSet.RecordCount);
FDataSet.First;
while not FDataSet.Eof do
begin
Add(TDataSetBookmark.Create(FDataSet.GetBookmark));
FDataSet.Next;
end;
FNotify := True;
end;
destructor TDataSetList.Destroy;
begin
FNotify := False;
inherited;
end;
procedure TDataSetList.DoAfterPost(DataSet: TDataSet);
begin
if DataSet.RecNo > Count then
Add(TDataSetBookmark.Create(DataSet.GetBookmark))
else
Items[DataSet.RecNo - 1].FBookmark := FDataSet.GetBookmark;
end;
procedure TDataSetList.Notify(const Value: TDataSetBookmark;
const Action: TCollectionChangedAction);
begin
if FNotify then
begin
inherited;
if Action = caRemove then
begin
FDataSet.GotoBookmark(Value.FBookmark);
FDataSet.Delete;
end;
end;
end;
{ TDataSetTemplate }
function TDataSetTemplate.CompareItems(const Item1, Item2: TObject;
const ColumnIndex: Integer): Integer;
begin
Result := CompareText(GetText(Item1, ColumnIndex), GetText(Item2, ColumnIndex));
end;
constructor TDataSetTemplate.Create(ADataSet: TDataSet);
begin
FDataSet := ADataSet;
end;
function TDataSetTemplate.GetItem(const Item: TObject;
const Index: Integer): TObject;
begin
if Item is TDataSetList then
Result := TDataSetList(Item).Items[Index]
else
Result := nil;
end;
function TDataSetTemplate.GetItemCount(const Item: TObject): Integer;
begin
if Item is TDataSetList then
Result := TDataSetList(Item).Count
else
Result := 0;
end;
function TDataSetTemplate.GetTemplateDataClass: TClass;
begin
Result := TDataSetBookmark;
end;
function TDataSetTemplate.GetText(const Item: TObject;
const ColumnIndex: Integer): string;
begin
FDataSet.GotoBookmark(TDataSetBookmark(Item).FBookmark);
if ColumnIndex > -1 then
Result := FDataSet.Fields[ColumnIndex].Value
else
Result := FDataSet.Fields[0].Value;
end;
procedure TDataSetTemplate.SetText(const Item: TObject;
const ColumnIndex: Integer; const Value: string);
begin
FDataSet.GotoBookmark(TDataSetBookmark(Item).FBookmark);
FDataSet.Edit;
if ColumnIndex > -1 then
FDataSet.Fields[ColumnIndex].Value := Value
else
FDataSet.Fields[0].Value := Value;
FDataSet.Post;
end;
{ TDataSetColumnDefinitions }
constructor TDataSetColumnDefinitions.Create(ADataSet: TDataSet);
var
i: Integer;
begin
inherited Create;
FMainColumnIndex := -1;
for i := 0 to ADataSet.Fields.Count - 1 do
Add(ADataSet.Fields[i].DisplayName, ADataSet.Fields[i].DisplayWidth * 10);
end;
end.
|
unit Mercado.Libre.View;
interface
uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms,
Vcl.Dialogs, Vcl.StdCtrls;
type
TFrmMercadoLibre = class(TForm)
btnGetUserInfo: TButton;
memoResponse: TMemo;
editUserID: TEdit;
editAccess_Token: TEdit;
procedure btnGetUserInfoClick(Sender: TObject);
end;
var
FrmMercadoLibre: TFrmMercadoLibre;
implementation
{$R *.dfm}
uses REST.Types, RESTRequest4D, Mercado.Libre.Consts;
procedure TFrmMercadoLibre.btnGetUserInfoClick(Sender: TObject);
var
LResponse: RESTRequest4D.IResponse;
begin
if Trim(editUserID.Text) = EmptyStr then
Exit;
if Trim(editAccess_Token.Text) = EmptyStr then
Exit;
LResponse := RESTRequest4D.TRequest.New
.BaseURL(ML_APIBASE)
.Resource(ML_GET_USR_INF_REGEX)
.AddUrlSegment('cust_id', editUserID.Text)
.Token('Bearer ' + editAccess_Token.Text)
.Accept(REST.Types.CONTENTTYPE_APPLICATION_JSON)
.RaiseExceptionOn500(True)
.Get;
memoResponse.Lines.Clear;
memoResponse.Lines.Add(Format('Http status: %d', [LResponse.StatusCode]));
memoResponse.Lines.Add(Format('Http text: %s', [LResponse.StatusText]));
memoResponse.Lines.Add(Format('Response content: %s', [LResponse.Content]));
end;
end.
|
{==============================================================================]
Author: Jarl K. Holta
Project: ObjectWalk
Project URL: https://github.com/WarPie/ObjectWalk
License: GNU LGPL (https://www.gnu.org/licenses/lgpl-3.0.en.html)
[==============================================================================}
{==============================================================================]
This is an early version, there might exist bugs. It also means that
variable-, type-, function-names and the structure in this file is not final.
Over time there might come several changes, mainly for the better.
Debug defines:
OW:DEBUG -> Nothing atm..
OW:DEBUG_WORDY -> Will write some text, for example if it can't find a DTM
OW:SMARTDEBUG -> Will draw to the smartimage.
OW:DEBUG_TIMES -> Will write some timings..
[==============================================================================}
{$include_once SRL/OSR.simba}
{$I Minimap.pas}
{$I MMDTM.pas}
type
TPathPoint = record
Objects: TMMDTM;
Dest: TPointArray; //one set of objects can cover several points. BUT this might not be supported in the future.
end;
TMMPath = array of TPathPoint;
TObjectWalk = record
Types: TIntegerArray;
MaxOffset, MaxInaccuracy, MaxScale: Double;
end;
const
//16 high pitch colors that should genrally show well on the minimap.
COLOR_LIST16: TIntegerArray = [
$0000ff, $00ff44, $eeff00, $ff0066, $6666ff, $55ffff, $f5ff66, $ff66a3,
$00bbff, $5555DD, $ff5500, $dd00ff, $66d6ff, $85ff66, $ff9966, $eb66ff
];
(*
Initalizes the walker with some presets
*)
procedure TObjectWalk.Init();
begin
self.MaxOffset := 20; //How much the minimap can offset in relation to the compass.
self.MaxInaccuracy := Hypot(4,4); //With slightly inaccurate object finding and other defomities on the mm, we need to allow a little inaccuracy.
self.MaxScale := 1.18; //Minimap scales 10-15%(?) (-20%,+10%), but there are various defomities that cause our readings to be inaccurate.
end;
(*
Meh.. these two methods aren't really used, but I might need them for
debugging later on
*)
function TObjectWalk.FindObjects(ObjIds: TIntegerArray): TMMObjectsArray; static;
var typ:Int32;
begin
for typ in ObjIds do
Result += TMMObjects([EMinimapObject(typ), Minimap.FindObj(MMObjRecords[typ])]);
end;
function TObjectWalk.FindObjects(DTM: TMMDTM): TMMObjectsArray; static; overload;
var
i:Int32;
test:TIntegerArray;
begin
for i:=0 to High(DTM) do
begin
if test.Find(Ord(DTM[i].typ)) >= 0 then
Continue;
Result += TMMObjects([DTM[i].typ, Minimap.FindObj(MMObjRecords[DTM[i].typ])]);
test += Ord(DTM[i].typ);
end;
end;
(*
Ugh.. the input points gotta be scaled and rotated in relation to where we found
the DTM, it's scale, and the minimap-offset-to-compass
*)
function TObjectWalk.AdjustPoint(pt:TPoint; mp:TMMDTMPoint; theta,scale:Double): TPoint; static;
var
p:PPoint;
begin
p.R := Hypot(pt.y, pt.x) * scale;
p.T := ArcTan2(pt.y, pt.x) + (minimap.GetCompassAngle(False) + theta);
Result := Point(Round(mp.x + p.r * Cos(p.t)), Round(mp.y + p.r * Sin(p.t)));
end;
function TObjectWalk.AdjustBlindPoint(pt:TPoint; theta,scale:Double): TPoint; static;
var
p:PPoint;
begin
pt -= minimap.Center;
p.R := Hypot(pt.y, pt.x) * scale;
p.T := ArcTan2(pt.y, pt.x) + (minimap.GetCompassAngle(False) + theta);
Result := Point(Round(minimap.Center.x + p.r * Cos(p.t)), Round(minimap.Center.y + p.r * Sin(p.t)));
end;
(*
A helper method to locate all the possible results for a DTM
*)
function TObjectWalk.FindDTM(out Matches:TMMDTMResultArray; DTM:TMMDTM; MaxTime:Int32=3500): Boolean; constref;
var
t:Int64;
begin
matches := [];
t := GetTickCount()+MaxTime;
while (GetTickCount() < t) do
if not DTM.RotateToCompass().Find(matches, self.MaxOffset, self.MaxScale, self.MaxInaccuracy) then
Wait(60)
else
Break;
Result := Length(matches) > 0;
end;
(*
A helper method to locate a DTM
*)
function TObjectWalk.FindDTM(out Match:TMMDTMResult; DTM:TMMDTM; MaxTime:Int32=3500): Boolean; constref; overload;
var
t:Int64;
begin
Match := [];
t := GetTickCount()+MaxTime;
while (GetTickCount() < t) do
if not DTM.RotateToCompass().Find(Match, self.MaxOffset, self.MaxScale, self.MaxInaccuracy) then
Wait(60)
else
Break;
Result := Match.DTM <> [];
end;
(*
Just a neat function to have..
It locates the "goal" point taking into account all minimap transformations..
Then it returns the distance from you (at minimap center) to this point.
*)
function TObjectWalk.DistanceTo(Goal:TPoint; DTM:TMMDTM): Double; constref;
var
F:TMMDTMResult;
other,me:TPoint;
i:Int32;
begin
Goal.x -= DTM[0].x;
Goal.y -= DTM[0].y;
me := minimap.Center;
if not self.FindDTM(F, DTM) then
Exit(-1);
other := self.AdjustPoint(Goal, F.DTM[0], F.theta, F.scale);
Result := Hypot(me.x-other.x, me.y-other.y);
end;
(*
Yeah.. this one is supersimple, with no real random at all (it's a prototype after all).
*)
procedure TObjectWalk.WalkTo(pt:TPoint{$IFDEF OW:SMARTDEBUG}; step:TPoint; DTM:TMMDTM{$ENDIF}); constref;
begin
{$IFDEF OW:SMARTDEBUG}self.DebugDTM(step, DTM, Smart.Image);{$ENDIF}
Mouse.Click(pt, mouse_left);
while minimap.IsFlagPresent(300) do
begin
{$IFDEF OW:SMARTDEBUG}
self.DebugDTM(step, DTM, Smart.Image);
Wait(7);
{$ELSE}
Wait(70);
{$ENDIF}
end;
{$IFDEF OW:SMARTDEBUG}
smart.Image.DrawClear(0);
{$ENDIF}
end;
(*
This is your best friend. It will walk the minimap up, down, and sideways, yo!
*)
function TObjectWalk.Walk(Path:TMMPath): Boolean; constref;
var
i,j,_,t: Int64;
step,pt: TPoint;
matches: TMMDTMResultArray;
F: TMMDTMResult;
theta,scale: Double;
begin
theta := 0;
scale := 1;
for i:=0 to High(Path) do
for step in Path[i].Dest do
begin
if Length(Path[i].Objects) = 0 then //blind step
begin
pt := self.AdjustBlindPoint(step, theta, scale);
self.WalkTo(pt.Random(4,4){$IFDEF OW:SMARTDEBUG},step,Path[i].Objects{$ENDIF});
continue;
end;
t := GetTickCount() + 3500;
repeat
if not self.FindDTM(matches, Path[i].Objects, 200) then
continue;
for F in matches do
begin
pt.x := step.x - Path[i].Objects[0].x;
pt.y := step.y - Path[i].Objects[0].y;
pt := self.AdjustPoint(pt, F.DTM[0], F.theta, F.scale);
if srl.PointInPoly(pt, MINIMAP_POLYGON) then
Break(2);
end;
until (not Minimap.isPlayerMoving()) and (GetTickCount() > t);
if Length(matches) = 0 then
begin
{$IFDEF OW:DEBUG_WORDY}WriteLn('Error: Unable to find DTM ', i);{$ENDIF}
Exit(False);
end;
if not srl.PointInPoly(pt, MINIMAP_POLYGON) then
begin
{$IFDEF OW:DEBUG_WORDY}WriteLn('Error: Point out of Range ', pt);{$ENDIF}
Exit(False);
end;
self.WalkTo(pt{$IFDEF OW:SMARTDEBUG},step,Path[i].Objects{$ENDIF});
{$IFDEF OW:DEBUG_WORDY}
if Length(matches) > 1 then
WriteLn('Warning: Found several matches of DTM #', i);
{$ENDIF}
theta := F.theta;
scale := F.scale;
end;
Result := True;
end;
(*==| THE FOLLOWING IS FOR DEBUGGING |========================================*)
(*============================================================================*)
var
__MMMask__:TPointArray := ReturnPointsNotInTPA(Minimap.MaskTPA, GetTPABounds(Minimap.MaskTPA));
procedure TObjectWalk.DebugMinimap(im:TMufasaBitmap; offset:TPoint=[0,0]; Clear:Boolean=True); constref;
var
objects: T2DPointArray;
color,i:Int32;
pt:TPoint;
b:TBox;
{$IFDEF OW:DEBUG_TIMES} t:TDateTime;{$ENDIF}
begin
for i:=0 to High(MMObjRecords) do
begin
{$IFDEF OW:DEBUG_TIMES}t := Now();{$ENDIF}
objects += Minimap.FindObj(MMObjRecords[i]);
{$IFDEF OW:DEBUG_TIMES}WriteLn('Finding ', EMinimapObject(i), ' used: ', FormatDateTime('z', Now()-t),'ms');{$ENDIF}
end;
if Clear {$IFDEF OW:SMARTDEBUG}and (PtrUInt(im) = PtrUInt(smart.Image)){$ENDIF} then
{$IFDEF OW:SMARTDEBUG}
im.DrawTPA(__MMMask__, 0);
{$ELSE}
im.DrawClear(0);
{$ENDIF}
for i:=0 to High(objects) do
for pt in objects[i] do
begin
color := COLOR_LIST16[i mod 16];
pt += offset;
try
Im.DrawTPA(TPAFromBox(Box(pt,1,1)), color);
except
end;
end;
end;
function TObjectWalk.DebugDTM(Goal:TPoint; DTM:TMMDTM; im:TMufasaBitmap; offset:TPoint=[0,0]; Clear:Boolean=True): Boolean; constref;
var
F:TMMDTMResult;
line,tmp:TPointArray;
found,p,q:TPoint;
i,color:Int32;
begin
if Length(DTM) = 0 then Exit();
Result := True;
Goal.x -= DTM[0].x;
Goal.y -= DTM[0].y;
if not self.FindDTM(F, DTM, 100) then
begin
{$IFDEF OW:DEBUG_WORDY}WriteLn('DebugDTM: Unable to find DTM!');{$ENDIF}
Exit(False);
end;
found := self.AdjustPoint(Goal, F.DTM[0], F.theta, F.scale);
found.Offset(offset);
if Clear {$IFDEF OW:SMARTDEBUG}and (PtrUInt(im) = PtrUInt(smart.Image)){$ENDIF} then
{$IFDEF OW:SMARTDEBUG}
im.DrawTPA(__MMMask__, 0);
{$ELSE}
im.DrawClear(0);
{$ENDIF}
Im.DrawTPA(TPAFromBox(Box(found,1,1)), COLOR_LIST16[0]);
line := TPAFromLine(found.x, found.y, Minimap.Center.x, Minimap.Center.y);
for i:=3 to High(line)-1 with 4 do
begin
Im.SetPixel(line[i+0].x, line[i+0].y, $FFFFFF);
Im.SetPixel(line[i+1].x, line[i+1].y, $FFFFFF);
end;
for i:=0 to High(F.DTM) do
begin
p := F.DTM[i];
p += offset;
color := COLOR_LIST16[(i+1) mod 16];
try
Im.DrawTPA(TPAFromBox(Box(p,1,1)), color);
except
end;
//draw line to center
Im.DrawTPA(TPAFromLine(p.x,p.y,Minimap.Center.x,Minimap.Center.y), $999999);
//draw line to next point
q := F.DTM[(i+1) mod Length(F.DTM)];
q += offset;
Im.DrawTPA(TPAFromLine(p.x,p.y,q.x,q.y), $FF);
tmp += p;
end;
im.DrawText(
'a:'+ToString(Round(Degrees(F.theta)))+'*, '+
's:'+Replace(Format('%.2f',[F.scale]), '.',',',[]),
tmp.Mean() - Point(9,5), $00FFFF
);
end;
function TObjectWalk.DebugDTMs(DTM:TMMDTM; im:TMufasaBitmap; offset:TPoint=[0,0]; Clear:Boolean=True): Boolean; constref;
var
matches:TMMDTMResultArray;
F: TMMDTMResult;
line,tmp:TPointArray;
found,p,q:TPoint;
i,j,color:Int32;
begin
if Length(DTM) = 0 then Exit();
Result := True;
if not self.FindDTM(matches, DTM, 100) then
begin
{$IFDEF OW:DEBUG_WORDY}WriteLn('DebugDTMs: Unable to find DTM!');{$ENDIF}
Exit(False);
end;
if Clear {$IFDEF OW:SMARTDEBUG}and (PtrUInt(im) = PtrUInt(smart.Image)){$ENDIF} then
{$IFDEF OW:SMARTDEBUG}
im.DrawTPA(__MMMask__, 0);
{$ELSE}
im.DrawClear(0);
{$ENDIF}
for j:=0 to High(matches) do
begin
F := matches[j];
SetLength(tmp, 0);
for i:=0 to High(F.DTM) do
begin
p := F.DTM[i];
p += offset;
color := COLOR_LIST16[(i+1) mod 16];
Im.DrawTPA(TPAFromBox(Box(p,1,1)), color);
q := F.DTM[(i+1) mod Length(F.DTM)];
q += offset;
Im.DrawTPA(TPAFromLine(p.x,p.y,q.x,q.y), $FF);
tmp += p;
end;
im.DrawText(
'a:'+ToString(Round(Degrees(F.theta)))+'*, '+
's:'+Format('%.2f',[F.scale]),
tmp.Mean() - Point(9,5), $00FFFF);
end;
end;
|
unit WeighingProduction_wms;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, ParentForm, cxGraphics, cxControls,
cxLookAndFeels, cxLookAndFeelPainters, cxStyles, cxCustomData, cxFilter,
cxData, cxDataStorage, cxEdit, Data.DB, cxDBData, dsdDB, cxGridLevel,
cxClasses, cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGrid, Datasnap.DBClient, Vcl.ActnList, dsdAction,
cxPropertiesStore, dxBar, Vcl.ExtCtrls, cxContainer, cxLabel, cxTextEdit,
Vcl.ComCtrls, dxCore, cxDateUtils, cxButtonEdit, cxMaskEdit, cxDropDownEdit,
cxCalendar, dsdGuides, Vcl.Menus, cxPCdxBarPopupMenu, cxPC, frxClass, frxDBSet,
dxSkinsCore, dxSkinBlack, dxSkinBlue, dxSkinBlueprint, dxSkinCaramel,
dxSkinCoffee, dxSkinDarkRoom, dxSkinDarkSide, dxSkinDevExpressDarkStyle,
dxSkinDevExpressStyle, dxSkinFoggy, dxSkinGlassOceans, dxSkinHighContrast,
dxSkiniMaginary, dxSkinLilian, dxSkinLiquidSky, dxSkinLondonLiquidSky,
dxSkinMcSkin, dxSkinMoneyTwins, dxSkinOffice2007Black, dxSkinOffice2007Blue,
dxSkinOffice2007Green, dxSkinOffice2007Pink, dxSkinOffice2007Silver,
dxSkinOffice2010Black, dxSkinOffice2010Blue, dxSkinOffice2010Silver,
dxSkinPumpkin, dxSkinSeven, dxSkinSevenClassic, dxSkinSharp, dxSkinSharpPlus,
dxSkinSilver, dxSkinSpringTime, dxSkinStardust, dxSkinSummer2008,
dxSkinTheAsphaltWorld, dxSkinsDefaultPainters, dxSkinValentine, dxSkinVS2010,
dxSkinWhiteprint, dxSkinXmas2008Blue, dxSkinscxPCPainter, dxSkinsdxBarPainter,
DataModul, dxBarExtItems, dsdAddOn, cxCheckBox, cxCurrencyEdit;
type
TWeighingProduction_wmsForm = class(TParentForm)
FormParams: TdsdFormParams;
spSelectMI: TdsdStoredProc;
dxBarManager: TdxBarManager;
dxBarManagerBar: TdxBar;
bbRefresh: TdxBarButton;
cxPropertiesStore: TcxPropertiesStore;
ActionList: TActionList;
actRefresh: TdsdDataSetRefresh;
MasterDS: TDataSource;
MasterCDS: TClientDataSet;
DataPanel: TPanel;
edInvNumber: TcxTextEdit;
cxLabel1: TcxLabel;
edOperDate: TcxDateEdit;
cxLabel2: TcxLabel;
edFrom: TcxButtonEdit;
edTo: TcxButtonEdit;
cxLabel3: TcxLabel;
cxLabel4: TcxLabel;
GuidesFrom: TdsdGuides;
GuidesTo: TdsdGuides;
PopupMenu: TPopupMenu;
N1: TMenuItem;
cxPageControl: TcxPageControl;
cxTabSheetMain: TcxTabSheet;
cxGrid: TcxGrid;
cxGridDBTableView: TcxGridDBTableView;
LineCode: TcxGridDBColumn;
cxGridLevel: TcxGridLevel;
actUpdateMasterDS: TdsdUpdateDataSet;
actPrint: TdsdPrintAction;
bbPrint: TdxBarButton;
UpdateDate: TcxGridDBColumn;
GoodsTypeKindName: TcxGridDBColumn;
bbShowAll: TdxBarButton;
bbStatic: TdxBarStatic;
actShowAll: TBooleanStoredProcAction;
MasterViewAddOn: TdsdDBViewAddOn;
UserSettingsStorageAddOn: TdsdUserSettingsStorageAddOn;
cxLabel5: TcxLabel;
cxLabel6: TcxLabel;
edStartWeighing: TcxDateEdit;
cxLabel7: TcxLabel;
HeaderSaver: THeaderSaver;
edMovementDescNumber: TcxTextEdit;
spGet: TdsdStoredProc;
RefreshAddOn: TRefreshAddOn;
GridToExcel: TdsdGridToExcel;
bbGridToExel: TdxBarButton;
GuidesFiller: TGuidesFiller;
actInsertUpdateMovement: TdsdExecStoredProc;
bbInsertUpdateMovement: TdxBarButton;
SetErased: TdsdUpdateErased;
SetUnErased: TdsdUpdateErased;
actShowErased: TBooleanStoredProcAction;
bbErased: TdxBarButton;
bbUnErased: TdxBarButton;
bbShowErased: TdxBarButton;
cxLabel11: TcxLabel;
spErasedMIMaster: TdsdStoredProc;
spUnErasedMIMaster: TdsdStoredProc;
IsErased: TcxGridDBColumn;
GuidesStatus: TdsdGuides;
spChangeStatus: TdsdStoredProc;
UnCompleteMovement: TChangeGuidesStatus;
CompleteMovement: TChangeGuidesStatus;
DeleteMovement: TChangeGuidesStatus;
ceStatus: TcxButtonEdit;
cxLabel9: TcxLabel;
edEndWeighing: TcxDateEdit;
cxLabel8: TcxLabel;
edUser: TcxButtonEdit;
GuidesUser: TdsdGuides;
BarCodeBoxName: TcxGridDBColumn;
WmsCode: TcxGridDBColumn;
edOperDate_parent: TcxDateEdit;
cxLabel12: TcxLabel;
cxLabel10: TcxLabel;
edPlaceNumber: TcxCurrencyEdit;
InsertDate: TcxGridDBColumn;
spSelectPrintCeh: TdsdStoredProc;
PrintHeaderCDS: TClientDataSet;
PrintItemsCDS: TClientDataSet;
MovementItemProtocolOpenForm: TdsdOpenForm;
bbProtocol: TdxBarButton;
bbOpenDocument: TdxBarButton;
actUpdateDocument: TdsdInsertUpdateAction;
GuidesMovementDesc: TdsdGuides;
edMovementDescName: TcxButtonEdit;
cxLabel13: TcxLabel;
edGoods: TcxButtonEdit;
GuidesGoods: TdsdGuides;
cxLabel14: TcxLabel;
edGoodsKind: TcxButtonEdit;
GuidesGoodsKind: TdsdGuides;
InvNumber_Parent: TcxGridDBColumn;
GuidesGoodsTypeKind1: TdsdGuides;
cxLabel15: TcxLabel;
edGoodsTypeKind_1: TcxButtonEdit;
cxLabel16: TcxLabel;
edGoodsTypeKind_2: TcxButtonEdit;
GuidesGoodsTypeKind2: TdsdGuides;
cxLabel17: TcxLabel;
edGoodsTypeKind_3: TcxButtonEdit;
GuidesGoodsTypeKind3: TdsdGuides;
edBarCodeBox_1: TcxButtonEdit;
cxLabel18: TcxLabel;
GuidesBarCodeBox1: TdsdGuides;
cxLabel19: TcxLabel;
edBarCodeBox_2: TcxButtonEdit;
GuidesBarCodeBox2: TdsdGuides;
cxLabel20: TcxLabel;
edBarCodeBox_3: TcxButtonEdit;
GuidesBarCodeBox3: TdsdGuides;
cxLabel21: TcxLabel;
edBox_1: TcxButtonEdit;
GuidesBox1: TdsdGuides;
cxLabel22: TcxLabel;
edBox_2: TcxButtonEdit;
GuidesBox2: TdsdGuides;
cxLabel23: TcxLabel;
edBox_3: TcxButtonEdit;
GuidesBox3: TdsdGuides;
Amount: TcxGridDBColumn;
RealWeight: TcxGridDBColumn;
BoxName: TcxGridDBColumn;
spSelectPrintSticker: TdsdStoredProc;
actPrintSticker: TdsdPrintAction;
bbPrintSticker: TdxBarButton;
spSelectPrintNoGroup: TdsdStoredProc;
actPrintNoGroup: TdsdPrintAction;
bbPrintNoGroup: TdxBarButton;
actOpenWeighingProductionForm: TdsdOpenForm;
bbOpenWeighingProductionForm: TdxBarButton;
private
public
end;
implementation
{$R *.dfm}
initialization
RegisterClass(TWeighingProduction_wmsForm);
end.
|
unit QApplication.Input;
interface
uses
SyncObjs,
Generics.Collections,
QCore.Input,
Strope.Math;
type
TEventMessageType = (
emtNone = 0,
emtMouseEvent = 1,
emtMouseButtonEvent = 2,
emtMouseWheelEvent = 3,
emtKeyEvent = 4
);
TEventMessage = record
strict private
FMessageType: TEventMessageType;
FMousePosition: TVectorF;
FMouseButton: TMouseButton;
FIsMouseButtonPressed: Boolean;
FMouseWheelDirection: Integer;
FKeyButton: TKeyButton;
FIsKeyPressed: Boolean;
public
constructor CreateAsMouseEvent(const APosition: TVectorF);
constructor CreateAsMouseButtonEvent(const APosition: TVectorF;
AButton: TMouseButton; AIsPressed: Boolean);
constructor CreateAsMouseWheelEvent(ADirection: Integer);
constructor CreateAsKeyEvent(AKey: TKeyButton; AIsPressed: Boolean);
property MessageType: TEventMessageType read FMessageType;
property MousePosition: TVectorF read FMousePosition;
property MouseButton: TMouseButton read FMouseButton;
property IsMouseButtonPressed: Boolean read FIsMouseButtonPressed;
property MouseWheelDirection: Integer read FMouseWheelDirection;
property KeyButton: TKeyButton read FKeyButton;
property IsKeyPressed: Boolean read FIsKeyPressed;
end;
implementation
uses
SysUtils;
{$REGION ' TEventMessage '}
constructor TEventMessage.CreateAsKeyEvent(AKey: TKeyButton;
AIsPressed: Boolean);
begin
FMessageType := emtKeyEvent;
FKeyButton := AKey;
FIsKeyPressed := AIsPressed;
end;
constructor TEventMessage.CreateAsMouseButtonEvent(const APosition: TVectorF;
AButton: TMouseButton; AIsPressed: Boolean);
begin
FMessageType := emtMouseButtonEvent;
FMousePosition := APosition;
FMouseButton := AButton;
FIsMouseButtonPressed := AIsPressed;
end;
constructor TEventMessage.CreateAsMouseEvent(const APosition: TVectorF);
begin
FMessageType := emtMouseEvent;
FMousePosition := APosition;
end;
constructor TEventMessage.CreateAsMouseWheelEvent(ADirection: Integer);
begin
FMessageType := emtMouseWheelEvent;
FMouseWheelDirection := ADirection;
end;
{$ENDREGION}
end.
|
{ Routines that do drawing.
}
module displ_draw;
define displ_draw_item;
define displ_draw_itemst;
define displ_draw_item_vect;
define displ_draw_list;
define displ_draw_listst;
%include 'displ2.ins.pas';
{
********************************************************************************
*
* Subroutine DISPL_DRAW_ITEM (ITEM)
*
* Draw the indicated display list item. The current drawing state is assumed
* to be the default.
}
procedure displ_draw_item ( {draw item, current RENDlib state is default}
in item: displ_item_t); {the item to draw}
val_param;
var
drdef: displ_rend_t; {default draw settings}
drcur: displ_rend_t; {current draw settings}
color: displ_color_t; {default color}
vect_parm: displ_vparm_t; {default vector drawing parameters}
text_parm: displ_tparm_t; {default text drawing parameters}
begin
rend_set.enter_rend^; {enter graphics mode}
{
* Get the current settings that modify drawing.
}
rend_get.rgba^ ( {get the current color}
color.red, color.grn, color.blu, color.opac);
rend_get.vect_parms^ (vect_parm.vparm); {get the current vector drawing parameters}
rend_get.text_parms^ (text_parm.tparm); {get the current text drawing parameters}
displ_rend_init (drcur); {init current settings descriptor}
drcur.color_p := addr(color); {save the current settings}
drcur.vect_parm_p := addr(vect_parm);
drcur.text_parm_p := addr(text_parm);
{
* Resolve the default draw settings.
}
displ_rend_init (drdef); {make sure all fields are set}
if item.list_p <> nil then begin {parent list exists ?}
displ_rend_resolve (drdef, item.list_p^.rend); {apply defaults from parent list}
end;
displ_rend_resolve (drdef, drcur); {use current settings for remaining defaults}
displ_draw_itemst (item, drdef, drcur); {actually draw the item}
rend_set.exit_rend^; {pop back out of graphics mode}
end;
{
********************************************************************************
*
* Subroutine DISPL_DRAW_ITEMST (ITEM, DRDEF, DRCUR)
*
* Low level routine to draw one display list item. The drawing state is
* supplied by the caller.
}
procedure displ_draw_itemst ( {draw item, drawing state supplied}
in item: displ_item_t; {the item to draw}
in drdef: displ_rend_t; {default drawing settings}
in out drcur: displ_rend_t); {current drawing settings}
val_param;
begin
case item.item of {what kind of item is this ?}
displ_item_list_k: begin
displ_draw_item_list (item, drdef, drcur); {draw the LIST item}
end;
displ_item_vect_k: begin
displ_draw_item_vect (item, drdef, drcur); {draw the VECT item}
end;
displ_item_img_k: begin
displ_draw_item_img (item, drdef, drcur); {draw the IMG item}
end;
end; {end of item type cases}
end;
{
********************************************************************************
*
* Subroutine DISPL_DRAW_ITEM_LIST (ITEM, DRDEF, DRCUR)
*
* Draw the subordinate list item ITEM.
*
* This is a low level routine that requires ITEM to be of type LIST, which is
* not checked.
}
procedure displ_draw_item_list ( {draw subordinate list display list item}
in item: displ_item_t; {the item to draw, must be type LIST}
in drdef: displ_rend_t; {default drawing settings}
in out drcur: displ_rend_t); {current drawing settings}
val_param;
begin
if item.list_sub_p = nil then return; {no subordinate list, nothing to do ?}
displ_draw_listst (item.list_sub_p^, drdef, drcur); {draw the subordinate list}
end;
{
********************************************************************************
*
* Subroutine DISPL_DRAW_ITEM_VECT (ITEM, DRDEF, DRCUR)
*
* Draw the chained vectors list item ITEM.
*
* This is a low level routine that requires ITEM to be of type VECT, which is
* not checked.
}
procedure displ_draw_item_vect ( {draw chained vectors display list item}
in item: displ_item_t; {the item to draw, must be type VECT}
in drdef: displ_rend_t; {default drawing settings}
in out drcur: displ_rend_t); {current drawing settings}
val_param;
var
coor_p: displ_coor2d_ent_p_t; {pointer to current coor of vectors list}
begin
coor_p := item.vect_first_p; {init pointer to starting coordinate}
if coor_p = nil then return; {no coordinate, nothing to draw ?}
if coor_p^.next_p = nil then return; {no second coordinate, nothing to draw ?}
displ_rend_set_color ( {set the color}
item.vect_color_p, drdef, drcur);
displ_rend_set_vect ( {set vector drawing parameters}
item.vect_parm_p, drdef, drcur);
rend_set.cpnt_2d^ (coor_p^.x, coor_p^.y); {set current point to first coordinate}
coor_p := coor_p^.next_p; {advance to the second coordinate}
repeat {back here each new vector to draw}
rend_prim.vect_2d^ (coor_p^.x, coor_p^.y); {draw vector to this coordinate}
coor_p := coor_p^.next_p; {advance to next coordinate in list}
until coor_p = nil; {back until hit end of list}
end;
{
********************************************************************************
*
* Subroutine DISPL_DRAW_LIST (LIST)
*
* Draw all the contents of the indicated display list. The current drawing
* state is assumed to be the default.
}
procedure displ_draw_list ( {draw display list, curr RENDlib state is default}
in list: displ_t); {the display list to draw}
val_param;
var
drdef: displ_rend_t; {default draw settings}
drcur: displ_rend_t; {current draw settings}
color: displ_color_t; {default color}
vect_parm: displ_vparm_t; {default vector drawing parameters}
text_parm: displ_tparm_t; {default text drawing parameters}
begin
rend_set.enter_rend^; {enter graphics mode}
{
* Get the current settings that modify drawing.
}
rend_get.rgba^ ( {get the current color}
color.red, color.grn, color.blu, color.opac);
rend_get.vect_parms^ (vect_parm.vparm); {get the current vector drawing parameters}
rend_get.text_parms^ (text_parm.tparm); {get the current text drawing parameters}
displ_rend_init (drcur); {init current settings descriptor}
drcur.color_p := addr(color); {save the current settings}
drcur.vect_parm_p := addr(vect_parm);
drcur.text_parm_p := addr(text_parm);
{
* Resolve the default draw settings.
}
displ_rend_init (drdef); {make sure all fields are set}
displ_rend_resolve (drdef, drcur); {use current settings as the defaults}
displ_draw_listst (list, drdef, drcur); {draw the list, pass drawing state}
rend_set.exit_rend^; {pop back out of graphics mode}
end;
{
********************************************************************************
*
* Subroutine DISPL_DRAW_LISTST (LIST, DRDEF, DRCUR)
*
* Low level routine to draw the contents of a display list. The drawing state
* is supplied by the caller.
}
procedure displ_draw_listst ( {draw list, drawing state supplied}
in list: displ_t; {the list to draw}
in drdef: displ_rend_t; {default drawing settings}
in out drcur: displ_rend_t); {current drawing settings}
val_param;
var
def: displ_rend_t; {nested default draw settings}
item_p: displ_item_p_t; {points to current item in display list}
begin
displ_rend_default (drdef, list.rend, def); {make our nested defaults}
item_p := list.first_p; {init to first item in the list}
while item_p <> nil do begin {loop over the list of items}
displ_draw_itemst (item_p^, def, drcur); {draw this item}
item_p := item_p^.next_p; {advance to next item in the list}
end; {back to draw this new item}
end;
|
//##############################################################################
{ TfrxPictureView }
//##############################################################################
type
{$IFDEF FR_COM}
TfrxPictureView = class(TfrxView, IfrxPictureView)
{$ELSE}
TfrxPictureView = class(TfrxView)
{$ENDIF}
private
FAutoSize: Boolean;
FCenter: Boolean;
FFileLink: String;
FImageIndex: Integer;
FIsImageIndexStored: Boolean;
FIsPictureStored: Boolean;
FKeepAspectRatio: Boolean;
FPicture: TPicture;
FPictureChanged: Boolean;
FStretched: Boolean;
FHightQuality: Boolean;
procedure SetPicture(const Value: TPicture);
procedure PictureChanged(Sender: TObject);
procedure SetAutoSize(const Value: Boolean);
{$IFDEF FR_COM}
protected
function Get_Picture(out Value: OLE_HANDLE): HResult; stdcall;
function Set_Picture(Value: OLE_HANDLE): HResult; stdcall;
function Get_Metafile(out Value: OLE_HANDLE): HResult; stdcall;
function Set_Metafile(Value: OLE_HANDLE): HResult; stdcall;
function LoadViewFromStream(const Stream: IUnknown): HResult; stdcall;
function SaveViewToStream(const Stream: IUnknown): HResult; stdcall;
{$ENDIF}
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
class function GetDescription: String; override;
function Diff(AComponent: TfrxComponent): String; override;
function LoadPictureFromStream(s: TStream): HResult;
procedure Draw(Canvas: TCanvas; ScaleX, ScaleY, OffsetX, OffsetY: Extended); override;
procedure GetData; override;
property IsImageIndexStored: Boolean read FIsImageIndexStored write FIsImageIndexStored;
property IsPictureStored: Boolean read FIsPictureStored write FIsPictureStored;
published
property Cursor;
property AutoSize: Boolean read FAutoSize write SetAutoSize default False;
property Center: Boolean read FCenter write FCenter default False;
property DataField;
property DataSet;
property DataSetName;
property Frame;
property FileLink: String read FFileLink write FFileLink;
property ImageIndex: Integer read FImageIndex write FImageIndex stored FIsImageIndexStored;
property KeepAspectRatio: Boolean read FKeepAspectRatio write FKeepAspectRatio default True;
property Picture: TPicture read FPicture write SetPicture stored FIsPictureStored;
property Stretched: Boolean read FStretched write FStretched default True;
property TagStr;
property URL;
property HightQuality: Boolean read FHightQuality write FHightQuality;
end;
//------------------------------------------------------------------------------
constructor TfrxPictureView.Create(AOwner: TComponent);
begin
inherited;
frComponentStyle := frComponentStyle - [csDefaultDiff];
FPicture := TPicture.Create;
FPicture.OnChange := PictureChanged;
FKeepAspectRatio := True;
FStretched := True;
FColor := clWhite;
FIsPictureStored := True;
end;
//------------------------------------------------------------------------------
destructor TfrxPictureView.Destroy;
begin
FPicture.Free;
inherited;
end;
//------------------------------------------------------------------------------
class function TfrxPictureView.GetDescription: String;
begin
Result := frxResources.Get('obPicture');
end;
//------------------------------------------------------------------------------
procedure TfrxPictureView.SetPicture(const Value: TPicture);
begin
FPicture.Assign(Value);
end;
//------------------------------------------------------------------------------
procedure TfrxPictureView.SetAutoSize(const Value: Boolean);
begin
FAutoSize := Value;
if FAutoSize and not (FPicture.Graphic = nil) then
begin
FWidth := FPicture.Width;
FHeight := FPicture.Height;
end;
end;
//------------------------------------------------------------------------------
procedure TfrxPictureView.PictureChanged(Sender: TObject);
begin
AutoSize := FAutoSize;
FPictureChanged := True;
end;
//------------------------------------------------------------------------------
procedure TfrxPictureView.Draw(Canvas: TCanvas; ScaleX, ScaleY, OffsetX, OffsetY: Extended);
var
r: TRect;
kx, ky: Extended;
rgn: HRGN;
procedure PrintGraphic(Canvas: TCanvas; DestRect: TRect; aGraph: TGraphic);
begin
frxDrawGraphic(Canvas, DestRect, aGraph, (IsPrinting or FHightQuality));
end;
begin
BeginDraw(Canvas, ScaleX, ScaleY, OffsetX, OffsetY);
with Canvas do
begin
DrawBackground;
r := Rect(FX, FY, FX1, FY1);
if (FPicture.Graphic = nil) or FPicture.Graphic.Empty then
begin
if IsDesigning then
frxResources.ObjectImages.Draw(Canvas, FX + 1, FY + 2, 3);
end
else
begin
if FStretched then
begin
if FKeepAspectRatio then
begin
kx := FDX / FPicture.Width;
ky := FDY / FPicture.Height;
if kx < ky then
r.Bottom := r.Top + Round(FPicture.Height * kx) else
r.Right := r.Left + Round(FPicture.Width * ky);
if FCenter then
OffsetRect(r, (FDX - (r.Right - r.Left)) div 2,
(FDY - (r.Bottom - r.Top)) div 2);
end;
PrintGraphic(Canvas, r, FPicture.Graphic);
end
else
begin
rgn := CreateRectRgn(0, 0, 10000, 10000);
GetClipRgn(Canvas.Handle, rgn);
IntersectClipRect(Canvas.Handle,
Round(FX),
Round(FY),
Round(FX1),
Round(FY1));
if FCenter then
OffsetRect(r, (FDX - Round(ScaleX * FPicture.Width)) div 2,
(FDY - Round(ScaleY * FPicture.Height)) div 2);
r.Right := r.Left + Round(FPicture.Width * ScaleX);
r.Bottom := r.Top + Round(FPicture.Height * ScaleY);
PrintGraphic(Canvas, r, Picture.Graphic);
SelectClipRgn(Canvas.Handle, rgn);
DeleteObject(rgn);
end;
end;
DrawFrame;
end;
end;
//------------------------------------------------------------------------------
function TfrxPictureView.Diff(AComponent: TfrxComponent): String;
begin
if FPictureChanged then
begin
Report.PreviewPages.AddPicture(Self);
FPictureChanged := False;
end;
Result := ' ' + inherited Diff(AComponent) + ' ImageIndex="' +
IntToStr(FImageIndex) + '"';
end;
//------------------------------------------------------------------------------
{$IFDEF FR_COM}
function TfrxPictureView.Get_Picture(out Value: OLE_HANDLE): HResult; stdcall;
begin
Value := FPicture.Bitmap.Handle;
Result := S_OK;
end;
//------------------------------------------------------------------------------
function TfrxPictureView.Set_Picture(Value: OLE_HANDLE): HResult; stdcall;
begin
FPicture.Bitmap.Handle := Value;
Result := S_OK;
end;
//------------------------------------------------------------------------------
function TfrxPictureView.Get_Metafile(out Value: OLE_HANDLE): HResult; stdcall;
begin
Value := FPicture.Metafile.Handle;
Result := S_OK;
end;
//------------------------------------------------------------------------------
function TfrxPictureView.Set_Metafile(Value: OLE_HANDLE): HResult; stdcall;
begin
FPicture.Metafile.Handle := Value;
Result := S_OK;
end;
//------------------------------------------------------------------------------
function TfrxPictureView.LoadViewFromStream(const Stream: IUnknown): HResult; stdcall;
var
ComStream: IStream;
OleStream: TOleStream;
NetStream: _Stream;
ClrStream: TClrStream;
begin
try
Result := Stream.QueryInterface(IStream, ComStream);
if Result = S_OK then
begin
OleStream := TOleStream.Create(ComStream);
LoadPictureFromStream(OleStream);
OleStream.Free;
ComStream := nil;
end
else
begin
Result := Stream.QueryInterface(_Stream, NetStream);
if Result = S_OK then
begin
ClrStream := TClrStream.Create(NetStream);
LoadPictureFromStream(ClrStream);
ClrStream.Free;
NetStream._Release();
end;
end;
except
Result := E_FAIL;
end;
end;
//------------------------------------------------------------------------------
function TfrxPictureView.SaveViewToStream(const Stream: IUnknown): HResult; stdcall;
var
ComStream: IStream;
OleStream: TOleStream;
NetStream: _Stream;
ClrStream: TClrStream;
begin
try
Result := Stream.QueryInterface(IStream, ComStream);
if Result = S_OK then
begin
OleStream := TOleStream.Create(ComStream);
FPicture.Bitmap.SaveToStream(OleStream);
OleStream.Free;
ComStream._Release();
end
else
begin
Result := Stream.QueryInterface(_Stream, NetStream);
if Result = S_OK then
begin
ClrStream := TClrStream.Create(NetStream);
FPicture.Bitmap.SaveToStream(ClrStream);
ClrStream.Free;
NetStream._Release();
end;
end;
except
Result := E_FAIL;
end;
end;
{$ENDIF}
const
WMFKey = Integer($9AC6CDD7);
WMFWord = $CDD7;
rc3_StockIcon = 0;
rc3_Icon = 1;
rc3_Cursor = 2;
type
TGraphicHeader = record
Count: Word;
HType: Word;
Size: Longint;
end;
TMetafileHeader = packed record
Key: Longint;
Handle: SmallInt;
Box: TSmallRect;
Inch: Word;
Reserved: Longint;
CheckSum: Word;
end;
TCursorOrIcon = packed record
Reserved: Word;
wType: Word;
Count: Word;
end;
//------------------------------------------------------------------------------
const
OriginalPngHeader: array[0..7] of Char = (#137, #80, #78, #71, #13, #10, #26, #10);
//------------------------------------------------------------------------------
function TfrxPictureView.LoadPictureFromStream(s: TStream): Hresult;
var
pos: Integer;
Header: TGraphicHeader;
BMPHeader: TBitmapFileHeader;
{$IFDEF JPEG}
JPEGHeader: array[0..1] of Byte;
{$ENDIF}
{$IFDEF PNG}
PNGHeader: array[0..7] of Char;
{$ENDIF}
EMFHeader: TEnhMetaHeader;
WMFHeader: TMetafileHeader;
ICOHeader: TCursorOrIcon;
NewGraphic: TGraphic;
bOK : Boolean;
begin
NewGraphic := nil;
if s.Size > 0 then
begin
// skip Delphi blob-image header
if s.Size >= SizeOf(TGraphicHeader) then
begin
s.Read(Header, SizeOf(Header));
if (Header.Count <> 1) or (Header.HType <> $0100) or
(Header.Size <> s.Size - SizeOf(Header)) then
s.Position := 0;
end;
pos := s.Position;
bOK := False;
if (s.Size-pos) >= SizeOf(BMPHeader) then
begin
// try bmp header
s.ReadBuffer(BMPHeader, SizeOf(BMPHeader));
s.Position := pos;
if BMPHeader.bfType = $4D42 then
begin
NewGraphic := TBitmap.Create;
bOK := True;
end;
end;
{$IFDEF JPEG}
if not bOK then
begin
if (s.Size-pos) >= SizeOf(JPEGHeader) then
begin
// try jpeg header
s.ReadBuffer(JPEGHeader, SizeOf(JPEGHeader));
s.Position := pos;
if (JPEGHeader[0] = $FF) and (JPEGHeader[1] = $D8) then
begin
NewGraphic := TJPEGImage.Create;
bOK := True;
end;
end;
end;
{$ENDIF}
{$IFDEF PNG}
if not bOK then
begin
if (s.Size-pos) >= SizeOf(PNGHeader) then
begin
// try png header
s.ReadBuffer(PNGHeader, SizeOf(PNGHeader));
s.Position := pos;
if PNGHeader = OriginalPngHeader then
begin
NewGraphic := TPngObject.Create;
bOK := True;
end;
end;
end;
{$ENDIF}
if not bOK then
begin
if (s.Size-pos) >= SizeOf(WMFHeader) then
begin
// try wmf header
s.ReadBuffer(WMFHeader, SizeOf(WMFHeader));
s.Position := pos;
if WMFHeader.Key = WMFKEY then
begin
NewGraphic := TMetafile.Create;
bOK := True;
end;
end;
end;
if not bOK then
begin
if (s.Size-pos) >= SizeOf(EMFHeader) then
begin
// try emf header
s.ReadBuffer(EMFHeader, SizeOf(EMFHeader));
s.Position := pos;
if EMFHeader.dSignature = ENHMETA_SIGNATURE then
begin
NewGraphic := TMetafile.Create;
bOK := True;
end;
end;
end;
if not bOK then
begin
if (s.Size-pos) >= SizeOf(ICOHeader) then
begin
// try icon header
s.ReadBuffer(ICOHeader, SizeOf(ICOHeader));
s.Position := pos;
if ICOHeader.wType in [RC3_STOCKICON, RC3_ICON] then
NewGraphic := TIcon.Create;
end;
end;
end;
if NewGraphic <> nil then
begin
FPicture.Graphic := NewGraphic;
NewGraphic.Free;
FPicture.Graphic.LoadFromStream(s);
Result := S_OK;
end
else
begin
FPicture.Assign(nil);
Result := E_INVALIDARG;
end;
// workaround pngimage bug
{$IFDEF PNG}
if FPicture.Graphic is TPngObject then
PictureChanged(nil);
{$ENDIF}
end;
//------------------------------------------------------------------------------
procedure TfrxPictureView.GetData;
var
m: TMemoryStream;
s: String;
begin
inherited;
if FFileLink <> '' then
begin
s := FFileLink;
if Pos('[', s) <> 0 then
ExpandVariables(s);
if FileExists(s) then
FPicture.LoadFromFile(s)
else
FPicture.Assign(nil);
end
else if IsDataField and DataSet.IsBlobField(DataField) then
begin
m := TMemoryStream.Create;
try
DataSet.AssignBlobTo(DataField, m);
LoadPictureFromStream(m);
finally
m.Free;
end;
end;
end;
//##############################################################################
{ TfrxPictureEditor }
//##############################################################################
type
TfrxPictureEditor = class(TfrxViewEditor)
public
function Edit: Boolean; override;
function HasEditor: Boolean; override;
procedure GetMenuItems; override;
function Execute(Tag: Integer; Checked: Boolean): Boolean; override;
end;
//------------------------------------------------------------------------------
function TfrxPictureEditor.Edit: Boolean;
begin
with TfrxPictureEditorForm.Create(Designer) do
begin
Image.Picture.Assign(TfrxPictureView(Component).Picture);
Result := ShowModal = mrOk;
if Result then
begin
TfrxPictureView(Component).Picture.Assign(Image.Picture);
TfrxDesignerForm(Self.Designer).PictureCache.AddPicture(
TfrxPictureView(Component)
);
end;
Free;
end;
end;
//------------------------------------------------------------------------------
function TfrxPictureEditor.HasEditor: Boolean;
begin
Result := True;
end;
//------------------------------------------------------------------------------
function TfrxPictureEditor.Execute(Tag: Integer; Checked: Boolean): Boolean;
var
i: Integer;
c: TfrxComponent;
p: TfrxPictureView;
begin
Result := inherited Execute(Tag, Checked);
for i := 0 to Designer.SelectedObjects.Count - 1 do
begin
c := Designer.SelectedObjects[i];
if (c is TfrxPictureView) and not (rfDontModify in c.Restrictions) then
begin
p := TfrxPictureView(c);
case Tag of
0: p.AutoSize := Checked;
1: p.Stretched := Checked;
2: p.Center := Checked;
3: p.KeepAspectRatio := Checked;
end;
Result := True;
end;
end;
end;
//------------------------------------------------------------------------------
procedure TfrxPictureEditor.GetMenuItems;
var
p: TfrxPictureView;
begin
p := TfrxPictureView(Component);
AddItem(frxResources.Get('pvAutoSize'), 0, p.AutoSize);
AddItem(frxResources.Get('mvStretch'), 1, p.Stretched);
AddItem(frxResources.Get('pvCenter'), 2, p.Center);
AddItem(frxResources.Get('pvAspect'), 3, p.KeepAspectRatio);
AddItem('-', -1);
inherited;
end;
//##############################################################################
{ TfrxPictureProperty }
//##############################################################################
type
TfrxPictureProperty = class(TfrxClassProperty)
public
function GetValue: String; override;
function GetAttributes: TfrxPropertyAttributes; override;
function Edit: Boolean; override;
end;
//------------------------------------------------------------------------------
function TfrxPictureProperty.GetAttributes: TfrxPropertyAttributes;
begin
Result := [paDialog, paReadOnly];
end;
//------------------------------------------------------------------------------
function TfrxPictureProperty.Edit: Boolean;
var
Pict: TPicture;
begin
with TfrxPictureEditorForm.Create(Designer) do
begin
Pict := TPicture(GetOrdValue);
Image.Picture.Assign(Pict);
Result := ShowModal = mrOk;
if Result then
Pict.Assign(Image.Picture);
Free;
end;
end;
//------------------------------------------------------------------------------
function TfrxPictureProperty.GetValue: String;
var
Pict: TPicture;
begin
Pict := TPicture(GetOrdValue);
if Pict.Graphic = nil then
Result := frxResources.Get('prNotAssigned') else
Result := frxResources.Get('prPict');
end;
//##############################################################################
frxObjects.RegisterObject1(TfrxPictureView, nil, '', '', 0, 3);
frxComponentEditors.Register(TfrxPictureView, TfrxPictureEditor);
frxPropertyEditors.Register(TypeInfo(TPicture), nil, '', TfrxPictureProperty);
frxHideProperties(TfrxPictureView, 'ImageIndex');
//##############################################################################
|
unit uFileDownloadThread;
interface
uses
Classes, FileLoader, SysUtils;
type
TDownloadMode = (dmDirectoty, dmFileServer, dmHTTPServer);
TFileDownloadThread = class(TThread)
private
FError : string;
procedure AddError(AMsg : string);
protected
procedure Execute; override;
procedure FileCopyProgress(Sender : TObject; Size : integer);
public
// Режим
DownloadMode : TDownloadMode;
ServerPath, DestPath, Filename : string;
DownloadComplete : boolean;
LoadedSize : integer;
procedure ExecuteDownload;
end;
implementation
uses OraUtil, zutil;
{ TFileDownloadThread }
procedure TFileDownloadThread.AddError(AMsg: string);
begin
AddToList(FError, AMsg, ';');
end;
procedure TFileDownloadThread.Execute;
begin
DownloadComplete := false;
ExecuteDownload;
DownloadComplete := true;
end;
procedure TFileDownloadThread.ExecuteDownload;
var
FileLoader : TCustomFileLoader;
Res : boolean;
begin
DownloadComplete := false;
FileLoader := nil;
LoadedSize := 0;
// Создание соответствующего класса для закачки файлов
case DownloadMode of
dmDirectoty : FileLoader := TDirectoryFileLoader.Create;
dmFileServer : FileLoader := TDirectoryFileLoader.Create;
dmHTTPServer : FileLoader := THTTPFileLoader.Create;
end;
// Выход, если тип загрузки не поддерживается
if FileLoader = nil then exit;
// 1. Создание каталогов
ForceDirectories(DestPath);
// 2 Проверка, созданы ли каталоги
// 2.1 Проверка, создан ли каталог TempPath
if not(DirectoryExists(DestPath)) then begin
AddError('Не удалось создать каталог '+DestPath);
exit;
end;
try
FileLoader.OnFileCopyProgress := FileCopyProgress;
Res := FileLoader.LoadFile(ServerPath + Filename, DestPath + Filename);
finally
FileLoader.Free;
DownloadComplete := true;
end;
end;
procedure TFileDownloadThread.FileCopyProgress(Sender: TObject;
Size: integer);
begin
LoadedSize := Size;
end;
end.
|
unit DataORs;
// TORsTableData - trida resici vypisovani oblasti rizeni do tabulky
interface
uses ComCtrls, SysUtils;
type
TORsTableData=class
private
LV:TListView;
public
procedure LoadToTable();
procedure UpdateTable(force:boolean = false);
constructor Create(LV:TListView);
end;
var
ORsTableData : TORsTableData;
implementation
uses TOblsRizeni, TOblRizeni;
////////////////////////////////////////////////////////////////////////////////
constructor TORsTableData.Create(LV:TListView);
begin
inherited Create();
Self.LV := LV;
end;//ctor
////////////////////////////////////////////////////////////////////////////////
procedure TORsTableData.LoadToTable();
var LI:TListItem;
i, j:Integer;
begin
Self.LV.Clear;
for i := 0 to ORs.Count-1 do
begin
LI := Self.LV.Items.Add;
LI.Caption := IntToStr(i);
for j := 0 to Self.LV.Columns.Count-2 do
LI.SubItems.Add('---');
end;//for i
Self.UpdateTable(true);
end;//procedure
////////////////////////////////////////////////////////////////////////////////
procedure TORsTableData.UpdateTable(force:boolean = false);
var i:Integer;
OblR:TOR;
begin
for i := 0 to ORs.Count-1 do
begin
ORs.GetORByIndex(i, OblR);
if ((OblR.changed) or (force)) then
begin
OblR.UpdateLine(Self.LV.Items.Item[i]);
OblR.changed := false;
end;
end;
end;//procedure
////////////////////////////////////////////////////////////////////////////////
initialization
finalization
ORsTableData.Free();
end.//unit
|
unit DialogStickerTare;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, AncestorDialogScale, StdCtrls, Mask, Buttons,
ExtCtrls, cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus,
dxSkinsCore, dxSkinsDefaultPainters, cxControls, cxContainer, cxEdit,
cxTextEdit, cxCurrencyEdit, dsdDB, Vcl.ActnList, dsdAction, cxPropertiesStore,
dsdAddOn, cxButtons, Vcl.ComCtrls, dxCore, cxDateUtils, cxCheckBox,
cxMaskEdit, cxDropDownEdit, cxCalendar, cxLabel;
type
TDialogStickerTareForm = class(TAncestorDialogScaleForm)
PanelValue: TPanel;
cxLabel3: TcxLabel;
deDateTare: TcxDateEdit;
cbTare: TcxCheckBox;
cbGoodsName: TcxCheckBox;
cbPartion: TcxCheckBox;
cxLabel2: TcxLabel;
cxLabel4: TcxLabel;
deDateProduction: TcxDateEdit;
deDatePack: TcxDateEdit;
edPartion: TcxLabel;
cxLabel5: TcxLabel;
ceNumTech: TcxCurrencyEdit;
ceNumPack: TcxCurrencyEdit;
private
function Checked: boolean; override;//Проверка корректного ввода в Edit
public
NumberValue:Integer;
end;
var
DialogStickerTareForm: TDialogStickerTareForm;
implementation
{$R *.dfm}
{------------------------------------------------------------------------------}
function TDialogStickerTareForm.Checked: boolean; //Проверка корректного ввода в Edit
var NumberValue : Integer;
begin
Result:= true;
//
if (cbTare.Checked = TRUE) and (cbPartion.Checked = FALSE) then
begin
try StrToDate (deDateTare.Text); except Result:= false; end;
end;
//
if (cbTare.Checked = TRUE) and (cbPartion.Checked = TRUE) then
begin
try StrToDate (deDatePack.Text); except Result:= false; end;
try StrToDate (deDateProduction.Text);except Result:= false; end;
//
if Result then
begin
try NumberValue:= StrToInt (ceNumPack.Text);except NumberValue:=0;end;
Result:= NumberValue > 0;
end;
//
if Result then
begin
try NumberValue:=StrToInt(ceNumTech.Text);except NumberValue:=0;end;
Result:=NumberValue>0;
end;
end;
end;
{------------------------------------------------------------------------------}
end.
|
unit Unit2;
interface
type CNumeroNatural = class
Private
Valor : Cardinal;
Function LiteralDigitos(V1,V2 : Cardinal) : String;
Public
Constructor Crear;
Procedure AsignarValor( NuevoValor : Cardinal);
Function ObtenerValor : Cardinal;
Function NumeroDigitos : Byte;
Function Digito( Posicion : Byte ) : Byte;
Function SumarDigitos : Byte;
Function DigitosPares : Byte;
Function DigitosImpares : Byte;
Procedure Invertir;
Function EsPar : Boolean;
Function EsImpar : Boolean;
Function EsCapicua : Boolean;
Function BaseN( N : Byte ) : String;
Function Hexa : String;
Function Romano : String;
Function Literal : String;
Procedure InsertarDigito( Posicion: Byte ; Digito : Byte);
Procedure EliminarDigito( Posicion : Byte );
Function BaseNS(conjunto : string) : string;
end;
implementation
//CONSTRUCTOR
Constructor CNumeroNatural.Crear;
Begin
Valor := 0;
End;
//PROCEDIMIENTO DE ASIGNAR VALOR
Procedure CNumeroNatural.AsignarValor( NuevoValor : Cardinal);
Begin
Valor := NuevoValor;
End;
//DEVOLVER EL VALOR
Function CNumeroNatural.ObtenerValor : Cardinal;
Begin
Result := Valor;
End;
//CANTIDAD DE DIGITOS
Function CNumeroNatural.NumeroDigitos : Byte;
Var
Aux : Cardinal;
Cant : Byte;
Begin
Aux := Valor;
Cant := 0;
While Aux>0 do
Begin
Aux := Aux Div 10;
Inc( Cant );
End;
Result := Cant;
End;
//N-ESIMO DIGITO
Function CNumeroNatural.Digito( Posicion : Byte ) : Byte;
Var
Aux,Res : Cardinal;
Vez , Digito : Byte; NroDigitos:Byte;
Begin
Aux := Valor;
NroDigitos:= Trunc(Ln(Valor)/Ln(10)) +1;
if( Posicion > 0 )and( Posicion <= NroDigitos )then
Begin
Vez:=1;
While aux>0 do
Begin
if (((Nrodigitos+1) - Vez) = Posicion) then Digito:=Aux mod 10;
Res:=Aux Div 10;
Vez:=Vez +1;
Aux:=Res;
End;
Result := Digito;
End
End;
//SUMA DE LOS DIGITOS
Function CNumeroNatural.SumarDigitos : Byte;
Var
Aux , Suma : Cardinal;
Begin
Aux := Valor;
Suma := 0;
Repeat
Suma := Suma +( Aux Mod 10 );
Aux := Aux Div 10;
Until( Aux = 0 );
Result := Suma;
End;
//DIGITOS PARES
Function CNumeroNatural.DigitosPares : Byte;
Var
Aux : Cardinal;
Cant , Digito : Byte;
Begin
Aux := Valor;
Cant := 0;
Repeat
Digito := Aux Mod 10;
Aux := Aux Div 10;
If( Digito mod 2 = 0 )Then Inc( Cant );
Until( Aux = 0 );
Result := Cant;
End;
//CANTIDAD DIGITOS IMPARES
Function CNumeroNatural.DigitosImpares : Byte;
Begin
Result := (NumeroDigitos - DigitosPares);
End;
//INVERTIR NUMERO
Procedure CNumeroNatural.Invertir;
Var
Aux , Aux2 , i :Cardinal;
Begin
Aux2 := Valor;
Aux := 0;
i := 0;
While( i < NumeroDigitos )do
Begin
Aux := ( Aux * 10 ) + Aux2 Mod 10;
Aux2 := Aux2 Div 10;
Inc( i );
End;
Valor := Aux;
End;
//ES PAR
Function CNumeroNatural.EsPar : Boolean;
Begin
Result := (valor mod 2)= 0 ;
End;
//ES IMPAR
Function CNumeroNatural.EsImpar : Boolean;
Begin
Result := Not (Espar) ;
End;
//ES CAPICUA
Function CNumeroNatural.EsCapicua : Boolean;
Var N:Cardinal;R:Boolean;
Begin
N:=Valor; Invertir;
R:=(Valor = N) ;
Valor:=N;
Result := R;
End;
//BASE N
Function CNumeroNatural.BaseN( N : Byte ) : String;
var
aux,i : Cardinal;
bn,answer : string;
begin
aux:=Valor;
while (aux>0) do
begin
case (aux mod N) of
0 : bn:=bn + '0';
1 : bn:=bn + '1';
2 : bn:=bn + '2';
3 : bn:=bn + '3';
4 : bn:=bn + '4';
5 : bn:=bn + '5';
6 : bn:=bn + '6';
7 : bn:=bn + '7';
8 : bn:=bn + '8';
9 : bn:=bn + '9';
10 : bn:=bn + 'A';
11 : bn:=bn + 'B';
12 : bn:=bn + 'C';
13 : bn:=bn + 'D';
14 : bn:=bn + 'E';
15 : bn:=bn + 'F';
end;
aux := aux div N;
end;
for i := length(bn) downto 1 do
begin
answer:=answer+bn[i];
end;
Result:=answer;
end;
//BASE HEXADECIMAL
Function CNumeroNatural.Hexa : string;
begin
Result := BaseN(16);
end;
//ROMANO
Function CNumeroNatural.Romano : string;
const
M : array [0..3] of string = ('', 'M', 'MM', 'MMM');
C : array [0..9] of string = ('','C','CC','CCC','CD','D','DC','DCC','DCCC','CM');
X : array [0..9] of string = ('', 'X', 'XX', 'XXX', 'XL', 'L','LX', 'LXX', 'LXXX', 'XC');
I : array [0..9] of string = ('', 'I', 'II', 'III', 'IV', 'V','VI', 'VII', 'VIII', 'IX');
var
milesima,centesima,decima,unidad : string;
aux : Cardinal;
begin
aux := Valor;
milesima := M[aux div 1000];
centesima := C[(aux mod 1000) div 100];
decima := X[(aux mod 100) div 10];
unidad := I[aux mod 10];
Result:= (milesima+centesima+decima+unidad);
end;
//LITERAL AUXILIAR (PRIVATE)
Function CNumeroNatural.LiteralDigitos(V1, V2 : Cardinal) : String;
const
c : array [0..9] of string = ('','cien', 'doscientos', 'trescientos', 'cuatrocientos' , 'quinientos' , 'seiscientos' , 'setecientos' , 'ochocientos', 'novecientos');
d : array [0..9] of string = ('','','veinti','treinta','cuarenta','cincuenta','sesenta','setenta','ochenta','noventa');
e : array [0..20] of string = ('','uno','dos','tres','cuatro','cinco','seis','siete','ocho','nueve','diez','once','doce','trece','catorece','quince','dieciseis','diecisiete','dieciocho','diecinueve','veinte');
var
aux : Cardinal;
s : string;
begin
aux := V1;
if((aux=0) and (V2=0)) then s:='Cero';
if((aux>=1) and (aux<=20)) then s:=e[aux] else
begin
s:= s + c[aux div 100];
if((aux>100) and (aux<200)) then s:=s+'to';
s:=s+' ';
if((aux mod 100 >=10) and (aux mod 100 <=20)) then s:=s+e[ aux mod 100 ] else
begin
s:=s+d[ (aux mod 100)div 10 ];
if ((aux mod 10 > 0) and ((aux mod 100)>30) and ((aux mod 100) < 100 )) then s:=s+' y ';
s:= s + e[aux mod 10];
end;
end;
Result:=s;
end;
//LITERAL
Function CNumeroNatural.Literal : string ;
var
lit : string;
aux : Cardinal;
begin
aux := Valor;
if((aux<2000) and (aux>=1000)) then lit:=lit+'mil ';
if(aux>=2000) then lit:=lit+LiteralDigitos(aux div 1000,aux) + ' mil ';
aux:= aux mod 1000;
lit:=lit+LiteralDigitos(aux,Valor);
Result:=lit;
end;
//INSERTAR DIGITO
Procedure CNumeroNatural.InsertarDigito( Posicion: Byte ; Digito : Byte);
Var
Aux , Aux2 , Digi :Cardinal;
Begin
Aux := Valor;
if( Posicion > 0)and( Posicion <= numeroDigitos) then
Begin
Aux2 := 0;
Digi := 0;
While( Digi <= NumeroDigitos-Posicion )do
Begin
Aux2 := ( Aux2 * 10 ) + Aux Mod 10;
Aux := Aux Div 10;
Inc( Digi );
End;
Aux := ( Aux * 10 ) + Digito;//Inserta Digito
While( Digi > 0 )do
Begin
Aux := ( Aux * 10 ) + ( Aux2 Mod 10 );
Aux2 := Aux2 Div 10;
Dec( Digi );
End;
Valor := Aux;
end;
End;
// ELIMINAR DIGITO
Procedure CNumeroNatural.EliminarDigito( Posicion : Byte );
Var
Aux , Aux2 , Digi :Cardinal;
Begin
Aux := Valor;
if( Posicion > 0) and ( Posicion <= NumeroDigitos ) then
Begin
Aux2 := 0;
Digi := 0;
While ( Digi < NumeroDigitos-Posicion ) do
Begin
Aux2 := ( Aux2 * 10 ) + Aux Mod 10;
Aux := Aux Div 10;
Inc( Digi );
End;
Aux := ( Aux Div 10 );//Elimina Digito
While( Digi > 0 )do
Begin
Aux := ( Aux * 10 ) + ( Aux2 Mod 10 );
Aux2 := Aux2 Div 10;
Dec( Digi );
End;
Valor := Aux;
End;
End;
//BASE N con conjunto de digitos variados
Function CNumeroNatural.BaseNS(conjunto: string) : string;
var
aux : Cardinal;
base,i : Byte;
ans,ss : string;
begin
aux := Valor;
base:=length(conjunto);
while(aux>0)do
begin
ans:=ans + conjunto[(aux mod base)+1];
aux:=aux div base;
end;
for i := length(ans) downto 1 do
begin
ss:=ss+ans[i];
end;
Result:=ss;
end;
begin
end.
|
unit WiRL.Wizards.Modules.MainForm;
interface
uses
WiRL.Wizards.Utils,
ToolsAPI;
resourcestring
SWiRLServerMainFormSRC = 'WiRLServerMainFormSRC';
SWiRLServerMainFormDFM = 'WiRLServerMainFormDFM';
SMainFormFileName = 'ServerMainForm';
type
TWiRLServerMainFormCreator = class(TInterfacedObject, IOTACreator, IOTAModuleCreator)
public
// IOTACreator
function GetCreatorType: string;
function GetExisting: Boolean;
function GetFileSystem: string;
function GetOwner: IOTAModule;
function GetUnnamed: Boolean;
// IOTAModuleCreator
function GetAncestorName: string;
function GetImplFileName: string;
function GetIntfFileName: string;
function GetFormName: string;
function GetMainForm: Boolean;
function GetShowForm: Boolean;
function GetShowSource: Boolean;
function NewFormFile(const FormIdent, AncestorIdent: string): IOTAFile;
function NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile;
function NewIntfSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile;
procedure FormCreated(const FormEditor: IOTAFormEditor);
end;
implementation
uses
System.SysUtils;
{$REGION 'IOTACreator'}
function TWiRLServerMainFormCreator.GetCreatorType: string;
begin
Result := sForm;
end;
function TWiRLServerMainFormCreator.GetExisting: Boolean;
begin
Result := False;
end;
function TWiRLServerMainFormCreator.GetFileSystem: string;
begin
Result := '';
end;
function TWiRLServerMainFormCreator.GetOwner: IOTAModule;
begin
Result := ActiveProject;
end;
function TWiRLServerMainFormCreator.GetUnnamed: Boolean;
begin
Result := True;
end;
{$ENDREGION}
{$REGION 'IOTAModuleCreator'}
function TWiRLServerMainFormCreator.GetAncestorName: string;
begin
Result := 'TForm';
end;
function TWiRLServerMainFormCreator.GetImplFileName: string;
begin
Result := GetCurrentDir + '\' + SMainFormFileName + '.pas';
end;
function TWiRLServerMainFormCreator.GetIntfFileName: string;
begin
Result := '';
end;
function TWiRLServerMainFormCreator.GetFormName: string;
begin
Result := 'MainForm';
end;
function TWiRLServerMainFormCreator.GetMainForm: Boolean;
begin
Result := True;
end;
function TWiRLServerMainFormCreator.GetShowForm: Boolean;
begin
Result := True;
end;
function TWiRLServerMainFormCreator.GetShowSource: Boolean;
begin
Result := True;
end;
function TWiRLServerMainFormCreator.NewFormFile(const FormIdent, AncestorIdent: string): IOTAFile;
begin
Result := TWiRLSourceFile.Create(SWiRLServerMainFormDFM);
end;
function TWiRLServerMainFormCreator.NewImplSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile;
begin
Result := TWiRLSourceFile.Create(SWiRLServerMainFormSRC);
end;
function TWiRLServerMainFormCreator.NewIntfSource(const ModuleIdent, FormIdent, AncestorIdent: string): IOTAFile;
begin
Result := NIL;
end;
procedure TWiRLServerMainFormCreator.FormCreated(const FormEditor: IOTAFormEditor);
begin
end;
{$ENDREGION}
end.
|
unit UtilsWindows_Application;
interface
uses
Windows, Sysutils;
function GetWndClassName(AWnd: HWND): AnsiString;
function GetWndTextName(AWnd: HWND): AnsiString;
procedure ForceBringFrontWindow(AWnd: HWND);
procedure SimulateKeyPress(AKeyCode: Byte; ASleep: Integer);
function ClickButtonWnd(AWnd: HWND): Boolean;
function InputEditWnd(AWnd: HWND; AValue: AnsiString): Boolean;
implementation
uses
UtilsApplication;
function InputEditWnd(AWnd: HWND; AValue: AnsiString): Boolean;
var
i: integer;
tmpValue: AnsiString;
tmpKeyCode: Byte;
begin
Result := false;
if not IsWindow(AWnd) then
exit;
ForceBringFrontWindow(AWnd);
SleepWait(20);
for i := 1 to 8 do
begin
SimulateKeyPress(VK_BACK, 20);
SimulateKeyPress(VK_DELETE, 20);
end;
tmpValue := UpperCase(AValue);
for i := 1 to Length(tmpValue) do
begin
if '.' = tmpValue[i] then
begin
tmpKeyCode := VK_DECIMAL;
end else
begin
tmpKeyCode := Byte(tmpValue[i]);
end;
SimulateKeyPress(tmpKeyCode, 20);
end;
Result := true;
end;
procedure ForceBringFrontWindow(AWnd: HWND);
var
wnd: HWND;
processid: DWORD;
begin
wnd := GetForegroundWindow;
GetWindowThreadProcessId(wnd, processid);
AttachThreadInput(processid, GetCurrentThreadId(), TRUE);
if Windows.GetForegroundWindow <> AWnd then
begin
SetForegroundWindow(AWnd);
end;
if Windows.GetFocus <> AWnd then
begin
SetFocus(AWnd);
end;
// wnd := GetForegroundWindow;
// GetWindowThreadProcessId(wnd, processid);
AttachThreadInput(processid, GetCurrentThreadId(), FALSE);
end;
function GetWndClassName(AWnd: HWND): AnsiString;
var
tmpAnsi: array[0..255] of AnsiChar;
begin
FillChar(tmpAnsi, SizeOf(tmpAnsi), 0);
GetClassNameA(AWnd, @tmpAnsi[0], Length(tmpAnsi));
Result := lowercase(tmpAnsi);
end;
function GetWndTextName(AWnd: HWND): AnsiString;
var
tmpAnsi: array[0..255] of AnsiChar;
begin
FillChar(tmpAnsi, SizeOf(tmpAnsi), 0);
GetWindowTextA(AWnd, @tmpAnsi[0], Length(tmpAnsi));
Result := lowercase(tmpAnsi);
end;
procedure SimulateKeyPress(AKeyCode: Byte; ASleep: Integer);
var
tmpSleep: integer;
begin
Windows.keybd_event(AKeyCode, MapVirtualKey(AKeyCode, 0), 0, 0) ;//#a¼üλÂëÊÇ86
Windows.keybd_event(AKeyCode, MapVirtualKey(AKeyCode, 0), KEYEVENTF_KEYUP, 0);
tmpSleep := ASleep;
while 0 < tmpSleep do
begin
UtilsApplication.SleepWait(10);
//Application.ProcessMessages;
tmpSleep := tmpSleep - 10;
end;
end;
function ClickButtonWnd(AWnd: HWND): Boolean;
var
tmpRect: TRect;
begin
Result := false;
if IsWindow(AWnd) then
begin
ForceBringFrontWindow(AWnd);
GetWindowRect(AWnd, tmpRect);
Windows.SetCursorPos((tmpRect.Left + tmpRect.Right) div 2, (tmpRect.Top + tmpRect.Bottom) div 2);
SleepWait(20);
Windows.mouse_event(MOUSEEVENTF_LEFTDOWN or MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);
SleepWait(20);
Result := true;
end;
end;
end.
|
object Grid: TGrid
OldCreateOrder = False
PageProducer = AdapterPageProducer
Left = 143
Top = 4
Height = 150
Width = 215
object AdapterPageProducer: TAdapterPageProducer
HTMLDoc.Strings = (
'<html>'
'<head>'
'</head>'
'<body>'
'<#STYLES><#WARNINGS><#SERVERSCRIPT>'
'</body>'
'</html>')
Left = 48
Top = 8
object AdapterForm1: TAdapterForm
object AdapterGrid1: TAdapterGrid
Adapter = WebDataModule1.DataSetAdapter1
object ColSpeciesNo: TAdapterDisplayColumn
Caption = 'Species No'
FieldName = 'SpeciesNo'
end
object ColCategory: TAdapterDisplayColumn
FieldName = 'Category'
end
object ColCommon_Name: TAdapterDisplayColumn
FieldName = 'Common_Name'
end
object ColSpeciesName: TAdapterDisplayColumn
Caption = 'Species Name'
FieldName = 'SpeciesName'
end
object ColLengthcm: TAdapterDisplayColumn
Caption = 'Length (cm)'
FieldName = 'Lengthcm'
end
object ColLength_In: TAdapterDisplayColumn
FieldName = 'Length_In'
end
object ColGraphic: TAdapterDisplayColumn
FieldName = 'Graphic'
end
object AdapterCommandColumn1: TAdapterCommandColumn
object CmdEditRow: TAdapterActionButton
ActionName = 'EditRow'
PageName = 'Modify'
end
end
end
end
end
end
|
unit ClothesReg.View;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs,
Common.Form, FMX.Edit, FMX.StdCtrls, FMX.ListBox, FMX.Controls.Presentation,
Database.Types,
Clothes.Classes, Clothes.DataModule, Clothes.ViewModel, ClothesTypesReg.View,
Data.Bind.Components, Data.Bind.DBScope, System.Rtti, System.Bindings.Outputs,
Fmx.Bind.Editors, Data.Bind.EngExt, Fmx.Bind.DBEngExt, FMX.Grid.Style,
Fmx.Bind.Grid, Data.Bind.Grid, FMX.ScrollBox, FMX.Grid;
type
TfrmClothesReg = class(TCommonForm)
cbbClothesTypes: TComboBox;
lbl1: TLabel;
lbl2: TLabel;
edtSN: TEdit;
btnNew: TSpeedButton;
grpEmployee: TGroupBox;
edt1: TEdit;
btn1: TSpeedButton;
procedure btnNewClick(Sender: TObject);
procedure btnCloseClick(Sender: TObject);
private
FViewModel: TClothesViewModel;
FClothes: TClothes;
FOperation: TOperation;
procedure GetCtrlVals;
procedure ClothesTypeRegForm(const AnOperation: TOperation = opInsert);
{ Private declarations }
public
constructor Create(AOwner: TComponent; AViewModel: TClothesViewModel; AnOperation: TOperation = opInsert); reintroduce;
{ Public declarations }
end;
var
frmClothesReg: TfrmClothesReg;
implementation
{$R *.fmx}
{ TForm3 }
procedure TfrmClothesReg.btnCloseClick(Sender: TObject);
begin
GetCtrlVals;
inherited;
end;
procedure TfrmClothesReg.btnNewClick(Sender: TObject);
begin
inherited;
ClothesTypeRegForm();
end;
procedure TfrmClothesReg.ClothesTypeRegForm(const AnOperation: TOperation);
var
frmClothesTypeReg: TfrmClothesTypeReg;
mr: TModalResult;
begin
frmClothesTypeReg := TfrmClothesTypeReg.Create(Self, FViewModel);
try
mr := frmClothesTypeReg.ShowModal;
// FViewModel.SaveClothesTypesDataset(mr);
if mr = mrOk then
begin
cbbClothesTypes.Items.AddObject(frmClothesTypeReg.ClothesType.Name, frmClothesTypeReg.ClothesType);
cbbClothesTypes.ItemIndex := cbbClothesTypes.Items.IndexOf(frmClothesTypeReg.ClothesType.Name);
end;
finally
FreeAndNil(frmClothesTypeReg);
end;
end;
constructor TfrmClothesReg.Create(AOwner: TComponent;
AViewModel: TClothesViewModel;
AnOperation: TOperation = opInsert);
begin
inherited Create(AOwner);
FViewModel := AViewModel;
FClothes := FViewModel.Clothes;
FOperation := AnOperation;
FViewModel.FillComboBox(cbbClothesTypes);
end;
procedure TfrmClothesReg.GetCtrlVals;
begin
FClothes.SN := edtSN.Text;
FClothes.ClothesType := TClothesType(cbbClothesTypes.Items.Objects[cbbClothesTypes.ItemIndex]);
end;
end.
|
{*!
* Fano Web Framework (https://fanoframework.github.io)
*
* @link https://github.com/fanoframework/fano
* @copyright Copyright (c) 2018 Zamrony P. Juhara
* @license https://github.com/fanoframework/fano/blob/master/LICENSE (MIT)
*}
unit TermSignalImpl;
interface
{$MODE OBJFPC}
{$H+}
uses
BaseUnix,
Unix;
var
//pipe handle that we use to monitor if we get SIGTERM/SIGINT signal
terminatePipeIn, terminatePipeOut : longint;
implementation
(*!-----------------------------------------------
* make listen socket non blocking
*-------------------------------------------------
* @param listenSocket, listen socket handle
*-----------------------------------------------*)
procedure makeNonBlocking(fd : longint);
var flags : longint;
begin
//read control flag and set listen socket to be non blocking
flags := fpFcntl(fd, F_GETFL, 0);
fpFcntl(fd, F_SETFl, flags or O_NONBLOCK);
end;
(*!-----------------------------------------------
* signal handler that will be called when
* SIGTERM, SIGINT and SIGQUIT is received
*-------------------------------------------------
* @param sig, signal id i.e, SIGTERM, SIGINT or SIGQUIT
* @param info, information about signal
* @param ctx, contex about signal
*-------------------------------------------------
* Signal handler must be ordinary procedure
*-----------------------------------------------*)
procedure doTerminate(sig : longint; info : PSigInfo; ctx : PSigContext); cdecl;
var ch : char;
begin
//write one byte to mark termination
ch := '.';
fpWrite(terminatePipeOut, ch, 1);
end;
(*!-----------------------------------------------
* install signal handler
*-------------------------------------------------
* @param aSig, signal id i.e, SIGTERM, SIGINT or SIGQUIT
*-----------------------------------------------*)
procedure installTerminateSignalHandler(aSig : longint);
var oldAct, newAct : SigactionRec;
begin
fillChar(newAct, sizeOf(SigactionRec), #0);
fillChar(oldAct, sizeOf(Sigactionrec), #0);
newAct.sa_handler := @doTerminate;
fpSigaction(aSig, @newAct, @oldAct);
end;
procedure makePipeNonBlocking(termPipeIn: longint; termPipeOut : longint);
begin
//read control flag and set pipe in to be non blocking
makeNonBlocking(termPipeIn);
//read control flag and set pipe out to be non blocking
makeNonBlocking(termPipeOut);
end;
initialization
//setup non blocking pipe to use for signal handler.
//Need to be done before install handler to prevent race condition
assignPipe(terminatePipeIn, terminatePipeOut);
makePipeNonBlocking(terminatePipeIn, terminatePipeOut);
//install signal handler after pipe setup
installTerminateSignalHandler(SIGTERM);
installTerminateSignalHandler(SIGINT);
installTerminateSignalHandler(SIGQUIT);
finalization
fpClose(terminatePipeIn);
fpClose(terminatePipeOut);
end.
|
unit uClassUtil;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, sqldb, DB;
type
TUtil = class(TObject)
private
public
class function incrementaChavePrimaria(conexao: TSQLConnection; nomeTabela: String; nomeCampoChavePrimaria: String): Integer;
class procedure validar_Email(email: string);
class procedure CheckCPF (sCPF : String);
class procedure CheckCGC(sCGC: String);
class function tirarMascara(const valorCampo: String): String;
class function mensagemErro(e: Exception): string;
end;
implementation
const
msgCGC_CPFInvalido ='%s Inválido !!!';
class function TUtil.incrementaChavePrimaria(conexao: TSQLConnection; nomeTabela: String; nomeCampoChavePrimaria: String): Integer;
var
qry: TSQLQuery;
begin
qry := TSQLQuery.Create(nil);
qry.SQLConnection := conexao;
try
qry.SQL.Add('select max(' + nomeCampoChavePrimaria + ') from ' + nomeTabela);
qry.Open;
result := qry.Fields[0].AsInteger + 1;
finally
qry.Close;
qry.Free;
end;
end;
class procedure TUtil.validar_Email(email: string);
const
csLetra = 'abcdefghijklmnopqrstuvwyxzABCDEFGHIJKLMNOPQRSTUVWYXZ';
csNumero = '0123456789';
csEspecial = '-_';
csArrouba = '@';
csPonto = '.';
csDoisPontos = '..';
var
vsiCont : Shortint;
vsiTamanho : Shortint;
vsiPosicaoPrimeiroArrouba : Shortint;
vcPrimeiroCaractere : String;
vsDominio : String;
emailValido: boolean;
begin
emailValido := True;
vsiTamanho := length(email);
vcPrimeiroCaractere := copy(email,1,1);
vsiPosicaoPrimeiroArrouba := pos(csArrouba,email);
vsDominio := copy(email,vsiPosicaoPrimeiroArrouba + 1, vsiTamanho - vsiPosicaoPrimeiroArrouba);
//Verifica se não tem caracteres brancos no fim e no começo
//Não está na especificação, mas objetiva evitar bugs
if email <> trim(email) then emailValido := false else
//Verifica se inicia com número
if pos(vcPrimeiroCaractere,csNumero) > 0 then emailValido := false else
//Verifica se contêm pelo menos um @
if vsiPosicaoPrimeiroArrouba = 0 then emailValido := false else
//Verifica se contêm mais de um @, é o mesmo que perguntar se existe @ no domínio
if pos(csArrouba,vsDominio) > 0 then emailValido := false else
//Verifica se existe pelo memos um "." após o @
if pos(csPonto,vsDominio) = 0 then emailValido := false else
//Verifica se existe dois pontos juntos
if pos(csDoisPontos,email) > 0 then emailValido := false else
//Verifica se existe algum caractere inválido
for vsiCont := 1 to vsiTamanho do
begin
if pos(copy(email,vsiCont,1), (csLetra + csNumero + csEspecial + csArrouba + csPonto)) = 0 then emailValido := false;
end;
if not emailValido then
raise Exception.Create('O e-mail informado não é válido.');
end;
(******************************************************************************)
(* Implementação da Classe. *)
(******************************************************************************)
(******************************************************************************)
(* Function : TUtil.tirarMascaraNumeros *)
(* Descrição : Função para retirar a mascara de conteúdo numérico *)
(* Parâmetro : valorCampo, conteúdo numérico de onde será retirada a máscara*)
(* Retorno : valorCampo sem a máscara. *)
(******************************************************************************)
class function TUtil.tirarMascara(const valorCampo: String): String;
var
iIndice : Integer; { Indice para poder varrer a entrada }
begin
Result := '';
//Varre a string com o CGC/CPF p/ tirar a máscara.
for iIndice := 1 to length(valorCampo) do
if valorCampo[iIndice] in ['0'..'9'] then
Result := Result + valorCampo[iIndice]; //Pega o CGC/CPF sem a máscara.
end;
(******************************************************************************)
(* Function : CheckCPF *)
(* Descrição : Função para verificar a validez do CPF *)
(* Parâmetro : sCPF - CPF p/ verificação. *)
(* Retorno : True => CPF valido *)
(* False => CPF inválido *)
(******************************************************************************)
class procedure TUtil.CheckCPF(sCPF: String);
var
aiDigito : array[1..11] of integer; { Digitos do CPF }
iIndice : integer; { Indice dos digitos }
{%H-}iErro : integer; { Variavel de Erro ( string -> integer ) }
iMultiplicador : integer; { Fator de Multiplicacao }
iTotal : integer; { Total para os Calculos }
cpfValido : boolean;
begin
try
//Zera o acumulador dos dígitos do CPF.
iTotal := 0;
//Pega o CPF sem máscara.
sCPF := TUtil.tirarMascara(sCPF);
//Usado para verificar os dígitos que estão antes do dg verificador.
iMultiplicador := 10;
//1º verificação do CPF.
cpfValido := (sCPF.Length = 11);
//Se for identidficado um erro gerar exceção.
if not cpfValido then
raise Exception.Create(Format(msgCGC_CPFInvalido, ['CPF']));
//Converte o String em um Integer.
for iIndice := 1 to 11 do Val(sCPF[iIndice], aiDigito[iIndice], iErro);
//Acumula os dígitos do CPF.
for iIndice := 1 to 9 do
begin
iTotal := iTotal + aiDigito[iIndice] * iMultiplicador;
Dec(iMultiplicador);
end;
//2º verificação do CPF.
cpfValido := ((((iTotal * 10) mod 11) = aiDigito[10]) or
(((iTotal * 10) mod 11) = aiDigito[10] + 10));
//Se for identidficado um erro gerar exceção.
if not cpfValido then
raise Exception.Create(Format(msgCGC_CPFInvalido, ['CPF']));
//Zera o acumulador dos dígitos do CPF.
iTotal := 0;
//Usado para validação do dígito verificador.
iMultiplicador := 11;
//Acumula os dígitos do CPF.
for iIndice := 1 to 10 do
begin
iTotal := iTotal + aiDigito[iIndice] * iMultiplicador;
dec(iMultiplicador);
end;
//3º verificação do CPF.
cpfValido := ((((iTotal * 10) mod 11) = aiDigito[11]) or
(((iTotal * 10) mod 11) = aiDigito[11] + 10));
//Se for identidficado um erro gerar exceção.
if not cpfValido then
raise Exception.Create(Format(msgCGC_CPFInvalido, ['CPF']));
except
raise;
end;
end;
(******************************************************************************)
(* Function : CheckCGC *)
(* Descrição : Função para verificar a validez do CGC *)
(* Parâmetro : sCGC - CGC p/ verificação. *)
(* Retorno : True => CGC valido *)
(* False => CGC inválido *)
(******************************************************************************)
class procedure TUtil.CheckCGC(sCGC: String);
var
aiDigito : array[1..14] of integer; { Digitos do CGC }
iTotal : integer; { Total para Calculos }
iMultiplicador : integer; { Fator de multiplicacao }
iIndice : integer; { Indice dos digitos }
{%H-}iErro : integer; { Variavel de Erro ( string -> integer ) }
iDigVerif : integer; { Digito para verificacao }
cpfValido : boolean;
begin
try
//Zera o acumulador dos dígitos do CGC.
iTotal := 0;
//Usado para auxiliar a validação do CGC.
iMultiplicador := 5;
//Pega CGC sem máscara.
sCGC := TUtil.tirarMascara(sCGC);
//1º verificação do CGC.
cpfValido := (length(sCGC) = 14);
//Se for identidficado um erro gerar exceção.
if not cpfValido then
raise Exception.Create(Format(msgCGC_CPFInvalido, ['CGC']));
//Converte o String em um Integer.
for iIndice := 1 to 14 do
Val(sCGC[iIndice], aiDigito[iIndice], iErro);
//Acumula os dígitos do CGC.
for iIndice := 1 to 12 do
begin
iTotal := iTotal + aiDigito[iIndice] * iMultiplicador;
if (iMultiplicador = 2) then iMultiplicador := 9 else dec(iMultiplicador);
end;
//Pega o dígito verificador(Início)
if (iTotal < 11) then iTotal := iTotal * 10;
if (((iTotal mod 11) = 1) or ((iTotal mod 11) = 0)) then
iDigVerif := 0
else
iDigVerif := 11 - (iTotal mod 11);
//Pega o dígito verificador(Fim)
//2º verificação do CGC.
cpfValido := not (iDigVerif <> aiDigito[13]);
//Se for identidficado um erro gerar exceção.
if not cpfValido then
raise Exception.Create(Format(msgCGC_CPFInvalido, ['CGC']));
//Zera o acumulador dos dígitos do CGC.
iTotal := 0;
//Usado para auxiliar a validação do CGC.
iMultiplicador := 6;
//Acumula os dígitos do CGC.
for iIndice := 1 to 13 do
begin
iTotal := iTotal + aiDigito[iIndice] * iMultiplicador;
if (iMultiplicador = 2) then iMultiplicador := 9 else dec(iMultiplicador);
end;
//Pega o dígito verificador(Início)
if (iTotal < 11) then iTotal := iTotal * 10;
if (((iTotal mod 11) = 1) or ((iTotal mod 11) = 0)) then iDigVerif := 0
else iDigVerif := 11 - (iTotal mod 11);
//Pega o dígito verificador(Fim)
//3º verificação do CGC.
cpfValido := not (iDigVerif <> aiDigito[14]);
//Se for identidficado um erro gerar exceção.
if not cpfValido then
raise Exception.Create(Format(msgCGC_CPFInvalido, ['CGC']));
except
raise;
end;
end;
class function TUtil.mensagemErro(e: Exception): string;
begin
// Chave primária
if EUpdateError(e).ErrorCode = 1062 then
result := 'Informação já cadastrada.'
else result := e.Message;
end;
end.
|
unit ufunctions;
{$mode delphi}{$H+}
interface
uses
Windows, Classes, IniFiles;
const
GLOBAL_SECTION = 'Global';
RUNONSTARTUP_VALUE = 'RunOnStartup';
LOOPVIDEOS_VALUE = 'LoopVideos';
function GetScreenshotFileName(const VidFile: string): string;
procedure SplitString(const Delimiter: char; const Str: string;
const ListOfStrings: TStrings);
function GetMonitorName(const Hnd: HMONITOR): string;
function GetCurrentUser(): string;
function InitializeConfig(): boolean;
function RECTToString(const R: TRect): string;
function IsWin7(): boolean;
function IsAeroEnabled(): boolean;
var
Config: TIniFile;
implementation
uses
SysUtils, Forms, Multimon, ActiveX, ComObj, Variants, Character;
function TrimLeadingZeros(const S: string): string;
var
I, L: integer;
begin
L := Length(S);
I := 1;
while (I < L) and (S[I] = '0') do
Inc(I);
Result := Copy(S, I);
end;
function GetScreenshotFileName(const VidFile: string): string;
begin
Result := IncludeTrailingBackslash(ExtractFilePath(Application.ExeName)) +
ChangeFileExt(ExtractFileName(VidFile), '.png');
end;
function GetMonitorName(const Hnd: HMONITOR): string;
const
WbemUser = '';
WbemPassword = '';
WbemComputer = 'localhost';
wbemFlagForwardOnly = $00000020;
type
TMonitorInfoEx = record
cbSize: DWORD;
rcMonitor: TRect;
rcWork: TRect;
dwFlags: DWORD;
szDevice: array[0..CCHDEVICENAME - 1] of AnsiChar;
end;
var
DispDev: TDisplayDevice;
monInfo: TMonitorInfoEx;
SL: TStringList;
FSWbemLocator: olevariant;
FWMIService, FWMIService2: olevariant;
FWbemObjectSet: olevariant;
FWbemObject: olevariant;
oEnum: IEnumvariant;
Query: WideString;
DeviceId: string;
iValue: longword;
I: integer;
begin
Result := '';
monInfo.cbSize := sizeof(monInfo);
SL := TStringList.Create();
try
if GetMonitorInfo(Hnd, @monInfo) then
begin
DispDev.cb := SizeOf(DispDev);
EnumDisplayDevices(@monInfo.szDevice, 0, @DispDev, 0);
Result := StrPas(DispDev.DeviceString);
SplitString('\', DispDev.DeviceID, SL);
if ((SL.Count = 4) and (SL[0] = 'MONITOR')) then
begin
FSWbemLocator := CreateOleObject('WbemScripting.SWbemLocator');
FWMIService := FSWbemLocator.ConnectServer(WbemComputer,
'root\CIMV2', WbemUser, WbemPassword);
FWMIService2 := FSWbemLocator.ConnectServer(WbemComputer,
'root\WMI', WbemUser, WbemPassword);
Query := 'SELECT * FROM Win32_PnPEntity WHERE ClassGUID = ''' +
SL[2] + ''' AND DeviceID LIKE ''DISPLAY\\' + SL[1] + '\\' +
TrimLeadingZeros(SL[3]) + '%''';
FWbemObjectSet := FWMIService.ExecQuery(Query, 'WQL', wbemFlagForwardOnly);
oEnum := IUnknown(FWbemObjectSet._NewEnum) as IEnumVariant;
if (oEnum.Next(1, FWbemObject, iValue) = 0) then
begin
DeviceId := StringReplace(VarToUnicodeStr(FWbemObject.DeviceId),
'\', '\\', [rfReplaceAll]);
FWbemObject := Unassigned;
Query :=
'SELECT UserFriendlyName FROM WmiMonitorId WHERE Active = True AND InstanceName LIKE "'
+ DeviceId + '%"';
FWbemObjectSet := FWMIService2.ExecQuery(Query, 'WQL', wbemFlagForwardOnly);
oEnum := IUnknown(FWbemObjectSet._NewEnum) as IEnumVariant;
if (oEnum.Next(1, FWbemObject, iValue) = 0) then
begin
Result := '';
for I := VarArrayLowBound(FWbemObject.UserFriendlyName, 1)
to VarArrayHighBound(FWbemObject.UserFriendlyName, 1) do
Result := Result + TCharacter.ConvertFromUtf32(
UCS4Char(integer(FWbemObject.UserFriendlyName[I])));
Result := Trim(Result);
end;
end;
end;
end;
finally
SL.Free();
end;
end;
procedure SplitString(const Delimiter: char; const Str: string;
const ListOfStrings: TStrings);
begin
ListOfStrings.Clear();
ListOfStrings.Delimiter := Delimiter;
ListOfStrings.StrictDelimiter := True;
ListOfStrings.DelimitedText := Str;
end;
function GetCurrentUser(): string;
var
nSize: DWord;
begin
nSize := 1024;
SetLength(Result, nSize);
if GetUserName(PChar(Result), nSize) then
SetLength(Result, nSize - 1)
else
Result := '';
end;
function InitializeConfig(): boolean;
begin
Config := TIniFile.Create(IncludeTrailingBackslash(
ExtractFilePath(Application.ExeName)) + 'config.ini', True);
// Populate the configuration file with defualt values.
Result := Config.SectionExists(GLOBAL_SECTION);
if (not Result) then
begin
Config.WriteBool(GLOBAL_SECTION, RUNONSTARTUP_VALUE, True);
Config.WriteBool(GLOBAL_SECTION, LOOPVIDEOS_VALUE, True);
end;
end;
function RECTToString(const R: TRect): string;
begin
Result := Format('(%d, %d) (%d, %d)', [R.Left, R.Top, R.Right, R.Bottom]);
end;
function IsWin7(): boolean;
begin
Result := ((Win32MajorVersion = 6) and (Win32MinorVersion = 1));
end;
function IsAeroEnabled: boolean;
type
TDwmIsCompositionEnabledFunc = function(out pfEnabled: BOOL): HRESULT; stdcall;
var
IsEnabled: BOOL;
ModuleHandle: HMODULE;
DwmIsCompositionEnabledFunc: TDwmIsCompositionEnabledFunc;
begin
Result := False;
if Win32MajorVersion >= 6 then
begin
ModuleHandle := LoadLibrary('dwmapi.dll');
if ModuleHandle <> 0 then
try
@DwmIsCompositionEnabledFunc := GetProcAddress(ModuleHandle, 'DwmIsCompositionEnabled');
if Assigned(DwmIsCompositionEnabledFunc) then
if DwmIsCompositionEnabledFunc(IsEnabled) = S_OK then
Result := IsEnabled;
finally
if (ModuleHandle <> 0) then
FreeLibrary(ModuleHandle);
end;
end;
end;
end.
|
unit PaymentTest;
interface
uses dbTest, dbMovementTest, ObjectTest;
type
TPaymentTest = class (TdbMovementTestNew)
published
procedure ProcedureLoad; override;
procedure Test; override;
end;
TPayment = class(TMovementTest)
private
protected
function InsertDefault: integer; override;
public
function InsertUpdateMovementPayment(Id: Integer; InvNumber: String;
OperDate: TDateTime; JuridicalId: Integer): integer;
constructor Create; override;
end;
implementation
uses UtilConst, UnitsTest, PaidKindTest, JuridicalTest, dbObjectTest, SysUtils,
Db, TestFramework, BankAccountTest;
{ TPayment }
constructor TPayment.Create;
begin
inherited;
spInsertUpdate := 'gpInsertUpdate_Movement_Payment';
spSelect := 'gpSelect_Movement_Payment';
spGet := 'gpGet_Movement_Payment';
end;
function TPayment.InsertDefault: integer;
var Id: Integer;
InvNumber: String;
OperDate: TDateTime;
JuridicalId: Integer;
begin
Id:=0;
InvNumber:='1';
JuridicalId := TJuridical.Create.GetDefault;
OperDate := Date;
TBankAccount.Create.GetDefault;
result := InsertUpdateMovementPayment(Id, InvNumber, OperDate, JuridicalId);
end;
function TPayment.InsertUpdateMovementPayment(Id: Integer; InvNumber: String;
OperDate: TDateTime; JuridicalId: Integer):Integer;
begin
FParams.Clear;
FParams.AddParam('ioId', ftInteger, ptInputOutput, Id);
FParams.AddParam('inInvNumber', ftString, ptInput, InvNumber);
FParams.AddParam('inOperDate', ftdateTime, ptInput, OperDate);
FParams.AddParam('inJuridicalId', ftInteger, ptInput, JuridicalId);
result := InsertUpdate(FParams);
end;
{ TPaymentTest }
procedure TPaymentTest.ProcedureLoad;
begin
ScriptDirectory := LocalProcedurePath + 'Movement\Payment\';
inherited;
end;
procedure TPaymentTest.Test;
var
MovementPayment: TPayment;
Id: Integer;
begin
MovementPayment := TPayment.Create;
// создание документа
Id := MovementPayment.InsertDefault;
try
// редактирование
finally
// удаление
DeleteMovement(Id);
end;
end;
{ TPaymentItem }
initialization
// TestFramework.RegisterTest('Документы', TPaymentTest.Suite);
end.
|
unit ResourceDialogUnit;
interface
uses
Windows,
Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, HelperUnit, StdCtrls, Buttons, ComCtrls, Grids, TypesUnit,
Menus, SynEditHighlighter, SynHighlighterRC, SynEdit, ExtCtrls;
type
TResourcesDialog = class(TForm)
btnLoad: TBitBtn;
cbKinds: TComboBox;
lbKind: TLabel;
PopupMenu: TPopupMenu;
menuLoad: TMenuItem;
menuRemove: TMenuItem;
N1: TMenuItem;
menuClear: TMenuItem;
btOK: TBitBtn;
btCancel: TBitBtn;
PageControl: TPageControl;
TabItems: TTabSheet;
ListView: TListView;
TabSource: TTabSheet;
RCSource: TSynEdit;
RC: TSynRCSyn;
TabView: TTabSheet;
ImageEdit: TImage;
procedure btnLoadClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure cbKindsChange(Sender: TObject);
procedure cbKindsCloseUp(Sender: TObject);
procedure ListViewColumnClick(Sender: TObject; Column: TListColumn);
procedure ListViewEdited(Sender: TObject; Item: TListItem;
var S: String);
procedure ListViewClick(Sender: TObject);
procedure ListViewResize(Sender: TObject);
procedure menuClearClick(Sender: TObject);
procedure menuRemoveClick(Sender: TObject);
procedure menuLoadClick(Sender: TObject);
procedure btOKClick(Sender: TObject);
procedure PopupMenuPopup(Sender: TObject);
procedure btCancelClick(Sender: TObject);
procedure PageControlChange(Sender: TObject);
procedure ListViewDblClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
function StrToRes(v:string):string;
procedure LoadResources;
end;
var
ResourcesDialog: TResourcesDialog;
implementation
{$R *.dfm}
uses MainUnit, ProjectPropertiesUnit;
function TResourceSDialog.StrToRes(v:string):string;
var
Ext :string;
begin
Result := '';
if v='' then exit;
Ext := ExtractFileExt(v);
if CompareText(Ext,'.bmp') = 0 then
Result := 'BITMAP'
else if CompareText(Ext,'.ico') = 0 then
Result := 'ICON'
else if CompareText(Ext,'.cur') = 0 then
Result := 'CURSOR'
else if (CompareText(Ext,'.html') = 0) or (CompareText(Ext,'.htm') = 0) then
Result := 'HTML'
else if CompareText(Ext,'.hta') = 0 then
Result := 'COMPILEDHTML'
else if CompareText(Ext,'.vxd') = 0 then
Result := 'VXD'
else if CompareText(Ext,'.JPEG') = 0 then
Result := 'JPEG'
else if CompareText(Ext,'.JPG') = 0 then
Result := 'JPG'
else if CompareText(Ext,'.TIFF') = 0 then
Result := 'TIFF'
else if CompareText(Ext,'.AVI') = 0 then
Result := 'AVI'
else if CompareText(Ext,'.MP3') = 0 then
Result := 'MP3'
else if CompareText(Ext,'.MP4') = 0 then
Result := 'MP4'
else if CompareText(Ext,'.FLV') = 0 then
Result := 'FLASH'
else if CompareText(Ext,'.3GP') = 0 then
Result := 'JAVAMOBILE'
else
Result :='RCDATA';
end;
procedure TResourcesDialog.btnLoadClick(Sender: TObject);
var
Li :TListItem;
it :TResourceItem;
i :integer;
begin
with TOpenDialog.Create(nil) do begin
Options := Options + [ofAllowMultiselect];
if Execute then begin
for i:=0 to Files.Count-1 do
if Resources.ResourceExists(Files[i]) =nil then begin
Li := ListView.Items.Add;
Li.Caption := ChangeFileExt(ExtractFileName(Files[i]),'');
Li.SubItems.Add(StrToRes(Files[i]));
Li.SubItems.Add(Files[i]);
it := TResourceItem.Create;
it.Name:= Li.Caption;
it.FileName := Li.SubItems[1];
it.Kind := StrToRes(Files[i]);
Li.Data := it;
Resources.AddItem(it);
end;
end;
Free;
end;
end;
procedure TResourcesDialog.LoadResources;
var
i :integer;
L :TListItem;
begin
ListView.Items.Clear;
for i := 0 to Resources.Items.Count-1 do begin
L := ListView.Items.Add;
L.Caption := Resources.Items[i];
L.SubItems.Add(TResourceItem(Resources.Items.Objects[i]).Kind);
L.SubItems.Add(TResourceItem(Resources.Items.Objects[i]).FileName);
L.Data:= Resources.Items.Objects[i];
end
end;
procedure TResourcesDialog.FormShow(Sender: TObject);
begin
LoadResources;
end;
procedure TResourcesDialog.cbKindsChange(Sender: TObject);
var
i :integer;
L :TListItem;
begin
i := ListView.ItemIndex;
if i <> -1 then begin
L := ListView.Items[i];
L.SubItems[0] := cbKinds.Text;
end;
end;
procedure TResourcesDialog.cbKindsCloseUp(Sender: TObject);
var
i :integer;
L :TListItem;
begin
i := ListView.ItemIndex;
if i <> -1 then begin
L := ListView.Items[i];
L.SubItems[0] := cbKinds.Text;
end;
end;
procedure TResourcesDialog.ListViewColumnClick(Sender: TObject;
Column: TListColumn);
begin
if Column = ListView.Columns[2] then
btnLoad.Click
end;
procedure TResourcesDialog.ListViewEdited(Sender: TObject; Item: TListItem;
var S: String);
var
i :integer;
Ri:TResourceItem;
begin
I := ListView.ItemIndex;
if i <> -1 then begin
Ri:=TResourceItem(ListView.Items[i].Data);
Ri.Name:=s;
Resources.Save
end
end;
procedure TResourcesDialog.ListViewClick(Sender: TObject);
var
ri :TResourceItem;
begin
cbKinds.Enabled :=(ListView.Selected <> nil);
if cbKinds.Enabled then begin
ri:=TResourceItem(ListView.Items[ListView.ItemIndex].Data);
cbKinds.ItemIndex :=cbKinds.Items.IndexOf(ri.Kind);
end;
end;
procedure TResourcesDialog.ListViewResize(Sender: TObject);
var
i :integer;
begin
i := ListView.ClientWidth div 3;
ListView.Columns[0].Width := i;
ListView.Columns[1].Width := i;
ListView.Columns[2].Width := i;
end;
procedure TResourcesDialog.menuClearClick(Sender: TObject);
var
i :integer;
begin
for i := ListView.Items.Count-1 downto 0 do begin
if ListView.Items[i].Data<>nil then
if TObject(ListView.Items[i].Data).InheritsFrom(TResourceItem) then begin
Resources.RemoveItem(TResourceItem(ListView.Items[i].Data).FileName);
end;
ListView.Items.Delete(i);
end;
end;
procedure TResourcesDialog.menuRemoveClick(Sender: TObject);
var
i :integer;
begin
i:=ListView.ItemIndex;
if i>-1 then begin
if ListView.Items[i].Data<>nil then
if TObject(ListView.Items[i].Data).InheritsFrom(TResourceItem) then begin
Resources.RemoveItem(TResourceItem(ListView.Items[i].Data).FileName);
end;
ListView.Items.Delete(i);
end;
end;
procedure TResourcesDialog.menuLoadClick(Sender: TObject);
begin
btnLoad.Click;
end;
procedure TResourcesDialog.btOKClick(Sender: TObject);
var
i :integer;
begin
Resources.Items.Clear();
for i := 0 to ListView.Items.Count-1 do
Resources.AddItem(TResourceItem(ListView.Items[i].Data));
ModalResult:=mrok;
Close;
end;
procedure TResourcesDialog.PopupMenuPopup(Sender: TObject);
begin
menuRemove.Enabled := ListView.Items.Count>0;
menuClear.Enabled := ListView.Items.Count>0;
end;
procedure TResourcesDialog.btCancelClick(Sender: TObject);
begin
ModalResult:=mrcancel;
Close;
end;
procedure TResourcesDialog.PageControlChange(Sender: TObject);
begin
RCSource.Lines.Assign(Resources);
end;
procedure TResourcesDialog.ListViewDblClick(Sender: TObject);
var
Ri:TResourceItem;
begin
if ListView.ItemIndex>-1 then begin
Ri:=ListView.Items[ListView.ItemIndex].data;
if Ri<>nil then
if Ri.Kind='ICON' then
ImageEdit.Picture.LoadFromFile(Ri.FileName);
end
end;
end.
|
//
// Created by the DataSnap proxy generator.
// 24/03/2018 15:21:33
//
unit ClientClassesUnit1;
interface
uses System.JSON, Datasnap.DSProxyRest, Datasnap.DSClientRest, Data.DBXCommon, Data.DBXClient, Data.DBXDataSnap, Data.DBXJSON, Datasnap.DSProxy, System.Classes, System.SysUtils, Data.DB, Data.SqlExpr, Data.DBXDBReaders, Data.DBXCDSReaders, Data.FireDACJSONReflect, Data.DBXJSONReflect;
type
IDSRestCachedTFDJSONDataSets = interface;
TSrvMetodosClient = class(TDSAdminRestClient)
private
FDSServerModuleCreateCommand: TDSRestCommand;
FDSServerModuleDestroyCommand: TDSRestCommand;
FGetTicketsCommand: TDSRestCommand;
FGetTicketsCommand_Cache: TDSRestCommand;
FSincronizarCommand: TDSRestCommand;
FPatchTicketCommand: TDSRestCommand;
public
constructor Create(ARestConnection: TDSRestConnection); overload;
constructor Create(ARestConnection: TDSRestConnection; AInstanceOwner: Boolean); overload;
destructor Destroy; override;
procedure DSServerModuleCreate(Sender: TObject);
procedure DSServerModuleDestroy(Sender: TObject);
function GetTickets(ATicket: string; const ARequestFilter: string = ''): TFDJSONDataSets;
function GetTickets_Cache(ATicket: string; const ARequestFilter: string = ''): IDSRestCachedTFDJSONDataSets;
function Sincronizar(ATickets: string; const ARequestFilter: string = ''): Boolean;
function PatchTicket(ATicket: string; const ARequestFilter: string = ''): Boolean;
end;
IDSRestCachedTFDJSONDataSets = interface(IDSRestCachedObject<TFDJSONDataSets>)
end;
TDSRestCachedTFDJSONDataSets = class(TDSRestCachedObject<TFDJSONDataSets>, IDSRestCachedTFDJSONDataSets, IDSRestCachedCommand)
end;
const
TSrvMetodos_DSServerModuleCreate: array [0..0] of TDSRestParameterMetaData =
(
(Name: 'Sender'; Direction: 1; DBXType: 37; TypeName: 'TObject')
);
TSrvMetodos_DSServerModuleDestroy: array [0..0] of TDSRestParameterMetaData =
(
(Name: 'Sender'; Direction: 1; DBXType: 37; TypeName: 'TObject')
);
TSrvMetodos_GetTickets: array [0..1] of TDSRestParameterMetaData =
(
(Name: 'ATicket'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: ''; Direction: 4; DBXType: 37; TypeName: 'TFDJSONDataSets')
);
TSrvMetodos_GetTickets_Cache: array [0..1] of TDSRestParameterMetaData =
(
(Name: 'ATicket'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: ''; Direction: 4; DBXType: 26; TypeName: 'String')
);
TSrvMetodos_Sincronizar: array [0..1] of TDSRestParameterMetaData =
(
(Name: 'ATickets'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean')
);
TSrvMetodos_PatchTicket: array [0..1] of TDSRestParameterMetaData =
(
(Name: 'ATicket'; Direction: 1; DBXType: 26; TypeName: 'string'),
(Name: ''; Direction: 4; DBXType: 4; TypeName: 'Boolean')
);
implementation
procedure TSrvMetodosClient.DSServerModuleCreate(Sender: TObject);
begin
if FDSServerModuleCreateCommand = nil then
begin
FDSServerModuleCreateCommand := FConnection.CreateCommand;
FDSServerModuleCreateCommand.RequestType := 'POST';
FDSServerModuleCreateCommand.Text := 'TSrvMetodos."DSServerModuleCreate"';
FDSServerModuleCreateCommand.Prepare(TSrvMetodos_DSServerModuleCreate);
end;
if not Assigned(Sender) then
FDSServerModuleCreateCommand.Parameters[0].Value.SetNull
else
begin
FMarshal := TDSRestCommand(FDSServerModuleCreateCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler;
try
FDSServerModuleCreateCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(Sender), True);
if FInstanceOwner then
Sender.Free
finally
FreeAndNil(FMarshal)
end
end;
FDSServerModuleCreateCommand.Execute;
end;
procedure TSrvMetodosClient.DSServerModuleDestroy(Sender: TObject);
begin
if FDSServerModuleDestroyCommand = nil then
begin
FDSServerModuleDestroyCommand := FConnection.CreateCommand;
FDSServerModuleDestroyCommand.RequestType := 'POST';
FDSServerModuleDestroyCommand.Text := 'TSrvMetodos."DSServerModuleDestroy"';
FDSServerModuleDestroyCommand.Prepare(TSrvMetodos_DSServerModuleDestroy);
end;
if not Assigned(Sender) then
FDSServerModuleDestroyCommand.Parameters[0].Value.SetNull
else
begin
FMarshal := TDSRestCommand(FDSServerModuleDestroyCommand.Parameters[0].ConnectionHandler).GetJSONMarshaler;
try
FDSServerModuleDestroyCommand.Parameters[0].Value.SetJSONValue(FMarshal.Marshal(Sender), True);
if FInstanceOwner then
Sender.Free
finally
FreeAndNil(FMarshal)
end
end;
FDSServerModuleDestroyCommand.Execute;
end;
function TSrvMetodosClient.GetTickets(ATicket: string; const ARequestFilter: string): TFDJSONDataSets;
begin
if FGetTicketsCommand = nil then
begin
FGetTicketsCommand := FConnection.CreateCommand;
FGetTicketsCommand.RequestType := 'GET';
FGetTicketsCommand.Text := 'TSrvMetodos.GetTickets';
FGetTicketsCommand.Prepare(TSrvMetodos_GetTickets);
end;
FGetTicketsCommand.Parameters[0].Value.SetWideString(ATicket);
FGetTicketsCommand.Execute(ARequestFilter);
if not FGetTicketsCommand.Parameters[1].Value.IsNull then
begin
FUnMarshal := TDSRestCommand(FGetTicketsCommand.Parameters[1].ConnectionHandler).GetJSONUnMarshaler;
try
Result := TFDJSONDataSets(FUnMarshal.UnMarshal(FGetTicketsCommand.Parameters[1].Value.GetJSONValue(True)));
if FInstanceOwner then
FGetTicketsCommand.FreeOnExecute(Result);
finally
FreeAndNil(FUnMarshal)
end
end
else
Result := nil;
end;
function TSrvMetodosClient.GetTickets_Cache(ATicket: string; const ARequestFilter: string): IDSRestCachedTFDJSONDataSets;
begin
if FGetTicketsCommand_Cache = nil then
begin
FGetTicketsCommand_Cache := FConnection.CreateCommand;
FGetTicketsCommand_Cache.RequestType := 'GET';
FGetTicketsCommand_Cache.Text := 'TSrvMetodos.GetTickets';
FGetTicketsCommand_Cache.Prepare(TSrvMetodos_GetTickets_Cache);
end;
FGetTicketsCommand_Cache.Parameters[0].Value.SetWideString(ATicket);
FGetTicketsCommand_Cache.ExecuteCache(ARequestFilter);
Result := TDSRestCachedTFDJSONDataSets.Create(FGetTicketsCommand_Cache.Parameters[1].Value.GetString);
end;
function TSrvMetodosClient.Sincronizar(ATickets: string; const ARequestFilter: string): Boolean;
begin
if FSincronizarCommand = nil then
begin
FSincronizarCommand := FConnection.CreateCommand;
FSincronizarCommand.RequestType := 'GET';
FSincronizarCommand.Text := 'TSrvMetodos.Sincronizar';
FSincronizarCommand.Prepare(TSrvMetodos_Sincronizar);
end;
FSincronizarCommand.Parameters[0].Value.SetWideString(ATickets);
FSincronizarCommand.Execute(ARequestFilter);
Result := FSincronizarCommand.Parameters[1].Value.GetBoolean;
end;
function TSrvMetodosClient.PatchTicket(ATicket: string; const ARequestFilter: string): Boolean;
begin
if FPatchTicketCommand = nil then
begin
FPatchTicketCommand := FConnection.CreateCommand;
FPatchTicketCommand.RequestType := 'GET';
FPatchTicketCommand.Text := 'TSrvMetodos.PatchTicket';
FPatchTicketCommand.Prepare(TSrvMetodos_PatchTicket);
end;
FPatchTicketCommand.Parameters[0].Value.SetWideString(ATicket);
FPatchTicketCommand.Execute(ARequestFilter);
Result := FPatchTicketCommand.Parameters[1].Value.GetBoolean;
end;
constructor TSrvMetodosClient.Create(ARestConnection: TDSRestConnection);
begin
inherited Create(ARestConnection);
end;
constructor TSrvMetodosClient.Create(ARestConnection: TDSRestConnection; AInstanceOwner: Boolean);
begin
inherited Create(ARestConnection, AInstanceOwner);
end;
destructor TSrvMetodosClient.Destroy;
begin
FDSServerModuleCreateCommand.DisposeOf;
FDSServerModuleDestroyCommand.DisposeOf;
FGetTicketsCommand.DisposeOf;
FGetTicketsCommand_Cache.DisposeOf;
FSincronizarCommand.DisposeOf;
FPatchTicketCommand.DisposeOf;
inherited;
end;
end.
|
unit dll_wsock32;
interface
uses
atmcmbaseconst, winconst, wintype;
const
wsock32 = 'wsock32.dll';
const
FD_SETSIZE = 64;
type
// u_char = Byte;
u_long = Cardinal;
u_short = Word;
u_int = Cardinal;
TSocket = Integer;
TSockAddr = record
sa_family: Word;//u_short; // address family
sa_data: array [0..13] of AnsiChar; // up to 14 bytes of direct address
end;
PSockAddr = ^TSockAddr;
TWSAData = record
wVersion: WORD;
wHighVersion: WORD;
{$IFDEF WIN64}
iMaxSockets: Word;
iMaxUdpDg: Word;
lpVendorInfo: PAnsiChar;
szDescription: array [0..WSADESCRIPTION_LEN] of AnsiChar;
szSystemStatus: array [0..WSASYS_STATUS_LEN] of AnsiChar;
{$ELSE}
szDescription: array [0..WSADESCRIPTION_LEN] of AnsiChar;
szSystemStatus: array [0..WSASYS_STATUS_LEN] of AnsiChar;
iMaxSockets: Word;
iMaxUdpDg: Word;
lpVendorInfo: PAnsiChar;
{$ENDIF}
end;
PWsaData = TWSAData;
TFDSet = record
fd_count : u_int; // how many are SET?
fd_array : array [0..FD_SETSIZE - 1] of TSocket; // an array of SOCKETs
end;
PFdSet = ^TFDSet;
TSunB = record
s_b1: Byte; //u_char;
s_b2: Byte; //u_char;
s_b3: Byte; //u_char;
s_b4: Byte; //u_char;
end;
TSunC = record
s_c1: AnsiChar;
s_c2: AnsiChar;
s_c3: AnsiChar;
s_c4: AnsiChar;
end;
TSunW = record
s_w1: Word; //u_short;
s_w2: Word; //u_short;
end;
TInAddr = record
case Integer of
0: (S_un_b: TSunB);
1: (S_un_c: TSunC);
2: (S_un_w: TSunW);
3: (S_addr: u_long);
// #define s_addr S_un.S_addr // can be used for most tcp & ip code
// #define s_host S_un.S_un_b.s_b2 // host on imp
// #define s_net S_un.S_un_b.s_b1 // netword
// #define s_imp S_un.S_un_w.s_w2 // imp
// #define s_impno S_un.S_un_b.s_b4 // imp #
// #define s_lh S_un.S_un_b.s_b3 // logical host
end;
PInAddr = ^TInAddr;
THostEnt = record
h_name: PAnsiChar; // official name of host
h_aliases: PPAnsiChar; // alias list
h_addrtype: Smallint; // host address type
h_length: Smallint; // length of address
case Integer of
0: (h_addr_list: PPAnsiChar); // list of addresses
1: (h_addr: PPAnsiChar); // address, for backward compat
end;
PHostEnt = ^THostEnt;
TProtoEnt = record
p_name: PAnsiChar; // official protocol name
p_aliases: PPAnsiChar; // alias list
p_proto: Smallint; // protocol #
end;
PProtoEnt = ^TProtoEnt;
TNetEnt = record
n_name: PAnsiChar; // official name of net
n_aliases: PPAnsiChar; // alias list
n_addrtype: Smallint; // net address type
n_net: u_long; // network #
end;
PNetEnt = ^TNetEnt;
TServEnt = record
s_name: PAnsiChar; // official service name
s_aliases: PPAnsiChar; // alias list
{$IFDEF WIn64}
s_proto: PAnsiChar; // protocol to use
s_port: Smallint; // port #
{$ELSE}
s_port: Smallint; // port #
s_proto: PAnsiChar; // protocol to use
{$ENDIF}
end;
PServEnt = ^TServEnt;
TTimeVal = record
tv_sec: Longint; // seconds
tv_usec: Longint; // and microseconds
end;
PTimeVal = ^TTimeVal;
function accept(s: TSocket; addr: PSockAddr; addrlen: PInteger): TSocket; stdcall; external wsock32 name 'accept';
function bind(s: TSocket; var addr: TSockAddr; namelen: Integer): Integer; stdcall; external wsock32 name 'bind';
function closesocket(s: TSocket): Integer; stdcall; external wsock32 name 'closesocket';
function connect(s: TSocket; var name: TSockAddr; namelen: Integer): Integer; stdcall; external wsock32 name 'connect';
function getpeername(s: TSocket; var name: TSockAddr; var namelen: Integer): Integer; stdcall; external wsock32 name 'getpeername';
function getsockname(s: TSocket; var name: TSockAddr; var namelen: Integer): Integer; stdcall; external wsock32 name 'getsockname';
function getsockopt(s: TSocket; level, optname: Integer; optval: PAnsiChar; var optlen: Integer): Integer; stdcall; external wsock32 name 'getsockopt';
function htonl(hostlong: u_long): u_long; stdcall; external wsock32 name 'htonl';
function htons(hostshort: u_short): u_short; stdcall; external wsock32 name 'htons';
function inet_addr(cp: PAnsiChar): u_long; stdcall; {PInAddr;} { TInAddr } external wsock32 name 'inet_addr';
function inet_ntoa(inaddr: TInAddr): PAnsiChar; stdcall; external wsock32 name 'inet_ntoa';
function ioctlsocket(s: TSocket; cmd: DWORD; var arg: u_long): Integer; stdcall; external wsock32 name 'ioctlsocket';
function listen(s: TSocket; backlog: Integer): Integer; stdcall; external wsock32 name 'listen';
function ntohl(netlong: u_long): u_long; stdcall; external wsock32 name 'ntohl';
function ntohs(netshort: u_short): u_short; stdcall; external wsock32 name 'ntohs';
function recv(s: TSocket; var Buf; len, flags: Integer): Integer; stdcall; external wsock32 name 'recv';
function recvfrom(s: TSocket; var Buf; len, flags: Integer;
var from: TSockAddr; var fromlen: Integer): Integer; stdcall; external wsock32 name 'recvfrom';
function select(nfds: Integer; readfds, writefds, exceptfds: PFDSet;
timeout: PTimeVal): Longint; stdcall; external wsock32 name 'select';
function send(s: TSocket; var Buf; len, flags: Integer): Integer; stdcall; external wsock32 name 'send';
function sendto(s: TSocket; var Buf; len, flags: Integer; var addrto: TSockAddr;
tolen: Integer): Integer; stdcall; external wsock32 name 'sendto';
function setsockopt(s: TSocket; level, optname: Integer; optval: PAnsiChar;
optlen: Integer): Integer; stdcall; external wsock32 name 'setsockopt';
function shutdown(s: TSocket; how: Integer): Integer; stdcall; external wsock32 name 'shutdown';
function socket(af, Struct, protocol: Integer): TSocket; stdcall; external wsock32 name 'socket';
function gethostbyaddr(addr: Pointer; len, Struct: Integer): PHostEnt; stdcall; external wsock32 name 'gethostbyaddr';
function gethostbyname(name: PAnsiChar): PHostEnt; stdcall; external wsock32 name 'gethostbyname';
function getprotobyname(name: PAnsiChar): PProtoEnt; stdcall; external wsock32 name 'getprotobyname';
function getprotobynumber(proto: Integer): PProtoEnt; stdcall; external wsock32 name 'getprotobynumber';
function getservbyname(name, proto: PAnsiChar): PServEnt; stdcall; external wsock32 name 'getservbyname';
function getservbyport(port: Integer; proto: PAnsiChar): PServEnt; stdcall; external wsock32 name 'getservbyport';
function gethostname(name: PAnsiChar; len: Integer): Integer; stdcall; external wsock32 name 'gethostname';
function WSAAsyncSelect(s: TSocket; AWindow: HWND; wMsg: u_int; lEvent: Longint): Integer; stdcall; external wsock32 name 'WSAAsyncSelect';
function WSARecvEx(s: TSocket; var buf; len: Integer; var flags: Integer): Integer; stdcall; external wsock32 name 'WSARecvEx';
function WSAAsyncGetHostByAddr(AWindow: HWND; wMsg: u_int; addr: PAnsiChar;
len, Struct: Integer; buf: PAnsiChar; buflen: Integer): THandle; stdcall; external wsock32 name 'WSAAsyncGetHostByAddr';
function WSAAsyncGetHostByName(AWindow: HWND; wMsg: u_int;
name, buf: PAnsiChar; buflen: Integer): THandle; stdcall; external wsock32 name 'WSAAsyncGetHostByName';
function WSAAsyncGetProtoByNumber(AWindow: HWND; wMsg: u_int; number: Integer;
buf: PAnsiChar; buflen: Integer): THandle; stdcall; external wsock32 name 'WSAAsyncGetProtoByNumber';
function WSAAsyncGetProtoByName(AWindow: HWND; wMsg: u_int;
name, buf: PAnsiChar; buflen: Integer): THandle; stdcall; external wsock32 name 'WSAAsyncGetProtoByName';
function WSAAsyncGetServByPort(AWindow: HWND; wMsg, port: u_int;
proto, buf: PAnsiChar; buflen: Integer): THandle; stdcall; external wsock32 name 'WSAAsyncGetServByPort';
function WSAAsyncGetServByName(AWindow: HWND; wMsg: u_int;
name, proto, buf: PAnsiChar; buflen: Integer): THandle; stdcall; external wsock32 name 'WSAAsyncGetServByName';
function WSACancelAsyncRequest(AsyncTaskHandle: THandle): Integer; stdcall; external wsock32 name 'WSACancelAsyncRequest';
function WSASetBlockingHook(lpBlockFunc: TFarProc): TFarProc; stdcall; external wsock32 name 'WSASetBlockingHook';
function WSAUnhookBlockingHook: Integer; stdcall; external wsock32 name 'WSAUnhookBlockingHook';
function WSAGetLastError: Integer; stdcall; external wsock32 name 'WSAGetLastError';
procedure WSASetLastError(iError: Integer); stdcall; external wsock32 name 'WSASetLastError';
function WSACancelBlockingCall: Integer; stdcall; external wsock32 name 'WSACancelBlockingCall';
function WSAIsBlocking: BOOL; stdcall; external wsock32 name 'WSAIsBlocking';
function WSAStartup(wVersionRequired: word; var WSData: TWSAData): Integer; stdcall; external wsock32 name 'WSAStartup';
function WSACleanup: Integer; stdcall; external wsock32 name 'WSACleanup';
function __WSAFDIsSet(s: TSocket; var FDSet: TFDSet): Bool; stdcall; external wsock32 name '__WSAFDIsSet';
function TransmitFile(ASocket: TSocket; AFile: THandle; nNumberOfBytesToWrite: DWORD;
nNumberOfBytesPerSend: DWORD; lpOverlapped: POverlapped;
lpTransmitBuffers: PTransmitFileBuffers; dwReserved: DWORD): BOOL; stdcall; external wsock32 name 'TransmitFile';
function AcceptEx(sListenSocket, sAcceptSocket: TSocket;
lpOutputBuffer: Pointer; dwReceiveDataLength, dwLocalAddressLength,
dwRemoteAddressLength: DWORD; var lpdwBytesReceived: DWORD;
lpOverlapped: POverlapped): BOOL; stdcall; external wsock32 name 'AcceptEx';
procedure GetAcceptExSockaddrs(lpOutputBuffer: Pointer;
dwReceiveDataLength, dwLocalAddressLength, dwRemoteAddressLength: DWORD;
var LocalSockaddr: PSockAddr; var LocalSockaddrLength: Integer;
var RemoteSockaddr: PSockAddr; var RemoteSockaddrLength: Integer); stdcall; external wsock32 name 'GetAcceptExSockaddrs';
implementation
end.
|
unit Frustum;
interface
uses OpenGL;
// This is the index in our selection buffer that has the closet object ID clicked
const FIRST_OBJECT_ID = 3;
// We create an enum of the sides so we don't have to call each side 0 or 1.
// This way it makes it more understandable and readable when dealing with frustum sides.
// enum FrustumSide
RIGHT = 0; // The RIGHT side of the frustum
LEFT = 1; // The LEFT side of the frustum
BOTTOM = 2; // The BOTTOM side of the frustum
TOP = 3; // The TOP side of the frustum
BACK = 4; // The BACK side of the frustum
FRONT = 5; // The FRONT side of the frustum
// Like above, instead of saying a number for the ABC and D of the plane, we
// want to be more descriptive.
// enum PlaneData
A = 0; // The X value of the plane's normal
B = 1; // The Y value of the plane's normal
C = 2; // The Z value of the plane's normal
D = 3; // The distance the plane is from the origin
type
TFrustumArray = array[0..5, 0..3] of single;
TFrustum = class(TObject)
private
mFrustum : TFrustumArray;
public
// Call this every time the camera moves to update the frustum
procedure CalculateFrustum;
// This takes a 3D point and returns TRUE if it's inside of the frustum
function PointInFrustum(x, y, z : single) : boolean;
// This takes a 3D point and a radius and returns TRUE if the sphere is inside of the frustum
function SphereInFrustum(x, y, z, radius : single) : boolean;
// This takes the center and half the length of the cube.
function CubeInFrustum(x, y, z, size : single) : boolean;
// This checks if a box is in the frustum
function BoxInFrustum(x, y, z, x2, y2, z2 : single) : boolean;
procedure NormalizePlane(side : integer);
end;
var frust : TFrustum;
implementation
///////////////////////////////// NORMALIZE PLANE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
/////
///// This normalizes a plane (A side) from a given frustum.
/////
///////////////////////////////// NORMALIZE PLANE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
procedure TFrustum.NormalizePlane(side : integer);
var magnitude : single;
begin
// Here we calculate the magnitude of the normal to the plane (point A B C)
// Remember that (A, B, C) is that same thing as the normal's (X, Y, Z).
// To calculate magnitude you use the equation: magnitude = sqrt( x^2 + y^2 + z^2)
magnitude := Sqrt(mFrustum[side, A] * mFrustum[side, A] +
mFrustum[side, B] * mFrustum[side, B] +
mFrustum[side, C] * mFrustum[side, C] );
// Then we divide the plane's values by it's magnitude.
// This makes it easier to work with.
mFrustum[side, A] := mFrustum[side, A] / magnitude;
mFrustum[side, B] := mFrustum[side, B] / magnitude;
mFrustum[side, C] := mFrustum[side, C] / magnitude;
mFrustum[side, D] := mFrustum[side, D] / magnitude;
end;
///////////////////////////////// CALCULATE mFrustum \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
/////
///// This extracts our mFrustum from the projection and modelview matrix.
/////
///////////////////////////////// CALCULATE mFrustum \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
procedure TFrustum.CalculateFrustum;
var proj : array[0..15] of single;// This will hold our projection matrix
modl : array[0..15] of single;// This will hold our modelview matrix
clip : array[0..15] of single;// This will hold the clipping planes
begin
// glGetFloatv() is used to extract information about our OpenGL world.
// Below, we pass in GL_PROJECTION_MATRIX to abstract our projection matrix.
// It then stores the matrix into an array of [16].
glGetFloatv( GL_PROJECTION_MATRIX, @proj );
// By passing in GL_MODELVIEW_MATRIX, we can abstract our model view matrix.
// This also stores it in an array of [16].
glGetFloatv( GL_MODELVIEW_MATRIX, @modl );
// Now that we have our modelview and projection matrix, if we combine these 2 matrices,
// it will give us our clipping planes. To combine 2 matrices, we multiply them.
clip[ 0] := modl[ 0] * proj[ 0] + modl[ 1] * proj[ 4] + modl[ 2] * proj[ 8] + modl[ 3] * proj[12];
clip[ 1] := modl[ 0] * proj[ 1] + modl[ 1] * proj[ 5] + modl[ 2] * proj[ 9] + modl[ 3] * proj[13];
clip[ 2] := modl[ 0] * proj[ 2] + modl[ 1] * proj[ 6] + modl[ 2] * proj[10] + modl[ 3] * proj[14];
clip[ 3] := modl[ 0] * proj[ 3] + modl[ 1] * proj[ 7] + modl[ 2] * proj[11] + modl[ 3] * proj[15];
clip[ 4] := modl[ 4] * proj[ 0] + modl[ 5] * proj[ 4] + modl[ 6] * proj[ 8] + modl[ 7] * proj[12];
clip[ 5] := modl[ 4] * proj[ 1] + modl[ 5] * proj[ 5] + modl[ 6] * proj[ 9] + modl[ 7] * proj[13];
clip[ 6] := modl[ 4] * proj[ 2] + modl[ 5] * proj[ 6] + modl[ 6] * proj[10] + modl[ 7] * proj[14];
clip[ 7] := modl[ 4] * proj[ 3] + modl[ 5] * proj[ 7] + modl[ 6] * proj[11] + modl[ 7] * proj[15];
clip[ 8] := modl[ 8] * proj[ 0] + modl[ 9] * proj[ 4] + modl[10] * proj[ 8] + modl[11] * proj[12];
clip[ 9] := modl[ 8] * proj[ 1] + modl[ 9] * proj[ 5] + modl[10] * proj[ 9] + modl[11] * proj[13];
clip[10] := modl[ 8] * proj[ 2] + modl[ 9] * proj[ 6] + modl[10] * proj[10] + modl[11] * proj[14];
clip[11] := modl[ 8] * proj[ 3] + modl[ 9] * proj[ 7] + modl[10] * proj[11] + modl[11] * proj[15];
clip[12] := modl[12] * proj[ 0] + modl[13] * proj[ 4] + modl[14] * proj[ 8] + modl[15] * proj[12];
clip[13] := modl[12] * proj[ 1] + modl[13] * proj[ 5] + modl[14] * proj[ 9] + modl[15] * proj[13];
clip[14] := modl[12] * proj[ 2] + modl[13] * proj[ 6] + modl[14] * proj[10] + modl[15] * proj[14];
clip[15] := modl[12] * proj[ 3] + modl[13] * proj[ 7] + modl[14] * proj[11] + modl[15] * proj[15];
// Now we actually want to get the sides of the mFrustum. To do this we take
// the clipping planes we received above and extract the sides from them.
// This will extract the RIGHT side of the mFrustum
mFrustum[RIGHT, A] := clip[ 3] - clip[ 0];
mFrustum[RIGHT, B] := clip[ 7] - clip[ 4];
mFrustum[RIGHT, C] := clip[11] - clip[ 8];
mFrustum[RIGHT, D] := clip[15] - clip[12];
// Now that we have a normal (A,B,C) and a distance (D) to the plane,
// we want to normalize that normal and distance.
// Normalize the RIGHT side
//NormalizePlane(RIGHT);
// This will extract the LEFT side of the mFrustum
mFrustum[LEFT, A] := clip[ 3] + clip[ 0];
mFrustum[LEFT, B] := clip[ 7] + clip[ 4];
mFrustum[LEFT, C] := clip[11] + clip[ 8];
mFrustum[LEFT, D] := clip[15] + clip[12];
// Normalize the LEFT side
//NormalizePlane(LEFT);
// This will extract the BOTTOM side of the mFrustum
mFrustum[BOTTOM, A] := clip[ 3] + clip[ 1];
mFrustum[BOTTOM, B] := clip[ 7] + clip[ 5];
mFrustum[BOTTOM, C] := clip[11] + clip[ 9];
mFrustum[BOTTOM, D] := clip[15] + clip[13];
// Normalize the BOTTOM side
//NormalizePlane(BOTTOM);
// This will extract the TOP side of the mFrustum
mFrustum[TOP, A] := clip[ 3] - clip[ 1];
mFrustum[TOP, B] := clip[ 7] - clip[ 5];
mFrustum[TOP, C] := clip[11] - clip[ 9];
mFrustum[TOP, D] := clip[15] - clip[13];
// Normalize the TOP side
//NormalizePlane(TOP);
// This will extract the BACK side of the mFrustum
mFrustum[BACK, A] := clip[ 3] - clip[ 2];
mFrustum[BACK, B] := clip[ 7] - clip[ 6];
mFrustum[BACK, C] := clip[11] - clip[10];
mFrustum[BACK, D] := clip[15] - clip[14];
// Normalize the BACK side
//NormalizePlane(BACK);
// This will extract the FRONT side of the mFrustum
mFrustum[FRONT, A] := clip[ 3] + clip[ 2];
mFrustum[FRONT, B] := clip[ 7] + clip[ 6];
mFrustum[FRONT, C] := clip[11] + clip[10];
mFrustum[FRONT, D] := clip[15] + clip[14];
// Normalize the FRONT side
//NormalizePlane(FRONT);
end;
// The code below will allow us to make checks within the mFrustum. For example,
// if we want to see if a point, a sphere, or a cube lies inside of the mFrustum.
// Because all of our planes point INWARDS (The normals are all pointing inside the mFrustum)
// we then can assume that if a point is in FRONT of all of the planes, it's inside.
///////////////////////////////// POINT IN mFrustum \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
/////
///// This determines if a point is inside of the mFrustum
/////
///////////////////////////////// POINT IN mFrustum \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
function TFrustum. PointInFrustum(x, y, z : single) : boolean;
var i : integer;
begin
// Go through all the sides of the mFrustum
for i := 0 to 5 do begin
// Calculate the plane equation and check if the point is behind a side of the mFrustum
if (mFrustum[i, A] * x + mFrustum[i, B] * y + mFrustum[i, C] * z + mFrustum[i, D] <= 0) then begin
// The point was behind a side, so it ISN'T in the mFrustum
result := false;
exit;
end;
end;
// The point was inside of the mFrustum (In front of ALL the sides of the mFrustum)
result := true;
end;
///////////////////////////////// SPHERE IN mFrustum \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
/////
///// This determines if a sphere is inside of our mFrustum by it's center and radius.
/////
///////////////////////////////// SPHERE IN mFrustum \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
function TFrustum.SphereInFrustum(x, y, z, radius : single) : boolean;
var i : integer;
begin
// Go through all the sides of the mFrustum
for i := 0 to 5 do begin
// If the center of the sphere is farther away from the plane than the radius
if (mFrustum[i, A] * x + mFrustum[i, B] * y + mFrustum[i, C] * z + mFrustum[i, D] <= -radius ) then begin
// The distance was greater than the radius so the sphere is outside of the mFrustum
result := false;
exit;
end;
end;
// The sphere was inside of the mFrustum!
result := true;
end;
///////////////////////////////// CUBE IN mFrustum \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
/////
///// This determines if a cube is in or around our mFrustum by it's center and 1/2 it's length
/////
///////////////////////////////// CUBE IN mFrustum \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
function TFrustum.CubeInFrustum(x, y, z, size : single) : boolean;
var i : integer;
begin
// Basically, what is going on is, that we are given the center of the cube,
// and half the length. Think of it like a radius. Then we checking each point
// in the cube and seeing if it is inside the mFrustum. If a point is found in front
// of a side, then we skip to the next side. If we get to a plane that does NOT have
// a point in front of it, then it will return false.
// *NOTE* - This will sometimes say that a cube is inside the mFrustum when it isn't.
// This happens when all the corners of the bounding box are not behind any one plane.
// This is rare and shouldn't effect the overall rendering speed.
for i := 0 to 5 do begin
if (mFrustum[i, A] * (x - size) + mFrustum[i, B] * (y - size) + mFrustum[i, C] * (z - size) + mFrustum[i, D] > 0) then continue;
if (mFrustum[i, A] * (x + size) + mFrustum[i, B] * (y - size) + mFrustum[i, C] * (z - size) + mFrustum[i, D] > 0) then continue;
if (mFrustum[i, A] * (x - size) + mFrustum[i, B] * (y + size) + mFrustum[i, C] * (z - size) + mFrustum[i, D] > 0) then continue;
if (mFrustum[i, A] * (x + size) + mFrustum[i, B] * (y + size) + mFrustum[i, C] * (z - size) + mFrustum[i, D] > 0) then continue;
if (mFrustum[i, A] * (x - size) + mFrustum[i, B] * (y - size) + mFrustum[i, C] * (z + size) + mFrustum[i, D] > 0) then continue;
if (mFrustum[i, A] * (x + size) + mFrustum[i, B] * (y - size) + mFrustum[i, C] * (z + size) + mFrustum[i, D] > 0) then continue;
if (mFrustum[i, A] * (x - size) + mFrustum[i, B] * (y + size) + mFrustum[i, C] * (z + size) + mFrustum[i, D] > 0) then continue;
if (mFrustum[i, A] * (x + size) + mFrustum[i, B] * (y + size) + mFrustum[i, C] * (z + size) + mFrustum[i, D] > 0) then continue;
// If we get here, it isn't in the mFrustum
result := false;
exit;
end;
result := true;
end;
///////////////////////////////// BOX IN mFrustum \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
/////
///// This determines if a BOX is in or around our mFrustum by it's min and max points
/////
///////////////////////////////// BOX IN mFrustum \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*
function TFrustum.BoxInFrustum(x, y, z, x2, y2, z2 : single) : boolean;
var i : integer;
begin
// Go through all of the corners of the box and check then again each plane
// in the mFrustum. If all of them are behind one of the planes, then it most
// like is not in the mFrustum.
for i := 0 to 5 do begin
if (mFrustum[i, A] * x + mFrustum[i, B] * y + mFrustum[i, C] * z + mFrustum[i, D] > 0) then continue;
if (mFrustum[i, A] * x2 + mFrustum[i, B] * y + mFrustum[i, C] * z + mFrustum[i, D] > 0) then continue;
if (mFrustum[i, A] * x + mFrustum[i, B] * y2 + mFrustum[i, C] * z + mFrustum[i, D] > 0) then continue;
if (mFrustum[i, A] * x2 + mFrustum[i, B] * y2 + mFrustum[i, C] * z + mFrustum[i, D] > 0) then continue;
if (mFrustum[i, A] * x + mFrustum[i, B] * y + mFrustum[i, C] * z2 + mFrustum[i, D] > 0) then continue;
if (mFrustum[i, A] * x2 + mFrustum[i, B] * y + mFrustum[i, C] * z2 + mFrustum[i, D] > 0) then continue;
if (mFrustum[i, A] * x + mFrustum[i, B] * y2 + mFrustum[i, C] * z2 + mFrustum[i, D] > 0) then continue;
if (mFrustum[i, A] * x2 + mFrustum[i, B] * y2 + mFrustum[i, C] * z2 + mFrustum[i, D] > 0) then continue;
result := false;
exit;
end;
// Return a true for the box being inside of the mFrustum
result := true;
end;
/////////////////////////////////////////////////////////////////////////////////
//
// * QUICK NOTES *
//
// This file holds the mFrustum and debug class prototypes.
//
//
// Ben Humphrey (DigiBen)
// Game Programmer
// DigiBen@GameTutorials.com
// Co-Web Host of www.GameTutorials.com
//
end.
|
unit uLibraryBuilder;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, VirtualTrees,
uLibrary,
uLibraryData;
type
ILibraryBuilder = interface
['{0248C43C-1EAC-480E-AF4A-34BB61A2B11C}']
procedure BuildData;
procedure BuildNode;
procedure AfterBuild;
procedure SetParentNode(const aNode: PVirtualNode);
procedure SetTree(const aTree: TBaseVirtualTree);
property ParentNode: PVirtualNode write SetParentNode;
property Tree: TBaseVirtualTree write SetTree;
end;
{ TLibraryBuilder }
TLibraryBuilder = class(TInterfacedObject, ILibraryBuilder)
protected
fParentNode: PVirtualNode;
fOwnerNode: PVirtualNode;
fTree: TBaseVirtualTree;
fLibraryData: TLibraryData;
protected
procedure BuildData; virtual; abstract;
procedure BuildNode; virtual;
procedure AfterBuild; virtual;
procedure SetParentNode(const aNode: PVirtualNode);
procedure SetTree(const aTree: TBaseVirtualTree);
public
constructor Create;
property ParentNode: PVirtualNode read fParentNode write SetParentNode;
property Tree: TBaseVirtualTree read fTree write SetTree;
end;
{ TLibraryDirector }
TLibraryDirector = class
public
class procedure Build(const aLibraryBuilder: ILibraryBuilder);
end;
{ TSublibraryBuilder }
TSublibraryBuilder = class(TLibraryBuilder)
private
fTypeSublibrary: TTypeSublibrary;
fSublibrary: ISublibrary;
public
procedure AfterBuild; override;
procedure BuildData; override;
constructor Create(const aTypeSublibrary: TTypeSublibrary;
const aSublibrary: ISublibrary);
end;
{ TModuleBuilder }
TModuleBuilder = class(TLibraryBuilder)
private
fModule: IModule;
public
procedure AfterBuild; override;
procedure BuildData; override;
constructor Create(const aModule: IModule);
end;
{ TBaseDescBuilder }
TBaseDescBuilder = class(TLibraryBuilder)
private
fBaseDesc: IBaseDescription;
public
procedure BuildData; override;
constructor Create(const aBasedesc: IBaseDescription);
end;
{ TPreSetsBuilder }
TPreSetsBuilder = class(TLibraryBuilder)
private
fPresets: IPresets;
public
procedure AfterBuild; override;
procedure BuildData; override;
constructor Create(const aPresets: IPresets);
end;
{ TPickListsBuilder }
TPickListsBuilder = class(TLIbraryBuilder)
private
fPickLists: IPickLists;
public
procedure BuildData; override;
constructor Create(const aPickLists: IPickLists);
end;
{ TBitsBuilder }
TBitsBuilder = class(TLIbraryBuilder)
private
fBitsSet: IBitsSet;
public
procedure BuildData; override;
constructor Create(const aBitsSet: IBitsSet);
end;
{ TRegistersBuilder }
TRegistersBuilder = class(TLibraryBuilder)
private
fRegisters: IRegisters;
public
procedure AfterBuild; override;
procedure BuildData; override;
constructor Create(const aRegisters: IRegisters);
end;
{ TVarsBuilder }
TVarsBuilder = class(TLibraryBuilder)
private
fVars: IVars;
fTypeRegister: TTypeRegister;
public
procedure BuildData; override;
constructor Create(const aTypeRegister: TTypeRegister; const aVars: IVars);
end;
{ TConfigurationBuilder }
TConfigurationBuilder = class(TLIbraryBuilder)
private
fConfiguration: IGroups;
fRegisters: IRegisters;
public
procedure BuildData; override;
constructor Create(const aRegisters: IRegisters; const aConfiguration: IGroups);
end;
implementation
{ TConfigurationBuilder }
procedure TConfigurationBuilder.BuildData;
begin
fLibraryData := TConfigurationData.Create(fRegisters, fConfiguration);
end;
constructor TConfigurationBuilder.Create(const aRegisters: IRegisters;
const aConfiguration: IGroups);
begin
inherited Create;
fRegisters := aRegisters;
fConfiguration := aConfiguration;
end;
{ TVarsBuilder }
procedure TVarsBuilder.BuildData;
begin
fLibraryData := TVarsData.Create(fTypeRegister, fVars);
end;
constructor TVarsBuilder.Create(const aTypeRegister: TTypeRegister;
const aVars: IVars);
begin
inherited Create;
fTypeRegister := aTypeRegister;
fVars := aVars;
end;
{ TRegistersBuilder }
procedure TRegistersBuilder.AfterBuild;
var
P: Pointer;
Builder: ILibraryBuilder;
begin
inherited AfterBuild;
// Инициализировать Holding, Input
if fRegisters.IndexOf(TTypeRegister.trHolding) < 0 then
fRegisters.Add(TTypeRegister.trHolding);
if fRegisters.IndexOf(TTypeRegister.trInput) < 0 then
fRegisters.Add(TTypeRegister.trInput);
for P in fRegisters do
begin
Builder := TVarsBuilder.Create(fRegisters.ExtractKey(P), fRegisters.ExtractData(P));
Builder.ParentNode := fOwnerNode;
Builder.Tree := fTree;
TLibraryDirector.Build(Builder);
end;
end;
procedure TRegistersBuilder.BuildData;
begin
fLibraryData := TRegistersData.Create(fRegisters);
end;
constructor TRegistersBuilder.Create(const aRegisters: IRegisters);
begin
inherited Create;
fRegisters := aRegisters;
end;
{ TBitsBuilder }
procedure TBitsBuilder.BuildData;
begin
fLibraryData := TBitsData.Create(fBitsSet);
end;
constructor TBitsBuilder.Create(const aBitsSet: IBitsSet);
begin
inherited Create;
fBitsSet := aBitsSet;
end;
{ TPickListsBuilder }
procedure TPickListsBuilder.BuildData;
begin
fLibraryData := TPickListsData.Create(fPicklists);
end;
constructor TPickListsBuilder.Create(const aPickLists: IPickLists);
begin
inherited Create;
fPickLists := aPickLists;
end;
{ TPreSetsBuilder }
procedure TPreSetsBuilder.AfterBuild;
var
Builder: ILibraryBuilder;
begin
inherited AfterBuild;
Builder := TPickListsBuilder.Create(fPresets.PickLists);
Builder.ParentNode := fOwnerNode;
Builder.Tree := fTree;
TLibraryDirector.Build(Builder);
Builder := TBitsBuilder.Create(fPresets.BitsSet);
Builder.ParentNode := fOwnerNode;
Builder.Tree := fTree;
TLibraryDirector.Build(Builder);
end;
procedure TPreSetsBuilder.BuildData;
begin
fLibraryData := TPresetsData.Create(fPresets);
end;
constructor TPreSetsBuilder.Create(const aPresets: IPresets);
begin
inherited Create;
fPresets := aPresets;
end;
{ TBaseDescBuilder }
procedure TBaseDescBuilder.BuildData;
begin
fLibraryData := TBaseDescData.Create(fBaseDesc);
end;
constructor TBaseDescBuilder.Create(const aBasedesc: IBaseDescription);
begin
inherited Create;
fBaseDesc := aBaseDesc;
end;
{ TModuleBuilder }
constructor TModuleBuilder.Create(const aModule: IModule);
begin
inherited Create;
fModule := aModule;
end;
procedure TModuleBuilder.BuildData;
begin
fLibraryData := TModuleData.Create(fModule);
end;
procedure TModuleBuilder.AfterBuild;
var
Builder: ILibraryBuilder;
begin
inherited AfterBuild;
Builder := TBaseDescBuilder.Create(fModule.ModuleDefine.BaseDescription);
Builder.ParentNode := fOwnerNode;
Builder.Tree := fTree;
TLibraryDirector.Build(Builder);
Builder := TPresetsBuilder.Create(fModule.ModuleDefine.PreSets);
Builder.ParentNode := fOwnerNode;
Builder.Tree := fTree;
TLibraryDirector.Build(Builder);
Builder := TRegistersBuilder.Create(fModule.ModuleDefine.Registers);
Builder.ParentNode := fOwnerNode;
Builder.Tree := fTree;
TLibraryDirector.Build(Builder);
Builder := TConfigurationBuilder.Create(fModule.ModuleDefine.Registers,
fModule.ModuleDefine.Configuration);
Builder.ParentNode := fOwnerNode;
Builder.Tree := fTree;
TLibraryDirector.Build(Builder);
end;
{ TLibraryBuilder }
procedure TLibraryBuilder.BuildNode;
begin
fOwnerNode := fTree.AddChild(fParentNode, fLibraryData);
end;
procedure TLibraryBuilder.AfterBuild;
begin
fLibraryData.OwnerNode := fOwnerNode;
fLibraryData.Tree := fTree;
end;
procedure TLibraryBuilder.SetParentNode(const aNode: PVirtualNode);
begin
fParentNode := aNode;
end;
procedure TLibraryBuilder.SetTree(const aTree: TBaseVirtualTree);
begin
fTree := aTree;
end;
constructor TLibraryBuilder.Create;
begin
inherited Create;
fParentNode := nil;
end;
{ TSublibraryBuilder }
constructor TSublibraryBuilder.Create(const aTypeSublibrary: TTypeSublibrary;
const aSublibrary: ISublibrary);
begin
inherited Create;
fSublibrary := aSublibrary;
fTypeSublibrary := aTypeSublibrary;
end;
procedure TSublibraryBuilder.BuildData;
begin
fLibraryData := TSublibraryData.Create(fTypeSublibrary, fSublibrary);
end;
procedure TSublibraryBuilder.AfterBuild;
var
Builder: ILibraryBuilder;
P: Pointer;
begin
inherited AfterBuild;
// Список модулей
for P in fSublibrary do
begin
Builder := TModuleBuilder.Create(fSublibrary.ExtractData(P));
Builder.ParentNode := fOwnerNode;
Builder.Tree := fTree;
TLibraryDirector.Build(Builder);
end;
fTree.Expanded[fOwnerNode] := True;
end;
{ TLibraryDirector }
class procedure TLibraryDirector.Build(const aLibraryBuilder: ILibraryBuilder);
begin
aLibraryBuilder.BuildData;
aLibraryBuilder.BuildNode;
aLibraryBuilder.AfterBuild;
end;
end.
|
{******************************************************************************}
{ }
{ Indy (Internet Direct) - Internet Protocols Simplified }
{ }
{ https://www.indyproject.org/ }
{ https://gitter.im/IndySockets/Indy }
{ }
{******************************************************************************}
{ }
{ This file is part of the Indy (Internet Direct) project, and is offered }
{ under the dual-licensing agreement described on the Indy website. }
{ (https://www.indyproject.org/license/) }
{ }
{ Copyright: }
{ (c) 1993-2020, Chad Z. Hower and the Indy Pit Crew. All rights reserved. }
{ }
{******************************************************************************}
{ }
{ Originally written by: Fabian S. Biehn }
{ fbiehn@aagon.com (German & English) }
{ }
{ Contributers: }
{ Here could be your name }
{ }
{******************************************************************************}
// This File is auto generated!
// Any change to this file should be made in the
// corresponding unit in the folder "intermediate"!
// Generation date: 23.07.2021 14:35:33
unit IdOpenSSLHeaders_txt_db;
interface
// Headers for OpenSSL 1.1.1
// txt_db.h
{$i IdCompilerDefines.inc}
uses
IdCTypes,
IdGlobal,
IdOpenSSLConsts,
IdOpenSSLHeaders_ossl_typ;
const
DB_ERROR_OK = 0;
DB_ERROR_MALLOC = 1;
DB_ERROR_INDEX_CLASH = 2;
DB_ERROR_INDEX_OUT_OF_RANGE = 3;
DB_ERROR_NO_INDEX = 4;
DB_ERROR_INSERT_INDEX_CLASH = 5;
DB_ERROR_WRONG_NUM_FIELDS = 6;
type
OPENSSL_STRING = type Pointer;
POPENSSL_STRING = ^OPENSSL_STRING;
// DEFINE_SPECIAL_STACK_OF(OPENSSL_PSTRING, OPENSSL_STRING)
qual_func = function (v1: POPENSSL_STRING): TIdC_INT;
txt_db_st = record
num_fields: TIdC_INT;
data: Pointer; // STACK_OF(OPENSSL_PSTRING) *
index: Pointer; // LHASH_OF(OPENSSL_STRING) **
qual: qual_func;
error: TIdC_LONG;
arg1: TIdC_LONG;
arg2: TIdC_LONG;
arg_row: POPENSSL_STRING;
end;
TXT_DB = txt_db_st;
PTXT_DB = ^TXT_DB;
TXT_DB_create_index_qual = function(v1: POPENSSL_STRING): TIdC_INT;
function TXT_DB_read(in_: PBIO; num: TIdC_INT): PTXT_DB cdecl; external CLibCrypto;
function TXT_DB_write(out_: PBIO; db: PTXT_DB): TIdC_LONG cdecl; external CLibCrypto;
//function TXT_DB_create_index(db: PTXT_DB; field: TIdC_INT; qual: TXT_DB_create_index_qual; hash: OPENSSL_LH_HashFunc; cmp: OPENSSL_LH_COMPFUNC): TIdC_INT;
procedure TXT_DB_free(db: PTXT_DB) cdecl; external CLibCrypto;
function TXT_DB_get_by_index(db: PTXT_DB; idx: TIdC_INT; value: POPENSSL_STRING): POPENSSL_STRING cdecl; external CLibCrypto;
function TXT_DB_insert(db: PTXT_DB; value: POPENSSL_STRING): TIdC_INT cdecl; external CLibCrypto;
implementation
end.
|
// This program demonstrates the basic features of a SwinGame program
program GameMain; //Starts and names the program
uses SwinGame; //Imports the SwinGame library
begin //Starts the program
OpenGraphicsWindow('Shape Drawing', 800, 600); //Opens a new graphics window
LoadDefaultColors(); //Loads default colorset
ClearScreen(ColorWhite); //Clears the screen to white
DrawCircle(ColorRed, 50, 100, 25); //Draws an empty circle
FillCircle(ColorRed, 50, 160, 25); //Draws a full circle
DrawRectangle(ColorBlue, 50, 190, 25, 25); //Draws an empty rectangle
FillRectangle(ColorBlue, 50, 225, 25, 25); //Draws a full rectangle
DrawTriangle(ColorGreen, 50, 255, 50, 280, 80, 270); //Draws an empty triangle
FillTriangle(ColorGreen, 90, 255, 90, 280, 120, 270); //Draws a full triangle
DrawEllipse(ColorMagenta, 50, 300, 50, 50); //Draws an empty ellipse
FillEllipse(ColorMagenta, 50, 360, 50, 50); //Draws a full ellipse
DrawLine(ColorGrey, 400, 400, 600, 600); //Draws a line
RefreshScreen(); //Refreshes the screen so the
// graphics become visible.
Delay(50000); //Delays execution so the
// screen can be seen.
end. //Ends the program.
|
unit UPlayLists;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Buttons, ComCtrls, ExtCtrls, CheckLst, Grids;
type
TMyListBoxObject = class(TObject)
public
ClipID: String;
StartTime: String;
Constructor Create;
Destructor Destroy;
end;
TFPlayLists = class(TForm)
SpeedButton1: TSpeedButton;
SpeedButton2: TSpeedButton;
edNamePL: TEdit;
Label1: TLabel;
Panel1: TPanel;
mmCommentPL: TMemo;
Label3: TLabel;
Panel2: TPanel;
Panel3: TPanel;
Panel4: TPanel;
Panel5: TPanel;
Label2: TLabel;
Label4: TLabel;
ListBox1: TListBox;
ListBox2: TListBox;
SpeedButton3: TSpeedButton;
SpeedButton5: TSpeedButton;
procedure FormCreate(Sender: TObject);
procedure SpeedButton2Click(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
procedure FormKeyUp(Sender: TObject; var Key: Word; Shift: TShiftState);
procedure SpeedButton3Click(Sender: TObject);
procedure SpeedButton5Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
PlayListName: string;
end;
var
FPlayLists: TFPlayLists;
Procedure EditPlayList(ARow: integer);
Procedure PlaylistToPanel(ARow: integer);
Procedure SetPlaylistBlocking(ARow: integer);
Procedure ReadListClips;
Procedure LoadClipsFromPlayLists(PLName: string);
function findclipposition(Grid: tstringgrid; ClipID: string): integer;
implementation
uses umain, ucommon, uinitforms, ugrid, uactplaylist, umyfiles, umytexttable;
{$R *.dfm}
constructor TMyListBoxObject.Create;
begin
inherited;
ClipID := '';
StartTime := '';
end;
destructor TMyListBoxObject.Destroy;
begin
FreeMem(@ClipID);
FreeMem(@StartTime);
inherited;
end;
Procedure SetPlaylistBlocking(ARow: integer);
begin
try
WriteLog('MAIN', 'Uplaylists.SetPlaylistBlocking ARow=' + inttostr(ARow));
With Form1.GridLists do
begin
Form1.Image1.Canvas.FillRect(Form1.Image1.Canvas.ClipRect);
if objects[0, ARow] is TGridRows then
if (objects[0, ARow] as TGridRows).MyCells[0].Mark then
LoadBMPFromRes(Form1.Image1.Canvas, Form1.Image1.Canvas.ClipRect, 20,
20, 'UnLock')
else
LoadBMPFromRes(Form1.Image1.Canvas, Form1.Image1.Canvas.ClipRect, 20,
20, 'Lock');
Form1.Image1.Repaint;
End;
except
on E: Exception do
WriteLog('MAIN', 'Uplaylists.SetPlaylistBlocking ARow=' + inttostr(ARow) +
' | ' + E.Message);
end;
end;
Procedure PlaylistToPanel(ARow: integer);
var
plnm: string;
i, j: integer;
begin
try
WriteLog('MAIN', 'Uplaylists.PlaylistToPanel ARow=' + inttostr(ARow));
with Form1, Form1.GridLists do
begin
ListBox1.Clear;
for i := 1 to GridLists.RowCount - 1 do
begin
plnm := (GridLists.objects[0, i] as TGridRows).MyCells[3]
.ReadPhrase('Name');
ListBox1.Items.Add(plnm);
j := ListBox1.Items.Count - 1;
if not(ListBox1.Items.objects[j] is TMyListBoxObject) then
ListBox1.Items.objects[j] := TMyListBoxObject.Create;
(ListBox1.Items.objects[j] as TMyListBoxObject).ClipID :=
(GridLists.objects[0, i] as TGridRows).MyCells[3].ReadPhrase('Note');
WriteLog('MAIN', 'Uplaylists.PlaylistToPanel Name=' + plnm + ' ClipID='
+ (ListBox1.Items.objects[j] as TMyListBoxObject).ClipID);
end;
ListBox1.ItemIndex := ARow - 1;
pntlapls.SetText('CommentText', (objects[0, ARow] as TGridRows)
.MyCells[3].ReadPhrase('Comment'));
pntlapls.Draw(imgpldata.Canvas);
imgpldata.Repaint;
// lbPLComment.Caption:=(Objects[0,ARow] as TGridRows).MyCells[3].ReadPhrase('Comment');
end; // with
except
on E: Exception do
WriteLog('MAIN', 'Uplaylists.PlaylistToPanel ARow=' + inttostr(ARow) +
' | ' + E.Message);
end;
end;
procedure TFPlayLists.FormCreate(Sender: TObject);
begin
InitPlaylists;
end;
Procedure ReadListClips;
var
i, ps: integer;
clpid, txt: string;
begin
try
WriteLog('MAIN', 'Uplaylists.ReadListClips');
with Form1.GridClips do
begin
FPlayLists.ListBox1.Clear;
for i := 1 to RowCount - 1 do
begin
txt := (Form1.GridClips.objects[0, i] as TGridRows).MyCells[3]
.ReadPhrase('Clip');
FPlayLists.ListBox1.Items.Add(' ' + txt);
ps := FPlayLists.ListBox1.Items.Count - 1;
if not(FPlayLists.ListBox1.Items.objects[ps] is TMyListBoxObject) then
FPlayLists.ListBox1.Items.objects[ps] := TMyListBoxObject.Create;
(FPlayLists.ListBox1.Items.objects[ps] as TMyListBoxObject).ClipID :=
(Form1.GridClips.objects[0, i] as TGridRows).MyCells[3]
.ReadPhrase('ClipID');
WriteLog('MAIN', 'Uplaylists.ReadListClips Clip=' + txt + ' ClipID=' +
(FPlayLists.ListBox1.Items.objects[ps] as TMyListBoxObject).ClipID);
end; // for
end;
except
on E: Exception do
WriteLog('MAIN', 'Uplaylists.ReadListClips | ' + E.Message);
end;
end;
function findclipposition(Grid: tstringgrid; ClipID: string): integer;
var
i: integer;
begin
try
WriteLog('MAIN', 'Start Uplaylists.findclipposition Grid=' + Grid.Name +
' ClipID=' + ClipID);
result := -1;
for i := 1 to Grid.RowCount - 1 do
begin
if trim((Grid.objects[0, i] as TGridRows).MyCells[3].ReadPhrase('ClipID'))
= trim(ClipID) then
begin
result := i;
WriteLog('MAIN', 'Finish Uplaylists.findclipposition ClipID=' + ClipID +
' Position=' + inttostr(i));
exit;
end;
end;
except
on E: Exception do
WriteLog('MAIN', 'Uplaylists.findclipposition Grid=' + Grid.Name +
' ClipID=' + ClipID + ' | ' + E.Message);
end;
end;
procedure WriteClipsToPlayLists;
var
Stream: TFileStream;
i, j, ps, cnt: integer;
renm, FileName, ClipID, StartTime: string;
lst: tstrings;
begin
try
WriteLog('MAIN', 'Uplaylists.WriteClipsToPlayLists');
with FPlayLists do
begin
FileName := PathPlayLists + '\' + FPlayLists.PlayListName;
if FileExists(FileName) then
begin
renm := PathPlayLists + '\' + 'Temp.prjl';
RenameFile(FileName, renm);
DeleteFile(renm);
end;
lst := tstringlist.Create;
lst.Clear;
try
for i := ListBox2.Items.Count - 1 downto 0 do
if trim(ListBox2.Items.Strings[i]) = '' then
ListBox2.Items.Delete(i);
for i := 0 to ListBox2.Items.Count - 1 do
begin
ClipID := trim
((ListBox2.Items.objects[i] as TMyListBoxObject).ClipID);
StartTime := trim((ListBox2.Items.objects[i] as TMyListBoxObject)
.StartTime);
if ClipID <> '' then
lst.Add(ClipID + '|' + StartTime);
end;
lst.SaveToFile(FileName);
finally
lst.Free;
end;
end;
except
on E: Exception do
WriteLog('MAIN', 'Uplaylists.WriteClipsToPlayLists | ' + E.Message);
end;
end;
Procedure LoadClipsFromPlayLists(PLName: string);
var
Stream: TFileStream;
i, cnt, ps, psi, plid: integer;
renm, FileName: string;
tc: TTypeCell;
clp, clpid, clid, sttm: string;
lst: tstrings;
begin
try
WriteLog('MAIN', ' Start Uplaylists.LoadClipsFromPlayLists Name=' + PLName);
with FPlayLists do
begin
FileName := PathPlayLists + '\' + FPlayLists.PlayListName;
if not FileExists(FileName) then
exit;
lst := tstringlist.Create;
lst.Clear;
try
lst.LoadFromFile(FileName);
ListBox2.Items.Clear;
for i := 0 to lst.Count - 1 do
begin
clid := trim(lst.Strings[i]);
plid := pos('|', clid);
if plid <= 0 then
begin
sttm := '';
end
else
begin
sttm := Copy(clid, plid + 1, length(clid));
clid := Copy(clid, 1, plid - 1);
end;
psi := findclipposition(Form1.GridClips, clid);
if psi > 0 then
begin
clp := (Form1.GridClips.objects[0, psi] as TGridRows).MyCells[3]
.ReadPhrase('Clip');
clpid := (Form1.GridClips.objects[0, psi] as TGridRows)
.MyCells[3].ReadPhrase('ClipId');
ListBox2.Items.Add(clp);
ps := ListBox2.Items.Count - 1;
if not(ListBox2.Items.objects[ps] is TMyListBoxObject) then
ListBox2.Items.objects[ps] := TMyListBoxObject.Create;
(ListBox2.Items.objects[ps] as TMyListBoxObject).ClipID := clpid;
(ListBox2.Items.objects[ps] as TMyListBoxObject).StartTime := sttm;
end;
WriteLog('MAIN', 'Uplaylists.LoadClipsFromPlayLists Clip=' + clp +
' ClipID=' + clpid);
end;
isprojectchanges := true;
if FileExists(FileName) then
begin
renm := PathPlayLists + '\' + 'Temp.prjl';
RenameFile(FileName, renm);
DeleteFile(renm);
end;
lst.SaveToFile(FileName);
finally
lst.Free;
end;
WriteLog('MAIN', ' Finish Uplaylists.LoadClipsFromPlayLists Name='
+ PLName);
end;
except
on E: Exception do
WriteLog('MAIN', 'Uplaylists.LoadClipsFromPlayLists Name=' + PLName +
' | ' + E.Message);
end;
end;
Procedure EditPlayList(ARow: integer);
var
i, setpos: integer;
dt: string;
begin
try
WriteLog('MAIN', 'Uplaylists.EditPlayList Start ARow=' + inttostr(ARow));
ReadListClips;
FPlayLists.ListBox2.Clear;
if ARow = -1 then
begin
FPlayLists.edNamePL.Text := '';
FPlayLists.mmCommentPL.Clear;
FPlayLists.PlayListName := '';
end
else
begin
FPlayLists.edNamePL.Text :=
(Form1.GridLists.objects[0, ARow] as TGridRows).MyCells[3]
.ReadPhrase('Name');
FPlayLists.mmCommentPL.Text :=
(Form1.GridLists.objects[0, ARow] as TGridRows).MyCells[3]
.ReadPhrase('Comment');
FPlayLists.PlayListName := (Form1.GridLists.objects[0, ARow] as TGridRows)
.MyCells[3].ReadPhrase('Note');
if trim(FPlayLists.PlayListName) <> '' then
LoadClipsFromPlayLists(FPlayLists.PlayListName);
end;
FPlayLists.ActiveControl := FPlayLists.edNamePL;
FPlayLists.ShowModal;
if FPlayLists.ModalResult = mrOk then
begin
if ARow = -1 then
begin
setpos := GridAddRow(Form1.GridLists, RowGridListPL);
(Form1.GridLists.objects[0, setpos] as TGridRows).MyCells[0]
.Mark := false;
(Form1.GridLists.objects[0, setpos] as TGridRows).MyCells[1]
.Mark := false;
(Form1.GridLists.objects[0, setpos] as TGridRows).MyCells[3]
.UpdatePhrase('Name', FPlayLists.edNamePL.Text);
(Form1.GridLists.objects[0, setpos] as TGridRows).MyCells[3]
.UpdatePhrase('Comment', FPlayLists.mmCommentPL.Text);
for i := 0 to Form1.GridLists.RowCount - 1 do
(Form1.GridLists.objects[0, i] as TGridRows).MyCells[2].Mark := false;
(Form1.GridLists.objects[0, setpos] as TGridRows).MyCells[2]
.Mark := true;
IDPLst := IDPLst + 1;
(Form1.GridLists.objects[0, setpos] as TGridRows).ID := IDPLst;
FPlayLists.PlayListName := 'PL' + createunicumname + '.plst';
(Form1.GridLists.objects[0, setpos] as TGridRows).MyCells[3]
.UpdatePhrase('Note', FPlayLists.PlayListName);
Form1.GridLists.Row := setpos;
end
else
begin
setpos := ARow;
(Form1.GridLists.objects[0, ARow] as TGridRows).MyCells[3]
.UpdatePhrase('Name', FPlayLists.edNamePL.Text);
(Form1.GridLists.objects[0, ARow] as TGridRows).MyCells[3]
.UpdatePhrase('Comment', FPlayLists.mmCommentPL.Text);
dt := (Form1.GridLists.objects[0, ARow] as TGridRows).MyCells[3]
.ReadPhrase('Note');
if trim(dt) = '' then
begin
FPlayLists.PlayListName := 'PL' + createunicumname + '.plst';
(Form1.GridLists.objects[0, ARow] as TGridRows).MyCells[3]
.UpdatePhrase('Note', FPlayLists.PlayListName);
end
else
FPlayLists.PlayListName := dt;
end;
WriteClipsToPlayLists;
SetPlaylistBlocking(setpos);
WriteLog('MAIN', 'Uplaylists.EditPlayList Finish ARow=' + inttostr(ARow));
end;
except
on E: Exception do
WriteLog('MAIN', 'Uplaylists.EditPlayList ARow=' + inttostr(ARow) + ' | '
+ E.Message);
end;
end;
procedure TFPlayLists.SpeedButton2Click(Sender: TObject);
begin
WriteLog('MAIN', 'TFPlayLists.SpeedButton2Click ModalResult:=mrCancel');
ModalResult := mrCancel;
end;
procedure TFPlayLists.SpeedButton1Click(Sender: TObject);
begin
if trim(edNamePL.Text) <> '' then
begin
WriteLog('MAIN', 'TFPlayLists.SpeedButton1Click ModalResult:=mrOk');
ModalResult := mrOk;
end
else
begin
WriteLog('MAIN', 'TFPlayLists.SpeedButton1Click ActiveControl:=edNamePL');
ActiveControl := edNamePL;
end;
end;
procedure TFPlayLists.FormKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key = 13 then
begin
WriteLog('MAIN', 'TFPlayLists.FormKeyUp key=13');
if ActiveControl = mmCommentPL then
exit;
WriteLog('MAIN', 'TFPlayLists.FormKeyUp SpeedButton1Click');
SpeedButton1Click(nil);
end;
end;
procedure TFPlayLists.SpeedButton3Click(Sender: TObject);
var
i: integer;
begin
WriteLog('MAIN', 'TFPlayLists.SpeedButton3Click ListBox2.DeleteSelected');
ListBox2.DeleteSelected;
end;
function ClipExists(ClipID: String): boolean;
var
i: integer;
begin
try
WriteLog('MAIN', 'Uplaylists.ClipExists ClipID=' + ClipID);
with FPlayLists do
begin
result := false;
for i := 0 to ListBox2.Items.Count - 1 do
begin
if ListBox2.Items.objects[i] is TMyListBoxObject then
begin
if (ListBox2.Items.objects[i] as TMyListBoxObject).ClipID = ClipID
then
begin
WriteLog('MAIN', 'Uplaylists.ClipExists ClipID=' + ClipID +
' Position=' + inttostr(i));
result := true;
exit;
end;
end;
end;
end;
except
on E: Exception do
WriteLog('MAIN', 'Uplaylists.ClipExists ClipID=' + ClipID + ' | ' +
E.Message);
end;
end;
procedure TFPlayLists.SpeedButton5Click(Sender: TObject);
var
i, ps: integer;
clp: string;
begin
try
WriteLog('MAIN', 'TFPlayLists.SpeedButton5Click');
for i := ListBox2.Items.Count - 1 downto 0 do
if trim(ListBox2.Items.Strings[i]) = '' then
ListBox2.Items.Delete(i);
for i := 0 to ListBox1.Items.Count - 1 do
begin
if ListBox1.Selected[i] then
begin
if ListBox1.Items.objects[i] is TMyListBoxObject then
begin
if not ClipExists((ListBox1.Items.objects[i] as TMyListBoxObject)
.ClipID) then
begin
clp := trim(ListBox1.Items.Strings[i]);
ListBox2.Items.Add(clp);
ps := ListBox2.Items.Count - 1;
if not(ListBox2.Items.objects[ps] is TMyListBoxObject) then
ListBox2.Items.objects[ps] := TMyListBoxObject.Create;
(ListBox2.Items.objects[ps] as TMyListBoxObject).ClipID :=
(ListBox1.Items.objects[i] as TMyListBoxObject).ClipID;
WriteLog('MAIN', 'TFPlayLists.SpeedButton5Click Clip=' + clp +
' ClipID=' + (ListBox2.Items.objects[ps]
as TMyListBoxObject).ClipID);
end;
end;
end;
ListBox1.Selected[i] := false;
end;
except
on E: Exception do
WriteLog('MAIN', 'TFPlayLists.SpeedButton5Click | ' + E.Message);
end;
end;
end.
|
unit uexportimport;
interface
uses
udrawtim;
procedure SaveImage(const FileName: string; Surf: PDrawSurf; Indexed: Boolean);
function LoadImage(const FileName: string): PDrawSurf;
implementation
uses
FPReadPNG, Classes, BGRABitmap, FileUtil, sysutils, zstream, FPWritePNG;
procedure SaveImage(const FileName: string; Surf: PDrawSurf; Indexed: Boolean);
var
Writer: TFPWriterPNG;
begin
Writer := TFPWriterPNG.Create;
Writer.CompressionLevel := clnone;
Writer.UseAlpha := True;
Writer.Indexed := Indexed;
Surf^.SaveToFileUTF8(FileName, Writer);
Writer.Free;
end;
function LoadImage(const FileName: string): PDrawSurf;
var
Reader: TFPReaderPNG;
Stream: TFileStream;
begin
Reader := TFPReaderPNG.Create;
Stream := TFileStream.Create(UTF8ToSys(FileName), fmOpenRead or fmShareDenyWrite);
Stream.Position := 0;
New(Result);
Result^ := TBGRABitmap.Create;
Result^.UsePalette := True;
Reader.ImageRead(Stream, Result^);
Stream.Free;
Reader.Free;
end;
end.
|
unit UData;
interface
uses
System.SysUtils,
System.Types,
System.Classes,
System.Generics.Collections,
System.ImageList,
Data.DB,
Vcl.ImgList,
Vcl.Controls,
ZAbstractConnection,
ZConnection,
ZAbstractRODataset,
ZDataset,
UDefinitions,
UCommandData;
type
TWorkerThread = class;
TMoveErrorsThread = class;
TdmData = class(TDataModule)
conMaster: TZConnection;
conSlave: TZConnection;
qrySelectReplicaSQL: TZReadOnlyQuery;
qrySelectReplicaCmd: TZReadOnlyQuery;
qryMasterHelper: TZReadOnlyQuery;
qryLastId: TZReadOnlyQuery;
qryCompareRecCountMS: TZReadOnlyQuery;
qrySlaveHelper: TZReadOnlyQuery;
qryCompareSeqMS: TZReadOnlyQuery;
qrySnapshotTables: TZReadOnlyQuery;
strict private
FStartId: Int64;
FLastId: Int64;
FStartDT, FLastDT : TDateTime;
FSelectRange: Integer;
FPacketRange: Integer;
FPacketNumber: Integer; // порядковый номер пакета в сессии
FSessionNumber: Integer;
FMsgProc: TNotifyMessage;
FStopped: Boolean;
FWriteCommands: Boolean;
FStartReplicaAttempt: Integer; // номер попытки начать репликацию
FClient_Id: Int64;// идентфикатор базы данных slave
FCommandData: TCommandData;
FFailCmds: TCommandData;
FReplicaFinished: TReplicaFinished;
FMoveErrorsThrd: TMoveErrorsThread;
FMoveErrorsThrdFinished: Boolean;
FOnChangeStartId: TOnChangeStartId;
FOnNewSession: TOnNewSession;
FOnEndSession: TNotifyEvent;
FOnNeedRestart: TNotifyEvent;
FOnCompareRecCountMS: TOnCompareRecCountMS;
strict private
procedure ApplyConnectionConfig(AConnection: TZConnection; ARank: TServerRank);
procedure BuildReplicaCommandsSQL(const AStartId: Int64; const ARange: Integer);
procedure ExecuteCommandsOneByOne;
procedure ExecuteErrCommands;
procedure LogMsg(const AMsg: string); overload;
procedure LogMsg(const AMsg: string; const aUID: Cardinal); overload;
procedure LogErrMsg(const AMsg: string);
procedure LogMsgFile(const AMsg, AFileName: string);
procedure OnTerminateMoveErrors(Sender: TObject);
procedure FetchSequences(AServer: TServerRank; out ASeqDataArr: TSequenceDataArray);
procedure SaveValueInDB(const AValue: Int64; const AFieldName: string; const ASaveInMaster: Boolean = True);
procedure SaveErrorInMaster(const AStep: Integer; const AStartId, ALastId, AClientId: Int64; const AErrDescription: string);
strict private
procedure SetStartId(const AValue: Int64);
function GetLastId: Int64;
procedure SetLastId(const AValue: Int64);
function GetLastId_DDL: Int64;
procedure SetLastId_DDL(const AValue: Int64);
strict private
function ApplyScriptsFor(AScriptsContent, AScriptNames: TStrings; AServer: TServerRank): TApplyScriptResult;
function ExecutePreparedPacket: Integer;
function ExecuteReplica: TReplicaFinished;
function IsConnected(AConnection: TZConnection; ARank: TServerRank): Boolean;
function IsConnectionAlive(AConnection: TZConnection): Boolean;
function IsBothConnectionsAlive: Boolean;
function GetSlaveValues: TSlaveValues;
function GetMasterValues(const AClientId: Int64): TMasterValues;
function SaveErrorInDB(AServerRank: TServerRank; const AStep: Integer; const AStartId, ALastId, AClientId: Int64;
const AErrDescription: string): Boolean;
protected
property StartId: Int64 read FStartId write SetStartId;
property LastId_DDL: Int64 read GetLastId_DDL write SetLastId_DDL;
public
MinDT: TDateTime;
MaxDT: TDateTime;
constructor Create(AOwner: TComponent; AMsgProc: TNotifyMessage); reintroduce; overload;
constructor Create(AOwner: TComponent; const AStartId: Int64; const ASelectRange, APacketRange: Integer;
AMsgProc: TNotifyMessage); reintroduce; overload;
destructor Destroy; override;
property OnChangeStartId: TOnChangeStartId read FOnChangeStartId write FOnChangeStartId;
property OnNewSession: TOnNewSession read FOnNewSession write FOnNewSession;
property OnEndSession: TNotifyEvent read FOnEndSession write FOnEndSession;
property OnNeedRestart: TNotifyEvent read FOnNeedRestart write FOnNeedRestart;
property OnCompareRecCountMS: TOnCompareRecCountMS read FOnCompareRecCountMS write FOnCompareRecCountMS;
property SelectRange: Integer read FSelectRange write FSelectRange;
property LastId: Int64 read GetLastId write SetLastId;
property ReplicaFinished: TReplicaFinished read FReplicaFinished;
function ApplyScripts(AScriptsContent, AScriptNames: TStrings): TApplyScriptResult;
function GetCompareRecCountMS_SQL(const ADeviationsOnly: Boolean): string;
function GetCompareSeqMS_SQL(const ADeviationsOnly: Boolean): string;
function IsMasterConnected: Boolean;
function IsSlaveConnected: Boolean;
function IsBothConnected: Boolean;
function GetReplicaCmdCount: Integer;
function GetMinMaxId: TMinMaxId;
function MinID: Int64;
function MaxID: Int64;
function InitConnection(AConnection: TZConnection; ARank: TServerRank): boolean;
procedure AlterSlaveSequences;
procedure MoveSavedProcToSlave;
procedure MoveErrorsFromSlaveToMaster;
procedure StartReplica;
procedure StopReplica;
end;
TWorkerThread = class(TThread)
strict private
FStartId: Int64;
FSelectRange: Integer;
FPacketRange: Integer;
FMsgProc: TNotifyMessage;
FData: TdmData;
FOnChangeStartId: TOnChangeStartId;
FOnNewSession: TOnNewSession;
FOnEndSession: TNotifyEvent;
FOnNeedRestart: TNotifyEvent;
strict private
procedure InnerChangeStartId(const ANewStartId: Int64; const ANewStartDT : TDateTime );
procedure InnerNewSession(const AStart: TDateTime; const AMinId, AMaxId: Int64; const AMinDT, AMaxDT: TDateTime; const ARecCount, ASessionNumber: Integer);
procedure InnerEndSession(Sender: TObject);
procedure InnerNeedRestart(Sender: TObject);
protected
FReturnValue: Int64;
FReturnDT: TDateTime;
protected
procedure InnerMsgProc(const AMsg, AFileName: string; const aUID: Cardinal; AMsgType: TLogMessageType);
procedure MySleep(const AInterval: Cardinal);
property Data: TdmData read FData;
public
constructor Create(CreateSuspended: Boolean; const AStartId: Int64; const ASelectRange, APacketRange: Integer;
AMsgProc: TNotifyMessage; AKind: TThreadKind = tknNondriven); reintroduce; overload;
constructor Create(CreateSuspended: Boolean; AMsgProc: TNotifyMessage; AKind: TThreadKind = tknNondriven); reintroduce; overload;
destructor Destroy; override;
procedure Stop;
property OnChangeStartId: TOnChangeStartId read FOnChangeStartId write FOnChangeStartId;
property OnNewSession: TOnNewSession read FOnNewSession write FOnNewSession;
property OnEndSession: TNotifyEvent read FOnEndSession write FOnEndSession;
property OnNeedRestart: TNotifyEvent read FOnNeedRestart write FOnNeedRestart;
property MyReturnValue: Int64 read FReturnValue;
property MyReturnDT: TDateTime read FReturnDT;
end;
TSinglePacket = class(TWorkerThread)
protected
procedure Execute; override;
end;
TMinMaxIdThread = class(TWorkerThread)
protected
procedure Execute; override;
end;
TLastIdThread = class(TWorkerThread)
protected
procedure Execute; override;
end;
TReplicaThread = class(TWorkerThread)
protected
procedure Execute; override;
end;
TCompareRecCountMSThread = class(TWorkerThread)
strict private
FDeviationsOnly: Boolean;
FOnCompareRecCountMS: TOnCompareRecCountMS;
strict private
procedure MyOnCompareRecCountMS(const aSQL: string);
protected
procedure Execute; override;
public
constructor Create(CreateSuspended, ADeviationsOnly: Boolean; AMsgProc: TNotifyMessage; AKind: TThreadKind = tknNondriven); reintroduce;
property OnCompareRecCountMS: TOnCompareRecCountMS read FOnCompareRecCountMS write FOnCompareRecCountMS;
end;
TCompareSeqMSThread = class(TWorkerThread)
strict private
FDeviationsOnly: Boolean;
protected
procedure Execute; override;
public
constructor Create(CreateSuspended, ADeviationsOnly: Boolean; AMsgProc: TNotifyMessage; AKind: TThreadKind = tknNondriven); reintroduce;
end;
TApplyScriptThread = class(TWorkerThread)
strict private
FScriptsContent: TStringList;
FScriptNames: TStringList;
protected
procedure Execute; override;
public
constructor Create(CreateSuspended: Boolean; AScriptsContent, AScriptNames: TStrings; AMsgProc: TNotifyMessage; AKind: TThreadKind = tknNondriven); reintroduce;
destructor Destroy; override;
end;
TMoveProcToSlaveThread = class(TWorkerThread)
protected
procedure Execute; override;
end;
TAlterSlaveSequencesThread = class(TWorkerThread)
protected
procedure Execute; override;
end;
TMoveErrorsThread = class(TWorkerThread)
protected
procedure Execute; override;
end;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
uses
Winapi.Windows,
System.Math,
ZDbcIntfs,
ZClasses,
UConstants,
USettings,
UCommon;
const
// Сообщения Шаг №1 - Шаг №3
cAttempt1 = '№1 <%d-%d> tranId=<%d-%d> %d записей за %s %s';
cAttempt2 = '№2 <%d-%d> ok = %d error = %d за %s';
cAttempt3 = '№3 <%d-%d> ok = %d error = %d за %s';
// номера шагов
cStep1 = 1;
cStep2 = 2;
cStep3 = 3;
// Сообщения об ошибке
cWrongRange = 'Ожидается, что MaxId >= StartId, а имеем MaxId = %d, StartId = %d';
cTransWrongRange = 'Команды с транзакциями из диапазона <%d-%d> уже выполнялись в другом пакете';
// Пороговые значения
cWaitNextMsg = 500;
cSaveInMasterAfterNSessions = 100;
{ TdmData }
procedure TdmData.AlterSlaveSequences;
const
cAlterSequence = 'alter sequence if exists public.%s increment %d restart with %d';
cSuccess = 'Последние значения последовательностей перенесены в Slave';
var
I: Integer;
arrSeq: TSequenceDataArray;
sAlterSequence: string;
begin
try
// Сначала получим все последовательности Master и их последние значения
FetchSequences(srMaster, arrSeq);
if FStopped then Exit;
// Теперь готов записать последние значения последовательностей в Slave
if IsSlaveConnected and (Length(arrSeq) > 0) then
begin
for I := Low(arrSeq) to High(arrSeq) do
begin
if FStopped then Exit;
sAlterSequence := Format(cAlterSequence, [arrSeq[I].Name, arrSeq[I].Increment, arrSeq[I].LastValue + 100000]);
try
with conSlave.DbcConnection do
begin
SetAutoCommit(False);
PrepareStatement(sAlterSequence).ExecutePrepared;
Commit;
end;
except
on E: Exception do
begin
conSlave.DbcConnection.Rollback;
LogErrMsg(Format(cExceptionMsg, [E.ClassName, E.Message]));
Break;
end;
end;
end;
if FStopped then Exit;
LogMsg(cSuccess);
end;
except
on E: Exception do
LogErrMsg(Format(cExceptionMsg, [E.ClassName, E.Message]));
end;
end;
procedure TdmData.ApplyConnectionConfig(AConnection: TZConnection; ARank: TServerRank);
var
sHost, sDatabase, sUser, sPassword: string;
iPort: Integer;
begin
iPort := TSettings.DefaultPort;
case ARank of
srMaster:
begin
sHost := TSettings.MasterServer;
sDatabase := TSettings.MasterDatabase;
iPort := TSettings.MasterPort;
sUser := TSettings.MasterUser;
sPassword := TSettings.MasterPassword;
end;
srSlave:
begin
sHost := TSettings.SlaveServer;
sDatabase := TSettings.SlaveDatabase;
iPort := TSettings.SlavePort;
sUser := TSettings.SlaveUser;
sPassword := TSettings.SlavePassword;
end;
end;
with AConnection do
begin
Disconnect;
HostName := sHost;
Database := sDatabase;
Port := iPort;
User := sUser;
Password := sPassword;
LibraryLocation := TSettings.LibLocation;
// Properties.Add('timeout=1');// таймаут сервера - 1 секунда
{ После потери коннекта и попытке переподключиться в методе BuildReplicaCommandsSQL
возникает исключение "[EZSQLException] SQL Error: ОШИБКА: подготовленный оператор "156270147041" не существует".
Параметр 'EMULATE_PREPARES' применен по рекомендации на форуме ZeosLib https://zeoslib.sourceforge.io/viewtopic.php?t=10695 }
Properties.Values['EMULATE_PREPARES'] := 'True';
end;
end;
function TdmData.ApplyScripts(AScriptsContent, AScriptNames: TStrings): TApplyScriptResult;
var
masterResult, slaveResult: TApplyScriptResult;
begin
Result := asNoAction;
masterResult := asError;
slaveResult := asError;
if (AScriptsContent = nil) or (AScriptNames = nil) or (AScriptsContent.Count = 0) or (AScriptNames.Count = 0) then Exit;
try
masterResult := ApplyScriptsFor(AScriptsContent, AScriptNames, srMaster);
if masterResult = asError then
begin
LogErrMsg('Не удалось выполнить скрипты для Master');
Exit;
end;
slaveResult := ApplyScriptsFor(AScriptsContent, AScriptNames, srSlave);
if slaveResult = asError then
LogErrMsg('Не удалось выполнить скрипты для Slave');
finally
if (masterResult = asSuccess) and (slaveResult = asSuccess) then
Result := asSuccess
else
Result := asError;
end;
end;
function TdmData.ApplyScriptsFor(AScriptsContent, AScriptNames: TStrings; AServer: TServerRank): TApplyScriptResult;
var
I: Integer;
bConnected: Boolean;
tmpStmt: IZPreparedStatement;
tmpConn: TZConnection;
const
cExceptMsg = 'Возникла ошибка в скрипте %s' + cCrLf + cExceptionMsg;
begin
Result := asError;
tmpConn := nil;
bConnected := False;
if (AScriptsContent = nil) or (AScriptNames = nil) or (AScriptsContent.Count = 0) or (AScriptNames.Count = 0) then Exit;
case AServer of
srMaster:
begin
bConnected := IsMasterConnected;
tmpConn := conMaster;
end;
srSlave:
begin
bConnected := IsSlaveConnected;
tmpConn := conSlave;
end;
end;
if (tmpConn <> nil) and bConnected then
for I := 0 to Pred(AScriptsContent.Count) do
try
if not FStopped then
begin
tmpConn.DbcConnection.SetAutoCommit(False);
tmpStmt := tmpConn.DbcConnection.PrepareStatement(AScriptsContent[I]);
tmpStmt.ExecuteUpdatePrepared;
tmpConn.DbcConnection.Commit;
Result := asSuccess;
end;
except
on E: Exception do
begin
tmpConn.DbcConnection.Rollback;
LogErrMsg(Format(cExceptMsg, [AScriptNames[I], E.ClassName, E.Message]));
Result := asError;
Break;
end;
end;
end;
procedure TdmData.BuildReplicaCommandsSQL(const AStartId: Int64; const ARange: Integer);
const
cGetSQL = 'формирование SQL ...';
cFetch = 'получение записей ...';
cElapsedFetch = '%s записей получено за %s';
cBuild = 'запись данных в локальное хранилище ...';
cElapsedBuild = '%s уникальных записей в локальное хранилище за %s';
var
crdStartFetch, crdStartBuild{, crdLastId}: Cardinal;
dtmStart: TDateTime;
begin
if FStopped then Exit;
Inc(FSessionNumber);
FLastId := -1;
dtmStart := Now;
crdStartFetch := GetTickCount;
qrySelectReplicaCmd.Close;
qrySelectReplicaCmd.SQL.Clear;
if IsMasterConnected then
try
LogMsg(cGetSQL, crdStartFetch);
with qrySelectReplicaSQL do // результат запроса содержит SQL-текст, записанный в виде набора строк
begin
Close;
ParamByName('id_start').AsLargeInt := AStartId;
ParamByName('rec_count').AsInteger := ARange;
Open;
First;
while not EOF and not FStopped do
begin
if not Fields[0].IsNull then
qrySelectReplicaCmd.SQL.Add(Fields[0].AsString);
Next;
end;
Close;
end;
if FStopped then Exit;
// LogMsg(qrySelectReplicaCmd.SQL.Text, 'Replica_SQL.txt');
{ qrySelectReplicaCmd вернет набор команд репликации (INSERT, UPDATE, DELETE) в поле Result,
которые могут быть выполнены пакетами с помощью conSlave }
LogMsg(cFetch, crdStartFetch);
qrySelectReplicaCmd.Open;
qrySelectReplicaCmd.FetchAll;
qrySelectReplicaCmd.First;
if qrySelectReplicaCmd.RecordCount = 0 then
FStartId := 0
else begin
FStartId := qrySelectReplicaCmd.FieldByName('Id').AsLargeInt; // откорректируем значение StartId в соответствии с реальными данными
FStartDT := qrySelectReplicaCmd.FieldByName('last_modified').AsDateTime; //
end;
LogMsg(Format(cElapsedFetch, [IntToStr(qrySelectReplicaCmd.RecordCount), Elapsed(crdStartFetch)]), crdStartFetch);
if FStopped then Exit;
// строим свой массив данных, который позволит выбирать записи пакетами с учетом границ transaction_id
crdStartBuild := GetTickCount;
LogMsg(cBuild, crdStartBuild);
FCommandData.BuildData(qrySelectReplicaCmd);
qrySelectReplicaCmd.Close;
LogMsg(Format(cElapsedBuild, [IntToStr(FCommandData.Count), Elapsed(crdStartBuild)]), crdStartBuild);
if FStopped then Exit;
FCommandData.Last; //чтобы прочитать MaxId
// сохраним правую границу сессии для последующего использования
FLastId := FCommandData.Data.Id;
FLastDT := FCommandData.Data.DT;
// показать инфу о новой сессии в GUI
if (FStartId > 0) and (FLastId > 0) and (FStartId <= FLastId) and Assigned(FOnNewSession) then
FOnNewSession(dtmStart, FStartId, FLastId, FStartDT, FLastDT, FCommandData.Count, FSessionNumber);
except
on E: Exception do
begin
FStopped := True;
FReplicaFinished := rfErrStopped;
LogErrMsg(Format(cExceptionMsg, [E.ClassName, E.Message]));
end;
end;
end;
constructor TdmData.Create(AOwner: TComponent; AMsgProc: TNotifyMessage);
begin
inherited Create(AOwner);
FMsgProc := AMsgProc;
end;
constructor TdmData.Create(AOwner: TComponent; const AStartId: Int64; const ASelectRange, APacketRange: Integer; AMsgProc: TNotifyMessage);
begin
inherited Create(AOwner);
FStartId := AStartId;
FMsgProc := AMsgProc;
FSelectRange := ASelectRange;
FPacketRange := APacketRange;
FCommandData := TCommandData.Create;
FFailCmds := TCommandData.Create;
FReplicaFinished := rfComplete;
FMoveErrorsThrdFinished := True;
end;
destructor TdmData.Destroy;
begin
conMaster.Disconnect;
conSlave.Disconnect;
FreeAndNil(FCommandData);
FreeAndNil(FFailCmds);
inherited;
end;
procedure TdmData.StartReplica;
var
bConnected: Boolean;
const
cStartReplicaAttemptCount = 3;// столько раз попытаемся начать репликацию, прежде чем прекратим выполнение
begin
{ Каждая репликация создается в отдельном потоке, на старте создается экземпляр TdmData,
поэтому в самом начале всегда FStopped = False. Если возникла потеря связи, программа рекурсивно вызывает
StartReplica, чтобы восстановить соединение }
if FStopped then Exit;// если пользователь решил прекратить рекурсивные попытки реконнекта
bConnected := IsBothConnected; // каждый вызов IsConnected делает 3 попытки установить соединение
// не удалось установить коннект перед началом репликации
if not bConnected then
begin
if FStartReplicaAttempt = 0 then
begin
FReplicaFinished := rfNoConnect;
if not FStopped and Assigned(FOnNeedRestart) then // если коннекта нет с самого начала, тогда просим запустить реконнект
FOnNeedRestart(nil); // из главного потока через [TSettings.ReconnectTimeoutMinute] минут
end
else
FReplicaFinished := rfErrStopped; // если это рекурсивный вызов StartReplica из блока 'if FReplicaFinished = rfErrStopped then'
end;
// если связь установлена, тогда начинаем репликацию
if bConnected then
try
FStopped := False;
FStartReplicaAttempt := 0;
FReplicaFinished := ExecuteReplica;
except
on E: Exception do
begin
FReplicaFinished := rfErrStopped;
LogErrMsg(Format(cExceptionMsg, [E.ClassName, E.Message]));
end;
end;
// Если реплика была прекращена из-за ошибки, тогда нужно проверить не была ли ошибка вызвана потерей связи
if FReplicaFinished = rfErrStopped then
begin
// если связи нет, тогда причиной ошибки считаем потерю связи
if not IsBothConnectionsAlive then
begin
FReplicaFinished := rfLostConnect;
Inc(FStartReplicaAttempt);
if FStartReplicaAttempt > cStartReplicaAttemptCount then
begin
if not FStopped and Assigned(FOnNeedRestart) then
FOnNeedRestart(nil);
Exit;
end
else StartReplica;
end;
end;
end;
procedure TdmData.ExecuteCommandsOneByOne; // предполагается использовать внутри StartReplica после неудачи ExecutePreparedPacket
var
iStartId, iLastId, iMaxId: Int64;
iSuccCount, iFailCount: Integer;
crdStart, crdLogMsg: Cardinal;
begin
// будем выполнять команды по одной
if FStopped then Exit;
{$IFDEF NO_EXECUTE} // для проверки границ пакета, без выполнения запросов
Exit;
{$ENDIF}
crdStart := GetTickCount;
iLastId := FStartId;
try
iMaxId := FCommandData.GetMaxId(FStartId, FPacketRange);
if FStartId >= iMaxId then
begin
LogErrMsg(Format(cWrongRange, [iMaxId, FStartId]));
FStopped := True;
FReplicaFinished := rfErrStopped;
Exit;
end;
FCommandData.MoveToId(FCommandData.ValidId(FStartId));
iStartId := FStartId;
iSuccCount := 0;
iFailCount := 0;
// строка "№2 <56477135-56513779> ок = 0 записей error = 0 записей за "
LogMsg(Format(cAttempt2, [iStartId, iMaxId, iSuccCount, iFailCount, EmptyStr]), crdStart);
crdLogMsg := GetTickCount;
try
while not FCommandData.EOF and (FCommandData.Data.Id <= iMaxId) and not FStopped do
begin
try
if IsSlaveConnected then
with conSlave.DbcConnection do
begin
SetAutoCommit(False);
PrepareStatement(FCommandData.Data.SQL).ExecutePrepared;
Commit;
Inc(iSuccCount);
end;
except
on E: Exception do
begin
conSlave.DbcConnection.Rollback;
// Id и SQL невыполненных команд сохраняем в FFailCmds
FFailCmds.Add(FCommandData.Data.Id, FCommandData.Data.TransId, FCommandData.Data.SQL);
Inc(iFailCount);
LogErrMsg(Format(cExceptionMsg, [E.ClassName, E.Message]));
// если нужно сохранять ошибки шага №2 в БД
if TSettings.SaveErrStep2InDB then
SaveErrorInMaster(cStep2, FCommandData.Data.Id, 0, FClient_Id, E.Message);
end;
end;
// Команды выполняются быстро и в большом количестве, но текст сообщений при этом отличается несущественно.
// Кроме того, в файл будет сохранено только последнее сообщение. Этот спам может подвесить программу.
// Для того, чтобы уменьшить поток сообщений, будем передавать только некоторые из них с интервалом cWaitNextMsg.
if (GetTickCount - crdLogMsg) > cWaitNextMsg then
begin
LogMsg(Format(cAttempt2, [iStartId, iMaxId, iSuccCount, iFailCount, Elapsed(crdStart)]), crdStart);
crdLogMsg := GetTickCount;
end;
iLastId := FCommandData.Data.Id; // FCommandData.Data.Id содержит table_update_data.Id
FCommandData.Next;
StartId := FCommandData.Data.Id; // используем св-во StartId, а не FStartId, чтобы возбудить событие OnChangeStartId
end;
if FCommandData.EOF then // если достигли правой границы сессии, тогда используем iMaxId + 1
StartId := iMaxId + 1;
finally
// обязательно записываем в лог последнее сообщение
LogMsg(Format(cAttempt2, [iStartId, iMaxId, iSuccCount, iFailCount, Elapsed(crdStart)]), crdStart);
end;
finally
TSettings.ReplicaLastId := IntToStr(iLastId);// сохраняем в INI-файл значение Id последней успешной команды
// В конце сессии нужно сохранить значение LastId на Master и Slave.
// На Master сохраняем реже, после cSaveInMasterAfterNSessions сессий
if FCommandData.EOF then
SaveValueInDB(iLastId, 'Last_Id', FSessionNumber > cSaveInMasterAfterNSessions);
end;
end;
procedure TdmData.ExecuteErrCommands;
var
iStartId, iEndId: Int64;
iSuccCount, iFailCount: Integer;
crdStart, crdLogMsg: Cardinal;
sFileName: string;
const
cFileName = '\Err_commands\%s';
cFileErr = '%s Id %d ERR.txt';
begin
// FFailCmds содержит команды, которые не удалось выполнить в пакетной выгрузке и в выгрузке "по одной команде"
if FStopped then Exit;
crdStart := GetTickCount;
FFailCmds.Last;
iEndId := FFailCmds.Data.Id;
FFailCmds.First;
iStartId := FFailCmds.Data.Id;
iSuccCount := 0;
iFailCount := 0;
if FFailCmds.Count > 0 then
begin
// строка "№3 <56477135-56513779> ок = 25 записей за "
LogMsg(Format(cAttempt3, [iStartId, iEndId, iSuccCount, iFailCount, EmptyStr]), crdStart);
crdLogMsg := GetTickCount;
try
while not FFailCmds.EOF and not FStopped do
begin
try
if IsSlaveConnected then
with conSlave.DbcConnection do
begin
SetAutoCommit(False);
PrepareStatement(FFailCmds.Data.SQL).ExecutePrepared;
Commit;
Inc(iSuccCount);
end;
except
on E: Exception do
begin
conSlave.DbcConnection.Rollback;
LogErrMsg(Format(cExceptionMsg, [E.ClassName, E.Message]));
// ошибки шага №3 нужно сохранять в БД
SaveErrorInMaster(cStep3, FFailCmds.Data.Id, 0, FClient_Id, E.Message);
// команды, которые так и не были выполнены, пишем в лог
if FWriteCommands then
begin
sFileName := Format(cFileName, [
Format(cFileErr, [
FormatDateTime(cDateTimeFileNameStr, Now),
FFailCmds.Data.Id
])
]);
LogMsgFile(FFailCmds.Data.SQL, sFileName);
end;
Inc(iFailCount);
end;
end;
if (GetTickCount - crdLogMsg) > cWaitNextMsg then
begin
// строка "№3 <56477135-56513779> ок = 25 записей за 00:00:2_225"
LogMsg(Format(cAttempt3, [iStartId, iEndId, iSuccCount, iFailCount, Elapsed(crdStart)]), crdStart);
crdLogMsg := GetTickCount;
end;
FFailCmds.Next;
end;
finally
// обязательно записываем в лог последнее сообщение
LogMsg(Format(cAttempt3, [iStartId, iEndId, iSuccCount, iFailCount, Elapsed(crdStart)]), crdStart);
end;
end;
if iFailCount > 0 then // всегда останавливаем реплику, если остались невыполненные команды
begin
FStopped := True;
FReplicaFinished := rfErrStopped;
end;
FFailCmds.Clear;
Sleep(25);
end;
function TdmData.ExecutePreparedPacket: Integer;
var
bStopIfError: Boolean;
crdStart: Cardinal;
I, iRecCount: Integer;
iMaxId, iStartId, iLastId, iStartTrans, iEndTrans: Int64;
rangeTransId: TMinMaxTransId;
sFileName: string;
tmpData: TCmdData;
tmpSL: TStringList;
{$IFNDEF NO_EXECUTE}
tmpStmt: IZPreparedStatement;
{$ENDIF}
const
cFileName = '\Packets\%s';
cFileOK = '%s Id %d-%d %d.txt';
cFileErr = '%s Id %d-%d %d ERR.txt';
cTransId = '-- Id= %d tranId= %d' + #13#10;
begin
Result := 0;
if FStopped then Exit;
bStopIfError := TSettings.StopIfError;
iStartId := FStartId;
crdStart := GetTickCount;
iMaxId := FCommandData.GetMaxId(FStartId, FPacketRange);
// проверим диапазон Id нового пакета
if iStartId > iMaxId then
begin
LogErrMsg(Format(cWrongRange, [iMaxId, iStartId]));
FStopped := True;
FReplicaFinished := rfErrStopped;
Exit;
end;
rangeTransId := FCommandData.MinMaxTransId(iStartId, iMaxId);
iStartTrans := rangeTransId.Min;
iEndTrans := rangeTransId.Max;
iRecCount := FCommandData.RecordCount(FCommandData.ValidId(iStartId), iMaxId);
// строка "№1 Id=<56477135-56513779> tranId=<677135-63779> 3500 записей за "
LogMsg(Format(cAttempt1, [iStartId, iMaxId, iStartTrans, iEndTrans, iRecCount, '', '']), crdStart);
tmpSL := TStringList.Create(True);// True означает, что tmpSL владеет объектами tmpData и освободит их в своем деструкторе
try
with FCommandData do
begin
MoveToId(ValidId(iStartId));
while not EOF and (Data.Id <= iMaxId) and not FStopped do
begin
tmpData := TCmdData.Create;
tmpData.Id := Data.Id;
tmpData.TranId := Data.TransId;
tmpSL.AddObject(Data.SQL, tmpData);
Next;
end;
end;
try
Inc(FPacketNumber);
// пакетная выгрузка (сделано по образцу кода из Release Notes "2.1.3 Batch Loading")
if (tmpSL.Count > 0) and IsSlaveConnected and not FStopped then
begin
{$IFDEF NO_EXECUTE} // для проверки границ пакета, без выполнения запросов
Result := 1;
Sleep(1000);
{$ELSE}
conSlave.DbcConnection.SetAutoCommit(False);
tmpStmt := conSlave.DbcConnection.PrepareStatement(tmpSL.Text);
tmpStmt.ExecuteUpdatePrepared;
conSlave.DbcConnection.Commit;
{$ENDIF}
// пакет успешно выполнен и можем передвинуть StartId на новую позицию
// сначала перемещаемся на правую границу диапазона
FCommandData.MoveToId(iMaxId);
iLastId := FCommandData.Data.Id;
TSettings.ReplicaLastId := IntToStr(iLastId);// сохраняем в INI-файл значение Id последней успешной команды
// последовательность Id может иметь разрывы, например 48256, 48257, 48351, 48352
// поэтому вместо iMaxId + 1 используем Next
FCommandData.Next;
if FCommandData.EOF then // если достигли правой границы сессии, тогда используем iMaxId + 1
begin
StartId := iMaxId + 1;
// В конце сессии нужно сохранить значение LastId на Master и Slave.
// На Master сохраняем реже, после cSaveInMasterAfterNSessions сессий
SaveValueInDB(iLastId, 'Last_Id', FSessionNumber > cSaveInMasterAfterNSessions);
end
else
StartId := FCommandData.Data.Id;
// запись успешного пакета в файл
if FWriteCommands then
begin
sFileName := Format(cFileName, [
Format(cFileOK, [
FormatDateTime(cDateTimeFileNameStr, Now),
iStartId,
iMaxId,
FPacketNumber
])
]);
for I := 0 to Pred(tmpSL.Count) do
tmpSL[I] := Format(cTransId,
[TCmdData(tmpSL.Objects[I]).Id, TCmdData(tmpSL.Objects[I]).TranId]
) + tmpSL[I];
LogMsgFile(tmpSL.Text, sFileName);
end;
// строка "№1 Id=<56477135-56513779> tranId=<677135-63779> 3500 записей за 00:00:00_212"
LogMsg(Format(cAttempt1, [iStartId, iMaxId, iStartTrans, iEndTrans, iRecCount, Elapsed(crdStart), '']), crdStart);
end;
Result := 1;
except
on E: Exception do
begin
Result := 0;
if bStopIfError then
begin
FStopped := True;
FReplicaFinished := rfErrStopped;
end;
// строка "№1 Id=<56477135-56513779> tranId=<677135-63779> 3500 записей за 00:00:00_212 error"
LogMsg(Format(cAttempt1, [iStartId, iMaxId, iStartTrans, iEndTrans, iRecCount, Elapsed(crdStart), 'error']), crdStart);
LogErrMsg(Format(cExceptionMsg, [E.ClassName, E.Message]));
// запись сбойного пакета в файл
if FWriteCommands then
begin
sFileName := Format(cFileName, [
Format(cFileErr, [
FormatDateTime(cDateTimeFileNameStr, Now),
iStartId,
iMaxId,
FPacketNumber
])
]);
for I := 0 to Pred(tmpSL.Count) do
tmpSL[I] := Format(cTransId,
[TCmdData(tmpSL.Objects[I]).Id, TCmdData(tmpSL.Objects[I]).TranId]
) + tmpSL[I];
LogMsgFile(tmpSL.Text, sFileName);
end;
// если нужно сохранять ошибки шага №1 в БД
if TSettings.SaveErrStep1InDB then
SaveErrorInMaster(cStep1, iStartId, iMaxId, FClient_Id, E.Message);
try
conSlave.DbcConnection.Rollback; // если утрачена связь, тогда этот метод выбросит исключение
except
on EE: Exception do
begin
LogErrMsg(Format(cExceptionMsg, [EE.ClassName, EE.Message]));
conSlave.Disconnect;
end;
end;
end;
end;
finally
FreeAndNil(tmpSL);
end;
end;
function TdmData.ExecuteReplica: TReplicaFinished;
var
iPrevStartId: Int64;
begin
iPrevStartId := -1;
// Идентификатор базы данных Slave. Это значение хранится в единственном числе
// в slave._replica.Settings в полях name, value как пара 'client_id = 1234565855222447722'.
// В Master содержится инфа о всех slave-ах в master._replica.Clients.client_id
FClient_Id := GetSlaveValues.ClientId;
// MaxID - это ф-ия, которая возвращает 'select Max(Id) from _replica.table_update_data'
while (FStartId > iPrevStartId) and (FStartId <= MaxID) and not FStopped do
begin
// Успешное выполнение методов репликации должно увеличивать FStartId и в конце итерации это значение обычно должно быть больше предыдущего.
// Возможен сценарий, когда в пакете нет ни одной команды. В этом случае FStartId останется неизменным.
// Сохраним предыдущеее значение FStartId, чтобы потом сравнить его с текущим значением FStartId
// и избежать бесконечного цикла для случая, когда в пакете нет ни одной команды.
iPrevStartId := FStartId;
// В процессе работы программы ошибки обычно сохраняются в Master._replica.Errors. Если в какой то момент связь с Master
// была утрачена, тогда ошибки сохраняются Slave._replica.Errors. Нужно проверить их наличие в Slave и перенести в Master
if FMoveErrorsThrdFinished then
begin
FMoveErrorsThrd := TMoveErrorsThread.Create(cCreateSuspended, FMsgProc, tknNondriven);
FMoveErrorsThrd.OnTerminate := OnTerminateMoveErrors;
FMoveErrorsThrd.Start;
end;
// Формируем набор команд в дипазоне StartId..(StartId + SelectRange) - это сессия
// Реальная правая граница может быть > (StartId + SelectRange), потому что BuildReplicaCommandsSQL учитывает номера транзакций
// и обеспечивает условие, чтобы записи с одинаковыми номерами транзакций были в одном наборе
BuildReplicaCommandsSQL(FStartId, FSelectRange);
if (FStartId = 0) and (FLastId = 0) then Break;
// FStartId увеличивается в процессе выполнения команд
FPacketNumber := 0; // сбрасываем нумерацию пакетов перед началом сессии
// Передаем команды из дипазона StartId..(StartId + SelectRange) порциями
while (FStartId <= FLastId) and not FStopped do
begin
// проверяем, нужно ли записывать текст команд в файл
FWriteCommands := TSettings.WriteCommandsToFile;
// Сначала попробуем передать данные целым пакетом. Id записей пакета в диапазоне FStartId..(FStartId + FPacketRange)
if ExecutePreparedPacket = 0 then // если передача пакета завершилась неудачей
ExecuteCommandsOneByOne; // выполняем команды по одной. Id и SQL невыполненных команд сохраняем в FFailCmds
// Выполняем команды, которые не удалось выполнить на этапе "по одной команде"
if FFailCmds.Count > 0 then
ExecuteErrCommands;
end;
// сессия закончена, передаем инфу в GUI
if Assigned(FOnEndSession) then
FOnEndSession(nil);
end;
Result := FReplicaFinished;
end;
procedure TdmData.FetchSequences(AServer: TServerRank; out ASeqDataArr: TSequenceDataArray);
const
cSelectSequences = 'select * from gpSelect_Sequences()';
cSelectLastValue = 'select last_value from %s';
var
I: Integer;
bConnected: Boolean;
qryHelper: TZReadOnlyQuery;
sSelectLastValue: string;
begin
try
SetLength(ASeqDataArr, 0);
qryHelper := nil;
bConnected := False;
case AServer of
srMaster:
begin
bConnected := IsMasterConnected;
qryHelper := qryMasterHelper;
end;
srSlave:
begin
bConnected := IsSlaveConnected;
qryHelper := qrySlaveHelper;
end;
end;
if bConnected and Assigned(qryHelper) then
begin
// получим все последовательности
with qryHelper do
begin
Close;
SQL.Clear;
SQL.Add(cSelectSequences);
Open;
FetchAll;
First;
SetLength(ASeqDataArr, RecordCount);
if not IsEmpty then
begin
Assert(Lowercase(Fields[0].FieldName) = 'sequencename',
'Ожидается, что gpSelect_Sequences() вернет датасет, в котором первое поле "SequenceName"');
Assert(Lowercase(Fields[1].FieldName) = 'increment',
'Ожидается, что gpSelect_Sequences() вернет датасет, в котором второе поле "Increment"');
I := 0;
while not EOF and not FStopped do
begin
ASeqDataArr[I].Name := Fields[0].AsString;
ASeqDataArr[I].Increment := Fields[1].AsInteger;
Inc(I);
Next;
end;
end;
end;
// получим последние значения каждой последовательности
for I := Low(ASeqDataArr) to High(ASeqDataArr) do
begin
if FStopped then Exit;
sSelectLastValue := Format(cSelectLastValue, [ASeqDataArr[I].Name]);
with qryHelper do
begin
Close;
SQL.Clear;
SQL.Add(sSelectLastValue);
Open;
if not IsEmpty and not Fields[0].IsNull then
ASeqDataArr[I].LastValue := Fields[0].AsLargeInt;
end;
end;
end;
except
on E: Exception do
LogErrMsg(Format(cExceptionMsg, [E.ClassName, E.Message]));
end;
end;
function TdmData.GetReplicaCmdCount: Integer;
const
cSQL = 'select Count(*) from (%s) as Commands';
begin
Result := 0;
try
// берем предварительно сформированный SQL из qrySelectReplicaCmd
if IsMasterConnected and (Length(qrySelectReplicaCmd.SQL.Text) > 0) then
with qryMasterHelper do
begin
Close;
SQL.Text := Format(cSQL, [qrySelectReplicaCmd.SQL.Text]);
Open;
if not Fields[0].IsNull then
Result := Fields[0].AsInteger;
Close;
end;
except
on E: Exception do
LogErrMsg(Format(cExceptionMsg, [E.ClassName, E.Message]));
end;
end;
function TdmData.GetSlaveValues: TSlaveValues;
const
cSelectSettings = 'select * from _replica.gpSelect_Settings()';
begin
try
if IsSlaveConnected then
with qrySlaveHelper do
begin
Close;
SQL.Clear;
SQL.Add(cSelectSettings);
Open;
if Locate('Name', 'Last_Id', [loCaseInsensitive]) then
if not FieldByName('Value').IsNull then
Result.LastId := StrToInt64Def(FieldByName('Value').AsString, 0);
if Locate('Name', 'Last_Id_DDL', [loCaseInsensitive]) then
if not FieldByName('Value').IsNull then
Result.LastId_DDL := StrToInt64Def(FieldByName('Value').AsString, 0);
if Locate('Name', 'Client_Id', [loCaseInsensitive]) then
if not FieldByName('Value').IsNull then
Result.ClientId := StrToInt64Def(FieldByName('Value').AsString, 0);
Close;
end;
except
on E: Exception do
LogErrMsg(Format(cExceptionMsg, [E.ClassName, E.Message]));
end;
end;
function TdmData.GetLastId: Int64;
var
slvValues: TSlaveValues;
iMasterId, iSlaveId: Int64;
begin
slvValues := GetSlaveValues;
iSlaveId := slvValues.LastId;
iMasterId := GetMasterValues(slvValues.ClientId).LastId;
Result := Max(iSlaveId, iMasterId);
end;
function TdmData.GetLastId_DDL: Int64;
var
slvValues: TSlaveValues;
iMasterId, iSlaveId: Int64;
begin
slvValues := GetSlaveValues;
iSlaveId := slvValues.LastId_DDL;
iMasterId := GetMasterValues(slvValues.ClientId).LastId_DDL;
Result := Max(iSlaveId, iMasterId);
end;
function TdmData.InitConnection(AConnection: TZConnection;
ARank: TServerRank): boolean;
begin
if not Assigned(AConnection) then
raise Exception.Create('Connection is not created');
Result := IsConnected(AConnection, ARank);
end;
function TdmData.IsBothConnected: Boolean;
begin
Result := IsMasterConnected and IsSlaveConnected;
end;
function TdmData.IsBothConnectionsAlive: Boolean;
var
bMasterAlive, bSlaveAlive: Boolean;
begin
bMasterAlive := IsConnectionAlive(conMaster);
bSlaveAlive := IsConnectionAlive(conSlave);
Result := bMasterAlive and bSlaveAlive;
// Нужно именно так проверять, по очереди, а не в одну строку 'Result := IsConnectionAlive(conMaster) and IsConnectionAlive(conSlave)'
// Если выражение в одну строку, тогда если IsConnectionAlive(conMaster) = False компилятор не станет вызывать IsConnectionAlive(conSlave),
// и не будет вызван conSlave.Disconnect (см. код IsConnectionAlive)
end;
function TdmData.IsConnected(AConnection: TZConnection; ARank: TServerRank): Boolean;
var
iAttempt: Integer;
const
cWaitReconnect = c1Sec;
cAttemptCount = 3;
begin
Result := AConnection.Connected;
if Result then Exit;
iAttempt := 0;
repeat
try
Inc(iAttempt);
ApplyConnectionConfig(AConnection, ARank);
AConnection.Connect;
Result := AConnection.Connected;
except
on E: Exception do
begin
Result := False;
if iAttempt >= cAttemptCount then
LogErrMsg(Format(cExceptionMsg, [E.ClassName, E.Message]))
else
Sleep(cWaitReconnect);
end;
end;
until Result or (iAttempt >= cAttemptCount);
end;
function TdmData.IsConnectionAlive(AConnection: TZConnection): Boolean;
begin
Result := AConnection.Ping;
if not Result and AConnection.Connected then
AConnection.Disconnect;
end;
function TdmData.IsMasterConnected: Boolean;
begin
Result := IsConnected(conMaster, srMaster);
end;
function TdmData.IsSlaveConnected: Boolean;
begin
Result := IsConnected(conSlave, srSlave);
end;
procedure TdmData.LogErrMsg(const AMsg: string);
begin
if Assigned(FMsgProc) then FMsgProc(AMsg, EmptyStr, 0, lmtError);
end;
procedure TdmData.LogMsg(const AMsg: string; const aUID: Cardinal);
begin
if Assigned(FMsgProc) then FMsgProc(AMsg, EmptyStr, aUID);
end;
procedure TdmData.LogMsg(const AMsg: string);
begin
if Assigned(FMsgProc) then FMsgProc(AMsg);
end;
procedure TdmData.LogMsgFile(const AMsg, AFileName: string);
begin
if Assigned(FMsgProc) then FMsgProc(AMsg, AFileName);
end;
function TdmData.GetCompareRecCountMS_SQL(const ADeviationsOnly: Boolean): string;
type
TTableData = record
Name: string;
PK_Id: Boolean; // таблица имеет Primary Key field = Id
PK_field: string;
MaxIdSlave: Int64;
MasterCount: Int64;
SlaveCount: Int64;
CountSQLSlave: string;
CountSQLMaster: string;
end;
const
cSelectPKFields = 'SELECT * FROM _replica.gpSelect_PKFields(%s)';
// cSelectPKFields = 'SELECT pk_keys FROM _replica.table_update_data WHERE table_name ILIKE %s limit 1';
cSelectTableNames = 'SELECT * FROM _replica.gpSelect_Replica_tables()';
cSelectUnion = 'SELECT ''%s'' as TableName, ''%s'' AS CountMaster, ''%s'' AS CountSlave, ''%s'' AS CountDiff';
cSelectCount = 'SELECT COUNT(*) FROM %s AS RecCount';
cSelectCountSlaveNoId = 'SELECT Max(%s) as MaxIdSlave, COUNT(*) AS RecCount FROM %s';
cSelectCountSlave = 'SELECT Max(Id) as MaxIdSlave, COUNT(*) AS RecCount FROM %s';
cSelectCountIdSlave = 'SELECT Max(Id) as MaxIdSlave, COUNT(Id) AS RecCount FROM %s';
cSelectCountMasterNoId = 'SELECT COUNT(*) AS RecCount FROM %s WHERE %s <= %d';
cSelectCountMaster = 'SELECT COUNT(*) AS RecCount FROM %s WHERE Id <= %d';
cSelectCountIdMaster = 'SELECT COUNT(Id) AS RecCount FROM %s WHERE Id <= %d';
cSelectCountIdMaster_two = 'SELECT COUNT(Id) AS RecCount FROM %s';
cUnion = ' UNION ALL ';
var
I, J: Integer;
arrTables: array of TTableData;
sTableName, sSQL: string;
begin
Result := Format(cSelectUnion, ['<нет данных>', '0', '0', '0']) + ';';
try
// строим массив имен таблиц
if IsSlaveConnected then
with qrySlaveHelper do
begin
Close;
SQL.Clear;
SQL.Add(cSelectTableNames);
Open;
FetchAll;
if IsEmpty then Exit;
First;
while not EOF and not FStopped do
begin
if not FieldByName('Master_table').IsNull then
begin
sTableName := FieldByName('Master_table').AsString;
if Length(Trim(sTableName)) > 0 then
begin
SetLength(arrTables, Length(arrTables) + 1);
arrTables[High(arrTables)].Name := sTableName;
end;
end;
Next;
end;
end;
if FStopped then Exit;
// Вычисляем Count(*) для таблиц из массива arrTables.
// Для 'MovementItemContainer' отдельный случай: select Count(Id).
{ В master все время идет запись, поэтому сверить практически нереально
Надо сделать сначала на slave
select count(*), max(Id) from table...
потом на master
select count(*) from table... where Id <= :max_Id_slave }
// выполняем запрос для каждой таблицы
for I := Low(arrTables) to High(arrTables) do
begin
if FStopped then Exit;
// Не у всех таблиц PrimaryKey состоит из одного поля Id. Определим имена полей, которые составляют PrimaryKey.
// ВСЕ составные индексы - 2 поля и обязательно присутствует descid, надо его отбросить.
// Если вдруг будет составной из 3-х или более полей, или вообще не будет, тогда и для Master делаем select Count(*) from ......
if IsMasterConnected then
with qryMasterHelper do
begin
Close;
SQL.Clear;
sSQL := Format(cSelectPKFields, [QuotedStr(arrTables[I].Name)]);
SQL.Add(sSQL);
Open;
FetchAll;
First;
arrTables[I].PK_Id := not Fields[0].IsNull and (RecordCount = 1) and SameText(Fields[0].AsString, 'Id');
arrTables[I].PK_field := '';
case RecordCount of
0, 3: // нет PrimaryKey
arrTables[I].PK_field := '';
1: // одно поле в PrimaryKey
if not Fields[0].IsNull then
arrTables[I].PK_field := Fields[0].AsString;
2: // 2 поля в PrimaryKey
while not EOF do
begin
if not Fields[0].IsNull then
if not SameText(Fields[0].AsString, 'descid') then // поле 'descid' отбрасываем
arrTables[I].PK_field := Fields[0].AsString;
Next;
end;
end;
end;
// для таблиц сервера Slave
if AnsiUpperCase(arrTables[I].Name) = AnsiUpperCase('MovementItemContainer') then
arrTables[I].CountSQLSlave := Format(cSelectCountIdSlave, [arrTables[I].Name])
else
if arrTables[I].PK_Id then
arrTables[I].CountSQLSlave := Format(cSelectCountSlave, [arrTables[I].Name])
else
if Length(arrTables[I].PK_field) > 0 then
arrTables[I].CountSQLSlave := Format(cSelectCountSlaveNoId, [arrTables[I].PK_field, arrTables[I].Name])
else
arrTables[I].CountSQLSlave := Format(cSelectCount, [arrTables[I].Name]);
if IsSlaveConnected then
with qrySlaveHelper do
begin
Close;
SQL.Clear;
SQL.Add(arrTables[I].CountSQLSlave);
Assert(Length(Trim(SQL.Text)) > 0, 'Ожидается, что CountSQLSlave <> "" для таблицы ' + arrTables[I].Name);
Open;
if Length(arrTables[I].PK_field) > 0 then
begin
if not Fields[0].IsNull then
arrTables[I].MaxIdSlave := Fields[0].AsLargeInt;
if not Fields[1].IsNull then
arrTables[I].SlaveCount := Fields[1].AsLargeInt;
end
else
if not Fields[0].IsNull then
arrTables[I].SlaveCount := Fields[0].AsLargeInt;
Close;
end;
if FStopped then Exit;
// для таблиц сервера Master
if (AnsiUpperCase(arrTables[I].Name) = AnsiUpperCase('MovementItemContainer')) and (arrTables[I].MaxIdSlave > 0) then
arrTables[I].CountSQLMaster := Format(cSelectCountIdMaster, [arrTables[I].Name, arrTables[I].MaxIdSlave])
else
// еще раз, если пусто в Slave
if (AnsiUpperCase(arrTables[I].Name) = AnsiUpperCase('MovementItemContainer')) then
arrTables[I].CountSQLMaster := Format(cSelectCountIdMaster_two, [arrTables[I].Name])
else
if (arrTables[I].PK_Id) and (arrTables[I].MaxIdSlave > 0) then
arrTables[I].CountSQLMaster := Format(cSelectCountMaster, [arrTables[I].Name, arrTables[I].MaxIdSlave])
else
if (Length(arrTables[I].PK_field) > 0) and (arrTables[I].MaxIdSlave > 0) then
arrTables[I].CountSQLMaster := Format(cSelectCountMasterNoId, [arrTables[I].Name, arrTables[I].PK_field, arrTables[I].MaxIdSlave])
else
arrTables[I].CountSQLMaster := Format(cSelectCount, [arrTables[I].Name]);
if IsMasterConnected then
with qryMasterHelper do
begin
Close;
SQL.Clear;
SQL.Add(arrTables[I].CountSQLMaster);
Assert(Length(Trim(SQL.Text)) > 0, 'Ожидается, что CountSQLMaster <> "" для таблицы ' + arrTables[I].Name);
Open;
if not Fields[0].IsNull then
arrTables[I].MasterCount := Fields[0].AsLargeInt;
Close;
end;
if Assigned(FOnCompareRecCountMS) then
begin
// формируем промежуточный текст запроса SELECT UNION, используя имеющиеся на данный момент данные массива arrTables
sSQL := '';
for J := Low(arrTables) to I do
begin
if FStopped then Exit;
if ADeviationsOnly then
if arrTables[J].MasterCount = arrTables[J].SlaveCount then Continue;
if Length(sSQL) = 0 then
sSQL := Format(cSelectUnion, [arrTables[J].Name, FormatFloat(',0.', arrTables[J].MasterCount), FormatFloat(',0.', arrTables[J].SlaveCount), FormatFloat(',0.', arrTables[J].MasterCount - arrTables[J].SlaveCount)])
else
sSQL := sSQL + cUnion + Format(cSelectUnion, [arrTables[J].Name, FormatFloat(',0.', arrTables[J].MasterCount), FormatFloat(',0.', arrTables[J].SlaveCount), FormatFloat(',0.', arrTables[J].MasterCount - arrTables[J].SlaveCount)]);
end;
if Length(sSQL) > 0 then
begin
Result := sSQL + ';';
FOnCompareRecCountMS(Result);
end;
end;
end;
// формируем итоговый текст запроса SELECT UNION, используя данные массива arrTables
sSQL := '';
for I := Low(arrTables) to High(arrTables) do
begin
// if FStopped then Exit;
if ADeviationsOnly then
if arrTables[I].MasterCount = arrTables[I].SlaveCount then Continue;
if Length(sSQL) = 0 then
sSQL := Format(cSelectUnion, [arrTables[I].Name, FormatFloat(',0.', arrTables[I].MasterCount), FormatFloat(',0.', arrTables[I].SlaveCount), FormatFloat(',0.', arrTables[I].MasterCount - arrTables[I].SlaveCount)])
else
sSQL := sSQL + cUnion + Format(cSelectUnion, [arrTables[I].Name, FormatFloat(',0.', arrTables[I].MasterCount), FormatFloat(',0.', arrTables[I].SlaveCount), FormatFloat(',0.', arrTables[I].MasterCount - arrTables[I].SlaveCount)]);
end;
if Length(sSQL) > 0 then
Result := sSQL + ';';
except
on E: Exception do
LogErrMsg(Format(cExceptionMsg, [E.ClassName, E.Message]));
end;
end;
function TdmData.GetCompareSeqMS_SQL(const ADeviationsOnly: Boolean): string;
type
TUnionData = record
Name: string;
MasterValue: Int64;
SlaveValue: Int64;
MasterIncrement: Integer;
SlaveIncrement: Integer;
end;
const
cSelectUnion = 'select ''%s'' as SequenceName, ''%s'' as MasterValue, ''%s'' as SlaveValue, ''%s'' as DiffValue, %d as MasterIncrement, %d as SlaveIncrement';
var
I, J: Integer;
arrMasterSeq, arrSlaveSeq: TSequenceDataArray;
arrUnion: array of TUnionData;
sSelect: string;
begin
Result := Format(cSelectUnion, ['<нет данных>', '0', '0', '0', 0, 0]);
try
// Получим список последовательностей Master
FetchSequences(srMaster, arrMasterSeq);
if Length(arrMasterSeq) = 0 then Exit;
if FStopped then Exit;
// Получим список последовательностей Slave
FetchSequences(srSlave, arrSlaveSeq);
if FStopped then Exit;
SetLength(arrUnion, Length(arrMasterSeq));
for I := Low(arrUnion) to High(arrUnion) do
begin
if FStopped then Exit;
arrUnion[I].Name := arrMasterSeq[I].Name;
arrUnion[I].MasterValue := arrMasterSeq[I].LastValue;
arrUnion[I].MasterIncrement := arrMasterSeq[I].Increment;
end;
// Репликация может быть еще не закончена и в Slave меньше последовательностей, чем в Master
for I := Low(arrUnion) to High(arrUnion) do
begin
if FStopped then Exit;
for J := Low(arrSlaveSeq) to High(arrSlaveSeq) do
if SameText(arrSlaveSeq[J].Name, arrUnion[I].Name) then
begin
if FStopped then Exit;
arrUnion[I].SlaveValue := arrSlaveSeq[J].LastValue;
arrUnion[I].SlaveIncrement := arrSlaveSeq[J].Increment;
Break;
end;
end;
// Теперь готов сформировать UNION
if Length(arrUnion) > 0 then Result := '';
for I := Low(arrUnion) to High(arrUnion) do
begin
if FStopped then Exit;
// если нужно показать только отличия, тогда пропускаем равные значения
if ADeviationsOnly then
if (arrUnion[I].MasterValue = arrUnion[I].SlaveValue) and
(arrUnion[I].MasterIncrement = arrUnion[I].SlaveIncrement)
then Continue;
sSelect := Format(cSelectUnion, [
arrUnion[I].Name, FormatFloat(',0.', arrUnion[I].MasterValue), FormatFloat(',0.', arrUnion[I].SlaveValue), FormatFloat(',0.', arrUnion[I].MasterValue - arrUnion[I].SlaveValue), arrUnion[I].MasterIncrement, arrUnion[I].SlaveIncrement
]);
if Length(Result) = 0 then
Result := sSelect
else
Result := Result + ' union ' + sSelect;
end;
if Length(Result) > 0 then
Result := Result + ' order by 1';
except
on E: Exception do
LogErrMsg(Format(cExceptionMsg, [E.ClassName, E.Message]));
end;
end;
function TdmData.GetMasterValues(const AClientId: Int64): TMasterValues;
const
cSelectClients = 'select * from _replica.gpSelect_Clients(%d)';
begin
try
if IsMasterConnected then
with qryMasterHelper do
begin
Close;
SQL.Clear;
SQL.Add(Format(cSelectClients, [AClientId]));
Open;
if not IsEmpty then
begin
if not FieldByName('last_id').IsNull then
Result.LastId := StrToInt64Def(FieldByName('last_id').AsString, 0);
if not FieldByName('last_id_ddl').IsNull then
Result.LastId_DDL := StrToInt64Def(FieldByName('last_id_ddl').AsString, 0);
end;
Close;
end;
except
on E: Exception do
LogErrMsg(Format(cExceptionMsg, [E.ClassName, E.Message]));
end;
end;
function TdmData.GetMinMaxId: TMinMaxId;
const
cSelect = 'SELECT * FROM _replica.gpSelect_MinMaxId()';
begin
Result.MinId := -1;
Result.MaxId := -1;
Result.RecCount := 0;
Result.MinDT := 0;
Result.MaxDT := 0;
try
if IsMasterConnected then
with qryMasterHelper do
begin
Close;
SQL.Clear;
SQL.Add(cSelect);
Open;
if not FieldByName('MinId').IsNull then begin
Result.MinId := FieldByName('MinId').AsLargeInt;
Result.MinDT := FieldByName('MinDT').AsDateTime;
end;
if not FieldByName('MaxId').IsNull then begin
Result.MaxId := FieldByName('MaxId').AsLargeInt;
Result.MaxDT := FieldByName('MaxDT').AsDateTime;
end;
if not FieldByName('RecCount').IsNull then
Result.RecCount := FieldByName('RecCount').AsLargeInt;
Close;
end;
except
on E: Exception do
LogErrMsg(Format(cExceptionMsg, [E.ClassName, E.Message]));
end;
end;
function TdmData.MaxID: Int64;
const
cSelect = 'select * from _replica.gpSelect_MaxId()';
begin
Result := -1;
try
if IsMasterConnected then
with qryMasterHelper do
begin
Close;
SQL.Clear;
SQL.Add(cSelect);
Open;
if not Fields[0].IsNull then
begin
Result := Fields[0].AsLargeInt;
MaxDT := Fields[1].AsDateTime;
end;
Close;
end;
except
on E: Exception do
LogErrMsg(Format(cExceptionMsg, [E.ClassName, E.Message]));
end;
end;
function TdmData.MinID: Int64;
const
cSelect = 'select * from _replica.gpSelect_MinId()';
begin
Result := -1;
try
if IsMasterConnected then
with qryMasterHelper do
begin
Close;
SQL.Clear;
SQL.Add(cSelect);
Open;
if not Fields[0].IsNull then
begin
Result := Fields[0].AsLargeInt;
MinDT:= Fields[1].AsDateTime;
end;
Close;
end;
except
on E: Exception do
LogErrMsg(Format(cExceptionMsg, [E.ClassName, E.Message]));
end;
end;
procedure TdmData.MoveErrorsFromSlaveToMaster;
const
cSelectSlave = 'select * from _replica.gpSelect_Errors()';
cDeleteSlave = 'select _replica.gpDelete_Errors()';
cInsertMaster = 'select _replica.gpInsert_Errors (%d, %d, %d, %d, %s);';
cFailMoveErrors = 'Не удалось перенести ошибки из Slave в Master';
cFailDeleteErrors = 'Ошибки перенесены в Master, но не удалось удалить их в Slave';
var
bMoveSuccess: Boolean;
slCmds: TStringList;
tmpStmt: IZPreparedStatement;
begin
bMoveSuccess := False;
// Обычно ошибки сохраняются сразу в Master.Errors. Если во время выполнения программы связь с Master была утрачена,
// тогда ошибки сохраняются в Slave.Errors. Нужно перенести эти ошибки в Master и потом удалить их в Slave
try
slCmds := TStringList.Create;
try
if IsSlaveConnected then
with qrySlaveHelper do
begin
Close;
SQL.Clear;
SQL.Add(cSelectSlave);
Open;
if not IsEmpty then // если в Slave есть сохраненные ошибки, тогда сформируем список команд
begin
First;
while not Eof do
begin
slCmds.Add(Format(cInsertMaster, [
FieldByName('Step').AsInteger,
FieldByName('Start_Id').AsLargeInt,
FieldByName('Last_Id').AsLargeInt,
FieldByName('Client_Id').AsLargeInt,
QuotedStr(FieldByName('Description').AsString)
]));
Next;
end;
end;
end;
// теперь можем перенести ошибки в Master
if (slCmds.Count > 0) and IsMasterConnected then
begin
try
conMaster.DbcConnection.SetAutoCommit(False);
tmpStmt := conMaster.DbcConnection.PrepareStatement(slCmds.Text);
tmpStmt.ExecuteUpdatePrepared;
conMaster.DbcConnection.Commit;
bMoveSuccess := True;
except
on E: Exception do
begin
LogErrMsg(cFailMoveErrors);
LogErrMsg(Format(cExceptionMsg, [E.ClassName, E.Message]));
conMaster.DbcConnection.Rollback;
end;
end;
end;
// если ошибки успешно перенесены, тогда можем удалить их в Slave
if bMoveSuccess and IsSlaveConnected then
try
conSlave.DbcConnection.SetAutoCommit(False);
tmpStmt := conSlave.DbcConnection.PrepareStatement(cDeleteSlave);
tmpStmt.ExecuteUpdatePrepared;
conSlave.DbcConnection.Commit;
except
on E: Exception do
begin
LogErrMsg(cFailDeleteErrors);
LogErrMsg(Format(cExceptionMsg, [E.ClassName, E.Message]));
conSlave.DbcConnection.Rollback;
end;
end;
finally
FreeAndNil(slCmds);
end;
except
on E: Exception do
LogErrMsg(Format(cExceptionMsg, [E.ClassName, E.Message]));
end;
end;
procedure TdmData.MoveSavedProcToSlave;
const
cSelect = 'select * from _replica.gpSelect_Table_ddl(:Id)';
cSession = '\DDL_Commands\%s\'; // \DDL_Commands\2020-08-11_14-49-00
cFileName = cSession + 'Id_%d.txt'; // \DDL_Commands\2020-08-11_14-49-00\Id_2095014.txt
cFileNameErr = cSession + 'Id_%d_ERR.txt'; // \DDL_Commands\2020-08-11_14-49-00\id_2095014_Error.txt
cFileContent = c2CrLf + 'Last_modified: %s' + c2CrLf + '%s';
var
I, idxId, idxQry, idxLM: Integer;
iId, iLastId: Int64;
sQry, sSessionStart, sFileName, sFileContent: string;
dtmLM: TDateTime;
tmpStmt: IZPreparedStatement;
begin
idxId := -1;
idxQry := -1;
idxLM := -1;
iLastId := LastId_DDL; // Id, на котором в прошлый раз завершилось выполнение
sSessionStart := FormatDateTime(cDateTimeFileNameStr, Now);
try
try
if IsMasterConnected then
with qryMasterHelper do
begin
Close;
SQL.Clear;
SQL.Add(Format(cSelect, [iLastId]));
ParamByName('Id').AsLargeInt := iLastId;
Open;
First;
// определим индексы полей в датасете, чтобы использовать в цикле 'while not EOF do'
for I := 0 to Pred(Fields.Count) do
if LowerCase(Fields[I].FieldName) = 'id' then idxId := I
else if LowerCase(Fields[I].FieldName) = 'query' then idxQry := I
else if LowerCase(Fields[I].FieldName) = 'last_modified' then idxLM := I;
if Locate('Id', iLastId, []) then // Найдем позицию, на которой закончили в прошлый раз
Next; // и передвинем на следующую для нового выполнения
while not EOF do
begin
iId := Fields[idxId].AsLargeInt;
sQry := Fields[idxQry].AsString;
dtmLM := Fields[idxLM].AsDateTime;
sFileContent := Format(cFileContent, [FormatDateTime(cDateTimeStrShort, dtmLM), sQry]);
try
if IsSlaveConnected and not FStopped then
begin
conSlave.DbcConnection.SetAutoCommit(False);
tmpStmt := conSlave.DbcConnection.PrepareStatement(sQry);
tmpStmt.ExecuteUpdatePrepared;
conSlave.DbcConnection.Commit;
iLastId := iId;
sFileName := Format(cFileName, [sSessionStart, iId]);
LogMsgFile(sFileContent, sFileName);
end;
except
on E: Exception do
begin
conSlave.DbcConnection.Rollback;
sFileName := Format(cFileNameErr, [sSessionStart, iId]);
LogMsgFile(sFileContent, sFileName);
LogErrMsg(Format(cExceptionMsg, [E.ClassName, E.Message]));
// Прекращаем выполнение из-за ошибки
Break;
end;
end;
Next;
end;
Close;
end;
except
on E: Exception do
LogErrMsg(Format(cExceptionMsg, [E.ClassName, E.Message]));
end;
finally
if iLastId <= High(Integer) then
TSettings.DDLLastId := iLastId
else
TSettings.DDLLastId := -1;
LastId_DDL := iLastId;
end;
end;
procedure TdmData.OnTerminateMoveErrors(Sender: TObject);
begin
FMoveErrorsThrdFinished := True;
end;
procedure TdmData.SetLastId_DDL(const AValue: Int64);
begin
SaveValueInDB(AValue, 'Last_Id_DDL');
end;
procedure TdmData.SetLastId(const AValue: Int64);
begin
SaveValueInDB(AValue, 'Last_Id');
end;
function TdmData.SaveErrorInDB(AServerRank: TServerRank; const AStep: Integer; const AStartId, ALastId, AClientId: Int64;
const AErrDescription: string): Boolean;
const
cInsert = 'SELECT _replica.gpInsert_Errors (%d, %d, %d, %d, %s)';
cExceptMsg = 'Не удалось сохранить в %s информацию об ошибке команды с StartId = %d, Client_Id = %d';
var
bConnected: Boolean;
sInsert, sSrvrLable: string;
tmpConn: TZConnection;
tmpStmt: IZPreparedStatement;
begin
Result := False;
bConnected := False;
tmpConn := nil;
case AServerRank of
srMaster:
begin
bConnected := IsMasterConnected;
sSrvrLable := 'Master';
tmpConn := conMaster;
end;
srSlave:
begin
bConnected := IsSlaveConnected;
sSrvrLable := 'Slave';
tmpConn := conSlave;
end;
end;
if bConnected and (tmpConn <> nil) then
try
with tmpConn.DbcConnection do
begin
SetAutoCommit(False);
sInsert := Format(cInsert, [AStep, AStartId, ALastId, AClientId, QuotedStr(AErrDescription)]);
tmpStmt := PrepareStatement(sInsert);
tmpStmt.ExecuteUpdatePrepared;
Commit;
Result := True;
end;
except
on E: Exception do
begin
LogErrMsg(Format(cExceptMsg, [sSrvrLable, AStartId, AClientId]));
LogErrMsg(Format(cExceptionMsg, [E.ClassName, E.Message]));
try
tmpConn.DbcConnection.Rollback; // если утрачена связь, тогда этот метод выбросит исключение
except
on EE: Exception do
begin
LogErrMsg(Format(cExceptionMsg, [EE.ClassName, EE.Message]));
tmpConn.Disconnect;
end;
end;
end;
end;
end;
procedure TdmData.SaveErrorInMaster(const AStep: Integer; const AStartId, ALastId, AClientId: Int64; const AErrDescription: string);
begin
// сначала попытаемся сохранить ошибку в Master, а в случае неудачи - в Slave
if not SaveErrorInDB(srMaster, AStep, AStartId, ALastId, AClientId, AErrDescription) then
SaveErrorInDB(srSlave, AStep, AStartId, ALastId, AClientId, AErrDescription);
end;
procedure TdmData.SaveValueInDB(const AValue: Int64; const AFieldName: string; const ASaveInMaster: Boolean);
const
cSelectSettings = 'select * from _replica.gpSelect_Settings()';
cUpdateMaster = 'select * from _replica.gpUpdate_Clients_LastId(%d, %d)';
cUpdateMasterDDL = 'select * from _replica.gpUpdate_Clients_LastId_Ddl(%d, %d)';
cInsUpdateSettings = 'select * from _replica.gpInsertUpdate_Settings(0, %s, %s)';
cFailSave = 'Не удалось сохранить значение %s на %s';
var
iClientId: Int64;
tmpStmt: IZPreparedStatement;
sServerRank, sFieldName, sUpdate, sInsUpdate: string;
begin
{$IFDEF NO_EXECUTE} // для проверки границ пакета, без выполнения запросов
Exit;
{$ENDIF}
iClientId := 0;
sFieldName := LowerCase(AFieldName);
Assert((sFieldName = 'last_id') or (sFieldName = 'last_id_ddl'), 'Ф-ия SaveValueInDB предназначена для полей Last_Id и Last_Id_DDL');
if sFieldName = 'last_id' then
sUpdate := cUpdateMaster;
if sFieldName = 'last_id_ddl' then
sUpdate := cUpdateMasterDDL;
try
if IsSlaveConnected then
begin // Блок ниже с qrySlaveHelper работает в ExecutePreparedPacket,
// но не работает в ExecuteCommandsOneByOne - ошибок нет, iClientId возвращает, но значение не сохраняется в таб. Settings
// Причина не установлена. Пришлось использовать отдельно GetSlaveValues.ClientId;
// with qrySlaveHelper do
// begin
// sServerRank := 'Slave';
// Close;
// SQL.Clear;
// SQL.Add(Format(cInsUpdateSettings, [QuotedStr(sFieldName), QuotedStr(IntToStr(AValue))]));
// Open;
// iClientId := Fields[0].AsLargeInt;
// Close;
// end;
try
sServerRank := 'Slave';
conSlave.DbcConnection.SetAutoCommit(False);
sInsUpdate := Format(cInsUpdateSettings, [QuotedStr(sFieldName), QuotedStr(IntToStr(AValue))]);
tmpStmt := conSlave.DbcConnection.PrepareStatement(sInsUpdate);
tmpStmt.ExecuteUpdatePrepared;
conSlave.DbcConnection.Commit;
iClientId := GetSlaveValues.ClientId;
except
on E: Exception do
begin
conSlave.DbcConnection.Rollback;
LogErrMsg(Format(cExceptionMsg, [E.ClassName, E.Message]));
LogErrMsg(Format(cFailSave, [sFieldName, sServerRank]));
end;
end;
end;
// Сохранение в Master требуется реже, чем в Slave, поэтому сохранением в Master управляет параметр ASaveInMaster
// Сохраняем значение AValue в Master._replica.Clients
if ASaveInMaster and (iClientId > 0) and IsMasterConnected then
begin
try
sServerRank := 'Master';
conMaster.DbcConnection.SetAutoCommit(False);
tmpStmt := conMaster.DbcConnection.PrepareStatement(Format(sUpdate, [iClientId, AValue]));
tmpStmt.ExecuteUpdatePrepared;
conMaster.DbcConnection.Commit;
except
on E: Exception do
begin
conMaster.DbcConnection.Rollback;
LogErrMsg(Format(cExceptionMsg, [E.ClassName, E.Message]));
LogErrMsg(Format(cFailSave, [sFieldName, sServerRank]));
end;
end;
end;
except
on E: Exception do
begin
LogErrMsg(Format(cExceptionMsg, [E.ClassName, E.Message]));
LogErrMsg(Format(cFailSave, [sFieldName, sServerRank]));
end;
end;
end;
procedure TdmData.SetStartId(const AValue: Int64);
begin
if FStartId <> AValue then
begin
FStartId := AValue;
if Assigned(FOnChangeStartId) then
FOnChangeStartId(FStartId,FStartDT);
end;
end;
procedure TdmData.StopReplica;
begin
FStopped := True;
FReplicaFinished := rfStopped;
end;
{ TWorkerThread }
constructor TWorkerThread.Create(CreateSuspended: Boolean; const AStartId: Int64;
const ASelectRange, APacketRange: Integer; AMsgProc: TNotifyMessage; AKind: TThreadKind);
begin
FStartId := AStartId;
FMsgProc := AMsgProc;
FSelectRange := ASelectRange;
FPacketRange := APacketRange;
FData := TdmData.Create(nil, FStartId, FSelectRange, FPacketRange, InnerMsgProc);
FData.OnChangeStartId := InnerChangeStartId;
FData.OnNewSession := InnerNewSession;
FData.OnEndSession := InnerEndSession;
FData.OnNeedRestart := InnerNeedRestart;
FreeOnTerminate := (AKind = tknNondriven);
inherited Create(CreateSuspended);
end;
constructor TWorkerThread.Create(CreateSuspended: Boolean; AMsgProc: TNotifyMessage; AKind: TThreadKind);
begin
Create(CreateSuspended, 0, 0, 0, AMsgProc, AKind);
end;
destructor TWorkerThread.Destroy;
begin
FreeAndNil(FData);
inherited;
end;
//function TWorkerThread.GetReturnValue: Int64;
//begin
// Result := ReturnValue;
//end;
procedure TWorkerThread.InnerChangeStartId(const ANewStartId: Int64; const ANewStartDT : TDateTime );
begin
TThread.Queue(nil, procedure
begin
if Assigned(FOnChangeStartId) then FOnChangeStartId(ANewStartId, ANewStartDT);
end);
end;
procedure TWorkerThread.InnerEndSession(Sender: TObject);
begin
TThread.Queue(nil, procedure
begin
if Assigned(FOnEndSession) then FOnEndSession(nil);
end);
end;
procedure TWorkerThread.InnerMsgProc(const AMsg, AFileName: string; const aUID: Cardinal; AMsgType: TLogMessageType);
begin
TThread.Queue(nil, procedure
begin
if Assigned(FMsgProc) then FMsgProc(AMsg, AFileName, aUID, AMsgType);
end);
end;
procedure TWorkerThread.InnerNeedRestart(Sender: TObject);
begin
TThread.Queue(nil, procedure
begin
if Assigned(FOnNeedRestart) then FOnNeedRestart(nil);
end);
end;
procedure TWorkerThread.InnerNewSession(const AStart: TDateTime; const AMinId, AMaxId: Int64; const AMinDT, AMaxDT: TDateTime; const ARecCount, ASessionNumber: Integer);
begin
TThread.Queue(nil, procedure
begin
if Assigned(FOnNewSession) then FOnNewSession(AStart, AMinId, AMaxId, AMinDT, AMaxDT, ARecCount, ASessionNumber);
end);
end;
procedure TWorkerThread.MySleep(const AInterval: Cardinal);
var
Start: Cardinal;
begin
// метод имитирует действие стандартного Sleep, но в отличие от него может выйти досрочно если поток Terminated
Start := GetTickCount;
while ((GetTickCount - Start) < AInterval) and not Terminated do
Sleep(1);
end;
procedure TWorkerThread.Stop;
begin
Data.StopReplica;
end;
{ TSinglePacket }
procedure TSinglePacket.Execute;
begin
inherited;
// Data.BuildReplicaCommandsSQL(Data.StartId, Data.SelectRange);
// ReturnValue := Data.ExecutePreparedPacket;
end;
{ TReplicaThread }
procedure TReplicaThread.Execute;
begin
inherited;
Data.StartReplica;
FReturnValue := Ord(Data.ReplicaFinished);
Terminate;
end;
{ TMinMaxIdThread }
procedure TMinMaxIdThread.Execute;
var
P: PMinMaxId;
tmpMinMax: TMinMaxId;
begin
inherited;
tmpMinMax := Data.GetMinMaxId;
New(P);
P^.MinId := tmpMinMax.MinId;
P^.MaxId := tmpMinMax.MaxId;
P^.RecCount := tmpMinMax.RecCount;
P^.MinDT := tmpMinMax.MinDT;
P^.MaxDT := tmpMinMax.MaxDT;
FReturnValue := LongWord(P);
Terminate;
end;
{ TCompareRecCountMSThread }
constructor TCompareRecCountMSThread.Create(CreateSuspended, ADeviationsOnly: Boolean; AMsgProc: TNotifyMessage;
AKind: TThreadKind);
begin
FDeviationsOnly := ADeviationsOnly;
inherited Create(CreateSuspended, AMsgProc, AKind);
end;
procedure TCompareRecCountMSThread.Execute;
var
P: PCompareMasterSlave;
sSQL: string;
begin
inherited;
Data.OnCompareRecCountMS := MyOnCompareRecCountMS;
sSQL := Data.GetCompareRecCountMS_SQL(FDeviationsOnly);
New(P);
P^.ResultSQL := sSQL;
FReturnValue := LongWord(P);
Terminate;
end;
procedure TCompareRecCountMSThread.MyOnCompareRecCountMS(const aSQL: string);
begin
TThread.Queue(nil, procedure
begin
if Assigned(FOnCompareRecCountMS) then FOnCompareRecCountMS(aSQL);
end);
end;
{ TCompareSeqMSThread }
constructor TCompareSeqMSThread.Create(CreateSuspended, ADeviationsOnly: Boolean; AMsgProc: TNotifyMessage;
AKind: TThreadKind);
begin
FDeviationsOnly := ADeviationsOnly;
inherited Create(CreateSuspended, AMsgProc, AKind);
end;
procedure TCompareSeqMSThread.Execute;
var
P: PCompareMasterSlave;
sSQL: string;
begin
inherited;
sSQL := Data.GetCompareSeqMS_SQL(FDeviationsOnly);
New(P);
P^.ResultSQL := sSQL;
FReturnValue := LongWord(P);
Terminate;
end;
{ TApplyScriptThread }
constructor TApplyScriptThread.Create(CreateSuspended: Boolean; AScriptsContent, AScriptNames: TStrings;
AMsgProc: TNotifyMessage; AKind: TThreadKind);
begin
FScriptsContent := TStringList.Create;
FScriptNames := TStringList.Create;
FScriptsContent.Assign(AScriptsContent);
FScriptNames.Assign(AScriptNames);
inherited Create(CreateSuspended, AMsgProc, AKind);
end;
destructor TApplyScriptThread.Destroy;
begin
FreeAndNil(FScriptsContent);
FreeAndNil(FScriptNames);
inherited;
end;
procedure TApplyScriptThread.Execute;
begin
inherited;
FReturnValue := Ord(Data.ApplyScripts(FScriptsContent, FScriptNames));
Terminate;
end;
{ TMoveProcToSlaveThread }
procedure TMoveProcToSlaveThread.Execute;
begin
inherited;
Data.MoveSavedProcToSlave;
Terminate;
end;
{ TLastIdThread }
procedure TLastIdThread.Execute;
begin
inherited;
FReturnValue := Data.LastId;
Terminate;
end;
{ TAlterSlaveSequencesThread }
procedure TAlterSlaveSequencesThread.Execute;
begin
inherited;
Data.AlterSlaveSequences;
Terminate;
end;
{ TMoveErrorsThread }
procedure TMoveErrorsThread.Execute;
begin
inherited;
Data.MoveErrorsFromSlaveToMaster;
end;
end.
|
unit Safecode;
{**********************************************
Kingstar Delphi Library
Copyright (C) Kingstar Corporation
<Unit> Safecode
<What> 编写可靠代码的类似断言的判断
<Written By> Huang YanLai
<History>
**********************************************}
interface
uses Sysutils;
type
// %EUnexpectedValue : 一个函数/过程返回一个不成功的结果时,调用CheckXXX产生的意外
EUnexpectedValue = class(exception);
procedure RaiseUnexpectedValue(const Msg:string='');
// %CheckZero : #n must be 0, otherwise RaiseUnexpectedValue
procedure CheckZero(n:integer; const Msg:string='');
// %CheckZero : #n must not be 0, otherwise RaiseUnexpectedValue
procedure CheckNotZero(n:integer; const Msg:string='');
// %CheckTrue : #b must not be true, otherwise RaiseUnexpectedValue
procedure CheckTrue(b : boolean; const Msg:string='');
// %CheckObject : #obj must not be nil, otherwise RaiseUnexpectedValue
procedure CheckObject(obj : TObject; const Msg:string='');
// %CheckPtr : #Ptr must not be nil, otherwise RaiseUnexpectedValue
procedure CheckPtr(Ptr : Pointer; const Msg:string='');
type
// %EInvalidParam : 当传入的参数无效时,产生
EInvalidParam = class(Exception);
// %EIndexOutOfRange : 索引越界时产生
EIndexOutOfRange = class(Exception);
// %ECannotDo : 不能执行指定操作时产生
ECannotDo = class(Exception);
procedure RaiseInvalidParam;
procedure RaiseIndexOutOfRange;
procedure RaiseConvertError;
procedure RaiseCannotDo(const info:string);
// %CheckRange : 当(index<min) or (index>max)时 RaiseIndexOutOfRange
procedure CheckRange(index,min,max : integer);
resourcestring
SUnexpectedError = 'An unexpected value that may be due to a unsuccessfal call';
SOutOfRangeError = '%d out of range [%d,%d]';
implementation
procedure RaiseUnexpectedValue(const Msg:string='');
begin
if Msg<>'' then
raise EUnexpectedValue.create(msg)
else
raise EUnexpectedValue.create(
SUnexpectedError);
end;
procedure CheckZero(n:integer; const Msg:string='');
begin
if (n<>0) then RaiseUnexpectedValue(msg);
end;
procedure CheckNotZero(n:integer; const Msg:string='');
begin
if (n=0) then RaiseUnexpectedValue(msg);
end;
procedure CheckTrue(b : boolean; const Msg:string='');
begin
if not b then
RaiseUnexpectedValue(msg);
end;
procedure CheckObject(obj : TObject; const Msg:string='');
begin
if obj=nil then RaiseUnexpectedValue(msg);
end;
procedure CheckPtr(Ptr : Pointer; const Msg:string='');
begin
if Ptr=nil then RaiseUnexpectedValue(msg);
end;
procedure RaiseInvalidParam;
begin
raise EInvalidParam.create('Invalid Property Type');
end;
procedure RaiseIndexOutOfRange;
begin
raise EIndexOutOfRange.create('Index out of range');
end;
procedure RaiseConvertError;
begin
raise EConvertError.Create('A convert error!');
end;
procedure RaiseCannotDo(const info:string);
begin
raise ECannotDo.Create(info);
end;
procedure CheckRange(index,min,max : integer);
begin
if (index<min) or (index>max) then
raise EIndexOutOfRange.CreateFmt(SOutOfRangeError,[Index,Min,Max]);
end;
end.
|
{*******************************************************}
{ }
{ Delphi FireMonkey Platform }
{ }
{ Copyright(c) 2011-2013 Embarcadero Technologies, Inc. }
{ }
{*******************************************************}
unit FMX.Context.GLES.iOS;
interface
uses
System.Classes, System.SysUtils, System.Types, System.UITypes, System.UIConsts, System.Generics.Collections, System.Math,
Macapi.CoreFoundation, iOSapi.CocoaTypes, iOSapi.CoreGraphics, iOSapi.Foundation, iOSapi.UIKit, iOSapi.OpenGLES, iOSapi.GLKit,
FMX.Types, FMX.Types3D, FMX.Platform, FMX.Filter, FMX.Graphics, FMX.Context.GLES;
type
TCustomContextIOS = class(TCustomContextOpenGL)
protected class var
FSharedContext: EAGLContext;
class function GetSharedContext: EAGLContext; static;
protected
class procedure CreateSharedContext; override;
class procedure DestroySharedContext; override;
public
class property SharedContext: EAGLContext read GetSharedContext;
class function IsContextAvailable: Boolean; override;
end;
procedure RegisterContextClasses;
procedure UnregisterContextClasses;
implementation {===============================================================}
uses
FMX.Platform.iOS, FMX.Forms, FMX.Consts, FMX.Canvas.GPU, FMX.Materials, FMX.PixelFormats;
{ TCustomContextIOS }
class procedure TCustomContextIOS.CreateSharedContext;
begin
if FSharedContext = nil then
begin
FSharedContext := TEAGLContext.Wrap(TEAGLContext.Create.initWithAPI(kEAGLRenderingAPIOpenGLES2));
TEAGLContext.OCClass.setCurrentContext(FSharedContext);
TCustomContextIOS.FStyle := [TContextStyle.RenderTargetFlipped];
TCustomContextIOS.FPixelFormat := TPixelFormat.pfA8B8G8R8;
TCustomContextIOS.FPixelToPixelPolygonOffset := PointF(0, 0);
TCustomContextIOS.FMaxLightCount := 4;
FillMetrics;
end;
end;
class procedure TCustomContextIOS.DestroySharedContext;
begin
if FSharedContext <> nil then
begin
DestroyPrograms;
FSharedContext := nil;
end;
end;
class function TCustomContextIOS.IsContextAvailable: Boolean;
begin
Result := Assigned(SharedContext);
end;
class function TCustomContextIOS.GetSharedContext: EAGLContext;
begin
CreateSharedContext;
Result := FSharedContext;
end;
{ TContextOpenGL }
type
TContextIOS = class(TCustomContextIOS)
private
protected
function GetValid: Boolean; override;
class function GetShaderArch: TContextShaderArch; override;
procedure DoSetScissorRect(const ScissorRect: TRect); override;
{ buffer }
procedure DoCreateBuffer; override;
procedure DoEndScene; override;
{ constructors }
constructor CreateFromWindow(const AParent: TWindowHandle; const AWidth, AHeight: Integer;
const AMultisample: TMultisample; const ADepthStencil: Boolean); override;
constructor CreateFromTexture(const ATexture: TTexture; const AMultisample: TMultisample;
const ADepthStencil: Boolean); override;
public
end;
{ TContextIOS }
constructor TContextIOS.CreateFromWindow(const AParent: TWindowHandle; const AWidth, AHeight: Integer;
const AMultisample: TMultisample; const ADepthStencil: Boolean);
var
View: GLKView;
begin
inherited;
View := WindowHandleToPlatform(AParent).GLView;
if Assigned(View) and (Multisample <> TMultisample.msNone) then
View.setDrawableMultisample(GLKViewDrawableMultisample4X);
CreateSharedContext;
CreateBuffer;
end;
constructor TContextIOS.CreateFromTexture(const ATexture: TTexture; const AMultisample: TMultisample;
const ADepthStencil: Boolean);
begin
{$WARNINGS OFF}
FSupportMS := Pos('gl_apple_framebuffer_multisample', LowerCase(MarshaledAString(glGetString(GL_EXTENSIONS)))) > 0;
{$WARNINGS ON}
inherited;
end;
procedure TContextIOS.DoCreateBuffer;
var
Status: Integer;
OldFBO: GLuint;
begin
if IsContextAvailable and Assigned(Texture) then
begin
{ create buffers }
if (Multisample <> TMultisample.msNone) and FSupportMS then
begin
glGetIntegerv(GL_FRAMEBUFFER_BINDING, @OldFBO);
glGenFramebuffers(1, @FFrameBuf);
glBindFramebuffer(GL_FRAMEBUFFER, FFrameBuf);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, Texture.Handle, 0);
if DepthStencil then
begin
glGenRenderbuffers(1, @FDepthBuf);
glBindRenderbuffer(GL_RENDERBUFFER, FDepthBuf);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8_OES, Width, Height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, FDepthBuf);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, FDepthBuf);
glBindRenderbuffer(GL_RENDERBUFFER, 0);
end;
Status := glCheckFramebufferStatus(GL_FRAMEBUFFER);
if Status <> GL_FRAMEBUFFER_COMPLETE then
RaiseContextExceptionFmt(@SCannotCreateRenderBuffers, [ClassName]);
{ MS }
glGenFramebuffers(1, @FFrameBufMS);
glBindFramebuffer(GL_FRAMEBUFFER, FFrameBufMS);
glGenRenderbuffers(1, @FRenderBufMS);
glBindRenderbuffer(GL_RENDERBUFFER, FRenderBufMS);
glRenderbufferStorageMultisampleAPPLE(GL_RENDERBUFFER, FMSValue, GL_RGBA8_OES, Width, Height);
glFrameBufferRenderBuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, FRenderBufMS);
if DepthStencil then
begin
glGenRenderbuffers(1, @FDepthBufMS);
glBindRenderbuffer(GL_RENDERBUFFER, FDepthBufMS);
glRenderbufferStorageMultisampleAPPLE(GL_RENDERBUFFER, FMSValue, GL_DEPTH24_STENCIL8_OES, Width, Height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, FDepthBufMS);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, FDepthBufMS);
glBindRenderbuffer(GL_RENDERBUFFER, 0);
end;
Status := glCheckFramebufferStatus(GL_FRAMEBUFFER);
if Status <> GL_FRAMEBUFFER_COMPLETE then
RaiseContextExceptionFmt(@SCannotCreateRenderBuffers, [ClassName]);
glBindFramebuffer(GL_FRAMEBUFFER, OldFBO);
end
else
begin
glGetIntegerv(GL_FRAMEBUFFER_BINDING, @OldFBO);
glGenFramebuffers(1, @FFrameBuf);
glBindFramebuffer(GL_FRAMEBUFFER, FFrameBuf);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, Texture.Handle, 0);
if DepthStencil then
begin
glGenRenderbuffers(1, @FDepthBuf);
glBindRenderbuffer(GL_RENDERBUFFER, FDepthBuf);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8_OES, Width, Height);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, FDepthBuf);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, FDepthBuf);
glBindRenderbuffer(GL_RENDERBUFFER, 0);
end;
Status := glCheckFramebufferStatus(GL_FRAMEBUFFER);
if Status <> GL_FRAMEBUFFER_COMPLETE then
RaiseContextExceptionFmt(@SCannotCreateRenderBuffers, [ClassName]);
glBindFramebuffer(GL_FRAMEBUFFER, OldFBO);
end;
if (GLHasAnyErrors()) then
RaiseContextExceptionFmt(@SCannotCreateRenderBuffers, [ClassName]);
end;
end;
procedure TContextIOS.DoEndScene;
begin
if Valid then
begin
if FFrameBufMS <> 0 then
begin
glBindFramebuffer(GL_READ_FRAMEBUFFER_APPLE, FFrameBufMS);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER_APPLE, FFrameBuf);
glResolveMultisampleFramebufferAPPLE;
glBindFramebuffer(GL_READ_FRAMEBUFFER_APPLE, 0);
glBindFramebuffer(GL_DRAW_FRAMEBUFFER_APPLE, 0);
end;
inherited;
end;
end;
procedure TContextIOS.DoSetScissorRect(const ScissorRect: TRect);
var
R: TRect;
begin
R := Rect(Round(ScissorRect.Left * FScale), Round(ScissorRect.Top * FScale),
Round(ScissorRect.Right * FScale), Round(ScissorRect.Bottom * FScale));
if Assigned(Texture) then
glScissor(R.Left, Height - R.Bottom, R.Width, R.Height)
else
glScissor(R.Left, Round(Height * FScale) - R.Bottom, R.Width, R.Height);
if (GLHasAnyErrors()) then
RaiseContextExceptionFmt(@SErrorInContextMethod, ['DoSetScissorRect']);
end;
class function TContextIOS.GetShaderArch: TContextShaderArch;
begin
Result := TContextShaderArch.saIOS;
end;
function TContextIOS.GetValid: Boolean;
begin
Result := IsContextAvailable;
if Result then
TEAGLContext.OCClass.setCurrentContext(FSharedContext);
end;
procedure RegisterContextClasses;
begin
TContextManager.RegisterContext(TContextIOS, True);
end;
procedure UnregisterContextClasses;
begin
TContextIOS.DestroySharedContext;
end;
end.
|
unit UnitFormReadVars;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.Grids,
Vcl.ExtCtrls, System.Generics.collections, model_network;
type
TStringGridEx = class helper for TStringGrid
public
function GetInplaceEditor(): TInplaceEdit;
end;
TFormReadVars = class(TForm)
StringGrid1: TStringGrid;
procedure StringGrid1DblClick(Sender: TObject);
procedure StringGrid1DrawCell(Sender: TObject; ACol, ARow: Integer;
Rect: TRect; State: TGridDrawState);
procedure StringGrid1KeyPress(Sender: TObject; var Key: Char);
procedure FormCreate(Sender: TObject);
procedure StringGrid1SelectCell(Sender: TObject; ACol, ARow: Integer;
var CanSelect: Boolean);
procedure StringGrid1MouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
procedure StringGrid1SetEditText(Sender: TObject; ACol, ARow: Integer;
const Value: string);
private
{ Private declarations }
Last_Edited_Col, Last_Edited_Row: Integer;
FPlace: Integer;
FVarIndex: Integer;
FErrors: TDictionary<string, string>;
FNetwork: TNetwork;
FInitialized:boolean;
procedure SetRowChecked(row: Integer; v: Boolean);
procedure ToggleRowChecked(row: Integer);
procedure ToggleColChecked(col: Integer);
function AddrByIndex(place: Integer): Integer;
function VarByIndex(varindex: Integer): Integer;
public
{ Public declarations }
function FormatAddrPlace(place, varindex: Integer): string;
procedure Init(ANetwork: TNetwork);
procedure HandleReadVar(X: TReadVar);
procedure reset;
end;
var
FormReadVars: TFormReadVars;
implementation
{$R *.dfm}
uses stringgridutils, stringutils, UnitFormPopup, UnitServerApp, serverapp_msg,
UnitFormChartSeries;
function TStringGridEx.GetInplaceEditor: TInplaceEdit;
begin
Result := InplaceEditor; // get access to InplaceEditor
end;
function col2place(col: Integer): Integer;
begin
Result := col - 1;
end;
function row2var(row: Integer): Integer;
begin
Result := row - 1;
end;
function place2col(place: Integer): Integer;
begin
Result := place + 1;
end;
function var2row(varindex: Integer): Integer;
begin
Result := varindex + 1;
end;
function plk(place: Integer): string;
begin
Result := inttostr(place) + '_';
end;
function pvk(place, varindex: Integer): string;
begin
Result := inttostr(place) + '_' + inttostr(varindex);
end;
function pvkk(col, row: Integer): string;
begin
if row = 0 then
exit(plk(col2place(col)))
else
exit(pvk(col2place(col), row2var(row)));
end;
procedure TFormReadVars.FormCreate(Sender: TObject);
begin
FPlace := -1;
FVarIndex := -1;
FErrors := TDictionary<string, string>.Create;
FInitialized := false;
end;
procedure TFormReadVars.StringGrid1DblClick(Sender: TObject);
var
r: TRect;
pt: TPoint;
place, varInd: Integer;
k: string;
ACol, ARow: Integer;
begin
with StringGrid1 do
begin
GetCursorPos(pt);
pt := ScreenToClient(pt);
MouseToCell(pt.X, pt.Y, ACol, ARow);
if (ACol = 0) AND (ARow = 0) then
begin
ServerApp.SendMsg(msgToggle, 0, 0);
exit;
end;
varInd := row2var(ACol);
place := col2place(ARow);
k := pvkk(ACol, ARow);
r := CellRect(ACol, ARow);
pt := ClientToScreen(r.BottomRight);
end;
if FErrors.ContainsKey(k) then
with FormPopup do
begin
RichEdit1.Font.Color := clRed;
RichEdit1.Text := FErrors[k];
Left := pt.X + 5;
Top := pt.Y + 5;
Show;
end;
end;
procedure TFormReadVars.StringGrid1DrawCell(Sender: TObject;
ACol, ARow: Integer; Rect: TRect; State: TGridDrawState);
var
grd: TStringGrid;
cnv: TCanvas;
X, Y: Integer;
txt_width, txt_height: double;
s: string;
Checked_col, Checked_row: Boolean;
// pv: RProductVarOrder;
place, var_ind: Integer;
const
lineColor: TColor = $00BCBCBC;
begin
place := col2place(ACol);
var_ind := row2var(ARow);
grd := TStringGrid(Sender);
s := grd.Cells[ACol, ARow];
if (ACol = 0) and (ARow > 0) then
s := '';
cnv := grd.Canvas;
cnv.Font.Assign(self.Font);
Checked_row := false;
if var_ind > -1 then
Checked_row := not FNetwork.FVars[var_ind].FUnchecked;
Checked_col := false;
if place > -1 then
Checked_col := not FNetwork.FPlaces[place].FUnchecked;
if gdFixed in State then
cnv.Brush.Color := cl3DLight
else if gdSelected in State then
cnv.Brush.Color := clGradientInactiveCaption
else if Checked_row and Checked_col then
cnv.Brush.Color := grd.Color
else
cnv.Brush.Color := clBtnFace;
if FErrors.ContainsKey(pvkk(ACol, ARow)) then
begin
cnv.Font.Color := clRed;
end;
if (place >= 0) and (var_ind >= 0) and (place = FPlace) and
(var_ind = FVarIndex) then
cnv.Brush.Color := clInfoBk;
if cnv.TextWidth(s) + 3 > Rect.Width then
s := cut_str(s, cnv, Rect.Width);
txt_width := cnv.TextWidth(s);
txt_height := cnv.TextHeight(s);
X := Rect.Left + 3;
// x := Rect.left + round((Rect.Width - txt_width) / 2.0);
if (ARow > 0) AND (ACol <> 1) then
X := Rect.Right - 3 - round(txt_width);
Y := Rect.Top + round((Rect.Height - txt_height) / 2.0);
cnv.TextRect(Rect, X, Y, s);
if (ACol = 0) and (ARow > 0) then
StringGrid_DrawCheckBoxCell(grd, ACol, ARow, Rect, State, Checked_row);
if (ARow = 0) and (ACol > 0) then
StringGrid_DrawCheckBoxCell(grd, ACol, ARow, Rect, State, Checked_col);
StringGrid_DrawCellBounds(cnv, ACol, ARow, Rect);
end;
procedure TFormReadVars.StringGrid1KeyPress(Sender: TObject; var Key: Char);
var
g: TStringGrid;
ARow: Integer;
v: Boolean;
begin
g := Sender as TStringGrid;
if (g.row > 0) AND (ord(Key) in [32, 27]) then
begin
v := FNetwork.FVars[row2var(g.Selection.Top)].FUnchecked;
for ARow := g.Selection.Top to g.Selection.Bottom do
SetRowChecked(ARow, not v);
end;
if ord(Key) = 1 then
begin
v := FNetwork.FVars[row2var(g.Selection.Top)].FUnchecked;
for ARow := 2 to StringGrid1.RowCount - 1 do
SetRowChecked(ARow, not v);
end;
end;
procedure TFormReadVars.StringGrid1MouseDown(Sender: TObject;
Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
var
ACol, ARow: Integer;
Rect: TRect;
begin
if (GetAsyncKeyState(VK_LBUTTON) >= 0) then
exit;
StringGrid1.MouseToCell(X, Y, ACol, ARow);
if ((ACol = 0) and (ARow = 0)) OR ((ACol <> 0) AND (ARow <> 0)) then
exit;
Rect := StringGrid1.CellRect(ACol, ARow);
if X > (Rect.Right + Rect.Left) div 2 then
with StringGrid1 do
begin
fixedrows := 0;
if True then
col := ACol;
row := ARow;
Options := Options + [goEditing];
EditorMode := True;
with GetInplaceEditor() do
begin
SelStart := 0;
SelLength := Length(Cells[ACol, ARow]);
end;
exit;
end;
if ACol = 0 then
begin
ToggleRowChecked(ARow);
StringGrid_RedrawRow(StringGrid1, ARow);
end
else
begin
ToggleColChecked(ACol);
StringGrid_RedrawCol(StringGrid1, ACol);
end;
end;
procedure TFormReadVars.StringGrid1SelectCell(Sender: TObject;
ACol, ARow: Integer; var CanSelect: Boolean);
var
r: TRect;
grd: TStringGrid;
begin
if (ACol = 0) AND (ARow = 0) then
begin
CanSelect := false;
exit;
end;
with Sender as TStringGrid do
begin
// When selecting a cell
if EditorMode then
begin // It was a cell being edited
EditorMode := false; // Deactivate the editor
// Do an extra check if the LastEdited_ACol and LastEdited_ARow are not -1 already.
// This is to be able to use also the arrow-keys up and down in the Grid.
if (Last_Edited_Col <> -1) and (Last_Edited_Row <> -1) then
StringGrid1SetEditText(grd, Last_Edited_Col, Last_Edited_Row,
Cells[Last_Edited_Col, Last_Edited_Row]);
// Just make the call
end;
// Do whatever else wanted
Options := Options - [goEditing];
end;
end;
procedure TFormReadVars.StringGrid1SetEditText(Sender: TObject;
ACol, ARow: Integer; const Value: string);
var
s: string;
v: extended;
n: Integer;
begin
With StringGrid1 do
// Fired on every change
if Not EditorMode // goEditing must be 'True' in Options
then
begin // Only after user ends editing the cell
Last_Edited_Col := -1; // Indicate no cell is edited
Last_Edited_Row := -1; // Indicate no cell is edited
// Do whatever wanted after user has finish editing a cell
fixedrows := 1;
if ARow = 0 then
begin
if TryStrToInt(Value, n) and (n > 0) and (n < 256) then
ServerApp.MustSendUserMsg(msgSetAddr, col2place(ACol), n)
else
ServerApp.MustSendUserMsg(msgPeer, 0, 0);
end;
if ACol = 0 then
begin
if TryStrToInt(Value, n) and (n > -1) then
ServerApp.MustSendUserMsg(msgSetvar, row2var(ARow), n)
else
ServerApp.MustSendUserMsg(msgPeer, 0, 0);
end;
end
else
begin // The cell is being editted
Last_Edited_Col := ACol; // Remember column of cell being edited
Last_Edited_Row := ARow; // Remember row of cell being edited
end;
end;
procedure TFormReadVars.Init(ANetwork: TNetwork);
var
ACol, ARow, place, varInd: Integer;
begin
if Assigned(FNetwork) then
begin
for place := 0 to Length(FNetwork.FPlaces) - 1 do
FNetwork.FPlaces[place].Free;
for varInd := 0 to Length(FNetwork.FVars) - 1 do
FNetwork.FVars[varInd].Free;
FNetwork.Free;
end;
FNetwork := ANetwork;
FErrors.Clear;
StringGrid_Clear(StringGrid1);
with StringGrid1 do
begin
RowCount := Length(FNetwork.FVars) + 1;
fixedrows := 1;
ColCount := Length(FNetwork.FPlaces) + 1;
Cells[0, 0] := '№';
Cells[1, 0] := 'Параметр';
for varInd := 0 to Length(FNetwork.FVars) - 1 do
begin
ARow := var2row(varInd);
Cells[0, ARow] := inttostr(FNetwork.FVars[varInd].FVar);
end;
for place := 0 to Length(FNetwork.FPlaces) - 1 do
begin
ACol := place2col(place);
Cells[ACol, 0] := inttostr(FNetwork.FPlaces[place].FAddr);
end;
end;
StringGrid_Redraw(StringGrid1);
FInitialized := true;
end;
procedure TFormReadVars.reset;
var
prev_place, prev_var: Integer;
begin
prev_place := FPlace;
prev_var := FVarIndex;
FPlace := -1;
FVarIndex := -1;
if (prev_place >= 0) and (prev_var >= 0) then
StringGrid_RedrawCell(StringGrid1, place2col(prev_place),
var2row(prev_var));
if (FPlace >= 0) and (FVarIndex >= 0) then
StringGrid_RedrawCell(StringGrid1, place2col(FPlace),
var2row(FVarIndex));
end;
procedure TFormReadVars.HandleReadVar(X: TReadVar);
var
prev_place, prev_var: Integer;
prev_place_err : boolean;
begin
if not FInitialized then
exit;
prev_place := FPlace;
prev_var := FVarIndex;
FPlace := X.FPlace;
FVarIndex := X.FVarIndex;
if X.FError <> '' then
begin
FErrors.AddOrSetValue(pvk(FPlace, FVarIndex), X.FError);
StringGrid1.Cells[place2col(FPlace), var2row(FVarIndex)] := X.FError;
end
else
begin
FErrors.Remove(pvk(FPlace, FVarIndex));
StringGrid1.Cells[place2col(FPlace), var2row(FVarIndex)] :=
floattostr(X.FValue);
FormChartSeries.AddValue(AddrByIndex(X.FPlace), VarByIndex(X.FVarIndex),
X.FValue, now);
end;
if (prev_place >= 0) and (prev_var >= 0) then
StringGrid_RedrawCell(StringGrid1, place2col(prev_place),
var2row(prev_var));
if (FPlace >= 0) and (FVarIndex >= 0) then
StringGrid_RedrawCell(StringGrid1, place2col(FPlace),
var2row(FVarIndex));
prev_place_err := FErrors.ContainsKey(plk(FPlace));
if Pos('нет ответа', LowerCase(X.FError)) > 0 then
FErrors.AddOrSetValue(plk(FPlace), X.FError)
else
FErrors.Remove(plk(FPlace));
if prev_place_err <> FErrors.ContainsKey(plk(FPlace)) then
StringGrid_RedrawCell(StringGrid1, place2col(FPlace), 0);
end;
procedure TFormReadVars.SetRowChecked(row: Integer; v: Boolean);
begin
FNetwork.FVars[row2var(row)].FUnchecked := v;
ServerApp.SendMsg(msgSetVarChecked, row2var(row), lParam(v));
StringGrid_RedrawRow(StringGrid1, row);
end;
procedure TFormReadVars.ToggleRowChecked(row: Integer);
begin
SetRowChecked(row, not FNetwork.FVars[row2var(row)].FUnchecked);
end;
procedure TFormReadVars.ToggleColChecked(col: Integer);
begin
FNetwork.FPlaces[col2place(col)].FUnchecked := not FNetwork.FPlaces
[col2place(col)].FUnchecked;
ServerApp.SendMsg(msgSetPlaceChecked, col2place(col),
lParam(FNetwork.FPlaces[col2place(col)].FUnchecked));
StringGrid_RedrawCol(StringGrid1, col);
end;
function TFormReadVars.FormatAddrPlace(place, varindex: Integer): string;
var
cl, ro: Integer;
s1, s2: string;
begin
cl := place2col(place);
ro := var2row(varindex);
if (cl > -1) AND (cl < StringGrid1.ColCount) then
s1 := StringGrid1.Cells[place2col(place), 0]
else
s1 := format('№%d', [place + 1]);
if (ro > -1) AND (ro < StringGrid1.RowCount) then
s2 := StringGrid1.Cells[0, var2row(varindex)]
else
s2 := format('№%d', [varindex + 1]);
Result := s1 + ': ' + s2;
end;
function TFormReadVars.AddrByIndex(place: Integer): Integer;
var
cl: Integer;
begin
cl := place2col(place);
if (cl > 0) AND (cl < StringGrid1.ColCount) then
if TryStrToInt(StringGrid1.Cells[cl, 0], result) then
exit(result);
exit(-1);
end;
function TFormReadVars.VarByIndex(varindex: Integer): Integer;
var
ro: Integer;
begin
ro := var2row(varindex);
if (ro > 0) AND (ro < StringGrid1.RowCount) then
if TryStrToInt(StringGrid1.Cells[0, ro], result) then
exit(result);
exit(-1);
end;
end.
|
unit Model.Department;
interface
uses
Model.Interfaces,
Model.IMyConnection,
System.Generics.Collections,
Spring.Collections,
Spring.Data.ObjectDataset,
Spring.Persistence.Criteria.Interfaces,
Spring.Persistence.Criteria.Restrictions,
Spring.Persistence.Criteria.OrderBy,
MainDM;
function CreateDepartmentModelClass: IDepartmentModelInterface;
implementation
uses
System.SysUtils, Model.Declarations, Model.FormDeclarations,
Forms;
type
TDepartmentModel = class (TInterfacedObject, IDepartmentModelInterface)
private
fDepartment: TDepartment;
public
function GetAllDepartments(const companyId : Integer; const filter : string) : IObjectList;
function GetAllDepartmentsDS(const companyId : Integer; const filter : string) : TObjectDataset;
procedure AddDepartment(const newDepartment: TDepartment);
function GetDepartment(const DepartmentCode: string): TDepartment; overload;
function GetDepartment(const DepartmentId : Integer) : TDepartment; overload;
procedure UpdateDepartment(const Department: TDepartment);
procedure DeleteDepartment(const Department: TDepartment);
end;
function CreateDepartmentModelClass: IDepartmentModelInterface;
begin
result:=TDepartmentModel.Create;
end;
{ TDepartmentModel }
procedure TDepartmentModel.AddDepartment(const newDepartment: TDepartment);
begin
end;
procedure TDepartmentModel.DeleteDepartment(const Department: TDepartment);
begin
DMMain.Session.Delete(Department);
end;
function TDepartmentModel.GetAllDepartments(const companyId : Integer;
const filter: string): IObjectList;
var
FCriteria : ICriteria<TDepartment>;
begin
FCriteria := DMMain.Session.CreateCriteria<TDepartment>;
Result := FCriteria
.Add(Restrictions.Eq('CompanyId', companyId))
.Add(Restrictions.NotEq('IsDeleted', -1))
.OrderBy(TOrderBy.Asc('DepartmentId')).ToList as IObjectList;
end;
function TDepartmentModel.GetAllDepartmentsDS(const companyId : Integer; const filter: string): TObjectDataset;
begin
Result := TObjectDataSet.Create(Application);
Result.DataList := GetAllDepartments(companyId, '');
end;
function TDepartmentModel.GetDepartment(const DepartmentCode: string): TDepartment;
begin
Result := DMMain.Session.FirstOrDefault<TDepartment>('select * from Department where DepartmentCode=:0', [DepartmentCode]);
end;
function TDepartmentModel.GetDepartment(const DepartmentId : Integer) : TDepartment;
begin
Result := DMMain.Session.FindOne<TDepartment>(DepartmentId);
end;
procedure TDepartmentModel.UpdateDepartment(const Department: TDepartment);
begin
DMMain.Session.Update(Department);
end;
end.
|
unit uUtilities;
interface
type
TEvent = procedure of object;
TTypeMsg = ( tMsgDNone, tMsgDInformation, tMsgDWarning, tMsgDanger,tMsgDSuccess );
TGenericFunctions = class
class function IsNumeric(aText:string):boolean;
end;
implementation
{ TGenericFunctions }
class function TGenericFunctions.IsNumeric(aText: string): boolean;
var
iValue, iCode: Integer;
begin
val(aText, iValue, iCode);
if iCode = 0 then
result := true
else
result := false;
end;
end.
|
{*************************************************************
www: http://sourceforge.net/projects/alcinoe/
svn: svn checkout svn://svn.code.sf.net/p/alcinoe/code/ alcinoe-code
Author(s): Stéphane Vander Clock (alcinoe@arkadia.com)
Sponsor(s): Arkadia SA (http://www.arkadia.com)
product: ALHintballon
Version: 4.00
Description: Custom Hint with good look (Balloon). Good for use
in help tips
Legal issues: Copyright (C) 1999-2013 by Arkadia Software Engineering
This software is provided 'as-is', without any express
or implied warranty. In no event will the author be
held liable for any damages arising from the use of
this software.
Permission is granted to anyone to use this software
for any purpose, including commercial applications,
and to alter it and redistribute it freely, subject
to the following restrictions:
1. The origin of this software must not be
misrepresented, you must not claim that you wrote
the original software. If you use this software in
a product, an acknowledgment in the product
documentation would be appreciated but is not
required.
2. Altered source versions must be plainly marked as
such, and must not be misrepresented as being the
original software.
3. This notice may not be removed or altered from any
source distribution.
4. You must register this software by sending a picture
postcard to the author. Use a nice stamp and mention
your name, street address, EMail address and any
comment you like to say.
Know bug :
History: 01/03/2004: fix CloseHintBalloons by Hilton Janfield
(hjanfield@shaw.ca)
26/06/2012: Add xe2 support
Link :
* Please send all your feedback to alcinoe@arkadia.com
* If you have downloaded this source from a website different from
sourceforge.net, please get the last version on http://sourceforge.net/projects/alcinoe/
* Please, help us to keep the development of these components free by
promoting the sponsor on http://static.arkadia.com/html/alcinoe_like.html
**************************************************************}
unit ALHintBalloon;
interface
uses Forms,
Classes,
Controls,
ExtCtrls,
Messages;
type
{-------------------}
TALHintBalloon=Class;
TALHintBalloonMsgType = (bmtInfo, bmtError, bmtWarning, bmtNone);
TALHintBalloonArrowPosition = (bapTopLeft, bapTopRight, bapBottomLeft, bapBottomRight);
TALHintBalloonAnimationType = (batNone, batBlend, batCenter, batSlideLeftToRight, batSlideRightToLeft, batSlideTopToBottom, batSlideBottomToTop, batWipeLeftToRight, batWipeRightToLeft, batWipeTopToBottom, batWipeBottomToTop);
TALHintBalloonCreateContentProcess = procedure (ALHintBalloonObject: TALHintBalloon);
{---------------------------------}
TALHintBalloon = class(TCustomForm)
private
FMainPanel: Tpanel;
FcustomProperty: String;
FLastActiveForm: Tform;
fOldLastActiveFormWndProc: TWndMethod;
FBorderWidth: Integer;
procedure FormPaint(Sender: TObject);
function IsWinXP: boolean;
procedure LastActiveFormWndProcWndProc(var Message: TMessage);
protected
procedure CreateParams(var Params: TCreateParams); override;
procedure OnFormDeactivate(Sender: TObject);
procedure OnExitTimer(Sender: TObject);
public
constructor CreateNew(AOwner: TComponent; Dummy: integer = 0); override;
destructor Destroy; override;
procedure OnFormClick(Sender: TObject); Virtual;
procedure ShowHintBalloon(blnCreateContentProcess: TALHintBalloonCreateContentProcess; blnLeft, blnTop: integer; blnSourceControl: TControl; blnDuration: integer; blnArrowPosition: TALHintBalloonArrowPosition; blnAnimationType: TALHintBalloonAnimationType; blnAnimationSpeed: cardinal);
function TranslateAnimation(Value: TALHintBalloonAnimationType): cardinal;
property MainPanel: Tpanel read FMainPanel write FMainPanel;
property CustomProperty: String read FcustomProperty write FcustomProperty;
Property BorderWidth: Integer read FborderWidth write FborderWidth;
end;
{---------------------------------------}
TALHintBalloonControl = class(TComponent)
private
FALHintBalloon: TALHintBalloon;
FDuration: integer;
FAnimationSpeed: cardinal;
FAnimationType: TALHintBalloonAnimationType;
public
procedure ShowTextHintBalloon(blnMsgType: TALHintBalloonMsgType; blnTitle, blnText: String; blnBestWidth, blnLeft, blnTop: integer; blnSourceControl: Tcontrol; blnArrowPosition: TALHintBalloonArrowPosition);
procedure ShowPictureHintBalloon(blnImageFilename: String; blnLeft, blnTop: integer; blnSourceControl: TControl; blnArrowPosition: TALHintBalloonArrowPosition);
procedure ShowCustomHintBalloon(blnCreateContentProcess: TALHintBalloonCreateContentProcess; BlncustomProperty: String; blnLeft, blnTop: integer; blnSourceControl: TControl; blnArrowPosition: TALHintBalloonArrowPosition);
function CloseHintBalloons: integer;
constructor Create(AOwner: TComponent); override;
published
property Duration: integer read FDuration write FDuration Default 0;
property AnimationType: TALHintBalloonAnimationType read FAnimationType write FAnimationType default BatBlend;
property AnimationSpeed: cardinal read FAnimationSpeed write FAnimationSpeed Default 300;
end;
procedure Register;
implementation
{$R ..\resource\ALHintBalloon.res}
{$R ..\resource\ALHintballoon.dcr}
uses Windows,
SysUtils,
StdCtrls,
Graphics,
math;
{*****************}
procedure Register;
begin
RegisterComponents('Alcinoe', [TALHintBalloonControl]);
end;
{*******************************************************************************}
procedure ALHintBalloonConstructTextContent(ALHintBalloonObject: TALHintBalloon);
var lblTitle, LblText: Tlabel;
IcoImage: Timage;
aScrollBox: TscrollBox;
str: String;
LastLabelWidth, MaxPanelWidth, MaxPanelHeight, BestPanelWidth : integer;
LstCustomPropertyParams: TstringList;
DecLabelWidth: Boolean;
begin
LstCustomPropertyParams := TstringList.create;
try
LstCustomPropertyParams.Delimiter := ';';
LstCustomPropertyParams.QuoteChar := '''';
LstCustomPropertyParams.DelimitedText := ALHintBalloonObject.CustomProperty;
{-------------------------------------}
ALHintBalloonObject.Color := $00E1FFFF;
ALHintBalloonObject.Font.Name := 'Tahoma';
ALHintBalloonObject.Font.Size := 8;
ALHintBalloonObject.Font.Color := clBlack;
{--------------}
lblTitle := nil;
IcoImage := nil;
{----------------------------------------------------}
str := LstCustomPropertyParams.Values['IconeResName'];
if (str <> '') then begin
IcoImage := TImage.Create(ALHintBalloonObject.MainPanel);
with IcoImage do begin
Parent := ALHintBalloonObject.MainPanel;
Transparent := True;
Left := 10;
Top := 10;
Autosize := True;
Picture.Bitmap.LoadFromResourceName(HInstance, str);
Onclick := ALHintBalloonObject.OnFormClick;
end;
end;
{---------------------------------------------}
str := LstCustomPropertyParams.Values['Title'];
If (str <> '') then begin
lblTitle := TLabel.Create(ALHintBalloonObject.MainPanel);
With lblTitle do begin
Parent := ALHintBalloonObject.MainPanel;
ParentColor := True;
ParentFont := True;
AutoSize := True;
Font.Style := [fsBold];
if assigned(IcoImage) then left := IcoImage.Left + IcoImage.width + 8
else Left := 10;
Top := 12;
Caption := str;
Onclick := ALHintBalloonObject.OnFormClick;
end;
end;
{------------------------------------------------------}
LblText := TLabel.Create(ALHintBalloonObject.MainPanel);
with LblText do begin
Parent := ALHintBalloonObject.MainPanel;
ParentColor := True;
ParentFont := True;
if assigned(lblTitle) and assigned(IcoImage) then Top := max(lblTitle.Top + lblTitle.Height + 8,IcoImage.Top + IcoImage.Height + 8)
else if assigned(lblTitle) then Top := lblTitle.Top + lblTitle.Height + 8
else if assigned(IcoImage) then Top := IcoImage.Top + IcoImage.Height + 8
else top := 10;
Left := 10;
WordWrap := True;
BestPanelWidth := strtoint(LstCustomPropertyParams.Values['MainPanelBestWidth']);
Width := BestPanelWidth - left - 10;
AutoSize := True;
caption := LstCustomPropertyParams.Values['Text'];
Onclick := ALHintBalloonObject.OnFormClick;
{-------------------------------------------------------}
ALHintBalloonObject.MainPanel.Width := Left + Width + 10;
ALHintBalloonObject.MainPanel.Height := Top + Height + 10;
{-----------------------------------------------------------------------------}
MaxPanelWidth := strtoint(LstCustomPropertyParams.Values['MainPanelMaxWidth']);
MaxPanelHeight := strtoint(LstCustomPropertyParams.Values['MainPanelMaxHeight']);
IF ALHintBalloonObject.MainPanel.height > MaxPanelheight then begin
Width := MaxPanelWidth - Left - 10;
AutoSize := False;
AutoSize := True;
ALHintBalloonObject.MainPanel.Width := Left + Width + 10;
ALHintBalloonObject.MainPanel.Height := Top + Height + 10;
LastLabelWidth := width;
while ALHintBalloonObject.MainPanel.Height < MaxPanelheight do begin
LastLabelWidth := width;
if width <= BestPanelWidth then break;
width := width - 10;
AutoSize := False;
AutoSize := True;
ALHintBalloonObject.MainPanel.Width := Left + Width + 10;
ALHintBalloonObject.MainPanel.Height := Top + Height + 10;
end;
if ALHintBalloonObject.MainPanel.Height > MaxPanelheight then begin
width := LastLabelWidth;
AutoSize := False;
AutoSize := True;
ALHintBalloonObject.MainPanel.Width := Left + Width + 10;
ALHintBalloonObject.MainPanel.Height := Top + Height + 10;
end;
end;
while ALHintBalloonObject.MainPanel.Width > MaxPanelWidth do begin
if ALHintBalloonObject.MainPanel.height >= MaxPanelheight then break;
width := width-10;
AutoSize := False;
AutoSize := True;
ALHintBalloonObject.MainPanel.Width := Left + Width + 10;
ALHintBalloonObject.MainPanel.Height := Top + Height + 10;
end;
if assigned(lblTitle) and ((lblTitle.Left + lblTitle.Width + 10) > (ALHintBalloonObject.MainPanel.Width)) then Begin
ALHintBalloonObject.MainPanel.Width := (lblTitle.Left + lblTitle.Width) + 10;
Width := lblTitle.Width + lblTitle.Left - left;
AutoSize := False;
AutoSize := True;
ALHintBalloonObject.MainPanel.Height := Top + Height + 10;
end;
If (ALHintBalloonObject.MainPanel.Width > MaxPanelWidth) or (ALHintBalloonObject.MainPanel.Height > MaxPanelHeight) then begin
ALHintBalloonObject.MainPanel.Width := ALHintBalloonObject.MainPanel.Width + 20;
DecLabelWidth := False;
If (ALHintBalloonObject.MainPanel.Width > MaxPanelWidth) then begin
ALHintBalloonObject.MainPanel.Width := MaxPanelWidth;
DecLabelWidth := True;
end;
If (ALHintBalloonObject.MainPanel.Height > MaxPanelHeight) then ALHintBalloonObject.MainPanel.Height := MaxPanelHeight;
aScrollBox := TscrollBox.Create(ALHintBalloonObject.MainPanel);
With aScrollBox do begin
Parent := ALHintBalloonObject.MainPanel;
BevelEdges := [];
BevelInner := bvNone;
BevelOuter := bvNone;
BorderStyle := BsNone;
VertScrollBar.ParentColor := True;
VertScrollBar.Style := ssFlat;
HorzScrollBar.ParentColor := True;
HorzScrollBar.Style := ssFlat;
Align := AlClient;
IcoImage.Parent := aScrollBox;
LblTitle.Parent := aScrollBox;
LblText.parent := aScrollBox;
if DecLabelWidth then begin
LblText.Width := LblText.Width - 20;
LblText.AutoSize := False;
LblText.AutoSize := True;
end;
If LblText.Top + LblText.Height + 10 > height then begin
LblText.AutoSize := False;
LblText.Height := LblText.Height + 10;
end;
end;
end;
end;
finally
LstCustomPropertyParams.free;
end;
end;
{**********************************************************************************}
procedure ALHintBalloonConstructPictureContent(ALHintBalloonObject: TALHintBalloon);
var MaxPanelWidth, MaxPanelHeight : integer;
LstCustomPropertyParams: TstringList;
begin
LstCustomPropertyParams := TstringList.create;
try
LstCustomPropertyParams.Delimiter := ';';
LstCustomPropertyParams.QuoteChar := '''';
LstCustomPropertyParams.DelimitedText := ALHintBalloonObject.CustomProperty;
{-----------------------------------}
ALHintBalloonObject.Color := ClBlack;
{--------------------------------------------------------}
with TImage.Create(ALHintBalloonObject.MainPanel) do begin
Parent := ALHintBalloonObject.MainPanel;
Transparent := False;
Left := 0;
Top := 0;
Autosize := True;
Center := True;
stretch := False;
Proportional := False;
Picture.LoadFromFile(LstCustomPropertyParams.Values['ImageFileName']);
Onclick := ALHintBalloonObject.OnFormClick;
{-------------------------------------------}
ALHintBalloonObject.MainPanel.Width := Width;
ALHintBalloonObject.MainPanel.Height := Height;
{-----------------------------------------------------------------------------}
MaxPanelWidth := strtoint(LstCustomPropertyParams.Values['MainPanelMaxWidth']);
MaxPanelHeight := strtoint(LstCustomPropertyParams.Values['MainPanelMaxHeight']);
IF ALHintBalloonObject.MainPanel.height > MaxPanelheight then begin
Autosize := False;
Center := True;
Proportional := True;
width := round((MaxPanelheight / height) * width);
height := MaxPanelheight;
ALHintBalloonObject.MainPanel.Width := Width;
ALHintBalloonObject.MainPanel.Height := Height;
end;
If ALHintBalloonObject.MainPanel.Width > MaxPanelWidth then begin
Autosize := False;
Center := True;
Proportional := True;
height := round((MaxPanelWidth / Width) * height);
width := MaxPanelwidth;
ALHintBalloonObject.MainPanel.Width := Width;
ALHintBalloonObject.MainPanel.Height := Height;
end;
end;
finally
LstCustomPropertyParams.free;
end;
end;
{***********************************************************}
constructor TALHintBalloonControl.Create(AOwner: TComponent);
begin
inherited;
FAnimationType := batBlend;
FAnimationSpeed := 300;
FDuration := 0;
end;
{************************************************************************************}
procedure TALHintBalloonControl.ShowTextHintBalloon(blnMsgType: TALHintBalloonMsgType;
blnTitle, blnText: String;
blnBestWidth, blnLeft, blnTop: integer;
blnSourceControl: TControl;
blnArrowPosition: TALHintBalloonArrowPosition);
begin
FALHintBalloon := TALHintBalloon.CreateNew(Application);
With FALHintBalloon do begin
Case blnMsgType of
bmtError: CustomProperty := quotedStr('IconeResName=ERROR');
bmtInfo: CustomProperty := quotedStr('IconeResName=INFO');
bmtWarning: CustomProperty := quotedStr('IconeResName=WARNING');
else CustomProperty := quotedStr('IconeResName=');
end;
CustomProperty := CustomProperty + ';' + quotedStr('Title='+blnTitle);
CustomProperty := CustomProperty + ';' + quotedStr('Text='+blnText);
CustomProperty := CustomProperty + ';' + quotedStr('MainPanelBestWidth='+inttostr(blnBestWidth));
ShowHintBalloon(ALHintBalloonConstructTextContent,
blnLeft,
blnTop,
blnSourceControl,
FDuration,
blnArrowPosition,
FAnimationType,
FAnimationSpeed);
end;
end;
{******************************************************************************}
procedure TALHintBalloonControl.ShowPictureHintBalloon(blnImageFilename: String;
blnLeft, blnTop: integer;
blnSourceControl: TControl;
blnArrowPosition: TALHintBalloonArrowPosition);
begin
FALHintBalloon := TALHintBalloon.CreateNew(Application);
With FALHintBalloon do begin
CustomProperty := quotedStr('ImageFileName='+blnImageFilename);
ShowHintBalloon(ALHintBalloonConstructPictureContent,
blnLeft,
blnTop,
blnSourceControl,
FDuration,
blnArrowPosition,
FAnimationType,
FAnimationSpeed);
end;
end;
{****************************************************************************************************************}
procedure TALHintBalloonControl.ShowCustomHintBalloon(blnCreateContentProcess: TALHintBalloonCreateContentProcess;
BlncustomProperty: String;
blnLeft, blnTop: integer;
blnSourceControl: TControl;
blnArrowPosition: TALHintBalloonArrowPosition);
begin
FALHintBalloon := TALHintBalloon.CreateNew(Application);
With FALHintBalloon do begin
CustomProperty := BlncustomProperty;
ShowHintBalloon(blnCreateContentProcess,
blnLeft,
blnTop,
blnSourceControl,
FDuration,
blnArrowPosition,
FAnimationType,
FAnimationSpeed);
end;
end;
{********************************************************}
function TALHintBalloonControl.CloseHintBalloons: integer;
var i: Integer;
begin
Result := 0;
i := 0;
if Application.ComponentCount = 0 then Exit;
repeat
if (Application.Components[i].ClassName = 'TALHintBalloon') then begin
Application.Components[i].Free;
Inc(Result);
end
else inc(I);
until (i >= Application.ComponentCount);
end;
{***************************************************************************************}
function TALHintBalloon.TranslateAnimation(Value: TALHintBalloonAnimationType): cardinal;
begin
case (Value) of
batCenter: Result := AW_CENTER;
batBlend: Result := AW_BLEND;
batSlideLeftToRight: Result := AW_SLIDE or AW_HOR_POSITIVE;
batSlideRightToLeft: Result := AW_SLIDE or AW_HOR_NEGATIVE;
batSlideTopToBottom: Result := AW_SLIDE or AW_VER_POSITIVE;
batSlideBottomToTop: Result := AW_SLIDE or AW_VER_NEGATIVE;
batWipeLeftToRight: Result := AW_HOR_POSITIVE;
batWipeRightToLeft: Result := AW_HOR_NEGATIVE;
batWipeTopToBottom: Result := AW_VER_POSITIVE;
batWipeBottomToTop: Result := AW_VER_NEGATIVE;
else Result := 0;
end;
end;
{***************************************************************}
procedure TALHintBalloon.CreateParams(var Params: TCreateParams);
begin
inherited CreateParams(Params);
Params.Style := (Params.Style and not WS_CAPTION) or WS_POPUP;
Params.ExStyle := Params.ExStyle or WS_EX_TOOLWINDOW or WS_EX_NOACTIVATE or WS_EX_TOPMOST;
if (IsWinXP) then Params.WindowClass.Style := Params.WindowClass.Style or CS_DROPSHADOW;
Params.WndParent := GetDesktopWindow;
end;
{*****************************************************}
procedure TALHintBalloon.OnFormClick(Sender: TObject);
begin
Release;
end;
{*********************************************************}
procedure TALHintBalloon.OnFormDeactivate(Sender: TObject);
begin
Release;
end;
{****************************************************}
procedure TALHintBalloon.OnExitTimer(Sender: TObject);
begin
Release;
end;
{***************************************************************************}
constructor TALHintBalloon.CreateNew(AOwner: TComponent; Dummy: integer = 0);
begin
inherited;
FLastActiveForm:= nil;
fOldLastActiveFormWndProc:= nil;
FCustomProperty := '';
FBorderWidth := 1;
OnDeactivate := OnFormDeactivate;
BorderStyle := bsNone;
FormStyle := fsStayOnTop;
OnPaint := FormPaint;
OnClick := OnFormClick;
FMainPanel := TPanel.Create(Self);
with FMainPanel do begin
Parent := Self;
OnClick := OnFormClick;
BevelOuter := BvNone;
Caption := '';
ParentBackGround := True;
ParentColor := True;
Top := 0;
Left := 0;
end;
end;
{********************************}
destructor TALHintBalloon.Destroy;
begin
If FLastActiveForm <> nil then FLastActiveForm.WindowProc := FOldLastActiveFormWndProc;
inherited;
end;
{**************************************************}
procedure TALHintBalloon.FormPaint(Sender: TObject);
var TempRegion: HRGN;
begin
with Canvas.Brush do begin
Color := clBlack;
Style := bsSolid;
end;
TempRegion := CreateRectRgn(0,0,1,1);
GetWindowRgn(Handle, TempRegion);
FrameRgn(Canvas.Handle, TempRegion, Canvas.Brush.handle, 1, 1);
DeleteObject(TempRegion);
end;
{***************************************}
function TALHintBalloon.IsWinXP: boolean;
begin
Result := (Win32Platform = VER_PLATFORM_WIN32_NT) and (Win32MajorVersion >= 5) and (Win32MinorVersion >= 1);
end;
{***************************************************************************************************}
procedure TALHintBalloon.ShowHintBalloon(blnCreateContentProcess: TALHintBalloonCreateContentProcess;
blnLeft, blnTop: integer;
blnSourceControl: TControl;
blnDuration: integer;
blnArrowPosition: TALHintBalloonArrowPosition;
blnAnimationType: TALHintBalloonAnimationType;
blnAnimationSpeed: cardinal);
Const ArrowHeight: integer = 20;
ArrowWidth: Integer = 20;
Arrowdx: Integer = 20;
var FormRegion, ArrowRegion: HRGN;
Arrow: array [0..2] of TPoint;
hModule: cardinal;
AnimateWindowFN: function (hWnd: HWND; dwTime: cardinal; dwFlags: cardinal): longbool; stdcall;
SourceControlRect: Trect;
SourceControlRect_Ldiv2,SourceControlRect_Hdiv2 : Integer;
Area1,Area2,Area3,Area4: integer;
L1, L2, H1, H2 : Integer;
MaxArea: Integer;
i : Integer;
MainPanelMaxWidth, MainPanelMaxHeight: Integer;
begin
{---last focus form-----------------}
FLastActiveForm := screen.ActiveForm;
If FLastActiveForm <> nil then begin
FOldLastActiveFormWndProc := FLastActiveForm.WindowProc;
FLastActiveForm.WindowProc := LastActiveFormWndProcWndProc;
end;
{---Calcul du MaxPanelWidth et MaxPanelHeight----}
if assigned(blnSourceControl) then begin
If blnSourceControl is TWincontrol then GetWindowRect((blnSourceControl as TWinControl).Handle, SourceControlRect)
else begin
SourceControlRect.TopLeft := blnSourceControl.parent.ClientToScreen(blnSourceControl.BoundsRect.TopLeft);
SourceControlRect.BottomRight := blnSourceControl.Parent.ClientToScreen(blnSourceControl.BoundsRect.BottomRight);
end;
SourceControlRect_Hdiv2 := ((SourceControlRect.Bottom - SourceControlRect.Top) div 2);
SourceControlRect_Ldiv2 := ((SourceControlRect.Right - SourceControlRect.Left) div 2);
blnTop := SourceControlRect.Top + ((SourceControlRect.Bottom - SourceControlRect.Top) div 2);
blnLeft := SourceControlRect.Left + ((SourceControlRect.Right - SourceControlRect.Left) div 2);
end
else begin
SourceControlRect_Hdiv2 := 0;
SourceControlRect_Ldiv2 := 0;
end;
L1 := (blnLeft - SourceControlRect_Ldiv2 + Arrowdx - 10);
H1 := (blnTop - SourceControlRect_Hdiv2 - ArrowHeight - 10);
L2 := (screen.Width - blnLeft - SourceControlRect_Ldiv2 + Arrowdx - 10);
H2 := (screen.Height - blntop - SourceControlRect_Hdiv2 - ArrowHeight - 10);
Area1 := L1 * H1;
Area2 := L1 * H2;
Area3 := L2 * H1;
Area4 := L2 * H2;
MaxArea := Maxintvalue([Area1,Area2,Area3,Area4]);
If MaxArea = Area1 then begin
MainPanelMaxWidth := L1;
MainPanelMaxheight := H1;
end
else If MaxArea = Area2 then begin
MainPanelMaxWidth := L1;
MainPanelMaxheight := H2;
end
else if MaxArea = Area3 then begin
MainPanelMaxWidth := L2;
MainPanelMaxheight := H1;
end
else begin
MainPanelMaxWidth := L2;
MainPanelMaxheight := H2;
end;
{-----Creation du mainPanel-------------------------------------------------------------------------}
CustomProperty := CustomProperty + ';' + quotedStr('MainPanelMaxWidth='+inttostr(MainPanelMaxWidth));
CustomProperty := CustomProperty + ';' + quotedStr('MainPanelMaxHeight='+inttostr(MainPanelMaxHeight));
blnCreateContentProcess(self);
{-----Positonnement du hint----------------}
if not assigned(blnSourceControl) then begin
SourceControlRect.Top := blnTop;
SourceControlRect.Left := blnLeft;
SourceControlRect.Bottom := blnTop;
SourceControlRect.Right := blnLeft;
end;
I := 1;
Repeat
if blnArrowPosition = bapTopLeft then begin
blnTop := SourceControlRect.Top ;
blnLeft := SourceControlRect.Left;
if (MainPanel.Width > L1) or (MainPanel.Height > H1) then blnArrowPosition := bapTopRight
else break;
end;
if blnArrowPosition = bapTopRight then begin
blnTop := SourceControlRect.Top ;
blnLeft := SourceControlRect.right;
if (MainPanel.Width > L2) or (MainPanel.Height > H1) then blnArrowPosition := bapBottomLeft
else break;
end;
if blnArrowPosition = bapBottomLeft then begin
blnTop := SourceControlRect.Bottom ;
blnLeft := SourceControlRect.Left;
if (MainPanel.Width > L1) or (MainPanel.Height > H2) then blnArrowPosition := bapBottomRight
else break;
end;
if blnArrowPosition = bapBottomRight then begin
blnTop := SourceControlRect.Bottom ;
blnLeft := SourceControlRect.Right;
if (MainPanel.Width > L2) or (MainPanel.Height > H2) then blnArrowPosition := bapTopLeft
else break;
end;
inc(i);
until (i > 4);
If I > 4 then begin
If MaxArea = Area1 then begin
blnArrowPosition := bapTopLeft;
blnTop := SourceControlRect.Top ;
blnLeft := SourceControlRect.Left;
end
else If MaxArea = Area2 then begin
blnArrowPosition := bapBottomLeft;
blnTop := SourceControlRect.Bottom ;
blnLeft := SourceControlRect.Left;
end
else if MaxArea = Area3 then begin
blnArrowPosition := bapTopRight;
blnTop := SourceControlRect.Top ;
blnLeft := SourceControlRect.right;
end
else begin
blnArrowPosition := bapBottomRight;
blnTop := SourceControlRect.Bottom ;
blnLeft := SourceControlRect.Right;
end;
end;
{-----Creation des bordures--------------------------------------}
FMainPanel.Left := 0;
if blnArrowPosition in [bapBottomRight, bapBottomLeft] then begin
FMainPanel.Top := ArrowHeight + 2;
ClientHeight := FMainPanel.Top + FMainPanel.Height + 1;
end
else begin
FMainPanel.Top := 0;
ClientHeight := FMainPanel.Top + FMainPanel.Height + ArrowHeight - 1;
end;
ClientWidth := FMainPanel.Width + 1;
if ClientWidth < Arrowdx + ArrowWidth + 1 then clientWidth := Arrowdx + ArrowWidth + 1;
if Clientheight < ArrowHeight + 2 then Clientheight := ArrowHeight + 2;
if blnArrowPosition = bapTopLeft then begin
Left := blnLeft - (Width - Arrowdx);
Top := blnTop - (Height);
end
else if blnArrowPosition = bapTopRight then begin
Left := blnLeft - Arrowdx;
Top := blnTop - (Height);
end
else if blnArrowPosition = bapBottomRight then begin
Left := blnLeft - Arrowdx;
Top := blnTop - 2;
end
else if blnArrowPosition = bapBottomLeft then begin
Left := blnLeft - (Width - Arrowdx);
Top := blnTop - 2;
end;
if blnArrowPosition = bapTopLeft then begin
FormRegion := CreateRoundRectRgn(0, 0, Width, Height - (ArrowHeight - 2), 7, 7);
Arrow[0] := Point(Width - ArrowWidth - Arrowdx, Height - ArrowHeight);
Arrow[1] := Point(Width - Arrowdx, Height);
Arrow[2] := Point(Width - Arrowdx, Height - ArrowHeight);
end
else if blnArrowPosition = bapTopRight then begin
FormRegion := CreateRoundRectRgn(0, 0, Width, Height - (ArrowHeight - 2), 7, 7);
Arrow[0] := Point(Arrowdx, Height - ArrowHeight);
Arrow[1] := Point(Arrowdx, Height);
Arrow[2] := Point(Arrowdx + ArrowWidth, Height - ArrowHeight);
end
else if blnArrowPosition = bapBottomRight then begin
FormRegion := CreateRoundRectRgn(0, ArrowHeight + 2, Width, Height, 7, 7);
Arrow[0] := Point(Arrowdx, 2);
Arrow[1] := Point(Arrowdx, ArrowHeight + 2);
Arrow[2] := Point(Arrowdx + ArrowWidth, ArrowHeight + 2);
end
else begin
FormRegion := CreateRoundRectRgn(0, ArrowHeight + 2, Width, Height, 7, 7);
Arrow[0] := Point(Width - Arrowdx, 2);
Arrow[1] := Point(Width - Arrowdx, ArrowHeight + 2);
Arrow[2] := Point(Width - Arrowdx - ArrowWidth, ArrowHeight + 2);
end;
ArrowRegion := CreatePolygonRgn(Arrow, 3, WINDING);
CombineRgn(FormRegion, FormRegion, ArrowRegion, RGN_OR);
SetWindowRgn(Handle, FormRegion, True);
DeleteObject(ArrowRegion);
DeleteObject(FormRegion);
If BorderWidth > 0 then begin
FormRegion := CreateRoundRectRgn(BorderWidth, BorderWidth, MainPanel.Width - BorderWidth +1, MainPanel.Height - BorderWidth + 1, 7, 7);
SetWindowRgn(MainPanel.Handle, FormRegion, True);
DeleteObject(FormRegion);
end;
{---affichage---}
Visible := False;
if (blnAnimationType <> batNone) and (blnAnimationSpeed > 0) then begin
hModule := LoadLibrary('user32.dll');
if hModule <> 0 then begin
AnimateWindowFN := GetProcAddress(hModule, 'AnimateWindow');
if (@AnimateWindowFN <> NIL) then AnimateWindowFN(Handle, blnAnimationSpeed, TranslateAnimation(blnAnimationType));
FreeLibrary(hModule);
end;
end;
ShowWindow(Handle, SW_SHOW);
Visible := True;
SetFocus;
Invalidate;
{---Timer-------------}
if blnDuration > 0 then
With TTimer.Create(Self) do begin
OnTimer := OnExitTimer;
Interval := blnDuration;
Enabled := True;
end;
end;
{***************************************************************************}
procedure TALHintBalloon.LastActiveFormWndProcWndProc(var Message: TMessage);
begin
if Message.Msg = WM_NCACTIVATE then Message.Result := 1
else FOldLastActiveFormWndProc (Message);
end;
end.
|
(*----------------------------------------------------------*)
(* Übung 4 ; Beispiel 2 Ranking *)
(* Entwickler: Neuhold Michael *)
(* Datum: 24.10.2018 *)
(* Lösungsidee: Weiterentwicklung von Bsp. 4 der Übung 3 *)
(* Array hab ich das letzte Mal auch schon *)
(* verwendet. Diesmal hab ich noch einen *)
(* eigenen Datentyp hinzugefügt. Und zu einem *)
(* 2 Dimensionalen Array umgeschrieben *)
(*----------------------------------------------------------*)
PROGRAM Ranking;
(*
Typdefinitionen
*)
TYPE
Bereich = 0..100;
ArrUmfrage = ARRAY[0..40] OF Bereich; (* Umfrage Werte müssen sich zwischen 0 und 100 befinden. *)
D2Umfrage = ARRAY[1..2] OF ArrUmfrage; (* 2 Dimensional, pos & neg *)
(*
Runden der Eingabe Werte auf die naheliegenste 10er Stelle
und Divison durch 10 für die Darstellung mit dem Zeichen X
für 10%.
*)
FUNCTION RundeEingabe(zahl:INTEGER) : INTEGER;
VAR
rest : INTEGER;
BEGIN
IF zahl < 0 THEN
zahl := zahl * (-1);
rest := zahl MOD 10;
IF rest <= 4 THEN
RundeEingabe := (zahl-rest) DIV 10 // DIV 10
ELSE
RundeEingabe := (zahl+(10-rest)) DIV 10; //DIV 10
END; (* RundeEingabe *)
(*
FOR Schleife wurde wegen mehrfacher
Verwendung ausgelagert.
*)
PROCEDURE AusgabeZaehlen(n: INTEGER; ch: CHAR);
VAR
i : INTEGER;
BEGIN
FOR i := 1 TO n DO BEGIN
Write(ch);
END;
END; (* AusgabeZaehlen *)
(*
Auslagerung für die "grafische" Ausgabe, damit das
Hauptprogramm übersichtlich bleibt.
*)
PROCEDURE Ausgabe(nr: INTEGER; neg:INTEGER; pos:INTEGER);
VAR
blanks : INTEGER; (* blanks bezieht sich auf die '-' in der Ausgabe *)
BEGIN
blanks := 10 - neg;
write('| ',nr,'. ');
IF (neg + pos) <= 10 THEN
BEGIN
AusgabeZaehlen(blanks,'-');
AusgabeZaehlen(neg,'X');
Write('|');
AusgabeZaehlen(pos,'X');
blanks := 10 - pos;
AusgabeZaehlen(blanks,'-');
WriteLn('|');
END
ELSE
WriteLn('--------Error--------|');
END; (* Ausgabe *)
(*
Main
*)
VAR
umfrage: D2Umfrage; (* 2 Dimensional *)
i,n : INTEGER;
BEGIN
Write('Wieviele Umfragewerte wollen Sie einlesen? ');
ReadLn(n);
IF (n >= 2) AND (n <= 40) THEN BEGIN
FOR i := 1 TO n DO BEGIN
Write('Partei ',i,' Positiver Wert: ');
ReadLn(umfrage[1][i]);
umfrage[1][i] := RundeEingabe(umfrage[1][i]);
Write('Partei ',i,' Negativer Wert: ');
ReadLn(umfrage[2][i]);
umfrage[2][i] := RundeEingabe(umfrage[2][i]);
END;
WriteLn('___________________________');
WriteLn('| NR Negativ | Positiv |');
WriteLn('|______________|__________|');
FOR i := 1 TO n DO BEGIN
Ausgabe(i, umfrage[2][i], umfrage[1][i]);
END;
WriteLn('|_________________________|');
END
ELSE
WriteLn('ERROR - Die Anzahl der Umfragewerte muss zwischen 2 und 40 liegen!');
END. (* Ranking *) |
unit FormProgress;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, Vcl.ComCtrls, Vcl.AppEvnts;
type
TFrmProgress = class(TForm)
Label1: TLabel;
Label2: TLabel;
lblCounter: TLabel;
Label3: TLabel;
lbTableName: TLabel;
Label4: TLabel;
lblData: TLabel;
ProgressBar: TProgressBar;
btnCancel: TButton;
appevents: TApplicationEvents;
procedure btnCancelClick(Sender: TObject);
procedure appeventsActivate(Sender: TObject);
private
{ Private declarations }
FMaxCounter: Integer;
public
{ Public declarations }
procedure SetMaxCounter(const Value: Integer);
function IsCancelled: Boolean;
end;
var
FrmProgress: TFrmProgress;
implementation
{$R *.dfm}
procedure TFrmProgress.appeventsActivate(Sender: TObject);
begin
if Visible then Show;
end;
procedure TFrmProgress.btnCancelClick(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
function TFrmProgress.IsCancelled: Boolean;
begin
Result:=ModalResult = mrCancel;
end;
procedure TFrmProgress.SetMaxCounter(const Value: Integer);
begin
FMaxCounter:=Value;
end;
end.
|
unit SegmentArrayUnit;
//------------------------------------------------------------------------------
// Фасад для накопления данных сегментированных команд
//------------------------------------------------------------------------------
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils;
type
SegmentType=record
guid: string;
count: integer;
segments: TStringList;
end;
SegmentArrayType=array of SegmentType;
{ TSegmentArray }
TSegmentArray = class(TObject)
private
arr: SegmentArrayType;
function getSegmentInd(const guid: string): integer;
public
constructor Create;
destructor Destroy; override;
procedure addSegment(const guid, text: string; const count: integer);
function getGuidFullData(const guid: string; const del_after_get: boolean = true): string;
procedure delSegment(const ind: integer);
end;
var
segments_arr: TSegmentArray;
implementation
{ TSegmentArray }
function TSegmentArray.getSegmentInd(const guid: string): integer;
var i: integer;
begin
result := -1;
for i:=0 to Length(arr)-1 do
if AnsiCompareText(guid, arr[i].guid)=0 then
begin
result := i;
break;
end;
end;
constructor TSegmentArray.Create;
begin
inherited;
end;
destructor TSegmentArray.Destroy;
var i: integer;
begin
for i := 0 to Length(arr)-1 do
arr[i].segments.Free;
SetLength(arr, 0);
inherited Destroy;
end;
procedure TSegmentArray.addSegment(const guid, text: string; const count: integer);
var ind: integer;
begin
ind := getSegmentInd(guid);
if ind<0 then
begin
SetLength(arr, Length(arr)+1);
ind := Length(arr)-1;
arr[ind].segments := TStringList.create;
end;
arr[ind].segments.Add(text);
arr[ind].guid := guid;
arr[ind].count := count;
end;
function TSegmentArray.getGuidFullData(const guid: string;
const del_after_get: boolean): string;
var ind: integer;
begin
result := '';
ind := getSegmentInd(guid);
if ind >= 0 then
if arr[ind].count=arr[ind].segments.Count then
begin
result := StringReplace(arr[ind].segments.Text, #13#10, '', [rfReplaceAll]);
if del_after_get then
delSegment(ind);
end;
end;
procedure TSegmentArray.delSegment(const ind: integer);
var i: integer;
begin
if not ((ind >= 0) and (ind < Length(arr))) then
exit;
arr[ind].segments.Free;
if Length(arr) > 1 then
for i := ind to Length(arr)-1 do
arr[i] := arr[i+1];
SetLength(arr, Length(arr)-1);
end;
end.
|
unit UAuthenticatorIntf;
interface
uses InvokeRegistry
, Types
, XSBuiltIns
, USessionsManager
, UCommonTypes;
type
IAuthenticator = interface(IInvokable)
['{AC90F9A4-69F6-48E0-86E3-AD226F7EB099}']
function Login(const aUser, aPassword: String; out aSessionID: String): Boolean; stdcall;
function SetSessionData(const aSessionID, aData: String): Boolean; stdcall;
function GetSessionData(const aSessionID: String): String; stdcall;
function SessionExists(const aSessionID: String): Boolean; stdcall;
function Logout(const aSessionID: String): Boolean; stdcall;
function ChangePassword(const aSessionID, aOldPassword, aNewPassword: String): Byte; stdcall;
end;
implementation
initialization
InvRegistry.RegisterInterface(TypeInfo(IAuthenticator),'','','Interface que expõe métodos relacionados a autenticação de usuários');
end.
|
unit USigSetup;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,
UFrameAnimation, UGraphics, UForms;
type
TSigSetup = class(TAdvancedForm)
Animator: TAnimateFrame;
private
FHasSignature: Boolean;
function GetHasSignature: Boolean;
public
procedure SetUserSignature(WrkImage: TCFimage; X,Y: Integer; destRect: TRect);
procedure GetUserSignature(WrkImage: TCFimage; var X,Y: Integer; var destRect: TRect);
property HasSignature: Boolean read GetHasSignature write FHasSignature;
end;
var
SigSetup: TSigSetup;
implementation
uses
UGlobals, UStatus, UUtil1;
{$R *.dfm}
{ TSigSetup }
function TSigSetup.GetHasSignature: Boolean;
begin
result := Animator.Actor <> nil;
end;
procedure TSigSetup.SetUserSignature(WrkImage: TCFimage; X,Y: Integer; destRect: TRect);
begin
Animator.LoadImage(WrkImage, X,Y, destRect);
end;
procedure TSIgSetup.GetUserSignature(WrkImage: TCFimage; var X,Y: Integer; var destRect: TRect);
begin
if WrkImage <> nil then
WrkImage.Assign(Animator.Image);
X := Animator.Stage.Offset.x;
Y := Animator.Stage.Offset.y;
destRect := Animator.Stage.DestRect; //destrect is normalized when read
end;
end.
|
{ **************************************************************************** }
{ }
{ Unit testing Framework for SmartPascal and DWScript }
{ }
{ Copyright (c) Eric Grange, Creative IT. All rights reserved. }
{ Licensed to Optimale Systemer AS. }
{ }
{ **************************************************************************** }
unit TextTestRunner;
interface
uses TestFramework, System.Diagnostics;
type
TTextOutProc = procedure (s : String);
TTextTestRunner = class (ITestListener)
private
FIndent : Integer;
FIndentString : String;
public
procedure BeginTest(test : TAbstractTestCase);
procedure EndTest(test : TAbstractTestCase);
procedure Failed(test : TAbstractTestCase; msg : String);
property OnTextOut : TTextOutProc;
procedure TextOut(s : String; BGcolor: string = '#00ff00'; color: string = 'blue');
procedure Run;
end;
implementation
var Console external 'console': Variant;
(* ═══════════════════════════════════════════════════════
TTextTestRunner
═══════════════════════════════════════════════════════*)
procedure TTextTestRunner.TextOut(s: String; BGcolor: string; color: string);
begin
if Assigned(OnTextOut) then
OnTextOut(FIndentString+s)
else console.log('%c'+FIndentString+s, 'background: #222; color: '+BGcolor, color);
end;
procedure TTextTestRunner.BeginTest(test: TAbstractTestCase);
begin
if test is TTestSuite then begin
TextOut('BEGIN '+test.Name+' %c', 'cyan', 'background: #222;');
Inc(FIndent, 2);
FIndentString:=StringOfChar(' ', FIndent);
end;
test.BeginTime:=PerformanceTimer.Now;
end;
procedure TTextTestRunner.EndTest(test: TAbstractTestCase);
begin
test.EndTime:=PerformanceTimer.Now;
if test is TTestSuite then begin
Dec(FIndent, 2);
FIndentString:=StringOfChar(' ', FIndent);
TextOut( 'END '
+test.Name
+(if test.Failed then ' failed' else ' passed')
+"%c"+Format(' (%.1f ms)', [test.Elapsed]), 'cyan');
end else if test.Passed then begin
console.info('%c '+FIndentString+test.Name+' passed '+"%c"+Format(' (%.1f ms)', [test.Elapsed]), 'background: green;color: white;', '#00ff00');
end;
end;
procedure TTextTestRunner.Failed(test: TAbstractTestCase; msg: String);
begin
console.error('%c'+ FIndentString+test.Name+' failed'
+if msg<>'' then ': '+"%c "+msg, 'background: red; color:white', 'blue');
end;
procedure TTextTestRunner.Run;
begin
TTestFrameWork.Run(Self as ITestListener);
end;
end. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.